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 | pypa__warehouse | tests/unit/legacy/api/xmlrpc/test_cache.py | {
"start": 577,
"end": 945
} | class ____:
def test_null_cache(self):
purger = pretend.call_recorder(lambda tags: None)
service = NullXMLRPCCache("null://", purger)
assert service.fetch(
func_test, (1, 2), {"kwarg0": 3, "kwarg1": 4}, None, None, None
) == [[1, 2], {"kwarg0": 3, "kwarg1": 4}]
assert service.purge(None) is None
| TestXMLRPCCache |
python | huggingface__transformers | src/transformers/models/qwen2_vl/modeling_qwen2_vl.py | {
"start": 29572,
"end": 33423
} | class ____(Qwen2VLPreTrainedModel):
config: Qwen2VLVisionConfig
input_modalities = ("image", "video")
_no_split_modules = ["Qwen2VLVisionBlock"]
def __init__(self, config) -> None:
super().__init__(config)
self.spatial_merge_size = config.spatial_merge_size
self.patch_embed = PatchEmbed(
patch_size=config.patch_size,
temporal_patch_size=config.temporal_patch_size,
in_channels=config.in_channels,
embed_dim=config.embed_dim,
)
head_dim = config.embed_dim // config.num_heads
self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
self.blocks = nn.ModuleList([Qwen2VLVisionBlock(config) for _ in range(config.depth)])
self.merger = PatchMerger(
dim=config.hidden_size, context_dim=config.embed_dim, spatial_merge_size=config.spatial_merge_size
)
self.gradient_checkpointing = False
def get_dtype(self) -> torch.dtype:
return self.blocks[0].mlp.fc2.weight.dtype
def get_device(self) -> torch.device:
return self.blocks[0].mlp.fc2.weight.device
def rot_pos_emb(self, grid_thw):
pos_ids = []
for t, h, w in grid_thw:
hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
hpos_ids = hpos_ids.reshape(
h // self.spatial_merge_size,
self.spatial_merge_size,
w // self.spatial_merge_size,
self.spatial_merge_size,
)
hpos_ids = hpos_ids.permute(0, 2, 1, 3)
hpos_ids = hpos_ids.flatten()
wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
wpos_ids = wpos_ids.reshape(
h // self.spatial_merge_size,
self.spatial_merge_size,
w // self.spatial_merge_size,
self.spatial_merge_size,
)
wpos_ids = wpos_ids.permute(0, 2, 1, 3)
wpos_ids = wpos_ids.flatten()
pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
pos_ids = torch.cat(pos_ids, dim=0)
max_grid_size = grid_thw[:, 1:].max()
rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
return rotary_pos_emb
@auto_docstring
def forward(
self,
hidden_states: torch.Tensor,
grid_thw: torch.Tensor,
**kwargs,
) -> torch.Tensor:
r"""
grid_thw (`torch.LongTensor` of shape `(num_images, 3)`):
The temporal, height and width dimensions of feature shape for each image. Each row contains [t, h, w] values.
"""
hidden_states = self.patch_embed(hidden_states)
rotary_pos_emb = self.rot_pos_emb(grid_thw)
emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
position_embeddings = (emb.cos(), emb.sin())
cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
dim=0,
# Select dtype based on the following factors:
# - FA2 requires that cu_seqlens_q must have dtype int32
# - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
# See https://github.com/huggingface/transformers/pull/34852 for more information
dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
)
cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
for blk in self.blocks:
hidden_states = blk(
hidden_states,
cu_seqlens=cu_seqlens,
position_embeddings=position_embeddings,
**kwargs,
)
return self.merger(hidden_states)
@auto_docstring
| Qwen2VisionTransformerPretrainedModel |
python | sqlalchemy__sqlalchemy | test/sql/test_operators.py | {
"start": 148022,
"end": 152997
} | class ____(fixtures.TestBase):
def test_is_comparison_legacy(self):
c = column("x")
c2 = column("y")
op1 = c.op("$", is_comparison=True)(c2).operator
op2 = c.op("$", is_comparison=False)(c2).operator
assert operators.is_comparison(op1)
assert not operators.is_comparison(op2)
def test_is_comparison_bool_op(self):
c = column("x")
c2 = column("y")
op1 = c.bool_op("$")(c2).operator
op2 = c.op("$")(c2).operator
assert operators.is_comparison(op1)
assert not operators.is_comparison(op2)
@testing.combinations(
(sqltypes.NULLTYPE,),
(Integer(),),
(ARRAY(String),),
(String(50),),
(Boolean(),),
(DateTime(),),
(sqltypes.JSON(),),
(postgresql.ARRAY(Integer),),
(sqltypes.Numeric(5, 2),),
id_="r",
)
def test_return_types(self, typ):
some_return_type = sqltypes.DECIMAL()
c = column("x", typ)
expr = c.op("$", is_comparison=True)(None)
is_(expr.type, sqltypes.BOOLEANTYPE)
c = column("x", typ)
expr = c.bool_op("$")(None)
is_(expr.type, sqltypes.BOOLEANTYPE)
expr = c.op("$")(None)
is_(expr.type, typ)
expr = c.op("$", return_type=some_return_type)(None)
is_(expr.type, some_return_type)
expr = c.op("$", is_comparison=True, return_type=some_return_type)(
None
)
is_(expr.type, some_return_type)
def test_python_impl(self):
"""test #3162"""
c = column("x")
c2 = column("y")
op1 = c.op("$", python_impl=lambda a, b: a > b)(c2).operator
is_(op1(3, 5), False)
is_(op1(5, 3), True)
def test_python_impl_not_present(self):
"""test #3162"""
c = column("x")
c2 = column("y")
op1 = c.op("$")(c2).operator
with expect_raises_message(
exc.InvalidRequestError,
r"Custom operator '\$' can't be used with plain Python objects "
"unless it includes the 'python_impl' parameter.",
):
op1(3, 5)
def test_operator_class_default(self):
"""Test that custom_op defaults to OperatorClass.BASE"""
op = operators.custom_op("++")
eq_(op.operator_class, OperatorClass.BASE)
def test_operator_class_explicit(self):
"""Test that custom_op accepts an explicit operator_class parameter"""
op = operators.custom_op("++", operator_class=OperatorClass.MATH)
eq_(op.operator_class, OperatorClass.MATH)
def test_operator_class_combined(self):
"""Test that custom_op accepts combined operator classes"""
op = operators.custom_op(
"++", operator_class=OperatorClass.MATH | OperatorClass.BITWISE
)
eq_(op.operator_class, OperatorClass.MATH | OperatorClass.BITWISE)
def test_operator_class_with_column_op(self):
"""Test that operator_class is passed through when using column.op()"""
c = column("x", Integer)
expr1 = c.op("++")("value")
eq_(expr1.operator.operator_class, OperatorClass.BASE)
expr2 = c.op("++", operator_class=OperatorClass.MATH)("value")
eq_(expr2.operator.operator_class, OperatorClass.MATH)
with expect_deprecated(
r"Type object .*Integer.* does not include custom "
r"operator '\+\+' in its operator classes."
):
expr3 = c.op("++", operator_class=OperatorClass.STRING_MATCH)(
"value"
)
eq_(expr3.operator.operator_class, OperatorClass.STRING_MATCH)
def test_operator_class_hash_and_equality(self):
op1 = operators.custom_op("++", operator_class=OperatorClass.MATH)
op2 = operators.custom_op("++", operator_class=OperatorClass.MATH)
op3 = operators.custom_op("++", operator_class=OperatorClass.BITWISE)
# Same opstring and same operator_class should be equal
eq_(op1, op2)
eq_(hash(op1), hash(op2))
# Same opstring but different operator_class should be different
ne_(op1, op3)
ne_(hash(op1), hash(op3))
def test_operator_class_warning_unspecified_type(self):
"""Test warning when type has UNSPECIFIED operator_classes"""
# Create a custom type with UNSPECIFIED operator_classes
class UnspecifiedType(TypeEngine):
operator_classes = OperatorClass.UNSPECIFIED
metadata = MetaData()
test_table = Table(
"test", metadata, Column("value", UnspecifiedType())
)
col = test_table.c.value
# Use a builtin operator that should not be compatible
# This should trigger the first deprecation warning
with expect_deprecated(
"Type object .* does not refer to an OperatorClass in "
"its operator_classes attribute"
):
col == "test"
| CustomOpTest |
python | google__pytype | pytype/tests/test_slice1.py | {
"start": 62,
"end": 953
} | class ____(test_base.BaseTest):
"""Tests for the SLICE_<n> opcodes, as well as for __getitem__(slice)."""
def test_getslice(self):
ty = self.Infer("""
x = [1,2,3]
a = x[:]
b = x[1:]
c = x[1:2]
d = x[1:2:3]
e = x[:2:3]
f = x[1::3]
g = x[1:2:]
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import List
x = ... # type: List[int]
a = ... # type: List[int]
b = ... # type: List[int]
c = ... # type: List[int]
d = ... # type: List[int]
e = ... # type: List[int]
f = ... # type: List[int]
g = ... # type: List[int]
""",
)
def test_slice_getitem(self):
self.Check("""
class Foo:
def __getitem__(self, s):
return s
assert_type(Foo()[:], slice)
""")
if __name__ == "__main__":
test_base.main()
| SliceTest |
python | pytorch__pytorch | torch/cuda/_sanitizer.py | {
"start": 5273,
"end": 7408
} | class ____:
def __init__(self) -> None:
self.accesses: dict[DataPtr, TensorInfo] = {}
def ensure_tensor_exists(self, data_ptr: DataPtr) -> None:
if data_ptr not in self.accesses:
logger.info(
"Found tensor with pointer: %s, but no matching tensor "
"allocation in the trace. Backfilling the trace now. "
"Perhaps the sanitizer was enabled after some torch operations?",
data_ptr,
)
self.create_tensor(data_ptr, None)
def ensure_tensor_does_not_exist(self, data_ptr: DataPtr) -> None:
if data_ptr in self.accesses:
logger.info(
"Found duplicate tensor allocation in the trace for tensor with "
"pointer: %s. Assuming the trace for tensor deallocation "
"wasn't caught and backfilling it now. "
"Perhaps the sanitizer was enabled after some torch operations?",
data_ptr,
)
self.delete_tensor(data_ptr)
def create_tensor(
self, data_ptr: DataPtr, stack_trace: Optional[traceback.StackSummary]
) -> None:
self.accesses[data_ptr] = TensorInfo(stack_trace)
def delete_tensor(self, data_ptr: DataPtr) -> None:
del self.accesses[data_ptr]
def were_there_reads_since_last_write(self, data_ptr: DataPtr) -> bool:
return bool(self.accesses[data_ptr].reads)
def get_allocation_stack_trace(
self, data_ptr: DataPtr
) -> Optional[traceback.StackSummary]:
return self.accesses[data_ptr].allocation_stack_trace
def get_write(self, data_ptr: DataPtr) -> Optional[Access]:
return self.accesses[data_ptr].write
def get_reads(self, data_ptr: DataPtr) -> list[Access]:
return self.accesses[data_ptr].reads
def add_read(self, data_ptr: DataPtr, access: Access) -> None:
self.accesses[data_ptr].reads.append(access)
def set_write(self, data_ptr: DataPtr, access: Access) -> None:
self.accesses[data_ptr].write = access
self.accesses[data_ptr].reads = []
| _TensorsAccessed |
python | astropy__astropy | astropy/io/votable/tree.py | {
"start": 11625,
"end": 12379
} | class ____:
_ucd_in_v1_2 = False
@property
def ucd(self):
"""The `unified content descriptor`_ for the element."""
return self._ucd
@ucd.setter
def ucd(self, ucd):
if ucd is not None and ucd.strip() == "":
ucd = None
if ucd is not None:
if self._ucd_in_v1_2 and not self._config.get("version_1_2_or_later"):
warn_or_raise(
W28,
W28,
("ucd", self._element_name, "1.2"),
self._config,
self._pos,
)
check_ucd(ucd, self._config, self._pos)
self._ucd = ucd
@ucd.deleter
def ucd(self):
self._ucd = None
| _UcdProperty |
python | pytorch__pytorch | torch/testing/_internal/opinfo/core.py | {
"start": 66203,
"end": 66730
} | class ____(SampleRule):
# expected error type
error_type: TypeVar = Exception
# expected error message
error_msg: str = ".*"
@property
def type(self) -> str:
return "xfail"
def get_context(self, test_case):
return test_case.assertRaisesRegex(
# failing within torch.compile wraps within a BackendCompilerFailed
(self.error_type, torch._dynamo.exc.BackendCompilerFailed),
self.error_msg,
)
# useful for specifying skips
@dataclass
| XFailRule |
python | pandas-dev__pandas | pandas/tests/series/methods/test_replace.py | {
"start": 184,
"end": 27661
} | class ____:
def test_replace_explicit_none(self):
# GH#36984 if the user explicitly passes value=None, give it to them
ser = pd.Series([0, 0, ""], dtype=object)
result = ser.replace("", None)
expected = pd.Series([0, 0, None], dtype=object)
tm.assert_series_equal(result, expected)
# Cast column 2 to object to avoid implicit cast when setting entry to ""
df = pd.DataFrame(np.zeros((3, 3))).astype({2: object})
df.iloc[2, 2] = ""
result = df.replace("", None)
expected = pd.DataFrame(
{
0: np.zeros(3),
1: np.zeros(3),
2: np.array([0.0, 0.0, None], dtype=object),
}
)
assert expected.iloc[2, 2] is None
tm.assert_frame_equal(result, expected)
# GH#19998 same thing with object dtype
ser = pd.Series([10, 20, 30, "a", "a", "b", "a"])
result = ser.replace("a", None)
expected = pd.Series([10, 20, 30, None, None, "b", None])
assert expected.iloc[-1] is None
tm.assert_series_equal(result, expected)
def test_replace_noop_doesnt_downcast(self):
# GH#44498
ser = pd.Series([None, None, pd.Timestamp("2021-12-16 17:31")], dtype=object)
res = ser.replace({np.nan: None}) # should be a no-op
tm.assert_series_equal(res, ser)
assert res.dtype == object
# same thing but different calling convention
res = ser.replace(np.nan, None)
tm.assert_series_equal(res, ser)
assert res.dtype == object
def test_replace(self):
N = 50
ser = pd.Series(np.random.default_rng(2).standard_normal(N))
ser[0:4] = np.nan
ser[6:10] = 0
# replace list with a single value
result = ser.replace([np.nan], -1, inplace=True)
assert result is ser
exp = ser.fillna(-1)
tm.assert_series_equal(ser, exp)
rs = ser.replace(0.0, np.nan)
ser[ser == 0.0] = np.nan
tm.assert_series_equal(rs, ser)
ser = pd.Series(
np.fabs(np.random.default_rng(2).standard_normal(N)),
pd.date_range("2020-01-01", periods=N),
dtype=object,
)
ser[:5] = np.nan
ser[6:10] = "foo"
ser[20:30] = "bar"
# replace list with a single value
rs = ser.replace([np.nan, "foo", "bar"], -1)
assert (rs[:5] == -1).all()
assert (rs[6:10] == -1).all()
assert (rs[20:30] == -1).all()
assert (pd.isna(ser[:5])).all()
# replace with different values
rs = ser.replace({np.nan: -1, "foo": -2, "bar": -3})
assert (rs[:5] == -1).all()
assert (rs[6:10] == -2).all()
assert (rs[20:30] == -3).all()
assert (pd.isna(ser[:5])).all()
# replace with different values with 2 lists
rs2 = ser.replace([np.nan, "foo", "bar"], [-1, -2, -3])
tm.assert_series_equal(rs, rs2)
# replace inplace
result = ser.replace([np.nan, "foo", "bar"], -1, inplace=True)
assert result is ser
assert (ser[:5] == -1).all()
assert (ser[6:10] == -1).all()
assert (ser[20:30] == -1).all()
def test_replace_nan_with_inf(self):
ser = pd.Series([np.nan, 0, np.inf])
tm.assert_series_equal(ser.replace(np.nan, 0), ser.fillna(0))
ser = pd.Series([np.nan, 0, "foo", "bar", np.inf, None, pd.NaT])
tm.assert_series_equal(ser.replace(np.nan, 0), ser.fillna(0))
filled = ser.copy()
filled[4] = 0
tm.assert_series_equal(ser.replace(np.inf, 0), filled)
def test_replace_listlike_value_listlike_target(self, datetime_series):
ser = pd.Series(datetime_series.index)
tm.assert_series_equal(ser.replace(np.nan, 0), ser.fillna(0))
# malformed
msg = r"Replacement lists must match in length\. Expecting 3 got 2"
with pytest.raises(ValueError, match=msg):
ser.replace([1, 2, 3], [np.nan, 0])
# ser is dt64 so can't hold 1 or 2, so this replace is a no-op
result = ser.replace([1, 2], [np.nan, 0])
tm.assert_series_equal(result, ser)
ser = pd.Series([0, 1, 2, 3, 4])
result = ser.replace([0, 1, 2, 3, 4], [4, 3, 2, 1, 0])
tm.assert_series_equal(result, pd.Series([4, 3, 2, 1, 0]))
def test_replace_gh5319(self):
# API change from 0.12?
# GH 5319
ser = pd.Series([0, np.nan, 2, 3, 4])
msg = (
"Series.replace must specify either 'value', "
"a dict-like 'to_replace', or dict-like 'regex'"
)
with pytest.raises(ValueError, match=msg):
ser.replace([np.nan])
with pytest.raises(ValueError, match=msg):
ser.replace(np.nan)
def test_replace_datetime64(self):
# GH 5797
ser = pd.Series(pd.date_range("20130101", periods=5))
expected = ser.copy()
expected.loc[2] = pd.Timestamp("20120101")
result = ser.replace({pd.Timestamp("20130103"): pd.Timestamp("20120101")})
tm.assert_series_equal(result, expected)
result = ser.replace(pd.Timestamp("20130103"), pd.Timestamp("20120101"))
tm.assert_series_equal(result, expected)
def test_replace_nat_with_tz(self):
# GH 11792: Test with replacing NaT in a list with tz data
ts = pd.Timestamp("2015/01/01", tz="UTC")
s = pd.Series([pd.NaT, pd.Timestamp("2015/01/01", tz="UTC")])
result = s.replace([np.nan, pd.NaT], pd.Timestamp.min)
expected = pd.Series([pd.Timestamp.min, ts], dtype=object)
tm.assert_series_equal(expected, result)
def test_replace_timedelta_td64(self):
tdi = pd.timedelta_range(0, periods=5)
ser = pd.Series(tdi)
# Using a single dict argument means we go through replace_list
result = ser.replace({ser[1]: ser[3]})
expected = pd.Series([ser[0], ser[3], ser[2], ser[3], ser[4]])
tm.assert_series_equal(result, expected)
def test_replace_with_single_list(self):
ser = pd.Series([0, 1, 2, 3, 4])
msg = (
"Series.replace must specify either 'value', "
"a dict-like 'to_replace', or dict-like 'regex'"
)
with pytest.raises(ValueError, match=msg):
ser.replace([1, 2, 3])
s = ser.copy()
with pytest.raises(ValueError, match=msg):
s.replace([1, 2, 3], inplace=True)
def test_replace_mixed_types(self):
ser = pd.Series(np.arange(5), dtype="int64")
def check_replace(to_rep, val, expected):
sc = ser.copy()
result = ser.replace(to_rep, val)
result = sc.replace(to_rep, val, inplace=True)
assert result is sc
tm.assert_series_equal(expected, result)
tm.assert_series_equal(expected, sc)
# 3.0 can still be held in our int64 series, so we do not upcast GH#44940
tr, v = [3], [3.0]
check_replace(tr, v, ser)
# Note this matches what we get with the scalars 3 and 3.0
check_replace(tr[0], v[0], ser)
# MUST upcast to float
e = pd.Series([0, 1, 2, 3.5, 4])
tr, v = [3], [3.5]
check_replace(tr, v, e)
# casts to object
e = pd.Series([0, 1, 2, 3.5, "a"])
tr, v = [3, 4], [3.5, "a"]
check_replace(tr, v, e)
# again casts to object
e = pd.Series([0, 1, 2, 3.5, pd.Timestamp("20130101")])
tr, v = [3, 4], [3.5, pd.Timestamp("20130101")]
check_replace(tr, v, e)
# casts to object
e = pd.Series([0, 1, 2, 3.5, True], dtype="object")
tr, v = [3, 4], [3.5, True]
check_replace(tr, v, e)
# test an object with dates + floats + integers + strings
dr = pd.Series(pd.date_range("1/1/2001", "1/10/2001", freq="D"))
result = dr.astype(object).replace([dr[0], dr[1], dr[2]], [1.0, 2, "a"])
expected = pd.Series([1.0, 2, "a"] + dr[3:].tolist(), dtype=object)
tm.assert_series_equal(result, expected)
def test_replace_bool_with_string_no_op(self):
s = pd.Series([True, False, True])
result = s.replace("fun", "in-the-sun")
tm.assert_series_equal(s, result)
def test_replace_bool_with_string(self):
# nonexistent elements
s = pd.Series([True, False, True])
result = s.replace(True, "2u")
expected = pd.Series(["2u", False, "2u"])
tm.assert_series_equal(expected, result)
def test_replace_bool_with_bool(self):
s = pd.Series([True, False, True])
result = s.replace(True, False)
expected = pd.Series([False] * len(s))
tm.assert_series_equal(expected, result)
def test_replace_with_dict_with_bool_keys(self):
s = pd.Series([True, False, True])
result = s.replace({"asdf": "asdb", True: "yes"})
expected = pd.Series(["yes", False, "yes"])
tm.assert_series_equal(result, expected)
def test_replace_Int_with_na(self, any_int_ea_dtype):
# GH 38267
result = pd.Series([0, None], dtype=any_int_ea_dtype).replace(0, pd.NA)
expected = pd.Series([pd.NA, pd.NA], dtype=any_int_ea_dtype)
tm.assert_series_equal(result, expected)
result = pd.Series([0, 1], dtype=any_int_ea_dtype).replace(0, pd.NA)
result2 = result.replace(1, pd.NA, inplace=True)
assert result2 is result
tm.assert_series_equal(result, expected)
def test_replace2(self):
N = 50
ser = pd.Series(
np.fabs(np.random.default_rng(2).standard_normal(N)),
pd.date_range("2020-01-01", periods=N),
dtype=object,
)
ser[:5] = np.nan
ser[6:10] = "foo"
ser[20:30] = "bar"
# replace list with a single value
rs = ser.replace([np.nan, "foo", "bar"], -1)
assert (rs[:5] == -1).all()
assert (rs[6:10] == -1).all()
assert (rs[20:30] == -1).all()
assert (pd.isna(ser[:5])).all()
# replace with different values
rs = ser.replace({np.nan: -1, "foo": -2, "bar": -3})
assert (rs[:5] == -1).all()
assert (rs[6:10] == -2).all()
assert (rs[20:30] == -3).all()
assert (pd.isna(ser[:5])).all()
# replace with different values with 2 lists
rs2 = ser.replace([np.nan, "foo", "bar"], [-1, -2, -3])
tm.assert_series_equal(rs, rs2)
# replace inplace
result = ser.replace([np.nan, "foo", "bar"], -1, inplace=True)
assert result is ser
assert (ser[:5] == -1).all()
assert (ser[6:10] == -1).all()
assert (ser[20:30] == -1).all()
@pytest.mark.parametrize("inplace", [True, False])
def test_replace_cascade(self, inplace):
# Test that replaced values are not replaced again
# GH #50778
ser = pd.Series([1, 2, 3])
expected = pd.Series([2, 3, 4])
res = ser.replace([1, 2, 3], [2, 3, 4], inplace=inplace)
if inplace:
tm.assert_series_equal(ser, expected)
else:
tm.assert_series_equal(res, expected)
def test_replace_with_dictlike_and_string_dtype(self, nullable_string_dtype):
# GH 32621, GH#44940
ser = pd.Series(["one", "two", np.nan], dtype=nullable_string_dtype)
expected = pd.Series(["1", "2", np.nan], dtype=nullable_string_dtype)
result = ser.replace({"one": "1", "two": "2"})
tm.assert_series_equal(expected, result)
def test_replace_with_empty_dictlike(self):
# GH 15289
s = pd.Series(list("abcd"))
tm.assert_series_equal(s, s.replace({}))
empty_series = pd.Series([])
tm.assert_series_equal(s, s.replace(empty_series))
def test_replace_string_with_number(self):
# GH 15743
s = pd.Series([1, 2, 3])
result = s.replace("2", np.nan)
expected = pd.Series([1, 2, 3])
tm.assert_series_equal(expected, result)
def test_replace_replacer_equals_replacement(self):
# GH 20656
# make sure all replacers are matching against original values
s = pd.Series(["a", "b"])
expected = pd.Series(["b", "a"])
result = s.replace({"a": "b", "b": "a"})
tm.assert_series_equal(expected, result)
def test_replace_unicode_with_number(self):
# GH 15743
s = pd.Series([1, 2, 3])
result = s.replace("2", np.nan)
expected = pd.Series([1, 2, 3])
tm.assert_series_equal(expected, result)
def test_replace_mixed_types_with_string(self):
# Testing mixed
s = pd.Series([1, 2, 3, "4", 4, 5])
result = s.replace([2, "4"], np.nan)
expected = pd.Series([1, np.nan, 3, np.nan, 4, 5], dtype=object)
tm.assert_series_equal(expected, result)
@pytest.mark.parametrize(
"categorical, numeric",
[
(["A"], [1]),
(["A", "B"], [1, 2]),
],
)
def test_replace_categorical(self, categorical, numeric):
# GH 24971, GH#23305
ser = pd.Series(pd.Categorical(categorical, categories=["A", "B"]))
result = ser.cat.rename_categories({"A": 1, "B": 2})
expected = pd.Series(numeric).astype("category")
if 2 not in expected.cat.categories:
# i.e. categories should be [1, 2] even if there are no "B"s present
# GH#44940
expected = expected.cat.add_categories(2)
tm.assert_series_equal(expected, result, check_categorical=False)
def test_replace_categorical_inplace(self):
# GH 53358
data = ["a", "b", "c"]
data_exp = ["b", "b", "c"]
ser = pd.Series(data, dtype="category")
result = ser.replace(to_replace="a", value="b", inplace=True)
assert result is ser
expected = pd.Series(pd.Categorical(data_exp, categories=data))
tm.assert_series_equal(ser, expected)
def test_replace_categorical_single(self):
# GH 26988
dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")
s = pd.Series(dti)
c = s.astype("category")
expected = c.copy()
expected = expected.cat.add_categories("foo")
expected[2] = "foo"
expected = expected.cat.remove_unused_categories()
assert c[2] != "foo"
result = c.cat.rename_categories({c.values[2]: "foo"})
tm.assert_series_equal(expected, result)
assert c[2] != "foo" # ensure non-inplace call does not alter original
def test_replace_with_no_overflowerror(self):
# GH 25616
# casts to object without Exception from OverflowError
s = pd.Series([0, 1, 2, 3, 4])
result = s.replace([3], ["100000000000000000000"])
expected = pd.Series([0, 1, 2, "100000000000000000000", 4])
tm.assert_series_equal(result, expected)
s = pd.Series([0, "100000000000000000000", "100000000000000000001"])
result = s.replace(["100000000000000000000"], [1])
expected = pd.Series([0, 1, "100000000000000000001"])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"ser, to_replace, exp",
[
([1, 2, 3], {1: 2, 2: 3, 3: 4}, [2, 3, 4]),
(["1", "2", "3"], {"1": "2", "2": "3", "3": "4"}, ["2", "3", "4"]),
],
)
def test_replace_commutative(self, ser, to_replace, exp):
# GH 16051
# DataFrame.replace() overwrites when values are non-numeric
series = pd.Series(ser)
expected = pd.Series(exp)
result = series.replace(to_replace)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"ser, exp", [([1, 2, 3], [1, True, 3]), (["x", 2, 3], ["x", True, 3])]
)
def test_replace_no_cast(self, ser, exp):
# GH 9113
# BUG: replace int64 dtype with bool coerces to int64
series = pd.Series(ser)
result = series.replace(2, True)
expected = pd.Series(exp)
tm.assert_series_equal(result, expected)
def test_replace_invalid_to_replace(self):
# GH 18634
# API: replace() should raise an exception if invalid argument is given
series = pd.Series(["a", "b", "c "])
msg = (
r"Expecting 'to_replace' to be either a scalar, array-like, "
r"dict or None, got invalid type.*"
)
with pytest.raises(TypeError, match=msg):
series.replace(lambda x: x.strip())
@pytest.mark.parametrize("frame", [False, True])
def test_replace_nonbool_regex(self, frame):
obj = pd.Series(["a", "b", "c "])
if frame:
obj = obj.to_frame()
msg = "'to_replace' must be 'None' if 'regex' is not a bool"
with pytest.raises(ValueError, match=msg):
obj.replace(to_replace=["a"], regex="foo")
@pytest.mark.parametrize("frame", [False, True])
def test_replace_empty_copy(self, frame):
obj = pd.Series([], dtype=np.float64)
if frame:
obj = obj.to_frame()
res = obj.replace(4, 5, inplace=True)
assert res is obj
res = obj.replace(4, 5, inplace=False)
tm.assert_equal(res, obj)
assert res is not obj
def test_replace_only_one_dictlike_arg(self, fixed_now_ts):
# GH#33340
ser = pd.Series([1, 2, "A", fixed_now_ts, True])
to_replace = {0: 1, 2: "A"}
value = "foo"
msg = (
"Series.replace cannot specify both a dict-like 'to_replace' and a 'value'"
)
with pytest.raises(ValueError, match=msg):
ser.replace(to_replace, value)
to_replace = 1
value = {0: "foo", 2: "bar"}
msg = "Series.replace cannot use dict-value and non-None to_replace"
with pytest.raises(ValueError, match=msg):
ser.replace(to_replace, value)
def test_replace_dict_like_with_dict_like(self):
# GH 59452
s = pd.Series([1, 2, 3, 4, 5])
to_replace = pd.Series([1])
value = pd.Series([75])
msg = "to_replace and value cannot be dict-like for Series.replace"
with pytest.raises(ValueError, match=msg):
s.replace(to_replace, value)
def test_replace_extension_other(self, frame_or_series):
# https://github.com/pandas-dev/pandas/issues/34530
obj = frame_or_series(pd.array([1, 2, 3], dtype="Int64"))
result = obj.replace("", "") # no exception
# should not have changed dtype
tm.assert_equal(obj, result)
def test_replace_with_compiled_regex(self):
# https://github.com/pandas-dev/pandas/issues/35680
s = pd.Series(["a", "b", "c"])
regex = re.compile("^a$")
result = s.replace({regex: "z"}, regex=True)
expected = pd.Series(["z", "b", "c"])
tm.assert_series_equal(result, expected)
def test_pandas_replace_na(self):
# GH#43344
# GH#56599
ser = pd.Series(["AA", "BB", "CC", "DD", "EE", "", pd.NA, "AA"], dtype="string")
regex_mapping = {
"AA": "CC",
"BB": "CC",
"EE": "CC",
"CC": "CC-REPL",
}
result = ser.replace(regex_mapping, regex=True)
exp = pd.Series(
["CC", "CC", "CC-REPL", "DD", "CC", "", pd.NA, "CC"], dtype="string"
)
tm.assert_series_equal(result, exp)
@pytest.mark.parametrize(
"dtype, input_data, to_replace, expected_data",
[
("bool", [True, False], {True: False}, [False, False]),
("int64", [1, 2], {1: 10, 2: 20}, [10, 20]),
("Int64", [1, 2], {1: 10, 2: 20}, [10, 20]),
("float64", [1.1, 2.2], {1.1: 10.1, 2.2: 20.5}, [10.1, 20.5]),
("Float64", [1.1, 2.2], {1.1: 10.1, 2.2: 20.5}, [10.1, 20.5]),
("string", ["one", "two"], {"one": "1", "two": "2"}, ["1", "2"]),
(
pd.IntervalDtype("int64"),
IntervalArray([pd.Interval(1, 2), pd.Interval(2, 3)]),
{pd.Interval(1, 2): pd.Interval(10, 20)},
IntervalArray([pd.Interval(10, 20), pd.Interval(2, 3)]),
),
(
pd.IntervalDtype("float64"),
IntervalArray([pd.Interval(1.0, 2.7), pd.Interval(2.8, 3.1)]),
{pd.Interval(1.0, 2.7): pd.Interval(10.6, 20.8)},
IntervalArray([pd.Interval(10.6, 20.8), pd.Interval(2.8, 3.1)]),
),
(
pd.PeriodDtype("M"),
[pd.Period("2020-05", freq="M")],
{pd.Period("2020-05", freq="M"): pd.Period("2020-06", freq="M")},
[pd.Period("2020-06", freq="M")],
),
],
)
def test_replace_dtype(self, dtype, input_data, to_replace, expected_data):
# GH#33484
ser = pd.Series(input_data, dtype=dtype)
result = ser.replace(to_replace)
expected = pd.Series(expected_data, dtype=dtype)
tm.assert_series_equal(result, expected)
def test_replace_string_dtype(self):
# GH#40732, GH#44940
ser = pd.Series(["one", "two", np.nan], dtype="string")
res = ser.replace({"one": "1", "two": "2"})
expected = pd.Series(["1", "2", np.nan], dtype="string")
tm.assert_series_equal(res, expected)
# GH#31644
ser2 = pd.Series(["A", np.nan], dtype="string")
res2 = ser2.replace("A", "B")
expected2 = pd.Series(["B", np.nan], dtype="string")
tm.assert_series_equal(res2, expected2)
ser3 = pd.Series(["A", "B"], dtype="string")
res3 = ser3.replace("A", pd.NA)
expected3 = pd.Series([pd.NA, "B"], dtype="string")
tm.assert_series_equal(res3, expected3)
def test_replace_string_dtype_list_to_replace(self):
# GH#41215, GH#44940
ser = pd.Series(["abc", "def"], dtype="string")
res = ser.replace(["abc", "any other string"], "xyz")
expected = pd.Series(["xyz", "def"], dtype="string")
tm.assert_series_equal(res, expected)
def test_replace_string_dtype_regex(self):
# GH#31644
ser = pd.Series(["A", "B"], dtype="string")
res = ser.replace(r".", "C", regex=True)
expected = pd.Series(["C", "C"], dtype="string")
tm.assert_series_equal(res, expected)
def test_replace_nullable_numeric(self):
# GH#40732, GH#44940
floats = pd.Series([1.0, 2.0, 3.999, 4.4], dtype=pd.Float64Dtype())
assert floats.replace({1.0: 9}).dtype == floats.dtype
assert floats.replace(1.0, 9).dtype == floats.dtype
assert floats.replace({1.0: 9.0}).dtype == floats.dtype
assert floats.replace(1.0, 9.0).dtype == floats.dtype
res = floats.replace(to_replace=[1.0, 2.0], value=[9.0, 10.0])
assert res.dtype == floats.dtype
ints = pd.Series([1, 2, 3, 4], dtype=pd.Int64Dtype())
assert ints.replace({1: 9}).dtype == ints.dtype
assert ints.replace(1, 9).dtype == ints.dtype
assert ints.replace({1: 9.0}).dtype == ints.dtype
assert ints.replace(1, 9.0).dtype == ints.dtype
# nullable (for now) raises instead of casting
with pytest.raises(TypeError, match="Invalid value"):
ints.replace({1: 9.5})
with pytest.raises(TypeError, match="Invalid value"):
ints.replace(1, 9.5)
@pytest.mark.parametrize("regex", [False, True])
def test_replace_regex_dtype_series(self, regex):
# GH-48644
series = pd.Series(["0"], dtype=object)
expected = pd.Series([1], dtype=object)
result = series.replace(to_replace="0", value=1, regex=regex)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("regex", [False, True])
def test_replace_regex_dtype_series_string(self, regex):
series = pd.Series(["0"], dtype="str")
expected = pd.Series([1], dtype=object)
result = series.replace(to_replace="0", value=1, regex=regex)
tm.assert_series_equal(result, expected)
def test_replace_different_int_types(self, any_int_numpy_dtype):
# GH#45311
labs = pd.Series([1, 1, 1, 0, 0, 2, 2, 2], dtype=any_int_numpy_dtype)
maps = pd.Series([0, 2, 1], dtype=any_int_numpy_dtype)
map_dict = dict(zip(maps.values, maps.index, strict=True))
result = labs.replace(map_dict)
expected = labs.replace({0: 0, 2: 1, 1: 2})
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("val", [2, np.nan, 2.0])
def test_replace_value_none_dtype_numeric(self, val):
# GH#48231
ser = pd.Series([1, val])
result = ser.replace(val, None)
expected = pd.Series([1, None], dtype=object)
tm.assert_series_equal(result, expected)
def test_replace_change_dtype_series(self):
# GH#25797
df = pd.DataFrame({"Test": ["0.5", True, "0.6"]}, dtype=object)
df["Test"] = df["Test"].replace([True], [np.nan])
expected = pd.DataFrame({"Test": ["0.5", np.nan, "0.6"]}, dtype=object)
tm.assert_frame_equal(df, expected)
df = pd.DataFrame({"Test": ["0.5", None, "0.6"]}, dtype=object)
df["Test"] = df["Test"].replace([None], [np.nan])
tm.assert_frame_equal(df, expected)
df = pd.DataFrame({"Test": ["0.5", None, "0.6"]}, dtype=object)
df["Test"] = df["Test"].fillna(np.nan)
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("dtype", ["object", "Int64"])
def test_replace_na_in_obj_column(self, dtype):
# GH#47480
ser = pd.Series([0, 1, pd.NA], dtype=dtype)
expected = pd.Series([0, 2, pd.NA], dtype=dtype)
result = ser.replace(to_replace=1, value=2)
tm.assert_series_equal(result, expected)
result = ser.replace(to_replace=1, value=2, inplace=True)
assert result is ser
tm.assert_series_equal(ser, expected)
@pytest.mark.parametrize("val", [0, 0.5])
def test_replace_numeric_column_with_na(self, val):
# GH#50758
ser = pd.Series([val, 1])
expected = pd.Series([val, pd.NA])
result = ser.replace(to_replace=1, value=pd.NA)
tm.assert_series_equal(result, expected)
result = ser.replace(to_replace=1, value=pd.NA, inplace=True)
assert result is ser
tm.assert_series_equal(ser, expected)
def test_replace_ea_float_with_bool(self):
# GH#55398
ser = pd.Series([0.0], dtype="Float64")
expected = ser.copy()
result = ser.replace(False, 1.0)
tm.assert_series_equal(result, expected)
ser = pd.Series([False], dtype="boolean")
expected = ser.copy()
result = ser.replace(0.0, True)
tm.assert_series_equal(result, expected)
def test_replace_all_NA(self):
# GH#60688
df = pd.Series([pd.NA, pd.NA])
result = df.replace({r"^#": "$"}, regex=True)
expected = pd.Series([pd.NA, pd.NA])
tm.assert_series_equal(result, expected)
@td.skip_if_no("pyarrow")
def test_replace_from_index():
# https://github.com/pandas-dev/pandas/issues/61622
idx = pd.Index(["a", "b", "c"], dtype="string[pyarrow]")
expected = pd.Series(["d", "b", "c"], dtype="string[pyarrow]")
result = pd.Series(idx).replace({"z": "b", "a": "d"})
tm.assert_series_equal(result, expected)
| TestSeriesReplace |
python | django-crispy-forms__django-crispy-forms | crispy_forms/templatetags/crispy_forms_tags.py | {
"start": 7940,
"end": 10158
} | class ____(BasicNode):
def render(self, context):
c = self.get_render(context).flatten()
if self.actual_helper is not None and getattr(self.actual_helper, "template", False):
template = get_template(self.actual_helper.template)
else:
if c["is_formset"]:
template = whole_uni_formset_template(self.template_pack)
else:
template = whole_uni_form_template(self.template_pack)
return template.render(c)
# {% crispy %} tag
@register.tag(name="crispy")
def do_uni_form(parser, token):
"""
You need to pass in at least the form/formset object, and can also pass in the
optional `crispy_forms.helpers.FormHelper` object.
helper (optional): A `crispy_forms.helper.FormHelper` object.
Usage::
{% load crispy_tags %}
{% crispy form form.helper %}
You can also provide the template pack as the third argument::
{% crispy form form.helper 'bootstrap' %}
If the `FormHelper` attribute is named `helper` you can simply do::
{% crispy form %}
{% crispy form 'bootstrap' %}
"""
tokens = token.split_contents()
form = tokens.pop(1)
helper = None
template_pack = "'%s'" % get_template_pack()
# {% crispy form helper %}
try:
helper = tokens.pop(1)
except IndexError:
pass
# {% crispy form helper 'bootstrap' %}
try:
template_pack = tokens.pop(1)
except IndexError:
pass
# {% crispy form 'bootstrap' %}
if helper is not None and isinstance(helper, str) and ("'" in helper or '"' in helper):
template_pack = helper
helper = None
if template_pack is not None:
template_pack = template_pack[1:-1]
ALLOWED_TEMPLATE_PACKS = getattr(
settings, "CRISPY_ALLOWED_TEMPLATE_PACKS", ("uni_form", "bootstrap3", "bootstrap4")
)
if template_pack not in ALLOWED_TEMPLATE_PACKS:
raise template.TemplateSyntaxError(
"crispy tag's template_pack argument should be in %s" % str(ALLOWED_TEMPLATE_PACKS)
)
return CrispyFormNode(form, helper, template_pack=template_pack)
| CrispyFormNode |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_scalarmath.py | {
"start": 22773,
"end": 25013
} | class ____(TestCase):
def test_seq_repeat(self):
# Test that basic sequences get repeated when multiplied with
# numpy integers. And errors are raised when multiplied with others.
# Some of this behaviour may be controversial and could be open for
# change.
accepted_types = set(np.typecodes["AllInteger"])
deprecated_types = {"?"}
forbidden_types = set(np.typecodes["All"]) - accepted_types - deprecated_types
forbidden_types -= {"V"} # can't default-construct void scalars
for seq_type in (list, tuple):
seq = seq_type([1, 2, 3])
for numpy_type in accepted_types:
i = np.dtype(numpy_type).type(2)
assert_equal(seq * i, seq * int(i))
assert_equal(i * seq, int(i) * seq)
for numpy_type in deprecated_types:
i = np.dtype(numpy_type).type()
assert_equal(
assert_warns(DeprecationWarning, operator.mul, seq, i), seq * int(i)
)
assert_equal(
assert_warns(DeprecationWarning, operator.mul, i, seq), int(i) * seq
)
for numpy_type in forbidden_types:
i = np.dtype(numpy_type).type()
assert_raises(TypeError, operator.mul, seq, i)
assert_raises(TypeError, operator.mul, i, seq)
def test_no_seq_repeat_basic_array_like(self):
# Test that an array-like which does not know how to be multiplied
# does not attempt sequence repeat (raise TypeError).
# See also gh-7428.
class ArrayLike:
def __init__(self, arr):
self.arr = arr
def __array__(self):
return self.arr
# Test for simple ArrayLike above and memoryviews (original report)
for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))):
assert_array_equal(arr_like * np.float32(3.0), np.full(3, 3.0))
assert_array_equal(np.float32(3.0) * arr_like, np.full(3, 3.0))
assert_array_equal(arr_like * np.int_(3), np.full(3, 3))
assert_array_equal(np.int_(3) * arr_like, np.full(3, 3))
| TestMultiply |
python | pytorch__pytorch | test/quantization/fx/test_numeric_suite_fx.py | {
"start": 109615,
"end": 115944
} | class ____(FXNumericSuiteQuantizationTestCase):
"""
Tests numeric suite core APIs on non-toy models.
"""
@skipIfNoFBGEMM
def test_compare_weights_conv(self):
test_cases = (
(ConvModel(),),
(ConvBnModel(),),
(ConvBnReLUModel(),),
)
for m, in test_cases:
m.eval()
example_inputs = (torch.randn(1, 3, 5, 5),)
self._test_extract_weights(m, example_inputs, results_len=1)
@skipIfNoFBGEMM
def test_compare_weights_linear(self):
test_cases = (
(SingleLayerLinearModel(), None),
(
SingleLayerLinearDynamicModel(),
{"object_type": [(nn.Linear, default_dynamic_qconfig)]},
),
)
for m, qconfig_dict in test_cases:
m.eval()
example_inputs = (torch.randn(1, 3, 5, 5),)
res = self._test_extract_weights(
m, example_inputs, results_len=1, qconfig_dict=qconfig_dict)
@skipIfNoFBGEMM
def test_compare_weights_lstm_dynamic(self):
qconfig_dict = {"object_type": [(nn.LSTM, default_dynamic_qconfig)]}
lstm_input = torch.rand((1, 1, 2))
lstm_hidden = (torch.rand(1, 1, 2), torch.rand(1, 1, 2))
example_inputs = (lstm_input, lstm_hidden)
m = LSTMwithHiddenDynamicModel().eval()
res = self._test_extract_weights(
m, example_inputs, results_len=1, qconfig_dict=qconfig_dict)
@skipIfNoFBGEMM
def test_compare_activations_conv(self):
test_cases = (
(ConvModel(),),
(ConvBnModel(),),
(ConvBnReLUModel(),),
)
for m, in test_cases:
m.eval()
res = self._test_match_activations(
m, (torch.randn(1, 3, 4, 4),), results_len=1)
@skipIfNoFBGEMM
def test_compare_activations_linear(self):
test_cases = (
(SingleLayerLinearModel(), None),
(
SingleLayerLinearDynamicModel(),
{"object_type": [(nn.Linear, default_dynamic_qconfig)]},
),
)
for m, qconfig_dict in test_cases:
m.eval()
res = self._test_match_activations(
m, (torch.randn(5, 5),), results_len=1, qconfig_dict=qconfig_dict)
@skipIfNoFBGEMM
def test_compare_activations_lstm_dynamic(self):
qconfig_dict = {"object_type": [(nn.LSTM, default_dynamic_qconfig)]}
m = LSTMwithHiddenDynamicModel().eval()
lstm_input = torch.rand((1, 1, 2))
lstm_hidden = (torch.rand(1, 1, 2), torch.rand(1, 1, 2))
# TODO(future PR): enable scripting (quant prepared LSTM not scriptable)
res = self._test_match_activations(
m, (lstm_input, lstm_hidden), results_len=1, qconfig_dict=qconfig_dict,
skip_scripting=True)
@skipIfNoFBGEMM
def test_compare_shadow_activations_conv(self):
test_cases = (
(ConvModel(),),
(ConvBnModel(),),
(ConvBnReLUModel(),),
)
for m, in test_cases:
m.eval()
res = self._test_match_shadow_activations(
m, (torch.randn(1, 3, 4, 4),), results_len=1)
@skipIfNoFBGEMM
def test_compare_shadow_activations_linear(self):
test_cases = (
(SingleLayerLinearModel(), None),
(
SingleLayerLinearDynamicModel(),
{"object_type": [(nn.Linear, default_dynamic_qconfig)]},
),
)
for m, qconfig_dict in test_cases:
m.eval()
res = self._test_match_shadow_activations(
m, (torch.randn(5, 5),), results_len=1, qconfig_dict=qconfig_dict)
@skipIfNoFBGEMM
def test_compare_shadow_activations_lstm_dynamic(self):
qconfig_dict = {"object_type": [(nn.LSTM, default_dynamic_qconfig)]}
m = LSTMwithHiddenDynamicModel().eval()
lstm_input = torch.rand((1, 1, 2))
lstm_hidden = (torch.rand(1, 1, 2), torch.rand(1, 1, 2))
# TODO(future PR): enable scripting (quant prepared LSTM not scriptable)
res = self._test_match_shadow_activations(
m, (lstm_input, lstm_hidden), results_len=1, qconfig_dict=qconfig_dict,
skip_scripting=True)
@skipIfNoFBGEMM
def test_sparsenn_compare_activations(self):
for should_log_inputs in (True, False):
sparse_nn = SparseNNModel().eval()
idx = torch.LongTensor([1, 2, 4, 5, 4, 3, 2, 9])
offsets = torch.LongTensor([0, 4])
x = torch.randn(2, 4)
self._test_match_activations(
sparse_nn, (idx, offsets, x),
results_len=5,
should_log_inputs=should_log_inputs)
@skipIfNoFBGEMM
def test_sparsenn_shadow(self):
for should_log_inputs in (True, False):
sparse_nn = SparseNNModel().eval()
idx = torch.LongTensor([1, 2, 4, 5, 4, 3, 2, 9])
offsets = torch.LongTensor([0, 4])
x = torch.randn(2, 4)
self._test_match_shadow_activations(
sparse_nn, (idx, offsets, x),
results_len=3,
should_log_inputs=should_log_inputs)
@skipIfTorchDynamo("too slow")
@skip_if_no_torchvision
@skipIfNoFBGEMM
def test_resnet18(self):
import torchvision
m = torchvision.models.quantization.resnet18(pretrained=False, quantize=False).eval()
qconfig_dict = {'': torch.ao.quantization.default_qconfig}
self._test_match_shadow_activations(
m, (torch.randn(1, 3, 224, 224),),
qconfig_dict=qconfig_dict,
should_log_inputs=False)
@skipIfTorchDynamo("too slow")
@skip_if_no_torchvision
@skipIfNoFBGEMM
def test_mobilenet_v2(self):
import torchvision
m = torchvision.models.quantization.mobilenet_v2(pretrained=False, quantize=False).eval()
qconfig_dict = {'': torch.ao.quantization.default_qconfig}
self._test_match_shadow_activations(
m, (torch.randn(1, 3, 224, 224),),
qconfig_dict=qconfig_dict,
should_log_inputs=False)
if __name__ == "__main__":
raise_on_run_directly("test/test_quantization.py")
| TestFXNumericSuiteCoreAPIsModels |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/job_execution_result.py | {
"start": 828,
"end": 7262
} | class ____(ExecutionResult):
"""Result object returned by :py:func:`dagster.execute_job`.
Used for retrieving run success, events, and outputs from `execute_job`.
Users should not directly instantiate this class.
Events and run information can be retrieved off of the object directly. In
order to access outputs, the `ExecuteJobResult` object needs to be opened
as a context manager, which will re-initialize the resources from
execution.
"""
def __init__(
self,
job_def: JobDefinition,
reconstruct_context: ContextManager[PlanExecutionContext],
event_list: Sequence[DagsterEvent],
dagster_run: DagsterRun,
):
self._job_def = job_def
self._reconstruct_context = reconstruct_context
self._context = None
self._event_list = event_list
self._dagster_run = dagster_run
def __enter__(self) -> "JobExecutionResult":
context = self._reconstruct_context.__enter__()
self._context = context
return self
def __exit__(self, *exc):
exit_result = self._reconstruct_context.__exit__(*exc)
self._context = None
return exit_result
@public
@property
def job_def(self) -> JobDefinition:
"""JobDefinition: The job definition that was executed."""
return self._job_def
@public
@property
def dagster_run(self) -> DagsterRun:
"""DagsterRun: The Dagster run that was executed."""
return self._dagster_run
@public
@property
def all_events(self) -> Sequence[DagsterEvent]:
"""Sequence[DagsterEvent]: List of all events yielded by the job execution."""
return self._event_list
@public
@property
def run_id(self) -> str:
"""str: The id of the Dagster run that was executed."""
return self.dagster_run.run_id
@public
def output_value(self, output_name: str = DEFAULT_OUTPUT) -> Any:
"""Retrieves output of top-level job, if an output is returned.
In order to use this method, the `ExecuteJobResult` object must be opened as a context manager. If this method is used without opening the context manager, it will result in a :py:class:`DagsterInvariantViolationError`. If the top-level job has no output, calling this method will also result in a :py:class:`DagsterInvariantViolationError`.
Args:
output_name (Optional[str]): The name of the output to retrieve. Defaults to `result`,
the default output name in dagster.
Returns:
Any: The value of the retrieved output.
"""
return super().output_value(output_name=output_name)
@public
def output_for_node(self, node_str: str, output_name: str = DEFAULT_OUTPUT) -> Any:
"""Retrieves output value with a particular name from the run of the job.
In order to use this method, the `ExecuteJobResult` object must be opened as a context manager. If this method is used without opening the context manager, it will result in a :py:class:`DagsterInvariantViolationError`.
Args:
node_str (str): Name of the op/graph whose output should be retrieved. If the intended
graph/op is nested within another graph, the syntax is `outer_graph.inner_node`.
output_name (Optional[str]): Name of the output on the op/graph to retrieve. Defaults to
`result`, the default output name in dagster.
Returns:
Any: The value of the retrieved output.
"""
return super().output_for_node(node_str, output_name=output_name)
def _get_output_for_handle(self, handle: NodeHandle, output_name: str) -> Any:
if not self._context:
raise DagsterInvariantViolationError(
"In order to access output objects, the result of `execute_job` must be opened as a"
" context manager: 'with execute_job(...) as result:"
)
found = False
result = None
for compute_step_event in self.compute_events_for_handle(handle):
if (
compute_step_event.is_successful_output
and compute_step_event.step_output_data.output_name == output_name
):
found = True
output = compute_step_event.step_output_data
step = self._context.execution_plan.get_executable_step_by_key(
check.not_none(compute_step_event.step_key)
)
dagster_type = (
self.job_def.get_node(handle).output_def_named(output_name).dagster_type
)
value = self._get_value(self._context.for_step(step), output, dagster_type)
check.invariant(
not (output.mapping_key and step.get_mapping_key()),
"Not set up to handle mapped outputs downstream of mapped steps",
)
mapping_key = output.mapping_key or step.get_mapping_key()
if mapping_key:
if result is None:
result = {mapping_key: value}
else:
cast("dict", result)[mapping_key] = value
else:
result = value
if found:
return result
node = self.job_def.get_node(handle)
raise DagsterInvariantViolationError(
f"Did not find result {output_name} in {node.describe_node()}"
)
def _get_value(
self,
context: StepExecutionContext,
step_output_data: StepOutputData,
dagster_type: DagsterType,
) -> object:
step_output_handle = step_output_data.step_output_handle
manager = context.get_io_manager(step_output_handle)
manager_key = context.execution_plan.get_manager_key(step_output_handle, self.job_def)
res = manager.load_input(
context.for_input_manager(
name="dummy_input_name",
config=None,
definition_metadata=None,
dagster_type=dagster_type,
source_handle=step_output_handle,
resource_config=context.resolved_run_config.resources[manager_key].config,
resources=build_resources_for_manager(manager_key, context),
)
)
return res
| JobExecutionResult |
python | allegroai__clearml | clearml/utilities/plotlympl/mplexporter/renderers/vega_renderer.py | {
"start": 3992,
"end": 5480
} | class ____(object):
def __init__(self, renderer: VegaRenderer) -> None:
self.specification = dict(
width=renderer.figwidth,
height=renderer.figheight,
data=renderer.data,
scales=renderer.scales,
axes=renderer.axes,
marks=renderer.marks,
)
def html(self) -> str:
"""Build the HTML representation for IPython."""
id = random.randint(0, 2**16)
html = '<div id="vis%d"></div>' % id
html += "<script>\n"
html += VEGA_TEMPLATE % (json.dumps(self.specification), id)
html += "</script>\n"
return html
def _repr_html_(self) -> str:
return self.html()
def fig_to_vega(fig: Any, notebook: bool = False) -> Union[VegaHTML, str]:
"""Convert a matplotlib figure to vega dictionary
if notebook=True, then return an object which will display in a notebook
otherwise, return an HTML string.
"""
renderer = VegaRenderer()
Exporter(renderer).run(fig)
vega_html = VegaHTML(renderer)
if notebook:
return vega_html
else:
return vega_html.html()
VEGA_TEMPLATE = """
( function() {
var _do_plot = function() {
if ( (typeof vg == 'undefined') && (typeof IPython != 'undefined')) {
$([IPython.events]).on("vega_loaded.vincent", _do_plot);
return;
}
vg.parse.spec(%s, function(chart) {
chart({el: "#vis%d"}).update();
});
};
_do_plot();
})();
"""
| VegaHTML |
python | pytorch__pytorch | test/test_rename_privateuse1_to_existing_device.py | {
"start": 604,
"end": 1826
} | class ____(TestCase):
@skipIfTorchDynamo(
"TorchDynamo exposes https://github.com/pytorch/pytorch/issues/166696"
)
def test_external_module_register_with_existing_backend(self):
torch.utils.rename_privateuse1_backend("maia")
with self.assertRaisesRegex(RuntimeError, "has already been set"):
torch.utils.rename_privateuse1_backend("dummmy")
custom_backend_name = torch._C._get_privateuse1_backend_name()
self.assertEqual(custom_backend_name, "maia")
with self.assertRaises(AttributeError):
torch.maia.is_available()
with self.assertRaisesRegex(AssertionError, "Tried to use AMP with the"):
with torch.autocast(device_type=custom_backend_name):
pass
torch._register_device_module("maia", DummyPrivateUse1Module)
torch.maia.is_available() # type: ignore[attr-defined]
with torch.autocast(device_type=custom_backend_name):
pass
self.assertEqual(torch._utils._get_device_index("maia:1"), 1)
self.assertEqual(torch._utils._get_device_index(torch.device("maia:2")), 2)
if __name__ == "__main__":
run_tests()
| TestRenamePrivateuseoneToExistingBackend |
python | gevent__gevent | src/gevent/tests/test__event.py | {
"start": 2482,
"end": 4328
} | class ____(greentest.TestCase):
def test_link(self):
ar = AsyncResult()
self.assertRaises(TypeError, ar.rawlink, None)
ar.unlink(None) # doesn't raise
ar.unlink(None) # doesn't raise
str(ar) # cover
def test_set_exc(self):
log = []
e = AsyncResult()
self.assertEqual(e.exc_info, ())
self.assertEqual(e.exception, None)
def waiter():
with self.assertRaises(MyException) as exc:
e.get()
log.append(('caught', exc.exception))
gevent.spawn(waiter)
obj = MyException()
e.set_exception(obj)
gevent.sleep(0)
self.assertEqual(log, [('caught', obj)])
def test_set(self):
event1 = AsyncResult()
timer_exc = MyException('interrupted')
# Notice that this test is racy:
# After DELAY, we set the event. We also try to immediately
# raise the exception with a timer of 0 --- but that depends
# on cycling the loop. Hence the fairly large value for DELAY.
g = gevent.spawn_later(DELAY, event1.set, 'hello event1')
self._close_on_teardown(g.kill)
with gevent.Timeout.start_new(0, timer_exc):
with self.assertRaises(MyException) as exc:
event1.get()
self.assertIs(timer_exc, exc.exception)
def test_set_with_timeout(self):
event2 = AsyncResult()
X = object()
result = gevent.with_timeout(DELAY, event2.get, timeout_value=X)
self.assertIs(
result, X,
'Nobody sent anything to event2 yet it received %r' % (result, ))
def test_nonblocking_get(self):
ar = AsyncResult()
self.assertRaises(gevent.Timeout, ar.get, block=False)
self.assertRaises(gevent.Timeout, ar.get_nowait)
| TestAsyncResult |
python | bottlepy__bottle | bottle.py | {
"start": 80314,
"end": 81096
} | class ____:
""" This plugin applies the :func:`view` decorator to all routes with a
`template` config parameter. If the parameter is a tuple, the second
element must be a dict with additional options (e.g. `template_engine`)
or default variables for the template. """
name = 'template'
api = 2
def setup(self, app):
app.tpl = self
def apply(self, callback, route):
conf = route.config.get('template')
if isinstance(conf, (tuple, list)) and len(conf) == 2:
return view(conf[0], **conf[1])(callback)
elif isinstance(conf, str):
return view(conf)(callback)
else:
return callback
#: Not a plugin, but part of the plugin API. TODO: Find a better place.
| TemplatePlugin |
python | pytorch__pytorch | test/dynamo/test_error_messages.py | {
"start": 1328,
"end": 1466
} | class ____:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
| GenericCtxMgr |
python | ipython__ipython | IPython/terminal/ptutils.py | {
"start": 6964,
"end": 8067
} | class ____(Lexer):
"""
Wrapper around PythonLexer and BashLexer.
"""
def __init__(self):
l = pygments_lexers
self.python_lexer = PygmentsLexer(l.Python3Lexer)
self.shell_lexer = PygmentsLexer(l.BashLexer)
self.magic_lexers = {
'HTML': PygmentsLexer(l.HtmlLexer),
'html': PygmentsLexer(l.HtmlLexer),
'javascript': PygmentsLexer(l.JavascriptLexer),
'js': PygmentsLexer(l.JavascriptLexer),
'perl': PygmentsLexer(l.PerlLexer),
'ruby': PygmentsLexer(l.RubyLexer),
'latex': PygmentsLexer(l.TexLexer),
}
def lex_document(self, document):
text = document.text.lstrip()
lexer = self.python_lexer
if text.startswith('!') or text.startswith('%%bash'):
lexer = self.shell_lexer
elif text.startswith('%%'):
for magic, l in self.magic_lexers.items():
if text.startswith('%%' + magic):
lexer = l
break
return lexer.lex_document(document)
| IPythonPTLexer |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/execution_api/app.py | {
"start": 4067,
"end": 5644
} | class ____(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
from airflow.configuration import conf
response: Response = await call_next(request)
refreshed_token: str | None = None
auth_header = request.headers.get("authorization")
if auth_header and auth_header.lower().startswith("bearer "):
token = auth_header.split(" ", 1)[1]
try:
async with svcs.Container(request.app.state.svcs_registry) as services:
validator: JWTValidator = await services.aget(JWTValidator)
claims = await validator.avalidated_claims(token, {})
now = int(time.time())
validity = conf.getint("execution_api", "jwt_expiration_time")
refresh_when_less_than = max(int(validity * 0.20), 30)
valid_left = int(claims.get("exp", 0)) - now
if valid_left <= refresh_when_less_than:
generator: JWTGenerator = await services.aget(JWTGenerator)
refreshed_token = generator.generate(claims)
except Exception as err:
# Do not block the response if refreshing fails; log a warning for visibility
logger.warning(
"JWT reissue middleware failed to refresh token", error=str(err), exc_info=True
)
if refreshed_token:
response.headers["Refreshed-API-Token"] = refreshed_token
return response
| JWTReissueMiddleware |
python | keras-team__keras | keras/src/layers/pooling/max_pooling_test.py | {
"start": 7582,
"end": 9968
} | class ____(testing.TestCase):
@parameterized.parameters(
(2, 1, "valid", "channels_last"),
(2, 1, "valid", "channels_first"),
(2, 1, "same", "channels_last"),
(2, 1, "same", "channels_first"),
((2,), (2,), "valid", "channels_last"),
((2,), (2,), "valid", "channels_first"),
)
def test_max_pooling1d(self, pool_size, strides, padding, data_format):
inputs = np.arange(24, dtype="float32").reshape((2, 3, 4))
layer = layers.MaxPooling1D(
pool_size=pool_size,
strides=strides,
padding=padding,
data_format=data_format,
)
outputs = layer(inputs)
expected = np_maxpool1d(
inputs, pool_size, strides, padding, data_format
)
self.assertAllClose(outputs, expected)
@parameterized.parameters(
(2, 1, "valid", "channels_last"),
(2, 1, "valid", "channels_first"),
((2, 2), (2, 2), "same", "channels_last"),
((2, 2), (2, 2), "same", "channels_first"),
((2, 3), (3, 3), "same", "channels_last"),
)
def test_max_pooling2d(self, pool_size, strides, padding, data_format):
inputs = np.arange(100, dtype="float32").reshape((1, 5, 5, 4))
layer = layers.MaxPooling2D(
pool_size=pool_size,
strides=strides,
padding=padding,
data_format=data_format,
)
outputs = layer(inputs)
expected = np_maxpool2d(
inputs, pool_size, strides, padding, data_format
)
self.assertAllClose(outputs, expected)
@parameterized.parameters(
(2, 1, "valid", "channels_last"),
(2, 1, "same", "channels_first"),
((2, 3, 2), (2, 2, 1), "valid", "channels_last"),
((2, 3, 2), (2, 2, 1), "valid", "channels_first"),
)
def test_max_pooling3d(self, pool_size, strides, padding, data_format):
inputs = np.arange(240, dtype="float32").reshape((2, 3, 4, 5, 2))
layer = layers.MaxPooling3D(
pool_size=pool_size,
strides=strides,
padding=padding,
data_format=data_format,
)
outputs = layer(inputs)
expected = np_maxpool3d(
inputs, pool_size, strides, padding, data_format
)
self.assertAllClose(outputs, expected)
| MaxPoolingCorrectnessTest |
python | huggingface__transformers | src/transformers/models/efficientloftr/modeling_efficientloftr.py | {
"start": 7512,
"end": 8309
} | class ____(nn.Module):
def __init__(self, config, in_channels, out_channels, kernel_size, stride, padding=None, activation=None):
super().__init__()
self.conv = nn.Conv2d(
in_channels,
out_channels,
kernel_size,
stride,
padding=(kernel_size - 1) // 2 if padding is None else padding,
bias=False,
)
self.norm = nn.BatchNorm2d(out_channels, config.batch_norm_eps)
self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
def forward(self, hidden_state):
hidden_state = self.conv(hidden_state)
hidden_state = self.norm(hidden_state)
hidden_state = self.activation(hidden_state)
return hidden_state
| EfficientLoFTRConvNormLayer |
python | getsentry__sentry | src/sentry/snuba/sessions_v2.py | {
"start": 4147,
"end": 5378
} | class ____:
def get_snuba_columns(self, raw_groupby):
if "session.status" in raw_groupby:
return ["users", "users_abnormal", "users_crashed", "users_errored", "users_unhandled"]
return ["users"]
def extract_from_row(self, row, group):
if row is None:
return 0
status = group.get("session.status")
if status is None:
return row["users"]
if status == "healthy":
healthy_users = row["users"] - row["users_errored"] - row["users_unhandled"]
return max(healthy_users, 0)
if status == "abnormal":
return row["users_abnormal"]
if status == "unhandled":
return row["users_unhandled"]
if status == "crashed":
return row["users_crashed"]
if status == "errored":
errored_users = (
row["users_errored"]
- row["users_crashed"]
- row["users_abnormal"]
- row["users_unhandled"]
)
return max(errored_users, 0)
return 0
def finite_or_none(val):
if isinstance(val, (int, float)) and not math.isfinite(val):
return None
return val
| UsersField |
python | walkccc__LeetCode | solutions/630. Course Schedule III/630.py | {
"start": 0,
"end": 532
} | class ____:
def scheduleCourse(self, courses: list[list[int]]) -> int:
time = 0
maxHeap = []
for duration, lastDay in sorted(courses, key=lambda x: x[1]):
heapq.heappush(maxHeap, -duration)
time += duration
# If the current course cannot be taken, check if it can be swapped with
# a previously taken course that has a larger duration to increase the
# time available to take upcoming courses.
if time > lastDay:
time += heapq.heappop(maxHeap)
return len(maxHeap)
| Solution |
python | pytorch__pytorch | torch/_inductor/distributed_autotune.py | {
"start": 3576,
"end": 6430
} | class ____(MultiTemplateBuffer):
"""
A MultiTemplateBuffer which represents a kernel being autotuned on a
different rank. When `schedule` is called this will be replaced by the
"real" buffer.
"""
# Name of the kernel being autotuned.
_kernel_name: str
def __init__(
self,
kernel_name: str,
inputs: list[Buffer],
layout: Layout,
) -> None:
super().__init__(
layout,
inputs,
choice_timings_fn=self._dummy_choice_timings,
unfiltered_choices=[],
allowed_prologue_inps=OrderedSet({}),
)
self._kernel_name = kernel_name
def _dummy_choice_timings(
self, _hint_override: int | None
) -> dict[ChoiceCaller, float]:
# This should never get called. It means that a remote autotune was
# scheduled but never filled in.
raise NotImplementedError
def autotune(self, ser_choice: _SerializedChoice) -> TensorBox:
"""
Given a _SerializedChoice (autotune results from another rank)
compute the final TensorBox.
"""
from .select_algorithm import autotune_select_algorithm
with patch.object(V.graph, "scheduler", None):
kernel_inputs = MMKernelInputs([*self.original_inputs])
assert isinstance(self.layout, Layout)
choice = ser_choice.get_choice(self.layout, kernel_inputs)
buffer = autotune_select_algorithm(
self._kernel_name,
[choice],
kernel_inputs.nodes(),
self.layout,
)
assert isinstance(buffer, TensorBox)
return buffer
# Can we make this async?
def _sync(autotune_results: list[_SerializedChoice]) -> Sequence[_SerializedChoice]:
"""
Perform the all_gather to collect the autotune results from all the ranks.
"""
autotune_pg = get_autotune_pg()
assert autotune_pg
# Perform allgather
all_states: list[list[_SerializedChoice]] = [None] * autotune_pg.size() # type: ignore[list-item]
torch.distributed.all_gather_object(all_states, autotune_results, group=autotune_pg)
node_count = sum(len(x) for x in all_states)
# It's faster to briefly lie about the type than to unzip the results and append.
choices_by_index: list[_SerializedChoice] = [None] * node_count # type: ignore[list-item]
check_count = 0
for other_results in all_states:
for choice in other_results:
assert isinstance(choice, _SerializedChoice)
assert choices_by_index[choice.index] is None
choices_by_index[choice.index] = choice
check_count += 1
assert node_count == check_count, f"count mismatch: {node_count} != {check_count}"
return choices_by_index
| _DistributedAutotuneBuffer |
python | realpython__materials | fastapi/main.py | {
"start": 290,
"end": 1048
} | class ____(BaseModel):
title: str
author: str
pages: int
@app.get("/books")
def get_books(limit: int | None = None):
"""Get all books, optionally limited by count."""
if limit:
return {"books": books[:limit]}
return {"books": books}
@app.get("/books/{book_id}")
def get_book(book_id: int):
"""Get a specific book by ID."""
for book in books:
if book["id"] == book_id:
return book
return {"error": "Book not found"}
@app.post("/books")
def create_book(book: Book):
"""Create a new book entry."""
new_book = {
"id": len(books) + 1,
"title": book.title,
"author": book.author,
"pages": book.pages,
}
books.append(new_book)
return new_book
| Book |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_searchstrategy.py | {
"start": 4685,
"end": 4774
} | class ____:
value: int
def to_json(self):
return "custom"
@dataclass
| Inner |
python | conda__conda | conda/models/records.py | {
"start": 6823,
"end": 7341
} | class ____(Entity):
_path = StringField()
prefix_placeholder = StringField(
required=False, nullable=True, default=None, default_in_dump=False
)
file_mode = EnumField(FileMode, required=False, nullable=True)
no_link = BooleanField(
required=False, nullable=True, default=None, default_in_dump=False
)
path_type = EnumField(PathType)
@property
def path(self):
# because I don't have aliases as an option for entity fields yet
return self._path
| PathData |
python | PrefectHQ__prefect | tests/test_flow_engine.py | {
"start": 57260,
"end": 61486
} | class ____:
async def test_generator_flow(self):
"""
Test for generator behavior including StopIteration
"""
@flow
async def g():
yield 1
yield 2
counter = 0
async for val in g():
if counter == 0:
assert val == 1
if counter == 1:
assert val == 2
assert counter <= 1
counter += 1
async def test_generator_flow_requires_return_type_result(self):
@flow
async def g():
yield 1
with pytest.raises(
ValueError, match="The return_type for a generator flow must be 'result'"
):
async for i in g(return_state=True):
pass
async def test_generator_flow_states(self, prefect_client: PrefectClient):
"""
Test for generator behavior including StopIteration
"""
@flow
async def g():
yield FlowRunContext.get().flow_run.id
async for val in g():
tr_id = val
tr = await prefect_client.read_flow_run(tr_id)
assert tr.state.is_running()
tr = await prefect_client.read_flow_run(tr_id)
assert tr.state.is_completed()
async def test_generator_flow_with_exception(self):
@flow
async def g():
yield 1
raise ValueError("xyz")
with pytest.raises(ValueError, match="xyz"):
async for val in g():
assert val == 1
async def test_generator_flow_with_exception_is_failed(
self, prefect_client: PrefectClient
):
@flow
async def g():
yield FlowRunContext.get().flow_run.id
raise ValueError("xyz")
with pytest.raises(ValueError, match="xyz"):
async for val in g():
tr_id = val
tr = await prefect_client.read_flow_run(tr_id)
assert tr.state.is_failed()
async def test_generator_retries(self):
"""
Test that a generator can retry and will re-emit its events
"""
@flow(retries=2)
async def g():
yield 1
yield 2
raise ValueError()
values = []
try:
async for v in g():
values.append(v)
except ValueError:
pass
assert values == [1, 2, 1, 2, 1, 2]
@pytest.mark.xfail(
reason="Synchronous sleep in an async flow is not interruptible by async timeout"
)
async def test_generator_timeout_with_sync_sleep(self):
"""
Test that a generator can timeout
"""
@flow(timeout_seconds=0.1)
async def g():
yield 1
time.sleep(2)
yield 2
values = []
with pytest.raises(TimeoutError):
async for v in g():
values.append(v)
assert values == [1]
async def test_generator_timeout_with_async_sleep(self):
"""
Test that a generator can timeout
"""
@flow(timeout_seconds=0.1)
async def g():
yield 1
await asyncio.sleep(2)
yield 2
values = []
with pytest.raises(TimeoutError):
async for v in g():
values.append(v)
assert values == [1]
async def test_generator_doesnt_retry_on_generator_exception(self):
"""
Test that a generator doesn't retry for normal generator exceptions like StopIteration
"""
@flow(retries=2)
async def g():
yield 1
yield 2
values = []
try:
async for v in g():
values.append(v)
except ValueError:
pass
assert values == [1, 2]
async def test_with_default_pydantic_model_dict_params(self):
class TheModel(pydantic.BaseModel):
x: list[int]
@flow
def g(required: str, model: TheModel = {"x": [1, 2, 3]}): # type: ignore
yield required
for i in model.x:
yield i
assert [i for i in g("hello")] == ["hello", 1, 2, 3]
| TestAsyncGenerators |
python | modin-project__modin | modin/core/execution/dispatching/factories/factories.py | {
"start": 22168,
"end": 22533
} | class ____(BaseFactory):
@classmethod
@doc(_doc_factory_prepare_method, io_module_name="``PandasOnRayIO``")
def prepare(cls):
from modin.core.execution.ray.implementations.pandas_on_ray.io import (
PandasOnRayIO,
)
cls.io_cls = PandasOnRayIO
@doc(_doc_factory_class, execution_name="PandasOnPython")
| PandasOnRayFactory |
python | tensorflow__tensorflow | third_party/xla/xla/python/xla_client.py | {
"start": 14920,
"end": 15573
} | class ____:
"""Python representation of a xla.ReplicaGroup protobuf."""
__slots__ = ('replica_ids',)
def __init__(self):
self.replica_ids = []
def _make_replica_group_proto(replica_group):
replica_group_proto = ReplicaGroup()
replica_group_proto.replica_ids.extend(replica_group)
return replica_group_proto
def make_replica_groups(replica_groups):
if replica_groups is None:
replica_groups_protos = [] # special value for XLA API
else:
replica_groups = list(replica_groups)
replica_groups_protos = [
_make_replica_group_proto(group) for group in replica_groups
]
return replica_groups_protos
| ReplicaGroup |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 108772,
"end": 113776
} | class ____(TestCase):
"""
Tests chasing OneToOne foreign keys across time points naturally with
HistoricForeignKey.
"""
def test_non_historic_to_historic(self):
"""
Non-historic table with one to one relationship to historic table.
In this case it should simply behave like OneToOneField because
the origin model (this one) cannot be historic, so OneToOneField
lookups are always "current".
"""
org = TestOrganizationWithHistory.objects.create(name="original")
part = TestParticipantToHistoricOrganizationOneToOne.objects.create(
name="part", organization=org
)
before_mod = timezone.now()
self.assertEqual(part.organization.id, org.id)
self.assertEqual(org.participant, part)
historg = TestOrganizationWithHistory.history.as_of(before_mod).get(
name="original"
)
self.assertEqual(historg.participant, part)
self.assertEqual(org.history.count(), 1)
org.name = "modified"
org.save()
self.assertEqual(org.history.count(), 2)
# drop internal caches, re-select
part = TestParticipantToHistoricOrganizationOneToOne.objects.get(name="part")
self.assertEqual(part.organization.name, "modified")
def test_historic_to_non_historic(self):
"""
Historic table OneToOneField to non-historic table.
In this case it should simply behave like OneToOneField because
the origin model (this one) can be historic but the target model
is not, so foreign key lookups are always "current".
"""
org = TestOrganization.objects.create(name="org")
part = TestHistoricParticipantToOrganizationOneToOne.objects.create(
name="original", organization=org
)
self.assertEqual(part.organization.id, org.id)
self.assertEqual(org.participant, part)
histpart = TestHistoricParticipantToOrganizationOneToOne.objects.get(
name="original"
)
self.assertEqual(histpart.organization.id, org.id)
def test_historic_to_historic(self):
"""
Historic table with one to one relationship to historic table.
In this case as_of queries on the origin model (this one)
or on the target model (the other one) will traverse the
foreign key relationship honoring the timepoint of the
original query. This only happens when both tables involved
are historic.
At t1 we have one org, one participant.
At t2 we have one org, one participant, however the org's name has changed.
"""
org = TestOrganizationWithHistory.objects.create(name="original")
p1 = TestHistoricParticipanToHistoricOrganizationOneToOne.objects.create(
name="p1", organization=org
)
t1 = timezone.now()
org.name = "modified"
org.save()
p1.name = "p1_modified"
p1.save()
t2 = timezone.now()
# forward relationships - see how natural chasing timepoint relations is
p1t1 = TestHistoricParticipanToHistoricOrganizationOneToOne.history.as_of(
t1
).get(name="p1")
self.assertEqual(p1t1.organization, org)
self.assertEqual(p1t1.organization.name, "original")
p1t2 = TestHistoricParticipanToHistoricOrganizationOneToOne.history.as_of(
t2
).get(name="p1_modified")
self.assertEqual(p1t2.organization, org)
self.assertEqual(p1t2.organization.name, "modified")
# reverse relationships
# at t1
ot1 = TestOrganizationWithHistory.history.as_of(t1).all()[0]
self.assertEqual(ot1.historic_participant.name, "p1")
# at t2
ot2 = TestOrganizationWithHistory.history.as_of(t2).all()[0]
self.assertEqual(ot2.historic_participant.name, "p1_modified")
# current
self.assertEqual(org.historic_participant.name, "p1_modified")
self.assertTrue(is_historic(ot1))
self.assertFalse(is_historic(org))
self.assertIsInstance(
to_historic(ot1), TestOrganizationWithHistory.history.model
)
self.assertIsNone(to_historic(org))
# test querying directly from the history table and converting
# to an instance, it should chase the foreign key properly
# in this case if _as_of is not present we use the history_date
# https://github.com/django-commons/django-simple-history/issues/983
pt1h = TestHistoricParticipanToHistoricOrganizationOneToOne.history.all()[0]
pt1i = pt1h.instance
self.assertEqual(pt1i.organization.name, "modified")
pt1h = (
TestHistoricParticipanToHistoricOrganizationOneToOne.history.all().order_by(
"history_date"
)[0]
)
pt1i = pt1h.instance
self.assertEqual(pt1i.organization.name, "original")
| HistoricOneToOneFieldTest |
python | getsentry__sentry | tests/acceptance/test_account_settings.py | {
"start": 117,
"end": 3112
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(name="Rowdy Tiger Rowdy Tiger Rowdy Tiger", owner=None)
self.team = self.create_team(
organization=self.org, name="Mariachi Band Mariachi Band Mariachi Band"
)
self.project = self.create_project(
organization=self.org, teams=[self.team], name="Bengal Bengal Bengal Bengal"
)
self.create_member(user=self.user, organization=self.org, role="owner", teams=[self.team])
second_org = self.create_organization(name="Multiple Owners", owner=self.user)
self.create_member(
user=self.create_user("bar@example.com"), organization=second_org, role="owner"
)
self.login_as(self.user)
def test_account_security_settings(self) -> None:
with (
self.options({"system.url-prefix": self.browser.live_server_url}),
self.feature("organizations:onboarding"),
):
self.browser.get("/settings/account/security/")
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
def test_account_notifications(self) -> None:
with (
self.options({"system.url-prefix": self.browser.live_server_url}),
self.feature("organizations:onboarding"),
):
self.browser.get("/settings/account/notifications/")
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
self.browser.click_when_visible('[data-test-id="fine-tuning"]')
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
def test_account_emails_settings(self) -> None:
with self.feature("organizations:onboarding"):
self.browser.get("/settings/account/emails/")
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
def test_account_subscriptions_settings(self) -> None:
with self.feature("organizations:onboarding"):
self.browser.get("/settings/account/subscriptions/")
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
def test_account_authorizations_settings(self) -> None:
with self.feature("organizations:onboarding"):
self.browser.get("/account/authorizations/")
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
def test_account_identities_settings(self) -> None:
with self.feature("organizations:onboarding"):
self.browser.get("/settings/account/identities/")
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
def test_close_account(self) -> None:
with self.options({"system.url-prefix": self.browser.live_server_url}):
self.browser.get("/account/remove/")
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
| AccountSettingsTest |
python | walkccc__LeetCode | solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639.py | {
"start": 0,
"end": 678
} | class ____:
def numWays(self, words: list[str], target: str) -> int:
MOD = 1_000_000_007
wordLength = len(words[0])
# counts[j] := the count map of words[i][j], where 0 <= i < |words|
counts = [collections.Counter() for _ in range(wordLength)]
for i in range(wordLength):
for word in words:
counts[i][word[i]] += 1
@functools.lru_cache(None)
def dp(i: int, j: int):
"""Returns the number of ways to form target[i..n) using word[j..n)."""
if i == len(target):
return 1
if j == wordLength:
return 0
return (dp(i + 1, j + 1) * counts[j][target[i]] + dp(i, j + 1)) % MOD
return dp(0, 0)
| Solution |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_A.py | {
"start": 5636,
"end": 6771
} | class ____(Benchmark):
r"""
Alpine02 objective function.
The Alpine02 [1]_ global optimization problem is a multimodal minimization
problem defined as follows:
.. math::
f_{\text{Alpine02}(x) = \prod_{i=1}^{n} \sqrt{x_i} \sin(x_i)
Here, :math:`n` represents the number of dimensions and :math:`x_i \in [0,
10]` for :math:`i = 1, ..., n`.
*Global optimum*: :math:`f(x) = -6.1295` for :math:`x =
[7.91705268, 4.81584232]` for :math:`i = 1, 2`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO: eqn 7 in [1]_ has the wrong global minimum value.
"""
change_dimensionality = True
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([0.0] * self.N, [10.0] * self.N))
self.global_optimum = [[7.91705268, 4.81584232]]
self.fglob = -6.12950
def fun(self, x, *args):
self.nfev += 1
return prod(sqrt(x) * sin(x))
| Alpine02 |
python | django__django | tests/model_fields/models.py | {
"start": 15422,
"end": 15466
} | class ____(UUIDChild):
pass
| UUIDGrandchild |
python | scipy__scipy | scipy/signal/tests/test_signaltools.py | {
"start": 1486,
"end": 11655
} | class ____:
@skip_xp_backends("jax.numpy",
reason="jax returns floats; scipy returns ints; cf gh-6076")
def test_basic(self, xp):
a = xp.asarray([3, 4, 5, 6, 5, 4])
b = xp.asarray([1, 2, 3])
c = convolve(a, b)
xp_assert_equal(c, xp.asarray([3, 10, 22, 28, 32, 32, 23, 12]))
@skip_xp_backends("jax.numpy",
reason="jax returns floats; scipy returns ints; cf gh-6076")
def test_same(self, xp):
a = xp.asarray([3, 4, 5])
b = xp.asarray([1, 2, 3, 4])
c = convolve(a, b, mode="same")
xp_assert_equal(c, xp.asarray([10, 22, 34]))
@skip_xp_backends("jax.numpy",
reason="jax returns floats; scipy returns ints; cf gh-6076")
def test_same_eq(self, xp):
a = xp.asarray([3, 4, 5])
b = xp.asarray([1, 2, 3])
c = convolve(a, b, mode="same")
xp_assert_equal(c, xp.asarray([10, 22, 22]))
def test_complex(self, xp):
x = xp.asarray([1 + 1j, 2 + 1j, 3 + 1j])
y = xp.asarray([1 + 1j, 2 + 1j])
z = convolve(x, y)
xp_assert_equal(z, xp.asarray([2j, 2 + 6j, 5 + 8j, 5 + 5j]))
@xfail_xp_backends("jax.numpy", reason="wrong output dtype")
def test_zero_rank(self, xp):
a = xp.asarray(1289)
b = xp.asarray(4567)
c = convolve(a, b)
xp_assert_equal(c, a * b)
@skip_xp_backends(np_only=True, reason="pure python")
def test_zero_rank_python_scalars(self, xp):
a = 1289
b = 4567
c = convolve(a, b)
assert c == a * b
@xfail_xp_backends("jax.numpy", reason="disagreement between methods")
def test_broadcastable(self, xp):
a = xp.reshape(xp.arange(27), (3, 3, 3))
b = xp.arange(3)
for i in range(3):
b_shape = [1]*3
b_shape[i] = 3
x = convolve(a, xp.reshape(b, tuple(b_shape)), method='direct')
y = convolve(a, xp.reshape(b, tuple(b_shape)), method='fft')
xp_assert_close(x, y, atol=1e-14)
@xfail_xp_backends("jax.numpy", reason="wrong output dtype")
def test_single_element(self, xp):
a = xp.asarray([4967])
b = xp.asarray([3920])
c = convolve(a, b)
xp_assert_equal(c, a * b)
@skip_xp_backends("jax.numpy",)
@skip_xp_backends("cupy")
def test_2d_arrays(self, xp):
a = xp.asarray([[1, 2, 3], [3, 4, 5]])
b = xp.asarray([[2, 3, 4], [4, 5, 6]])
c = convolve(a, b)
d = xp.asarray([[2, 7, 16, 17, 12],
[10, 30, 62, 58, 38],
[12, 31, 58, 49, 30]])
xp_assert_equal(c, d)
@skip_xp_backends("torch")
@skip_xp_backends("cupy")
def test_input_swapping(self, xp):
small = xp.reshape(xp.arange(8), (2, 2, 2))
big = 1j * xp.reshape(xp.arange(27, dtype=xp.complex128), (3, 3, 3))
big += xp.reshape(xp.arange(27, dtype=xp.complex128)[::-1], (3, 3, 3))
out_array = xp.asarray(
[[[0 + 0j, 26 + 0j, 25 + 1j, 24 + 2j],
[52 + 0j, 151 + 5j, 145 + 11j, 93 + 11j],
[46 + 6j, 133 + 23j, 127 + 29j, 81 + 23j],
[40 + 12j, 98 + 32j, 93 + 37j, 54 + 24j]],
[[104 + 0j, 247 + 13j, 237 + 23j, 135 + 21j],
[282 + 30j, 632 + 96j, 604 + 124j, 330 + 86j],
[246 + 66j, 548 + 180j, 520 + 208j, 282 + 134j],
[142 + 66j, 307 + 161j, 289 + 179j, 153 + 107j]],
[[68 + 36j, 157 + 103j, 147 + 113j, 81 + 75j],
[174 + 138j, 380 + 348j, 352 + 376j, 186 + 230j],
[138 + 174j, 296 + 432j, 268 + 460j, 138 + 278j],
[70 + 138j, 145 + 323j, 127 + 341j, 63 + 197j]],
[[32 + 72j, 68 + 166j, 59 + 175j, 30 + 100j],
[68 + 192j, 139 + 433j, 117 + 455j, 57 + 255j],
[38 + 222j, 73 + 499j, 51 + 521j, 21 + 291j],
[12 + 144j, 20 + 318j, 7 + 331j, 0 + 182j]]])
xp_assert_equal(convolve(small, big, 'full'), out_array)
xp_assert_equal(convolve(big, small, 'full'), out_array)
xp_assert_equal(convolve(small, big, 'same'),
out_array[1:3, 1:3, 1:3])
xp_assert_equal(convolve(big, small, 'same'),
out_array[0:3, 0:3, 0:3])
xp_assert_equal(convolve(small, big, 'valid'),
out_array[1:3, 1:3, 1:3])
xp_assert_equal(convolve(big, small, 'valid'),
out_array[1:3, 1:3, 1:3])
def test_invalid_params(self, xp):
a = xp.asarray([3, 4, 5])
b = xp.asarray([1, 2, 3])
assert_raises(ValueError, convolve, a, b, mode='spam')
assert_raises(ValueError, convolve, a, b, mode='eggs', method='fft')
assert_raises(ValueError, convolve, a, b, mode='ham', method='direct')
assert_raises(ValueError, convolve, a, b, mode='full', method='bacon')
assert_raises(ValueError, convolve, a, b, mode='same', method='bacon')
@skip_xp_backends("jax.numpy", reason="dtypes do not match")
def test_valid_mode2(self, xp):
# See gh-5897
a = xp.asarray([1, 2, 3, 6, 5, 3])
b = xp.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1])
expected = xp.asarray([70, 78, 73, 65])
out = convolve(a, b, 'valid')
xp_assert_equal(out, expected)
out = convolve(b, a, 'valid')
xp_assert_equal(out, expected)
a = xp.asarray([1 + 5j, 2 - 1j, 3 + 0j])
b = xp.asarray([2 - 3j, 1 + 0j])
expected = xp.asarray([2 - 3j, 8 - 10j])
out = convolve(a, b, 'valid')
xp_assert_equal(out, expected)
out = convolve(b, a, 'valid')
xp_assert_equal(out, expected)
@skip_xp_backends("jax.numpy", reason="dtypes do not match")
def test_same_mode(self, xp):
a = xp.asarray([1, 2, 3, 3, 1, 2])
b = xp.asarray([1, 4, 3, 4, 5, 6, 7, 4, 3, 2, 1, 1, 3])
c = convolve(a, b, 'same')
d = xp.asarray([57, 61, 63, 57, 45, 36])
xp_assert_equal(c, d)
@skip_xp_backends("cupy", reason="different exception")
def test_invalid_shapes(self, xp):
# By "invalid," we mean that no one
# array has dimensions that are all at
# least as large as the corresponding
# dimensions of the other array. This
# setup should throw a ValueError.
a = xp.reshape(xp.arange(1, 7), (2, 3))
b = xp.reshape(xp.arange(-6, 0), (3, 2))
assert_raises(ValueError, convolve, *(a, b), **{'mode': 'valid'})
assert_raises(ValueError, convolve, *(b, a), **{'mode': 'valid'})
@skip_xp_backends(np_only=True, reason="TODO: convert this test")
def test_convolve_method(self, xp, n=100):
# this types data structure was manually encoded instead of
# using custom filters on the soon-to-be-removed np.sctypes
types = {'uint16', 'uint64', 'int64', 'int32',
'complex128', 'float64', 'float16',
'complex64', 'float32', 'int16',
'uint8', 'uint32', 'int8', 'bool'}
args = [(t1, t2, mode) for t1 in types for t2 in types
for mode in ['valid', 'full', 'same']]
# These are random arrays, which means test is much stronger than
# convolving testing by convolving two np.ones arrays
rng = np.random.RandomState(42)
array_types = {'i': rng.choice([0, 1], size=n),
'f': rng.randn(n)}
array_types['b'] = array_types['u'] = array_types['i']
array_types['c'] = array_types['f'] + 0.5j*array_types['f']
for t1, t2, mode in args:
x1 = array_types[np.dtype(t1).kind].astype(t1)
x2 = array_types[np.dtype(t2).kind].astype(t2)
results = {key: convolve(x1, x2, method=key, mode=mode)
for key in ['fft', 'direct']}
assert results['fft'].dtype == results['direct'].dtype
if 'bool' in t1 and 'bool' in t2:
assert choose_conv_method(x1, x2) == 'direct'
continue
# Found by experiment. Found approx smallest value for (rtol, atol)
# threshold to have tests pass.
if any([t in {'complex64', 'float32'} for t in [t1, t2]]):
kwargs = {'rtol': 1.0e-4, 'atol': 1e-6}
elif 'float16' in [t1, t2]:
# atol is default for np.allclose
kwargs = {'rtol': 1e-3, 'atol': 1e-3}
else:
# defaults for np.allclose (different from assert_allclose)
kwargs = {'rtol': 1e-5, 'atol': 1e-8}
xp_assert_close(results['fft'], results['direct'], **kwargs)
@skip_xp_backends("jax.numpy", reason="dtypes do not match")
def test_convolve_method_large_input(self, xp):
# This is really a test that convolving two large integers goes to the
# direct method even if they're in the fft method.
for n in [10, 20, 50, 51, 52, 53, 54, 60, 62]:
z = xp.asarray([2**n], dtype=xp.int64)
fft = convolve(z, z, method='fft')
direct = convolve(z, z, method='direct')
# this is the case when integer precision gets to us
# issue #6076 has more detail, hopefully more tests after resolved
# # XXX: revisit check_dtype under np 2.0: 32bit linux & windows
if n < 50:
val = xp.asarray([2**(2*n)])
xp_assert_equal(fft, direct)
xp_assert_equal(fft, val, check_dtype=False)
xp_assert_equal(direct, val, check_dtype=False)
@skip_xp_backends(np_only=True)
def test_mismatched_dims(self, xp):
# Input arrays should have the same number of dimensions
assert_raises(ValueError, convolve, [1], 2, method='direct')
assert_raises(ValueError, convolve, 1, [2], method='direct')
assert_raises(ValueError, convolve, [1], 2, method='fft')
assert_raises(ValueError, convolve, 1, [2], method='fft')
assert_raises(ValueError, convolve, [1], [[2]])
assert_raises(ValueError, convolve, [3], 2)
@make_xp_test_case(convolve2d)
| TestConvolve |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-agent-search-retriever/llama_index/packs/agent_search_retriever/base.py | {
"start": 309,
"end": 396
} | class ____(str, Enum):
BING = "bing"
AGENT_SEARCH = "agent-search"
| SearchProvider |
python | catalyst-team__catalyst | tests/catalyst/runners/test_runner.py | {
"start": 315,
"end": 5353
} | class ____(Dataset):
"""
Dummy dataset.
"""
features_dim: int = 4
out_dim: int = 1
def __len__(self):
"""
Returns:
dataset's length.
"""
return 4
def __getitem__(self, idx: int) -> Tuple[Tensor, Tensor]:
"""
Args:
idx: index of sample
Returns:
dummy features and targets vector
"""
x = torch.ones(self.features_dim, dtype=torch.float)
y = torch.ones(self.out_dim, dtype=torch.float)
return x, y
def run_train_with_empty_loader() -> None:
"""
In this function we push loader to be empty because we
use batch_size > len(dataset) and drop_last=True.
"""
dataset = DummyDataset()
model = nn.Linear(in_features=dataset.features_dim, out_features=dataset.out_dim)
loader = DataLoader(dataset=dataset, batch_size=len(dataset) + 1, drop_last=True)
runner = SupervisedRunner()
runner.train(
loaders={"train": loader},
model=model,
num_epochs=1,
criterion=nn.BCEWithLogitsLoss(),
)
def test_cathing_empty_loader() -> None:
"""
We expect a error because loader is empty.
"""
try:
run_train_with_empty_loader()
except IRunnerError:
pass
def test_evaluation_loader_metrics() -> None:
"""
Test if metrics in evaluate loader works properly.
"""
dataset = DummyDataset()
model = nn.Linear(in_features=dataset.features_dim, out_features=dataset.out_dim)
loader = DataLoader(dataset=dataset, batch_size=1)
callbacks = [
dl.AccuracyCallback(input_key="logits", target_key="targets", topk=(1,))
]
runner = SupervisedRunner()
runner.train(
loaders={"train": loader, "valid": loader},
model=model,
num_epochs=1,
criterion=nn.BCEWithLogitsLoss(),
callbacks=callbacks,
)
runner_internal_metrics = runner.loader_metrics
evaluate_loader_metrics = runner.evaluate_loader(loader=loader, callbacks=callbacks)
assert runner_internal_metrics["accuracy01"] == evaluate_loader_metrics["accuracy01"]
def test_evaluation_loader_empty_model() -> None:
"""
Test if there is no model was given, assertion raises.
"""
with pytest.raises(AssertionError) as record:
dataset = DummyDataset()
loader = DataLoader(dataset=dataset, batch_size=1)
callbacks = [
dl.AccuracyCallback(input_key="logits", target_key="targets", topk=(1,))
]
runner = SupervisedRunner()
runner.evaluate_loader(loader=loader, callbacks=callbacks, model=None)
if not record:
pytest.fail("Expected assertion bacuase model is empty!")
def test_evaluation_loader_custom_model() -> None:
"""
Test if evaluate loader works with custom model.
"""
dataset = DummyDataset()
model = nn.Linear(in_features=dataset.features_dim, out_features=dataset.out_dim)
loader = DataLoader(dataset=dataset, batch_size=1)
callbacks = [
dl.AccuracyCallback(input_key="logits", target_key="targets", topk=(1,))
]
runner = SupervisedRunner()
runner.evaluate_loader(loader=loader, callbacks=callbacks, model=model)
def test_epoch_increasing():
class IncreaseCheckerCallback(Callback):
def __init__(self, attribute: str, start_value: int = None):
super().__init__(CallbackOrder.Internal)
self.attr = attribute
self.prev = start_value
def on_epoch_start(self, runner):
if not hasattr(runner, self.attr):
raise ValueError(f"There is no {self.attr} in runner!")
value = getattr(runner, self.attr)
if self.prev is not None:
# print(
# f">>> '{self.attr}': "
# f"previous - {self.prev}, "
# f"current - {value}"
# )
assert self.prev < value
self.prev = value
# experiment_setup
logdir = "./logs/core_runner"
# data
num_samples, num_features = int(1e4), int(1e1)
X = torch.rand(num_samples, num_features)
y = torch.randint(0, 5, size=[num_samples])
dataset = TensorDataset(X, y)
loader = DataLoader(dataset, batch_size=32, num_workers=1)
loaders = {"train": loader, "valid": loader}
# model, criterion, optimizer, scheduler
model = torch.nn.Linear(num_features, 5)
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters())
runner = SupervisedRunner()
callbacks = [
IncreaseCheckerCallback("epoch_step"),
IncreaseCheckerCallback("batch_step"),
IncreaseCheckerCallback("sample_step"),
]
runner.train(
model=model,
criterion=criterion,
optimizer=optimizer,
loaders=loaders,
logdir=logdir,
num_epochs=2,
verbose=False,
callbacks=callbacks,
)
shutil.rmtree(logdir, ignore_errors=True)
| DummyDataset |
python | openai__openai-python | src/openai/types/vector_store.py | {
"start": 979,
"end": 2470
} | class ____(BaseModel):
id: str
"""The identifier, which can be referenced in API endpoints."""
created_at: int
"""The Unix timestamp (in seconds) for when the vector store was created."""
file_counts: FileCounts
last_active_at: Optional[int] = None
"""The Unix timestamp (in seconds) for when the vector store was last active."""
metadata: Optional[Metadata] = None
"""Set of 16 key-value pairs that can be attached to an object.
This can be useful for storing additional information about the object in a
structured format, and querying for objects via API or the dashboard.
Keys are strings with a maximum length of 64 characters. Values are strings with
a maximum length of 512 characters.
"""
name: str
"""The name of the vector store."""
object: Literal["vector_store"]
"""The object type, which is always `vector_store`."""
status: Literal["expired", "in_progress", "completed"]
"""
The status of the vector store, which can be either `expired`, `in_progress`, or
`completed`. A status of `completed` indicates that the vector store is ready
for use.
"""
usage_bytes: int
"""The total number of bytes used by the files in the vector store."""
expires_after: Optional[ExpiresAfter] = None
"""The expiration policy for a vector store."""
expires_at: Optional[int] = None
"""The Unix timestamp (in seconds) for when the vector store will expire."""
| VectorStore |
python | kamyu104__LeetCode-Solutions | Python/find-longest-special-substring-that-occurs-thrice-i.py | {
"start": 774,
"end": 1366
} | class ____(object):
def maximumLength(self, s):
"""
:type s: str
:rtype: int
"""
lookup = [[0] for _ in xrange(26)]
result = 0
for i, c in enumerate(s):
curr = lookup[ord(c)-ord('a')]
for j in xrange(i, len(s)):
if s[j] != s[i]:
break
if j-i+1 == len(curr):
curr.append(0)
curr[j-i+1] += 1
if curr[j-i+1] == 3:
result = max(result, j-i+1)
return result if result else -1
| Solution2 |
python | eth-brownie__brownie | brownie/network/event.py | {
"start": 12542,
"end": 23550
} | class ____(metaclass=_Singleton):
"""
Singleton class containing methods to set callbacks on user-specified events.
This class is multi-threaded :
- The main thread (original process) activates a sub-thread and can be used
to add callback instructions on specific events.
- The sub-thread looks for new events among the ones with a callback set.
When found, calls a method that creates new threads to run the callback
instructions with the event(s) data as a parameter.
"""
def __init__(self) -> None:
self.target_list_lock: Lock = Lock()
self.target_events_watch_data: Dict[str, _EventWatchData] = {}
self._kill: bool = False
self._has_started: bool = False
self._watcher_thread = Thread(target=self._loop, daemon=True)
def __del__(self) -> None:
self.stop()
def stop(self, wait: bool = True) -> None:
"""
Stops the running threads. This function does not reset the instance
to its initial state. If that is your goal, check the 'reset' method.
Args:
wait (bool, optional): Whether to wait for thread to join within the function.
Defaults to True.
"""
self._kill = True
if wait is True and self._watcher_thread.is_alive():
self._watcher_thread.join()
self._has_started = False
def reset(self) -> None:
"""Stops the running threads and reset the instance to its initial state"""
self.stop()
self._setup()
def add_event_callback(
self,
event: ContractEvent,
callback: Callable[[AttributeDict], None],
delay: float = 2.0,
repeat: bool = True,
) -> None:
"""
Adds a callback instruction for the specified event.
Args:
event (ContractEvent): The ContractEvent instance to watch for.
callback (Callable[[AttributeDict], None]): The function to be called
when a new 'event' is detected.
delay (float, optional): The delay between each check for new 'event'(s).
Defaults to 2.0.
repeat (bool, optional): Whether to repeat the callback or not (if False,
the callback will be called once only). Defaults to True.
Raises:
TypeError: Raises when the parameter 'callback' is not a callable object.
"""
if not callable(callback):
raise TypeError("Argument 'callback' argument must be a callable.")
delay = max(delay, 0.05)
self.target_list_lock.acquire() # lock
# Key referring to this specific event (event.address is the address
# of the contract to which the event is linked)
event_watch_data_key = f"{str(event.address)}+{event.event_name}"
if self.target_events_watch_data.get(event_watch_data_key) is None:
# If the _EventWatchData for 'event' does not exist, creates it.
self.target_events_watch_data[event_watch_data_key] = _EventWatchData(
event, callback, delay, repeat
)
else:
# Adds a new callback to the already existing _EventWatchData.
self.target_events_watch_data[event_watch_data_key].add_callback(callback, repeat)
if repeat is True:
# Updates the delay between each check calling the
# _EventWatchData.update_delay function
self.target_events_watch_data[event_watch_data_key].update_delay(delay)
self.target_list_lock.release() # unlock
# Start watch if not done
if self._has_started is False:
self._start_watch()
def _setup(self) -> None:
"""Sets up the EventWatcher instance member variables so it is ready to run"""
self.target_list_lock.acquire()
self.target_events_watch_data.clear()
self.target_list_lock.release()
self._kill = False
self._has_started = False
self._watcher_thread = Thread(target=self._loop, daemon=True)
def _start_watch(self) -> None:
"""Starts the thread running the _loop function"""
self._watcher_thread.start()
self._has_started = True
def _loop(self) -> None:
"""
Watches for new events. Whenever new events are detected, calls the
'_EventWatchData._trigger_callbacks' function to run the callbacks instructions
(in separate threads) on the detected events data.
"""
workers_list: List[Thread] = []
while not self._kill:
try:
sleep_time: float = 1.0 # Max sleep time.
self.target_list_lock.acquire() # lock
for _, elem in self.target_events_watch_data.items():
# If cooldown is not over :
# skip and store time left before next check if needed.
time_left = elem.time_left
if time_left > 0:
sleep_time = min(sleep_time, time_left)
continue
# Check for new events & execute callback async if some are found
latest_events = elem.get_new_events()
if len(latest_events) != 0:
workers_list += elem._trigger_callbacks(latest_events)
elem.reset_timer()
# after elem.reset_timer elem.time_left is approximately elem.delay
sleep_time = min(sleep_time, elem.time_left)
finally:
self.target_list_lock.release() # unlock
# Remove dead threads from the workers_list
workers_list = list(filter(lambda x: x.is_alive(), workers_list))
time.sleep(sleep_time)
# Join running threads when leaving function.
for worker_instance in workers_list:
worker_instance.join(timeout=30)
if worker_instance.is_alive():
worker_name = worker_instance.getName()
warnings.warn(
message=f"Callback execution ({worker_name}) could not be joined.",
category=RuntimeWarning,
)
def __get_path() -> Path:
return _get_data_folder().joinpath("topics.json")
def _get_topics(abi: List[ABIElement]) -> Dict[str, HexStr]:
topic_map = eth_event.get_topic_map(abi)
updated_topics = _topics.copy()
for key, value in topic_map.items():
if key not in updated_topics:
# new event topic
updated_topics[key] = value
elif value == updated_topics[key]:
# existing event topic, nothing has changed
continue
elif not any(i["indexed"] for i in updated_topics[key]["inputs"]):
# existing topic, but the old abi has no indexed events - keep the new one
updated_topics[key] = value
if updated_topics != _topics:
_topics.update(updated_topics)
with __get_path().open("w") as fp:
ujson_dump(updated_topics, fp, sort_keys=True, indent=2)
return {v["name"]: k for k, v in topic_map.items()}
def _add_deployment_topics(address: ChecksumAddress, abi: List[ABIElement]) -> None:
_deployment_topics[address] = eth_event.get_topic_map(abi)
def _decode_logs(
# Mapping is included so we don't break dependent lib ypricemagic with this change
logs: List[_EventItem] | List[Mapping[str, Any]],
contracts: Optional[Dict[ChecksumAddress, "Contract"]] = None,
) -> EventDict:
if not logs:
return EventDict()
idx = 0
events: List[DecodedEvent | NonDecodedEvent] = []
while True:
address: ChecksumAddress = logs[idx]["address"]
try:
new_idx = logs.index(
next(i for i in logs[idx:] if i["address"] != address) # type: ignore [misc]
)
log_slice = logs[idx:new_idx]
idx = new_idx
except StopIteration:
log_slice = logs[idx:]
topics_map = _deployment_topics.get(address, _topics)
for item in log_slice:
if contracts:
contract = contracts[address]
if contract is not None:
note = _decode_ds_note(item, contract)
if note is not None:
events.append(note)
continue
try:
events.extend(
eth_event.decode_logs([item], topics_map, allow_undecoded=True) # type: ignore [call-overload]
)
except EventError as exc:
warnings.warn(f"{address}: {exc}")
if log_slice[-1] == logs[-1]:
break
return EventDict(format_event(event) for event in events)
def _decode_ds_note(
log: _EventItem | Mapping[str, Any], contract: "Contract"
) -> Optional[DecodedEvent]:
# ds-note encodes function selector as the first topic
# TODO double check typing for `log` input
topic0 = log.topics[0]
selector, tail = topic0[:4], topic0[4:]
selector_hexstr = Selector(hexbytes_to_hexstring(selector))
if selector_hexstr not in contract.selectors or sum(tail):
return None
name = contract.selectors[selector_hexstr]
log_data = log.data
data = bytes.fromhex(log_data[2:]) if isinstance(log_data, str) else log_data
# data uses ABI encoding of [uint256, bytes] or [bytes] in different versions
# instead of trying them all, assume the payload starts from selector
try:
func, args = contract.decode_input(data[data.index(selector) :])
except ValueError:
return None
selector_hexstr = Selector(hexbytes_to_hexstring(selector))
inputs = contract.get_method_object(selector_hexstr).abi["inputs"]
return DecodedEvent(
name=name,
address=cast(ChecksumAddress, log.address),
decoded=True,
data=[
{"name": abi["name"], "type": abi["type"], "value": arg, "decoded": True}
for arg, abi in zip(args, inputs)
],
)
def _decode_trace(trace: Sequence[_TraceStep], initial_address: AnyAddress) -> EventDict:
if not trace:
return EventDict()
events = eth_event.decode_traceTransaction(
trace if type(trace) is list else list(trace),
_topics,
allow_undecoded=True,
initial_address=initial_address,
)
return EventDict(format_event(event) for event in events)
# dictionary of event topic ABIs specific to a single contract deployment
_deployment_topics: Final[DeploymentTopics] = {}
# EventWatcher program instance
event_watcher: Final = EventWatcher()
try:
with __get_path().open() as fp:
__topics = ujson_load(fp)
except (FileNotFoundError, JSONDecodeError):
__topics = None
# general event topic ABIs for decoding events on unknown contracts
_topics: Final[TopicMap] = __topics or {}
del __topics
| EventWatcher |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 56188,
"end": 56640
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("owner_id", "domain", "client_mutation_id")
owner_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="ownerId")
domain = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="domain")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| AddVerifiableDomainInput |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 262628,
"end": 267395
} | class ____(Response):
"""
Response of datasets.update_frames endpoint.
:param updated: Number of frames updated
:type updated: int
:param merged: Number of frames merged
:type merged: int
:param failed: Number of frames we failed to update
:type failed: int
:param errors: Failure details
:type errors: Sequence[dict]
:param ids: Updated frame IDs
:type ids: Sequence[str]
:param total_rois: Total number of ROIs updated
:type total_rois: int
"""
_service = "datasets"
_action = "update_frames"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"errors": {
"description": "Failure details",
"items": {
"additionalProperties": True,
"description": "Json object describing an update error",
"type": "object",
},
"type": ["array", "null"],
},
"failed": {
"description": "Number of frames we failed to update",
"type": ["integer", "null"],
},
"ids": {
"description": "Updated frame IDs",
"items": {"type": "string"},
"type": ["array", "null"],
},
"merged": {
"description": "Number of frames merged",
"type": ["integer", "null"],
},
"total_rois": {
"description": "Total number of ROIs updated",
"type": ["integer", "null"],
},
"updated": {
"description": "Number of frames updated",
"type": ["integer", "null"],
},
},
"type": "object",
}
def __init__(
self,
updated=None,
merged=None,
failed=None,
errors=None,
ids=None,
total_rois=None,
**kwargs
):
super(UpdateFramesResponse, self).__init__(**kwargs)
self.updated = updated
self.merged = merged
self.failed = failed
self.errors = errors
self.ids = ids
self.total_rois = total_rois
@schema_property("updated")
def updated(self):
return self._property_updated
@updated.setter
def updated(self, value):
if value is None:
self._property_updated = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "updated", six.integer_types)
self._property_updated = value
@schema_property("merged")
def merged(self):
return self._property_merged
@merged.setter
def merged(self, value):
if value is None:
self._property_merged = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "merged", six.integer_types)
self._property_merged = value
@schema_property("failed")
def failed(self):
return self._property_failed
@failed.setter
def failed(self, value):
if value is None:
self._property_failed = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "failed", six.integer_types)
self._property_failed = value
@schema_property("errors")
def errors(self):
return self._property_errors
@errors.setter
def errors(self, value):
if value is None:
self._property_errors = None
return
self.assert_isinstance(value, "errors", (list, tuple))
self.assert_isinstance(value, "errors", (dict,), is_array=True)
self._property_errors = value
@schema_property("ids")
def ids(self):
return self._property_ids
@ids.setter
def ids(self, value):
if value is None:
self._property_ids = None
return
self.assert_isinstance(value, "ids", (list, tuple))
self.assert_isinstance(value, "ids", six.string_types, is_array=True)
self._property_ids = value
@schema_property("total_rois")
def total_rois(self):
return self._property_total_rois
@total_rois.setter
def total_rois(self, value):
if value is None:
self._property_total_rois = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "total_rois", six.integer_types)
self._property_total_rois = value
| UpdateFramesResponse |
python | google__pytype | pytype/pytd/optimize_test.py | {
"start": 510,
"end": 20617
} | class ____(parser_test_base.ParserTest):
"""Test the visitors in optimize.py."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.loader = load_pytd.Loader(
config.Options.create(python_version=cls.python_version)
)
cls.builtins = cls.loader.builtins
cls.typing = cls.loader.typing
def ParseAndResolve(self, src):
ast = self.Parse(src)
return ast.Visit(visitors.LookupBuiltins(self.builtins))
def Optimize(self, ast, **kwargs):
return optimize.Optimize(ast, self.builtins, **kwargs)
def OptimizedString(self, data):
tree = self.Parse(data) if isinstance(data, str) else data
new_tree = self.Optimize(tree)
return pytd_utils.Print(new_tree)
def AssertOptimizeEquals(self, src, new_src):
self.AssertSourceEquals(self.OptimizedString(src), new_src)
def test_one_function(self):
src = pytd_src("""
def foo(a: int, c: bool) -> int:
raise AssertionError()
raise ValueError()
""")
self.AssertOptimizeEquals(src, src)
def test_function_duplicate(self):
src = pytd_src("""
def foo(a: int, c: bool) -> int:
raise AssertionError()
raise ValueError()
def foo(a: int, c: bool) -> int:
raise AssertionError()
raise ValueError()
""")
new_src = pytd_src("""
def foo(a: int, c: bool) -> int:
raise AssertionError()
raise ValueError()
""")
self.AssertOptimizeEquals(src, new_src)
def test_complex_function_duplicate(self):
src = pytd_src("""
def foo(a: Union[int, float], c: bool) -> list[int]:
raise IndexError()
def foo(a: str, c: str) -> str: ...
def foo(a: int, *args) -> Union[int, float]:
raise ValueError()
def foo(a: Union[int, float], c: bool) -> list[int]:
raise IndexError()
def foo(a: int, *args) -> Union[int, float]:
raise ValueError()
""")
new_src = pytd_src("""
def foo(a: float, c: bool) -> list[int]:
raise IndexError()
def foo(a: str, c: str) -> str: ...
def foo(a: int, *args) -> Union[int, float]:
raise ValueError()
""")
self.AssertOptimizeEquals(src, new_src)
def test_combine_returns(self):
src = pytd_src("""
def foo(a: int) -> int: ...
def foo(a: int) -> float: ...
""")
new_src = pytd_src("""
def foo(a: int) -> Union[int, float]: ...
""")
self.AssertOptimizeEquals(src, new_src)
def test_combine_redundant_returns(self):
src = pytd_src("""
def foo(a: int) -> int: ...
def foo(a: int) -> float: ...
def foo(a: int) -> Union[int, float]: ...
""")
new_src = pytd_src("""
def foo(a: int) -> Union[int, float]: ...
""")
self.AssertOptimizeEquals(src, new_src)
def test_combine_union_returns(self):
src = pytd_src("""
def foo(a: int) -> Union[int, float]: ...
def bar(a: str) -> str: ...
def foo(a: int) -> Union[str, bytes]: ...
""")
new_src = pytd_src("""
def foo(a: int) -> Union[int, float, str, bytes]: ...
def bar(a: str) -> str: ...
""")
self.AssertOptimizeEquals(src, new_src)
def test_combine_exceptions(self):
src = pytd_src("""
def foo(a: int) -> int:
raise ValueError()
def foo(a: int) -> int:
raise IndexError()
def foo(a: float) -> int:
raise IndexError()
def foo(a: int) -> int:
raise AttributeError()
""")
new_src = pytd_src("""
def foo(a: int) -> int:
raise ValueError()
raise IndexError()
raise AttributeError()
def foo(a: float) -> int:
raise IndexError()
""")
self.AssertOptimizeEquals(src, new_src)
def test_mixed_combine(self):
src = pytd_src("""
def foo(a: int) -> int:
raise ValueError()
def foo(a: int) -> float:
raise ValueError()
def foo(a: int) -> int:
raise IndexError()
""")
new_src = pytd_src("""
def foo(a: int) -> Union[int, float]:
raise ValueError()
raise IndexError()
""")
self.AssertOptimizeEquals(src, new_src)
def test_lossy(self):
# Lossy compression is hard to test, since we don't know to which degree
# "compressible" items will be compressed. This test only checks that
# non-compressible things stay the same.
src = pytd_src("""
def foo(a: int) -> float:
raise IndexError()
def foo(a: str) -> complex:
raise AssertionError()
""")
optimized = self.Optimize(self.Parse(src), lossy=True, use_abcs=False)
self.AssertSourceEquals(optimized, src)
@unittest.skip("Needs ABCs to be included in the builtins")
def test_abcs(self):
src = pytd_src("""
def foo(a: Union[int, float]) -> NoneType: ...
def foo(a: Union[int, complex, float]) -> NoneType: ...
""")
new_src = pytd_src("""
def foo(a: Real) -> NoneType: ...
def foo(a: Complex) -> NoneType: ...
""")
optimized = self.Optimize(self.Parse(src), lossy=True, use_abcs=True)
self.AssertSourceEquals(optimized, new_src)
def test_duplicates_in_unions(self):
src = pytd_src("""
def a(x: Union[int, float, complex]) -> bool: ...
def b(x: Union[int, float]) -> bool: ...
def c(x: Union[int, int, int]) -> bool: ...
def d(x: Union[int, int]) -> bool: ...
def e(x: Union[float, int, int, float]) -> bool: ...
def f(x: Union[float, int]) -> bool: ...
""")
new_src = pytd_src("""
def a(x) -> builtins.bool: ... # max_union=2 makes this object
def b(x: Union[builtins.int, builtins.float]) -> builtins.bool: ...
def c(x: builtins.int) -> builtins.bool: ...
def d(x: builtins.int) -> builtins.bool: ...
def e(x: Union[builtins.float, builtins.int]) -> builtins.bool: ...
def f(x: Union[builtins.float, builtins.int]) -> builtins.bool: ...
""")
ast = self.ParseAndResolve(src)
optimized = self.Optimize(ast, lossy=False, max_union=2)
self.AssertSourceEquals(optimized, new_src)
def test_simplify_unions(self):
src = pytd_src("""
from typing import Any
a = ... # type: Union[int, int]
b = ... # type: Union[int, Any]
c = ... # type: Union[int, int, float]
""")
new_src = pytd_src("""
from typing import Any
a = ... # type: int
b = ... # type: Any
c = ... # type: Union[int, float]
""")
self.AssertSourceEquals(
self.ApplyVisitorToString(src, optimize.SimplifyUnions()), new_src
)
def test_builtin_superclasses(self):
src = pytd_src("""
def f(x: Union[list, object], y: Union[complex, slice]) -> Union[int, bool]: ...
""")
expected = pytd_src("""
def f(x: builtins.object, y: builtins.object) -> builtins.int: ...
""")
hierarchy = self.builtins.Visit(visitors.ExtractSuperClassesByName())
hierarchy.update(self.typing.Visit(visitors.ExtractSuperClassesByName()))
visitor = optimize.FindCommonSuperClasses(
optimize.SuperClassHierarchy(hierarchy)
)
ast = self.ParseAndResolve(src)
ast = ast.Visit(visitor)
ast = ast.Visit(visitors.CanonicalOrderingVisitor())
self.AssertSourceEquals(ast, expected)
def test_user_superclass_hierarchy(self):
class_data = pytd_src("""
class AB:
pass
class EFG:
pass
class A(AB, EFG):
pass
class B(AB):
pass
class E(EFG, AB):
pass
class F(EFG):
pass
class G(EFG):
pass
""")
src = pytd_src("""
from typing import Any
def f(x: Union[A, B], y: A, z: B) -> Union[E, F, G]: ...
def g(x: Union[E, F, G, B]) -> Union[E, F]: ...
def h(x) -> Any: ...
""") + class_data
expected = pytd_src("""
from typing import Any
def f(x: AB, y: A, z: B) -> EFG: ...
def g(x: object) -> EFG: ...
def h(x) -> Any: ...
""") + class_data
hierarchy = self.Parse(src).Visit(visitors.ExtractSuperClassesByName())
visitor = optimize.FindCommonSuperClasses(
optimize.SuperClassHierarchy(hierarchy)
)
new_src = self.ApplyVisitorToString(src, visitor)
self.AssertSourceEquals(new_src, expected)
def test_find_common_superclasses(self):
src = pytd_src("""
x = ... # type: Union[int, other.Bar]
""")
expected = pytd_src("""
x = ... # type: Union[int, other.Bar]
""")
ast = self.Parse(src)
ast = ast.Visit(
visitors.ReplaceTypesByName({"other.Bar": pytd.LateType("other.Bar")})
)
hierarchy = ast.Visit(visitors.ExtractSuperClassesByName())
ast = ast.Visit(
optimize.FindCommonSuperClasses(optimize.SuperClassHierarchy(hierarchy))
)
ast = ast.Visit(visitors.LateTypeToClassType())
self.AssertSourceEquals(ast, expected)
def test_simplify_unions_with_superclasses(self):
src = pytd_src("""
x = ... # type: Union[int, bool]
y = ... # type: Union[int, bool, float]
z = ... # type: Union[list[int], int]
""")
expected = pytd_src("""
x = ... # type: int
y = ... # type: Union[int, float]
z = ... # type: Union[list[int], int]
""")
hierarchy = self.builtins.Visit(visitors.ExtractSuperClassesByName())
visitor = optimize.SimplifyUnionsWithSuperclasses(
optimize.SuperClassHierarchy(hierarchy)
)
ast = self.Parse(src)
ast = visitors.LookupClasses(ast, self.builtins)
ast = ast.Visit(visitor)
self.AssertSourceEquals(ast, expected)
@unittest.skip("Needs better handling of GenericType")
def test_simplify_unions_with_superclasses_generic(self):
src = pytd_src("""
x = ... # type: Union[frozenset[int], AbstractSet[int]]
""")
expected = pytd_src("""
x = ... # type: AbstractSet[int]
""")
hierarchy = self.builtins.Visit(visitors.ExtractSuperClassesByName())
visitor = optimize.SimplifyUnionsWithSuperclasses(
optimize.SuperClassHierarchy(hierarchy)
)
ast = self.Parse(src)
ast = visitors.LookupClasses(ast, self.builtins)
ast = ast.Visit(visitor)
self.AssertSourceEquals(ast, expected)
def test_collapse_long_unions(self):
src = pytd_src("""
from typing import Any
def f(x: Union[A, B, C, D]) -> X: ...
def g(x: Union[A, B, C, D, E]) -> X: ...
def h(x: Union[A, Any]) -> X: ...
""")
expected = pytd_src("""
def f(x: Union[A, B, C, D]) -> X: ...
def g(x) -> X: ...
def h(x) -> X: ...
""")
ast = self.ParseAndResolve(src)
ast = ast.Visit(optimize.CollapseLongUnions(max_length=4))
self.AssertSourceEquals(ast, expected)
def test_collapse_long_constant_unions(self):
src = pytd_src("""
x = ... # type: Union[A, B, C, D]
y = ... # type: Union[A, B, C, D, E]
""")
expected = pytd_src("""
from typing import Any
x = ... # type: Union[A, B, C, D]
y = ... # type: Any
""")
ast = self.ParseAndResolve(src)
ast = ast.Visit(optimize.CollapseLongUnions(max_length=4))
ast = ast.Visit(optimize.AdjustReturnAndConstantGenericType())
self.AssertSourceEquals(ast, expected)
def test_combine_containers(self):
src = pytd_src("""
from typing import Any
def f(x: Union[list[int], list[float]]) -> Any: ...
def g(x: Union[list[int], str, list[float], set[int], long]) -> Any: ...
def h(x: Union[list[int], list[str], set[int], set[float]]) -> Any: ...
def i(x: Union[list[int], list[int]]) -> Any: ...
def j(x: Union[dict[int, float], dict[float, int]]) -> Any: ...
def k(x: Union[dict[int, bool], list[int], dict[bool, int], list[bool]]) -> Any: ...
""")
expected = pytd_src("""
from typing import Any
def f(x: list[float]) -> Any: ...
def g(x: Union[list[float], str, set[int], long]) -> Any: ...
def h(x: Union[list[Union[int, str]], set[float]]) -> Any: ...
def i(x: list[int]) -> Any: ...
def j(x: dict[float, float]) -> Any: ...
def k(x: Union[dict[Union[int, bool], Union[bool, int]], list[Union[int, bool]]]) -> Any: ...
""")
new_src = self.ApplyVisitorToString(src, optimize.CombineContainers())
self.AssertSourceEquals(new_src, expected)
def test_combine_containers_multi_level(self):
src = pytd_src("""
v = ... # type: Union[list[tuple[Union[long, int], ...]], list[tuple[Union[float, bool], ...]]]
""")
expected = pytd_src("""
v = ... # type: list[tuple[Union[long, int, float, bool], ...]]
""")
new_src = self.ApplyVisitorToString(src, optimize.CombineContainers())
self.AssertSourceEquals(new_src, expected)
def test_combine_same_length_tuples(self):
src = pytd_src("""
x = ... # type: Union[tuple[int], tuple[str]]
""")
expected = pytd_src("""
x = ... # type: tuple[Union[int, str]]
""")
new_src = self.ApplyVisitorToString(src, optimize.CombineContainers())
self.AssertSourceEquals(new_src, expected)
def test_combine_different_length_tuples(self):
src = pytd_src("""
x = ... # type: Union[tuple[int], tuple[int, str]]
""")
expected = pytd_src("""
x = ... # type: tuple[Union[int, str], ...]
""")
new_src = self.ApplyVisitorToString(src, optimize.CombineContainers())
self.AssertSourceEquals(new_src, expected)
def test_combine_different_length_callables(self):
src = pytd_src("""
from typing import Callable
x = ... # type: Union[Callable[[int], str], Callable[[int, int], str]]
""")
expected = pytd_src("""
from typing import Callable
x = ... # type: Callable[..., str]
""")
new_src = self.ApplyVisitorToString(src, optimize.CombineContainers())
self.AssertSourceEquals(new_src, expected)
def test_pull_in_method_classes(self):
src = pytd_src("""
from typing import Any
class A:
mymethod1 = ... # type: Method1
mymethod2 = ... # type: Method2
member = ... # type: Method3
mymethod4 = ... # type: Method4
class Method1:
def __call__(self: A, x: int) -> Any: ...
class Method2:
def __call__(self: object, x: int) -> Any: ...
class Method3:
def __call__(x: bool, y: int) -> Any: ...
class Method4:
def __call__(self: Any) -> Any: ...
class B(Method4):
pass
""")
expected = pytd_src("""
from typing import Any
class A:
member = ... # type: Method3
def mymethod1(self, x: int) -> Any: ...
def mymethod2(self, x: int) -> Any: ...
def mymethod4(self) -> Any: ...
class Method3:
def __call__(x: bool, y: int) -> Any: ...
class Method4:
def __call__(self) -> Any: ...
class B(Method4):
pass
""")
new_src = self.ApplyVisitorToString(src, optimize.PullInMethodClasses())
self.AssertSourceEquals(new_src, expected)
def test_add_inherited_methods(self):
src = pytd_src("""
from typing import Any
class A():
foo = ... # type: bool
def f(self, x: int) -> float: ...
def h(self) -> complex: ...
class B(A):
bar = ... # type: int
def g(self, y: int) -> bool: ...
def h(self, z: float) -> Any: ...
""")
ast = self.Parse(src)
ast = visitors.LookupClasses(ast, self.builtins)
self.assertCountEqual(("g", "h"), [m.name for m in ast.Lookup("B").methods])
ast = ast.Visit(optimize.AddInheritedMethods())
self.assertCountEqual(
("f", "g", "h"), [m.name for m in ast.Lookup("B").methods]
)
def test_adjust_inherited_method_self(self):
src = pytd_src("""
class A():
def f(self: object) -> float: ...
class B(A):
pass
""")
ast = self.Parse(src)
ast = visitors.LookupClasses(ast, self.builtins)
ast = ast.Visit(optimize.AddInheritedMethods())
self.assertMultiLineEqual(
pytd_utils.Print(ast.Lookup("B")),
pytd_src("""
class B(A):
def f(self) -> float: ...
""").lstrip(),
)
def test_absorb_mutable_parameters(self):
src = pytd_src("""
from typing import Any
def popall(x: list[Any]) -> Any:
x = list[nothing]
def add_float(x: list[int]) -> Any:
x = list[Union[int, float]]
def f(x: list[int]) -> Any:
x = list[Union[int, float]]
""")
expected = pytd_src("""
from typing import Any
def popall(x: list[Any]) -> Any: ...
def add_float(x: list[Union[int, float]]) -> Any: ...
def f(x: list[Union[int, float]]) -> Any: ...
""")
tree = self.Parse(src)
new_tree = tree.Visit(optimize.AbsorbMutableParameters())
new_tree = new_tree.Visit(optimize.CombineContainers())
self.AssertSourceEquals(new_tree, expected)
def test_absorb_mutable_parameters_from_methods(self):
# This is a test for intermediate data. See AbsorbMutableParameters class
# pydoc about how AbsorbMutableParameters works on methods.
src = pytd_src("""
from typing import Any
T = TypeVar('T')
NEW = TypeVar('NEW')
class MyClass(typing.Generic[T], object):
def append(self, x: NEW) -> Any:
self = MyClass[Union[T, NEW]]
""")
tree = self.Parse(src)
new_tree = tree.Visit(optimize.AbsorbMutableParameters())
new_tree = new_tree.Visit(optimize.CombineContainers())
self_type = (
new_tree.Lookup("MyClass").Lookup("append").signatures[0].params[0].type
)
self.assertEqual(pytd_utils.Print(self_type), "MyClass[Union[T, NEW]]")
def test_merge_type_parameters(self):
# This test uses pytd of the kind that's typically the output of
# AbsorbMutableParameters.
# See comment in RemoveMutableParameters
src = pytd_src("""
from typing import Any
T = TypeVar('T')
T2 = TypeVar('T2')
T3 = TypeVar('T3')
class A(typing.Generic[T], object):
def foo(self, x: Union[T, T2]) -> T2: ...
def bar(self, x: Union[T, T2, T3]) -> T3: ...
def baz(self, x: Union[T, T2], y: Union[T2, T3]) -> Any: ...
K = TypeVar('K')
V = TypeVar('V')
class D(typing.Generic[K, V], object):
def foo(self, x: T) -> Union[K, T]: ...
def bar(self, x: T) -> Union[V, T]: ...
def baz(self, x: Union[K, V]) -> Union[K, V]: ...
def lorem(self, x: T) -> Union[T, K, V]: ...
def ipsum(self, x: T) -> Union[T, K]: ...
""")
expected = pytd_src("""
from typing import Any
T = TypeVar('T')
T2 = TypeVar('T2')
T3 = TypeVar('T3')
class A(typing.Generic[T], object):
def foo(self, x: T) -> T: ...
def bar(self, x: T) -> T: ...
def baz(self, x: T, y: T) -> Any: ...
K = TypeVar('K')
V = TypeVar('V')
class D(typing.Generic[K, V], object):
def foo(self, x: K) -> K: ...
def bar(self, x: V) -> V: ...
def baz(self, x: Union[K, V]) -> Union[K, V]: ...
def lorem(self, x: Union[K, V]) -> Union[K, V]: ...
def ipsum(self, x: K) -> K: ...
""")
tree = self.Parse(src)
new_tree = tree.Visit(optimize.MergeTypeParameters())
self.AssertSourceEquals(new_tree, expected)
def test_overloads_not_flattened(self):
# This test checks that @overloaded functions are not flattened into a
# single signature.
src = pytd_src("""
from typing import overload
@overload
def f(x: int) -> str: ...
@overload
def f(x: str) -> str: ...
""")
self.AssertOptimizeEquals(src, src)
if __name__ == "__main__":
unittest.main()
| TestOptimize |
python | scikit-learn__scikit-learn | sklearn/tests/test_pipeline.py | {
"start": 2773,
"end": 2866
} | class ____(TransformerMixin, NoTrans):
def transform(self, X):
return X
| NoInvTransf |
python | dagster-io__dagster | python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py | {
"start": 20771,
"end": 25012
} | class ____(ColumnConstraintWithMetadata):
"""This class is useful for constructing more complicated relationships between columns
and expectations -- i.e. you want some validations on column A, others on column B, etc.
This lets you package up the metadata neatly, and also allows for cases like 'fail if any one of
these constraints fails but still run all of them'.
Args:
description (str): description of the overall set of validations
fn_and_columns_dict (Dict[str, List[Callable[[Any], Tuple[bool, dict[str, Union[dict,list, str, set]]]]]):
while this is a relatively complex type,
what it amounts to is 'a dict mapping columns to the functions to
run on them'
resulting_exception (type): the response to generate if validation fails. Subclass of
ConstraintWithMetadataException
raise_or_typecheck (Optional[bool]): whether to raise an exception (true) or a failed typecheck (false)
type_for_internal (Optional[type]): what type to use for internal validators. Subclass of
ConstraintWithMetadata
name (Optional[str]): what to call the constraint, defaults to the class name.
"""
def __init__(
self,
description,
fn_and_columns_dict,
resulting_exception,
raise_or_typecheck=True,
type_for_internal=ColumnConstraintWithMetadata,
name=None,
):
# TODO: support multiple descriptions
self.column_to_fn_dict = check.dict_param(
fn_and_columns_dict, "fn_and_columns_dict", key_type=str
)
def validation_fn(data, *args, **kwargs):
metadict = defaultdict(dict)
truthparam = True
for column, fn_arr in self.column_to_fn_dict.items():
if column not in data.columns:
continue
for fn in fn_arr:
# TODO: do this more effectively
new_validator = type_for_internal(
fn.__doc__, fn, ColumnWithMetadataException, raise_or_typecheck=False
)
result = new_validator.validate(
DataFrame(data[column]), column, *args, **kwargs
)
result_val = result.success # pyright: ignore[reportOptionalMemberAccess]
if result_val:
continue
result_dict = result.metadata[CONSTRAINT_METADATA_KEY].data # pyright: ignore[reportAttributeAccessIssue,reportOptionalMemberAccess]
truthparam = truthparam and result_val
for key in result_dict.keys():
if "constraint" not in key:
if key == "expected":
new_key = "expectation"
result_dict[key] = result_dict[key].replace("returns", "").strip()
if column not in metadict[new_key] or new_key not in metadict:
metadict[new_key][column] = dict()
metadict[new_key][column][fn.__name__] = result_dict[key]
else:
if column not in metadict[key] or key not in metadict:
metadict[key][column] = dict()
if isinstance(result_dict[key], dict):
metadict[key][column][fn.__name__] = result_dict[key][column]
else:
metadict[key][column][fn.__name__] = "a violation"
return truthparam, metadict
super().__init__(
description,
validation_fn,
resulting_exception,
raise_or_typecheck=raise_or_typecheck,
name=name,
)
def validate(self, data, *args, **kwargs):
return ConstraintWithMetadata.validate(self, data, *args, **kwargs)
@beta
| MultiColumnConstraintWithMetadata |
python | Textualize__textual | docs/examples/guide/screens/modes01.py | {
"start": 127,
"end": 269
} | class ____(Screen):
def compose(self) -> ComposeResult:
yield Placeholder("Dashboard Screen")
yield Footer()
| DashboardScreen |
python | scipy__scipy | benchmarks/benchmarks/fft_basic.py | {
"start": 2988,
"end": 3567
} | class ____(Benchmark):
params = [
[100, 256, 313, 512, 1000, 1024, 2048, 2048*2, 2048*4],
['scipy.fftpack', 'scipy.fft', 'numpy.fft']
]
param_names = ['size', 'module']
def setup(self, size, module):
self.x = random([size]).astype(double)
module = get_module(module)
self.rfft = getattr(module, 'rfft')
self.irfft = getattr(module, 'irfft')
self.y = self.rfft(self.x)
def time_rfft(self, size, module):
self.rfft(self.x)
def time_irfft(self, size, module):
self.irfft(self.y)
| RFft |
python | numba__numba | numba/tests/test_array_exprs.py | {
"start": 17641,
"end": 19182
} | class ____(MemoryLeakMixin, unittest.TestCase):
""" Tests the arrival and correct lowering of Optional types at a arrayexpr
derived ufunc, see #3972"""
def test_optional_scalar_type(self):
@njit
def arr_expr(x, y):
return x + y
@njit
def do_call(x, y):
if y > 0:
z = None
else:
z = y
return arr_expr(x, z)
args = (np.arange(5), -1.2)
# check result
res = do_call(*args)
expected = do_call.py_func(*args)
np.testing.assert_allclose(res, expected)
# check type
s = arr_expr.signatures
oty = s[0][1]
self.assertTrue(isinstance(oty, types.Optional))
self.assertTrue(isinstance(oty.type, types.Float))
def test_optional_array_type(self):
@njit
def arr_expr(x, y):
return x + y
@njit
def do_call(x, y):
if y[0] > 0:
z = None
else:
z = y
return arr_expr(x, z)
args = (np.arange(5), np.arange(5.))
# check result
res = do_call(*args)
expected = do_call.py_func(*args)
np.testing.assert_allclose(res, expected)
# check type
s = arr_expr.signatures
oty = s[0][1]
self.assertTrue(isinstance(oty, types.Optional))
self.assertTrue(isinstance(oty.type, types.Array))
self.assertTrue(isinstance(oty.type.dtype, types.Float))
| TestOptionals |
python | huggingface__transformers | src/transformers/models/deformable_detr/modeling_deformable_detr.py | {
"start": 79015,
"end": 88245
} | class ____(DeformableDetrPreTrainedModel):
# When using clones, all layers > 0 will be clones, but layer 0 *is* required
# We can't initialize the model on meta device as some weights are modified during the initialization
_no_split_modules = None
_tied_weights_keys = {
r"bbox_embed.(?![0])\d+": "bbox_embed.0",
r"class_embed.(?![0])\d+": "class_embed.0",
}
def __init__(self, config: DeformableDetrConfig):
super().__init__(config)
# Deformable DETR encoder-decoder model
self.model = DeformableDetrModel(config)
# Detection heads on top
# if two-stage, the last class_embed and bbox_embed is for region proposal generation
num_pred = (config.decoder_layers + 1) if config.two_stage else config.decoder_layers
self.class_embed = nn.ModuleList([nn.Linear(config.d_model, config.num_labels) for _ in range(num_pred)])
self.bbox_embed = nn.ModuleList(
[
DeformableDetrMLPPredictionHead(
input_dim=config.d_model,
hidden_dim=config.d_model,
output_dim=4,
num_layers=3,
)
for _ in range(num_pred)
]
)
if config.with_box_refine:
self.model.decoder.bbox_embed = self.bbox_embed
self._tied_weights_keys["model.decoder.bbox_embed"] = "bbox_embed"
if config.two_stage:
self.model.decoder.class_embed = self.class_embed
self._tied_weights_keys["model.decoder.class_embed"] = "class_embed"
self.post_init()
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
pixel_mask: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.FloatTensor] = None,
encoder_outputs: Optional[torch.FloatTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[list[dict]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple[torch.FloatTensor], DeformableDetrObjectDetectionOutput]:
r"""
decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
Not used by default. Can be used to mask object queries.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
can choose to directly pass a flattened representation of an image.
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
embedded representation.
labels (`list[Dict]` of len `(batch_size,)`, *optional*):
Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
Examples:
```python
>>> from transformers import AutoImageProcessor, DeformableDetrForObjectDetection
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
>>> model = DeformableDetrForObjectDetection.from_pretrained("SenseTime/deformable-detr")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
... 0
... ]
>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
... box = [round(i, 2) for i in box.tolist()]
... print(
... f"Detected {model.config.id2label[label.item()]} with confidence "
... f"{round(score.item(), 3)} at location {box}"
... )
Detected cat with confidence 0.8 at location [16.5, 52.84, 318.25, 470.78]
Detected cat with confidence 0.789 at location [342.19, 24.3, 640.02, 372.25]
Detected remote with confidence 0.633 at location [40.79, 72.78, 176.76, 117.25]
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# First, sent images through DETR base model to obtain encoder + decoder outputs
outputs = self.model(
pixel_values,
pixel_mask=pixel_mask,
decoder_attention_mask=decoder_attention_mask,
encoder_outputs=encoder_outputs,
inputs_embeds=inputs_embeds,
decoder_inputs_embeds=decoder_inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = outputs.intermediate_hidden_states if return_dict else outputs[2]
init_reference = outputs.init_reference_points if return_dict else outputs[0]
inter_references = outputs.intermediate_reference_points if return_dict else outputs[3]
# class logits + predicted bounding boxes
outputs_classes = []
outputs_coords = []
for level in range(hidden_states.shape[1]):
if level == 0:
reference = init_reference
else:
reference = inter_references[:, level - 1]
reference = inverse_sigmoid(reference)
outputs_class = self.class_embed[level](hidden_states[:, level])
delta_bbox = self.bbox_embed[level](hidden_states[:, level])
if reference.shape[-1] == 4:
outputs_coord_logits = delta_bbox + reference
elif reference.shape[-1] == 2:
delta_bbox[..., :2] += reference
outputs_coord_logits = delta_bbox
else:
raise ValueError(f"reference.shape[-1] should be 4 or 2, but got {reference.shape[-1]}")
outputs_coord = outputs_coord_logits.sigmoid()
outputs_classes.append(outputs_class)
outputs_coords.append(outputs_coord)
outputs_class = torch.stack(outputs_classes)
outputs_coord = torch.stack(outputs_coords)
logits = outputs_class[-1]
pred_boxes = outputs_coord[-1]
loss, loss_dict, auxiliary_outputs = None, None, None
if labels is not None:
loss, loss_dict, auxiliary_outputs = self.loss_function(
logits,
labels,
self.device,
pred_boxes,
self.config,
outputs_class,
outputs_coord,
)
if not return_dict:
if auxiliary_outputs is not None:
output = (logits, pred_boxes) + auxiliary_outputs + outputs
else:
output = (logits, pred_boxes) + outputs
tuple_outputs = ((loss, loss_dict) + output) if loss is not None else output
return tuple_outputs
dict_outputs = DeformableDetrObjectDetectionOutput(
loss=loss,
loss_dict=loss_dict,
logits=logits,
pred_boxes=pred_boxes,
auxiliary_outputs=auxiliary_outputs,
last_hidden_state=outputs.last_hidden_state,
decoder_hidden_states=outputs.decoder_hidden_states,
decoder_attentions=outputs.decoder_attentions,
cross_attentions=outputs.cross_attentions,
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
encoder_hidden_states=outputs.encoder_hidden_states,
encoder_attentions=outputs.encoder_attentions,
intermediate_hidden_states=outputs.intermediate_hidden_states,
intermediate_reference_points=outputs.intermediate_reference_points,
init_reference_points=outputs.init_reference_points,
enc_outputs_class=outputs.enc_outputs_class,
enc_outputs_coord_logits=outputs.enc_outputs_coord_logits,
)
return dict_outputs
__all__ = [
"DeformableDetrForObjectDetection",
"DeformableDetrModel",
"DeformableDetrPreTrainedModel",
]
| DeformableDetrForObjectDetection |
python | dask__dask | dask/tests/test_delayed.py | {
"start": 587,
"end": 3029
} | class ____:
__dask_scheduler__ = staticmethod(dask.threaded.get)
__dask_optimize__ = None
def __init__(self, dsk, keys):
self._dask = dsk
self._keys = keys
def __dask_tokenize__(self):
return self._keys
def __dask_graph__(self):
return self._dask
def __dask_keys__(self):
return self._keys
def __dask_postcompute__(self):
return tuple, ()
@pytest.mark.filterwarnings("ignore:The dask.delayed:UserWarning")
def test_to_task_dask():
a = delayed(1, name="a")
b = delayed(2, name="b")
task, dask = to_task_dask([a, b, 3])
assert task == ["a", "b", 3]
task, dask = to_task_dask((a, b, 3))
assert task == (tuple, ["a", "b", 3])
assert dict(dask) == merge(a.dask, b.dask)
task, dask = to_task_dask({a: 1, b: 2})
assert task == (dict, [["b", 2], ["a", 1]]) or task == (dict, [["a", 1], ["b", 2]])
assert dict(dask) == merge(a.dask, b.dask)
f = namedtuple("f", ["a", "b", "c"])
x = f(a, b, 3)
task, dask = to_task_dask(x)
assert task == (f, "a", "b", 3)
assert dict(dask) == merge(a.dask, b.dask)
task, dask = to_task_dask(slice(a, b, 3))
assert task == (slice, "a", "b", 3)
assert dict(dask) == merge(a.dask, b.dask)
# Issue https://github.com/dask/dask/issues/2107
class MyClass(dict):
pass
task, dask = to_task_dask(MyClass())
assert type(task) is MyClass
assert dict(dask) == {}
# Custom dask objects
x = Tuple({"a": 1, "b": 2, "c": (add, "a", "b")}, ["a", "b", "c"])
task, dask = to_task_dask(x)
assert task in dask
f = dask.pop(task)
assert f.func == tuple
assert f.dependencies == {"a", "b", "c"}
assert dask == x._dask
def test_delayed():
add2 = delayed(add)
assert add2(1, 2).compute() == 3
assert (add2(1, 2) + 3).compute() == 6
assert add2(add2(1, 2), 3).compute() == 6
a = delayed(1)
assert a.compute() == 1
b = add2(add2(a, 2), 3)
assert a.key in b.dask
def test_delayed_with_namedtuple():
class ANamedTuple(NamedTuple):
a: int # type: ignore[annotation-unchecked]
literal = dask.delayed(3)
with_class = dask.delayed({"a": ANamedTuple(a=literal)})
assert with_class.compute() == {"a": ANamedTuple(a=3)}
def return_nested(obj):
return obj["a"].a
final = delayed(return_nested)(with_class)
assert final.compute() == 3
@dataclass
| Tuple |
python | doocs__leetcode | solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/Solution2.py | {
"start": 0,
"end": 563
} | class ____:
def __init__(self, n):
self.p = list(range(n))
self.size = [1] * n
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a, b):
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
| UnionFind |
python | django__django | tests/db_functions/math/test_floor.py | {
"start": 270,
"end": 2344
} | class ____(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerModel.objects.annotate(null_floor=Floor("normal")).first()
self.assertIsNone(obj.null_floor)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("-12.9"), n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_floor=Floor("n1"), n2_floor=Floor("n2")
).first()
self.assertIsInstance(obj.n1_floor, Decimal)
self.assertIsInstance(obj.n2_floor, Decimal)
self.assertEqual(obj.n1_floor, Decimal(math.floor(obj.n1)))
self.assertEqual(obj.n2_floor, Decimal(math.floor(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=-27.5, f2=0.33)
obj = FloatModel.objects.annotate(
f1_floor=Floor("f1"), f2_floor=Floor("f2")
).first()
self.assertIsInstance(obj.f1_floor, float)
self.assertIsInstance(obj.f2_floor, float)
self.assertEqual(obj.f1_floor, math.floor(obj.f1))
self.assertEqual(obj.f2_floor, math.floor(obj.f2))
def test_integer(self):
IntegerModel.objects.create(small=-20, normal=15, big=-1)
obj = IntegerModel.objects.annotate(
small_floor=Floor("small"),
normal_floor=Floor("normal"),
big_floor=Floor("big"),
).first()
self.assertIsInstance(obj.small_floor, int)
self.assertIsInstance(obj.normal_floor, int)
self.assertIsInstance(obj.big_floor, int)
self.assertEqual(obj.small_floor, math.floor(obj.small))
self.assertEqual(obj.normal_floor, math.floor(obj.normal))
self.assertEqual(obj.big_floor, math.floor(obj.big))
def test_transform(self):
with register_lookup(DecimalField, Floor):
DecimalModel.objects.create(n1=Decimal("5.4"), n2=Decimal("0"))
DecimalModel.objects.create(n1=Decimal("3.4"), n2=Decimal("0"))
obj = DecimalModel.objects.filter(n1__floor__gt=4).get()
self.assertEqual(obj.n1, Decimal("5.4"))
| FloorTests |
python | sqlalchemy__sqlalchemy | test/orm/test_merge.py | {
"start": 63027,
"end": 64132
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"data",
metadata,
Column("pk1", String(10), primary_key=True),
Column("pk2", String(10), primary_key=True),
)
@classmethod
def setup_classes(cls):
class Data(cls.Basic):
pass
def test_merge_allow_partial(self):
Data, data = self.classes.Data, self.tables.data
self.mapper_registry.map_imperatively(Data, data)
sess = fixture_session()
d1 = Data(pk1="someval", pk2=None)
def go():
return sess.merge(d1)
self.assert_sql_count(testing.db, go, 1)
def test_merge_disallow_partial(self):
Data, data = self.classes.Data, self.tables.data
self.mapper_registry.map_imperatively(
Data, data, allow_partial_pks=False
)
sess = fixture_session()
d1 = Data(pk1="someval", pk2=None)
def go():
return sess.merge(d1)
self.assert_sql_count(testing.db, go, 0)
| CompositeNullPksTest |
python | astropy__astropy | astropy/utils/exceptions.py | {
"start": 708,
"end": 879
} | class ____(UserWarning, AstropyWarning):
"""
The primary warning class for Astropy.
Use this if you do not need a specific sub-class.
"""
| AstropyUserWarning |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/daemon_tests/test_queued_run_coordinator_daemon.py | {
"start": 1459,
"end": 62183
} | class ____(ABC):
@pytest.fixture
def run_coordinator_config(self):
return {}
@pytest.fixture
def concurrency_config(self):
return {}
@abstractmethod
@pytest.fixture()
def instance(self, run_coordinator_config):
raise NotImplementedError
@pytest.fixture(params=[1, 25])
def page_size(self, request):
yield request.param
@abstractmethod
@pytest.fixture()
def daemon(self, page_size):
raise NotImplementedError
@pytest.fixture()
def workspace_context(self, instance):
with create_test_daemon_workspace_context(
workspace_load_target=EmptyWorkspaceTarget(), instance=instance
) as workspace_context:
yield workspace_context
@pytest.fixture(scope="module")
def job_handle(self) -> Iterator[JobHandle]:
with get_foo_job_handle() as handle:
yield handle
@pytest.fixture()
def concurrency_limited_workspace_context(self, instance):
with create_test_daemon_workspace_context(
workspace_load_target=PythonFileTarget(
python_file=dg.file_relative_path(
__file__, "test_locations/concurrency_limited_workspace.py"
),
attribute=None,
working_directory=None,
location_name="test",
),
instance=instance,
) as workspace_context:
yield workspace_context
@pytest.fixture(scope="module")
def other_location_job_handle(self, job_handle: JobHandle) -> JobHandle:
code_location_origin = job_handle.repository_handle.code_location_origin
assert isinstance(code_location_origin, ManagedGrpcPythonEnvCodeLocationOrigin)
new_origin = code_location_origin._replace(location_name="other_location_name")
with dg.instance_for_test() as temp_instance:
with new_origin.create_single_location(temp_instance) as location:
new_repo_handle = RepositoryHandle.from_location(
job_handle.repository_name, location
)
return copy(
job_handle,
repository_handle=new_repo_handle,
)
def create_run(self, instance, job_handle, **kwargs):
create_run_for_test(
instance,
remote_job_origin=job_handle.get_remote_origin(),
job_code_origin=job_handle.get_python_origin(),
job_name="foo",
**kwargs,
)
def create_queued_run(self, instance, job_handle, **kwargs):
run = create_run_for_test(
instance,
remote_job_origin=job_handle.get_remote_origin(),
job_code_origin=job_handle.get_python_origin(),
job_name="foo",
status=DagsterRunStatus.NOT_STARTED,
**kwargs,
)
enqueued_event = DagsterEvent.job_enqueue(run)
instance.report_dagster_event(enqueued_event, run_id=run.run_id)
return instance.get_run_by_id(run.run_id)
def submit_run(
self,
instance: DagsterInstance,
remote_job: RemoteJob,
workspace: WorkspaceRequestContext,
**kwargs: Any,
):
location = workspace.get_code_location(remote_job.handle.location_name)
subset_job = location.get_job(
JobSubsetSelector(
location_name=location.name,
repository_name=remote_job.handle.repository_name,
job_name=remote_job.handle.job_name,
op_selection=None,
asset_selection=kwargs.get("asset_selection"),
)
)
execution_plan = location.get_execution_plan(
subset_job,
{},
step_keys_to_execute=None,
known_state=None,
instance=instance,
)
run = create_run_for_test(
instance,
remote_job_origin=subset_job.get_remote_origin(),
job_code_origin=subset_job.get_python_origin(),
job_name=subset_job.name,
execution_plan_snapshot=execution_plan.execution_plan_snapshot,
job_snapshot=subset_job.job_snapshot,
parent_job_snapshot=subset_job.parent_job_snapshot,
status=DagsterRunStatus.NOT_STARTED,
asset_graph=workspace.asset_graph,
**kwargs,
)
instance.submit_run(run.run_id, workspace)
return run
def get_run_ids(self, runs_queue):
return [run.run_id for run in runs_queue]
def get_concurrency_job(self, workspace):
return workspace.get_full_job(
JobSubsetSelector(
location_name="test",
repository_name="__repository__",
job_name="concurrency_limited_asset_job",
op_selection=None,
)
)
def test_attempt_to_launch_runs_filter(self, instance, workspace_context, daemon, job_handle):
queued_run_id, non_queued_run_id = [make_new_run_id() for _ in range(2)]
self.create_queued_run(
instance,
job_handle,
run_id=queued_run_id,
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_run(
instance,
job_handle,
run_id=non_queued_run_id,
status=DagsterRunStatus.NOT_STARTED,
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
assert self.get_run_ids(instance.run_launcher.queue()) == [queued_run_id]
def test_attempt_to_launch_runs_no_queued(
self, instance, job_handle, workspace_context, daemon
):
queued_run_id = make_new_run_id()
non_queued_run_id = make_new_run_id()
self.create_run(
instance,
job_handle,
run_id=queued_run_id,
status=DagsterRunStatus.STARTED,
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_run(
instance,
job_handle,
run_id=non_queued_run_id,
status=DagsterRunStatus.NOT_STARTED,
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
assert instance.run_launcher.queue() == []
@pytest.mark.parametrize(
"num_in_progress_runs",
[0, 1, 5],
)
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(max_concurrent_runs=4, dequeue_use_threads=True),
dict(max_concurrent_runs=4, dequeue_use_threads=False),
],
)
def test_get_queued_runs_max_runs(
self,
num_in_progress_runs,
job_handle,
workspace_context,
daemon,
run_coordinator_config,
instance,
):
max_runs = run_coordinator_config["max_concurrent_runs"]
# fill run store with ongoing runs
in_progress_run_ids = [make_new_run_id() for i in range(num_in_progress_runs)]
for i, run_id in enumerate(in_progress_run_ids):
# get a selection of all in progress statuses
status = IN_PROGRESS_RUN_STATUSES[i % len(IN_PROGRESS_RUN_STATUSES)]
self.create_run(
instance,
job_handle,
run_id=run_id,
status=status,
asset_graph=workspace_context.create_request_context().asset_graph,
)
# add more queued runs than should be launched
queued_run_ids = [make_new_run_id() for i in range(max_runs + 1)]
for run_id in queued_run_ids:
self.create_queued_run(
instance,
job_handle,
run_id=run_id,
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
assert len(instance.run_launcher.queue()) == max(0, max_runs - num_in_progress_runs)
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(max_concurrent_runs=-1, dequeue_use_threads=True),
dict(max_concurrent_runs=-1, dequeue_use_threads=False),
],
)
def test_disable_max_concurrent_runs_limit(
self, workspace_context, job_handle, daemon, instance
):
# create ongoing runs
in_progress_run_ids = [make_new_run_id() for i in range(5)]
for i, run_id in enumerate(in_progress_run_ids):
# get a selection of all in progress statuses
status = IN_PROGRESS_RUN_STATUSES[i % len(IN_PROGRESS_RUN_STATUSES)]
self.create_run(
instance,
job_handle,
run_id=run_id,
status=status,
asset_graph=workspace_context.create_request_context().asset_graph,
)
# add more queued runs
queued_run_ids = [make_new_run_id() for i in range(6)]
for run_id in queued_run_ids:
self.create_queued_run(
instance,
job_handle,
run_id=run_id,
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
assert len(instance.run_launcher.queue()) == 6
def test_priority(self, instance, workspace_context, job_handle, daemon):
default_run_id, hi_pri_run_id, lo_pri_run_id = [make_new_run_id() for _ in range(3)]
self.create_run(
instance,
job_handle,
run_id=default_run_id,
status=DagsterRunStatus.QUEUED,
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=lo_pri_run_id,
tags={PRIORITY_TAG: "-1"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=hi_pri_run_id,
tags={PRIORITY_TAG: "3"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
assert self.get_run_ids(instance.run_launcher.queue()) == [
hi_pri_run_id,
default_run_id,
lo_pri_run_id,
]
def test_priority_on_malformed_tag(self, instance, workspace_context, job_handle, daemon):
bad_pri_run_id = make_new_run_id()
self.create_queued_run(
instance,
job_handle,
run_id=bad_pri_run_id,
tags={PRIORITY_TAG: "foobar"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
assert self.get_run_ids(instance.run_launcher.queue()) == [bad_pri_run_id]
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[{"key": "database", "value": "tiny", "limit": 1}],
dequeue_use_threads=True,
),
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[{"key": "database", "value": "tiny", "limit": 1}],
dequeue_use_threads=False,
),
],
)
def test_tag_limits(self, workspace_context, job_handle, daemon, instance):
tiny_run_id, tiny_run_id_2, large_run_id = [make_new_run_id() for _ in range(3)]
self.create_queued_run(
instance,
job_handle,
run_id=tiny_run_id,
tags={"database": "tiny"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=tiny_run_id_2,
tags={"database": "tiny"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=large_run_id,
tags={"database": "large"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
# exact order non-deterministic due to threaded dequeue
assert set(self.get_run_ids(instance.run_launcher.queue())) == {tiny_run_id, large_run_id}
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "database", "value": {"applyLimitPerUniqueValue": False}, "limit": 2}
],
dequeue_use_threads=True,
),
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "database", "value": {"applyLimitPerUniqueValue": False}, "limit": 2}
],
dequeue_use_threads=False,
),
],
)
def test_tag_limits_just_key(self, workspace_context, job_handle, daemon, instance):
tiny_run_id, tiny_run_id_2, large_run_id = [make_new_run_id() for _ in range(3)]
self.create_queued_run(
instance,
job_handle,
run_id=tiny_run_id,
tags={"database": "tiny"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=tiny_run_id_2,
tags={"database": "tiny"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=large_run_id,
tags={"database": "large"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
# exact order non-deterministic due to threaded dequeue
assert set(self.get_run_ids(instance.run_launcher.queue())) == {tiny_run_id, tiny_run_id_2}
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "database", "value": "tiny", "limit": 1},
{"key": "user", "value": "johann", "limit": 2},
],
dequeue_use_threads=True,
),
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "database", "value": "tiny", "limit": 1},
{"key": "user", "value": "johann", "limit": 2},
],
dequeue_use_threads=False,
),
],
)
def test_multiple_tag_limits(
self,
workspace_context,
daemon,
job_handle,
instance,
):
run_id_1, run_id_2, run_id_3, run_id_4 = [make_new_run_id() for _ in range(4)]
self.create_queued_run(
instance,
job_handle,
run_id=run_id_1,
tags={"database": "tiny", "user": "johann"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_2,
tags={"database": "tiny"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_3,
tags={"user": "johann"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_4,
tags={"user": "johann"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
# exact order non-deterministic due to threaded dequeue
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_1, run_id_3}
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "foo", "limit": 2},
{"key": "foo", "value": "bar", "limit": 1},
],
dequeue_use_threads=True,
),
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "foo", "limit": 2},
{"key": "foo", "value": "bar", "limit": 1},
],
dequeue_use_threads=False,
),
],
)
def test_overlapping_tag_limits(self, workspace_context, daemon, job_handle, instance):
run_id_1, run_id_2, run_id_3, run_id_4 = [make_new_run_id() for _ in range(4)]
self.create_queued_run(
instance,
job_handle,
run_id=run_id_1,
tags={"foo": "bar"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_2,
tags={"foo": "bar"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_3,
tags={"foo": "other"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_4,
tags={"foo": "other"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
# exact order non-deterministic due to threaded dequeue
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_1, run_id_3}
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "foo", "limit": 1, "value": {"applyLimitPerUniqueValue": True}},
],
dequeue_use_threads=True,
),
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "foo", "limit": 1, "value": {"applyLimitPerUniqueValue": True}},
],
dequeue_use_threads=False,
),
],
)
def test_limits_per_unique_value(self, workspace_context, job_handle, daemon, instance):
run_id_1, run_id_2, run_id_3, run_id_4 = [make_new_run_id() for _ in range(4)]
self.create_queued_run(
instance,
job_handle,
run_id=run_id_1,
tags={"foo": "bar"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_2,
tags={"foo": "bar"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
self.create_queued_run(
instance,
job_handle,
run_id=run_id_3,
tags={"foo": "other"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_4,
tags={"foo": "other"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
# exact order non-deterministic due to threaded dequeue
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_1, run_id_3}
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "foo", "limit": 1, "value": {"applyLimitPerUniqueValue": True}},
{"key": "foo", "limit": 2},
],
dequeue_use_threads=True,
),
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "foo", "limit": 1, "value": {"applyLimitPerUniqueValue": True}},
{"key": "foo", "limit": 2},
],
dequeue_use_threads=False,
),
],
)
def test_limits_per_unique_value_overlapping_limits_less_than(
self,
workspace_context,
daemon,
job_handle,
instance,
):
run_id_1, run_id_2, run_id_3, run_id_4 = [make_new_run_id() for _ in range(4)]
self.create_queued_run(
instance,
job_handle,
run_id=run_id_1,
tags={"foo": "bar"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_2,
tags={"foo": "bar"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_3,
tags={"foo": "other"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_4,
tags={"foo": "other-2"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
# exact order non-deterministic due to threaded dequeue
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_1, run_id_3}
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "foo", "limit": 2, "value": {"applyLimitPerUniqueValue": True}},
{"key": "foo", "limit": 1, "value": "bar"},
],
dequeue_use_threads=True,
),
dict(
max_concurrent_runs=10,
tag_concurrency_limits=[
{"key": "foo", "limit": 2, "value": {"applyLimitPerUniqueValue": True}},
{"key": "foo", "limit": 1, "value": "bar"},
],
dequeue_use_threads=False,
),
],
)
def test_limits_per_unique_value_overlapping_limits_greater_than(
self,
workspace_context,
daemon,
job_handle,
instance,
):
run_id_1, run_id_2, run_id_3, run_id_4, run_id_5 = [make_new_run_id() for _ in range(5)]
self.create_queued_run(
instance,
job_handle,
run_id=run_id_1,
tags={"foo": "bar"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_2,
tags={"foo": "baz"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_3,
tags={"foo": "bar"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_4,
tags={"foo": "baz"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_5,
tags={"foo": "baz"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
# exact order non-deterministic due to threaded dequeue
assert set(self.get_run_ids(instance.run_launcher.queue())) == {
run_id_1,
run_id_2,
run_id_4,
}
def test_locations_not_created(
self, instance, monkeypatch, workspace_context, daemon, job_handle
):
"""Verifies that no repository location is created when runs are dequeued."""
queued_run_id_1, queued_run_id_2 = [make_new_run_id() for _ in range(2)]
self.create_queued_run(
instance,
job_handle,
run_id=queued_run_id_1,
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=queued_run_id_2,
asset_graph=workspace_context.create_request_context().asset_graph,
)
original_method = GrpcServerCodeLocation.__init__
method_calls = []
def mocked_location_init(
self,
origin,
host=None,
port=None,
socket=None,
heartbeat=False,
watch_server=True,
grpc_server_registry=None,
):
method_calls.append(origin)
return original_method(
self,
origin,
host, # pyright: ignore[reportArgumentType]
port,
socket,
heartbeat, # pyright: ignore[reportArgumentType]
watch_server,
grpc_server_registry,
)
monkeypatch.setattr(
GrpcServerCodeLocation,
"__init__",
mocked_location_init,
)
list(daemon.run_iteration(workspace_context))
assert self.get_run_ids(instance.run_launcher.queue()) == [queued_run_id_1, queued_run_id_2]
assert len(method_calls) == 0
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(max_concurrent_runs=10, dequeue_use_threads=True),
dict(max_concurrent_runs=10, dequeue_use_threads=False),
],
)
def test_skip_error_runs(self, job_handle, daemon, instance, workspace_context):
good_run_id = make_new_run_id()
self.create_queued_run(
instance,
job_handle,
run_id=BAD_RUN_ID_UUID,
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=good_run_id,
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=BAD_USER_CODE_RUN_ID_UUID,
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
assert self.get_run_ids(instance.run_launcher.queue()) == [good_run_id]
assert instance.get_run_by_id(BAD_RUN_ID_UUID).status == DagsterRunStatus.FAILURE
assert instance.get_run_by_id(BAD_USER_CODE_RUN_ID_UUID).status == DagsterRunStatus.FAILURE
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(max_user_code_failure_retries=2, max_concurrent_runs=10, dequeue_use_threads=True),
dict(
max_user_code_failure_retries=2, max_concurrent_runs=10, dequeue_use_threads=False
),
],
)
def test_retry_user_code_error_run(
self, job_handle, other_location_job_handle, daemon, instance, workspace_context
):
good_run_id, good_run_same_location_id, good_run_other_location_id = [
make_new_run_id() for _ in range(3)
]
fixed_iteration_time = time.time() - 3600 * 24 * 365
self.create_queued_run(
instance,
job_handle,
run_id=BAD_RUN_ID_UUID,
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=good_run_id,
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=BAD_USER_CODE_RUN_ID_UUID,
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context, fixed_iteration_time=fixed_iteration_time))
assert self.get_run_ids(instance.run_launcher.queue()) == [good_run_id]
assert instance.get_run_by_id(BAD_RUN_ID_UUID).status == DagsterRunStatus.FAILURE
# Run was put back into the queue due to the user code failure
assert instance.get_run_by_id(BAD_USER_CODE_RUN_ID_UUID).status == DagsterRunStatus.QUEUED
# Other runs in the same location are skipped
self.create_queued_run(
instance,
job_handle,
run_id=good_run_same_location_id,
tags={
"dagster/priority": "5",
},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
other_location_job_handle,
run_id=good_run_other_location_id,
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context, fixed_iteration_time=fixed_iteration_time))
assert self.get_run_ids(instance.run_launcher.queue()) == [
good_run_id,
good_run_other_location_id,
]
fixed_iteration_time = fixed_iteration_time + 10
# Add more runs, one in the same location, one in another location - the former is
# skipped, the other launches. The original failed run is also skipped
list(daemon.run_iteration(workspace_context, fixed_iteration_time=fixed_iteration_time))
assert instance.get_run_by_id(BAD_USER_CODE_RUN_ID_UUID).status == DagsterRunStatus.QUEUED
assert instance.get_run_by_id(good_run_same_location_id).status == DagsterRunStatus.QUEUED
fixed_iteration_time = fixed_iteration_time + 121
list(daemon.run_iteration(workspace_context, fixed_iteration_time=fixed_iteration_time))
assert instance.get_run_by_id(BAD_USER_CODE_RUN_ID_UUID).status == DagsterRunStatus.QUEUED
fixed_iteration_time = fixed_iteration_time + 121
# Gives up after max_user_code_failure_retries retries _ the good run from that
# location succeeds
list(daemon.run_iteration(workspace_context, fixed_iteration_time=fixed_iteration_time))
assert instance.get_run_by_id(BAD_USER_CODE_RUN_ID_UUID).status == DagsterRunStatus.FAILURE
fixed_iteration_time = fixed_iteration_time + 121
list(daemon.run_iteration(workspace_context, fixed_iteration_time=fixed_iteration_time))
# good run is now free to launch (since it is dequeud before the bad run due to), bad run does its second retry
assert self.get_run_ids(instance.run_launcher.queue()) == [
good_run_id,
good_run_other_location_id,
good_run_same_location_id,
]
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_user_code_failure_retries=1,
user_code_failure_retry_delay=5,
max_concurrent_runs=10,
dequeue_use_threads=True,
),
dict(
max_user_code_failure_retries=1,
user_code_failure_retry_delay=5,
max_concurrent_runs=10,
dequeue_use_threads=False,
),
],
)
def test_retry_user_code_error_recovers(self, job_handle, daemon, instance, workspace_context):
fixed_iteration_time = time.time() - 3600 * 24 * 365
self.create_queued_run(
instance,
job_handle,
run_id=BAD_USER_CODE_RUN_ID_UUID,
asset_graph=workspace_context.create_request_context().asset_graph,
)
# fails on initial dequeue
list(daemon.run_iteration(workspace_context, fixed_iteration_time=fixed_iteration_time))
assert instance.get_run_by_id(BAD_USER_CODE_RUN_ID_UUID).status == DagsterRunStatus.QUEUED
fixed_iteration_time = fixed_iteration_time + 6
# Passes on retry
instance.run_launcher.bad_user_code_run_ids = set()
list(daemon.run_iteration(workspace_context, fixed_iteration_time=fixed_iteration_time))
assert self.get_run_ids(instance.run_launcher.queue()) == [BAD_USER_CODE_RUN_ID_UUID]
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_concurrent_runs=2,
tag_concurrency_limits=[
{"key": "test", "limit": 1},
],
dequeue_use_threads=True,
),
dict(
max_concurrent_runs=2,
tag_concurrency_limits=[
{"key": "test", "limit": 1},
],
dequeue_use_threads=False,
),
],
)
def test_key_limit_with_extra_tags(self, workspace_context, daemon, job_handle, instance):
run_id_1 = make_new_run_id()
run_id_2 = make_new_run_id()
self.create_queued_run(
instance,
job_handle,
run_id=run_id_1,
tags={"other-tag": "value", "test": "value"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=run_id_2,
tags={"other-tag": "value", "test": "value"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
assert self.get_run_ids(instance.run_launcher.queue()) == [run_id_1]
@pytest.mark.parametrize(
"run_coordinator_config",
[
dict(
max_concurrent_runs=2,
tag_concurrency_limits=[
{"key": "test", "limit": 1},
],
dequeue_use_threads=True,
),
],
)
def test_key_limit_with_priority(
self, workspace_context, daemon, job_handle, instance, run_coordinator_config
):
lo_pri_run_id, hi_pri_run_id = [make_new_run_id() for _ in range(2)]
self.create_queued_run(
instance,
job_handle,
run_id=lo_pri_run_id,
tags={"test": "value", PRIORITY_TAG: "-100"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
self.create_queued_run(
instance,
job_handle,
run_id=hi_pri_run_id,
tags={"test": "value", PRIORITY_TAG: "100"},
asset_graph=workspace_context.create_request_context().asset_graph,
)
list(daemon.run_iteration(workspace_context))
assert self.get_run_ids(instance.run_launcher.queue()) == [hi_pri_run_id]
@pytest.mark.parametrize(
"run_coordinator_config",
[
{"block_op_concurrency_limited_runs": {"enabled": True}},
],
)
def test_op_concurrency_aware_dequeuing(
self,
concurrency_limited_workspace_context,
daemon,
instance,
caplog,
):
run_id_1, run_id_2, run_id_3 = [make_new_run_id() for _ in range(3)]
workspace = concurrency_limited_workspace_context.create_request_context()
remote_job = self.get_concurrency_job(workspace)
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
instance.event_log_storage.set_concurrency_slots("foo", 1)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
caplog.text.count("is blocked by global concurrency limits") == 0 # pyright: ignore[reportUnusedExpression]
self.submit_run(
instance, remote_job, workspace, run_id=run_id_2, asset_selection=set([foo_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_1}
caplog.text.count(f"Run {run_id_2} is blocked by global concurrency limits") == 1 # pyright: ignore[reportUnusedExpression]
self.submit_run(
instance, remote_job, workspace, run_id=run_id_3, asset_selection=set([foo_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_1}
# the log message only shows up once per run
caplog.text.count(f"Run {run_id_2} is blocked by global concurrency limits") == 1 # pyright: ignore[reportUnusedExpression]
caplog.text.count(f"Run {run_id_3} is blocked by global concurrency limits") == 1 # pyright: ignore[reportUnusedExpression]
# bumping up the slot by one means that one more run should get dequeued
instance.event_log_storage.set_concurrency_slots("foo", 2)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_1, run_id_2}
caplog.text.count(f"Run {run_id_2} is blocked by global concurrency limits") == 1 # pyright: ignore[reportUnusedExpression]
caplog.text.count(f"Run {run_id_3} is blocked by global concurrency limits") == 1 # pyright: ignore[reportUnusedExpression]
@pytest.mark.flaky(max_runs=2)
@pytest.mark.parametrize(
"run_coordinator_config",
[
{"block_op_concurrency_limited_runs": {"enabled": True}},
],
)
def test_op_concurrency_root_progress(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1, run_id_2 = [make_new_run_id() for _ in range(2)]
workspace = concurrency_limited_workspace_context.create_request_context()
remote_job = self.get_concurrency_job(workspace)
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
bar_key = dg.AssetKey(["prefix", "bar_limited_asset"])
# foo is blocked, but bar is not
instance.event_log_storage.set_concurrency_slots("foo", 0)
instance.event_log_storage.set_concurrency_slots("bar", 1)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set()
self.submit_run(
instance, remote_job, workspace, run_id=run_id_2, asset_selection=set([bar_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_2}
@pytest.mark.parametrize(
"run_coordinator_config",
[
{"block_op_concurrency_limited_runs": {"enabled": True}},
],
)
def test_op_concurrency_partial_root(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1 = make_new_run_id()
workspace = concurrency_limited_workspace_context.create_request_context()
remote_job = workspace.get_full_job(
JobSubsetSelector(
location_name="test",
repository_name="__repository__",
job_name="partial_concurrency_limited_multi_root_job",
op_selection=None,
)
)
instance.event_log_storage.set_concurrency_slots("foo", 0)
self.submit_run(instance, remote_job, workspace, run_id=run_id_1)
list(daemon.run_iteration(concurrency_limited_workspace_context))
# is not blocked because there's an unconstrained node at the root
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_1}
@pytest.mark.parametrize(
"run_coordinator_config",
[
{"block_op_concurrency_limited_runs": {"enabled": True}},
],
)
def test_in_progress_root_key_accounting(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1, run_id_2 = [make_new_run_id() for _ in range(2)]
workspace = concurrency_limited_workspace_context.create_request_context()
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
remote_job = self.get_concurrency_job(workspace)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_2, asset_selection=set([foo_key])
)
instance.event_log_storage.set_concurrency_slots("foo", 1)
with environ({"DAGSTER_OP_CONCURRENCY_KEYS_ALLOTTED_FOR_STARTED_RUN_SECONDS": "0"}):
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
assert instance.get_run_by_id(run_id_1).status == DagsterRunStatus.STARTING
instance.handle_run_event(
run_id_1,
dg.DagsterEvent(
event_type_value=DagsterEventType.RUN_START,
job_name="concurrency_limited_asset_job",
message="start that run",
),
)
assert instance.get_run_by_id(run_id_1).status == DagsterRunStatus.STARTED
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1, run_id_2])
@pytest.mark.parametrize(
"run_coordinator_config",
[
{
"block_op_concurrency_limited_runs": {
"enabled": True,
"op_concurrency_slot_buffer": 1,
}
},
],
)
def test_op_concurrency_aware_slot_buffer(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1, run_id_2, run_id_3 = [make_new_run_id() for _ in range(3)]
workspace = concurrency_limited_workspace_context.create_request_context()
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
remote_job = self.get_concurrency_job(workspace)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_2, asset_selection=set([foo_key])
)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_3, asset_selection=set([foo_key])
)
instance.event_log_storage.set_concurrency_slots("foo", 1)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1, run_id_2])
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1, run_id_2])
@pytest.mark.parametrize("concurrency_config", [{"default_op_concurrency_limit": 1}])
@pytest.mark.parametrize(
"run_coordinator_config",
[
{"block_op_concurrency_limited_runs": {"enabled": True}},
],
)
def test_op_concurrency_aware_started_allottment_time(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1, run_id_2, run_id_3 = [make_new_run_id() for _ in range(3)]
workspace = concurrency_limited_workspace_context.create_request_context()
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
remote_job = self.get_concurrency_job(workspace)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_2, asset_selection=set([foo_key])
)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_3, asset_selection=set([foo_key])
)
instance.event_log_storage.set_concurrency_slots("foo", 1)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
freeze_datetime = create_datetime(year=2024, month=2, day=21)
with environ({"DAGSTER_OP_CONCURRENCY_KEYS_ALLOTTED_FOR_STARTED_RUN_SECONDS": "1"}):
with freeze_time(freeze_datetime):
assert instance.get_run_by_id(run_id_1).status == DagsterRunStatus.STARTING
instance.handle_run_event(
run_id_1,
dg.DagsterEvent(
event_type_value=DagsterEventType.RUN_START,
job_name="concurrency_limited_asset_job",
message="start that run",
),
)
assert instance.get_run_by_id(run_id_1).status == DagsterRunStatus.STARTED
assert (
instance.get_run_record_by_id(run_id_1).start_time
== freeze_datetime.timestamp()
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
# even though run-1 is started, it still occupies one of the foo "slots" in the run
# coordinator accounting because the env var is set to wait for at 1 second after
# the run has started
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
freeze_datetime = freeze_datetime + datetime.timedelta(seconds=2)
with freeze_time(freeze_datetime):
# we are now out of the 1-second window for having run-1 account for slots in the
# run coordinator
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set(
[run_id_1, run_id_2]
)
@pytest.mark.parametrize(
"run_coordinator_config",
[
{
"tag_concurrency_limits": [{"key": "database", "value": "tiny", "limit": 0}],
"block_op_concurrency_limited_runs": {"enabled": True},
},
],
)
def test_multiple_blocks(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1 = make_new_run_id()
workspace = concurrency_limited_workspace_context.create_request_context()
remote_job = self.get_concurrency_job(workspace)
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
# foo is blocked, but bar is not
instance.event_log_storage.set_concurrency_slots("foo", 0)
self.submit_run(
instance,
remote_job,
workspace,
run_id=run_id_1,
asset_selection=set([foo_key]),
tags={"database": "tiny"},
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set()
@pytest.mark.parametrize("concurrency_config", [{"default_op_concurrency_limit": 1}])
@pytest.mark.parametrize(
"run_coordinator_config",
[
{
"block_op_concurrency_limited_runs": {
"enabled": True,
"op_concurrency_slot_buffer": 0,
}
},
],
)
def test_concurrency_buffer_with_default_slot(
self,
concurrency_limited_workspace_context,
daemon,
instance,
caplog,
):
run_id_1, run_id_2, run_id_3 = [make_new_run_id() for _ in range(3)]
workspace = concurrency_limited_workspace_context.create_request_context()
remote_job = self.get_concurrency_job(workspace)
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
# foo is not configured; relying on the default limit of 1
assert "foo" not in instance.event_log_storage.get_concurrency_keys()
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
caplog.text.count("is blocked by global concurrency limits") == 0 # pyright: ignore[reportUnusedExpression]
# the global concurrency counter has initialized the concurrency configuration
assert "foo" in instance.event_log_storage.get_concurrency_keys()
self.submit_run(
instance, remote_job, workspace, run_id=run_id_2, asset_selection=set([foo_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == {run_id_1}
caplog.text.count(f"Run {run_id_2} is blocked by global concurrency limits") == 1 # pyright: ignore[reportUnusedExpression]
@pytest.mark.parametrize(
"concurrency_config",
[
{"pools": {"granularity": "run", "default_limit": 1}},
],
)
@pytest.mark.parametrize(
"run_coordinator_config",
[
{
"block_op_concurrency_limited_runs": {
"enabled": True,
},
},
],
)
def test_concurrency_run_granularity(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1, run_id_2 = [make_new_run_id() for _ in range(2)]
workspace = concurrency_limited_workspace_context.create_request_context()
# concurrency_limited_asset_job
remote_job = self.get_concurrency_job(workspace)
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
bar_key = dg.AssetKey(["prefix", "bar_limited_asset"])
baz_key = dg.AssetKey(["prefix", "baz_limited_asset"])
downstream_baz_key = dg.AssetKey(["prefix", "baz_limited_asset_depends_on_foo"])
# first submit a run that occupies the baz slot
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([baz_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
# submit a run that has 2 root nodes, respectively with foo, bar concurrency groups
# also with a downstream extra baz concurrency group asset
self.submit_run(
instance,
remote_job,
workspace,
run_id=run_id_2,
asset_selection=set([foo_key, bar_key, downstream_baz_key]),
)
# even though the root nodes have slots available, the second run is not launched
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
instance.event_log_storage.set_concurrency_slots("baz", 2)
# all group slots available, run launched, even though there is only one slot open for baz
# and the run has two baz-grouped nodes
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1, run_id_2])
@pytest.mark.parametrize(
"run_coordinator_config",
[
{"block_op_concurrency_limited_runs": {"enabled": True}},
],
)
def test_concurrency_pending_slot_accounting(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1, run_id_2 = [make_new_run_id() for _ in range(2)]
workspace = concurrency_limited_workspace_context.create_request_context()
remote_job = self.get_concurrency_job(workspace)
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
self.submit_run(
instance, remote_job, workspace, run_id=run_id_2, asset_selection=set([foo_key])
)
instance.event_log_storage.set_concurrency_slots("foo", 1)
# only 1 slot, so only one run should be dequeued
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
# start the first run, have it claim the slot
freeze_datetime = create_datetime(year=2024, month=2, day=21)
with freeze_time(freeze_datetime):
assert instance.get_run_by_id(run_id_1).status == DagsterRunStatus.STARTING
instance.handle_run_event(
run_id_1,
dg.DagsterEvent(
event_type_value=DagsterEventType.RUN_START,
job_name="concurrency_limited_asset_job",
message="start that run",
),
)
assert instance.get_run_by_id(run_id_1).status == DagsterRunStatus.STARTED
instance.event_log_storage.claim_concurrency_slot("foo", run_id_1, "foo_limited_asset")
freeze_datetime = freeze_datetime + datetime.timedelta(seconds=60)
with freeze_time(freeze_datetime):
# the slot is still claimed by the first run, so the second run is not dequeued
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
# as soon as the first run frees that slot, the second run should be dequeued
instance.event_log_storage.free_concurrency_slot_for_step(run_id_1, "foo_limited_asset")
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1, run_id_2])
@pytest.mark.parametrize(
"concurrency_config",
[
{"pools": {"granularity": "op", "default_limit": 1}},
],
)
@pytest.mark.parametrize(
"run_coordinator_config",
[
{"block_op_concurrency_limited_runs": {"enabled": False}},
],
)
def test_disable_concurrency_run_blocking(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1, run_id_2 = [make_new_run_id() for _ in range(2)]
workspace = concurrency_limited_workspace_context.create_request_context()
# concurrency_limited_asset_job
remote_job = self.get_concurrency_job(workspace)
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
# first submit a run that occupies the foo slot
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
# submit a run that also occupies the foo slot
self.submit_run(
instance, remote_job, workspace, run_id=run_id_2, asset_selection=set([foo_key])
)
# the second run is launched
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1, run_id_2])
@pytest.mark.parametrize("concurrency_config", [{}, {"pools": {"granularity": "op"}}])
@pytest.mark.parametrize("run_coordinator_config", [{}])
def test_concurrency_run_default(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1, run_id_2, run_id_3 = [make_new_run_id() for _ in range(3)]
workspace = concurrency_limited_workspace_context.create_request_context()
# concurrency_limited_asset_job
remote_job = self.get_concurrency_job(workspace)
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
bar_key = dg.AssetKey(["prefix", "bar_limited_asset"])
instance.event_log_storage.set_concurrency_slots("foo", 1)
# first submit a run that occupies the foo slot
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
# the second run is not launched
self.submit_run(
instance, remote_job, workspace, run_id=run_id_2, asset_selection=set([foo_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
# submit a run that also occupies the foo slot, bar slot and is launched (the bar key is unconstrained)
self.submit_run(
instance,
remote_job,
workspace,
run_id=run_id_3,
asset_selection=set([foo_key, bar_key]),
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1, run_id_3])
@pytest.mark.parametrize(
"concurrency_config",
[
{"pools": {"granularity": "op"}},
{"pools": {"granularity": "run"}},
{},
],
)
@pytest.mark.parametrize("run_coordinator_config", [{}])
def test_concurrency_run_unconfigured(
self,
concurrency_limited_workspace_context,
daemon,
instance,
):
run_id_1 = make_new_run_id()
workspace = concurrency_limited_workspace_context.create_request_context()
# concurrency_limited_asset_job
remote_job = self.get_concurrency_job(workspace)
foo_key = dg.AssetKey(["prefix", "foo_limited_asset"])
# there are no configured slots, the run should be launched
self.submit_run(
instance, remote_job, workspace, run_id=run_id_1, asset_selection=set([foo_key])
)
list(daemon.run_iteration(concurrency_limited_workspace_context))
assert set(self.get_run_ids(instance.run_launcher.queue())) == set([run_id_1])
| QueuedRunCoordinatorDaemonTests |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 280,
"end": 343
} | class ____:
a = attr.ib(type=int)
c = C(1)
C(a=1)
@attr.s
| C |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingFalsy1.py | {
"start": 2180,
"end": 2801
} | class ____:
def __init__(self, value: int = 0) -> None:
self.value = value
def __bool__(self) -> bool:
return self.value >= 0
def method(self) -> None:
while not self:
reveal_type(self, expected_text="Self@E")
self.value += 1
def func10(val: AnyStr | None):
return 1
def func11(val: AnyStr | None):
assert val
reveal_type(val, expected_text="AnyStr@func11")
T = TypeVar("T")
def func12(val: T) -> T:
if val:
reveal_type(val, expected_text="T@func12")
else:
reveal_type(val, expected_text="T@func12")
return val
| E |
python | huggingface__transformers | src/transformers/models/t5gemma/modeling_t5gemma.py | {
"start": 24670,
"end": 28983
} | class ____(PreTrainedModel):
config: T5GemmaConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["T5GemmaEncoderLayer", "T5GemmaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_can_compile_fullgraph = True
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": T5GemmaDecoderLayer,
"attentions": [
OutputRecorder(T5GemmaSelfAttention, index=1, layer_name="self_attn"),
OutputRecorder(T5GemmaSelfAttention, index=1, layer_name="cross_attn"),
OutputRecorder(T5GemmaCrossAttention, index=1, layer_name="cross_attn"),
],
}
@torch.no_grad()
def _init_weights(self, module):
# TODO: support initialization for encoders and decoders separately(?)
super()._init_weights(module)
std = self.config.initializer_range
if isinstance(module, T5GemmaClassificationHead):
scale = module.out_proj.weight.shape[0] ** -0.5
init.normal_(module.out_proj.weight, mean=0.0, std=std * scale)
if hasattr(module.out_proj, "bias") and module.out_proj.bias is not None:
init.zeros_(module.out_proj.bias)
elif isinstance(module, T5GemmaLMHead):
if not self.config.tie_word_embeddings:
scale = module.out_proj.weight.shape[0] ** -0.5
init.normal_(module.out_proj.weight, mean=0.0, std=std * scale)
# We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight)
elif "RMSNorm" in module.__class__.__name__:
init.zeros_(module.weight)
def _shift_right(self, input_ids):
"""
Shifts input_ids to the right, prepends the decoder_start_token_id, and handles
pad_token_id replacement for labels that were -100.
This is a common preparation step for decoder inputs in sequence-to-sequence models.
"""
decoder_start_token_id = self.config.decoder.bos_token_id
pad_token_id = self.config.decoder.pad_token_id
if decoder_start_token_id is None:
raise ValueError("self.model.config.decoder.bos_token_id has to be defined. ")
# shift inputs to the right
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
shifted_input_ids[..., 0] = decoder_start_token_id
if pad_token_id is None:
raise ValueError("self.model.config.decoder.pad_token_id has to be defined.")
# Is this T5 specific?
# replace possible -100 values in labels by `pad_token_id`
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
return shifted_input_ids
def bidirectional_mask_function(attention_mask: Optional[torch.Tensor]) -> Callable:
"""
This creates bidirectional attention mask.
"""
def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
if attention_mask is None:
return torch.ones((), dtype=torch.bool)
return attention_mask[batch_idx, kv_idx].to(torch.bool)
return inner_mask
def sliding_window_bidirectional_mask_function(sliding_window: int) -> Callable:
"""
This creates bidirectional attention mask with sliding window.
"""
def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
return (q_idx - sliding_window < kv_idx) & (kv_idx < q_idx + sliding_window)
return inner_mask
def make_default_2d_attention_mask(
token_ids: Optional[torch.LongTensor],
hidden_states: torch.Tensor,
pad_token_id: Optional[int],
) -> torch.Tensor:
"""Construct the default attention mask."""
if token_ids is not None:
if pad_token_id is None:
raise ValueError("`pad_token_id` is required for padding information.")
attention_mask = (token_ids != pad_token_id).to(hidden_states.device, torch.long)
else:
attention_mask = torch.ones(
(hidden_states.shape[0], hidden_states.shape[1]), device=hidden_states.device, dtype=torch.long
)
return attention_mask
| T5GemmaPreTrainedModel |
python | apache__airflow | airflow-core/src/airflow/models/pool.py | {
"start": 1925,
"end": 13243
} | class ____(Base):
"""the class to get Pool info."""
__tablename__ = "slot_pool"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
pool: Mapped[str] = mapped_column(String(256), unique=True)
# -1 for infinite
slots: Mapped[int] = mapped_column(Integer, default=0)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
include_deferred: Mapped[bool] = mapped_column(Boolean, nullable=False)
team_id: Mapped[str | None] = mapped_column(UUIDType(binary=False), ForeignKey("team.id"), nullable=True)
DEFAULT_POOL_NAME = "default_pool"
def __repr__(self):
return str(self.pool)
@staticmethod
@provide_session
def get_pools(session: Session = NEW_SESSION) -> Sequence[Pool]:
"""Get all pools."""
return session.scalars(select(Pool)).all()
@staticmethod
@provide_session
def get_pool(pool_name: str, session: Session = NEW_SESSION) -> Pool | None:
"""
Get the Pool with specific pool name from the Pools.
:param pool_name: The pool name of the Pool to get.
:param session: SQLAlchemy ORM Session
:return: the pool object
"""
return session.scalar(select(Pool).where(Pool.pool == pool_name))
@staticmethod
@provide_session
def get_default_pool(session: Session = NEW_SESSION) -> Pool | None:
"""
Get the Pool of the default_pool from the Pools.
:param session: SQLAlchemy ORM Session
:return: the pool object
"""
return Pool.get_pool(Pool.DEFAULT_POOL_NAME, session=session)
@staticmethod
@provide_session
def is_default_pool(id: int, session: Session = NEW_SESSION) -> bool:
"""
Check id if is the default_pool.
:param id: pool id
:param session: SQLAlchemy ORM Session
:return: True if id is default_pool, otherwise False
"""
return exists_query(
Pool.id == id,
Pool.pool == Pool.DEFAULT_POOL_NAME,
session=session,
)
@staticmethod
@provide_session
def create_or_update_pool(
name: str,
slots: int,
description: str,
include_deferred: bool,
session: Session = NEW_SESSION,
) -> Pool:
"""Create a pool with given parameters or update it if it already exists."""
if not name:
raise ValueError("Pool name must not be empty")
pool = session.scalar(select(Pool).filter_by(pool=name))
if pool is None:
pool = Pool(pool=name, slots=slots, description=description, include_deferred=include_deferred)
session.add(pool)
else:
pool.slots = slots
pool.description = description
pool.include_deferred = include_deferred
session.commit()
return pool
@staticmethod
@provide_session
def delete_pool(name: str, session: Session = NEW_SESSION) -> Pool:
"""Delete pool by a given name."""
if name == Pool.DEFAULT_POOL_NAME:
raise AirflowException(f"{Pool.DEFAULT_POOL_NAME} cannot be deleted")
pool = session.scalar(select(Pool).filter_by(pool=name))
if pool is None:
raise PoolNotFound(f"Pool '{name}' doesn't exist")
session.delete(pool)
session.commit()
return pool
@staticmethod
@provide_session
def slots_stats(
*,
lock_rows: bool = False,
session: Session = NEW_SESSION,
) -> dict[str, PoolStats]:
"""
Get Pool stats (Number of Running, Queued, Open & Total tasks).
If ``lock_rows`` is True, and the database engine in use supports the ``NOWAIT`` syntax, then a
non-blocking lock will be attempted -- if the lock is not available then SQLAlchemy will throw an
OperationalError.
:param lock_rows: Should we attempt to obtain a row-level lock on all the Pool rows returns
:param session: SQLAlchemy ORM Session
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
pools: dict[str, PoolStats] = {}
pool_includes_deferred: dict[str, bool] = {}
query: Select[Any] | Query[Any] = select(Pool.pool, Pool.slots, Pool.include_deferred)
if lock_rows:
query = with_row_locks(query, session=session, nowait=True)
pool_rows = session.execute(query)
for pool_name, total_slots_in, include_deferred in pool_rows:
total_slots = float("inf") if total_slots_in == -1 else total_slots_in
pools[pool_name] = PoolStats(
total=total_slots, running=0, queued=0, open=0, deferred=0, scheduled=0
)
pool_includes_deferred[pool_name] = include_deferred
allowed_execution_states = EXECUTION_STATES | {
TaskInstanceState.DEFERRED,
TaskInstanceState.SCHEDULED,
}
state_count_by_pool = session.execute(
select(TaskInstance.pool, TaskInstance.state, func.sum(TaskInstance.pool_slots))
.filter(TaskInstance.state.in_(allowed_execution_states))
.group_by(TaskInstance.pool, TaskInstance.state)
)
# calculate queued and running metrics
for pool_name, state, decimal_count in state_count_by_pool:
# Some databases return decimal.Decimal here.
count = int(decimal_count)
stats_dict: PoolStats | None = pools.get(pool_name)
if not stats_dict:
continue
# TypedDict key must be a string literal, so we use if-statements to set value
if state == TaskInstanceState.RUNNING:
stats_dict["running"] = count
elif state == TaskInstanceState.QUEUED:
stats_dict["queued"] = count
elif state == TaskInstanceState.DEFERRED:
stats_dict["deferred"] = count
elif state == TaskInstanceState.SCHEDULED:
stats_dict["scheduled"] = count
else:
raise AirflowException(f"Unexpected state. Expected values: {allowed_execution_states}.")
# calculate open metric
for pool_name, stats_dict in pools.items():
stats_dict["open"] = stats_dict["total"] - stats_dict["running"] - stats_dict["queued"]
if pool_includes_deferred[pool_name]:
stats_dict["open"] -= stats_dict["deferred"]
return pools
def to_json(self) -> dict[str, Any]:
"""
Get the Pool in a json structure.
:return: the pool object in json format
"""
return {
"id": self.id,
"pool": self.pool,
"slots": self.slots,
"description": self.description,
"include_deferred": self.include_deferred,
}
@provide_session
def occupied_slots(self, session: Session = NEW_SESSION) -> int:
"""
Get the number of slots used by running/queued tasks at the moment.
:param session: SQLAlchemy ORM Session
:return: the used number of slots
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
occupied_states = self.get_occupied_states()
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots))
.filter(TaskInstance.pool == self.pool)
.filter(TaskInstance.state.in_(occupied_states))
)
or 0
)
def get_occupied_states(self):
if self.include_deferred:
return EXECUTION_STATES | {
TaskInstanceState.DEFERRED,
}
return EXECUTION_STATES
@provide_session
def running_slots(self, session: Session = NEW_SESSION) -> int:
"""
Get the number of slots used by running tasks at the moment.
:param session: SQLAlchemy ORM Session
:return: the used number of slots
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots))
.filter(TaskInstance.pool == self.pool)
.filter(TaskInstance.state == TaskInstanceState.RUNNING)
)
or 0
)
@provide_session
def queued_slots(self, session: Session = NEW_SESSION) -> int:
"""
Get the number of slots used by queued tasks at the moment.
:param session: SQLAlchemy ORM Session
:return: the used number of slots
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots))
.filter(TaskInstance.pool == self.pool)
.filter(TaskInstance.state == TaskInstanceState.QUEUED)
)
or 0
)
@provide_session
def scheduled_slots(self, session: Session = NEW_SESSION) -> int:
"""
Get the number of slots scheduled at the moment.
:param session: SQLAlchemy ORM Session
:return: the number of scheduled slots
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots))
.filter(TaskInstance.pool == self.pool)
.filter(TaskInstance.state == TaskInstanceState.SCHEDULED)
)
or 0
)
@provide_session
def deferred_slots(self, session: Session = NEW_SESSION) -> int:
"""
Get the number of slots deferred at the moment.
:param session: SQLAlchemy ORM Session
:return: the number of deferred slots
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
return int(
session.scalar(
select(func.sum(TaskInstance.pool_slots)).where(
TaskInstance.pool == self.pool, TaskInstance.state == TaskInstanceState.DEFERRED
)
)
or 0
)
@provide_session
def open_slots(self, session: Session = NEW_SESSION) -> float:
"""
Get the number of slots open at the moment.
:param session: SQLAlchemy ORM Session
:return: the number of slots
"""
if self.slots == -1:
return float("inf")
return self.slots - self.occupied_slots(session)
@staticmethod
@provide_session
def get_team_name(pool_name: str, session: Session = NEW_SESSION) -> str | None:
stmt = select(Team.name).join(Pool, Team.id == Pool.team_id).where(Pool.pool == pool_name)
return session.scalar(stmt)
@staticmethod
@provide_session
def get_name_to_team_name_mapping(
pool_names: list[str], session: Session = NEW_SESSION
) -> dict[str, str | None]:
stmt = (
select(Pool.pool, Team.name).join(Team, Pool.team_id == Team.id).where(Pool.pool.in_(pool_names))
)
return {pool: team_name for pool, team_name in session.execute(stmt)}
| Pool |
python | pypa__pip | src/pip/_vendor/distlib/resources.py | {
"start": 6087,
"end": 10820
} | class ____(ResourceFinder):
"""
Resource finder for resources in .zip files.
"""
def __init__(self, module):
super(ZipResourceFinder, self).__init__(module)
archive = self.loader.archive
self.prefix_len = 1 + len(archive)
# PyPy doesn't have a _files attr on zipimporter, and you can't set one
if hasattr(self.loader, '_files'):
self._files = self.loader._files
else:
self._files = zipimport._zip_directory_cache[archive]
self.index = sorted(self._files)
def _adjust_path(self, path):
return path
def _find(self, path):
path = path[self.prefix_len:]
if path in self._files:
result = True
else:
if path and path[-1] != os.sep:
path = path + os.sep
i = bisect.bisect(self.index, path)
try:
result = self.index[i].startswith(path)
except IndexError:
result = False
if not result:
logger.debug('_find failed: %r %r', path, self.loader.prefix)
else:
logger.debug('_find worked: %r %r', path, self.loader.prefix)
return result
def get_cache_info(self, resource):
prefix = self.loader.archive
path = resource.path[1 + len(prefix):]
return prefix, path
def get_bytes(self, resource):
return self.loader.get_data(resource.path)
def get_stream(self, resource):
return io.BytesIO(self.get_bytes(resource))
def get_size(self, resource):
path = resource.path[self.prefix_len:]
return self._files[path][3]
def get_resources(self, resource):
path = resource.path[self.prefix_len:]
if path and path[-1] != os.sep:
path += os.sep
plen = len(path)
result = set()
i = bisect.bisect(self.index, path)
while i < len(self.index):
if not self.index[i].startswith(path):
break
s = self.index[i][plen:]
result.add(s.split(os.sep, 1)[0]) # only immediate children
i += 1
return result
def _is_directory(self, path):
path = path[self.prefix_len:]
if path and path[-1] != os.sep:
path += os.sep
i = bisect.bisect(self.index, path)
try:
result = self.index[i].startswith(path)
except IndexError:
result = False
return result
_finder_registry = {
type(None): ResourceFinder,
zipimport.zipimporter: ZipResourceFinder
}
try:
# In Python 3.6, _frozen_importlib -> _frozen_importlib_external
try:
import _frozen_importlib_external as _fi
except ImportError:
import _frozen_importlib as _fi
_finder_registry[_fi.SourceFileLoader] = ResourceFinder
_finder_registry[_fi.FileFinder] = ResourceFinder
# See issue #146
_finder_registry[_fi.SourcelessFileLoader] = ResourceFinder
del _fi
except (ImportError, AttributeError):
pass
def register_finder(loader, finder_maker):
_finder_registry[type(loader)] = finder_maker
_finder_cache = {}
def finder(package):
"""
Return a resource finder for a package.
:param package: The name of the package.
:return: A :class:`ResourceFinder` instance for the package.
"""
if package in _finder_cache:
result = _finder_cache[package]
else:
if package not in sys.modules:
__import__(package)
module = sys.modules[package]
path = getattr(module, '__path__', None)
if path is None:
raise DistlibException('You cannot get a finder for a module, '
'only for a package')
loader = getattr(module, '__loader__', None)
finder_maker = _finder_registry.get(type(loader))
if finder_maker is None:
raise DistlibException('Unable to locate finder for %r' % package)
result = finder_maker(module)
_finder_cache[package] = result
return result
_dummy_module = types.ModuleType(str('__dummy__'))
def finder_for_path(path):
"""
Return a resource finder for a path, which should represent a container.
:param path: The path.
:return: A :class:`ResourceFinder` instance for the path.
"""
result = None
# calls any path hooks, gets importer into cache
pkgutil.get_importer(path)
loader = sys.path_importer_cache.get(path)
finder = _finder_registry.get(type(loader))
if finder:
module = _dummy_module
module.__file__ = os.path.join(path, '')
module.__loader__ = loader
result = finder(module)
return result
| ZipResourceFinder |
python | ipython__ipython | tests/test_magic_terminal.py | {
"start": 2296,
"end": 5943
} | class ____(TestCase):
"""Multiple tests for clipboard pasting"""
def paste(self, txt, flags="-q"):
"""Paste input text, by default in quiet mode"""
ip.hooks.clipboard_get = lambda: txt
ip.run_line_magic("paste", flags)
def setUp(self):
# Inject fake clipboard hook but save original so we can restore it later
self.original_clip = ip.hooks.clipboard_get
def tearDown(self):
# Restore original hook
ip.hooks.clipboard_get = self.original_clip
def test_paste(self):
ip.user_ns.pop("x", None)
self.paste("x = 1")
self.assertEqual(ip.user_ns["x"], 1)
ip.user_ns.pop("x")
def test_paste_pyprompt(self):
ip.user_ns.pop("x", None)
self.paste(">>> x=2")
self.assertEqual(ip.user_ns["x"], 2)
ip.user_ns.pop("x")
def test_paste_py_multi(self):
self.paste(
"""
>>> x = [1,2,3]
>>> y = []
>>> for i in x:
... y.append(i**2)
...
"""
)
self.assertEqual(ip.user_ns["x"], [1, 2, 3])
self.assertEqual(ip.user_ns["y"], [1, 4, 9])
def test_paste_py_multi_r(self):
"Now, test that self.paste -r works"
self.test_paste_py_multi()
self.assertEqual(ip.user_ns.pop("x"), [1, 2, 3])
self.assertEqual(ip.user_ns.pop("y"), [1, 4, 9])
self.assertFalse("x" in ip.user_ns)
ip.run_line_magic("paste", "-r")
self.assertEqual(ip.user_ns["x"], [1, 2, 3])
self.assertEqual(ip.user_ns["y"], [1, 4, 9])
def test_paste_email(self):
"Test pasting of email-quoted contents"
self.paste(
"""\
>> def foo(x):
>> return x + 1
>> xx = foo(1.1)"""
)
self.assertEqual(ip.user_ns["xx"], 2.1)
def test_paste_email2(self):
"Email again; some programs add a space also at each quoting level"
self.paste(
"""\
> > def foo(x):
> > return x + 1
> > yy = foo(2.1) """
)
self.assertEqual(ip.user_ns["yy"], 3.1)
def test_paste_email_py(self):
"Email quoting of interactive input"
self.paste(
"""\
>> >>> def f(x):
>> ... return x+1
>> ...
>> >>> zz = f(2.5) """
)
self.assertEqual(ip.user_ns["zz"], 3.5)
def test_paste_echo(self):
"Also test self.paste echoing, by temporarily faking the writer"
w = StringIO()
old_write = sys.stdout.write
sys.stdout.write = w.write
code = """
a = 100
b = 200"""
try:
self.paste(code, "")
out = w.getvalue()
finally:
sys.stdout.write = old_write
self.assertEqual(ip.user_ns["a"], 100)
self.assertEqual(ip.user_ns["b"], 200)
assert out == code + "\n## -- End pasted text --\n"
def test_paste_leading_commas(self):
"Test multiline strings with leading commas"
tm = ip.magics_manager.registry["TerminalMagics"]
s = '''\
a = """
,1,2,3
"""'''
ip.user_ns.pop("foo", None)
tm.store_or_execute(s, "foo")
self.assertIn("foo", ip.user_ns)
def test_paste_trailing_question(self):
"Test pasting sources with trailing question marks"
tm = ip.magics_manager.registry["TerminalMagics"]
s = """\
def funcfoo():
if True: #am i true?
return 'fooresult'
"""
ip.user_ns.pop("funcfoo", None)
self.paste(s)
self.assertEqual(ip.user_ns["funcfoo"](), "fooresult")
| PasteTestCase |
python | walkccc__LeetCode | solutions/1924. Erect the Fence II/1924.py | {
"start": 121,
"end": 167
} | class ____:
center: Point
radius: float
| Disk |
python | ipython__ipython | IPython/core/prefilter.py | {
"start": 16656,
"end": 17602
} | class ____(PrefilterChecker):
priority = Integer(700).tag(config=True)
def check(self, line_info):
"""If the ifun is magic, and automagic is on, run it. Note: normal,
non-auto magic would already have been triggered via '%' in
check_esc_chars. This just checks for automagic. Also, before
triggering the magic handler, make sure that there is nothing in the
user namespace which could shadow it."""
if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
return None
# We have a likely magic method. Make sure we should actually call it.
if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
return None
head = line_info.ifun.split('.',1)[0]
if is_shadowed(head, self.shell):
return None
return self.prefilter_manager.get_handler_by_name('magic')
| AutoMagicChecker |
python | modin-project__modin | modin/core/io/column_stores/feather_dispatcher.py | {
"start": 1109,
"end": 3535
} | class ____(ColumnStoreDispatcher):
"""Class handles utils for reading `.feather` files."""
@classmethod
def _read(cls, path, columns=None, **kwargs):
"""
Read data from the file path, returning a query compiler.
Parameters
----------
path : str or file-like object
The filepath of the feather file.
columns : array-like, optional
Columns to read from file. If not provided, all columns are read.
**kwargs : dict
`read_feather` function kwargs.
Returns
-------
BaseQueryCompiler
Query compiler with imported data for further processing.
Notes
-----
`PyArrow` engine and local files only are supported for now,
multi threading is set to False by default.
PyArrow feather is used. Please refer to the documentation here
https://arrow.apache.org/docs/python/api.html#feather-format
"""
path = stringify_path(path)
path = cls.get_path(path)
if columns is None:
import_optional_dependency(
"pyarrow", "pyarrow is required to read feather files."
)
from pyarrow import ipc
with OpenFile(
path,
**(kwargs.get("storage_options", None) or {}),
) as file:
# Opens the file to extract its metadata
reader = ipc.open_file(file)
# TODO: pyarrow's schema contains much more metadata than just column names, it also
# has dtypes and index information that we could use when building a dataframe
index_cols = frozenset(
col
for col in reader.schema.pandas_metadata["index_columns"]
# 'index_columns' field may also contain dictionary fields describing actual
# RangeIndices, so we're only filtering here for string column names
if isinstance(col, str)
)
# Filtering out the columns that describe the frame's index
columns = [col for col in reader.schema.names if col not in index_cols]
return cls.build_query_compiler(
path,
columns,
use_threads=False,
storage_options=kwargs["storage_options"],
dtype_backend=kwargs["dtype_backend"],
)
| FeatherDispatcher |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/packaging.py | {
"start": 1869,
"end": 3038
} | class ____(PackagingCheck):
name = "Python connectors must have PyPi publishing declared."
description = f"Python connectors must have [PyPi](https://pypi.org/) publishing enabled in their `{consts.METADATA_FILE_NAME}` file. This is declared by setting `remoteRegistries.pypi.enabled` to `true` in {consts.METADATA_FILE_NAME}. This is to ensure that all connectors can be published to PyPi and can be used in `PyAirbyte`."
applies_to_connector_languages = [
ConnectorLanguage.PYTHON,
ConnectorLanguage.LOW_CODE,
]
applies_to_connector_types = ["source"]
def _run(self, connector: Connector) -> CheckResult:
publish_to_pypi_is_enabled = get(connector.metadata, "remoteRegistries.pypi.enabled")
if publish_to_pypi_is_enabled is None:
return self.create_check_result(
connector=connector,
passed=False,
message=f"PyPi publishing is not declared. Please set it in the {consts.METADATA_FILE_NAME} file",
)
return self.create_check_result(connector=connector, passed=True, message="PyPi publishing is declared")
| CheckPublishToPyPiIsDeclared |
python | facebook__pyre-check | scripts/explore_pysa_models.py | {
"start": 17560,
"end": 17971
} | class ____(NamedTuple):
filename: str
path: Optional[str]
line: int
start: int
end: int
def print(self, prefix: str, indent: str) -> None:
filename = self.filename
path = self.path
if filename == "*" and path is not None:
filename = path
print(f"{indent}{prefix}{blue(filename)}:{blue(self.line)}:{blue(self.start)}")
| SourceLocationWithFilename |
python | jina-ai__jina | tests/unit/serve/runtimes/worker/test_worker_request_handler.py | {
"start": 455,
"end": 612
} | class ____(Executor):
@requests
async def foo(self, docs, **kwargs):
return DocumentArray([Document(text='new document')])
| AsyncNewDocsExecutor |
python | PyCQA__pylint | doc/data/messages/u/unused-private-member/good.py | {
"start": 0,
"end": 256
} | class ____:
FRUITS = {"apple": "red", "orange": "orange"}
def __print_color(self, name, color):
print(f"{name}: {color}")
def print(self):
for fruit, color in self.FRUITS.items():
self.__print_color(fruit, color)
| Fruit |
python | huggingface__transformers | tests/models/unispeech_sat/test_modeling_unispeech_sat.py | {
"start": 20434,
"end": 28353
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (
(UniSpeechSatForCTC, UniSpeechSatForPreTraining, UniSpeechSatModel, UniSpeechSatForSequenceClassification)
if is_torch_available()
else ()
)
def setUp(self):
self.model_tester = UniSpeechSatModelTester(
self, conv_stride=(3, 3, 3), feat_extract_norm="layer", do_stable_layer_norm=True
)
self.config_tester = ConfigTester(self, config_class=UniSpeechSatConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_batched_inference(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_batch_inference(*config_and_inputs)
def test_ctc_loss_inference(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_ctc_loss(*config_and_inputs)
def test_seq_classifier_loss_inference(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_seq_classifier_loss(*config_and_inputs)
def test_ctc_train(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_ctc_training(*config_and_inputs)
def test_seq_classifier_train(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_seq_classifier_training(*config_and_inputs)
def test_labels_out_of_vocab(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_labels_out_of_vocab(*config_and_inputs)
@unittest.skip(reason="Model has no input_embeds")
def test_inputs_embeds(self):
pass
@unittest.skip(reason="Model has input_values instead of input_ids")
def test_forward_signature(self):
pass
@unittest.skip(reason="Model has no tokens embeddings")
def test_resize_tokens_embeddings(self):
pass
@unittest.skip(reason="Model has no input_embeds")
def test_model_get_set_embeddings(self):
pass
def test_retain_grad_hidden_states_attentions(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.output_hidden_states = True
config.output_attentions = True
# force eager attention to support output attentions
config._attn_implementation = "eager"
# no need to test all models as different heads yield the same functionality
model_class = self.all_model_classes[0]
model = model_class(config)
model.to(torch_device)
# set layer drop to 0
model.config.layerdrop = 0.0
input_values = inputs_dict["input_values"]
input_lengths = torch.tensor(
[input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device
)
output_lengths = model._get_feat_extract_output_lengths(input_lengths)
labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size)
inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"])
inputs_dict["labels"] = labels
outputs = model(**inputs_dict)
output = outputs[0]
# Encoder-/Decoder-only models
hidden_states = outputs.hidden_states[0]
attentions = outputs.attentions[0]
hidden_states.retain_grad()
attentions.retain_grad()
output.flatten()[0].backward(retain_graph=True)
self.assertIsNotNone(hidden_states.grad)
self.assertIsNotNone(attentions.grad)
# overwrite from test_modeling_common
def _mock_init_weights(self, module):
if hasattr(module, "weight") and module.weight is not None:
module.weight.fill_(3)
if hasattr(module, "weight_g") and module.weight_g is not None:
module.weight_g.data.fill_(3)
if hasattr(module, "weight_v") and module.weight_v is not None:
module.weight_v.data.fill_(3)
if hasattr(module, "bias") and module.bias is not None:
module.bias.fill_(3)
if hasattr(module, "codevectors") and module.codevectors is not None:
module.codevectors.data.fill_(3)
if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None:
module.masked_spec_embed.data.fill_(3)
def test_mask_feature_prob_ctc(self):
model = UniSpeechSatForCTC.from_pretrained(
"hf-internal-testing/tiny-random-unispeech-sat", mask_feature_prob=0.2, mask_feature_length=2
)
model.to(torch_device).train()
processor = Wav2Vec2Processor.from_pretrained(
"hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True
)
batch_duration_in_seconds = [1, 3, 2, 6]
input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]
batch = processor(
input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt"
)
logits = model(
input_values=batch["input_values"].to(torch_device),
attention_mask=batch["attention_mask"].to(torch_device),
).logits
self.assertEqual(logits.shape, (4, 1498, 32))
def test_mask_time_prob_ctc(self):
model = UniSpeechSatForCTC.from_pretrained(
"hf-internal-testing/tiny-random-unispeech-sat", mask_time_prob=0.2, mask_time_length=2
)
model.to(torch_device).train()
processor = Wav2Vec2Processor.from_pretrained(
"hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True
)
batch_duration_in_seconds = [1, 3, 2, 6]
input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]
batch = processor(
input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt"
)
logits = model(
input_values=batch["input_values"].to(torch_device),
attention_mask=batch["attention_mask"].to(torch_device),
).logits
self.assertEqual(logits.shape, (4, 1498, 32))
def test_mask_time_feature_prob_ctc_single_batch(self):
model = UniSpeechSatForCTC.from_pretrained(
"hf-internal-testing/tiny-random-unispeech-sat",
mask_time_prob=0.2,
mask_feature_prob=0.2,
mask_time_length=2,
mask_feature_length=2,
)
model.to(torch_device).train()
processor = Wav2Vec2Processor.from_pretrained(
"hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True
)
batch_duration_in_seconds = [6]
input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]
batch = processor(
input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt"
)
logits = model(
input_values=batch["input_values"].to(torch_device),
attention_mask=batch["attention_mask"].to(torch_device),
).logits
self.assertEqual(logits.shape, (1, 1498, 32))
@unittest.skip(reason="Feed forward chunking is not implemented")
def test_feed_forward_chunking(self):
pass
@slow
def test_model_from_pretrained(self):
model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-large")
self.assertIsNotNone(model)
@require_torch
@require_torchcodec
@slow
| UniSpeechSatRobustModelTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/errors_handlers.py | {
"start": 5937,
"end": 7254
} | class ____(GithubStreamABCErrorHandler):
def interpret_response(self, response_or_exception: Optional[Union[requests.Response, Exception]] = None) -> ErrorResolution:
if isinstance(response_or_exception, requests.Response):
if response_or_exception.status_code in (requests.codes.BAD_GATEWAY, requests.codes.GATEWAY_TIMEOUT):
self.stream.page_size = int(self.stream.page_size / 2)
return ErrorResolution(
response_action=ResponseAction.RETRY,
failure_type=FailureType.transient_error,
error_message=f"Response status code: {response_or_exception.status_code}. Retrying...",
)
self.stream.page_size = (
constants.DEFAULT_PAGE_SIZE_FOR_LARGE_STREAM if self.stream.large_stream else constants.DEFAULT_PAGE_SIZE
)
if response_or_exception.json().get("errors"):
return ErrorResolution(
response_action=ResponseAction.RETRY,
failure_type=FailureType.transient_error,
error_message=f"Response status code: {response_or_exception.status_code}. Retrying...",
)
return super().interpret_response(response_or_exception)
| GitHubGraphQLErrorHandler |
python | huggingface__transformers | tests/models/jamba/test_modeling_jamba.py | {
"start": 22916,
"end": 26538
} | class ____(unittest.TestCase):
model = None
tokenizer = None
# This variable is used to determine which acclerator are we using for our runners (e.g. A10 or T4)
# Depending on the hardware we get different logits / generations
device_properties: DeviceProperties = (None, None, None)
@classmethod
def setUpClass(cls):
model_id = "ai21labs/Jamba-tiny-dev"
cls.model = JambaForCausalLM.from_pretrained(
model_id,
dtype=torch.bfloat16,
use_mamba_kernels=False,
)
cls.tokenizer = AutoTokenizer.from_pretrained(model_id)
cls.device_properties = get_device_properties()
def test_simple_generate(self):
# ("cuda", 8) for A100/A10, and ("cuda", 7) for T4.
#
# considering differences in hardware processing and potential deviations in generated text.
# fmt: off
EXPECTED_TEXTS = Expectations(
{
("cuda", 7): "<|startoftext|>Hey how are you doing on this lovely evening? Canyon rins hugaughter glamour Rutgers Singh<|reserved_797|>cw algunas",
("cuda", 8): "<|startoftext|>Hey how are you doing on this lovely evening? I'm so glad you're here.",
("rocm", 9): "<|startoftext|>Hey how are you doing on this lovely evening? Canyon rins hugaughter glamour Rutgers Singh Hebrew llam bb",
}
)
# fmt: on
expected_sentence = EXPECTED_TEXTS.get_expectation()
self.model.to(torch_device)
input_ids = self.tokenizer("Hey how are you doing on this lovely evening?", return_tensors="pt")[
"input_ids"
].to(torch_device)
out = self.model.generate(input_ids, do_sample=False, max_new_tokens=10)
output_sentence = self.tokenizer.decode(out[0, :])
self.assertEqual(output_sentence, expected_sentence)
def test_simple_batched_generate_with_padding(self):
# ("cuda", 8) for A100/A10, and ("cuda", 7) for T4.
#
# considering differences in hardware processing and potential deviations in generated text.
# fmt: off
EXPECTED_TEXTS = Expectations(
{
("cuda", 7): ["<|startoftext|>Hey how are you doing on this lovely evening? Canyon rins hugaughter glamour Rutgers Singh Hebrew cases Cats", "<|pad|><|pad|><|pad|><|pad|><|pad|><|pad|><|startoftext|>Tell me a storyptus Nets Madison El chamadamodern updximVaparsed",],
("cuda", 8): ["<|startoftext|>Hey how are you doing on this lovely evening? I'm so glad you're here.", "<|pad|><|pad|><|pad|><|pad|><|pad|><|pad|><|startoftext|>Tell me a story about a woman who was born in the United States",],
("rocm", 9): ["<|startoftext|>Hey how are you doing on this lovely evening? Canyon rins hugaughter glamour Rutgers Singh<|reserved_797|>cw algunas", "<|pad|><|pad|><|pad|><|pad|><|pad|><|pad|><|startoftext|>Tell me a storyptus Nets Madison El chamadamodern updximVaparsed",],
}
)
# fmt: on
expected_sentences = EXPECTED_TEXTS.get_expectation()
self.model.to(torch_device)
inputs = self.tokenizer(
["Hey how are you doing on this lovely evening?", "Tell me a story"], padding=True, return_tensors="pt"
).to(torch_device)
out = self.model.generate(**inputs, do_sample=False, max_new_tokens=10)
output_sentences = self.tokenizer.batch_decode(out)
self.assertEqual(output_sentences[0], expected_sentences[0])
self.assertEqual(output_sentences[1], expected_sentences[1])
| JambaModelIntegrationTest |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_request_mcp_tool_result_block_param.py | {
"start": 413,
"end": 761
} | class ____(TypedDict, total=False):
tool_use_id: Required[str]
type: Required[Literal["mcp_tool_result"]]
cache_control: Optional[BetaCacheControlEphemeralParam]
"""Create a cache control breakpoint at this content block."""
content: Union[str, Iterable[BetaTextBlockParam]]
is_error: bool
| BetaRequestMCPToolResultBlockParam |
python | dagster-io__dagster | python_modules/libraries/dagster-powerbi/dagster_powerbi/translator.py | {
"start": 3273,
"end": 4816
} | class ____:
"""A record representing all content in a PowerBI workspace.
Provided as context for the translator so that it can resolve dependencies between content.
"""
workspace_id: str
dashboards_by_id: dict[str, PowerBIContentData]
reports_by_id: dict[str, PowerBIContentData]
semantic_models_by_id: dict[str, PowerBIContentData]
data_sources_by_id: dict[str, PowerBIContentData]
@classmethod
def from_content_data(
cls, workspace_id: str, content_data: Sequence[PowerBIContentData]
) -> "PowerBIWorkspaceData":
return cls(
workspace_id=workspace_id,
dashboards_by_id={
dashboard.properties["id"]: dashboard
for dashboard in content_data
if dashboard.content_type == PowerBIContentType.DASHBOARD
},
reports_by_id={
report.properties["id"]: report
for report in content_data
if report.content_type == PowerBIContentType.REPORT
},
semantic_models_by_id={
dataset.properties["id"]: dataset
for dataset in content_data
if dataset.content_type == PowerBIContentType.SEMANTIC_MODEL
},
data_sources_by_id={
data_source.properties["datasourceId"]: data_source
for data_source in content_data
if data_source.content_type == PowerBIContentType.DATA_SOURCE
},
)
| PowerBIWorkspaceData |
python | huggingface__transformers | src/transformers/models/longformer/modeling_longformer.py | {
"start": 6914,
"end": 9855
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Masked language modeling (MLM) loss.
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +
attention_window + 1)`, where `x` is the number of tokens with global attention mask.
Local attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token in the sequence to every token with
global attention (first `x` values) and to every token in the attention window (remaining `attention_window
+ 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the
remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a
token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding
(succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.
If the attention window contains a token with global attention, the attention weight at the corresponding
index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global
attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be
accessed from `global_attentions`.
global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
where `x` is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
loss: Optional[torch.FloatTensor] = None
logits: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
global_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for outputs of question answering Longformer models.
"""
)
| LongformerMaskedLMOutput |
python | ethereum__web3.py | web3/types.py | {
"start": 5481,
"end": 5736
} | class ____(TypedDict):
address: ChecksumAddress
blockHash: HexBytes
blockNumber: BlockNumber
data: HexBytes
logIndex: int
removed: bool
topics: Sequence[HexBytes]
transactionHash: HexBytes
transactionIndex: int
| LogReceipt |
python | getsentry__sentry | src/sentry/api/bases/team.py | {
"start": 694,
"end": 1442
} | class ____(OrganizationPermission):
scope_map = {
"GET": ["team:read", "team:write", "team:admin"],
"POST": ["team:write", "team:admin"],
"PUT": ["team:write", "team:admin"],
"DELETE": ["team:admin"],
}
def has_object_permission(self, request: Request, view: APIView, team: Any) -> bool:
has_org_scope = super().has_object_permission(request, view, team.organization)
if has_org_scope:
# Org-admin has "team:admin", but they can only act on their teams
# Org-owners and Org-managers have no restrictions due to team memberships
return request.access.has_team_access(team)
return has_team_permission(request, team, self.scope_map)
| TeamPermission |
python | pandas-dev__pandas | pandas/tests/indexes/categorical/test_category.py | {
"start": 9816,
"end": 15131
} | class ____:
def test_view_i8(self):
# GH#25464
ci = CategoricalIndex(list("ab") * 50)
msg = "When changing to a larger dtype, its size must be a divisor"
with pytest.raises(ValueError, match=msg):
ci.view("i8")
with pytest.raises(ValueError, match=msg):
ci._data.view("i8")
ci = ci[:-4] # length divisible by 8
res = ci.view("i8")
expected = ci._data.codes.view("i8")
tm.assert_numpy_array_equal(res, expected)
cat = ci._data
tm.assert_numpy_array_equal(cat.view("i8"), expected)
@pytest.mark.parametrize(
"dtype, engine_type",
[
(np.int8, libindex.Int8Engine),
(np.int16, libindex.Int16Engine),
(np.int32, libindex.Int32Engine),
(np.int64, libindex.Int64Engine),
],
)
def test_engine_type(self, dtype, engine_type):
if dtype != np.int64:
# num. of uniques required to push CategoricalIndex.codes to a
# dtype (128 categories required for .codes dtype to be int16 etc.)
num_uniques = {np.int8: 1, np.int16: 128, np.int32: 32768}[dtype]
ci = CategoricalIndex(range(num_uniques))
else:
# having 2**32 - 2**31 categories would be very memory-intensive,
# so we cheat a bit with the dtype
ci = CategoricalIndex(range(32768)) # == 2**16 - 2**(16 - 1)
arr = ci.values._ndarray.astype("int64")
NDArrayBacked.__init__(ci._data, arr, ci.dtype)
assert np.issubdtype(ci.codes.dtype, dtype)
assert isinstance(ci._engine, engine_type)
@pytest.mark.parametrize(
"func,op_name",
[
(lambda idx: idx - idx, "__sub__"),
(lambda idx: idx + idx, "__add__"),
(lambda idx: idx - ["a", "b"], "__sub__"),
(lambda idx: idx + ["a", "b"], "__add__"),
(lambda idx: ["a", "b"] - idx, "__rsub__"),
(lambda idx: ["a", "b"] + idx, "__radd__"),
],
)
def test_disallow_addsub_ops(self, func, op_name):
# GH 10039
# set ops (+/-) raise TypeError
idx = Index(Categorical(["a", "b"]))
cat_or_list = "'(Categorical|list)' and '(Categorical|list)'"
msg = "|".join(
[
rf"unsupported operand type\(s\) for [\+-]: {cat_or_list}",
"Object with dtype category cannot perform the numpy op (add|subtract)",
"operation 'r?(add|sub)' not supported for dtype 'str' "
"with dtype 'category'",
]
)
with pytest.raises(TypeError, match=msg):
func(idx)
def test_method_delegation(self):
ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
result = ci.set_categories(list("cab"))
tm.assert_index_equal(
result, CategoricalIndex(list("aabbca"), categories=list("cab"))
)
ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
result = ci.rename_categories(list("efg"))
tm.assert_index_equal(
result, CategoricalIndex(list("ffggef"), categories=list("efg"))
)
# GH18862 (let rename_categories take callables)
result = ci.rename_categories(lambda x: x.upper())
tm.assert_index_equal(
result, CategoricalIndex(list("AABBCA"), categories=list("CAB"))
)
ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
result = ci.add_categories(["d"])
tm.assert_index_equal(
result, CategoricalIndex(list("aabbca"), categories=list("cabd"))
)
ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
result = ci.remove_categories(["c"])
tm.assert_index_equal(
result,
CategoricalIndex(list("aabb") + [np.nan] + ["a"], categories=list("ab")),
)
ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
result = ci.as_unordered()
tm.assert_index_equal(result, ci)
ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
result = ci.as_ordered()
tm.assert_index_equal(
result,
CategoricalIndex(list("aabbca"), categories=list("cabdef"), ordered=True),
)
# invalid
msg = "cannot use inplace with CategoricalIndex"
with pytest.raises(ValueError, match=msg):
ci.set_categories(list("cab"), inplace=True)
def test_remove_maintains_order(self):
ci = CategoricalIndex(list("abcdda"), categories=list("abcd"))
result = ci.reorder_categories(["d", "c", "b", "a"], ordered=True)
tm.assert_index_equal(
result,
CategoricalIndex(list("abcdda"), categories=list("dcba"), ordered=True),
)
result = result.remove_categories(["c"])
tm.assert_index_equal(
result,
CategoricalIndex(
["a", "b", np.nan, "d", "d", "a"], categories=list("dba"), ordered=True
),
)
def test_contains_rangeindex_categories_no_engine():
ci = CategoricalIndex(range(3))
assert 2 in ci
assert 5 not in ci
assert "_engine" not in ci._cache
| TestCategoricalIndex2 |
python | run-llama__llama_index | llama-index-core/llama_index/core/objects/base_node_mapping.py | {
"start": 414,
"end": 3093
} | class ____(Generic[OT]):
"""Base object node mapping."""
@classmethod
@abstractmethod
def from_objects(
cls, objs: Sequence[OT], *args: Any, **kwargs: Any
) -> "BaseObjectNodeMapping":
"""
Initialize node mapping from a list of objects.
Only needs to be specified if the node mapping
needs to be initialized with a list of objects.
"""
def validate_object(self, obj: OT) -> None:
"""Validate object."""
def add_object(self, obj: OT) -> None:
"""
Add object.
Only needs to be specified if the node mapping
needs to be initialized with a list of objects.
"""
self.validate_object(obj)
self._add_object(obj)
@property
@abstractmethod
def obj_node_mapping(self) -> Dict[Any, Any]:
"""The mapping data structure between node and object."""
@abstractmethod
def _add_object(self, obj: OT) -> None:
"""
Add object.
Only needs to be specified if the node mapping
needs to be initialized with a list of objects.
"""
@abstractmethod
def to_node(self, obj: OT) -> BaseNode:
"""To node."""
def to_nodes(self, objs: Sequence[OT]) -> Sequence[BaseNode]:
return [self.to_node(obj) for obj in objs]
def from_node(self, node: BaseNode) -> OT:
"""From node."""
obj = self._from_node(node)
self.validate_object(obj)
return obj
@abstractmethod
def _from_node(self, node: BaseNode) -> OT:
"""From node."""
@abstractmethod
def persist(
self,
persist_dir: str = DEFAULT_PERSIST_DIR,
obj_node_mapping_fname: str = DEFAULT_PERSIST_FNAME,
) -> None:
"""Persist objs."""
@classmethod
def from_persist_dir(
cls,
persist_dir: str = DEFAULT_PERSIST_DIR,
obj_node_mapping_fname: str = DEFAULT_PERSIST_FNAME,
) -> "BaseObjectNodeMapping[OT]":
"""Load from serialization."""
obj_node_mapping = None
errors = []
for cls in BaseObjectNodeMapping.__subclasses__(): # type: ignore
try:
obj_node_mapping = cls.from_persist_dir(
persist_dir=persist_dir,
obj_node_mapping_fname=obj_node_mapping_fname,
)
break
except (NotImplementedError, pickle.PickleError) as err:
# raise unhandled exception otherwise
errors.append(err)
if obj_node_mapping:
return obj_node_mapping
else:
raise Exception(errors)
| BaseObjectNodeMapping |
python | FactoryBoy__factory_boy | tests/djapp/models.py | {
"start": 830,
"end": 949
} | class ____(models.Model):
foo = models.CharField(max_length=20)
class Meta:
abstract = True
| AbstractBase |
python | coleifer__peewee | playhouse/cockroachdb.py | {
"start": 1658,
"end": 1990
} | class ____(AutoField):
field_type = 'INT'
def __init__(self, *args, **kwargs):
if kwargs.get('constraints'):
raise ValueError('%s cannot specify constraints.' % type(self))
kwargs['constraints'] = [SQL('DEFAULT unique_rowid()')]
super(RowIDField, self).__init__(*args, **kwargs)
| RowIDField |
python | getsentry__sentry | src/sentry/seer/similarity/types.py | {
"start": 260,
"end": 372
} | class ____(StrEnum):
"""Model version for similarity grouping."""
V1 = "v1"
V2 = "v2"
| GroupingVersion |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 98701,
"end": 103822
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(40)),
)
Table(
"t2",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(40)),
Column("t1id", Integer, ForeignKey("t1.id")),
)
class Case:
def __init__(
self,
Ba_err=False,
Abs_err=False,
map_err=False,
Ba_evt=False,
Abs_evt=False,
):
self.B_a_init_error = Ba_err
self.A_bs_init_error = Abs_err
self.map_error = map_err
self.B_a_event = Ba_evt
self.A_bs_event = Abs_evt
def __repr__(self):
return str(self.__dict__)
cases = {
# (B_a_view, B_a_sync, A_bs_view, A_bs_sync)
(0, 0, 0, 0): Case(),
(0, 0, 0, 1): Case(Abs_evt=1),
(0, 0, 1, 0): Case(),
(0, 0, 1, 1): Case(Abs_err=1),
(0, 1, 0, 0): Case(Ba_evt=1),
(0, 1, 0, 1): Case(Ba_evt=1, Abs_evt=1),
(0, 1, 1, 0): Case(map_err="BA"),
(0, 1, 1, 1): Case(Abs_err=1),
(1, 0, 0, 0): Case(),
(1, 0, 0, 1): Case(map_err="AB"),
(1, 0, 1, 0): Case(),
(1, 0, 1, 1): Case(Abs_err=1),
(1, 1, 0, 0): Case(Ba_err=1),
(1, 1, 0, 1): Case(Ba_err=1),
(1, 1, 1, 0): Case(Ba_err=1),
(1, 1, 1, 1): Case(Abs_err=1),
(0, None, 0, 0): Case(Ba_evt=1),
(0, None, 0, 1): Case(Ba_evt=1, Abs_evt=1),
(0, None, 1, 0): Case(),
(0, None, 1, 1): Case(Abs_err=1),
(1, None, 0, 0): Case(),
(1, None, 0, 1): Case(map_err="AB"),
(1, None, 1, 0): Case(),
(1, None, 1, 1): Case(Abs_err=1),
(0, 0, 0, None): Case(Abs_evt=1),
(0, 0, 1, None): Case(),
(0, 1, 0, None): Case(Ba_evt=1, Abs_evt=1),
(0, 1, 1, None): Case(map_err="BA"),
(1, 0, 0, None): Case(),
(1, 0, 1, None): Case(),
(1, 1, 0, None): Case(Ba_err=1),
(1, 1, 1, None): Case(Ba_err=1),
(0, None, 0, None): Case(Ba_evt=1, Abs_evt=1),
(0, None, 1, None): Case(),
(1, None, 0, None): Case(),
(1, None, 1, None): Case(),
}
@testing.combinations(True, False, None, argnames="A_bs_sync")
@testing.combinations(True, False, argnames="A_bs_view")
@testing.combinations(True, False, None, argnames="B_a_sync")
@testing.combinations(True, False, argnames="B_a_view")
def test_case(self, B_a_view, B_a_sync, A_bs_view, A_bs_sync):
class A(ComparableEntity):
pass
class B(ComparableEntity):
pass
case = self.cases[(B_a_view, B_a_sync, A_bs_view, A_bs_sync)]
print(
{
"B_a_view": B_a_view,
"B_a_sync": B_a_sync,
"A_bs_view": A_bs_view,
"A_bs_sync": A_bs_sync,
},
case,
)
def rel():
return relationship(
B,
viewonly=A_bs_view,
sync_backref=A_bs_sync,
backref=backref("a", viewonly=B_a_view, sync_backref=B_a_sync),
)
if case.A_bs_init_error:
assert_raises_message(
exc.ArgumentError,
"sync_backref and viewonly cannot both be True",
rel,
)
return
self.mapper_registry.map_imperatively(
A,
self.tables.t1,
properties={"bs": rel()},
)
self.mapper_registry.map_imperatively(B, self.tables.t2)
if case.B_a_init_error:
assert_raises_message(
exc.ArgumentError,
"sync_backref and viewonly cannot both be True",
configure_mappers,
)
return
if case.map_error:
if case.map_error == "AB":
args = ("A.bs", "B.a")
else:
args = ("B.a", "A.bs")
assert_raises_message(
exc.InvalidRequestError,
"Relationship %s cannot specify sync_backref=True since %s "
% args,
configure_mappers,
)
return
configure_mappers()
a1 = A()
b1 = B()
b1.a = a1
assert (b1 in a1.bs) == case.B_a_event
assert inspect(a1).attrs.bs.history.has_changes() == case.B_a_event
assert inspect(b1).attrs.a.history.has_changes() == (not B_a_view)
a2 = A()
b2 = B()
a2.bs.append(b2)
assert (b2.a == a2) == case.A_bs_event
assert inspect(a2).attrs.bs.history.has_changes() == (not A_bs_view)
assert inspect(b2).attrs.a.history.has_changes() == case.A_bs_event
| ViewOnlySyncBackref |
python | huggingface__transformers | src/transformers/models/seed_oss/modeling_seed_oss.py | {
"start": 18839,
"end": 22303
} | class ____(SeedOssPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = SeedOssModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs: Unpack[TransformersKwargs],
) -> CausalLMOutputWithPast:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example:
```python
>>> from transformers import AutoTokenizer, SeedOssForCausalLM
>>> model = SeedOssForCausalLM.from_pretrained("ByteDance-Seed/SeedOss-36B")
>>> tokenizer = AutoTokenizer.from_pretrained("ByteDance-Seed/SeedOss-36B")
>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```"""
outputs: BaseModelOutputWithPast = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs.last_hidden_state
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
| SeedOssForCausalLM |
python | Textualize__rich | rich/traceback.py | {
"start": 8347,
"end": 35727
} | class ____:
"""A Console renderable that renders a traceback.
Args:
trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
the last exception.
width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.
extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
theme (str, optional): Override pygments theme used in traceback.
word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
show_locals (bool, optional): Enable display of local variables. Defaults to False.
indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
Defaults to 10.
locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
"""
LEXERS = {
"": "text",
".py": "python",
".pxd": "cython",
".pyx": "cython",
".pxi": "pyrex",
}
def __init__(
self,
trace: Optional[Trace] = None,
*,
width: Optional[int] = 100,
code_width: Optional[int] = 88,
extra_lines: int = 3,
theme: Optional[str] = None,
word_wrap: bool = False,
show_locals: bool = False,
locals_max_length: int = LOCALS_MAX_LENGTH,
locals_max_string: int = LOCALS_MAX_STRING,
locals_hide_dunder: bool = True,
locals_hide_sunder: bool = False,
indent_guides: bool = True,
suppress: Iterable[Union[str, ModuleType]] = (),
max_frames: int = 100,
):
if trace is None:
exc_type, exc_value, traceback = sys.exc_info()
if exc_type is None or exc_value is None or traceback is None:
raise ValueError(
"Value for 'trace' required if not called in except: block"
)
trace = self.extract(
exc_type, exc_value, traceback, show_locals=show_locals
)
self.trace = trace
self.width = width
self.code_width = code_width
self.extra_lines = extra_lines
self.theme = Syntax.get_theme(theme or "ansi_dark")
self.word_wrap = word_wrap
self.show_locals = show_locals
self.indent_guides = indent_guides
self.locals_max_length = locals_max_length
self.locals_max_string = locals_max_string
self.locals_hide_dunder = locals_hide_dunder
self.locals_hide_sunder = locals_hide_sunder
self.suppress: Sequence[str] = []
for suppress_entity in suppress:
if not isinstance(suppress_entity, str):
assert (
suppress_entity.__file__ is not None
), f"{suppress_entity!r} must be a module with '__file__' attribute"
path = os.path.dirname(suppress_entity.__file__)
else:
path = suppress_entity
path = os.path.normpath(os.path.abspath(path))
self.suppress.append(path)
self.max_frames = max(4, max_frames) if max_frames > 0 else 0
@classmethod
def from_exception(
cls,
exc_type: Type[Any],
exc_value: BaseException,
traceback: Optional[TracebackType],
*,
width: Optional[int] = 100,
code_width: Optional[int] = 88,
extra_lines: int = 3,
theme: Optional[str] = None,
word_wrap: bool = False,
show_locals: bool = False,
locals_max_length: int = LOCALS_MAX_LENGTH,
locals_max_string: int = LOCALS_MAX_STRING,
locals_hide_dunder: bool = True,
locals_hide_sunder: bool = False,
indent_guides: bool = True,
suppress: Iterable[Union[str, ModuleType]] = (),
max_frames: int = 100,
) -> "Traceback":
"""Create a traceback from exception info
Args:
exc_type (Type[BaseException]): Exception type.
exc_value (BaseException): Exception value.
traceback (TracebackType): Python Traceback object.
width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.
extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
theme (str, optional): Override pygments theme used in traceback.
word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
show_locals (bool, optional): Enable display of local variables. Defaults to False.
indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
Defaults to 10.
locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
Returns:
Traceback: A Traceback instance that may be printed.
"""
rich_traceback = cls.extract(
exc_type,
exc_value,
traceback,
show_locals=show_locals,
locals_max_length=locals_max_length,
locals_max_string=locals_max_string,
locals_hide_dunder=locals_hide_dunder,
locals_hide_sunder=locals_hide_sunder,
)
return cls(
rich_traceback,
width=width,
code_width=code_width,
extra_lines=extra_lines,
theme=theme,
word_wrap=word_wrap,
show_locals=show_locals,
indent_guides=indent_guides,
locals_max_length=locals_max_length,
locals_max_string=locals_max_string,
locals_hide_dunder=locals_hide_dunder,
locals_hide_sunder=locals_hide_sunder,
suppress=suppress,
max_frames=max_frames,
)
@classmethod
def extract(
cls,
exc_type: Type[BaseException],
exc_value: BaseException,
traceback: Optional[TracebackType],
*,
show_locals: bool = False,
locals_max_length: int = LOCALS_MAX_LENGTH,
locals_max_string: int = LOCALS_MAX_STRING,
locals_hide_dunder: bool = True,
locals_hide_sunder: bool = False,
_visited_exceptions: Optional[Set[BaseException]] = None,
) -> Trace:
"""Extract traceback information.
Args:
exc_type (Type[BaseException]): Exception type.
exc_value (BaseException): Exception value.
traceback (TracebackType): Python Traceback object.
show_locals (bool, optional): Enable display of local variables. Defaults to False.
locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
Defaults to 10.
locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
Returns:
Trace: A Trace instance which you can use to construct a `Traceback`.
"""
stacks: List[Stack] = []
is_cause = False
from rich import _IMPORT_CWD
notes: List[str] = getattr(exc_value, "__notes__", None) or []
grouped_exceptions: Set[BaseException] = (
set() if _visited_exceptions is None else _visited_exceptions
)
def safe_str(_object: Any) -> str:
"""Don't allow exceptions from __str__ to propagate."""
try:
return str(_object)
except Exception:
return "<exception str() failed>"
while True:
stack = Stack(
exc_type=safe_str(exc_type.__name__),
exc_value=safe_str(exc_value),
is_cause=is_cause,
notes=notes,
)
if sys.version_info >= (3, 11):
if isinstance(exc_value, (BaseExceptionGroup, ExceptionGroup)):
stack.is_group = True
for exception in exc_value.exceptions:
if exception in grouped_exceptions:
continue
grouped_exceptions.add(exception)
stack.exceptions.append(
Traceback.extract(
type(exception),
exception,
exception.__traceback__,
show_locals=show_locals,
locals_max_length=locals_max_length,
locals_hide_dunder=locals_hide_dunder,
locals_hide_sunder=locals_hide_sunder,
_visited_exceptions=grouped_exceptions,
)
)
if isinstance(exc_value, SyntaxError):
stack.syntax_error = _SyntaxError(
offset=exc_value.offset or 0,
filename=exc_value.filename or "?",
lineno=exc_value.lineno or 0,
line=exc_value.text or "",
msg=exc_value.msg,
notes=notes,
)
stacks.append(stack)
append = stack.frames.append
def get_locals(
iter_locals: Iterable[Tuple[str, object]],
) -> Iterable[Tuple[str, object]]:
"""Extract locals from an iterator of key pairs."""
if not (locals_hide_dunder or locals_hide_sunder):
yield from iter_locals
return
for key, value in iter_locals:
if locals_hide_dunder and key.startswith("__"):
continue
if locals_hide_sunder and key.startswith("_"):
continue
yield key, value
for frame_summary, line_no in walk_tb(traceback):
filename = frame_summary.f_code.co_filename
last_instruction: Optional[Tuple[Tuple[int, int], Tuple[int, int]]]
last_instruction = None
if sys.version_info >= (3, 11):
instruction_index = frame_summary.f_lasti // 2
instruction_position = next(
islice(
frame_summary.f_code.co_positions(),
instruction_index,
instruction_index + 1,
)
)
(
start_line,
end_line,
start_column,
end_column,
) = instruction_position
if (
start_line is not None
and end_line is not None
and start_column is not None
and end_column is not None
):
last_instruction = (
(start_line, start_column),
(end_line, end_column),
)
if filename and not filename.startswith("<"):
if not os.path.isabs(filename):
filename = os.path.join(_IMPORT_CWD, filename)
if frame_summary.f_locals.get("_rich_traceback_omit", False):
continue
frame = Frame(
filename=filename or "?",
lineno=line_no,
name=frame_summary.f_code.co_name,
locals=(
{
key: pretty.traverse(
value,
max_length=locals_max_length,
max_string=locals_max_string,
)
for key, value in get_locals(frame_summary.f_locals.items())
if not (inspect.isfunction(value) or inspect.isclass(value))
}
if show_locals
else None
),
last_instruction=last_instruction,
)
append(frame)
if frame_summary.f_locals.get("_rich_traceback_guard", False):
del stack.frames[:]
if not grouped_exceptions:
cause = getattr(exc_value, "__cause__", None)
if cause is not None and cause is not exc_value:
exc_type = cause.__class__
exc_value = cause
# __traceback__ can be None, e.g. for exceptions raised by the
# 'multiprocessing' module
traceback = cause.__traceback__
is_cause = True
continue
cause = exc_value.__context__
if cause is not None and not getattr(
exc_value, "__suppress_context__", False
):
exc_type = cause.__class__
exc_value = cause
traceback = cause.__traceback__
is_cause = False
continue
# No cover, code is reached but coverage doesn't recognize it.
break # pragma: no cover
trace = Trace(stacks=stacks)
return trace
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
theme = self.theme
background_style = theme.get_background_style()
token_style = theme.get_style_for_token
traceback_theme = Theme(
{
"pretty": token_style(TextToken),
"pygments.text": token_style(Token),
"pygments.string": token_style(String),
"pygments.function": token_style(Name.Function),
"pygments.number": token_style(Number),
"repr.indent": token_style(Comment) + Style(dim=True),
"repr.str": token_style(String),
"repr.brace": token_style(TextToken) + Style(bold=True),
"repr.number": token_style(Number),
"repr.bool_true": token_style(Keyword.Constant),
"repr.bool_false": token_style(Keyword.Constant),
"repr.none": token_style(Keyword.Constant),
"scope.border": token_style(String.Delimiter),
"scope.equals": token_style(Operator),
"scope.key": token_style(Name),
"scope.key.special": token_style(Name.Constant) + Style(dim=True),
},
inherit=False,
)
highlighter = ReprHighlighter()
@group()
def render_stack(stack: Stack, last: bool) -> RenderResult:
if stack.frames:
stack_renderable: ConsoleRenderable = Panel(
self._render_stack(stack),
title="[traceback.title]Traceback [dim](most recent call last)",
style=background_style,
border_style="traceback.border",
expand=True,
padding=(0, 1),
)
stack_renderable = Constrain(stack_renderable, self.width)
with console.use_theme(traceback_theme):
yield stack_renderable
if stack.syntax_error is not None:
with console.use_theme(traceback_theme):
yield Constrain(
Panel(
self._render_syntax_error(stack.syntax_error),
style=background_style,
border_style="traceback.border.syntax_error",
expand=True,
padding=(0, 1),
width=self.width,
),
self.width,
)
yield Text.assemble(
(f"{stack.exc_type}: ", "traceback.exc_type"),
highlighter(stack.syntax_error.msg),
)
elif stack.exc_value:
yield Text.assemble(
(f"{stack.exc_type}: ", "traceback.exc_type"),
highlighter(stack.exc_value),
)
else:
yield Text.assemble((f"{stack.exc_type}", "traceback.exc_type"))
for note in stack.notes:
yield Text.assemble(("[NOTE] ", "traceback.note"), highlighter(note))
if stack.is_group:
for group_no, group_exception in enumerate(stack.exceptions, 1):
grouped_exceptions: List[Group] = []
for group_last, group_stack in loop_last(group_exception.stacks):
grouped_exceptions.append(render_stack(group_stack, group_last))
yield ""
yield Constrain(
Panel(
Group(*grouped_exceptions),
title=f"Sub-exception #{group_no}",
border_style="traceback.group.border",
),
self.width,
)
if not last:
if stack.is_cause:
yield Text.from_markup(
"\n[i]The above exception was the direct cause of the following exception:\n",
)
else:
yield Text.from_markup(
"\n[i]During handling of the above exception, another exception occurred:\n",
)
for last, stack in loop_last(reversed(self.trace.stacks)):
yield render_stack(stack, last)
@group()
def _render_syntax_error(self, syntax_error: _SyntaxError) -> RenderResult:
highlighter = ReprHighlighter()
path_highlighter = PathHighlighter()
if syntax_error.filename != "<stdin>":
if os.path.exists(syntax_error.filename):
text = Text.assemble(
(f" {syntax_error.filename}", "pygments.string"),
(":", "pygments.text"),
(str(syntax_error.lineno), "pygments.number"),
style="pygments.text",
)
yield path_highlighter(text)
syntax_error_text = highlighter(syntax_error.line.rstrip())
syntax_error_text.no_wrap = True
offset = min(syntax_error.offset - 1, len(syntax_error_text))
syntax_error_text.stylize("bold underline", offset, offset)
syntax_error_text += Text.from_markup(
"\n" + " " * offset + "[traceback.offset]▲[/]",
style="pygments.text",
)
yield syntax_error_text
@classmethod
def _guess_lexer(cls, filename: str, code: str) -> str:
ext = os.path.splitext(filename)[-1]
if not ext:
# No extension, look at first line to see if it is a hashbang
# Note, this is an educated guess and not a guarantee
# If it fails, the only downside is that the code is highlighted strangely
new_line_index = code.index("\n")
first_line = code[:new_line_index] if new_line_index != -1 else code
if first_line.startswith("#!") and "python" in first_line.lower():
return "python"
try:
return cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name
except ClassNotFound:
return "text"
@group()
def _render_stack(self, stack: Stack) -> RenderResult:
path_highlighter = PathHighlighter()
theme = self.theme
def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]:
if frame.locals:
yield render_scope(
frame.locals,
title="locals",
indent_guides=self.indent_guides,
max_length=self.locals_max_length,
max_string=self.locals_max_string,
)
exclude_frames: Optional[range] = None
if self.max_frames != 0:
exclude_frames = range(
self.max_frames // 2,
len(stack.frames) - self.max_frames // 2,
)
excluded = False
for frame_index, frame in enumerate(stack.frames):
if exclude_frames and frame_index in exclude_frames:
excluded = True
continue
if excluded:
assert exclude_frames is not None
yield Text(
f"\n... {len(exclude_frames)} frames hidden ...",
justify="center",
style="traceback.error",
)
excluded = False
first = frame_index == 0
frame_filename = frame.filename
suppressed = any(frame_filename.startswith(path) for path in self.suppress)
if os.path.exists(frame.filename):
text = Text.assemble(
path_highlighter(Text(frame.filename, style="pygments.string")),
(":", "pygments.text"),
(str(frame.lineno), "pygments.number"),
" in ",
(frame.name, "pygments.function"),
style="pygments.text",
)
else:
text = Text.assemble(
"in ",
(frame.name, "pygments.function"),
(":", "pygments.text"),
(str(frame.lineno), "pygments.number"),
style="pygments.text",
)
if not frame.filename.startswith("<") and not first:
yield ""
yield text
if frame.filename.startswith("<"):
yield from render_locals(frame)
continue
if not suppressed:
try:
code_lines = linecache.getlines(frame.filename)
code = "".join(code_lines)
if not code:
# code may be an empty string if the file doesn't exist, OR
# if the traceback filename is generated dynamically
continue
lexer_name = self._guess_lexer(frame.filename, code)
syntax = Syntax(
code,
lexer_name,
theme=theme,
line_numbers=True,
line_range=(
frame.lineno - self.extra_lines,
frame.lineno + self.extra_lines,
),
highlight_lines={frame.lineno},
word_wrap=self.word_wrap,
code_width=self.code_width,
indent_guides=self.indent_guides,
dedent=False,
)
yield ""
except Exception as error:
yield Text.assemble(
(f"\n{error}", "traceback.error"),
)
else:
if frame.last_instruction is not None:
start, end = frame.last_instruction
# Stylize a line at a time
# So that indentation isn't underlined (which looks bad)
for line1, column1, column2 in _iter_syntax_lines(start, end):
try:
if column1 == 0:
line = code_lines[line1 - 1]
column1 = len(line) - len(line.lstrip())
if column2 == -1:
column2 = len(code_lines[line1 - 1])
except IndexError:
# Being defensive here
# If last_instruction reports a line out-of-bounds, we don't want to crash
continue
syntax.stylize_range(
style="traceback.error_range",
start=(line1, column1),
end=(line1, column2),
)
yield (
Columns(
[
syntax,
*render_locals(frame),
],
padding=1,
)
if frame.locals
else syntax
)
if __name__ == "__main__": # pragma: no cover
install(show_locals=True)
import sys
def bar(
a: Any,
) -> None: # 这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑
one = 1
print(one / a)
def foo(a: Any) -> None:
_rich_traceback_guard = True
zed = {
"characters": {
"Paul Atreides",
"Vladimir Harkonnen",
"Thufir Hawat",
"Duncan Idaho",
},
"atomic_types": (None, False, True),
}
bar(a)
def error() -> None:
foo(0)
error()
| Traceback |
python | huggingface__transformers | src/transformers/models/cohere2/modular_cohere2.py | {
"start": 15856,
"end": 18706
} | class ____(Gemma2Model):
def __init__(self, config: Cohere2Config):
super().__init__(config)
self.norm = Cohere2LayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if use_cache and past_key_values is None and not self.training:
past_key_values = DynamicCache(config=self.config)
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
if not isinstance(causal_mask_mapping := attention_mask, dict):
mask_kwargs = {
"config": self.config,
"input_embeds": inputs_embeds,
"attention_mask": attention_mask,
"cache_position": cache_position,
"past_key_values": past_key_values,
"position_ids": position_ids,
}
causal_mask_mapping = {
"full_attention": create_causal_mask(**mask_kwargs),
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
}
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers:
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
position_embeddings=position_embeddings,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_ids=position_ids,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
| Cohere2Model |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py | {
"start": 30336,
"end": 32039
} | class ____(TestDagEndpoint):
"""Unit tests for unfavoriting a DAG."""
@pytest.mark.parametrize(
("dag_id", "expected_status_code", "expected_exist_in_favorites"),
[
("fake_dag_id", 404, None),
(DAG1_ID, 204, False),
],
)
def test_unfavorite_dag(
self, test_client, dag_id, expected_status_code, expected_exist_in_favorites, session
):
if dag_id != "fake_dag_id":
session.execute(insert(DagFavorite).values(dag_id=dag_id, user_id="test"))
session.commit()
response = test_client.post(f"/dags/{dag_id}/unfavorite")
assert response.status_code == expected_status_code
if expected_status_code == 204:
result = session.execute(
select(DagFavorite).where(DagFavorite.dag_id == dag_id, DagFavorite.user_id == "test")
).first()
assert result is not None if expected_exist_in_favorites else result is None
check_last_log(session, dag_id=dag_id, event="unfavorite_dag", logical_date=None)
def test_unfavorite_dag_should_response_401(self, unauthenticated_test_client):
response = unauthenticated_test_client.post(f"/dags/{DAG1_ID}/unfavorite")
assert response.status_code == 401
def test_unfavorite_dag_should_response_403(self, unauthorized_test_client):
response = unauthorized_test_client.post(f"/dags/{DAG1_ID}/unfavorite")
assert response.status_code == 403
def test_unfavoriting_dag_that_is_not_favorite_returns_409(self, test_client):
response = test_client.post(f"/dags/{DAG1_ID}/unfavorite")
assert response.status_code == 409
| TestUnfavoriteDag |
python | allegroai__clearml | examples/advanced/model_embedding.py | {
"start": 1617,
"end": 7269
} | class ____:
"""
Persistent store for documents and their embeddings.
"""
def __init__(
self,
embedding_service: EmbeddingService,
store_path: str = "embeddings_store.json",
similarity: str = "cosine",
):
self.embedding_service = embedding_service
self.similarity = similarity
self.store_path = store_path
self.docs: List[Dict[str, Any]] = []
self._load_store()
def _load_store(self):
if os.path.exists(self.store_path):
with open(self.store_path, "r", encoding="utf-8") as f:
raw = json.load(f)
for item in raw:
self.docs.append(
{
"id": item["id"],
"text": item["text"],
"embedding": np.array(item["embedding"], dtype=np.float32),
}
)
def _save_store(self):
serializable = []
for doc in self.docs:
serializable.append(
{
"id": doc["id"],
"text": doc["text"],
"embedding": doc["embedding"].tolist(),
}
)
with open(self.store_path, "w", encoding="utf-8") as f:
json.dump(serializable, f, ensure_ascii=False, indent=2)
def add_document(self, identifier: str, text: str):
"""
Add a single document chunk by extracting its embedding.
"""
embedding = self.embedding_service.embed([text])[0]
vec = np.array(embedding, dtype=np.float32)
self.docs.append({"id": identifier, "text": text, "embedding": vec})
self._save_store()
def query(self, query_text: str, top_k: int = 5) -> List[Dict[str, Any]]:
"""
Query the store for the top_k most similar document chunks.
"""
q_emb = np.array(
self.embedding_service.embed([query_text])[0], dtype=np.float32
)
results = []
for doc in self.docs:
d_emb = doc["embedding"]
if self.similarity == "cosine":
sim = np.dot(q_emb, d_emb) / (
np.linalg.norm(q_emb) * np.linalg.norm(d_emb)
)
elif self.similarity == "dot":
sim = np.dot(q_emb, d_emb)
else:
raise ValueError(f"Unknown similarity metric: {self.similarity}")
results.append({"id": doc["id"], "score": float(sim), "text": doc["text"]})
results.sort(key=lambda x: x["score"], reverse=True)
return results[:top_k]
def load_text(path: str) -> str:
"""
Load plain text or extract text from PDF.
"""
if not os.path.exists(path):
raise FileNotFoundError(f"File not found: {path}")
if path.lower().endswith(".pdf"):
reader = PdfReader(path)
pages = [page.extract_text() or "" for page in reader.pages]
return "\n".join(pages)
with open(path, "r", encoding="utf-8") as f:
return f.read()
def main():
parser = argparse.ArgumentParser(
description="Persistent embedding service with chunking"
)
parser.add_argument(
"--api-url",
required=True,
help="Embedding service URL endpoint as seen in ClearML UI",
)
parser.add_argument(
"--model", required=True, help="Embedding model name as seen in ClearML UI"
)
parser.add_argument(
"--store-file",
default="embeddings_store.json",
help="Path to persistent embeddings store",
)
parser.add_argument(
"--chunk-size",
type=int,
default=1000,
help="Max characters per chunk when ingesting large files",
)
subparsers = parser.add_subparsers(dest="command", help="Commands: ingest, query")
ingest_parser = subparsers.add_parser(
"ingest", help="Ingest documents for embedding"
)
ingest_parser.add_argument(
"files", nargs="+", help="Paths to document files (txt or pdf)"
)
query_parser = subparsers.add_parser("query", help="Query nearest document chunks")
query_parser.add_argument("text", help="Query text")
query_parser.add_argument(
"--top-k", type=int, default=5, help="Number of top results to return"
)
query_parser.add_argument(
"--metric",
choices=["cosine", "dot"],
default="cosine",
help="Similarity metric",
)
args = parser.parse_args()
service = EmbeddingService(api_url=args.api_url, model=args.model)
store = DocumentStore(
embedding_service=service,
store_path=args.store_file,
similarity=getattr(args, "metric", "cosine"),
)
if args.command == "ingest":
for filepath in args.files:
print(f"Loading {filepath}...")
txt = load_text(filepath)
chunks = chunk_text(txt, args.chunk_size)
base_id = os.path.basename(filepath)
for i, chunk in enumerate(chunks, start=1):
chunk_id = f"{base_id}::chunk{i}"
store.add_document(chunk_id, chunk)
print(f"Ingested {len(store.docs)} chunks (persisted to {args.store_file}).")
elif args.command == "query":
results = store.query(args.text, top_k=args.top_k)
print(f"Top {len(results)} results:")
for idx, res in enumerate(results, start=1):
print(
f"{idx}. ID: {res['id']}, Score: {res['score']:.4f}\n{res['text'][:200]}...\n"
)
else:
parser.print_help()
if __name__ == "__main__":
main()
| DocumentStore |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 56832,
"end": 56891
} | class ____(_TestNorm2D, _TestNormGeneral):
pass
| _TestNorm |
python | prabhupant__python-ds | data_structures/queue/queue.py | {
"start": 0,
"end": 893
} | class ____:
"""
Queue is an abstract data structure, somewhat similar to Stacks.
Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue)
and the other is used to remove data (dequeue).
Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first.
"""
def __init__(self):
self.entries = []
self.length = 0
self.front = 0
def put(self, item):
self.entries.append(item)
self.length += 1
def get(self):
if self.length <= 0:
return
self.length -= 1
de_queued = self.entries[self.front]
self.entries = self.entries[1:]
return de_queued
def rotate(self, rotation):
for i in range(rotation):
self.put(self.get())
def size(self):
return self.length
| Queue |
python | pennersr__django-allauth | allauth/socialaccount/providers/steam/provider.py | {
"start": 532,
"end": 1668
} | class ____(OpenIDAccount):
def to_str(self):
dflt = super(SteamAccount, self).to_str()
return self.account.extra_data.get("personaname", dflt)
def get_profile_url(self):
return self.account.extra_data.get("profileurl")
def get_avatar_url(self):
return (
self.account.extra_data.get("avatarfull")
or self.account.extra_data.get("avatarmedium")
or self.account.extra_data.get("avatar")
)
def extract_steam_id(url):
prefix = "https://steamcommunity.com/openid/id/"
if not url.startswith(prefix):
raise ValueError(url)
return url[len(prefix) :]
def request_steam_account_summary(api_key, steam_id):
api_base = "https://api.steampowered.com/"
method = "ISteamUser/GetPlayerSummaries/v0002/"
params = {"key": api_key, "steamids": steam_id}
resp = get_adapter().get_requests_session().get(api_base + method, params=params)
resp.raise_for_status()
data = resp.json()
playerlist = data.get("response", {}).get("players", [])
return playerlist[0] if playerlist else {"steamid": steam_id}
| SteamAccount |
python | kamyu104__LeetCode-Solutions | Python/maximum-enemy-forts-that-can-be-captured.py | {
"start": 51,
"end": 453
} | class ____(object):
def captureForts(self, forts):
"""
:type forts: List[int]
:rtype: int
"""
result = left = 0
for right in xrange(len(forts)):
if not forts[right]:
continue
if forts[right] == -forts[left]:
result = max(result, right-left-1)
left = right
return result
| Solution |
python | tensorflow__tensorflow | tensorflow/tools/compatibility/ast_edits_test.py | {
"start": 3385,
"end": 3843
} | class ____(RemoveDeprecatedAliasKeyword):
"""A specification where kw1_alias is removed in g.
The new API is
def g(a, b, c, kw1): ...
def g2(a, b, c, d, kw1): ...
"""
def __init__(self):
RemoveDeprecatedAliasKeyword.__init__(self)
# Note that these should be in the old order.
self.function_reorders["g"] = ["a", "b", "kw1", "c"]
self.function_reorders["g2"] = ["a", "b", "kw1", "c", "d"]
| RemoveDeprecatedAliasAndReorderRest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 484185,
"end": 484555
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("CWE", graphql_name="node")
"""The item at the end of the edge."""
| CWEEdge |
python | getsentry__sentry | tests/sentry/users/web/test_user_avatar.py | {
"start": 333,
"end": 1044
} | class ____(TestCase):
def test_headers_control_file(self) -> None:
user = self.create_user(email="a@example.com")
photo = ControlFile.objects.create(name="test.png", type="avatar.file")
photo.putfile(BytesIO(b"test"))
avatar = UserAvatar.objects.create(user=user, control_file_id=photo.id)
url = reverse("sentry-user-avatar-url", kwargs={"avatar_id": avatar.ident})
response = self.client.get(url)
assert response.status_code == 200
assert response["Cache-Control"] == FOREVER_CACHE
assert response.get("Vary") is None
assert response.get("Set-Cookie") is None
assert response["Access-Control-Allow-Origin"]
| UserAvatarTest |
python | paramiko__paramiko | paramiko/pipe.py | {
"start": 1271,
"end": 1977
} | class ____:
def __init__(self):
self._rfd, self._wfd = os.pipe()
self._set = False
self._forever = False
self._closed = False
def close(self):
os.close(self._rfd)
os.close(self._wfd)
# used for unit tests:
self._closed = True
def fileno(self):
return self._rfd
def clear(self):
if not self._set or self._forever:
return
os.read(self._rfd, 1)
self._set = False
def set(self):
if self._set or self._closed:
return
self._set = True
os.write(self._wfd, b"*")
def set_forever(self):
self._forever = True
self.set()
| PosixPipe |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_translate.py | {
"start": 3101,
"end": 7933
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.cloud.hooks.translate.TranslateHook.__init__",
new=mock_base_gcp_hook_default_project_id,
):
self.hook = TranslateHook(gcp_conn_id="test")
@mock.patch("airflow.providers.google.cloud.hooks.translate.TranslateHook.get_credentials")
@mock.patch("airflow.providers.google.cloud.hooks.translate.TranslationServiceClient")
def test_translate_client_creation(self, mock_client, mock_get_creds):
result = self.hook.get_client()
mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO)
assert mock_client.return_value == result
assert self.hook._client == result
@mock.patch("airflow.providers.google.cloud.hooks.translate.TranslateHook.get_client")
def test_translate_text_method(self, get_client):
translation_result_data = {
"translations": [
{"translated_text": "Hello World!", "model": "", "detected_language_code": ""},
{
"translated_text": "Can you get me a cup of coffee, please?",
"model": "",
"detected_language_code": "",
},
],
"glossary_translations": [],
}
data_to_translate = ["Ciao mondo!", "Mi puoi prendere una tazza di caffè, per favore?"]
translate_client = get_client.return_value
translate_text_client_method = translate_client.translate_text
translate_text_client_method.return_value = TranslateTextResponse(translation_result_data)
input_translation_args = dict(
project_id=PROJECT_ID_TEST,
contents=data_to_translate,
source_language_code="it",
target_language_code="en",
mime_type="text/plain",
location="global",
glossary_config=None,
transliteration_config=None,
model=None,
labels=None,
metadata=(),
timeout=30,
retry=None,
)
result = self.hook.translate_text(**input_translation_args)
assert result == translation_result_data
expected_call_args = {
"request": {
"parent": f"projects/{PROJECT_ID_TEST}/locations/global",
"contents": data_to_translate,
"source_language_code": "it",
"target_language_code": "en",
"mime_type": "text/plain",
"glossary_config": None,
"transliteration_config": None,
"model": None,
"labels": None,
},
"retry": None,
"metadata": (),
"timeout": 30,
}
translate_text_client_method.assert_called_once_with(**expected_call_args)
@mock.patch("airflow.providers.google.cloud.hooks.translate.TranslateHook.get_client")
def test_batch_translate_text_method(self, get_client):
sample_method_result = "batch_translate_api_call_result_obj"
translate_client = get_client.return_value
translate_text_client_method = translate_client.batch_translate_text
translate_text_client_method.return_value = sample_method_result
BATCH_TRANSLATE_INPUT = {
"gcs_source": {"input_uri": "input_source_uri"},
"mime_type": "text/plain",
}
GCS_OUTPUT_DST = {"gcs_destination": {"output_uri_prefix": "translate_output_uri_prefix"}}
LOCATION = "us-central1"
input_translation_args = dict(
project_id=PROJECT_ID_TEST,
source_language_code="de",
target_language_codes=["en", "uk"],
location=LOCATION,
input_configs=[BATCH_TRANSLATE_INPUT],
output_config=GCS_OUTPUT_DST,
glossaries=None,
models=None,
labels=None,
metadata=(),
timeout=30,
retry=None,
)
result = self.hook.batch_translate_text(**input_translation_args)
expected_call_args = {
"request": {
"parent": f"projects/{PROJECT_ID_TEST}/locations/{LOCATION}",
"source_language_code": "de",
"target_language_codes": ["en", "uk"],
"input_configs": [BATCH_TRANSLATE_INPUT],
"output_config": GCS_OUTPUT_DST,
"glossaries": None,
"models": None,
"labels": None,
},
"retry": None,
"metadata": (),
"timeout": 30,
}
translate_text_client_method.assert_called_once_with(**expected_call_args)
assert result == sample_method_result
| TestTranslateHook |
python | getsentry__sentry | tests/sentry/sudo/test_middleware.py | {
"start": 320,
"end": 4046
} | class ____(BaseTestCase):
middleware = SudoMiddleware(placeholder_get_response)
def assertSignedCookieEqual(self, v1, v2, reason=None):
value, _, _ = v1.split(":")
return self.assertEqual(value, v2, reason)
def test_process_request_raises_without_session(self) -> None:
del self.request.session
with pytest.raises(AssertionError):
self.middleware.process_request(self.request)
def test_process_request_adds_is_sudo(self) -> None:
self.middleware.process_request(self.request)
self.assertFalse(self.request.is_sudo())
def test_process_response_noop(self) -> None:
response = self.middleware.process_response(self.request, HttpResponse())
self.assertEqual(len(response.cookies.items()), 0)
def test_process_response_with_sudo_sets_cookie(self) -> None:
self.login()
self.middleware.process_request(self.request)
grant_sudo_privileges(self.request)
response = self.middleware.process_response(self.request, HttpResponse())
morsels = list(response.cookies.items())
self.assertEqual(len(morsels), 1)
self.assertEqual(morsels[0][0], COOKIE_NAME)
_, sudo = morsels[0]
self.assertEqual(sudo.key, COOKIE_NAME)
self.assertSignedCookieEqual(sudo.value, self.request._sudo_token)
self.assertEqual(sudo["max-age"], self.request._sudo_max_age)
self.assertTrue(sudo["httponly"])
# Asserting that these are insecure together explicitly
# since it's a big deal to not bungle.
self.assertFalse(self.request.is_secure())
self.assertFalse(sudo["secure"]) # insecure request
def test_process_response_sets_secure_cookie(self) -> None:
self.login()
self.request.is_secure = lambda: True
self.middleware.process_request(self.request)
grant_sudo_privileges(self.request)
response = self.middleware.process_response(self.request, HttpResponse())
morsels = list(response.cookies.items())
self.assertEqual(len(morsels), 1)
self.assertEqual(morsels[0][0], COOKIE_NAME)
_, sudo = morsels[0]
self.assertTrue(self.request.is_secure())
# XXX: Even if sudo.settings.COOKIE_SECURE is patched to be None
# from False (from sentry initializer), we need to move the import
# into the middleware's process_response rather than at module level.
# self.assertTrue(sudo["secure"])
def test_process_response_sudo_revoked_removes_cookie(self) -> None:
self.login()
self.middleware.process_request(self.request)
grant_sudo_privileges(self.request)
self.request.COOKIES[COOKIE_NAME] = self.request._sudo_token
revoke_sudo_privileges(self.request)
response = self.middleware.process_response(self.request, HttpResponse())
morsels = list(response.cookies.items())
self.assertEqual(len(morsels), 1)
self.assertEqual(morsels[0][0], COOKIE_NAME)
_, sudo = morsels[0]
# Deleting a cookie is just setting it's value to empty
# and telling it to expire
self.assertEqual(sudo.key, COOKIE_NAME)
self.assertFalse(sudo.value)
self.assertEqual(sudo["max-age"], 0)
def test_process_response_sudo_revoked_without_cookie(self) -> None:
self.login()
self.middleware.process_request(self.request)
grant_sudo_privileges(self.request)
revoke_sudo_privileges(self.request)
response = self.middleware.process_response(self.request, HttpResponse())
morsels = list(response.cookies.items())
self.assertEqual(len(morsels), 0)
| SudoMiddlewareTestCase |
python | openai__openai-python | src/openai/lib/streaming/responses/_events.py | {
"start": 2958,
"end": 5576
} | class ____(RawResponseCompletedEvent, GenericModel, Generic[TextFormatT]):
response: ParsedResponse[TextFormatT] # type: ignore[assignment]
ResponseStreamEvent: TypeAlias = Annotated[
Union[
# wrappers with snapshots added on
ResponseTextDeltaEvent,
ResponseTextDoneEvent[TextFormatT],
ResponseFunctionCallArgumentsDeltaEvent,
ResponseCompletedEvent[TextFormatT],
# the same as the non-accumulated API
ResponseAudioDeltaEvent,
ResponseAudioDoneEvent,
ResponseAudioTranscriptDeltaEvent,
ResponseAudioTranscriptDoneEvent,
ResponseCodeInterpreterCallCodeDeltaEvent,
ResponseCodeInterpreterCallCodeDoneEvent,
ResponseCodeInterpreterCallCompletedEvent,
ResponseCodeInterpreterCallInProgressEvent,
ResponseCodeInterpreterCallInterpretingEvent,
ResponseContentPartAddedEvent,
ResponseContentPartDoneEvent,
ResponseCreatedEvent,
ResponseErrorEvent,
ResponseFileSearchCallCompletedEvent,
ResponseFileSearchCallInProgressEvent,
ResponseFileSearchCallSearchingEvent,
ResponseFunctionCallArgumentsDoneEvent,
ResponseInProgressEvent,
ResponseFailedEvent,
ResponseIncompleteEvent,
ResponseOutputItemAddedEvent,
ResponseOutputItemDoneEvent,
ResponseRefusalDeltaEvent,
ResponseRefusalDoneEvent,
ResponseTextDoneEvent,
ResponseWebSearchCallCompletedEvent,
ResponseWebSearchCallInProgressEvent,
ResponseWebSearchCallSearchingEvent,
ResponseReasoningSummaryPartAddedEvent,
ResponseReasoningSummaryPartDoneEvent,
ResponseReasoningSummaryTextDeltaEvent,
ResponseReasoningSummaryTextDoneEvent,
ResponseImageGenCallCompletedEvent,
ResponseImageGenCallInProgressEvent,
ResponseImageGenCallGeneratingEvent,
ResponseImageGenCallPartialImageEvent,
ResponseMcpCallCompletedEvent,
ResponseMcpCallArgumentsDeltaEvent,
ResponseMcpCallArgumentsDoneEvent,
ResponseMcpCallFailedEvent,
ResponseMcpCallInProgressEvent,
ResponseMcpListToolsCompletedEvent,
ResponseMcpListToolsFailedEvent,
ResponseMcpListToolsInProgressEvent,
ResponseOutputTextAnnotationAddedEvent,
ResponseQueuedEvent,
ResponseReasoningTextDeltaEvent,
ResponseReasoningTextDoneEvent,
ResponseCustomToolCallInputDeltaEvent,
ResponseCustomToolCallInputDoneEvent,
],
PropertyInfo(discriminator="type"),
]
| ResponseCompletedEvent |
python | doocs__leetcode | lcci/17.25.Word Rectangle/Solution.py | {
"start": 0,
"end": 356
} | class ____:
def __init__(self):
self.children = [None] * 26
self.is_end = False
def insert(self, w):
node = self
for c in w:
idx = ord(c) - ord("a")
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True
| Trie |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.