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
plotly__plotly.py
plotly/graph_objs/isosurface/slices/_y.py
{ "start": 233, "end": 5303 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "isosurface.slices" _path_str = "isosurface.slices.y" _valid_props = {"fill", "locations", "locationssrc", "show"} @property def fill(self): """ Sets the fill ratio of the `slices`. The default fill value of the `slices` is 1 meaning that they are entirely shaded. On the other hand Applying a `fill` ratio less than one would allow the creation of openings parallel to the edges. The 'fill' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["fill"] @fill.setter def fill(self, val): self["fill"] = val @property def locations(self): """ Specifies the location(s) of slices on the axis. When not specified slices would be created for all points of the axis y except start and end. The 'locations' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["locations"] @locations.setter def locations(self, val): self["locations"] = val @property def locationssrc(self): """ Sets the source reference on Chart Studio Cloud for `locations`. The 'locationssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["locationssrc"] @locationssrc.setter def locationssrc(self, val): self["locationssrc"] = val @property def show(self): """ Determines whether or not slice planes about the y dimension are drawn. The 'show' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["show"] @show.setter def show(self, val): self["show"] = val @property def _prop_descriptions(self): return """\ fill Sets the fill ratio of the `slices`. The default fill value of the `slices` is 1 meaning that they are entirely shaded. On the other hand Applying a `fill` ratio less than one would allow the creation of openings parallel to the edges. locations Specifies the location(s) of slices on the axis. When not specified slices would be created for all points of the axis y except start and end. locationssrc Sets the source reference on Chart Studio Cloud for `locations`. show Determines whether or not slice planes about the y dimension are drawn. """ def __init__( self, arg=None, fill=None, locations=None, locationssrc=None, show=None, **kwargs, ): """ Construct a new Y object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.isosurface.slices.Y` fill Sets the fill ratio of the `slices`. The default fill value of the `slices` is 1 meaning that they are entirely shaded. On the other hand Applying a `fill` ratio less than one would allow the creation of openings parallel to the edges. locations Specifies the location(s) of slices on the axis. When not specified slices would be created for all points of the axis y except start and end. locationssrc Sets the source reference on Chart Studio Cloud for `locations`. show Determines whether or not slice planes about the y dimension are drawn. Returns ------- Y """ super().__init__("y") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.isosurface.slices.Y constructor must be a dict or an instance of :class:`plotly.graph_objs.isosurface.slices.Y`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("fill", arg, fill) self._set_property("locations", arg, locations) self._set_property("locationssrc", arg, locationssrc) self._set_property("show", arg, show) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Y
python
sqlalchemy__sqlalchemy
test/orm/test_bundle.py
{ "start": 899, "end": 21623 }
class ____(fixtures.MappedTest, AssertsCompiledSQL): __dialect__ = "default" run_inserts = "once" run_setup_mappers = "once" run_deletes = None @classmethod def define_tables(cls, metadata): Table( "data", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("d1", String(10)), Column("d2", String(10)), Column("d3", String(10)), ) Table( "other", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("data_id", ForeignKey("data.id")), Column("o1", String(10)), ) @classmethod def setup_classes(cls): class Data(cls.Basic): pass class Other(cls.Basic): pass @classmethod def setup_mappers(cls): cls.mapper_registry.map_imperatively( cls.classes.Data, cls.tables.data, properties={"others": relationship(cls.classes.Other)}, ) cls.mapper_registry.map_imperatively( cls.classes.Other, cls.tables.other ) @classmethod def insert_data(cls, connection): sess = Session(connection) sess.add_all( [ cls.classes.Data( d1="d%dd1" % i, d2="d%dd2" % i, d3="d%dd3" % i, others=[ cls.classes.Other(o1="d%do%d" % (i, j)) for j in range(5) ], ) for i in range(10) ] ) sess.commit() def test_tuple_suggests_bundle(self, connection): Data, Other = self.classes("Data", "Other") sess = Session(connection) q = sess.query(tuple_(Data.id, Other.id)).join(Data.others) assert_raises_message( exc.CompileError, r"Most backends don't support SELECTing from a tuple\(\) object. " "If this is an ORM query, consider using the Bundle object.", q.all, ) def test_tuple_suggests_bundle_future(self, connection): Data, Other = self.classes("Data", "Other") stmt = select(tuple_(Data.id, Other.id)).join(Data.others) sess = Session(connection, future=True) assert_raises_message( exc.CompileError, r"Most backends don't support SELECTing from a tuple\(\) object. " "If this is an ORM query, consider using the Bundle object.", sess.execute, stmt, ) def test_same_named_col_clauselist(self): Data, Other = self.classes("Data", "Other") bundle = Bundle("pk", Data.id, Other.id) self.assert_compile(ClauseList(Data.id, Other.id), "data.id, other.id") self.assert_compile(bundle.__clause_element__(), "data.id, other.id") def test_dict_same_named_col_clauselist(self): Data, Other = self.classes("Data", "Other") with expect_raises_message( exc.ArgumentError, "DictBundle does not support duplicate column names", ): DictBundle("pk", Data.id, Other.id) def test_same_named_col_in_orderby(self): Data, Other = self.classes("Data", "Other") bundle = Bundle("pk", Data.id, Other.id) sess = fixture_session() self.assert_compile( sess.query(Data, Other).order_by(bundle), "SELECT data.id AS data_id, data.d1 AS data_d1, " "data.d2 AS data_d2, data.d3 AS data_d3, " "other.id AS other_id, other.data_id AS other_data_id, " "other.o1 AS other_o1 " "FROM data, other ORDER BY data.id, other.id", ) def test_same_named_col_in_fetch(self): Data, Other = self.classes("Data", "Other") bundle = Bundle("pk", Data.id, Other.id) sess = fixture_session() eq_( sess.query(bundle) .filter(Data.id == Other.id) .filter(Data.id < 3) .all(), [((1, 1),), ((2, 2),)], ) @testing.combinations(Bundle, DictBundle, argnames="kind") def test_c_attr(self, kind): Data = self.classes.Data b1 = kind("b1", Data.d1, Data.d2) self.assert_compile( select(b1.c.d1, b1.c.d2), "SELECT data.d1, data.d2 FROM data" ) @testing.variation( "stmt_type", ["legacy", "newstyle", "newstyle_w_label_conv"] ) @testing.variation("col_type", ["orm", "core"]) def test_dupe_col_name(self, stmt_type, col_type): """test #11347""" Data = self.classes.Data sess = fixture_session() if col_type.orm: b1 = Bundle("b1", Data.d1, Data.d3) cols = Data.d1, Data.d2 elif col_type.core: data_table = self.tables.data b1 = Bundle("b1", data_table.c.d1, data_table.c.d3) cols = data_table.c.d1, data_table.c.d2 else: col_type.fail() if stmt_type.legacy: row = ( sess.query(cols[0], cols[1], b1) .filter(Data.d1 == "d0d1") .one() ) elif stmt_type.newstyle: row = sess.execute( select(cols[0], cols[1], b1).filter(Data.d1 == "d0d1") ).one() elif stmt_type.newstyle_w_label_conv: row = sess.execute( select(cols[0], cols[1], b1) .filter(Data.d1 == "d0d1") .set_label_style( SelectLabelStyle.LABEL_STYLE_TABLENAME_PLUS_COL ) ).one() else: stmt_type.fail() if stmt_type.newstyle_w_label_conv: # decision is made here that even if a SELECT with the # "tablename_plus_colname" label style, within a Bundle we still # use straight column name, even though the overall row # uses tablename_colname eq_( row._mapping, {"data_d1": "d0d1", "data_d2": "d0d2", "b1": ("d0d1", "d0d3")}, ) else: eq_( row._mapping, {"d1": "d0d1", "d2": "d0d2", "b1": ("d0d1", "d0d3")}, ) eq_(row[2]._mapping, {"d1": "d0d1", "d3": "d0d3"}) @testing.variation( "stmt_type", ["legacy", "newstyle", "newstyle_w_label_conv"] ) @testing.variation("col_type", ["orm", "core"]) def test_dupe_col_name_nested(self, stmt_type, col_type): """test #11347""" Data = self.classes.Data sess = fixture_session() if col_type.core: data_table = self.tables.data b1 = DictBundle("b1", data_table.c.d1, data_table.c.d3) b2 = DictBundle("b2", data_table.c.d2, data_table.c.d3) b3 = DictBundle("b3", data_table.c.d2, data_table.c.d3, b1, b2) elif col_type.orm: b1 = DictBundle("b1", Data.d1, Data.d3) b2 = DictBundle("b2", Data.d2, Data.d3) b3 = DictBundle("b3", Data.d2, Data.d3, b1, b2) else: col_type.fail() if stmt_type.legacy: row = ( sess.query(Data.d1, Data.d2, b3) .filter(Data.d1 == "d0d1") .one() ) elif stmt_type.newstyle: row = sess.execute( select(Data.d1, Data.d2, b3).filter(Data.d1 == "d0d1") ).one() elif stmt_type.newstyle_w_label_conv: row = sess.execute( select(Data.d1, Data.d2, b3) .filter(Data.d1 == "d0d1") .set_label_style( SelectLabelStyle.LABEL_STYLE_TABLENAME_PLUS_COL ) ).one() else: stmt_type.fail() if stmt_type.newstyle_w_label_conv: eq_( row._mapping, { "data_d1": "d0d1", "data_d2": "d0d2", "b3": { "d2": "d0d2", "d3": "d0d3", "b1": {"d1": "d0d1", "d3": "d0d3"}, "b2": {"d2": "d0d2", "d3": "d0d3"}, }, }, ) else: eq_( row._mapping, { "d1": "d0d1", "d2": "d0d2", "b3": { "d2": "d0d2", "d3": "d0d3", "b1": {"d1": "d0d1", "d3": "d0d3"}, "b2": {"d2": "d0d2", "d3": "d0d3"}, }, }, ) eq_( row[2], { "d2": "d0d2", "d3": "d0d3", "b1": {"d1": "d0d1", "d3": "d0d3"}, "b2": {"d2": "d0d2", "d3": "d0d3"}, }, ) def test_result(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle("b1", Data.d1, Data.d2) eq_( sess.query(b1).filter(b1.c.d1.between("d3d1", "d5d1")).all(), [(("d3d1", "d3d2"),), (("d4d1", "d4d2"),), (("d5d1", "d5d2"),)], ) def test_subclass(self): Data = self.classes.Data sess = fixture_session() class MyBundle(Bundle): def create_row_processor(self, query, procs, labels): def proc(row): return list(zip(labels, (proc(row) for proc in procs))) return proc b1 = MyBundle("b1", Data.d1, Data.d2) eq_( sess.query(b1).filter(b1.c.d1.between("d3d1", "d5d1")).all(), [ ([("d1", "d3d1"), ("d2", "d3d2")],), ([("d1", "d4d1"), ("d2", "d4d2")],), ([("d1", "d5d1"), ("d2", "d5d2")],), ], ) def test_multi_bundle(self): Data = self.classes.Data Other = self.classes.Other d1 = aliased(Data) b1 = Bundle("b1", d1.d1, d1.d2) b2 = Bundle("b2", Data.d1, Other.o1) sess = fixture_session() q = ( sess.query(b1, b2) .join(Data.others) .join(d1, d1.id == Data.id) .filter(b1.c.d1 == "d3d1") ) eq_( q.all(), [ (("d3d1", "d3d2"), ("d3d1", "d3o0")), (("d3d1", "d3d2"), ("d3d1", "d3o1")), (("d3d1", "d3d2"), ("d3d1", "d3o2")), (("d3d1", "d3d2"), ("d3d1", "d3o3")), (("d3d1", "d3d2"), ("d3d1", "d3o4")), ], ) def test_multi_bundle_future(self): Data = self.classes.Data Other = self.classes.Other d1 = aliased(Data) b1 = Bundle("b1", d1.d1, d1.d2) b2 = Bundle("b2", Data.d1, Other.o1) sess = Session(testing.db, future=True) stmt = ( select(b1, b2) .join(Data.others) .join(d1, d1.id == Data.id) .filter(b1.c.d1 == "d3d1") ) eq_( sess.execute(stmt).all(), [ (("d3d1", "d3d2"), ("d3d1", "d3o0")), (("d3d1", "d3d2"), ("d3d1", "d3o1")), (("d3d1", "d3d2"), ("d3d1", "d3o2")), (("d3d1", "d3d2"), ("d3d1", "d3o3")), (("d3d1", "d3d2"), ("d3d1", "d3o4")), ], ) def test_single_entity_legacy_query(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle("b1", Data.d1, Data.d2, single_entity=True) eq_( sess.query(b1).filter(b1.c.d1.between("d3d1", "d5d1")).all(), [("d3d1", "d3d2"), ("d4d1", "d4d2"), ("d5d1", "d5d2")], ) def test_labeled_cols_non_single_entity_legacy_query(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle("b1", Data.d1.label("x"), Data.d2.label("y")) eq_( sess.query(b1).filter(b1.c.x.between("d3d1", "d5d1")).all(), [(("d3d1", "d3d2"),), (("d4d1", "d4d2"),), (("d5d1", "d5d2"),)], ) def test_labeled_cols_single_entity_legacy_query(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle( "b1", Data.d1.label("x"), Data.d2.label("y"), single_entity=True ) eq_( sess.query(b1).filter(b1.c.x.between("d3d1", "d5d1")).all(), [("d3d1", "d3d2"), ("d4d1", "d4d2"), ("d5d1", "d5d2")], ) def test_labeled_cols_as_rows_future(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle("b1", Data.d1.label("x"), Data.d2.label("y")) stmt = select(b1).filter(b1.c.x.between("d3d1", "d5d1")) eq_( sess.execute(stmt).all(), [(("d3d1", "d3d2"),), (("d4d1", "d4d2"),), (("d5d1", "d5d2"),)], ) def test_labeled_cols_as_scalars_future(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle("b1", Data.d1.label("x"), Data.d2.label("y")) stmt = select(b1).filter(b1.c.x.between("d3d1", "d5d1")) eq_( sess.scalars(stmt).all(), [("d3d1", "d3d2"), ("d4d1", "d4d2"), ("d5d1", "d5d2")], ) def test_single_entity_flag_is_legacy_w_future(self): Data = self.classes.Data sess = Session(testing.db, future=True) # flag has no effect b1 = Bundle("b1", Data.d1, Data.d2, single_entity=True) stmt = select(b1).filter(b1.c.d1.between("d3d1", "d5d1")) rows = sess.execute(stmt).all() eq_( rows, [(("d3d1", "d3d2"),), (("d4d1", "d4d2"),), (("d5d1", "d5d2"),)], ) def test_as_scalars_future(self): Data = self.classes.Data sess = Session(testing.db) b1 = Bundle("b1", Data.d1, Data.d2) stmt = select(b1).filter(b1.c.d1.between("d3d1", "d5d1")) eq_( sess.scalars(stmt).all(), [("d3d1", "d3d2"), ("d4d1", "d4d2"), ("d5d1", "d5d2")], ) def test_single_entity_flag_but_multi_entities(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle("b1", Data.d1, Data.d2, single_entity=True) b2 = Bundle("b1", Data.d3, single_entity=True) eq_( sess.query(b1, b2).filter(b1.c.d1.between("d3d1", "d5d1")).all(), [ (("d3d1", "d3d2"), ("d3d3",)), (("d4d1", "d4d2"), ("d4d3",)), (("d5d1", "d5d2"), ("d5d3",)), ], ) def test_bundle_nesting(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle("b1", Data.d1, Bundle("b2", Data.d2, Data.d3)) eq_( sess.query(b1) .filter(b1.c.d1.between("d3d1", "d7d1")) .filter(b1.c.b2.c.d2.between("d4d2", "d6d2")) .all(), [ (("d4d1", ("d4d2", "d4d3")),), (("d5d1", ("d5d2", "d5d3")),), (("d6d1", ("d6d2", "d6d3")),), ], ) def test_bundle_nesting_unions(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle("b1", Data.d1, Bundle("b2", Data.d2, Data.d3)) q1 = ( sess.query(b1) .filter(b1.c.d1.between("d3d1", "d7d1")) .filter(b1.c.b2.c.d2.between("d4d2", "d5d2")) ) q2 = ( sess.query(b1) .filter(b1.c.d1.between("d3d1", "d7d1")) .filter(b1.c.b2.c.d2.between("d5d2", "d6d2")) ) eq_( q1.union(q2).all(), [ (("d4d1", ("d4d2", "d4d3")),), (("d5d1", ("d5d2", "d5d3")),), (("d6d1", ("d6d2", "d6d3")),), ], ) # naming structure is preserved row = q1.union(q2).first() eq_(row.b1.d1, "d4d1") eq_(row.b1.b2.d2, "d4d2") def test_query_count(self): Data = self.classes.Data b1 = Bundle("b1", Data.d1, Data.d2) eq_(fixture_session().query(b1).count(), 10) def test_join_relationship(self): Data = self.classes.Data sess = fixture_session() b1 = Bundle("b1", Data.d1, Data.d2) q = sess.query(b1).join(Data.others) self.assert_compile( q, "SELECT data.d1 AS data_d1, data.d2 " "AS data_d2 FROM data " "JOIN other ON data.id = other.data_id", ) def test_join_selectable(self): Data = self.classes.Data Other = self.classes.Other sess = fixture_session() b1 = Bundle("b1", Data.d1, Data.d2) q = sess.query(b1).join(Other) self.assert_compile( q, "SELECT data.d1 AS data_d1, data.d2 AS data_d2 " "FROM data " "JOIN other ON data.id = other.data_id", ) def test_joins_from_adapted_entities(self): Data = self.classes.Data # test for #1853 in terms of bundles # specifically this exercises adapt_to_selectable() b1 = Bundle("b1", Data.id, Data.d1, Data.d2) session = fixture_session() first = session.query(b1) second = session.query(b1) unioned = first.union(second) subquery = session.query(Data.id).subquery() joined = unioned.outerjoin(subquery, subquery.c.id == Data.id) joined = joined.order_by(Data.id, Data.d1, Data.d2) self.assert_compile( joined, "SELECT anon_1.data_id AS anon_1_data_id, " "anon_1.data_d1 AS anon_1_data_d1, " "anon_1.data_d2 AS anon_1_data_d2 FROM " "(SELECT data.id AS data_id, data.d1 AS data_d1, " "data.d2 AS data_d2 FROM " "data UNION SELECT data.id AS data_id, data.d1 AS data_d1, " "data.d2 AS data_d2 FROM data) AS anon_1 " "LEFT OUTER JOIN (SELECT data.id AS id FROM data) AS anon_2 " "ON anon_2.id = anon_1.data_id " "ORDER BY anon_1.data_id, anon_1.data_d1, anon_1.data_d2", ) # tuple nesting still occurs eq_( joined.all(), [ ((1, "d0d1", "d0d2"),), ((2, "d1d1", "d1d2"),), ((3, "d2d1", "d2d2"),), ((4, "d3d1", "d3d2"),), ((5, "d4d1", "d4d2"),), ((6, "d5d1", "d5d2"),), ((7, "d6d1", "d6d2"),), ((8, "d7d1", "d7d2"),), ((9, "d8d1", "d8d2"),), ((10, "d9d1", "d9d2"),), ], ) def test_filter_by(self): Data = self.classes.Data b1 = Bundle("b1", Data.id, Data.d1, Data.d2) sess = fixture_session() self.assert_compile( sess.query(b1).filter_by(d1="d1"), "SELECT data.id AS data_id, data.d1 AS data_d1, " "data.d2 AS data_d2 FROM data WHERE data.d1 = :d1_1", ) def test_clause_expansion(self): Data = self.classes.Data b1 = Bundle("b1", Data.id, Data.d1, Data.d2) sess = fixture_session() self.assert_compile( sess.query(Data).order_by(b1), "SELECT data.id AS data_id, data.d1 AS data_d1, " "data.d2 AS data_d2, data.d3 AS data_d3 FROM data " "ORDER BY data.id, data.d1, data.d2", ) self.assert_compile( sess.query(func.row_number().over(order_by=b1)), "SELECT row_number() OVER (ORDER BY data.id, data.d1, data.d2) " "AS anon_1 FROM data", ) def test_non_mapped_columns_non_single_entity(self): data_table = self.tables.data b1 = Bundle("b1", data_table.c.d1, data_table.c.d2) sess = fixture_session() eq_( sess.query(b1).filter(b1.c.d1.between("d3d1", "d5d1")).all(), [(("d3d1", "d3d2"),), (("d4d1", "d4d2"),), (("d5d1", "d5d2"),)], ) def test_non_mapped_columns_single_entity(self): data_table = self.tables.data b1 = Bundle("b1", data_table.c.d1, data_table.c.d2, single_entity=True) sess = fixture_session() eq_( sess.query(b1).filter(b1.c.d1.between("d3d1", "d5d1")).all(), [("d3d1", "d3d2"), ("d4d1", "d4d2"), ("d5d1", "d5d2")], )
BundleTest
python
huggingface__transformers
src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py
{ "start": 12431, "end": 19825 }
class ____(Qwen2_5_VLPreTrainedModel): config: Qwen2_5_VLVisionConfig _no_split_modules = ["Qwen2_5_VLVisionBlock"] def __init__(self, config, *inputs, **kwargs) -> None: super().__init__(config, *inputs, **kwargs) self.spatial_merge_size = config.spatial_merge_size self.patch_size = config.patch_size self.fullatt_block_indexes = config.fullatt_block_indexes self.window_size = config.window_size self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size self.patch_embed = Qwen2_5_VisionPatchEmbed( patch_size=config.patch_size, temporal_patch_size=config.temporal_patch_size, in_channels=config.in_channels, embed_dim=config.hidden_size, ) head_dim = config.hidden_size // config.num_heads self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2) self.blocks = nn.ModuleList([Qwen2_5_VLVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen2_5_VLPatchMerger( dim=config.out_hidden_size, context_dim=config.hidden_size, spatial_merge_size=config.spatial_merge_size, ) self.gradient_checkpointing = False 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 def get_window_index(self, grid_thw): window_index: list = [] cu_window_seqlens: list = [0] window_index_id = 0 vit_merger_window_size = self.window_size // self.spatial_merge_size // self.patch_size for grid_t, grid_h, grid_w in grid_thw: llm_grid_h, llm_grid_w = ( grid_h // self.spatial_merge_size, grid_w // self.spatial_merge_size, ) index = torch.arange(grid_t * llm_grid_h * llm_grid_w).reshape(grid_t, llm_grid_h, llm_grid_w) pad_h = vit_merger_window_size - llm_grid_h % vit_merger_window_size pad_w = vit_merger_window_size - llm_grid_w % vit_merger_window_size num_windows_h = (llm_grid_h + pad_h) // vit_merger_window_size num_windows_w = (llm_grid_w + pad_w) // vit_merger_window_size index_padded = F.pad(index, (0, pad_w, 0, pad_h), "constant", -100) index_padded = index_padded.reshape( grid_t, num_windows_h, vit_merger_window_size, num_windows_w, vit_merger_window_size, ) index_padded = index_padded.permute(0, 1, 3, 2, 4).reshape( grid_t, num_windows_h * num_windows_w, vit_merger_window_size, vit_merger_window_size, ) seqlens = (index_padded != -100).sum([2, 3]).reshape(-1) index_padded = index_padded.reshape(-1) index_new = index_padded[index_padded != -100] window_index.append(index_new + window_index_id) cu_seqlens_tmp = seqlens.cumsum(0) * self.spatial_merge_unit + cu_window_seqlens[-1] cu_window_seqlens.extend(cu_seqlens_tmp.tolist()) window_index_id += (grid_t * llm_grid_h * llm_grid_w).item() window_index = torch.cat(window_index, dim=0) return window_index, cu_window_seqlens def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) -> torch.Tensor: """ Args: hidden_states (`torch.Tensor` of shape `(seq_len, hidden_size)`): The final hidden states of the model. grid_thw (`torch.Tensor` of shape `(num_images_or_videos, 3)`): The temporal, height and width of feature shape of each image in LLM. Returns: `torch.Tensor`: hidden_states. """ hidden_states = self.patch_embed(hidden_states) rotary_pos_emb = self.rot_pos_emb(grid_thw) window_index, cu_window_seqlens = self.get_window_index(grid_thw) cu_window_seqlens = torch.tensor( cu_window_seqlens, device=hidden_states.device, dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32, ) cu_window_seqlens = torch.unique_consecutive(cu_window_seqlens) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) hidden_states = hidden_states[window_index, :, :] hidden_states = hidden_states.reshape(seq_len, -1) rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) rotary_pos_emb = rotary_pos_emb[window_index, :, :] rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) 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 layer_num, blk in enumerate(self.blocks): if layer_num in self.fullatt_block_indexes: cu_seqlens_now = cu_seqlens else: cu_seqlens_now = cu_window_seqlens hidden_states = blk( hidden_states, cu_seqlens=cu_seqlens_now, position_embeddings=position_embeddings, **kwargs, ) hidden_states = self.merger(hidden_states) reverse_indices = torch.argsort(window_index) hidden_states = hidden_states[reverse_indices, :] return hidden_states @dataclass @auto_docstring( custom_intro=""" Base class for Llava outputs, with hidden states and attentions. """ )
Qwen2_5_VisionTransformerPretrainedModel
python
joke2k__faker
faker/providers/phone_number/hy_AM/__init__.py
{ "start": 49, "end": 441 }
class ____(PhoneNumberProvider): # Source: https://en.wikipedia.org/wiki/Telephone_numbers_in_Armenia formats = ( "2##-#####", "3##-#####", "(2##) #####", "(3##) #####", "2##.#####", "3##.#####", "10-######", "(10) ######", "10.######", "9#-######", "(9#) ######", "9#.######", )
Provider
python
TheAlgorithms__Python
data_structures/linked_list/print_reverse.py
{ "start": 130, "end": 192 }
class ____: data: int next_node: Node | None = None
Node
python
catalyst-team__catalyst
examples/detection/models/yolo_x.py
{ "start": 2995, "end": 3849 }
class ____(nn.Module): """Spatial pyramid pooling layer used in YOLOv3-SPP""" def __init__( self, in_channels, out_channels, kernel_sizes=(5, 9, 13), activation="silu" ): super().__init__() hidden_channels = in_channels // 2 self.conv1 = BaseConv(in_channels, hidden_channels, 1, stride=1, act=activation) self.m = nn.ModuleList( [ nn.MaxPool2d(kernel_size=ks, stride=1, padding=ks // 2) for ks in kernel_sizes ] ) conv2_channels = hidden_channels * (len(kernel_sizes) + 1) self.conv2 = BaseConv(conv2_channels, out_channels, 1, stride=1, act=activation) def forward(self, x): x = self.conv1(x) x = torch.cat([x] + [m(x) for m in self.m], dim=1) x = self.conv2(x) return x
SPPBottleneck
python
getsentry__sentry
src/sentry/db/models/fields/text.py
{ "start": 773, "end": 829 }
class ____(TextType, models.CharField): pass
CharField
python
rq__rq
tests/test_registry.py
{ "start": 9772, "end": 11660 }
class ____(RQTestCase): def setUp(self): super().setUp() self.registry = FinishedJobRegistry(connection=self.connection) def test_key(self): self.assertEqual(self.registry.key, 'rq:finished:default') def test_cleanup(self): """Finished job registry removes expired jobs.""" timestamp = current_timestamp() self.connection.zadd(self.registry.key, {'foo': 1}) self.connection.zadd(self.registry.key, {'bar': timestamp + 10}) self.connection.zadd(self.registry.key, {'baz': timestamp + 30}) self.registry.cleanup() self.assertEqual(self.registry.get_job_ids(), ['bar', 'baz']) self.registry.cleanup(timestamp + 20) self.assertEqual(self.registry.get_job_ids(), ['baz']) # CanceledJobRegistry now implements noop cleanup, should not raise exception registry = CanceledJobRegistry(connection=self.connection) registry.cleanup() def test_jobs_are_put_in_registry(self): """Completed jobs are added to FinishedJobRegistry.""" self.assertEqual(self.registry.get_job_ids(), []) queue = Queue(connection=self.connection) worker = Worker([queue], connection=self.connection) # Completed jobs are put in FinishedJobRegistry job = queue.enqueue(say_hello) worker.perform_job(job, queue) self.assertEqual(self.registry.get_job_ids(), [job.id]) # When job is deleted, it should be removed from FinishedJobRegistry self.assertEqual(job.get_status(), JobStatus.FINISHED) job.delete() self.assertEqual(self.registry.get_job_ids(), []) # Failed jobs are not put in FinishedJobRegistry failed_job = queue.enqueue(div_by_zero) worker.perform_job(failed_job, queue) self.assertEqual(self.registry.get_job_ids(), [])
TestFinishedJobRegistry
python
pypa__pipenv
pipenv/patched/pip/_vendor/distlib/version.py
{ "start": 595, "end": 691 }
class ____(ValueError): """This is an unsupported version.""" pass
UnsupportedVersionError
python
walkccc__LeetCode
solutions/2512. Reward Top K Students/2512.py
{ "start": 0, "end": 567 }
class ____: def topStudents( self, positive_feedback: list[str], negative_feedback: list[str], report: list[str], student_id: list[int], k: int, ) -> list[int]: scoreAndIds = [] pos = set(positive_feedback) neg = set(negative_feedback) for sid, r in zip(student_id, report): score = 0 for word in r.split(): if word in pos: score += 3 if word in neg: score -= 1 scoreAndIds.append((-score, sid)) return [sid for _, sid in sorted(scoreAndIds)[:k]]
Solution
python
getsentry__sentry
src/sentry/services/http.py
{ "start": 923, "end": 6417 }
class ____(Service): name = "http" def __init__( self, host: str | None = None, port: int | None = None, debug: bool = False, workers: int | None = None, extra_options: dict[str, Any] | None = None, ) -> None: from django.conf import settings from sentry import options as sentry_options from sentry.logging import LoggingFormat host = host or settings.SENTRY_WEB_HOST port = port or settings.SENTRY_WEB_PORT options = (settings.SENTRY_WEB_OPTIONS or {}).copy() if extra_options is not None: for k, v in extra_options.items(): options[k] = v options.setdefault("module", "sentry.wsgi:application") options.setdefault("protocol", "http") options.setdefault("auto-procname", True) options.setdefault("procname-prefix-spaced", "[Sentry]") options.setdefault("workers", 1) options.setdefault("threads", 2) options.setdefault("http-timeout", 30) options.setdefault("vacuum", True) options.setdefault("thunder-lock", True) options.setdefault("log-x-forwarded-for", False) options.setdefault("buffer-size", 32768) options.setdefault("post-buffering", 65536) options.setdefault("limit-post", 20971520) options.setdefault("need-app", True) options.setdefault("disable-logging", False) options.setdefault("memory-report", True) options.setdefault("reload-on-rss", 600) options.setdefault("ignore-sigpipe", True) options.setdefault("ignore-write-errors", True) options.setdefault("disable-write-exception", True) options.setdefault("binary-path", sys.executable) options.setdefault("virtualenv", sys.prefix) options.setdefault("die-on-term", True) options.setdefault( "log-format", '%(addr) - %(user) [%(ltime)] "%(method) %(uri) %(proto)" %(status) %(size) "%(referer)" "%(uagent)"', ) options.setdefault("%s-socket" % options["protocol"], f"{host}:{port}") # We only need to set uid/gid when stepping down from root, but if # we are trying to run as root, then ignore it entirely. uid = os.getuid() if uid > 0: options.setdefault("uid", uid) gid = os.getgid() if gid > 0: options.setdefault("gid", gid) # Required arguments that should not be overridden options["master"] = True options["enable-threads"] = True options["lazy-apps"] = True options["single-interpreter"] = True if workers: options["workers"] = workers # Old options from gunicorn if "bind" in options: options["%s-socket" % options["protocol"]] = options.pop("bind") if "accesslog" in options: if options["accesslog"] != "-": options["logto"] = options["accesslog"] del options["accesslog"] if "errorlog" in options: if options["errorlog"] != "-": options["logto2"] = options["errorlog"] del options["errorlog"] if "timeout" in options: options["http-timeout"] = options.pop("timeout") if "proc_name" in options: options["procname-prefix-spaced"] = options.pop("proc_name") if "secure_scheme_headers" in options: del options["secure_scheme_headers"] if "loglevel" in options: del options["loglevel"] # For machine logging, we are choosing to 100% disable logging # from uwsgi since it's currently not possible to get a nice json # logging out of uwsgi, so it's better to just opt out. There's # also an assumption that anyone operating at the scale of needing # machine formatted logs, they are also using nginx in front which # has it's own logs that can be formatted correctly. if sentry_options.get("system.logging-format") == LoggingFormat.MACHINE: options["disable-logging"] = True self.options = options self.debug = debug def prepare_environment(self, env: MutableMapping[str, str] | None = None) -> None: from django.conf import settings if env is None: env = os.environ # Move all of the options into UWSGI_ env vars for k, v in convert_options_to_env(self.options): env.setdefault(k, v) # Signal that we're running within uwsgi env["SENTRY_RUNNING_UWSGI"] = "1" if settings.SENTRY_USE_UWSGI else "0" # This has already been validated inside __init__ env["SENTRY_SKIP_BACKEND_VALIDATION"] = "1" def run(self) -> NoReturn: self.prepare_environment() if self.debug or os.environ.get("SENTRY_RUNNING_UWSGI") == "0": from wsgiref.simple_server import make_server from sentry.wsgi import application assert os.environ.get("UWSGI_MODULE") == "sentry.wsgi:application" host, port = os.environ["UWSGI_HTTP_SOCKET"].split(":") httpd = make_server(host, int(port), application) httpd.serve_forever() raise AssertionError("unreachable") else: # TODO: https://github.com/lincolnloop/pyuwsgi-wheels/pull/17 cmd = (sys.executable, "-c", PYUWSGI_PROG) os.execvp(cmd[0], cmd)
SentryHTTPServer
python
huggingface__transformers
src/transformers/models/glm4v/modular_glm4v.py
{ "start": 22649, "end": 23031 }
class ____(Qwen2_5_VLVisionBlock): def __init__(self, config) -> None: super().__init__(config) self.norm1 = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.norm2 = Glm4vRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.attn = Glm4vVisionAttention(config) self.mlp = Glm4VisionMlp(config, bias=False)
Glm4vVisionBlock
python
celery__celery
celery/canvas.py
{ "start": 55391, "end": 55779 }
class ____(_basemap): """Map operation for tasks. Note: Tasks executed sequentially in process, this is not a parallel operation like :class:`group`. """ _task_name = 'celery.map' def __repr__(self): task, it = self._unpack_args(self.kwargs) return f'[{task.task}(x) for x in {truncate(repr(it), 100)}]' @Signature.register_type()
xmap
python
django__django
django/core/paginator.py
{ "start": 10191, "end": 12204 }
class ____(collections.abc.Sequence): def __init__(self, object_list, number, paginator): self.object_list = object_list self.number = number self.paginator = paginator def __repr__(self): return "<Page %s of %s>" % (self.number, self.paginator.num_pages) def __len__(self): return len(self.object_list) def __getitem__(self, index): if not isinstance(index, (int, slice)): raise TypeError( "Page indices must be integers or slices, not %s." % type(index).__name__ ) # The object_list is converted to a list so that if it was a QuerySet # it won't be a database hit per __getitem__. if not isinstance(self.object_list, list): self.object_list = list(self.object_list) return self.object_list[index] def has_next(self): return self.number < self.paginator.num_pages def has_previous(self): return self.number > 1 def has_other_pages(self): return self.has_previous() or self.has_next() def next_page_number(self): return self.paginator.validate_number(self.number + 1) def previous_page_number(self): return self.paginator.validate_number(self.number - 1) def start_index(self): """ Return the 1-based index of the first object on this page, relative to total objects in the paginator. """ # Special case, return zero if no items. if self.paginator.count == 0: return 0 return (self.paginator.per_page * (self.number - 1)) + 1 def end_index(self): """ Return the 1-based index of the last object on this page, relative to total objects found (hits). """ # Special case for the last page because there can be orphans. if self.number == self.paginator.num_pages: return self.paginator.count return self.number * self.paginator.per_page
Page
python
celery__celery
t/unit/contrib/test_rdb.py
{ "start": 242, "end": 3146 }
class ____: @patch('celery.contrib.rdb.Rdb') def test_debugger(self, Rdb): x = debugger() assert x assert x is debugger() @patch('celery.contrib.rdb.debugger') @patch('celery.contrib.rdb._frame') def test_set_trace(self, _frame, debugger): assert set_trace(Mock()) assert set_trace() debugger.return_value.set_trace.assert_called() @patch('celery.contrib.rdb.Rdb.get_avail_port') @t.skip.if_pypy def test_rdb(self, get_avail_port): sock = Mock() get_avail_port.return_value = (sock, 8000) sock.accept.return_value = (Mock(), ['helu']) out = WhateverIO() with Rdb(out=out) as rdb: get_avail_port.assert_called() assert 'helu' in out.getvalue() # set_quit with patch('sys.settrace') as settrace: rdb.set_quit() settrace.assert_called_with(None) # set_trace with patch('celery.contrib.rdb.Pdb.set_trace') as pset: with patch('celery.contrib.rdb._frame'): rdb.set_trace() rdb.set_trace(Mock()) pset.side_effect = SockErr pset.side_effect.errno = errno.ENOENT with pytest.raises(SockErr): rdb.set_trace() # _close_session rdb._close_session() rdb.active = True rdb._handle = None rdb._client = None rdb._sock = None rdb._close_session() # do_continue rdb.set_continue = Mock() rdb.do_continue(Mock()) rdb.set_continue.assert_called_with() # do_quit rdb.set_quit = Mock() rdb.do_quit(Mock()) rdb.set_quit.assert_called_with() @patch('socket.socket') @t.skip.if_pypy def test_get_avail_port(self, sock): out = WhateverIO() sock.return_value.accept.return_value = (Mock(), ['helu']) with Rdb(out=out): pass with patch('celery.contrib.rdb.current_process') as curproc: curproc.return_value.name = 'PoolWorker-10' with Rdb(out=out): pass err = sock.return_value.bind.side_effect = SockErr() err.errno = errno.ENOENT with pytest.raises(SockErr): with Rdb(out=out): pass err.errno = errno.EADDRINUSE with pytest.raises(Exception): with Rdb(out=out): pass called = [0] def effect(*a, **kw): try: if called[0] > 50: return True raise err finally: called[0] += 1 sock.return_value.bind.side_effect = effect with Rdb(out=out): pass
test_Rdb
python
tornadoweb__tornado
demos/s3server/s3server.py
{ "start": 4709, "end": 5322 }
class ____(BaseRequestHandler): def get(self): names = os.listdir(self.application.directory) buckets = [] for name in names: path = os.path.join(self.application.directory, name) info = os.stat(path) buckets.append( { "Name": name, "CreationDate": datetime.datetime.fromtimestamp( info.st_ctime, datetime.timezone.utc ), } ) self.render_xml({"ListAllMyBucketsResult": {"Buckets": {"Bucket": buckets}}})
RootHandler
python
tiangolo__fastapi
tests/test_response_model_data_filter_no_inheritance.py
{ "start": 145, "end": 209 }
class ____(BaseModel): email: str password: str
UserCreate
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call.py
{ "start": 8110, "end": 10805 }
class ____: """Test response content rewriting with wrap_model_call.""" def test_uppercase_response(self) -> None: """Test middleware that transforms response to uppercase.""" class UppercaseMiddleware(AgentMiddleware): def wrap_model_call(self, request, handler): result = handler(request) # result is ModelResponse, extract AIMessage from it ai_message = result.result[0] return AIMessage(content=ai_message.content.upper()) model = GenericFakeChatModel(messages=iter([AIMessage(content="hello world")])) agent = create_agent(model=model, middleware=[UppercaseMiddleware()]) result = agent.invoke({"messages": [HumanMessage("Test")]}) assert result["messages"][1].content == "HELLO WORLD" def test_prefix_response(self) -> None: """Test middleware that adds prefix to response.""" class PrefixMiddleware(AgentMiddleware): def __init__(self, prefix: str): super().__init__() self.prefix = prefix def wrap_model_call(self, request, handler): result = handler(request) # result is ModelResponse, extract AIMessage from it ai_message = result.result[0] return AIMessage(content=f"{self.prefix}{ai_message.content}") model = GenericFakeChatModel(messages=iter([AIMessage(content="Response")])) agent = create_agent(model=model, middleware=[PrefixMiddleware(prefix="[BOT]: ")]) result = agent.invoke({"messages": [HumanMessage("Test")]}) assert result["messages"][1].content == "[BOT]: Response" def test_multi_stage_transformation(self) -> None: """Test middleware applying multiple transformations.""" class MultiTransformMiddleware(AgentMiddleware): def wrap_model_call(self, request, handler): result = handler(request) # result is ModelResponse, extract AIMessage from it ai_message = result.result[0] # First transformation: uppercase content = ai_message.content.upper() # Second transformation: add prefix and suffix content = f"[START] {content} [END]" return AIMessage(content=content) model = GenericFakeChatModel(messages=iter([AIMessage(content="hello")])) agent = create_agent(model=model, middleware=[MultiTransformMiddleware()]) result = agent.invoke({"messages": [HumanMessage("Test")]}) assert result["messages"][1].content == "[START] HELLO [END]"
TestResponseRewriting
python
keras-team__keras
keras/src/layers/core/input_layer.py
{ "start": 213, "end": 8168 }
class ____(Layer): def __init__( self, shape=None, batch_size=None, dtype=None, sparse=None, ragged=None, batch_shape=None, input_tensor=None, optional=False, name=None, **kwargs, ): super().__init__(name=name) if "input_shape" in kwargs: warnings.warn( "Argument `input_shape` is deprecated. Use `shape` instead." ) shape = kwargs.pop("input_shape") if "batch_input_shape" in kwargs: batch_shape = kwargs.pop("batch_input_shape") if input_tensor is not None: if not isinstance(input_tensor, backend.KerasTensor): raise ValueError( "Argument `input_tensor` must be a KerasTensor. " f"Received invalid type: input_tensor={input_tensor} " f"(of type {type(input_tensor)})" ) if batch_size is not None: if ( len(input_tensor.shape) < 1 or input_tensor.shape[0] != batch_size ): raise ValueError( "When providing the `input_tensor` argument, you " "cannot provide an incompatible `batch_size` argument." ) if shape is not None: if ( len(shape) != len(input_tensor.shape) - 1 or shape != input_tensor.shape[1:] ): raise ValueError( "When providing the `input_tensor` argument, you " "cannot provide an incompatible `shape` argument." ) if batch_shape is not None and batch_shape != input_tensor.shape: raise ValueError( "When providing the `input_tensor` argument, you " "cannot provide an incompatible `batch_shape` argument." ) if dtype is not None and input_tensor.dtype != dtype: raise ValueError( "When providing the `input_tensor` argument, you " "cannot provide an incompatible `dtype` argument." ) if sparse is not None and input_tensor.sparse != sparse: raise ValueError( "When providing the `input_tensor` argument, you " "cannot provide an incompatible `sparse` argument." ) batch_shape = input_tensor.shape dtype = input_tensor.dtype sparse = input_tensor.sparse else: if shape is not None and batch_shape is not None: raise ValueError( "You cannot pass both `shape` and `batch_shape` at the " "same time." ) if batch_size is not None and batch_shape is not None: raise ValueError( "You cannot pass both `batch_size` and `batch_shape` " "at the same time." ) if shape is None and batch_shape is None: raise ValueError("You must pass a `shape` argument.") if shape is not None: shape = backend.standardize_shape(shape) batch_shape = (batch_size,) + shape self._batch_shape = backend.standardize_shape(batch_shape) self._dtype = backend.standardize_dtype(dtype) self.sparse = bool(sparse) if self.sparse and not backend.SUPPORTS_SPARSE_TENSORS: raise ValueError( f"`sparse=True` is not supported with the {backend.backend()} " "backend" ) self.ragged = bool(ragged) if self.ragged and not backend.SUPPORTS_RAGGED_TENSORS: raise ValueError( f"`ragged=True` is not supported with the {backend.backend()} " "backend" ) if input_tensor is None: input_tensor = backend.KerasTensor( shape=batch_shape, dtype=dtype, sparse=sparse, ragged=ragged, name=name, ) self._input_tensor = input_tensor Node(operation=self, call_args=(), call_kwargs={}, outputs=input_tensor) self.built = True self.optional = optional def call(self): return @property def batch_shape(self): return self._batch_shape @property def dtype(self): return self._dtype def get_config(self): return { "batch_shape": self.batch_shape, "dtype": self.dtype, "sparse": self.sparse, "ragged": self.ragged, "name": self.name, "optional": self.optional, } @keras_export(["keras.layers.Input", "keras.Input"]) def Input( shape=None, batch_size=None, dtype=None, sparse=None, ragged=None, batch_shape=None, name=None, tensor=None, optional=False, ): """Used to instantiate a Keras tensor. A Keras tensor is a symbolic tensor-like object, which we augment with certain attributes that allow us to build a Keras model just by knowing the inputs and outputs of the model. For instance, if `a`, `b` and `c` are Keras tensors, it becomes possible to do: `model = Model(input=[a, b], output=c)` Args: shape: A shape tuple (tuple of integers or `None` objects), not including the batch size. For instance, `shape=(32,)` indicates that the expected input will be batches of 32-dimensional vectors. Elements of this tuple can be `None`; `None` elements represent dimensions where the shape is not known and may vary (e.g. sequence length). batch_size: Optional static batch size (integer). dtype: The data type expected by the input, as a string (e.g. `"float32"`, `"int32"`...) sparse: A boolean specifying whether the expected input will be sparse tensors. Note that, if `sparse` is `False`, sparse tensors can still be passed into the input - they will be densified with a default value of 0. This feature is only supported with the TensorFlow and the JAX backends. Defaults to `False`. ragged: A boolean specifying whether the expected input will be ragged tensors. Note that, if `ragged` is `False`, ragged tensors can still be passed into the input - they will be densified with a default value of 0. This feature is only supported with the TensorFlow backend. Defaults to `False`. batch_shape: Optional shape tuple (tuple of integers or `None` objects), including the batch size. name: Optional name string for the layer. Should be unique in a model (do not reuse the same name twice). It will be autogenerated if it isn't provided. tensor: Optional existing tensor to wrap into the `Input` layer. If set, the layer will use this tensor rather than creating a new placeholder tensor. optional: Boolean, whether the input is optional or not. An optional input can accept `None` values. Returns: A Keras tensor. Example: ```python # This is a logistic regression in Keras x = Input(shape=(32,)) y = Dense(16, activation='softmax')(x) model = Model(x, y) ``` """ layer = InputLayer( shape=shape, batch_size=batch_size, dtype=dtype, sparse=sparse, ragged=ragged, batch_shape=batch_shape, name=name, input_tensor=tensor, optional=optional, ) return layer.output
InputLayer
python
kamyu104__LeetCode-Solutions
Python/count-strictly-increasing-subarrays.py
{ "start": 44, "end": 409 }
class ____(object): def countSubarrays(self, nums): """ :type nums: List[int] :rtype: int """ result = l = 1 for i in xrange(1, len(nums)): if nums[i-1] >= nums[i]: l = 0 l += 1 result += l return result # Time: O(n) # Space: O(1) # two pointers
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-k8s/dagster_k8s/client.py
{ "start": 1028, "end": 1086 }
class ____(DagsterK8sError): pass
DagsterK8sTimeoutError
python
oauthlib__oauthlib
oauthlib/openid/connect/core/grant_types/authorization_code.py
{ "start": 307, "end": 1441 }
class ____(GrantTypeBase): def __init__(self, request_validator=None, **kwargs): self.proxy_target = OAuth2AuthorizationCodeGrant( request_validator=request_validator, **kwargs) self.custom_validators.post_auth.append( self.openid_authorization_validator) self.register_token_modifier(self.add_id_token) def add_id_token(self, token, token_handler, request): """ Construct an initial version of id_token, and let the request_validator sign or encrypt it. The authorization_code version of this method is used to retrieve the nonce accordingly to the code storage. """ # Treat it as normal OAuth 2 auth code request if openid is not present if not request.scopes or 'openid' not in request.scopes: return token nonce = self.request_validator.get_authorization_code_nonce( request.client_id, request.code, request.redirect_uri, request ) return super().add_id_token(token, token_handler, request, nonce=nonce)
AuthorizationCodeGrant
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_kubernetes_engine.py
{ "start": 40372, "end": 45656 }
class ____: def setup_method(self): self.operator = GKEListJobsOperator( project_id=TEST_PROJECT_ID, location=TEST_LOCATION, cluster_name=GKE_CLUSTER_NAME, task_id=TEST_TASK_ID, ) def test_template_fields(self): expected_template_fields = {"namespace"} | set(GKEOperatorMixin.template_fields) assert set(GKEListJobsOperator.template_fields) == expected_template_fields @mock.patch(GKE_OPERATORS_PATH.format("V1JobList.to_dict")) @mock.patch(GKE_OPERATORS_PATH.format("GKEListJobsOperator.log")) @mock.patch(GKE_OPERATORS_PATH.format("GKEHook")) @mock.patch(GKE_OPERATORS_PATH.format("GKEKubernetesHook")) def test_execute(self, mock_hook, cluster_hook, mock_log, mock_to_dict): mock_list_jobs_from_namespace = mock_hook.return_value.list_jobs_from_namespace mock_list_jobs_all_namespaces = mock_hook.return_value.list_jobs_all_namespaces mock_job_1, mock_job_2 = mock.MagicMock(), mock.MagicMock() mock_jobs = mock.MagicMock(items=[mock_job_1, mock_job_2]) mock_list_jobs_all_namespaces.return_value = mock_jobs mock_to_dict_value = mock_to_dict.return_value mock_ti = mock.MagicMock() context = {"ti": mock_ti, "task": mock.MagicMock()} result = self.operator.execute(context=context) mock_list_jobs_all_namespaces.assert_called_once() mock_list_jobs_from_namespace.assert_not_called() mock_log.info.assert_has_calls( [ call("Retrieved description of Job:\n %s", mock_job_1), call("Retrieved description of Job:\n %s", mock_job_2), ] ) mock_to_dict.assert_has_calls([call(mock_jobs), call(mock_jobs)]) mock_ti.xcom_push.assert_has_calls( [call(key="jobs_list", value=mock_to_dict_value), call(key="kubernetes_workloads_conf", value={})] ) assert result == mock_to_dict_value @mock.patch(GKE_OPERATORS_PATH.format("KubernetesEngineWorkloadsLink")) @mock.patch(GKE_OPERATORS_PATH.format("V1JobList.to_dict")) @mock.patch(GKE_OPERATORS_PATH.format("GKEListJobsOperator.log")) @mock.patch(GKE_OPERATORS_PATH.format("GKEHook")) @mock.patch(GKE_OPERATORS_PATH.format("GKEKubernetesHook")) def test_execute_namespaced(self, mock_hook, cluster_hook, mock_log, mock_to_dict, mock_link): mock_list_jobs_from_namespace = mock_hook.return_value.list_jobs_from_namespace mock_list_jobs_all_namespaces = mock_hook.return_value.list_jobs_all_namespaces mock_job_1, mock_job_2 = mock.MagicMock(), mock.MagicMock() mock_jobs = mock.MagicMock(items=[mock_job_1, mock_job_2]) mock_list_jobs_from_namespace.return_value = mock_jobs mock_to_dict_value = mock_to_dict.return_value mock_ti = mock.MagicMock() context = {"ti": mock_ti, "task": mock.MagicMock()} self.operator.namespace = K8S_NAMESPACE result = self.operator.execute(context=context) mock_list_jobs_all_namespaces.assert_not_called() mock_list_jobs_from_namespace.assert_called_once_with(namespace=K8S_NAMESPACE) mock_log.info.assert_has_calls( [ call("Retrieved description of Job:\n %s", mock_job_1), call("Retrieved description of Job:\n %s", mock_job_2), ] ) mock_to_dict.assert_has_calls([call(mock_jobs), call(mock_jobs)]) mock_ti.xcom_push.assert_called_once_with(key="jobs_list", value=mock_to_dict_value) mock_link.persist.assert_called_once_with(context=context) assert result == mock_to_dict_value @mock.patch(GKE_OPERATORS_PATH.format("KubernetesEngineWorkloadsLink")) @mock.patch(GKE_OPERATORS_PATH.format("V1JobList.to_dict")) @mock.patch(GKE_OPERATORS_PATH.format("GKEListJobsOperator.log")) @mock.patch(GKE_OPERATORS_PATH.format("GKEHook")) @mock.patch(GKE_OPERATORS_PATH.format("GKEKubernetesHook")) def test_execute_not_do_xcom_push(self, mock_hook, cluster_hook, mock_log, mock_to_dict, mock_link): mock_list_jobs_from_namespace = mock_hook.return_value.list_jobs_from_namespace mock_list_jobs_all_namespaces = mock_hook.return_value.list_jobs_all_namespaces mock_job_1, mock_job_2 = mock.MagicMock(), mock.MagicMock() mock_jobs = mock.MagicMock(items=[mock_job_1, mock_job_2]) mock_list_jobs_all_namespaces.return_value = mock_jobs mock_to_dict_value = mock_to_dict.return_value mock_ti = mock.MagicMock() context = {"ti": mock_ti, "task": mock.MagicMock()} self.operator.do_xcom_push = False result = self.operator.execute(context=context) mock_list_jobs_all_namespaces.assert_called_once() mock_list_jobs_from_namespace.assert_not_called() mock_log.info.assert_has_calls( [ call("Retrieved description of Job:\n %s", mock_job_1), call("Retrieved description of Job:\n %s", mock_job_2), ] ) mock_to_dict.assert_called_once_with(mock_jobs) mock_link.persist.assert_called_once_with(context=context) assert result == mock_to_dict_value
TestGKEListJobsOperator
python
huggingface__transformers
tests/cli/test_serve.py
{ "start": 32788, "end": 35381 }
class ____(ServeResponsesMixin, unittest.TestCase): """Tests the Responses API.""" @classmethod def setUpClass(cls): """Starts a server for tests to connect to.""" cls.port = 8003 cls.server = Serve(port=cls.port, default_seed=42, non_blocking=True) @classmethod def tearDownClass(cls): cls.server.kill_server() @slow def test_full_request(self): """Tests that an inference using the Responses API works""" request = { "model": "Qwen/Qwen2.5-0.5B-Instruct", "instructions": "You are a sports assistant designed to craft sports programs.", "input": "Tell me what you can do.", "stream": True, "max_output_tokens": 30, # Disable sampling for deterministic output "temperature": 0, } all_payloads = self.run_server(request) full_text = "" for token in all_payloads: if isinstance(token, ResponseTextDeltaEvent): full_text += token.delta # Verify that the system prompt went through. # With deterministic decoding, exact wording can still vary across versions. # Assert non-empty output and that it references sports. self.assertTrue(len(full_text) > 0) self.assertIn("sports", full_text.lower()) @slow def test_non_streaming_request(self): """Tests that an inference using the Responses API with stream=False returns a single Response payload.""" from openai import OpenAI from openai.types.responses import Response as OpenAIResponse client = OpenAI(base_url=f"http://localhost:{self.port}/v1", api_key="<KEY>") resp = client.responses.create( model="Qwen/Qwen2.5-0.5B-Instruct", instructions="You are a helpful assistant.", input="Hello!", stream=False, max_output_tokens=5, ) # Should be a single Response object with completed status and one output item containing text self.assertIsInstance(resp, OpenAIResponse) self.assertEqual(resp.status, "completed") self.assertTrue(len(resp.output) >= 1) first_item = resp.output[0] self.assertEqual(first_item.type, "message") self.assertEqual(first_item.status, "completed") self.assertTrue(len(first_item.content) >= 1) first_part = first_item.content[0] self.assertEqual(first_part.type, "output_text") self.assertIsInstance(first_part.text, str)
ServeResponsesIntegrationTest
python
scipy__scipy
scipy/interpolate/_fitpack2.py
{ "start": 61350, "end": 67633 }
class ____(_BivariateSplineBase): """ Bivariate spline s(x,y) of degrees 3 on a sphere, calculated from a given set of data points (theta,phi,r). .. versionadded:: 0.11.0 See Also -------- bisplrep : a function to find a bivariate B-spline representation of a surface bisplev : a function to evaluate a bivariate B-spline and its derivatives UnivariateSpline : a smooth univariate spline to fit a given set of data points. SmoothBivariateSpline : a smoothing bivariate spline through the given points LSQUnivariateSpline : a univariate spline using weighted least-squares fitting """ def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): """ Evaluate the spline or its derivatives at given positions. Parameters ---------- theta, phi : array_like Input coordinates. If `grid` is False, evaluate the spline at points ``(theta[i], phi[i]), i=0, ..., len(x)-1``. Standard Numpy broadcasting is obeyed. If `grid` is True: evaluate spline at the grid points defined by the coordinate arrays theta, phi. The arrays must be sorted to increasing order. The ordering of axes is consistent with ``np.meshgrid(..., indexing="ij")`` and inconsistent with the default ordering ``np.meshgrid(..., indexing="xy")``. dtheta : int, optional Order of theta-derivative .. versionadded:: 0.14.0 dphi : int Order of phi-derivative .. versionadded:: 0.14.0 grid : bool Whether to evaluate the results on a grid spanned by the input arrays, or at points specified by the input arrays. .. versionadded:: 0.14.0 Examples -------- Suppose that we want to use splines to interpolate a bivariate function on a sphere. The value of the function is known on a grid of longitudes and colatitudes. >>> import numpy as np >>> from scipy.interpolate import RectSphereBivariateSpline >>> def f(theta, phi): ... return np.sin(theta) * np.cos(phi) We evaluate the function on the grid. Note that the default indexing="xy" of meshgrid would result in an unexpected (transposed) result after interpolation. >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1] >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1] >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij") >>> zdata = f(thetagrid, phigrid) We next set up the interpolator and use it to evaluate the function on a finer grid. >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata) >>> thetaarr_fine = np.linspace(0, np.pi, 200) >>> phiarr_fine = np.linspace(0, 2 * np.pi, 200) >>> zdata_fine = rsbs(thetaarr_fine, phiarr_fine) Finally we plot the coarsly-sampled input data alongside the finely-sampled interpolated data to check that they agree. >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> ax1 = fig.add_subplot(1, 2, 1) >>> ax2 = fig.add_subplot(1, 2, 2) >>> ax1.imshow(zdata) >>> ax2.imshow(zdata_fine) >>> plt.show() """ theta = np.asarray(theta) phi = np.asarray(phi) if theta.size > 0 and (theta.min() < 0. or theta.max() > np.pi): raise ValueError("requested theta out of bounds.") return _BivariateSplineBase.__call__(self, theta, phi, dx=dtheta, dy=dphi, grid=grid) def ev(self, theta, phi, dtheta=0, dphi=0): """ Evaluate the spline at points Returns the interpolated value at ``(theta[i], phi[i]), i=0,...,len(theta)-1``. Parameters ---------- theta, phi : array_like Input coordinates. Standard Numpy broadcasting is obeyed. The ordering of axes is consistent with np.meshgrid(..., indexing="ij") and inconsistent with the default ordering np.meshgrid(..., indexing="xy"). dtheta : int, optional Order of theta-derivative .. versionadded:: 0.14.0 dphi : int, optional Order of phi-derivative .. versionadded:: 0.14.0 Examples -------- Suppose that we want to use splines to interpolate a bivariate function on a sphere. The value of the function is known on a grid of longitudes and colatitudes. >>> import numpy as np >>> from scipy.interpolate import RectSphereBivariateSpline >>> def f(theta, phi): ... return np.sin(theta) * np.cos(phi) We evaluate the function on the grid. Note that the default indexing="xy" of meshgrid would result in an unexpected (transposed) result after interpolation. >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1] >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1] >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij") >>> zdata = f(thetagrid, phigrid) We next set up the interpolator and use it to evaluate the function at points not on the original grid. >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata) >>> thetainterp = np.linspace(thetaarr[0], thetaarr[-1], 200) >>> phiinterp = np.linspace(phiarr[0], phiarr[-1], 200) >>> zinterp = rsbs.ev(thetainterp, phiinterp) Finally we plot the original data for a diagonal slice through the initial grid, and the spline approximation along the same slice. >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> ax1 = fig.add_subplot(1, 1, 1) >>> ax1.plot(np.sin(thetaarr) * np.sin(phiarr), np.diag(zdata), "or") >>> ax1.plot(np.sin(thetainterp) * np.sin(phiinterp), zinterp, "-b") >>> plt.show() """ return self.__call__(theta, phi, dtheta=dtheta, dphi=dphi, grid=False) @xp_capabilities(out_of_scope=True)
SphereBivariateSpline
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_iban.py
{ "start": 1420, "end": 3447 }
class ____(ColumnMapExpectation): """Expect column values to be valid IBAN format.""" map_metric = "column_values.valid_iban" success_keys = ("mostly",) default_kwarg_values = {} library_metadata = { "maturity": "experimental", "tags": ["experimental", "hackathon", "typed-entities"], "contributors": ["@voidforall", "@mkopec87"], "requirements": ["schwifty"], } examples = [ { "data": { "well_formed_iban": [ "DE89 3704 0044 0532 0130 00", "FR14 2004 1010 0505 0001 3M02 606", "IT60 X054 2811 1010 0000 0123 456", "CH93 0076 2011 6238 5295 7", "GB29 NWBK 6016 1331 9268 19", ], "malformed_iban": [ # invalid length "DE89 3704 0044 0532 0130", "DE89 3704 0044 0532 0130 0000", # wrong country code "XX89 3704 0044 0532 0130 00", # wrong format "DE89 AA04 0044 0532 0130 00", # wrong checksum digits "GB01 BARC 2071 4583 6083 87", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "well_formed_iban"}, "out": {"success": True}, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "malformed_iban"}, "out": {"success": False}, }, ], } ] if __name__ == "__main__": ExpectColumnValuesToBeValidIban().print_diagnostic_checklist()
ExpectColumnValuesToBeValidIban
python
ray-project__ray
rllib/algorithms/dqn/torch/default_dqn_torch_rl_module.py
{ "start": 878, "end": 13850 }
class ____(TorchRLModule, DefaultDQNRLModule): framework: str = "torch" def __init__(self, *args, **kwargs): catalog_class = kwargs.pop("catalog_class", None) if catalog_class is None: catalog_class = DQNCatalog super().__init__(*args, **kwargs, catalog_class=catalog_class) @override(RLModule) def _forward_inference(self, batch: Dict[str, TensorType]) -> Dict[str, TensorType]: # Q-network forward pass. qf_outs = self.compute_q_values(batch) # Get action distribution. action_dist_cls = self.get_exploration_action_dist_cls() action_dist = action_dist_cls.from_logits(qf_outs[QF_PREDS]) # Note, the deterministic version of the categorical distribution # outputs directly the `argmax` of the logits. exploit_actions = action_dist.to_deterministic().sample() output = {Columns.ACTIONS: exploit_actions} if Columns.STATE_OUT in qf_outs: output[Columns.STATE_OUT] = qf_outs[Columns.STATE_OUT] # In inference, we only need the exploitation actions. return output @override(RLModule) def _forward_exploration( self, batch: Dict[str, TensorType], t: int ) -> Dict[str, TensorType]: # Define the return dictionary. output = {} # Q-network forward pass. qf_outs = self.compute_q_values(batch) # Get action distribution. action_dist_cls = self.get_exploration_action_dist_cls() action_dist = action_dist_cls.from_logits(qf_outs[QF_PREDS]) # Note, the deterministic version of the categorical distribution # outputs directly the `argmax` of the logits. exploit_actions = action_dist.to_deterministic().sample() # We need epsilon greedy to support exploration. # TODO (simon): Implement sampling for nested spaces. # Update scheduler. self.epsilon_schedule.update(t) # Get the actual epsilon, epsilon = self.epsilon_schedule.get_current_value() # Apply epsilon-greedy exploration. B = qf_outs[QF_PREDS].shape[0] random_actions = torch.squeeze( torch.multinomial( ( torch.nan_to_num( qf_outs[QF_PREDS].reshape(-1, qf_outs[QF_PREDS].size(-1)), neginf=0.0, ) != 0.0 ).float(), num_samples=1, ), dim=1, ) actions = torch.where( torch.rand((B,)) < epsilon, random_actions, exploit_actions, ) # Add the actions to the return dictionary. output[Columns.ACTIONS] = actions # If this is a stateful module, add output states. if Columns.STATE_OUT in qf_outs: output[Columns.STATE_OUT] = qf_outs[Columns.STATE_OUT] return output @override(RLModule) def _forward_train( self, batch: Dict[str, TensorType] ) -> Dict[str, TensorStructType]: if self.inference_only: raise RuntimeError( "Trying to train a module that is not a learner module. Set the " "flag `inference_only=False` when building the module." ) output = {} # If we use a double-Q setup. if self.uses_double_q: # Then we need to make a single forward pass with both, # current and next observations. batch_base = { Columns.OBS: torch.concat( [batch[Columns.OBS], batch[Columns.NEXT_OBS]], dim=0 ), } # If this is a stateful module add the input states. if Columns.STATE_IN in batch: # Add both, the input state for the actual observation and # the one for the next observation. batch_base.update( { Columns.STATE_IN: tree.map_structure( lambda t1, t2: torch.cat([t1, t2], dim=0), batch[Columns.STATE_IN], batch[Columns.NEXT_STATE_IN], ) } ) # Otherwise we can just use the current observations. else: batch_base = {Columns.OBS: batch[Columns.OBS]} # If this is a stateful module add the input state. if Columns.STATE_IN in batch: batch_base.update({Columns.STATE_IN: batch[Columns.STATE_IN]}) batch_target = {Columns.OBS: batch[Columns.NEXT_OBS]} # If we have a stateful encoder, add the states for the target forward # pass. if Columns.NEXT_STATE_IN in batch: batch_target.update({Columns.STATE_IN: batch[Columns.NEXT_STATE_IN]}) # Q-network forward passes. qf_outs = self.compute_q_values(batch_base) if self.uses_double_q: output[QF_PREDS], output[QF_NEXT_PREDS] = torch.chunk( qf_outs[QF_PREDS], chunks=2, dim=0 ) else: output[QF_PREDS] = qf_outs[QF_PREDS] # The target Q-values for the next observations. qf_target_next_outs = self.forward_target(batch_target) output[QF_TARGET_NEXT_PREDS] = qf_target_next_outs[QF_PREDS] # We are learning a Q-value distribution. if self.num_atoms > 1: # Add distribution artefacts to the output. # Distribution support. output[ATOMS] = qf_target_next_outs[ATOMS] # Original logits from the Q-head. output[QF_LOGITS] = qf_outs[QF_LOGITS] # Probabilities of the Q-value distribution of the current state. output[QF_PROBS] = qf_outs[QF_PROBS] # Probabilities of the target Q-value distribution of the next state. output[QF_TARGET_NEXT_PROBS] = qf_target_next_outs[QF_PROBS] # Add the states to the output, if the module is stateful. if Columns.STATE_OUT in qf_outs: output[Columns.STATE_OUT] = qf_outs[Columns.STATE_OUT] # For correctness, also add the output states from the target forward pass. # Note, we do not backpropagate through this state. if Columns.STATE_OUT in qf_target_next_outs: output[Columns.NEXT_STATE_OUT] = qf_target_next_outs[Columns.STATE_OUT] return output @override(QNetAPI) def compute_advantage_distribution( self, batch: Dict[str, TensorType], ) -> Dict[str, TensorType]: output = {} # Distributional Q-learning uses a discrete support `z` # to represent the action value distribution. # TODO (simon): Check, if we still need here the device for torch. z = torch.arange(0.0, self.num_atoms, dtype=torch.float32).to( batch.device, ) # Rescale the support. z = self.v_min + z * (self.v_max - self.v_min) / float(self.num_atoms - 1) # Reshape the action values. # NOTE: Handcrafted action shape. logits_per_action_per_atom = torch.reshape( batch, shape=(*batch.shape[:-1], self.action_space.n, self.num_atoms) ) # Calculate the probability for each action value atom. Note, # the sum along action value atoms of a single action value # must sum to one. prob_per_action_per_atom = nn.functional.softmax( logits_per_action_per_atom, dim=-1, ) # Compute expected action value by weighted sum. output[ATOMS] = z output["logits"] = logits_per_action_per_atom output["probs"] = prob_per_action_per_atom return output # TODO (simon): Test, if providing the function with a `return_probs` # improves performance significantly. @override(DefaultDQNRLModule) def _qf_forward_helper( self, batch: Dict[str, TensorType], encoder: Encoder, head: Union[Model, Dict[str, Model]], ) -> Dict[str, TensorType]: """Computes Q-values. This is a helper function that takes care of all different cases, i.e. if we use a dueling architecture or not and if we use distributional Q-learning or not. Args: batch: The batch received in the forward pass. encoder: The encoder network to use. Here we have a single encoder for all heads (Q or advantages and value in case of a dueling architecture). head: Either a head model or a dictionary of head model (dueling architecture) containing advantage and value stream heads. Returns: In case of expectation learning the Q-value predictions ("qf_preds") and in case of distributional Q-learning in addition to the predictions the atoms ("atoms"), the Q-value predictions ("qf_preds"), the Q-logits ("qf_logits") and the probabilities for the support atoms ("qf_probs"). """ output = {} # Encoder forward pass. encoder_outs = encoder(batch) # Do we have a dueling architecture. if self.uses_dueling: # Head forward passes for advantage and value stream. qf_outs = head["af"](encoder_outs[ENCODER_OUT]) vf_outs = head["vf"](encoder_outs[ENCODER_OUT]) # We learn a Q-value distribution. if self.num_atoms > 1: # Compute the advantage stream distribution. af_dist_output = self.compute_advantage_distribution(qf_outs) # Center the advantage stream distribution. centered_af_logits = af_dist_output["logits"] - af_dist_output[ "logits" ].mean(dim=-1, keepdim=True) # Calculate the Q-value distribution by adding advantage and # value stream. qf_logits = centered_af_logits + vf_outs.view( -1, *((1,) * (centered_af_logits.dim() - 1)) ) # Calculate probabilites for the Q-value distribution along # the support given by the atoms. qf_probs = nn.functional.softmax(qf_logits, dim=-1) # Return also the support as we need it in the learner. output[ATOMS] = af_dist_output[ATOMS] # Calculate the Q-values by the weighted sum over the atoms. output[QF_PREDS] = torch.sum(af_dist_output[ATOMS] * qf_probs, dim=-1) output[QF_LOGITS] = qf_logits output[QF_PROBS] = qf_probs # Otherwise we learn an expectation. else: # Center advantages. Note, we cannot do an in-place operation here # b/c we backpropagate through these values. See for a discussion # https://discuss.pytorch.org/t/gradient-computation-issue-due-to- # inplace-operation-unsure-how-to-debug-for-custom-model/170133 # Has to be a mean for each batch element. af_outs_mean = torch.nan_to_num(qf_outs, neginf=torch.nan).nanmean( dim=-1, keepdim=True ) qf_outs = qf_outs - af_outs_mean # Add advantage and value stream. Note, we broadcast here. output[QF_PREDS] = qf_outs + vf_outs # No dueling architecture. else: # Note, in this case the advantage network is the Q-network. # Forward pass through Q-head. qf_outs = head(encoder_outs[ENCODER_OUT]) # We learn a Q-value distribution. if self.num_atoms > 1: # Note in a non-dueling architecture the advantage distribution is # the Q-value distribution. # Get the Q-value distribution. qf_dist_outs = self.compute_advantage_distribution(qf_outs) # Get the support of the Q-value distribution. output[ATOMS] = qf_dist_outs[ATOMS] # Calculate the Q-values by the weighted sum over the atoms. output[QF_PREDS] = torch.sum( qf_dist_outs[ATOMS] * qf_dist_outs["probs"], dim=-1 ) output[QF_LOGITS] = qf_dist_outs["logits"] output[QF_PROBS] = qf_dist_outs["probs"] # Otherwise we learn an expectation. else: # In this case we have a Q-head of dimension (1, action_space.n). output[QF_PREDS] = qf_outs # If we have a stateful encoder add the output states to the return # dictionary. if Columns.STATE_OUT in encoder_outs: output[Columns.STATE_OUT] = encoder_outs[Columns.STATE_OUT] return output
DefaultDQNTorchRLModule
python
huggingface__transformers
src/transformers/models/deberta_v2/modeling_deberta_v2.py
{ "start": 28506, "end": 29104 }
class ____(PreTrainedModel): config: DebertaV2Config base_model_prefix = "deberta" _keys_to_ignore_on_load_unexpected = ["position_embeddings"] supports_gradient_checkpointing = True @torch.no_grad() def _init_weights(self, module): """Initialize the weights.""" super()._init_weights(module) if isinstance(module, (LegacyDebertaV2LMPredictionHead, DebertaV2LMPredictionHead)): init.zeros_(module.bias) @auto_docstring # Copied from transformers.models.deberta.modeling_deberta.DebertaModel with Deberta->DebertaV2
DebertaV2PreTrainedModel
python
joke2k__faker
faker/providers/ssn/lt_LT/__init__.py
{ "start": 42, "end": 451 }
class ____(BaseProvider): """ A Faker provider for the Lithuanian VAT IDs """ vat_id_formats = ( "LT#########", "LT############", ) def vat_id(self) -> str: """ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11 :return: a random Lithuanian VAT ID """ return self.bothify(self.random_element(self.vat_id_formats))
Provider
python
facebookresearch__faiss
tests/test_index_binary.py
{ "start": 660, "end": 2315 }
class ____(unittest.TestCase): """ Use a PQ that mimicks a binary encoder """ def test_encode_to_binary(self): d = 256 nt = 256 nb = 1500 nq = 500 (xt, xb, xq) = make_binary_dataset(d, nt, nb, nq) pq = faiss.ProductQuantizer(d, int(d / 8), 8) centroids = binary_to_float( np.tile(np.arange(256), int(d / 8)).astype('uint8').reshape(-1, 1)) faiss.copy_array_to_vector(centroids.ravel(), pq.centroids) pq.is_trained = True codes = pq.compute_codes(binary_to_float(xb)) assert np.all(codes == xb) indexpq = faiss.IndexPQ(d, int(d / 8), 8) indexpq.pq = pq indexpq.is_trained = True indexpq.add(binary_to_float(xb)) D, I = indexpq.search(binary_to_float(xq), 3) for i in range(nq): for j, dj in zip(I[i], D[i]): ref_dis = binary_dis(xq[i], xb[j]) assert 4 * ref_dis == dj nlist = 32 quantizer = faiss.IndexFlatL2(d) # pretext class for training iflat = faiss.IndexIVFFlat(quantizer, d, nlist) iflat.train(binary_to_float(xt)) indexivfpq = faiss.IndexIVFPQ(quantizer, d, nlist, int(d / 8), 8) indexivfpq.pq = pq indexivfpq.is_trained = True indexivfpq.by_residual = False indexivfpq.add(binary_to_float(xb)) indexivfpq.nprobe = 4 D, I = indexivfpq.search(binary_to_float(xq), 3) for i in range(nq): for j, dj in zip(I[i], D[i]): ref_dis = binary_dis(xq[i], xb[j]) assert 4 * ref_dis == dj
TestBinaryPQ
python
wandb__wandb
wandb/sdk/data_types/molecule.py
{ "start": 553, "end": 8972 }
class ____(BatchableMedia): """W&B class for 3D Molecular data.""" SUPPORTED_TYPES = { "pdb", "pqr", "mmcif", "mcif", "cif", "sdf", "sd", "gro", "mol2", "mmtf", } SUPPORTED_RDKIT_TYPES = {"mol", "sdf"} _log_type = "molecule-file" def __init__( self, data_or_path: Union[str, pathlib.Path, "TextIO"], caption: Optional[str] = None, **kwargs: str, ) -> None: """Initialize a Molecule object. Args: data_or_path: Molecule can be initialized from a file name or an io object. caption: Caption associated with the molecule for display. """ super().__init__(caption=caption) if hasattr(data_or_path, "name"): # if the file has a path, we just detect the type and copy it from there data_or_path = data_or_path.name if hasattr(data_or_path, "read"): if hasattr(data_or_path, "seek"): data_or_path.seek(0) molecule = data_or_path.read() extension = kwargs.pop("file_type", None) if extension is None: raise ValueError( "Must pass file_type keyword argument when using io objects." ) if extension not in Molecule.SUPPORTED_TYPES: raise ValueError( "Molecule 3D only supports files of the type: " + ", ".join(Molecule.SUPPORTED_TYPES) ) tmp_path = os.path.join( MEDIA_TMP.name, runid.generate_id() + "." + extension ) with open(tmp_path, "w") as f: f.write(molecule) self._set_file(tmp_path, is_tmp=True) elif isinstance(data_or_path, (str, pathlib.Path)): data_or_path = str(data_or_path) extension = os.path.splitext(data_or_path)[1][1:] if extension not in Molecule.SUPPORTED_TYPES: raise ValueError( "Molecule only supports files of the type: " + ", ".join(Molecule.SUPPORTED_TYPES) ) self._set_file(data_or_path, is_tmp=False) else: raise ValueError("Data must be file name or a file object") @classmethod def from_rdkit( cls, data_or_path: "RDKitDataType", caption: Optional[str] = None, convert_to_3d_and_optimize: bool = True, mmff_optimize_molecule_max_iterations: int = 200, ) -> "Molecule": """Convert RDKit-supported file/object types to wandb.Molecule. Args: data_or_path: (string, rdkit.Chem.rdchem.Mol) Molecule can be initialized from a file name or an rdkit.Chem.rdchem.Mol object. caption: (string) Caption associated with the molecule for display. convert_to_3d_and_optimize: (bool) Convert to rdkit.Chem.rdchem.Mol with 3D coordinates. This is an expensive operation that may take a long time for complicated molecules. mmff_optimize_molecule_max_iterations: (int) Number of iterations to use in rdkit.Chem.AllChem.MMFFOptimizeMolecule <!-- lazydoc-ignore-classmethod: internal --> """ rdkit_chem = util.get_module( "rdkit.Chem", required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".', ) rdkit_chem_all_chem = util.get_module( "rdkit.Chem.AllChem", required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".', ) if isinstance(data_or_path, str): # path to a file? path = pathlib.Path(data_or_path) extension = path.suffix.split(".")[-1] if extension not in Molecule.SUPPORTED_RDKIT_TYPES: raise ValueError( "Molecule.from_rdkit only supports files of the type: " + ", ".join(Molecule.SUPPORTED_RDKIT_TYPES) ) # use the appropriate method if extension == "sdf": with rdkit_chem.SDMolSupplier(data_or_path) as supplier: molecule = next(supplier) # get only the first molecule else: molecule = getattr(rdkit_chem, f"MolFrom{extension.capitalize()}File")( data_or_path ) elif isinstance(data_or_path, rdkit_chem.rdchem.Mol): molecule = data_or_path else: raise TypeError("Data must be file name or an rdkit.Chem.rdchem.Mol object") if convert_to_3d_and_optimize: molecule = rdkit_chem.AddHs(molecule) rdkit_chem_all_chem.EmbedMolecule(molecule) rdkit_chem_all_chem.MMFFOptimizeMolecule( molecule, maxIters=mmff_optimize_molecule_max_iterations, ) # convert to the pdb format supported by Molecule pdb_block = rdkit_chem.rdmolfiles.MolToPDBBlock(molecule) return cls(io.StringIO(pdb_block), caption=caption, file_type="pdb") @classmethod def from_smiles( cls, data: str, caption: Optional[str] = None, sanitize: bool = True, convert_to_3d_and_optimize: bool = True, mmff_optimize_molecule_max_iterations: int = 200, ) -> "Molecule": """Convert SMILES string to wandb.Molecule. Args: data: SMILES string. caption: Caption associated with the molecule for display. sanitize: Check if the molecule is chemically reasonable by the RDKit's definition. convert_to_3d_and_optimize: Convert to rdkit.Chem.rdchem.Mol with 3D coordinates. This is a computationally intensive operation that may take a long time for complicated molecules. mmff_optimize_molecule_max_iterations: Number of iterations to use in rdkit.Chem.AllChem.MMFFOptimizeMolecule. <!-- lazydoc-ignore-classmethod: internal --> """ rdkit_chem = util.get_module( "rdkit.Chem", required='wandb.Molecule needs the rdkit-pypi package. To get it, run "pip install rdkit-pypi".', ) molecule = rdkit_chem.MolFromSmiles(data, sanitize=sanitize) if molecule is None: raise ValueError("Unable to parse the SMILES string.") return cls.from_rdkit( data_or_path=molecule, caption=caption, convert_to_3d_and_optimize=convert_to_3d_and_optimize, mmff_optimize_molecule_max_iterations=mmff_optimize_molecule_max_iterations, ) @classmethod def get_media_subdir(cls: Type["Molecule"]) -> str: """Get media subdirectory. <!-- lazydoc-ignore-classmethod: internal --> """ return os.path.join("media", "molecule") def to_json(self, run_or_artifact: Union["LocalRun", "Artifact"]) -> dict: """Returns the JSON representation expected by the backend. <!-- lazydoc-ignore: internal --> """ json_dict = super().to_json(run_or_artifact) json_dict["_type"] = self._log_type return json_dict @classmethod def seq_to_json( cls: Type["Molecule"], seq: Sequence["BatchableMedia"], run: "LocalRun", key: str, step: Union[int, str], ) -> dict: """Convert a sequence of Molecule objects to a JSON representation. <!-- lazydoc-ignore-classmethod: internal --> """ seq = list(seq) jsons = [obj.to_json(run) for obj in seq] for obj in jsons: expected = LogicalPath(cls.get_media_subdir()) if not obj["path"].startswith(expected): raise ValueError( "Files in an array of Molecule's must be in the {} directory, not {}".format( cls.get_media_subdir(), obj["path"] ) ) return { "_type": "molecule", "filenames": [obj["path"] for obj in jsons], "count": len(jsons), "captions": Media.captions(seq), }
Molecule
python
dagster-io__dagster
python_modules/dagster-webserver/dagster_webserver/external_assets.py
{ "start": 10497, "end": 10812 }
class ____: """Class to collect all supported args by report_asset_materialization endpoint to ensure consistency with related APIs. """ asset_key = "asset_key" data_version = "data_version" metadata = "metadata" description = "description" partition = "partition"
ReportAssetMatParam
python
catalyst-team__catalyst
catalyst/callbacks/metric.py
{ "start": 1059, "end": 5005 }
class ____(_IMetricCallback): """ MetricCallback is a base implementation of callback that updates metrics over batch or loader. Args: metric: metric to calculate in callback input_key: keys of tensors that should be used as inputs in metric calculation target_key: keys of tensors that should be used as targets in metric calculation """ def __init__( self, metric: Union[ICallbackBatchMetric, ICallbackLoaderMetric], input_key: Union[str, Iterable[str], Dict[str, str]], target_key: Union[str, Iterable[str], Dict[str, str]], ): """Init MetricCallback""" super().__init__() self.metric = metric assert isinstance(metric, IMetric) self._metric_update_method = self.metric.update kv_types = (dict, list, tuple) is_value_input = isinstance(input_key, str) is_value_targets = isinstance(target_key, str) is_key_value_input = isinstance(input_key, kv_types) is_key_value_targets = isinstance(target_key, kv_types) if is_value_input and is_value_targets: self._get_inputs = self._get_value_inputs self._update_metric = self._update_value_metric elif is_key_value_input and is_key_value_targets: self._get_inputs = self._get_key_value_inputs self._update_metric = self._update_key_value_metric else: raise NotImplementedError() self.input_key = input_key self.target_key = target_key self._keys = { **self._convert_keys_to_kv(input_key), **self._convert_keys_to_kv(target_key), } @staticmethod def _convert_keys_to_kv( keys: Union[str, Iterable[str], Dict[str, str]] ) -> Dict[str, str]: """ Convert keys to key-value format Args: keys: keys to convert Returns: dict of keys like {"a": "b"} where "a" is a field name of field in batch, "b" is a name of the same data for metric """ kv_keys = {} if isinstance(keys, dict): kv_keys.update(keys) elif isinstance(keys, str): kv_keys[keys] = keys else: for key in keys: kv_keys[key] = key return kv_keys def _get_value_inputs(self, runner: "IRunner") -> Tuple[torch.Tensor, torch.Tensor]: """ Get data from batch in value input case Args: runner: current runner Returns: tuple of tensor of inputs and tensor of targets """ return runner.batch[self.input_key], runner.batch[self.target_key] def _get_key_value_inputs(self, runner: "IRunner") -> Dict[str, torch.Tensor]: """ Get data from batch in key-value input case Args: runner: current runner Returns: dict of inputs and targets tensors """ kv_inputs = {} for key in self._keys: kv_inputs[self._keys[key]] = runner.batch[key] return kv_inputs def _update_value_metric( self, value_inputs: Tuple[torch.Tensor, torch.Tensor] ) -> Optional[Dict[str, float]]: """ Update metric in value input case Args: value_inputs: tuple of input tensor and target tensor Returns: result of metric update: None or metric values """ return self._metric_update_method(*value_inputs) def _update_key_value_metric( self, kv_inputs: Dict[str, torch.Tensor] ) -> Optional[Dict[str, float]]: """ Update metric in key-value input case Args: kv_inputs: input tensors in key-value format Returns: result of metric update: None or metric values """ return self._metric_update_method(**kv_inputs)
_MetricCallback
python
ZoranPandovski__al-go-rithms
data_structures/Graphs/graphsearch/a-star-search/python/util/path.py
{ "start": 1, "end": 501 }
class ____: def __init__(self,source,destination,cost): """ Described a path from a node to another node including its cost. :param source: from this node :param destination: to this node :param cost: cost to travel the path """ self.source=source self.destination=destination self.cost=cost def __repr__(self): return "path:[source={}, destination={}, cost={}]".format(self.source,self.destination,self.cost)
path
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 109848, "end": 109897 }
class ____(str, Enum): INT8 = "int8"
ScalarType
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/manager.py
{ "start": 747, "end": 2602 }
class ____(KernelManager, QtKernelManagerMixin): """A KernelManager with Qt signals for restart""" client_class = DottedObjectName('qtconsole.client.QtKernelClient') autorestart = Bool(True, config=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._is_restarting = False def start_restarter(self): """Start restarter mechanism.""" if self.autorestart and self.has_kernel: if self._restarter is None: self._restarter = QtKernelRestarter( kernel_manager=self, parent=self, log=self.log, ) self._restarter.add_callback(self._handle_kernel_restarting) self._restarter.start() def stop_restarter(self): """Stop restarter mechanism.""" if self.autorestart: if self._restarter is not None: self._restarter.stop() def post_start_kernel(self, **kw): """Kernel restarted.""" super().post_start_kernel(**kw) if self._is_restarting: self.kernel_restarted.emit() self._is_restarting = False def reset_autorestart_count(self): """Reset autorestart count.""" if self._restarter: self._restarter.reset_count() async def _async_post_start_kernel(self, **kw): """ This is necessary for Jupyter-client 8+ because `start_kernel` doesn't call `post_start_kernel` directly. """ await super()._async_post_start_kernel(**kw) if self._is_restarting: self.kernel_restarted.emit() self._is_restarting = False def _handle_kernel_restarting(self): """Kernel has died, and will be restarted.""" self._is_restarting = True
QtKernelManager
python
huggingface__transformers
src/transformers/models/oneformer/modeling_oneformer.py
{ "start": 84575, "end": 85683 }
class ____(nn.Module): def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int = 3): """ A classic Multi Layer Perceptron (MLP). Args: input_dim (`int`): The input dimensions. hidden_dim (`int`): The hidden dimensions. output_dim (`int`): The output dimensions. num_layers (int, *optional*, defaults to 3): The number of layers. """ super().__init__() in_dims = [input_dim] + [hidden_dim] * (num_layers - 1) out_dims = [hidden_dim] * (num_layers - 1) + [output_dim] layers = [] for i, (in_dim, out_dim) in enumerate(zip(in_dims, out_dims)): layers.append( PredictionBlock(in_dim, out_dim, activation=nn.ReLU() if i < num_layers - 1 else nn.Identity()) ) self.layers = nn.Sequential(*layers) def forward(self, input: Tensor) -> Tensor: return self.layers(input) # refactored from original implementation
OneFormerMLPPredictionHead
python
numba__numba
numba/pycc/cc.py
{ "start": 494, "end": 9463 }
class ____(object): """ An ahead-of-time compiler to create extension modules that don't depend on Numba. """ # NOTE: using ccache can speed up repetitive builds # (especially for the mixin modules) _mixin_sources = ['modulemixin.c',] + extension_libs # -flto strips all unused helper functions, which 1) makes the # produced output much smaller and 2) can make the linking step faster. # (the Windows linker seems to do this by default, judging by the results) _extra_cflags = { # Comment out due to odd behavior with GCC 4.9+ with LTO # 'posix': ['-flto'], } _extra_ldflags = { # Comment out due to odd behavior with GCC 4.9+ with LTO # 'posix': ['-flto'], } def __init__(self, extension_name, source_module=None): if '.' in extension_name: raise ValueError("basename should be a simple module name, not " "qualified name") self._basename = extension_name self._init_function = 'pycc_init_' + extension_name self._exported_functions = {} # Resolve source module name and directory f = sys._getframe(1) if source_module is None: dct = f.f_globals source_module = dct['__name__'] elif hasattr(source_module, '__name__'): dct = source_module.__dict__ source_module = source_module.__name__ else: dct = sys.modules[source_module].__dict__ self._source_path = dct.get('__file__', '') self._source_module = source_module self._toolchain = Toolchain() self._verbose = False # By default, output in directory of caller module self._output_dir = os.path.dirname(self._source_path) self._output_file = self._toolchain.get_ext_filename(extension_name) self._use_nrt = True self._target_cpu = '' @property def name(self): """ The name of the extension module to create. """ return self._basename @property def output_file(self): """ The specific output file (a DLL) that will be generated. """ return self._output_file @output_file.setter def output_file(self, value): self._output_file = value @property def output_dir(self): """ The directory the output file will be put in. """ return self._output_dir @output_dir.setter def output_dir(self, value): self._output_dir = value @property def use_nrt(self): return self._use_nrt @use_nrt.setter def use_nrt(self, value): self._use_nrt = value @property def target_cpu(self): """ The target CPU model for code generation. """ return self._target_cpu @target_cpu.setter def target_cpu(self, value): self._target_cpu = value @property def verbose(self): """ Whether to display detailed information when compiling. """ return self._verbose @verbose.setter def verbose(self, value): self._verbose = value def export(self, exported_name, sig): """ Mark a function for exporting in the extension module. """ fn_args, fn_retty = sigutils.normalize_signature(sig) sig = typing.signature(fn_retty, *fn_args) if exported_name in self._exported_functions: raise KeyError("duplicated export symbol %s" % (exported_name)) def decorator(func): entry = ExportEntry(exported_name, sig, func) self._exported_functions[exported_name] = entry return func return decorator @property def _export_entries(self): return sorted(self._exported_functions.values(), key=lambda entry: entry.symbol) def _get_mixin_sources(self): here = os.path.dirname(__file__) mixin_sources = self._mixin_sources[:] if self._use_nrt: mixin_sources.append('../core/runtime/nrt.cpp') return [os.path.join(here, f) for f in mixin_sources] def _get_mixin_defines(self): # Macro definitions required by modulemixin.c return [ ('PYCC_MODULE_NAME', self._basename), ('PYCC_USE_NRT', int(self._use_nrt)), ] def _get_extra_cflags(self): extra_cflags = self._extra_cflags.get(sys.platform, []) if not extra_cflags: extra_cflags = self._extra_cflags.get(os.name, []) return extra_cflags def _get_extra_ldflags(self): extra_ldflags = self._extra_ldflags.get(sys.platform, []) if not extra_ldflags: extra_ldflags = self._extra_ldflags.get(os.name, []) # helperlib uses pthread on linux. make sure we are linking to it. if sys.platform.startswith("linux"): if "-pthread" not in extra_ldflags: extra_ldflags.append('-pthread') return extra_ldflags def _compile_mixins(self, build_dir): sources = self._get_mixin_sources() macros = self._get_mixin_defines() include_dirs = self._toolchain.get_python_include_dirs() extra_cflags = self._get_extra_cflags() # XXX distutils creates a whole subtree inside build_dir, # e.g. /tmp/test_pycc/home/antoine/numba/numba/pycc/modulemixin.o objects = self._toolchain.compile_objects(sources, build_dir, include_dirs=include_dirs, macros=macros, extra_cflags=extra_cflags) return objects @global_compiler_lock def _compile_object_files(self, build_dir): compiler = ModuleCompiler(self._export_entries, self._basename, self._use_nrt, cpu_name=self._target_cpu) compiler.external_init_function = self._init_function temp_obj = os.path.join(build_dir, os.path.splitext(self._output_file)[0] + '.o') log.info("generating LLVM code for '%s' into %s", self._basename, temp_obj) compiler.write_native_object(temp_obj, wrap=True) return [temp_obj], compiler.dll_exports @global_compiler_lock def compile(self): """ Compile the extension module. """ self._toolchain.verbose = self.verbose build_dir = tempfile.mkdtemp(prefix='pycc-build-%s-' % self._basename) # Compile object file objects, dll_exports = self._compile_object_files(build_dir) # Compile mixins objects += self._compile_mixins(build_dir) # Then create shared library extra_ldflags = self._get_extra_ldflags() output_dll = os.path.join(self._output_dir, self._output_file) libraries = self._toolchain.get_python_libraries() library_dirs = self._toolchain.get_python_library_dirs() self._toolchain.link_shared(output_dll, objects, libraries, library_dirs, export_symbols=dll_exports, extra_ldflags=extra_ldflags) shutil.rmtree(build_dir) def distutils_extension(self, **kwargs): """ Create a distutils extension object that can be used in your setup.py. """ macros = kwargs.pop('macros', []) + self._get_mixin_defines() depends = kwargs.pop('depends', []) + [self._source_path] extra_compile_args = (kwargs.pop('extra_compile_args', []) + self._get_extra_cflags()) extra_link_args = (kwargs.pop('extra_link_args', []) + self._get_extra_ldflags()) include_dirs = (kwargs.pop('include_dirs', []) + self._toolchain.get_python_include_dirs()) libraries = (kwargs.pop('libraries', []) + self._toolchain.get_python_libraries()) library_dirs = (kwargs.pop('library_dirs', []) + self._toolchain.get_python_library_dirs()) python_package_path = self._source_module[:self._source_module.rfind('.')+1] ext = _CCExtension(name=python_package_path + self._basename, sources=self._get_mixin_sources(), depends=depends, define_macros=macros, include_dirs=include_dirs, libraries=libraries, library_dirs=library_dirs, extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, **kwargs) ext.monkey_patch_distutils() ext._cc = self return ext
CC
python
aimacode__aima-python
agents.py
{ "start": 8730, "end": 12953 }
class ____: """Abstract class representing an Environment. 'Real' Environment classes inherit from this. Your Environment will typically need to implement: percept: Define the percept that an agent sees. execute_action: Define the effects of executing an action. Also update the agent.performance slot. The environment keeps a list of .things and .agents (which is a subset of .things). Each agent has a .performance slot, initialized to 0. Each thing has a .location slot, even though some environments may not need this.""" def __init__(self): self.things = [] self.agents = [] def thing_classes(self): return [] # List of classes that can go into environment def percept(self, agent): """Return the percept that the agent sees at this point. (Implement this.)""" raise NotImplementedError def execute_action(self, agent, action): """Change the world to reflect this action. (Implement this.)""" raise NotImplementedError def default_location(self, thing): """Default location to place a new thing with unspecified location.""" return None def exogenous_change(self): """If there is spontaneous change in the world, override this.""" pass def is_done(self): """By default, we're done when we can't find a live agent.""" return not any(agent.is_alive() for agent in self.agents) def step(self): """Run the environment for one time step. If the actions and exogenous changes are independent, this method will do. If there are interactions between them, you'll need to override this method.""" if not self.is_done(): actions = [] for agent in self.agents: if agent.alive: actions.append(agent.program(self.percept(agent))) else: actions.append("") for (agent, action) in zip(self.agents, actions): self.execute_action(agent, action) self.exogenous_change() def run(self, steps=1000): """Run the Environment for given number of time steps.""" for step in range(steps): if self.is_done(): return self.step() def list_things_at(self, location, tclass=Thing): """Return all things exactly at a given location.""" if isinstance(location, numbers.Number): return [thing for thing in self.things if thing.location == location and isinstance(thing, tclass)] return [thing for thing in self.things if all(x == y for x, y in zip(thing.location, location)) and isinstance(thing, tclass)] def some_things_at(self, location, tclass=Thing): """Return true if at least one of the things at location is an instance of class tclass (or a subclass).""" return self.list_things_at(location, tclass) != [] def add_thing(self, thing, location=None): """Add a thing to the environment, setting its location. For convenience, if thing is an agent program we make a new agent for it. (Shouldn't need to override this.)""" if not isinstance(thing, Thing): thing = Agent(thing) if thing in self.things: print("Can't add the same thing twice") else: thing.location = location if location is not None else self.default_location(thing) self.things.append(thing) if isinstance(thing, Agent): thing.performance = 0 self.agents.append(thing) def delete_thing(self, thing): """Remove a thing from the environment.""" try: self.things.remove(thing) except ValueError as e: print(e) print(" in Environment delete_thing") print(" Thing to be removed: {} at {}".format(thing, thing.location)) print(" from list: {}".format([(thing, thing.location) for thing in self.things])) if thing in self.agents: self.agents.remove(thing)
Environment
python
dask__dask
dask/dataframe/dask_expr/_rolling.py
{ "start": 5450, "end": 5643 }
class ____(RollingReduction): how = "agg" def _simplify_up(self, parent, dependents): # Disable optimization in `agg`; function may access other columns return
RollingAgg
python
joke2k__faker
tests/providers/test_automotive.py
{ "start": 9199, "end": 9375 }
class ____(_SimpleAutomotiveTestMixin): """Test pt_BR automotive provider methods""" license_plate_pattern: Pattern = re.compile(r"[A-Z]{3}-\d{1}[A-Z]{1}\d{2}")
TestPtBr
python
pytest-dev__pytest
testing/_py/test_local.py
{ "start": 412, "end": 17885 }
class ____: def test_constructor_equality(self, path1): p = path1.__class__(path1) assert p == path1 def test_eq_nonstring(self, path1): p1 = path1.join("sampledir") p2 = path1.join("sampledir") assert p1 == p2 def test_new_identical(self, path1): assert path1 == path1.new() def test_join(self, path1): p = path1.join("sampledir") strp = str(p) assert strp.endswith("sampledir") assert strp.startswith(str(path1)) def test_join_normalized(self, path1): newpath = path1.join(path1.sep + "sampledir") strp = str(newpath) assert strp.endswith("sampledir") assert strp.startswith(str(path1)) newpath = path1.join((path1.sep * 2) + "sampledir") strp = str(newpath) assert strp.endswith("sampledir") assert strp.startswith(str(path1)) def test_join_noargs(self, path1): newpath = path1.join() assert path1 == newpath def test_add_something(self, path1): p = path1.join("sample") p = p + "dir" assert p.check() assert p.exists() assert p.isdir() assert not p.isfile() def test_parts(self, path1): newpath = path1.join("sampledir", "otherfile") par = newpath.parts()[-3:] assert par == [path1, path1.join("sampledir"), newpath] revpar = newpath.parts(reverse=True)[:3] assert revpar == [newpath, path1.join("sampledir"), path1] def test_common(self, path1): other = path1.join("sampledir") x = other.common(path1) assert x == path1 # def test_parents_nonexisting_file(self, path1): # newpath = path1 / 'dirnoexist' / 'nonexisting file' # par = list(newpath.parents()) # assert par[:2] == [path1 / 'dirnoexist', path1] def test_basename_checks(self, path1): newpath = path1.join("sampledir") assert newpath.check(basename="sampledir") assert newpath.check(notbasename="xyz") assert newpath.basename == "sampledir" def test_basename(self, path1): newpath = path1.join("sampledir") assert newpath.check(basename="sampledir") assert newpath.basename, "sampledir" def test_dirname(self, path1): newpath = path1.join("sampledir") assert newpath.dirname == str(path1) def test_dirpath(self, path1): newpath = path1.join("sampledir") assert newpath.dirpath() == path1 def test_dirpath_with_args(self, path1): newpath = path1.join("sampledir") assert newpath.dirpath("x") == path1.join("x") def test_newbasename(self, path1): newpath = path1.join("samplefile") newbase = newpath.new(basename="samplefile2") assert newbase.basename == "samplefile2" assert newbase.dirpath() == newpath.dirpath() def test_not_exists(self, path1): assert not path1.join("does_not_exist").check() assert path1.join("does_not_exist").check(exists=0) def test_exists(self, path1): assert path1.join("samplefile").check() assert path1.join("samplefile").check(exists=1) assert path1.join("samplefile").exists() assert path1.join("samplefile").isfile() assert not path1.join("samplefile").isdir() def test_dir(self, path1): # print repr(path1.join("sampledir")) assert path1.join("sampledir").check(dir=1) assert path1.join("samplefile").check(notdir=1) assert not path1.join("samplefile").check(dir=1) assert path1.join("samplefile").exists() assert not path1.join("samplefile").isdir() assert path1.join("samplefile").isfile() def test_fnmatch_file(self, path1): assert path1.join("samplefile").check(fnmatch="s*e") assert path1.join("samplefile").fnmatch("s*e") assert not path1.join("samplefile").fnmatch("s*x") assert not path1.join("samplefile").check(fnmatch="s*x") # def test_fnmatch_dir(self, path1): # pattern = path1.sep.join(['s*file']) # sfile = path1.join("samplefile") # assert sfile.check(fnmatch=pattern) def test_relto(self, path1): p = path1.join("sampledir", "otherfile") assert p.relto(path1) == p.sep.join(["sampledir", "otherfile"]) assert p.check(relto=path1) assert path1.check(notrelto=p) assert not path1.check(relto=p) def test_bestrelpath(self, path1): curdir = path1 sep = curdir.sep s = curdir.bestrelpath(curdir) assert s == "." s = curdir.bestrelpath(curdir.join("hello", "world")) assert s == "hello" + sep + "world" s = curdir.bestrelpath(curdir.dirpath().join("sister")) assert s == ".." + sep + "sister" assert curdir.bestrelpath(curdir.dirpath()) == ".." assert curdir.bestrelpath("hello") == "hello" def test_relto_not_relative(self, path1): l1 = path1.join("bcde") l2 = path1.join("b") assert not l1.relto(l2) assert not l2.relto(l1) def test_listdir(self, path1): p = path1.listdir() assert path1.join("sampledir") in p assert path1.join("samplefile") in p with pytest.raises(error.ENOTDIR): path1.join("samplefile").listdir() def test_listdir_fnmatchstring(self, path1): p = path1.listdir("s*dir") assert len(p) assert p[0], path1.join("sampledir") def test_listdir_filter(self, path1): p = path1.listdir(lambda x: x.check(dir=1)) assert path1.join("sampledir") in p assert path1.join("samplefile") not in p def test_listdir_sorted(self, path1): p = path1.listdir(lambda x: x.check(basestarts="sample"), sort=True) assert path1.join("sampledir") == p[0] assert path1.join("samplefile") == p[1] assert path1.join("samplepickle") == p[2] def test_visit_nofilter(self, path1): lst = [] for i in path1.visit(): lst.append(i.relto(path1)) assert "sampledir" in lst assert path1.sep.join(["sampledir", "otherfile"]) in lst def test_visit_norecurse(self, path1): lst = [] for i in path1.visit(None, lambda x: x.basename != "sampledir"): lst.append(i.relto(path1)) assert "sampledir" in lst assert path1.sep.join(["sampledir", "otherfile"]) not in lst def test_visit_filterfunc_is_string(self, path1): lst = [] for i in path1.visit("*dir"): lst.append(i.relto(path1)) assert len(lst), 2 # noqa: PLC1802,RUF040 assert "sampledir" in lst assert "otherdir" in lst def test_visit_ignore(self, path1): p = path1.join("nonexisting") assert list(p.visit(ignore=error.ENOENT)) == [] def test_visit_endswith(self, path1): p = [] for i in path1.visit(lambda x: x.check(endswith="file")): p.append(i.relto(path1)) assert path1.sep.join(["sampledir", "otherfile"]) in p assert "samplefile" in p def test_cmp(self, path1): path1 = path1.join("samplefile") path2 = path1.join("samplefile2") assert (path1 < path2) == ("samplefile" < "samplefile2") assert not (path1 < path1) def test_simple_read(self, path1): with ignore_encoding_warning(): x = path1.join("samplefile").read("r") assert x == "samplefile\n" def test_join_div_operator(self, path1): newpath = path1 / "/sampledir" / "/test//" newpath2 = path1.join("sampledir", "test") assert newpath == newpath2 def test_ext(self, path1): newpath = path1.join("sampledir.ext") assert newpath.ext == ".ext" newpath = path1.join("sampledir") assert not newpath.ext def test_purebasename(self, path1): newpath = path1.join("samplefile.py") assert newpath.purebasename == "samplefile" def test_multiple_parts(self, path1): newpath = path1.join("samplefile.py") dirname, purebasename, basename, ext = newpath._getbyspec( "dirname,purebasename,basename,ext" ) assert str(path1).endswith(dirname) # be careful with win32 'drive' assert purebasename == "samplefile" assert basename == "samplefile.py" assert ext == ".py" def test_dotted_name_ext(self, path1): newpath = path1.join("a.b.c") ext = newpath.ext assert ext == ".c" assert newpath.ext == ".c" def test_newext(self, path1): newpath = path1.join("samplefile.py") newext = newpath.new(ext=".txt") assert newext.basename == "samplefile.txt" assert newext.purebasename == "samplefile" def test_readlines(self, path1): fn = path1.join("samplefile") with ignore_encoding_warning(): contents = fn.readlines() assert contents == ["samplefile\n"] def test_readlines_nocr(self, path1): fn = path1.join("samplefile") with ignore_encoding_warning(): contents = fn.readlines(cr=0) assert contents == ["samplefile", ""] def test_file(self, path1): assert path1.join("samplefile").check(file=1) def test_not_file(self, path1): assert not path1.join("sampledir").check(file=1) assert path1.join("sampledir").check(file=0) def test_non_existent(self, path1): assert path1.join("sampledir.nothere").check(dir=0) assert path1.join("sampledir.nothere").check(file=0) assert path1.join("sampledir.nothere").check(notfile=1) assert path1.join("sampledir.nothere").check(notdir=1) assert path1.join("sampledir.nothere").check(notexists=1) assert not path1.join("sampledir.nothere").check(notfile=0) # pattern = path1.sep.join(['s*file']) # sfile = path1.join("samplefile") # assert sfile.check(fnmatch=pattern) def test_size(self, path1): url = path1.join("samplefile") assert url.size() > len("samplefile") def test_mtime(self, path1): url = path1.join("samplefile") assert url.mtime() > 0 def test_relto_wrong_type(self, path1): with pytest.raises(TypeError): path1.relto(42) def test_load(self, path1): p = path1.join("samplepickle") obj = p.load() assert type(obj) is dict assert obj.get("answer", None) == 42 def test_visit_filesonly(self, path1): p = [] for i in path1.visit(lambda x: x.check(file=1)): p.append(i.relto(path1)) assert "sampledir" not in p assert path1.sep.join(["sampledir", "otherfile"]) in p def test_visit_nodotfiles(self, path1): p = [] for i in path1.visit(lambda x: x.check(dotfile=0)): p.append(i.relto(path1)) assert "sampledir" in p assert path1.sep.join(["sampledir", "otherfile"]) in p assert ".dotfile" not in p def test_visit_breadthfirst(self, path1): lst = [] for i in path1.visit(bf=True): lst.append(i.relto(path1)) for i, p in enumerate(lst): if path1.sep in p: for j in range(i, len(lst)): assert path1.sep in lst[j] break else: pytest.fail("huh") def test_visit_sort(self, path1): lst = [] for i in path1.visit(bf=True, sort=True): lst.append(i.relto(path1)) for i, p in enumerate(lst): if path1.sep in p: break assert lst[:i] == sorted(lst[:i]) assert lst[i:] == sorted(lst[i:]) def test_endswith(self, path1): def chk(p): return p.check(endswith="pickle") assert not chk(path1) assert not chk(path1.join("samplefile")) assert chk(path1.join("somepickle")) def test_copy_file(self, path1): otherdir = path1.join("otherdir") initpy = otherdir.join("__init__.py") copied = otherdir.join("copied") initpy.copy(copied) try: assert copied.check() s1 = initpy.read_text(encoding="utf-8") s2 = copied.read_text(encoding="utf-8") assert s1 == s2 finally: if copied.check(): copied.remove() def test_copy_dir(self, path1): otherdir = path1.join("otherdir") copied = path1.join("newdir") try: otherdir.copy(copied) assert copied.check(dir=1) assert copied.join("__init__.py").check(file=1) s1 = otherdir.join("__init__.py").read_text(encoding="utf-8") s2 = copied.join("__init__.py").read_text(encoding="utf-8") assert s1 == s2 finally: if copied.check(dir=1): copied.remove(rec=1) def test_remove_file(self, path1): d = path1.ensure("todeleted") assert d.check() d.remove() assert not d.check() def test_remove_dir_recursive_by_default(self, path1): d = path1.ensure("to", "be", "deleted") assert d.check() p = path1.join("to") p.remove() assert not p.check() def test_ensure_dir(self, path1): b = path1.ensure_dir("001", "002") assert b.basename == "002" assert b.isdir() def test_mkdir_and_remove(self, path1): tmpdir = path1 with pytest.raises(error.EEXIST): tmpdir.mkdir("sampledir") new = tmpdir.join("mktest1") new.mkdir() assert new.check(dir=1) new.remove() new = tmpdir.mkdir("mktest") assert new.check(dir=1) new.remove() assert tmpdir.join("mktest") == new def test_move_file(self, path1): p = path1.join("samplefile") newp = p.dirpath("moved_samplefile") p.move(newp) try: assert newp.check(file=1) assert not p.check() finally: dp = newp.dirpath() if hasattr(dp, "revert"): dp.revert() else: newp.move(p) assert p.check() def test_move_dir(self, path1): source = path1.join("sampledir") dest = path1.join("moveddir") source.move(dest) assert dest.check(dir=1) assert dest.join("otherfile").check(file=1) assert not source.join("sampledir").check() def test_fspath_protocol_match_strpath(self, path1): assert path1.__fspath__() == path1.strpath def test_fspath_func_match_strpath(self, path1): from os import fspath assert fspath(path1) == path1.strpath def test_fspath_open(self, path1): f = path1.join("samplefile") stream = open(f, encoding="utf-8") stream.close() def test_fspath_fsencode(self, path1): from os import fsencode assert fsencode(path1) == fsencode(path1.strpath) def setuptestfs(path): if path.join("samplefile").check(): return # print "setting up test fs for", repr(path) samplefile = path.ensure("samplefile") samplefile.write_text("samplefile\n", encoding="utf-8") execfile = path.ensure("execfile") execfile.write_text("x=42", encoding="utf-8") execfilepy = path.ensure("execfile.py") execfilepy.write_text("x=42", encoding="utf-8") d = {1: 2, "hello": "world", "answer": 42} path.ensure("samplepickle").dump(d) sampledir = path.ensure("sampledir", dir=1) sampledir.ensure("otherfile") otherdir = path.ensure("otherdir", dir=1) otherdir.ensure("__init__.py") module_a = otherdir.ensure("a.py") module_a.write_text("from .b import stuff as result\n", encoding="utf-8") module_b = otherdir.ensure("b.py") module_b.write_text('stuff="got it"\n', encoding="utf-8") module_c = otherdir.ensure("c.py") module_c.write_text( """import py; import otherdir.a value = otherdir.a.result """, encoding="utf-8", ) module_d = otherdir.ensure("d.py") module_d.write_text( """import py; from otherdir import a value2 = a.result """, encoding="utf-8", ) win32only = pytest.mark.skipif( "not (sys.platform == 'win32' or getattr(os, '_name', None) == 'nt')" ) skiponwin32 = pytest.mark.skipif( "sys.platform == 'win32' or getattr(os, '_name', None) == 'nt'" ) ATIME_RESOLUTION = 0.01 @pytest.fixture(scope="session") def path1(tmpdir_factory): path = tmpdir_factory.mktemp("path") setuptestfs(path) yield path assert path.join("samplefile").check() @pytest.fixture def fake_fspath_obj(request): class FakeFSPathClass: def __init__(self, path): self._path = path def __fspath__(self): return self._path return FakeFSPathClass(os.path.join("this", "is", "a", "fake", "path")) def batch_make_numbered_dirs(rootdir, repeats): for i in range(repeats): dir_ = local.make_numbered_dir(prefix="repro-", rootdir=rootdir) file_ = dir_.join("foo") file_.write_text(f"{i}", encoding="utf-8") actual = int(file_.read_text(encoding="utf-8")) assert actual == i, ( f"int(file_.read_text(encoding='utf-8')) is {actual} instead of {i}" ) dir_.join(".lock").remove(ignore_errors=True) return True
CommonFSTests
python
ray-project__ray
python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py
{ "start": 9971, "end": 14438 }
class ____: """Tests for input normalization in the prefix-aware router.""" def test_normalize_prompt_string(self, prefix_request_router): req = fake_pending_request(prompt="Hello world") normalized = prefix_request_router._extract_text_from_request(req) assert normalized == "Hello world" def test_normalize_messages_list_of_strings(self, prefix_request_router): req = fake_pending_request(messages=["Hello", " ", "world"]) normalized = prefix_request_router._extract_text_from_request(req) assert normalized == "Hello world" def test_normalize_messages_dict_content_string(self, prefix_request_router): req = fake_pending_request( messages=[ {"content": "Hello"}, {"content": " world"}, ] ) normalized = prefix_request_router._extract_text_from_request(req) assert normalized == "Hello world" def test_normalize_messages_dict_content_list_of_dicts_text( self, prefix_request_router ): req = fake_pending_request( messages=[ { "content": [ {"type": "text", "text": "Hello"}, {"type": "text", "text": " world"}, ] } ] ) normalized = prefix_request_router._extract_text_from_request(req) assert normalized == "Hello world" def test_normalize_messages_dict_content_list_of_strings( self, prefix_request_router ): req = fake_pending_request(messages=[{"content": ["Hello", " ", "world"]}]) normalized = prefix_request_router._extract_text_from_request(req) assert normalized == "Hello world" def test_normalize_unsupported_returns_empty(self, prefix_request_router): # For now, unsupported multimodal parts should be ignored, resulting in empty string req = fake_pending_request( messages=[ { "content": [ { "type": "image_url", "image_url": {"url": "http://example.com"}, }, ] } ] ) normalized = prefix_request_router._extract_text_from_request(req) assert normalized == "" def test_extract_raises_when_no_prompt_or_messages(self, prefix_request_router): with pytest.raises(ValueError): _ = prefix_request_router._extract_text_from_request(fake_pending_request()) @pytest.mark.asyncio @pytest.mark.parametrize( "prefix_request_router", [ { "do_eviction": True, "eviction_threshold_chars": 10, "eviction_target_chars": 5, "eviction_interval_secs": 1.0, } ], indirect=True, ) async def test_eviction_threshold_behavior(self, prefix_request_router): """Test that eviction reduces tree size below threshold after interval.""" r1 = FakeRunningReplica("r1") prefix_request_router.update_replicas([r1]) # Insert text that exceeds eviction_threshold_chars ray.get( prefix_request_router._tree_actor.insert.remote( "verylongtext", r1.replica_id.to_full_id_str(), time.time() ) ) ray.get( prefix_request_router._tree_actor.insert.remote( "anotherlongtext", r1.replica_id.to_full_id_str(), time.time() ) ) # Verify initial size exceeds eviction_threshold_chars tenant_counts = ray.get( prefix_request_router._tree_actor.getattr.remote("tenant_to_char_count") ) assert tenant_counts[r1.replica_id.to_full_id_str()] > 10 # Wait for eviction interval await asyncio.sleep(1.1) # Verify size is reduced below eviction_target_chars tenant_counts = ray.get( prefix_request_router._tree_actor.getattr.remote("tenant_to_char_count") ) assert tenant_counts[r1.replica_id.to_full_id_str()] <= 5 ray.get(prefix_request_router._tree_actor.stop_eviction_loop.remote()) await asyncio.sleep(0.1) if __name__ == "__main__": import sys exit_code = pytest.main(["-vs", __file__]) sys.exit(exit_code)
TestPromptNormalization
python
huggingface__transformers
src/transformers/core_model_loading.py
{ "start": 3502, "end": 4565 }
class ____(ConversionOps): """Split a tensor along ``dim`` into equally sized chunks.""" def __init__(self, dim: int = 0): self.dim = dim @torch.no_grad def convert( self, input_dict: dict[str, torch.Tensor], source_patterns: list[str], target_patterns: list[str], **kwargs ) -> dict[str, torch.Tensor]: tensors = next(iter(input_dict.values())) tensor = tensors[0] if isinstance(tensors, list) else tensors targets = self.get_target_pattern(input_dict, target_patterns) sizes = len(targets) chunks = torch.chunk(tensor, sizes, dim=self.dim) return dict(zip(targets, chunks)) def get_target_pattern(self, input_dict: dict, target_patterns: list[str]) -> list[str]: # Here we always return the target patterns if len(input_dict) > 1 or len(target_patterns) == 1: raise ValueError("Undefined Operation encountered!") return target_patterns @property def reverse_op(self) -> ConversionOps: return Concatenate(self.dim)
Chunk
python
huggingface__transformers
src/transformers/models/git/modeling_git.py
{ "start": 11352, "end": 12854 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_idx=None): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = GitAttention(config, layer_idx=layer_idx) self.intermediate = GitIntermediate(config) self.output = GitOutput(config) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Cache] = None, output_attentions: Optional[bool] = False, pixel_values_present: Optional[bool] = False, ) -> tuple[torch.Tensor]: # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 attention_output, self_attention_weights = self.attention( hidden_states, attention_mask, output_attentions=output_attentions, past_key_values=past_key_values, pixel_values_present=pixel_values_present, ) layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output ) return layer_output, self_attention_weights def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output
GitLayer
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py
{ "start": 6161, "end": 7012 }
class ____(Node): __slots__ = ('loc', 'name', 'value',) _fields = ('name', 'value',) def __init__(self, name, value, loc=None): self.loc = loc self.name = name self.value = value def __eq__(self, other): return ( self is other or ( isinstance(other, Argument) and # self.loc == other.loc and self.name == other.name and self.value == other.value ) ) def __repr__(self): return ('Argument(' 'name={self.name!r}' ', value={self.value!r}' ')').format(self=self) def __copy__(self): return type(self)( self.name, self.value, self.loc ) def __hash__(self): return id(self)
Argument
python
plotly__plotly.py
plotly/graph_objs/densitymap/colorbar/title/_font.py
{ "start": 233, "end": 9929 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "densitymap.colorbar.title" _path_str = "densitymap.colorbar.title.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["family"] @family.setter def family(self, val): self["family"] = val @property def lineposition(self): """ Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. The 'lineposition' property is a flaglist and may be specified as a string containing: - Any combination of ['under', 'over', 'through'] joined with '+' characters (e.g. 'under+over') OR exactly one of ['none'] (e.g. 'none') Returns ------- Any """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = val @property def shadow(self): """ Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options. The 'shadow' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = val @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def style(self): """ Sets whether a font should be styled with a normal or italic face from its family. The 'style' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'italic'] Returns ------- Any """ return self["style"] @style.setter def style(self, val): self["style"] = val @property def textcase(self): """ Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. The 'textcase' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'word caps', 'upper', 'lower'] Returns ------- Any """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = val @property def variant(self): """ Sets the variant of the font. The 'variant' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'] Returns ------- Any """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = val @property def weight(self): """ Sets the weight (or boldness) of the font. The 'weight' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 1000] OR exactly one of ['normal', 'bold'] (e.g. 'bold') Returns ------- int """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def _prop_descriptions(self): return """\ color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. """ def __init__( self, arg=None, color=None, family=None, lineposition=None, shadow=None, size=None, style=None, textcase=None, variant=None, weight=None, **kwargs, ): """ Construct a new Font object Sets this color bar's title font. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.densitymap.col orbar.title.Font` color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. Returns ------- Font """ super().__init__("font") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.densitymap.colorbar.title.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.densitymap.colorbar.title.Font`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("family", arg, family) self._set_property("lineposition", arg, lineposition) self._set_property("shadow", arg, shadow) self._set_property("size", arg, size) self._set_property("style", arg, style) self._set_property("textcase", arg, textcase) self._set_property("variant", arg, variant) self._set_property("weight", arg, weight) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Font
python
ray-project__ray
doc/source/serve/doc_code/http_guide/http_guide.py
{ "start": 122, "end": 533 }
class ____: def __call__(self, request: starlette.requests.Request): return request.query_params serve.run(Counter.bind()) resp = requests.get("http://localhost:8000?a=b&c=d") assert resp.json() == {"a": "b", "c": "d"} # __end_starlette__ # __begin_fastapi__ import ray import requests from fastapi import FastAPI from ray import serve app = FastAPI() @serve.deployment @serve.ingress(app)
Counter
python
Textualize__textual
docs/examples/guide/layout/dock_layout2_sidebar.py
{ "start": 344, "end": 672 }
class ____(App): CSS_PATH = "dock_layout2_sidebar.tcss" def compose(self) -> ComposeResult: yield Static("Sidebar2", id="another-sidebar") yield Static("Sidebar1", id="sidebar") yield Static(TEXT * 10, id="body") app = DockLayoutExample() if __name__ == "__main__": app.run()
DockLayoutExample
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-databricks/llama_index/vector_stores/databricks/base.py
{ "start": 769, "end": 876 }
class ____(str, Enum): DIRECT_ACCESS = "DIRECT_ACCESS" DELTA_SYNC = "DELTA_SYNC"
_DatabricksIndexType
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 185382, "end": 205505 }
class ____(Response): """ Response of frames.get_next endpoint. :param frames: Frames list :type frames: Sequence[Frame] :param frames_returned: Number of frames returned :type frames_returned: int :param scroll_state: JSON object representing the scroll state :type scroll_state: dict :param scroll_id: Scroll session id to be provided in order to get the next batch of images :type scroll_id: str :param roi_stats: Json object containing the count per labels in frames, e.g. { 'background': 312, 'boat': 2, 'bus': 4, 'car': 2, } :type roi_stats: dict :param eof: When 'frames' is empty, represents whether there are no more frames left. If "false", client can retry the operation. :type eof: bool """ _service = "frames" _action = "get_next" _version = "2.23" _schema = { "definitions": { "augmentation": { "properties": { "arguments": { "additionalProperties": True, "description": "Arguments dictionary, passed to custom augmentations.", "type": ["object", "null"], }, "cls": { "description": "Augmentation class (see global definitions)", "type": ["string", "null"], }, "params": { "description": ( "Transform parameters, an array ot 3 randomly generated values. Fixed values are passed in" " case of affine reflect augmentation." ), "items": {"type": "number"}, "type": ["array", "null"], }, "strength": { "description": "Transform strength. Required for pixel transforms.", "type": ["number", "null"], }, "trans_mat": { "description": "Transform matrix (list of lists). Required for affine transforms.", "items": {"items": {"type": "number"}, "type": "array"}, "type": ["array", "null"], }, "type": { "description": "Augmentation type (see global definitions)", "type": ["string", "null"], }, }, "type": "object", }, "dataset_version": { "properties": { "id": {"description": "Dataset id", "type": ["string", "null"]}, "version": { "description": "Dataset version id", "type": ["string", "null"], }, }, "type": "object", }, "frame": { "properties": { "augmentation": { "description": "List of augmentations", "items": {"$ref": "#/definitions/augmentation"}, "type": ["array", "null"], }, "blob": { "description": "Raw data (blob) for the frame", "type": ["string", "null"], }, "context_id": { "description": ( "Context ID. Used for the default frames sorting. If not set then it is filled from the uri" " of the first source." ), "type": ["string", "null"], }, "dataset": { "description": "Frame's dataset version", "oneOf": [ {"$ref": "#/definitions/dataset_version"}, {"type": "null"}, ], }, "id": {"description": "Frame id", "type": ["string", "null"]}, "is_key_frame": { "description": "Is this a key frame (only applicable in frames who'se src is a video)", "type": ["boolean", "null"], }, "key_frame": { "description": "ID of the key frame that this frame belongs to", "type": ["string", "null"], }, "label_rule_counts": { "additionalProperties": True, "description": "The number of matched roi per lable rule", "type": ["object", "null"], }, "labels_size": { "description": "Number of labels returned", "type": ["integer", "null"], }, "meta": { "additionalProperties": True, "description": ( "Additional metadata dictionary for the frame. Please note that using this field" " effectively defines a schema (dictionary structure and types used as values) - frames" " within the same dataset cannot use conflicting schemas for this field (see documentation" " for more details)." ), "type": ["object", "null"], }, "meta_blob": { "additionalProperties": True, "description": ( "Non searchable metadata dictionary for the frame. The fields in this object cannot be" " searched by and are not added to the frame schema" ), "type": ["object", "null"], }, "new_ver": { "description": "Newer version of this frame, if asked to merge", "oneOf": [{"$ref": "#/definitions/frame"}, {"type": "null"}], }, "rois": { "description": "Frame regions of interest", "items": {"$ref": "#/definitions/roi"}, "type": ["array", "null"], }, "rule_name": { "description": ( "Name of the filtering rule according to which this frame was provided (if applicable)" ), "type": ["string", "null"], }, "saved": { "description": "Last time frame was saved (timestamp)", "type": ["integer", "null"], }, "saved_in_version": { "description": "Last version this frame was saved in (version ID)", "type": ["string", "null"], }, "sources": { "description": "Sources of this frame", "items": {"$ref": "#/definitions/source"}, "type": ["array", "null"], }, "timestamp": { "description": ( "Frame's offset in milliseconds, used primarily for video content. Used for the default" " frames sorting as the secondary key (with the primary key being 'context_id'). For" " images, this value should typically be 0. If not set, value is filled from the timestamp" " of the first source. We recommend using this field only in cases concerning the default" " sorting behavior." ), "type": ["integer", "null"], }, "updated": { "description": "Last time frame was saved (timestamp)", "type": ["integer", "null"], }, "updated_in_version": { "description": "Last version this frame was updated in (version ID)", "type": ["string", "null"], }, "video_gop": { "description": ( "Video encoding GOP value for the source of this frame. Only valid for video frames" ), "type": ["number", "null"], }, }, "type": "object", }, "mask": { "properties": { "content_type": { "description": "Content type (e.g. 'image/jpeg', 'image/png')", "type": ["string", "null"], }, "height": { "description": "Height in pixels", "type": ["integer", "null"], }, "id": { "description": "unique ID (in this frame)", "type": ["string", "null"], }, "timestamp": { "default": 0, "description": ( "Timestamp in the source data (for video content. for images, this value should be 0)" ), "type": ["integer", "null"], }, "uri": {"description": "Data URI", "type": ["string", "null"]}, "width": { "description": "Width in pixels", "type": ["integer", "null"], }, }, "type": "object", }, "preview": { "properties": { "content_type": { "description": "Content type (e.g. 'image/jpeg', 'image/png')", "type": ["string", "null"], }, "height": { "description": "Height in pixels", "type": ["integer", "null"], }, "timestamp": { "default": 0, "description": ( "Timestamp in the source data (for video content. for images, this value should be 0)" ), "type": ["integer", "null"], }, "uri": {"description": "Data URI", "type": ["string", "null"]}, "width": { "description": "Width in pixels", "type": ["integer", "null"], }, }, "type": "object", }, "roi": { "properties": { "area": { "description": "ROI area (not used)", "type": ["integer", "null"], }, "confidence": { "description": "ROI confidence", "type": ["number", "null"], }, "id": {"description": "ROI id", "type": ["string", "null"]}, "label": { "description": "ROI labels", "items": {"type": "string"}, "type": ["array", "null"], }, "label_num": { "description": ( "Label number according to the specified labels mapping Used only when ROI is returned as" " part of a task's frame." ), "type": ["integer", "null"], }, "mask": { "description": "Mask info for this ROI", "oneOf": [{"$ref": "#/definitions/roi_mask"}, {"type": "null"}], }, "meta": { "additionalProperties": True, "description": "Additional metadata dictionary for the roi", "type": ["object", "null"], }, "poly": { "description": "ROI polygon (x0, y0, ..., xn, yn)", "items": {"type": "number"}, "type": ["array", "null"], }, "sources": { "description": "Sources that this ROI belongs to", "items": {"type": "string"}, "type": ["array", "null"], }, }, "type": "object", }, "roi_mask": { "properties": { "id": {"description": "Mask ID", "type": "string"}, "value": { "description": "Mask value", "items": {"type": "integer"}, "type": "array", }, }, "required": ["id", "value"], "type": "object", }, "source": { "properties": { "content_type": { "description": "Content type (e.g. 'image/jpeg', 'image/png')", "type": ["string", "null"], }, "height": { "description": "Height in pixels", "type": ["integer", "null"], }, "id": { "description": "unique ID (in this frame)", "type": ["string", "null"], }, "masks": { "items": {"$ref": "#/definitions/mask"}, "type": ["array", "null"], }, "meta": { "additionalProperties": True, "description": "Additional metadata dictionary for the source", "type": ["object", "null"], }, "preview": { "oneOf": [{"$ref": "#/definitions/preview"}, {"type": "null"}] }, "timestamp": { "default": 0, "description": ( "Timestamp in the source data (for video content. for images, this value should be 0)" ), "type": ["integer", "null"], }, "uri": {"description": "Data URI", "type": ["string", "null"]}, "width": { "description": "Width in pixels", "type": ["integer", "null"], }, }, "type": "object", }, }, "properties": { "eof": { "description": ( "When 'frames' is empty, represents whether there are no more frames left. " 'If "false",\n' " client can retry the " "operation." ), "type": ["boolean", "null"], }, "frames": { "description": "Frames list", "items": {"$ref": "#/definitions/frame"}, "type": ["array", "null"], }, "frames_returned": { "description": "Number of frames returned", "type": ["integer", "null"], }, "roi_stats": { "additionalProperties": {"type": "integer"}, "description": ( "Json object containing the count per labels in frames, e.g.\n {\n " " 'background': 312,\n 'boat': 2,\n 'bus': 4,\n " " 'car': 2,\n }" ), "type": ["object", "null"], }, "scroll_id": { "description": "Scroll session id to be provided in order to get the next batch of images", "type": ["string", "null"], }, "scroll_state": { "additionalProperties": True, "description": "JSON object representing the scroll state", "type": ["object", "null"], }, }, "type": "object", } def __init__( self, frames=None, frames_returned=None, scroll_state=None, scroll_id=None, roi_stats=None, eof=None, **kwargs ): super(GetNextResponse, self).__init__(**kwargs) self.frames = frames self.frames_returned = frames_returned self.scroll_state = scroll_state self.scroll_id = scroll_id self.roi_stats = roi_stats self.eof = eof @schema_property("frames") def frames(self): return self._property_frames @frames.setter def frames(self, value): if value is None: self._property_frames = None return self.assert_isinstance(value, "frames", (list, tuple)) if any(isinstance(v, dict) for v in value): value = [Frame.from_dict(v) if isinstance(v, dict) else v for v in value] else: self.assert_isinstance(value, "frames", Frame, is_array=True) self._property_frames = value @schema_property("frames_returned") def frames_returned(self): return self._property_frames_returned @frames_returned.setter def frames_returned(self, value): if value is None: self._property_frames_returned = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "frames_returned", six.integer_types) self._property_frames_returned = value @schema_property("scroll_state") def scroll_state(self): return self._property_scroll_state @scroll_state.setter def scroll_state(self, value): if value is None: self._property_scroll_state = None return self.assert_isinstance(value, "scroll_state", (dict,)) self._property_scroll_state = value @schema_property("scroll_id") def scroll_id(self): return self._property_scroll_id @scroll_id.setter def scroll_id(self, value): if value is None: self._property_scroll_id = None return self.assert_isinstance(value, "scroll_id", six.string_types) self._property_scroll_id = value @schema_property("roi_stats") def roi_stats(self): return self._property_roi_stats @roi_stats.setter def roi_stats(self, value): if value is None: self._property_roi_stats = None return self.assert_isinstance(value, "roi_stats", (dict,)) self._property_roi_stats = value @schema_property("eof") def eof(self): return self._property_eof @eof.setter def eof(self, value): if value is None: self._property_eof = None return self.assert_isinstance(value, "eof", (bool,)) self._property_eof = value
GetNextResponse
python
scipy__scipy
scipy/optimize/tests/test__shgo.py
{ "start": 15915, "end": 34780 }
class ____: def test_1_1_simpl_iter(self): """Iterative simplicial sampling on TestFunction 1 (multivariate)""" run_test(test1_2, n=None, iters=2, sampling_method='simplicial') def test_1_2_simpl_iter(self): """Iterative simplicial on TestFunction 2 (univariate)""" options = {'minimize_every_iter': False} run_test(test2_1, n=None, iters=9, options=options, sampling_method='simplicial') def test_2_1_sobol_iter(self): """Iterative Sobol sampling on TestFunction 1 (multivariate)""" run_test(test1_2, n=None, iters=1, sampling_method='sobol') def test_2_2_sobol_iter(self): """Iterative Sobol sampling on TestFunction 2 (univariate)""" res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons, n=None, iters=1, sampling_method='sobol') np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5) np.testing.assert_allclose(res.fun, test2_1.expected_fun, atol=1e-5) def test_3_1_disp_simplicial(self): """Iterative sampling on TestFunction 1 and 2 (multi and univariate) """ def callback_func(x): print("Local minimization callback test") for test in [test1_1, test2_1]: shgo(test.f, test.bounds, iters=1, sampling_method='simplicial', callback=callback_func, options={'disp': True}) shgo(test.f, test.bounds, n=1, sampling_method='simplicial', callback=callback_func, options={'disp': True}) def test_3_2_disp_sobol(self): """Iterative sampling on TestFunction 1 and 2 (multi and univariate)""" def callback_func(x): print("Local minimization callback test") for test in [test1_1, test2_1]: shgo(test.f, test.bounds, iters=1, sampling_method='sobol', callback=callback_func, options={'disp': True}) shgo(test.f, test.bounds, n=1, sampling_method='simplicial', callback=callback_func, options={'disp': True}) def test_args_gh14589(self): """Using `args` used to cause `shgo` to fail; see #14589, #15986, #16506""" res = shgo(func=lambda x, y, z: x * z + y, bounds=[(0, 3)], args=(1, 2) ) ref = shgo(func=lambda x: 2 * x + 1, bounds=[(0, 3)]) assert_allclose(res.fun, ref.fun) assert_allclose(res.x, ref.x) def test_args_gh23517(self): """ Checks that using `args` for func, jac and hess works """ obj = MaratosTestArgs("a", 234) obj.bounds = Bounds([-5, -5], [5, 5]) res2 = minimize( obj.fun, [4.0, 4.0], constraints=obj.constr, bounds=obj.bounds, method='trust-constr', args=("a", 234), jac=obj.grad ) assert_allclose(res2.x, obj.x_opt, atol=1e-6) obj = MaratosTestArgs("a", 234) obj.bounds = Bounds([-10., -10.], [10., 10.]) with warnings.catch_warnings(): # warnings are from initialization of NonlinearConstraint and # poor initialization of the constraint by shgo warnings.simplefilter( "ignore", (OptimizeWarning, RuntimeWarning) ) res = shgo( func=obj.fun, bounds=obj.bounds, args=("a", 234), minimizer_kwargs={ "method": 'trust-constr', "constraints": obj.constr, "bounds": obj.bounds, "jac": obj.grad, "args": ("a", 234), }, constraints=obj.constr, sampling_method='sobol', ) assert_allclose(res.x, obj.x_opt, atol=1e-6) res = shgo( func=obj.fun, bounds=obj.bounds, args=("a", 234), minimizer_kwargs={ "method": 'trust-constr', "constraints": obj.constr, "bounds": obj.bounds, "jac": obj.grad, "hess": obj.hess, }, constraints=obj.constr, sampling_method='sobol', ) assert_allclose(res.x, obj.x_opt, atol=1e-6) @pytest.mark.slow def test_4_1_known_f_min(self): """Test known function minima stopping criteria""" # Specify known function value options = {'f_min': test4_1.expected_fun, 'f_tol': 1e-6, 'minimize_every_iter': True} # TODO: Make default n higher for faster tests run_test(test4_1, n=None, test_atol=1e-5, options=options, sampling_method='simplicial') @pytest.mark.slow def test_4_2_known_f_min(self): """Test Global mode limiting local evaluations""" options = { # Specify known function value 'f_min': test4_1.expected_fun, 'f_tol': 1e-6, # Specify number of local iterations to perform 'minimize_every_iter': True, 'local_iter': 1} run_test(test4_1, n=None, test_atol=1e-5, options=options, sampling_method='simplicial') def test_4_4_known_f_min(self): """Test Global mode limiting local evaluations for 1D funcs""" options = { # Specify known function value 'f_min': test2_1.expected_fun, 'f_tol': 1e-6, # Specify number of local iterations to perform+ 'minimize_every_iter': True, 'local_iter': 1, 'infty_constraints': False} res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons, n=None, iters=None, options=options, sampling_method='sobol') np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5) def test_5_1_simplicial_argless(self): """Test Default simplicial sampling settings on TestFunction 1""" res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons) np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5) def test_5_2_sobol_argless(self): """Test Default sobol sampling settings on TestFunction 1""" res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons, sampling_method='sobol') np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5) def test_6_1_simplicial_max_iter(self): """Test that maximum iteration option works on TestFunction 3""" options = {'max_iter': 2} res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons, options=options, sampling_method='simplicial') np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5) np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5) def test_6_2_simplicial_min_iter(self): """Test that maximum iteration option works on TestFunction 3""" options = {'min_iter': 2} res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons, options=options, sampling_method='simplicial') np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5) np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5) def test_7_1_minkwargs(self): """Test the minimizer_kwargs arguments for solvers with constraints""" # Test solvers for solver in ['COBYLA', 'COBYQA', 'SLSQP']: # Note that passing global constraints to SLSQP is tested in other # unittests which run test4_1 normally minimizer_kwargs = {'method': solver, 'constraints': test3_1.cons} run_test(test3_1, n=100, test_atol=1e-3, minimizer_kwargs=minimizer_kwargs, sampling_method='sobol') def test_7_2_minkwargs(self): """Test the minimizer_kwargs default inits""" minimizer_kwargs = {'ftol': 1e-5} options = {'disp': True} # For coverage purposes SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0], minimizer_kwargs=minimizer_kwargs, options=options) def test_7_3_minkwargs(self): """Test minimizer_kwargs arguments for solvers without constraints""" for solver in ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'dogleg', 'trust-ncg', 'trust-exact', 'trust-krylov']: def jac(x): return np.array([2 * x[0], 2 * x[1]]).T def hess(x): return np.array([[2, 0], [0, 2]]) minimizer_kwargs = {'method': solver, 'jac': jac, 'hess': hess} logging.info(f"Solver = {solver}") logging.info("=" * 100) run_test(test1_1, n=100, test_atol=1e-3, minimizer_kwargs=minimizer_kwargs, sampling_method='sobol') def test_8_homology_group_diff(self): options = {'minhgrd': 1, 'minimize_every_iter': True} run_test(test1_1, n=None, iters=None, options=options, sampling_method='simplicial') def test_9_cons_g(self): """Test single function constraint passing""" SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0]) @pytest.mark.xfail(IS_PYPY and sys.platform == 'win32', reason="Failing and fix in PyPy not planned (see gh-18632)") def test_10_finite_time(self): """Test single function constraint passing""" options = {'maxtime': 1e-15} def f(x): time.sleep(1e-14) return 0.0 res = shgo(f, test1_1.bounds, iters=5, options=options) # Assert that only 1 rather than 5 requested iterations ran: assert res.nit == 1 def test_11_f_min_0(self): """Test to cover the case where f_lowest == 0""" options = {'f_min': 0.0, 'disp': True} res = shgo(test1_2.f, test1_2.bounds, n=10, iters=None, options=options, sampling_method='sobol') np.testing.assert_equal(0, res.x[0]) np.testing.assert_equal(0, res.x[1]) # @nottest @pytest.mark.skip(reason="no way of currently testing this") def test_12_sobol_inf_cons(self): """Test to cover the case where f_lowest == 0""" # TODO: This test doesn't cover anything new, it is unknown what the # original test was intended for as it was never complete. Delete or # replace in the future. options = {'maxtime': 1e-15, 'f_min': 0.0} res = shgo(test1_2.f, test1_2.bounds, n=1, iters=None, options=options, sampling_method='sobol') np.testing.assert_equal(0.0, res.fun) def test_13_high_sobol(self): """Test init of high-dimensional sobol sequences""" def f(x): return 0 bounds = [(None, None), ] * 41 SHGOc = SHGO(f, bounds, sampling_method='sobol') # SHGOc.sobol_points(2, 50) SHGOc.sampling_function(2, 50) def test_14_local_iter(self): """Test limited local iterations for a pseudo-global mode""" options = {'local_iter': 4} run_test(test5_1, n=60, options=options) def test_15_min_every_iter(self): """Test minimize every iter options and cover function cache""" options = {'minimize_every_iter': True} run_test(test1_1, n=1, iters=7, options=options, sampling_method='sobol') def test_16_disp_bounds_minimizer(self, capsys): """Test disp=True with minimizers that do not support bounds """ options = {'disp': True} minimizer_kwargs = {'method': 'nelder-mead'} run_test(test1_2, sampling_method='simplicial', options=options, minimizer_kwargs=minimizer_kwargs) def test_17_custom_sampling(self): """Test the functionality to add custom sampling methods to shgo""" def sample(n, d): return np.random.uniform(size=(n, d)) run_test(test1_1, n=30, sampling_method=sample) def test_18_bounds_class(self): # test that new and old bounds yield same result def f(x): return np.square(x).sum() lb = [-6., 1., -5.] ub = [-1., 3., 5.] bounds_old = list(zip(lb, ub)) bounds_new = Bounds(lb, ub) res_old_bounds = shgo(f, bounds_old) res_new_bounds = shgo(f, bounds_new) assert res_new_bounds.nfev == res_old_bounds.nfev assert res_new_bounds.message == res_old_bounds.message assert res_new_bounds.success == res_old_bounds.success x_opt = np.array([-1., 1., 0.]) np.testing.assert_allclose(res_new_bounds.x, x_opt) np.testing.assert_allclose(res_new_bounds.x, res_old_bounds.x) @pytest.mark.fail_slow(10) def test_19_parallelization(self): """Test the functionality to add custom sampling methods to shgo""" with Pool(2) as p: run_test(test1_1, n=30, workers=p.map) # Constrained run_test(test1_1, n=30, workers=map) # Constrained with Pool(2) as p: run_test(test_s, n=30, workers=p.map) # Unconstrained run_test(test_s, n=30, workers=map) # Unconstrained def test_20_constrained_args(self): """Test that constraints can be passed to arguments""" def eggholder(x): return ( -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0] / 2.0 + (x[1] + 47.0)))) - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0)))) ) def f(x): # (cattle-feed) return 24.55 * x[0] + 26.75 * x[1] + 39 * x[2] + 40.50 * x[3] bounds = [(0, 1.0), ] * 4 def g1_modified(x, i): return i * 2.3 * x[0] + i * 5.6 * x[1] + 11.1 * x[2] + 1.3 * x[ 3] - 5 # >=0 def g2(x): return ( 12*x[0] + 11.9*x[1] + 41.8*x[2] + 52.1*x[3] - 21 - 1.645*np.sqrt( 0.28*x[0]**2 + 0.19*x[1]**2 + 20.5*x[2]**2 + 0.62*x[3]**2 ) ) # >=0 def h1(x): return x[0] + x[1] + x[2] + x[3] - 1 # == 0 cons = ({'type': 'ineq', 'fun': g1_modified, "args": (0,)}, {'type': 'ineq', 'fun': g2}, {'type': 'eq', 'fun': h1}) shgo(f, bounds, n=300, iters=1, constraints=cons) # using constrain with arguments AND sampling method sobol shgo(f, bounds, n=300, iters=1, constraints=cons, sampling_method='sobol') def test_21_1_jac_true(self): """Test that shgo can handle objective functions that return the gradient alongside the objective value. Fixes gh-13547""" # previous def func(x): return np.sum(np.power(x, 2)), 2 * x min_kwds = {"method": "SLSQP", "jac": True} opt_kwds = {"jac": True} shgo( func, bounds=[[-1, 1], [1, 2]], n=100, iters=5, sampling_method="sobol", minimizer_kwargs=min_kwds, options=opt_kwds ) assert min_kwds['jac'] is True assert "jac" in opt_kwds # new def func(x): return np.sum(x ** 2), 2 * x bounds = [[-1, 1], [1, 2], [-1, 1], [1, 2], [0, 3]] res = shgo(func, bounds=bounds, sampling_method="sobol", minimizer_kwargs={'method': 'SLSQP', 'jac': True}) ref = minimize(func, x0=[1, 1, 1, 1, 1], bounds=bounds, jac=True) assert res.success assert_allclose(res.fun, ref.fun) assert_allclose(res.x, ref.x, atol=1e-15) # Testing the passing of jac via options dict res = shgo(func, bounds=bounds, sampling_method="sobol", minimizer_kwargs={'method': 'SLSQP'}, options={'jac': True}) assert res.success assert_allclose(res.fun, ref.fun) assert_allclose(res.x, ref.x, atol=1e-15) @pytest.mark.parametrize('derivative', ['jac', 'hess', 'hessp']) def test_21_2_derivative_options(self, derivative): """shgo used to raise an error when passing `options` with 'jac' # see gh-12963. check that this is resolved """ def objective(x): return 3 * x[0] * x[0] + 2 * x[0] + 5 def gradient(x): return 6 * x[0] + 2 def hess(x): return 6 def hessp(x, p): return 6 * p derivative_funcs = {'jac': gradient, 'hess': hess, 'hessp': hessp} options = {derivative: derivative_funcs[derivative]} minimizer_kwargs = {'method': 'trust-constr'} bounds = [(-100, 100)] res = shgo(objective, bounds, minimizer_kwargs=minimizer_kwargs, options=options) ref = minimize(objective, x0=[0], bounds=bounds, **minimizer_kwargs, **options) assert res.success np.testing.assert_allclose(res.fun, ref.fun) np.testing.assert_allclose(res.x, ref.x) def test_21_3_hess_options_rosen(self): """Ensure the Hessian gets passed correctly to the local minimizer routine. Previous report gh-14533. """ bounds = [(0, 1.6), (0, 1.6), (0, 1.4), (0, 1.4), (0, 1.4)] options = {'jac': rosen_der, 'hess': rosen_hess} minimizer_kwargs = {'method': 'Newton-CG'} res = shgo(rosen, bounds, minimizer_kwargs=minimizer_kwargs, options=options) ref = minimize(rosen, np.zeros(5), method='Newton-CG', **options) assert res.success assert_allclose(res.fun, ref.fun) assert_allclose(res.x, ref.x, atol=1e-15) def test_21_arg_tuple_sobol(self): """shgo used to raise an error when passing `args` with Sobol sampling # see gh-12114. check that this is resolved""" def fun(x, k): return x[0] ** k constraints = ({'type': 'ineq', 'fun': lambda x: x[0] - 1}) bounds = [(0, 10)] res = shgo(fun, bounds, args=(1,), constraints=constraints, sampling_method='sobol') ref = minimize(fun, np.zeros(1), bounds=bounds, args=(1,), constraints=constraints) assert res.success assert_allclose(res.fun, ref.fun) assert_allclose(res.x, ref.x) # Failure test functions
TestShgoArguments
python
gevent__gevent
src/gevent/libev/corecffi.py
{ "start": 1501, "end": 6813 }
class ____(AbstractCallbacks): # pylint:disable=arguments-differ,arguments-renamed def python_check_callback(self, *args): # There's a pylint bug (pylint 2.9.3, astroid 2.6.2) that causes pylint to crash # with an AttributeError on certain types of arguments-differ errors # But code in _ffi/loop depends on being able to find the watcher_ptr # argument is the local frame. BUT it gets invoked before the function body runs. # Hence the override of _find_watcher_ptr_in_traceback. # pylint:disable=unused-variable _loop, watcher_ptr, _events = args AbstractCallbacks.python_check_callback(self, watcher_ptr) def _find_watcher_ptr_in_traceback(self, tb): if tb is not None: l = tb.tb_frame.f_locals if 'watcher_ptr' in l: return l['watcher_ptr'] if 'args' in l and len(l['args']) == 3: return l['args'][1] return AbstractCallbacks._find_watcher_ptr_in_traceback(self, tb) def python_prepare_callback(self, _loop_ptr, watcher_ptr, _events): AbstractCallbacks.python_prepare_callback(self, watcher_ptr) def _find_loop_from_c_watcher(self, watcher_ptr): loop_handle = ffi.cast('struct ev_watcher*', watcher_ptr).data return self.from_handle(loop_handle) _callbacks = assign_standard_callbacks(ffi, libev, _Callbacks) UNDEF = libev.EV_UNDEF NONE = libev.EV_NONE READ = libev.EV_READ WRITE = libev.EV_WRITE TIMER = libev.EV_TIMER PERIODIC = libev.EV_PERIODIC SIGNAL = libev.EV_SIGNAL CHILD = libev.EV_CHILD STAT = libev.EV_STAT IDLE = libev.EV_IDLE PREPARE = libev.EV_PREPARE CHECK = libev.EV_CHECK EMBED = libev.EV_EMBED FORK = libev.EV_FORK CLEANUP = libev.EV_CLEANUP ASYNC = libev.EV_ASYNC CUSTOM = libev.EV_CUSTOM ERROR = libev.EV_ERROR READWRITE = libev.EV_READ | libev.EV_WRITE MINPRI = libev.EV_MINPRI MAXPRI = libev.EV_MAXPRI BACKEND_PORT = libev.EVBACKEND_PORT BACKEND_KQUEUE = libev.EVBACKEND_KQUEUE BACKEND_EPOLL = libev.EVBACKEND_EPOLL BACKEND_POLL = libev.EVBACKEND_POLL BACKEND_SELECT = libev.EVBACKEND_SELECT FORKCHECK = libev.EVFLAG_FORKCHECK NOINOTIFY = libev.EVFLAG_NOINOTIFY SIGNALFD = libev.EVFLAG_SIGNALFD NOSIGMASK = libev.EVFLAG_NOSIGMASK from gevent._ffi.loop import EVENTS GEVENT_CORE_EVENTS = EVENTS def get_version(): return 'libev-%d.%02d' % (libev.ev_version_major(), libev.ev_version_minor()) def get_header_version(): return 'libev-%d.%02d' % (libev.EV_VERSION_MAJOR, libev.EV_VERSION_MINOR) # This list backends in the order they are actually tried by libev, # as defined in loop_init. The names must be lower case. _flags = [ # IOCP --- not supported/used. (libev.EVBACKEND_PORT, 'port'), (libev.EVBACKEND_KQUEUE, 'kqueue'), (libev.EVBACKEND_IOURING, 'linux_iouring'), (libev.EVBACKEND_LINUXAIO, "linux_aio"), (libev.EVBACKEND_EPOLL, 'epoll'), (libev.EVBACKEND_POLL, 'poll'), (libev.EVBACKEND_SELECT, 'select'), (libev.EVFLAG_NOENV, 'noenv'), (libev.EVFLAG_FORKCHECK, 'forkcheck'), (libev.EVFLAG_SIGNALFD, 'signalfd'), (libev.EVFLAG_NOSIGMASK, 'nosigmask') ] _flags_str2int = dict((string, flag) for (flag, string) in _flags) def _flags_to_list(flags): result = [] for code, value in _flags: if flags & code: result.append(value) flags &= ~code if not flags: break if flags: result.append(flags) return result if sys.version_info[0] >= 3: basestring = (bytes, str) integer_types = (int,) else: import __builtin__ # pylint:disable=import-error basestring = (__builtin__.basestring,) integer_types = (int, __builtin__.long) def _flags_to_int(flags): # Note, that order does not matter, libev has its own predefined order if not flags: return 0 if isinstance(flags, integer_types): return flags result = 0 try: if isinstance(flags, basestring): flags = flags.split(',') for value in flags: value = value.strip().lower() if value: result |= _flags_str2int[value] except KeyError as ex: raise ValueError('Invalid backend or flag: %s\nPossible values: %s' % (ex, ', '.join(sorted(_flags_str2int.keys())))) return result def _str_hex(flag): if isinstance(flag, integer_types): return hex(flag) return str(flag) def _check_flags(flags): as_list = [] flags &= libev.EVBACKEND_MASK if not flags: return if not flags & libev.EVBACKEND_ALL: raise ValueError('Invalid value for backend: 0x%x' % flags) if not flags & libev.ev_supported_backends(): as_list = [_str_hex(x) for x in _flags_to_list(flags)] raise ValueError('Unsupported backend: %s' % '|'.join(as_list)) def supported_backends(): return _flags_to_list(libev.ev_supported_backends()) def recommended_backends(): return _flags_to_list(libev.ev_recommended_backends()) def embeddable_backends(): return _flags_to_list(libev.ev_embeddable_backends()) def time(): return libev.ev_time() from gevent._ffi.loop import AbstractLoop from gevent.libev import watcher as _watchers _events_to_str = _watchers._events_to_str # exported @implementer(ILoop)
_Callbacks
python
huggingface__transformers
tests/models/cohere2/test_modeling_cohere2.py
{ "start": 2918, "end": 13736 }
class ____(unittest.TestCase): input_text = ["Hello I am doing", "Hi today"] def tearDown(self): cleanup(torch_device, gc_collect=True) def test_model_bf16(self): model_id = "CohereForAI/c4ai-command-r7b-12-2024" EXPECTED_TEXTS = [ "<BOS_TOKEN>Hello I am doing a project for a school assignment and I need to create a website for a fictional company. I have", "<PAD><PAD><BOS_TOKEN>Hi today I'm going to show you how to make a simple and easy to make a chocolate cake.\n", ] model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16, attn_implementation="eager").to( torch_device ) tokenizer = AutoTokenizer.from_pretrained(model_id) inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device) output = model.generate(**inputs, max_new_tokens=20, do_sample=False) output_text = tokenizer.batch_decode(output, skip_special_tokens=False) self.assertEqual(output_text, EXPECTED_TEXTS) def test_model_fp16(self): model_id = "CohereForAI/c4ai-command-r7b-12-2024" # fmt: off EXPECTED_TEXTS = Expectations( { ("xpu", 3): ["<BOS_TOKEN>Hello I am doing a project for my school and I need to create a website for a fictional company. I have the", "<PAD><PAD><BOS_TOKEN>Hi today I'm going to show you how to make a simple and easy to make a chocolate cake.\n"], (None, None): ["<BOS_TOKEN>Hello I am doing a project for a school assignment and I need to create a website for a fictional company. I have", "<PAD><PAD><BOS_TOKEN>Hi today I'm going to show you how to make a simple and easy to make a chocolate cake.\n"], ("cuda", 8): ['<BOS_TOKEN>Hello I am doing a project for my school and I need to create a website for a fictional company. I have the', "<PAD><PAD><BOS_TOKEN>Hi today I'm going to show you how to make a simple and easy to make a chocolate cake.\n"], } ) EXPECTED_TEXT = EXPECTED_TEXTS.get_expectation() # fmt: on model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.float16, attn_implementation="eager").to( torch_device ) tokenizer = AutoTokenizer.from_pretrained(model_id) inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device) output = model.generate(**inputs, max_new_tokens=20, do_sample=False) output_text = tokenizer.batch_decode(output, skip_special_tokens=False) self.assertEqual(output_text, EXPECTED_TEXT) def test_model_pipeline_bf16(self): # See https://github.com/huggingface/transformers/pull/31747 -- pipeline was broken for Cohere2 before this PR model_id = "CohereForAI/c4ai-command-r7b-12-2024" # EXPECTED_TEXTS should match the same non-pipeline test, minus the special tokens EXPECTED_TEXTS = [ "Hello I am doing a project for a school assignment and I need to create a website for a fictional company. I have", "Hi today I'm going to show you how to make a simple and easy to make a chocolate cake.\n", ] model = AutoModelForCausalLM.from_pretrained( model_id, dtype=torch.bfloat16, attn_implementation="flex_attention" ).to(torch_device) tokenizer = AutoTokenizer.from_pretrained(model_id) pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) output = pipe(self.input_text, max_new_tokens=20, do_sample=False, padding=True) self.assertEqual(output[0][0]["generated_text"], EXPECTED_TEXTS[0]) self.assertEqual(output[1][0]["generated_text"], EXPECTED_TEXTS[1]) @require_flash_attn @mark.flash_attn_test def test_model_flash_attn(self): # See https://github.com/huggingface/transformers/issues/31953 --- flash attn was generating garbage for Gemma2, especially in long context model_id = "CohereForAI/c4ai-command-r7b-12-2024" EXPECTED_TEXTS = [ '<BOS_TOKEN>Hello I am doing a project for my school and I need to create a website for a fictional company. I have the logo and the name of the company. I need a website that is simple and easy to navigate. I need a home page, about us, services, contact us, and a gallery. I need the website to be responsive and I need it to be able to be hosted on a server. I need the website to be done in a week. I need the website to be done in HTML,', "<PAD><PAD><BOS_TOKEN>Hi today I'm going to show you how to make a simple and easy to make a chocolate cake.\n\nThis recipe is very simple and easy to make.\n\nYou will need:\n\n* 2 cups of flour\n* 1 cup of sugar\n* 1/2 cup of cocoa powder\n* 1 teaspoon of baking powder\n* 1 teaspoon of baking soda\n* 1/2 teaspoon of salt\n* 2 eggs\n* 1 cup of milk\n", ] # fmt: skip model = AutoModelForCausalLM.from_pretrained( model_id, attn_implementation="flash_attention_2", dtype="float16" ).to(torch_device) tokenizer = AutoTokenizer.from_pretrained(model_id) inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device) output = model.generate(**inputs, max_new_tokens=100, do_sample=False) output_text = tokenizer.batch_decode(output, skip_special_tokens=False) self.assertEqual(output_text, EXPECTED_TEXTS) @pytest.mark.torch_export_test def test_export_static_cache(self): if version.parse(torch.__version__) < version.parse("2.5.0"): self.skipTest(reason="This test requires torch >= 2.5 to run.") from transformers.integrations.executorch import ( TorchExportableModuleWithStaticCache, convert_and_export_with_cache, ) model_id = "CohereForAI/c4ai-command-r7b-12-2024" # fmt: off EXPECTED_TEXT_COMPLETIONS = Expectations( { ("xpu", 3): ["Hello I am doing a project for a friend and I am stuck on a few things. I have a 2004 Ford F-"], (None, None): ["Hello I am doing a project on the effects of social media on mental health. I have a few questions. 1. What is the relationship"], ("cuda", 8): ['Hello I am doing a project for a friend and I am stuck on a few things. I have a 2004 Ford F-'], } ) EXPECTED_TEXT_COMPLETION = EXPECTED_TEXT_COMPLETIONS.get_expectation() # fmt: on tokenizer = AutoTokenizer.from_pretrained(model_id, pad_token="<PAD>", padding_side="right") # Load model device = "cpu" # TODO (joao / export experts): should be on `torch_device`, but causes GPU OOM dtype = torch.bfloat16 cache_implementation = "static" attn_implementation = "sdpa" batch_size = 1 model = AutoModelForCausalLM.from_pretrained( "CohereForAI/c4ai-command-r7b-12-2024", device_map=device, dtype=dtype, attn_implementation=attn_implementation, generation_config=GenerationConfig( use_cache=True, cache_implementation=cache_implementation, max_length=30, cache_config={ "batch_size": batch_size, "max_cache_len": 30, }, ), ) prompts = ["Hello I am doing"] prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) prompt_token_ids = prompt_tokens["input_ids"] max_new_tokens = 30 - prompt_token_ids.shape[-1] # Static Cache + export exported_program = convert_and_export_with_cache(model) ep_generated_ids = TorchExportableModuleWithStaticCache.generate( exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=max_new_tokens ) ep_generated_text = tokenizer.batch_decode(ep_generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, ep_generated_text) @parameterized.expand([("flash_attention_2",), ("sdpa",), ("flex_attention",), ("eager",)]) @require_read_token def test_generation_beyond_sliding_window(self, attn_implementation: str): """Test that we can correctly generate beyond the sliding window. This is non trivial as we need to correctly slice the attention mask in all cases (because we use a hybrid cache). Outputs for every attention functions should be coherent and identical. """ # Impossible to test it with this model (even with < 100 tokens), probably due to the compilation of a large model. if attn_implementation == "flex_attention": self.skipTest( reason="`flex_attention` gives `torch._inductor.exc.InductorError: RuntimeError: No valid triton configs. OutOfMemoryError: out of resource: triton_tem_fused_0 Required: 147456 Hardware limit:101376 Reducing block sizes or `num_stages` may help.`" ) if attn_implementation == "flash_attention_2" and not is_flash_attn_2_available(): self.skipTest("FlashAttention2 is required for this test.") if torch_device == "xpu" and attn_implementation == "flash_attention_2": self.skipTest(reason="Intel XPU doesn't support flash_attention_2 as of now.") model_id = "CohereForAI/c4ai-command-r7b-12-2024" EXPECTED_COMPLETIONS = [ " the mountains, the lakes, the rivers, the forests, the trees, the birds, the animals", ", green, yellow, orange, purple, pink, brown, black, white, grey, silver", ] input_text = [ "This is a nice place. " * 200 + "I really enjoy the scenery,", # This is larger than 1024 tokens "A list of colors: red, blue", # This will almost all be padding tokens ] tokenizer = AutoTokenizer.from_pretrained(model_id, padding="left") inputs = tokenizer(input_text, padding=True, return_tensors="pt").to(torch_device) # We use `sliding_window=1024` instead of the origin value `4096` in the config to avoid GPU OOM model = AutoModelForCausalLM.from_pretrained( model_id, attn_implementation=attn_implementation, dtype=torch.float16, sliding_window=1024 ).to(torch_device) # Make sure prefill is larger than sliding window input_size = inputs.input_ids.shape[-1] self.assertTrue(input_size > model.config.sliding_window) out = model.generate(**inputs, max_new_tokens=20)[:, input_size:] output_text = tokenizer.batch_decode(out) self.assertEqual(output_text, EXPECTED_COMPLETIONS)
Cohere2IntegrationTest
python
walkccc__LeetCode
solutions/395. Longest Substring with At Least K Repeating Characters/395.py
{ "start": 0, "end": 1060 }
class ____: def longestSubstring(self, s: str, k: int) -> int: def longestSubstringWithNUniqueLetters(n: int) -> int: res = 0 uniqueLetters = 0 # the number of unique letters lettersHavingKFreq = 0 # the number of letters having frequency >= k count = collections.Counter() l = 0 for r, c in enumerate(s): count[c] += 1 if count[c] == 1: uniqueLetters += 1 if count[c] == k: lettersHavingKFreq += 1 while uniqueLetters > n: if count[s[l]] == k: lettersHavingKFreq -= 1 count[s[l]] -= 1 if count[s[l]] == 0: uniqueLetters -= 1 l += 1 # Since both the number of unique letters and the number of letters # having frequency >= k are equal to n, this is a valid window. if lettersHavingKFreq == n: # Implicit: uniqueLetters == n res = max(res, r - l + 1) return res return max(longestSubstringWithNUniqueLetters(n) for n in range(1, 27))
Solution
python
huggingface__transformers
src/transformers/models/superglue/image_processing_superglue_fast.py
{ "start": 3475, "end": 12546 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BILINEAR size = {"height": 480, "width": 640} default_to_square = False do_resize = True do_rescale = True rescale_factor = 1 / 255 do_normalize = None valid_kwargs = SuperGlueImageProcessorKwargs def __init__(self, **kwargs: Unpack[SuperGlueImageProcessorKwargs]): super().__init__(**kwargs) @auto_docstring def preprocess(self, images: ImageInput, **kwargs: Unpack[SuperGlueImageProcessorKwargs]) -> BatchFeature: return super().preprocess(images, **kwargs) def _prepare_images_structure( self, images: ImageInput, **kwargs, ) -> ImageInput: # we need to handle image pairs validation and flattening return flatten_pair_images(images) def _preprocess( self, images: list["torch.Tensor"], size: Union[dict[str, int], SizeDict], rescale_factor: float, do_rescale: bool, do_resize: bool, interpolation: Optional["F.InterpolationMode"], do_grayscale: bool, disable_grouping: bool, return_tensors: Union[str, TensorType], **kwargs, ) -> BatchFeature: grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) processed_images_grouped = {} for shape, stacked_images in grouped_images.items(): if do_resize: stacked_images = self.resize(stacked_images, size=size, interpolation=interpolation) processed_images_grouped[shape] = stacked_images resized_images = reorder_images(processed_images_grouped, grouped_images_index) grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping) processed_images_grouped = {} for shape, stacked_images in grouped_images.items(): if do_rescale: stacked_images = self.rescale(stacked_images, rescale_factor) if do_grayscale: stacked_images = convert_to_grayscale(stacked_images) processed_images_grouped[shape] = stacked_images processed_images = reorder_images(processed_images_grouped, grouped_images_index) # Convert back to pairs format image_pairs = [processed_images[i : i + 2] for i in range(0, len(processed_images), 2)] # Stack each pair into a single tensor to match slow processor format stacked_pairs = [torch.stack(pair, dim=0) for pair in image_pairs] # Return in same format as slow processor image_pairs = torch.stack(stacked_pairs, dim=0) if return_tensors else stacked_pairs return BatchFeature(data={"pixel_values": image_pairs}) def post_process_keypoint_matching( self, outputs: "SuperGlueKeypointMatchingOutput", target_sizes: Union[TensorType, list[tuple]], threshold: float = 0.0, ) -> list[dict[str, torch.Tensor]]: """ Converts the raw output of [`SuperGlueKeypointMatchingOutput`] into lists of keypoints, scores and descriptors with coordinates absolute to the original image sizes. Args: outputs ([`SuperGlueKeypointMatchingOutput`]): Raw outputs of the model. target_sizes (`torch.Tensor` or `list[tuple[tuple[int, int]]]`, *optional*): Tensor of shape `(batch_size, 2, 2)` or list of tuples of tuples (`tuple[int, int]`) containing the target size `(height, width)` of each image in the batch. This must be the original image size (before any processing). threshold (`float`, *optional*, defaults to 0.0): Threshold to filter out the matches with low scores. Returns: `list[Dict]`: A list of dictionaries, each dictionary containing the keypoints in the first and second image of the pair, the matching scores and the matching indices. """ if outputs.mask.shape[0] != len(target_sizes): raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the mask") if not all(len(target_size) == 2 for target_size in target_sizes): raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch") if isinstance(target_sizes, list): image_pair_sizes = torch.tensor(target_sizes, device=outputs.mask.device) else: if target_sizes.shape[1] != 2 or target_sizes.shape[2] != 2: raise ValueError( "Each element of target_sizes must contain the size (h, w) of each image of the batch" ) image_pair_sizes = target_sizes keypoints = outputs.keypoints.clone() keypoints = keypoints * image_pair_sizes.flip(-1).reshape(-1, 2, 1, 2) keypoints = keypoints.to(torch.int32) results = [] for mask_pair, keypoints_pair, matches, scores in zip( outputs.mask, keypoints, outputs.matches[:, 0], outputs.matching_scores[:, 0] ): mask0 = mask_pair[0] > 0 mask1 = mask_pair[1] > 0 keypoints0 = keypoints_pair[0][mask0] keypoints1 = keypoints_pair[1][mask1] matches0 = matches[mask0] scores0 = scores[mask0] # Filter out matches with low scores, invalid matches, and out-of-bounds indices valid_matches = (scores0 > threshold) & (matches0 > -1) & (matches0 < keypoints1.shape[0]) matched_keypoints0 = keypoints0[valid_matches] matched_keypoints1 = keypoints1[matches0[valid_matches]] matching_scores = scores0[valid_matches] results.append( { "keypoints0": matched_keypoints0, "keypoints1": matched_keypoints1, "matching_scores": matching_scores, } ) return results def visualize_keypoint_matching( self, images, keypoint_matching_output: list[dict[str, torch.Tensor]], ) -> list["Image.Image"]: """ Plots the image pairs side by side with the detected keypoints as well as the matching between them. Args: images: Image pairs to plot. Same as `EfficientLoFTRImageProcessor.preprocess`. Expects either a list of 2 images or a list of list of 2 images list with pixel values ranging from 0 to 255. keypoint_matching_output (List[Dict[str, torch.Tensor]]]): A post processed keypoint matching output Returns: `List[PIL.Image.Image]`: A list of PIL images, each containing the image pairs side by side with the detected keypoints as well as the matching between them. """ from ...image_utils import to_numpy_array from .image_processing_superglue import validate_and_format_image_pairs images = validate_and_format_image_pairs(images) images = [to_numpy_array(image) for image in images] image_pairs = [images[i : i + 2] for i in range(0, len(images), 2)] results = [] for image_pair, pair_output in zip(image_pairs, keypoint_matching_output): height0, width0 = image_pair[0].shape[:2] height1, width1 = image_pair[1].shape[:2] plot_image = torch.zeros((max(height0, height1), width0 + width1, 3), dtype=torch.uint8) plot_image[:height0, :width0] = torch.from_numpy(image_pair[0]) plot_image[:height1, width0:] = torch.from_numpy(image_pair[1]) plot_image_pil = Image.fromarray(plot_image.numpy()) draw = ImageDraw.Draw(plot_image_pil) keypoints0_x, keypoints0_y = pair_output["keypoints0"].unbind(1) keypoints1_x, keypoints1_y = pair_output["keypoints1"].unbind(1) for keypoint0_x, keypoint0_y, keypoint1_x, keypoint1_y, matching_score in zip( keypoints0_x, keypoints0_y, keypoints1_x, keypoints1_y, pair_output["matching_scores"] ): color = self._get_color(matching_score) draw.line( (keypoint0_x, keypoint0_y, keypoint1_x + width0, keypoint1_y), fill=color, width=3, ) draw.ellipse((keypoint0_x - 2, keypoint0_y - 2, keypoint0_x + 2, keypoint0_y + 2), fill="black") draw.ellipse( (keypoint1_x + width0 - 2, keypoint1_y - 2, keypoint1_x + width0 + 2, keypoint1_y + 2), fill="black", ) results.append(plot_image_pil) return results def _get_color(self, score): """Maps a score to a color.""" r = int(255 * (1 - score)) g = int(255 * score) b = 0 return r, g, b __all__ = ["SuperGlueImageProcessorFast"]
SuperGlueImageProcessorFast
python
pytorch__pytorch
torch/export/_draft_export.py
{ "start": 7673, "end": 7807 }
class ____: result_id: int argument_ids: list[int] record: dict[str, object] visited: bool = False
ExpressionCreatedNode
python
apache__airflow
airflow-core/tests/unit/cli/commands/test_info_command.py
{ "start": 1412, "end": 2570 }
class ____: def setup_method(self) -> None: self.instance = info_command.PiiAnonymizer() def test_should_remove_pii_from_path(self): home_path = os.path.expanduser("~/airflow/config") assert self.instance.process_path(home_path) == "${HOME}/airflow/config" @pytest.mark.parametrize( ("before", "after"), [ ( "postgresql+psycopg2://postgres:airflow@postgres/airflow", "postgresql+psycopg2://p...s:PASSWORD@postgres/airflow", ), ( "postgresql+psycopg2://postgres@postgres/airflow", "postgresql+psycopg2://p...s@postgres/airflow", ), ( "postgresql+psycopg2://:airflow@postgres/airflow", "postgresql+psycopg2://:PASSWORD@postgres/airflow", ), ( "postgresql+psycopg2://postgres/airflow", "postgresql+psycopg2://postgres/airflow", ), ], ) def test_should_remove_pii_from_url(self, before, after): assert after == self.instance.process_url(before)
TestPiiAnonymizer
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/layer_order_independence.py
{ "start": 186, "end": 308 }
class ____(Container): def compose(self) -> ComposeResult: yield Label("This should float over the top")
Overlay
python
pandas-dev__pandas
pandas/tests/arithmetic/test_timedelta64.py
{ "start": 81512, "end": 82784 }
class ____: # Arithmetic tests for timedelta64[ns] vectors fully parametrized over # DataFrame/Series/TimedeltaIndex/TimedeltaArray. Ideally all arithmetic # tests will eventually end up here. def test_td64arr_pow_invalid(self, scalar_td, box_with_array): td1 = Series([timedelta(minutes=5, seconds=3)] * 3) td1.iloc[2] = np.nan td1 = tm.box_expected(td1, box_with_array) # check that we are getting a TypeError # with 'operate' (from core/ops.py) for the ops that are not # defined pattern = "operate|unsupported|cannot|not supported" with pytest.raises(TypeError, match=pattern): scalar_td**td1 with pytest.raises(TypeError, match=pattern): td1**scalar_td def test_add_timestamp_to_timedelta(): # GH: 35897 timestamp = Timestamp("2021-01-01") result = timestamp + timedelta_range("0s", "1s", periods=31) expected = DatetimeIndex( [ timestamp + ( pd.to_timedelta("0.033333333s") * i + pd.to_timedelta("0.000000001s") * divmod(i, 3)[0] ) for i in range(31) ] ) tm.assert_index_equal(result, expected)
TestTimedelta64ArrayLikeArithmetic
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dlp.py
{ "start": 19192, "end": 20003 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook") def test_list_dlp_jobs(self, mock_hook): mock_hook.return_value.list_dlp_jobs.return_value = mock.MagicMock() operator = CloudDLPListDLPJobsOperator(project_id=PROJECT_ID, task_id="id") operator.execute(context=mock.MagicMock()) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=None, ) mock_hook.return_value.list_dlp_jobs.assert_called_once_with( project_id=PROJECT_ID, results_filter=None, page_size=None, job_type=None, order_by=None, retry=DEFAULT, timeout=None, metadata=(), )
TestCloudDLPListDlpJobsOperator
python
spack__spack
lib/spack/spack/directory_layout.py
{ "start": 14762, "end": 14881 }
class ____(DirectoryLayoutError): """Raised when an extension file has a bad spec in it."""
InvalidExtensionSpecError
python
astropy__astropy
astropy/coordinates/transformations/affine.py
{ "start": 10944, "end": 12590 }
class ____(BaseAffineTransform): """ A coordinate transformation defined as a 3 x 3 cartesian transformation matrix. This is distinct from DynamicMatrixTransform in that this kind of matrix is independent of frame attributes. That is, it depends *only* on the class of the frame. Parameters ---------- matrix : array-like or callable A 3 x 3 matrix for transforming 3-vectors. In most cases will be unitary (although this is not strictly required). If a callable, will be called *with no arguments* to get the matrix. fromsys : class The coordinate frame class to start from. tosys : class The coordinate frame class to transform into. priority : float or int The priority if this transform when finding the shortest coordinate transform path - large numbers are lower priorities. register_graph : `~astropy.coordinates.TransformGraph` or None A graph to register this transformation with on creation, or `None` to leave it unregistered. Raises ------ ValueError If the matrix is not 3 x 3 """ def __init__(self, matrix, fromsys, tosys, priority=1, register_graph=None): if callable(matrix): matrix = matrix() self.matrix = np.array(matrix) if self.matrix.shape != (3, 3): raise ValueError("Provided matrix is not 3 x 3") super().__init__( fromsys, tosys, priority=priority, register_graph=register_graph ) def _affine_params(self, fromcoord, toframe): return self.matrix, None
StaticMatrixTransform
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 248878, "end": 251153 }
class ____(Request): """ Remove a task from its queue. Fails if task status is not queued. :param task: Task ID :type task: str :param status_reason: Reason for status change :type status_reason: str :param status_message: Extra information regarding status change :type status_message: str """ _service = "tasks" _action = "dequeue" _version = "2.23" _schema = { "definitions": {}, "properties": { "status_message": { "description": "Extra information regarding status change", "type": "string", }, "status_reason": { "description": "Reason for status change", "type": "string", }, "task": {"description": "Task ID", "type": "string"}, }, "required": ["task"], "type": "object", } def __init__(self, task, status_reason=None, status_message=None, **kwargs): super(DequeueRequest, self).__init__(**kwargs) self.task = task self.status_reason = status_reason self.status_message = status_message @schema_property("task") def task(self): return self._property_task @task.setter def task(self, value): if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("status_reason") def status_reason(self): return self._property_status_reason @status_reason.setter def status_reason(self, value): if value is None: self._property_status_reason = None return self.assert_isinstance(value, "status_reason", six.string_types) self._property_status_reason = value @schema_property("status_message") def status_message(self): return self._property_status_message @status_message.setter def status_message(self, value): if value is None: self._property_status_message = None return self.assert_isinstance(value, "status_message", six.string_types) self._property_status_message = value
DequeueRequest
python
OmkarPathak__pygorithm
tests/test_sorting.py
{ "start": 4327, "end": 4555 }
class ____(unittest.TestCase, TestSortingAlgorithm): inplace = True alph_support = True @staticmethod def sort(arr): # use a smaller run for testing return tim_sort.tim_sort(arr, run=4)
TestTimSort
python
scikit-learn__scikit-learn
sklearn/decomposition/_incremental_pca.py
{ "start": 532, "end": 16334 }
class ____(_BasePCA): """Incremental principal components analysis (IPCA). Linear dimensionality reduction using Singular Value Decomposition of the data, keeping only the most significant singular vectors to project the data to a lower dimensional space. The input data is centered but not scaled for each feature before applying the SVD. Depending on the size of the input data, this algorithm can be much more memory efficient than a PCA, and allows sparse input. This algorithm has constant memory complexity, on the order of ``batch_size * n_features``, enabling use of np.memmap files without loading the entire file into memory. For sparse matrices, the input is converted to dense in batches (in order to be able to subtract the mean) which avoids storing the entire dense matrix at any one time. The computational overhead of each SVD is ``O(batch_size * n_features ** 2)``, but only 2 * batch_size samples remain in memory at a time. There will be ``n_samples / batch_size`` SVD computations to get the principal components, versus 1 large SVD of complexity ``O(n_samples * n_features ** 2)`` for PCA. For a usage example, see :ref:`sphx_glr_auto_examples_decomposition_plot_incremental_pca.py`. Read more in the :ref:`User Guide <IncrementalPCA>`. .. versionadded:: 0.16 Parameters ---------- n_components : int, default=None Number of components to keep. If ``n_components`` is ``None``, then ``n_components`` is set to ``min(n_samples, n_features)``. whiten : bool, default=False When True (False by default) the ``components_`` vectors are divided by ``n_samples`` times ``components_`` to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometimes improve the predictive accuracy of the downstream estimators by making data respect some hard-wired assumptions. copy : bool, default=True If False, X will be overwritten. ``copy=False`` can be used to save memory but is unsafe for general use. batch_size : int, default=None The number of samples to use for each batch. Only used when calling ``fit``. If ``batch_size`` is ``None``, then ``batch_size`` is inferred from the data and set to ``5 * n_features``, to provide a balance between approximation accuracy and memory consumption. Attributes ---------- components_ : ndarray of shape (n_components, n_features) Principal axes in feature space, representing the directions of maximum variance in the data. Equivalently, the right singular vectors of the centered input data, parallel to its eigenvectors. The components are sorted by decreasing ``explained_variance_``. explained_variance_ : ndarray of shape (n_components,) Variance explained by each of the selected components. explained_variance_ratio_ : ndarray of shape (n_components,) Percentage of variance explained by each of the selected components. If all components are stored, the sum of explained variances is equal to 1.0. singular_values_ : ndarray of shape (n_components,) The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the ``n_components`` variables in the lower-dimensional space. mean_ : ndarray of shape (n_features,) Per-feature empirical mean, aggregate over calls to ``partial_fit``. var_ : ndarray of shape (n_features,) Per-feature empirical variance, aggregate over calls to ``partial_fit``. noise_variance_ : float The estimated noise covariance following the Probabilistic PCA model from Tipping and Bishop 1999. See "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf. n_components_ : int The estimated number of components. Relevant when ``n_components=None``. n_samples_seen_ : int The number of samples processed by the estimator. Will be reset on new calls to fit, but increments across ``partial_fit`` calls. batch_size_ : int Inferred batch size from ``batch_size``. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 See Also -------- PCA : Principal component analysis (PCA). KernelPCA : Kernel Principal component analysis (KPCA). SparsePCA : Sparse Principal Components Analysis (SparsePCA). TruncatedSVD : Dimensionality reduction using truncated SVD. Notes ----- Implements the incremental PCA model from Ross et al. (2008) [1]_. This model is an extension of the Sequential Karhunen-Loeve Transform from Levy and Lindenbaum (2000) [2]_. We have specifically abstained from an optimization used by authors of both papers, a QR decomposition used in specific situations to reduce the algorithmic complexity of the SVD. The source for this technique is *Matrix Computations* (Golub and Van Loan 1997 [3]_). This technique has been omitted because it is advantageous only when decomposing a matrix with ``n_samples`` (rows) >= 5/3 * ``n_features`` (columns), and hurts the readability of the implemented algorithm. This would be a good opportunity for future optimization, if it is deemed necessary. References ---------- .. [1] D. Ross, J. Lim, R. Lin, M. Yang. Incremental Learning for Robust Visual Tracking, International Journal of Computer Vision, Volume 77, Issue 1-3, pp. 125-141, May 2008. https://www.cs.toronto.edu/~dross/ivt/RossLimLinYang_ijcv.pdf .. [2] :doi:`A. Levy and M. Lindenbaum, Sequential Karhunen-Loeve Basis Extraction and its Application to Images, IEEE Transactions on Image Processing, Volume 9, Number 8, pp. 1371-1374, August 2000. <10.1109/83.855432>` .. [3] G. Golub and C. Van Loan. Matrix Computations, Third Edition, Chapter 5, Section 5.4.4, pp. 252-253, 1997. Examples -------- >>> from sklearn.datasets import load_digits >>> from sklearn.decomposition import IncrementalPCA >>> from scipy import sparse >>> X, _ = load_digits(return_X_y=True) >>> transformer = IncrementalPCA(n_components=7, batch_size=200) >>> # either partially fit on smaller batches of data >>> transformer.partial_fit(X[:100, :]) IncrementalPCA(batch_size=200, n_components=7) >>> # or let the fit function itself divide the data into batches >>> X_sparse = sparse.csr_matrix(X) >>> X_transformed = transformer.fit_transform(X_sparse) >>> X_transformed.shape (1797, 7) """ __metadata_request__partial_fit = {"check_input": metadata_routing.UNUSED} _parameter_constraints: dict = { "n_components": [Interval(Integral, 1, None, closed="left"), None], "whiten": ["boolean"], "copy": ["boolean"], "batch_size": [Interval(Integral, 1, None, closed="left"), None], } def __init__(self, n_components=None, *, whiten=False, copy=True, batch_size=None): self.n_components = n_components self.whiten = whiten self.copy = copy self.batch_size = batch_size @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y=None): """Fit the model with X, using minibatches of size batch_size. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Returns the instance itself. """ self.components_ = None self.n_samples_seen_ = 0 self.mean_ = 0.0 self.var_ = 0.0 self.singular_values_ = None self.explained_variance_ = None self.explained_variance_ratio_ = None self.noise_variance_ = None X = validate_data( self, X, accept_sparse=["csr", "csc", "lil"], copy=self.copy, dtype=[np.float64, np.float32], force_writeable=True, ) n_samples, n_features = X.shape if self.batch_size is None: self.batch_size_ = 5 * n_features else: self.batch_size_ = self.batch_size for batch in gen_batches( n_samples, self.batch_size_, min_batch_size=self.n_components or 0 ): X_batch = X[batch] if sparse.issparse(X_batch): X_batch = X_batch.toarray() self.partial_fit(X_batch, check_input=False) return self @_fit_context(prefer_skip_nested_validation=True) def partial_fit(self, X, y=None, check_input=True): """Incremental fit with X. All of X is processed as a single batch. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present for API consistency by convention. check_input : bool, default=True Run check_array on X. Returns ------- self : object Returns the instance itself. """ first_pass = not hasattr(self, "components_") if check_input: if sparse.issparse(X): raise TypeError( "IncrementalPCA.partial_fit does not support " "sparse input. Either convert data to dense " "or use IncrementalPCA.fit to do so in batches." ) X = validate_data( self, X, copy=self.copy, dtype=[np.float64, np.float32], force_writeable=True, reset=first_pass, ) n_samples, n_features = X.shape if first_pass: self.components_ = None if self.n_components is None: if self.components_ is None: self.n_components_ = min(n_samples, n_features) else: self.n_components_ = self.components_.shape[0] elif not self.n_components <= n_features: raise ValueError( "n_components=%r invalid for n_features=%d, need " "more rows than columns for IncrementalPCA " "processing" % (self.n_components, n_features) ) elif self.n_components > n_samples and first_pass: raise ValueError( f"n_components={self.n_components} must be less or equal to " f"the batch number of samples {n_samples} for the first " "partial_fit call." ) else: self.n_components_ = self.n_components if (self.components_ is not None) and ( self.components_.shape[0] != self.n_components_ ): raise ValueError( "Number of input features has changed from %i " "to %i between calls to partial_fit! Try " "setting n_components to a fixed value." % (self.components_.shape[0], self.n_components_) ) # This is the first partial_fit if not hasattr(self, "n_samples_seen_"): self.n_samples_seen_ = 0 self.mean_ = 0.0 self.var_ = 0.0 # Update stats - they are 0 if this is the first step col_mean, col_var, n_total_samples = _incremental_mean_and_var( X, last_mean=self.mean_, last_variance=self.var_, last_sample_count=np.repeat(self.n_samples_seen_, X.shape[1]), ) n_total_samples = n_total_samples[0] # Whitening if self.n_samples_seen_ == 0: # If it is the first step, simply whiten X X -= col_mean else: col_batch_mean = np.mean(X, axis=0) X -= col_batch_mean # Build matrix of combined previous basis and new data mean_correction = np.sqrt( (self.n_samples_seen_ / n_total_samples) * n_samples ) * (self.mean_ - col_batch_mean) X = np.vstack( ( self.singular_values_.reshape((-1, 1)) * self.components_, X, mean_correction, ) ) U, S, Vt = linalg.svd(X, full_matrices=False, check_finite=False) U, Vt = svd_flip(U, Vt, u_based_decision=False) explained_variance = S**2 / (n_total_samples - 1) explained_variance_ratio = S**2 / np.sum(col_var * n_total_samples) self.n_samples_seen_ = n_total_samples self.components_ = Vt[: self.n_components_] self.singular_values_ = S[: self.n_components_] self.mean_ = col_mean self.var_ = col_var self.explained_variance_ = explained_variance[: self.n_components_] self.explained_variance_ratio_ = explained_variance_ratio[: self.n_components_] # we already checked `self.n_components <= n_samples` above if self.n_components_ not in (n_samples, n_features): self.noise_variance_ = explained_variance[self.n_components_ :].mean() else: self.noise_variance_ = 0.0 return self def transform(self, X): """Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set, using minibatches of size batch_size if X is sparse. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) New data, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- X_new : ndarray of shape (n_samples, n_components) Projection of X in the first principal components. Examples -------- >>> import numpy as np >>> from sklearn.decomposition import IncrementalPCA >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], ... [1, 1], [2, 1], [3, 2]]) >>> ipca = IncrementalPCA(n_components=2, batch_size=3) >>> ipca.fit(X) IncrementalPCA(batch_size=3, n_components=2) >>> ipca.transform(X) # doctest: +SKIP """ if sparse.issparse(X): n_samples = X.shape[0] output = [] for batch in gen_batches( n_samples, self.batch_size_, min_batch_size=self.n_components or 0 ): output.append(super().transform(X[batch].toarray())) return np.vstack(output) else: return super().transform(X) def __sklearn_tags__(self): tags = super().__sklearn_tags__() # Beware that fit accepts sparse data but partial_fit doesn't tags.input_tags.sparse = True return tags
IncrementalPCA
python
airbytehq__airbyte
airbyte-integrations/connectors/source-bing-ads/components.py
{ "start": 15730, "end": 17604 }
class ____(RecordTransformation): report_aggregation: str def transform_report_hourly_datetime_format_to_rfc_3339(self, original_value: str) -> str: """ Bing Ads API reports with hourly aggregation provides date fields in custom format: "2023-11-04|11" Return date in RFC3339 format: "2023-11-04T11:00:00+00:00" """ return datetime.strptime(original_value, "%Y-%m-%d|%H").replace(tzinfo=timezone.utc).isoformat(timespec="seconds") def transform( self, record: MutableMapping[str, Any], config: Optional[Mapping[str, Any]] = None, stream_state: Optional[StreamState] = None, stream_slice: Optional[StreamSlice] = None, ) -> None: if self.report_aggregation == "Hourly": if record.get("TimePeriod"): record.update({"TimePeriod": self.transform_report_hourly_datetime_format_to_rfc_3339(record["TimePeriod"])}) if self.report_aggregation == "DayOfWeek": cursor_field = record["TimePeriod"] record.update( { "StartOfTimePeriod": stream_slice["start_time"], "EndOfTimePeriod": stream_slice["end_time"], "DayOfWeek": cursor_field, "TimePeriod": stream_slice["end_time"], } ) record["TimePeriod"] = record["EndOfTimePeriod"] if self.report_aggregation == "HourOfDay": cursor_field = record["TimePeriod"] record.update( { "StartOfTimePeriod": stream_slice["start_time"], "EndOfTimePeriod": stream_slice["end_time"], "HourOfDay": cursor_field, "TimePeriod": stream_slice["end_time"], } ) @dataclass
CustomReportTransformation
python
apache__airflow
providers/apache/hive/tests/unit/apache/hive/__init__.py
{ "start": 2184, "end": 2677 }
class ____(HiveCliHook): def __init__(self, *args, **kwargs): super().__init__() self.conn = MockConnectionCursor() self.conn.schema = "default" self.conn.host = "localhost" self.conn.port = 10000 self.conn.login = None self.conn.password = None self.conn.execute = MagicMock() self.get_conn = MagicMock(return_value=self.conn) self.get_connection = MagicMock(return_value=MockDBConnection({}))
MockHiveCliHook
python
wandb__wandb
wandb/vendor/gql-0.2.0/wandb_gql/transport/local_schema.py
{ "start": 46, "end": 316 }
class ____(object): def __init__(self, schema): self.schema = schema def execute(self, document, *args, **kwargs): return execute( self.schema, document, *args, **kwargs )
LocalSchemaTransport
python
apache__airflow
task-sdk/tests/task_sdk/execution_time/test_context.py
{ "start": 21072, "end": 23965 }
class ____: @pytest.mark.parametrize( ("access_key", "internal_key"), ( (Asset("test"), AssetUniqueKey.from_asset(Asset("test"))), ( Asset(name="test", uri="test://asset"), AssetUniqueKey.from_asset(Asset(name="test", uri="test://asset")), ), (AssetAlias("test_alias"), AssetAliasUniqueKey.from_asset_alias(AssetAlias("test_alias"))), ), ) def test__get_item__dict_key_not_exists(self, access_key, internal_key): outlet_event_accessors = OutletEventAccessors() assert len(outlet_event_accessors) == 0 outlet_event_accessor = outlet_event_accessors[access_key] assert len(outlet_event_accessors) == 1 assert outlet_event_accessor.key == internal_key assert outlet_event_accessor.extra == {} @pytest.mark.parametrize( ("access_key", "asset"), ( (Asset.ref(name="test"), Asset(name="test")), (Asset.ref(name="test1"), Asset(name="test1", uri="test://asset-uri")), (Asset.ref(uri="test://asset-uri"), Asset(uri="test://asset-uri")), ), ) def test__get_item__asset_ref(self, access_key, asset, mock_supervisor_comms): """Test accessing OutletEventAccessors with AssetRef resolves to correct Asset.""" internal_key = AssetUniqueKey.from_asset(asset) outlet_event_accessors = OutletEventAccessors() assert len(outlet_event_accessors) == 0 # Asset from the API Server via the supervisor mock_supervisor_comms.send.return_value = AssetResult( name=asset.name, uri=asset.uri, group=asset.group, ) outlet_event_accessor = outlet_event_accessors[access_key] assert len(outlet_event_accessors) == 1 assert outlet_event_accessor.key == internal_key assert outlet_event_accessor.extra == {} @pytest.mark.parametrize( ("name", "uri", "expected_key"), ( ("test_uri", "test://test/", TEST_ASSET), ("test_uri", None, TEST_ASSET_REFS[0]), (None, "test://test/", TEST_ASSET_REFS[1]), ), ) @mock.patch("airflow.sdk.execution_time.context.OutletEventAccessors.__getitem__") def test_for_asset(self, mocked__getitem__, name, uri, expected_key): outlet_event_accessors = OutletEventAccessors() outlet_event_accessors.for_asset(name=name, uri=uri) assert mocked__getitem__.call_args[0][0] == expected_key @mock.patch("airflow.sdk.execution_time.context.OutletEventAccessors.__getitem__") def test_for_asset_alias(self, mocked__getitem__): outlet_event_accessors = OutletEventAccessors() outlet_event_accessors.for_asset_alias(name="name") assert mocked__getitem__.call_args[0][0] == TEST_ASSET_ALIAS
TestOutletEventAccessors
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_J.py
{ "start": 1247, "end": 3557 }
class ____(Benchmark): r""" Judge objective function. This class defines the Judge [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Judge}}(x) = \sum_{i=1}^{20} \left [ \left (x_1 + A_i x_2 + B x_2^2 \right ) - C_i \right ]^2 Where, in this exercise: .. math:: \begin{cases} C = [4.284, 4.149, 3.877, 0.533, 2.211, 2.389, 2.145, 3.231, 1.998, 1.379, 2.106, 1.428, 1.011, 2.179, 2.858, 1.388, 1.651, 1.593, 1.046, 2.152] \\ A = [0.286, 0.973, 0.384, 0.276, 0.973, 0.543, 0.957, 0.948, 0.543, 0.797, 0.936, 0.889, 0.006, 0.828, 0.399, 0.617, 0.939, 0.784, 0.072, 0.889] \\ B = [0.645, 0.585, 0.310, 0.058, 0.455, 0.779, 0.259, 0.202, 0.028, 0.099, 0.142, 0.296, 0.175, 0.180, 0.842, 0.039, 0.103, 0.620, 0.158, 0.704] \end{cases} with :math:`x_i \in [-10, 10]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x_i) = 16.0817307` for :math:`\mathbf{x} = [0.86479, 1.2357]`. .. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015 """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-10.0] * self.N, [10.0] * self.N)) self.global_optimum = [[0.86479, 1.2357]] self.custom_bounds = [(-2.0, 2.0), (-2.0, 2.0)] self.fglob = 16.0817307 self.c = asarray([4.284, 4.149, 3.877, 0.533, 2.211, 2.389, 2.145, 3.231, 1.998, 1.379, 2.106, 1.428, 1.011, 2.179, 2.858, 1.388, 1.651, 1.593, 1.046, 2.152]) self.a = asarray([0.286, 0.973, 0.384, 0.276, 0.973, 0.543, 0.957, 0.948, 0.543, 0.797, 0.936, 0.889, 0.006, 0.828, 0.399, 0.617, 0.939, 0.784, 0.072, 0.889]) self.b = asarray([0.645, 0.585, 0.310, 0.058, 0.455, 0.779, 0.259, 0.202, 0.028, 0.099, 0.142, 0.296, 0.175, 0.180, 0.842, 0.039, 0.103, 0.620, 0.158, 0.704]) def fun(self, x, *args): self.nfev += 1 return sum(((x[0] + x[1] * self.a + (x[1] ** 2.0) * self.b) - self.c) ** 2.0)
Judge
python
streamlit__streamlit
lib/tests/streamlit/elements/map_test.py
{ "start": 1188, "end": 13557 }
class ____(DeltaGeneratorTestCase): """Test ability to marshall deck_gl_json_chart protos via st.map.""" def test_no_args(self): """Test that it can be called with no args.""" st.map() c = self.get_delta_from_queue().new_element.deck_gl_json_chart assert json.loads(c.json) == _DEFAULT_MAP def test_basic(self): """Test that it can be called with lat/lon.""" st.map(mock_df) c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert c.get("initialViewState") is not None assert c.get("layers") is not None assert c.get("mapStyle") is None assert len(c.get("layers")) == 1 assert c.get("initialViewState").get("latitude") == 2.5 assert c.get("initialViewState").get("longitude") == 25 assert c.get("initialViewState").get("zoom") == 3 assert c.get("initialViewState").get("pitch") == 0 assert c.get("layers")[0].get("@@type") == "ScatterplotLayer" def test_alternative_names_columns(self): """Test that it can be called with alternative names of lat/lon columns.""" name_combination = itertools.product( {"lat", "latitude", "LAT", "LATITUDE"}, {"lon", "longitude", "LON", "LONGITUDE"}, ) for lat_column_name, lon_column_name in name_combination: df = mock_df.rename( columns={"lat": lat_column_name, "lon": lon_column_name} ) st.map(df) c = json.loads( self.get_delta_from_queue().new_element.deck_gl_json_chart.json ) assert len(c.get("layers")[0].get("data")) == 4 def test_map_uses_convert_anything_to_df(self): """Test that st.map uses convert_anything_to_df to convert input data.""" with mock.patch( "streamlit.dataframe_util.convert_anything_to_pandas_df" ) as convert_anything_to_df: convert_anything_to_df.return_value = mock_df st.map(mock_df) convert_anything_to_df.assert_called_once() def test_main_kwargs(self): """Test that latitude, longitude, color and size propagate correctly.""" df = pd.DataFrame( { "lat": [38.8762997, 38.8742997, 38.9025842], "lon": [-77.0037, -77.0057, -77.0556545], "color": [[255, 0, 0, 128], [0, 255, 0, 128], [0, 0, 255, 128]], "size": [100, 50, 30], "xlat": [-38.8762997, -38.8742997, -38.9025842], "xlon": [77.0037, 77.0057, 77.0556545], } ) st.map(df, latitude="xlat", longitude="xlon", color="color", size="size") c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert c.get("layers")[0].get("getPosition") == "@@=[xlon, xlat]" assert c.get("layers")[0].get("getFillColor") == "@@=color" assert c.get("layers")[0].get("getRadius") == "@@=size" # Also test that the radius property is set up correctly. assert c.get("layers")[0].get("radiusMinPixels") == 3 @parameterized.expand( [ ("string_index", ["a", "b", "c"]), ("indexed_from_1", [1, 2, 3]), ] ) def test_alternative_dataframe_index(self, _, index): """Test that the map method does not error with non-standard dataframe indexes""" df = pd.DataFrame( { "lat": [38.8762997, 38.8742997, 38.9025842], "lon": [-77.0037, -77.0057, -77.0556545], "color": [[255, 0, 0, 128], [0, 255, 0, 128], [0, 0, 255, 128]], "size": [100, 50, 30], }, index=index, ) st.map(df, size="size", color="color") c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert c.get("layers")[0].get("getFillColor") == "@@=color" assert c.get("layers")[0].get("getRadius") == "@@=size" def test_named_dataframe_index(self): """Test that the map method does not error with a dataframe with a named index""" df = pd.DataFrame( { "lat": [38.8762997, 38.8742997, 38.9025842], "lon": [-77.0037, -77.0057, -77.0556545], "color": [[255, 0, 0, 128], [0, 255, 0, 128], [0, 0, 255, 128]], "size": [100, 50, 30], } ) df.index.name = "my index" st.map(df, color="color", size="size") c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert c.get("layers")[0].get("getFillColor") == "@@=color" assert c.get("layers")[0].get("getRadius") == "@@=size" # Also test that the radius property is set up correctly. assert c.get("layers")[0].get("radiusMinPixels") == 3 def test_common_color_formats(self): """Test that users can pass colors in different formats.""" df = pd.DataFrame( { "lat": [38.8762997, 38.8742997, 38.9025842], "lon": [-77.0037, -77.0057, -77.0556545], "tuple3_int_color": [[255, 0, 0], [0, 255, 0], [0, 0, 255]], "tuple4_int_int_color": [ [255, 0, 0, 51], [0, 255, 0, 51], [0, 0, 255, 51], ], "tuple4_int_float_color": [ [255, 0, 0, 0.2], [0, 255, 0, 0.2], [0, 0, 255, 0.2], ], "tuple3_float_color": [ [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ], "tuple4_float_float_color": [ [1.0, 0.0, 0.0, 0.2], [0.0, 1.0, 0.0, 0.2], [0.0, 0.0, 1.0, 0.2], ], "hex3_color": ["#f00", "#0f0", "#00f"], "hex4_color": ["#f008", "#0f08", "#00f8"], "hex6_color": ["#ff0000", "#00ff00", "#0000ff"], "hex8_color": ["#ff000088", "#00ff0088", "#0000ff88"], "named_color": ["red", "green", "blue"], } ) color_columns = sorted(set(df.columns)) color_columns.remove("lat") color_columns.remove("lon") expected_values = { "tuple3": [[255, 0, 0], [0, 255, 0], [0, 0, 255]], "tuple4": [[255, 0, 0, 51], [0, 255, 0, 51], [0, 0, 255, 51]], "hex3": [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]], "hex6": [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]], # 88 in hex = 136 "hex4": [[255, 0, 0, 136], [0, 255, 0, 136], [0, 0, 255, 136]], "hex8": [[255, 0, 0, 136], [0, 255, 0, 136], [0, 0, 255, 136]], "named": None, } def get_expected_color_values(col_name): for prefix, expected_color_values in expected_values.items(): if col_name.startswith(prefix): return expected_color_values return None for color_column in color_columns: expected_color_values = get_expected_color_values(color_column) if expected_color_values is None: with pytest.raises(StreamlitAPIException): st.map(df, color=color_column) else: st.map(df, color=color_column) c = json.loads( self.get_delta_from_queue().new_element.deck_gl_json_chart.json ) rows = c.get("layers")[0].get("data") for i, row in enumerate(rows): assert row[color_column] == expected_color_values[i] def test_unused_columns_get_dropped(self): """Test that unused columns don't get transmitted.""" df = pd.DataFrame( { "lat": [38.8762997, 38.8742997, 38.9025842], "lon": [-77.0037, -77.0057, -77.0556545], "int_color": [[255, 0, 0, 128], [0, 255, 0, 128], [0, 0, 255, 128]], "size": [100, 50, 30], "xlat": [-38.8762997, -38.8742997, -38.9025842], "xlon": [77.0037, 77.0057, 77.0556545], } ) st.map(df) c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert len(c.get("layers")[0].get("data")[0]) == 2 st.map(df, latitude="xlat", longitude="xlon") c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert len(c.get("layers")[0].get("data")[0]) == 2 st.map(df, latitude="xlat", longitude="xlon", color="int_color") c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert len(c.get("layers")[0].get("data")[0]) == 3 st.map(df, latitude="xlat", longitude="xlon", size="size") c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert len(c.get("layers")[0].get("data")[0]) == 3 st.map(df, latitude="xlat", longitude="xlon", color="int_color", size="size") c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert len(c.get("layers")[0].get("data")[0]) == 4 def test_original_df_is_untouched(self): """Test that when we modify the outgoing DF we don't mutate the input DF.""" df = pd.DataFrame( { "lat": [38.8762997, 38.8742997, 38.9025842], "lon": [-77.0037, -77.0057, -77.0556545], "foo": [0, 1, 2], } ) st.map(df) c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert len(c.get("layers")[0].get("data")[0]) == 2 assert len(df.columns) == 3 def test_default_map_copy(self): """Test that _DEFAULT_MAP is not modified as other work occurs.""" assert _DEFAULT_MAP["initialViewState"]["latitude"] == 0 st.map(mock_df) assert _DEFAULT_MAP["initialViewState"]["latitude"] == 0 def test_default_zoom_level(self): """Test that _DEFAULT_ZOOM_LEVEL is set if zoom is not provided and distance is too small.""" df = pd.DataFrame({"lat": [1], "lon": [1]}) st.map(df) c = json.loads(self.get_delta_from_queue().new_element.deck_gl_json_chart.json) assert c.get("initialViewState").get("zoom") == _DEFAULT_ZOOM_LEVEL def test_map_leak(self): """Test that maps don't stay in memory when you create a new blank one. This is testing for an actual (fixed) bug. """ st.map(mock_df) st.map() c = self.get_delta_from_queue().new_element.deck_gl_json_chart assert json.loads(c.json) == _DEFAULT_MAP @parameterized.expand( [ [ "lat", "Map data must contain a latitude column named: 'LAT', 'LATITUDE', 'lat', 'latitude'. " "Existing columns: 'lon'", ], [ "lon", "Map data must contain a longitude column named: 'LON', 'LONGITUDE', 'lon', 'longitude'. " "Existing columns: 'lat'", ], ] ) def test_missing_column(self, column_name, exception_message): """Test st.map with wrong lat column label.""" df = mock_df.drop(columns=[column_name]) with pytest.raises(StreamlitAPIException, match=re.escape(exception_message)): st.map(df) def test_nan_exception(self): """Test st.map with NaN in data.""" df = pd.DataFrame({"lat": [1, 2, np.nan], "lon": [11, 12, 13]}) with pytest.raises( StreamlitAPIException, match="not allowed to contain null values" ): st.map(df) def test_mapbox_token_is_set_in_proto(self): """Test that mapbox token is set in proto if configured.""" with patch_config_options({"mapbox.token": "test_mapbox_token"}): st.map(mock_df) c = self.get_delta_from_queue().new_element.deck_gl_json_chart assert c.mapbox_token == "test_mapbox_token"
StMapTest
python
google__pytype
pytype/tests/test_typed_dict.py
{ "start": 26116, "end": 29824 }
class ____(test_base.BaseTest): """Tests for typing.(Not)Required.""" def test_required(self): self.CheckWithErrors(""" from typing_extensions import Required, TypedDict class X(TypedDict, total=False): k1: int k2: Required[str] x1: X = {'k2': 'ok'} x2: X = {'k1': 1, 'k2': 'ok'} x3: X = {'k1': 0} # annotation-type-mismatch """) def test_not_required(self): self.CheckWithErrors(""" from typing_extensions import NotRequired, TypedDict class X(TypedDict): k1: str k2: NotRequired[int] x1: X = {'k1': 'ok'} x2: X = {'k1': 'ok', 'k2': 1} x3: X = {'k2': 0} # annotation-type-mismatch """) def test_malformed(self): self.CheckWithErrors(""" from typing_extensions import NotRequired, Required, TypedDict class X(TypedDict): k1: Required[...] # invalid-annotation k2: NotRequired[...] # invalid-annotation k3: Required[int, str] # invalid-annotation k4: NotRequired[str, int] # invalid-annotation k5: Required[NotRequired[int]] # invalid-annotation k6: NotRequired[Required[str]] # invalid-annotation """) @test_utils.skipBeforePy((3, 11), "typing.(Not)Required is new in 3.11.") def test_typing_import(self): self.CheckWithErrors(""" from typing import NotRequired, Required, TypedDict class X(TypedDict, total=False): k1: NotRequired[int] k2: Required[str] x1: X = {'k1': 1, 'k2': 'ok'} x2: X = {'k2': 'ok'} x3: X = {'k1': 0} # annotation-type-mismatch """) def test_annotated(self): self.Check(""" from typing_extensions import Annotated, NotRequired, TypedDict class X(TypedDict): k1: Annotated[NotRequired[str], 'HELLO'] k2: NotRequired[Annotated[int, 'WORLD']] x1: X = {'k1': 'ok', 'k2': 1} x2: X = {'k1': 'ok'} x3: X = {'k2': 1} x4: X = {} """) def test_unparameterized(self): self.CheckWithErrors(""" from typing_extensions import Required, TypedDict class X(TypedDict, total=False): k1: Required # treated as Required[Any] class Anything: pass x1: X = {'k1': Anything()} x2: X = {} # annotation-type-mismatch """) def test_functional_syntax(self): self.CheckWithErrors(""" from typing_extensions import NotRequired, Required, TypedDict X = TypedDict('X', {'k1': Required[str], 'k2': NotRequired[int]}) x1: X = {'k1': 'ok'} x2: X = {'k1': 'ok', 'k2': 1} x3: X = {'k2': 0} # annotation-type-mismatch """) def test_pyi(self): with self.DepTree([( "foo.pyi", """ from typing import NotRequired, Required, TypedDict class X(TypedDict): k1: Required[str] k2: NotRequired[int] """, )]): self.CheckWithErrors(""" import foo x1: foo.X = {'k1': 'ok'} x2: foo.X = {'k1': 'ok', 'k2': 1} x3: foo.X = {'k2': 0} # annotation-type-mismatch """) def test_output(self): ty = self.Infer(""" from typing_extensions import NotRequired, Required, TypedDict class X1(TypedDict): k1: Required[str] k2: NotRequired[int] class X2(TypedDict, total=False): k1: Required[str] k2: NotRequired[int] """) self.assertTypesMatchPytd( ty, """ from typing import NotRequired, Required, TypedDict class X1(TypedDict): k1: str k2: NotRequired[int] class X2(TypedDict, total=False): k1: Required[str] k2: int """, ) if __name__ == "__main__": test_base.main()
ItemRequirednessTest
python
sympy__sympy
sympy/core/numbers.py
{ "start": 112675, "end": 117250 }
class ____(NumberSymbol, metaclass=Singleton): r"""The `e` constant. Explanation =========== The transcendental number `e = 2.718281828\ldots` is the base of the natural logarithm and of the exponential function, `e = \exp(1)`. Sometimes called Euler's number or Napier's constant. Exp1 is a singleton, and can be accessed by ``S.Exp1``, or can be imported as ``E``. Examples ======== >>> from sympy import exp, log, E >>> E is exp(1) True >>> log(E) 1 References ========== .. [1] https://en.wikipedia.org/wiki/E_%28mathematical_constant%29 """ is_real = True is_positive = True is_negative = False # XXX Forces is_negative/is_nonnegative is_irrational = True is_number = True is_algebraic = False is_transcendental = True __slots__ = () def _latex(self, printer): return r"e" @staticmethod def __abs__(): return S.Exp1 def __int__(self): return 2 def _as_mpf_val(self, prec): return mpf_e(prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (Integer(2), Integer(3)) elif issubclass(number_cls, Rational): pass def _eval_power(self, expt): if global_parameters.exp_is_pow: return self._eval_power_exp_is_pow(expt) else: from sympy.functions.elementary.exponential import exp return exp(expt) def _eval_power_exp_is_pow(self, arg): if arg.is_Number: if arg is oo: return oo elif arg == -oo: return S.Zero from sympy.functions.elementary.exponential import log if isinstance(arg, log): return arg.args[0] # don't autoexpand Pow or Mul (see the issue 3351): elif not arg.is_Add: Ioo = I*oo if arg in [Ioo, -Ioo]: return nan coeff = arg.coeff(pi*I) if coeff: if (2*coeff).is_integer: if coeff.is_even: return S.One elif coeff.is_odd: return S.NegativeOne elif (coeff + S.Half).is_even: return -I elif (coeff + S.Half).is_odd: return I elif coeff.is_Rational: ncoeff = coeff % 2 # restrict to [0, 2pi) if ncoeff > 1: # restrict to (-pi, pi] ncoeff -= 2 if ncoeff != coeff: return S.Exp1**(ncoeff*S.Pi*S.ImaginaryUnit) # Warning: code in risch.py will be very sensitive to changes # in this (see DifferentialExtension). # look for a single log factor coeff, terms = arg.as_coeff_Mul() # but it can't be multiplied by oo if coeff in (oo, -oo): return coeffs, log_term = [coeff], None for term in Mul.make_args(terms): if isinstance(term, log): if log_term is None: log_term = term.args[0] else: return elif term.is_comparable: coeffs.append(term) else: return return log_term**Mul(*coeffs) if log_term else None elif arg.is_Add: out = [] add = [] argchanged = False for a in arg.args: if a is S.One: add.append(a) continue newa = self**a if isinstance(newa, Pow) and newa.base is self: if newa.exp != a: add.append(newa.exp) argchanged = True else: add.append(a) else: out.append(newa) if out or argchanged: return Mul(*out)*Pow(self, Add(*add), evaluate=False) elif arg.is_Matrix: return arg.exp() def _eval_rewrite_as_sin(self, **kwargs): from sympy.functions.elementary.trigonometric import sin return sin(I + S.Pi/2) - I*sin(I) def _eval_rewrite_as_cos(self, **kwargs): from sympy.functions.elementary.trigonometric import cos return cos(I) + I*cos(I + S.Pi/2) E = S.Exp1
Exp1
python
astropy__astropy
astropy/modeling/fitting.py
{ "start": 65271, "end": 67414 }
class ____(_NLLSQFitter): """ `scipy.optimize.least_squares` Levenberg-Marquardt algorithm and least squares statistic. Parameters ---------- calc_uncertainties : bool If the covariance matrix should be computed and set in the fit_info. Default: False Attributes ---------- fit_info : A `scipy.optimize.OptimizeResult` class which contains all of the most recent fit information """ def __init__(self, calc_uncertainties=False): super().__init__("lm", calc_uncertainties, True) @fitter_unit_support def __call__( self, model, x, y, z=None, weights=None, maxiter=DEFAULT_MAXITER, acc=DEFAULT_ACC, epsilon=DEFAULT_EPS, estimate_jacobian=False, filter_non_finite=False, inplace=False, ): # Since there are several fitters with proper support for bounds, it # is not a good idea to keep supporting the hacky bounds algorithm # from LevMarLSQFitter here, and better to communicate with users # that they should use another fitter. Once we remove the deprecation, # we should update ``supported_constraints`` and change ``True`` to # ``False`` in the call to ``super().__init__`` above. if model.has_bounds: warnings.warn( "Using LMLSQFitter for models with bounds is now " "deprecated since astropy 7.0. We recommend you use another non-linear " "fitter such as TRFLSQFitter or DogBoxLSQFitter instead " "as these have full support for fitting models with " "bounds", AstropyDeprecationWarning, stacklevel=2, ) return super().__call__( model, x, y, z=z, weights=weights, maxiter=maxiter, acc=acc, epsilon=epsilon, estimate_jacobian=estimate_jacobian, filter_non_finite=filter_non_finite, inplace=inplace, )
LMLSQFitter
python
kamyu104__LeetCode-Solutions
Python/closest-divisors.py
{ "start": 458, "end": 843 }
class ____(object): def closestDivisors(self, num): """ :type num: int :rtype: List[int] """ result, d = [1, num+1], 1 while d*d <= num+2: if (num+2) % d == 0: result = [d, (num+2)//d] if (num+1) % d == 0: result = [d, (num+1)//d] d += 1 return result
Solution2
python
pytorch__pytorch
tools/linter/adapters/clangtidy_linter.py
{ "start": 1061, "end": 8275 }
class ____(NamedTuple): path: str | None line: int | None char: int | None code: str severity: LintSeverity name: str original: str | None replacement: str | None description: str | None # c10/core/DispatchKey.cpp:281:26: error: 'k' used after it was moved [bugprone-use-after-move] RESULTS_RE: re.Pattern[str] = re.compile( r"""(?mx) ^ (?P<file>.*?): (?P<line>\d+): (?:(?P<column>-?\d+):)? \s(?P<severity>\S+?):? \s(?P<message>.*) \s(?P<code>\[.*\]) $ """ ) def run_command( args: list[str], ) -> subprocess.CompletedProcess[bytes]: logging.debug("$ %s", " ".join(args)) start_time = time.monotonic() try: return subprocess.run( args, capture_output=True, check=False, ) finally: end_time = time.monotonic() logging.debug("took %dms", (end_time - start_time) * 1000) # Severity is either "error" or "note": # https://github.com/python/mypy/blob/8b47a032e1317fb8e3f9a818005a6b63e9bf0311/mypy/errors.py#L46-L47 severities = { "error": LintSeverity.ERROR, "warning": LintSeverity.WARNING, } def clang_search_dirs() -> list[str]: # Compilers are ordered based on fallback preference # We pick the first one that is available on the system compilers = ["clang", "gcc", "cpp", "cc"] compilers = [c for c in compilers if shutil.which(c) is not None] if len(compilers) == 0: raise RuntimeError(f"None of {compilers} were found") compiler = compilers[0] result = subprocess.run( [compiler, "-E", "-x", "c++", "-", "-v"], stdin=subprocess.DEVNULL, capture_output=True, check=True, ) stderr = result.stderr.decode().strip().split("\n") search_start = r"#include.*search starts here:" search_end = r"End of search list." append_path = False search_paths = [] for line in stderr: if re.match(search_start, line): if append_path: continue else: append_path = True elif re.match(search_end, line): break elif append_path: search_paths.append(line.strip()) return search_paths include_args = [] include_dir = [ "/usr/lib/llvm-11/include/openmp", get_python_include_dir(), os.path.join(PYTORCH_ROOT, "third_party/pybind11/include"), ] + clang_search_dirs() for dir in include_dir: include_args += ["--extra-arg", f"-I{dir}"] def check_file( filename: str, binary: str, build_dir: Path, ) -> list[LintMessage]: try: proc = run_command( [binary, f"-p={build_dir}", *include_args, filename], ) except OSError as err: return [ LintMessage( path=filename, line=None, char=None, code="CLANGTIDY", severity=LintSeverity.ERROR, name="command-failed", original=None, replacement=None, description=(f"Failed due to {err.__class__.__name__}:\n{err}"), ) ] lint_messages = [] try: # Change the current working directory to the build directory, since # clang-tidy will report files relative to the build directory. saved_cwd = os.getcwd() os.chdir(build_dir) for match in RESULTS_RE.finditer(proc.stdout.decode()): # Convert the reported path to an absolute path. abs_path = str(Path(match["file"]).resolve()) if not abs_path.startswith(PYTORCH_ROOT): continue message = LintMessage( path=abs_path, name=match["code"], description=match["message"], line=int(match["line"]), char=int(match["column"]) if match["column"] is not None and not match["column"].startswith("-") else None, code="CLANGTIDY", severity=severities.get(match["severity"], LintSeverity.ERROR), original=None, replacement=None, ) lint_messages.append(message) finally: os.chdir(saved_cwd) return lint_messages def main() -> None: parser = argparse.ArgumentParser( description="clang-tidy wrapper linter.", fromfile_prefix_chars="@", ) parser.add_argument( "--binary", required=True, help="clang-tidy binary path", ) parser.add_argument( "--build-dir", "--build_dir", required=True, help=( "Where the compile_commands.json file is located. " "Gets passed to clang-tidy -p" ), ) parser.add_argument( "--verbose", action="store_true", help="verbose logging", ) parser.add_argument( "filenames", nargs="+", help="paths to lint", ) args = parser.parse_args() logging.basicConfig( format="<%(threadName)s:%(levelname)s> %(message)s", level=logging.NOTSET if args.verbose else logging.DEBUG if len(args.filenames) < 1000 else logging.INFO, stream=sys.stderr, ) if not os.path.exists(args.binary): err_msg = LintMessage( path="<none>", line=None, char=None, code="CLANGTIDY", severity=LintSeverity.ERROR, name="command-failed", original=None, replacement=None, description=( f"Could not find clang-tidy binary at {args.binary}," " you may need to run `lintrunner init`." ), ) print(json.dumps(err_msg._asdict()), flush=True) sys.exit(0) abs_build_dir = Path(args.build_dir).resolve() # Get the absolute path to clang-tidy and use this instead of the relative # path such as .lintbin/clang-tidy. The problem here is that os.chdir is # per process, and the linter uses it to move between the current directory # and the build folder. And there is no .lintbin directory in the latter. # When it happens in a race condition, the linter command will fails with # the following no such file or directory error: '.lintbin/clang-tidy' binary_path = os.path.abspath(args.binary) with concurrent.futures.ThreadPoolExecutor( max_workers=os.cpu_count(), thread_name_prefix="Thread", ) as executor: futures = { executor.submit( check_file, filename, binary_path, abs_build_dir, ): filename for filename in args.filenames } for future in concurrent.futures.as_completed(futures): try: for lint_message in future.result(): print(json.dumps(lint_message._asdict()), flush=True) except Exception: logging.critical('Failed at "%s".', futures[future]) raise if __name__ == "__main__": main()
LintMessage
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 25552, "end": 25754 }
class ____(Structure): _fields_ = (("name", lc_str), ("nmodules", p_uint32), ("linked_modules", lc_str)) def describe(self): return {"nmodules": int(self.nmodules)}
prebound_dylib_command
python
joke2k__faker
tests/providers/test_ssn.py
{ "start": 10672, "end": 20127 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("en_US") Faker.seed(0) def test_ssn(self): for _ in range(100): ssn = self.fake.ssn(taxpayer_identification_number_type="SSN") # Ensure that generated SINs are 11 characters long # including dashes, consist of dashes and digits only, and # satisfy these requirements: # # An United States Social Security Number # (SSN) is a tax processing number issued by the Internal # Revenue Service with the format "AAA-GG-SSSS". The # number is divided into three parts: the first three # digits, known as the area number because they were # formerly assigned by geographical region; the middle two # digits, known as the group number; and the final four # digits, known as the serial number. SSNs with the # following characteristics are not allocated: # # 1) Numbers with all zeros in any digit group # (000-##-####, ###-00-####, ###-##-0000). # # 2) Numbers with 666 or 900-999 in the first digit group. # # https://en.wikipedia.org/wiki/Social_Security_number assert len(ssn) == 11 assert ssn.replace("-", "").isdigit() [area, group, serial] = ssn.split("-") assert 1 <= int(area) <= 899 and int(area) != 666 assert 1 <= int(group) <= 99 assert 1 <= int(serial) <= 9999 assert area != "666" def test_invalid_ssn(self): # Magic Numbers below generate '666-92-7944', '000-54-2963', '956-GG-9478', '436-00-1386', # and 134-76-0000 respectively. The "group" (GG) returned for '956-GG-9478 will be a random # number, and that random number is not in the "itin_group_numbers" List. The random GG occurs # even when using the same seed_instance() due to using random.choice() for GG to avoid valid # ITINs being returned as an invalid SSN: # # Ensure that generated SSNs are 11 characters long # including dashes, consist of dashes and digits only, and the tested number # violates the requirements below, ensuring an INVALID SSN is returned: # # A United States Social Security Number # (SSN) is a tax processing number issued by the Internal # Revenue Service with the format "AAA-GG-SSSS". The # number is divided into three parts: the first three # digits, known as the area number because they were # formerly assigned by geographical region; the middle two # digits, known as the group number; and the final four # digits, known as the serial number. SSNs with the # following characteristics are not allocated: # # 1) Numbers with all zeros in any digit group # (000-##-####, ###-00-####, ###-##-0000). # # 2) Numbers with 666 or 900-999 in the first digit group. # # https://en.wikipedia.org/wiki/Social_Security_number # # ITIN explained: # https://www.irs.gov/individuals/international-taxpayers/general-itin-information itin_group_numbers = [ 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 90, 91, 92, 94, 95, 96, 97, 98, 99, ] self.fake.seed_instance(2432) ssn = self.fake.ssn(taxpayer_identification_number_type="INVALID_SSN") assert len(ssn) == 11 assert ssn.replace("-", "").isdigit() assert ssn.startswith("666") self.fake.seed_instance(1514) ssn = self.fake.ssn(taxpayer_identification_number_type="INVALID_SSN") assert ssn.startswith("000") self.fake.seed_instance(2) ssn = self.fake.ssn(taxpayer_identification_number_type="INVALID_SSN") [area, group, serial] = ssn.split("-") assert 900 <= int(area) <= 999 and int(group) not in itin_group_numbers self.fake.seed_instance(0) ssn = self.fake.ssn(taxpayer_identification_number_type="INVALID_SSN") [area, group, serial] = ssn.split("-") assert int(area) < 900 and int(group) == 0 self.fake.seed_instance(1) ssn = self.fake.ssn(taxpayer_identification_number_type="INVALID_SSN") [area, group, serial] = ssn.split("-") assert int(area) < 900 and int(serial) == 0 def test_prohibited_ssn_value(self): # 666 is a prohibited value. The magic number selected as a seed # is one that would (if not specifically checked for) return an # SSN with an area of '666'. Faker.seed(19031) ssn = self.fake.ssn() [area, group, serial] = ssn.split("-") assert area != "666" def test_itin(self): for _ in range(100): itin = self.fake.ssn(taxpayer_identification_number_type="ITIN") # Ensure that generated SINs are 11 characters long # including dashes, consist of dashes and digits only, and # satisfy these requirements: # # An United States Individual Taxpayer Identification Number # (ITIN) is a tax processing number issued by the Internal # Revenue Service. It is a nine-digit number that always begins # with the number 9 and has a range of 70-88 in the fourth and # fifth digit. Effective April 12, 2011, the range was extended # to include 900-70-0000 through 999-88-9999, 900-90-0000 # through 999-92-9999 and 900-94-0000 through 999-99-9999. # https://www.irs.gov/individuals/international-taxpayers/general-itin-information assert len(itin) == 11 assert itin.replace("-", "").isdigit() [area, group, serial] = itin.split("-") assert 900 <= int(area) <= 999 assert 70 <= int(group) <= 88 or 90 <= int(group) <= 92 or 94 <= int(group) <= 99 assert 0 <= int(serial) <= 9999 def test_ein(self): ein_prefix_choices = [ "01", "02", "03", "04", "05", "06", "10", "11", "12", "13", "14", "15", "16", "20", "21", "22", "23", "24", "25", "26", "27", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "71", "72", "73", "74", "75", "76", "77", "80", "81", "82", "83", "84", "85", "86", "87", "88", "90", "91", "92", "93", "94", "95", "98", "99", ] for _ in range(100): ein = self.fake.ssn(taxpayer_identification_number_type="EIN") # An United States An Employer Identification Number (EIN) is # also known as a Federal Tax Identification Number, and is # used to identify a business entity. EINs follow a format of a # two-digit prefix followed by a hyphen and a seven-digit sequence. # https://www.irs.gov/businesses/small-businesses-self-employed/employer-id-numbers # # Ensure that generated EINs are 10 characters long # including a dash, consist of dashes and digits only, and # satisfy these requirements: # # There are only certain EIN Prefix values assigned: # https://www.irs.gov/businesses/small-businesses-self-employed/how-eins-are-assigned-and-valid-ein-prefixes assert len(ein) == 10 assert ein.replace("-", "").isdigit() [prefix, sequence] = ein.split("-") assert prefix in ein_prefix_choices assert 0 <= int(sequence) <= 9999999 def test_bad_tin_type(self): with self.assertRaises(ValueError): self.fake.ssn(taxpayer_identification_number_type="badValue") def test_wrong_tin_type_case(self): with self.assertRaises(ValueError): self.fake.ssn(taxpayer_identification_number_type="ssn")
TestEnUS
python
kamyu104__LeetCode-Solutions
Python/connecting-cities-with-minimum-cost.py
{ "start": 538, "end": 983 }
class ____(object): def minimumCost(self, N, connections): """ :type N: int :type connections: List[List[int]] :rtype: int """ connections.sort(key = lambda x: x[2]) union_find = UnionFind(N) result = 0 for u, v, val in connections: if union_find.union_set(u-1, v-1): result += val return result if union_find.count == 1 else -1
Solution
python
facebookresearch__faiss
tests/test_build_blocks.py
{ "start": 343, "end": 1822 }
class ____(unittest.TestCase): def test_pca(self): d = 64 n = 1000 np.random.seed(123) x = np.random.random(size=(n, d)).astype('float32') pca = faiss.PCAMatrix(d, 10) pca.train(x) y = pca.apply_py(x) # check that energy per component is decreasing column_norm2 = (y**2).sum(0) prev = 1e50 for o in column_norm2: self.assertGreater(prev, o) prev = o def test_pca_epsilon(self): d = 64 n = 1000 np.random.seed(123) x = np.random.random(size=(n, d)).astype('float32') # make sure data is in a sub-space x[:, ::2] = 0 # check division by 0 with default computation pca = faiss.PCAMatrix(d, 60, -0.5) pca.train(x) y = pca.apply(x) self.assertFalse(np.all(np.isfinite(y))) # check add epsilon pca = faiss.PCAMatrix(d, 60, -0.5) pca.epsilon = 1e-5 pca.train(x) y = pca.apply(x) self.assertTrue(np.all(np.isfinite(y))) # check I/O index = faiss.index_factory(d, "PCAW60,Flat") index = faiss.deserialize_index(faiss.serialize_index(index)) pca1 = faiss.downcast_VectorTransform(index.chain.at(0)) pca1.epsilon = 1e-5 index.train(x) pca = faiss.downcast_VectorTransform(index.chain.at(0)) y = pca.apply(x) self.assertTrue(np.all(np.isfinite(y)))
TestPCA
python
django__django
tests/auth_tests/test_forms.py
{ "start": 53186, "end": 56050 }
class ____(SimpleTestCase): def test_bug_19349_render_with_none_value(self): # Rendering the widget with value set to None # mustn't raise an exception. widget = ReadOnlyPasswordHashWidget() html = widget.render(name="password", value=None, attrs={}) self.assertIn(_("No password set."), html) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.PBKDF2PasswordHasher"] ) def test_render(self): widget = ReadOnlyPasswordHashWidget() value = ( "pbkdf2_sha256$100000$a6Pucb1qSFcD$WmCkn9Hqidj48NVe5x0FEM6A9YiOqQcl/83m2Z5u" "dm0=" ) self.assertHTMLEqual( widget.render("name", value, {"id": "id_password"}), '<div id="id_password">' " <p>" " <strong>algorithm</strong>: <bdi>pbkdf2_sha256</bdi>" " <strong>iterations</strong>: <bdi>100000</bdi>" " <strong>salt</strong>: <bdi>a6Pucb******</bdi>" " <strong>hash</strong>: " " <bdi>WmCkn9**************************************</bdi>" " </p>" ' <p><a role="button" class="button" href="../password/">' "Reset password</a></p>" "</div>", ) def test_render_no_password(self): widget = ReadOnlyPasswordHashWidget() self.assertHTMLEqual( widget.render("name", None, {}), "<div><p><strong>No password set.</p><p>" '<a role="button" class="button" href="../password/">Set password</a>' "</p></div>", ) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.PBKDF2PasswordHasher"] ) def test_render_invalid_password_format(self): widget = ReadOnlyPasswordHashWidget() value = "pbkdf2_sh" self.assertHTMLEqual( widget.render("name", value, {}), "<div><p>" "<strong>Invalid password format or unknown hashing algorithm.</strong>" '</p><p><a role="button" class="button" href="../password/">Reset password' "</a></p></div>", ) def test_readonly_field_has_changed(self): field = ReadOnlyPasswordHashField() self.assertIs(field.disabled, True) self.assertFalse(field.has_changed("aaa", "bbb")) def test_label(self): """ ReadOnlyPasswordHashWidget doesn't contain a for attribute in the <label> because it doesn't have any labelable elements. """ class TestForm(forms.Form): hash_field = ReadOnlyPasswordHashField() bound_field = TestForm()["hash_field"] self.assertIsNone(bound_field.field.widget.id_for_label("id")) self.assertEqual(bound_field.label_tag(), "<label>Hash field:</label>")
ReadOnlyPasswordHashTest
python
doocs__leetcode
solution/3000-3099/3010.Divide an Array Into Subarrays With Minimum Cost I/Solution.py
{ "start": 0, "end": 251 }
class ____: def minimumCost(self, nums: List[int]) -> int: a, b, c = nums[0], inf, inf for x in nums[1:]: if x < b: c, b = b, x elif x < c: c = x return a + b + c
Solution
python
openai__openai-python
src/openai/types/beta/realtime/response_text_done_event.py
{ "start": 199, "end": 724 }
class ____(BaseModel): content_index: int """The index of the content part in the item's content array.""" event_id: str """The unique ID of the server event.""" item_id: str """The ID of the item.""" output_index: int """The index of the output item in the response.""" response_id: str """The ID of the response.""" text: str """The final text content.""" type: Literal["response.text.done"] """The event type, must be `response.text.done`."""
ResponseTextDoneEvent
python
huggingface__transformers
src/transformers/cli/chat.py
{ "start": 3864, "end": 8088 }
class ____: def __init__(self, model_id: str, user_id: str): self._console = Console() self.model_id = model_id self.user_id = user_id async def stream_output(self, stream: AsyncIterator[ChatCompletionStreamOutput]) -> tuple[str, str | Any | None]: self._console.print(f"[bold blue]<{self.model_id}>:") with Live(console=self._console, refresh_per_second=4) as live: text = "" finish_reason: str | None = None async for token in await stream: outputs = token.choices[0].delta.content finish_reason = getattr(token.choices[0], "finish_reason", finish_reason) if not outputs: continue # Escapes single words encased in <>, e.g. <think> -> \<think\>, for proper rendering in Markdown. # It only escapes single words that may have `_`, optionally following a `/` (e.g. </think>) outputs = re.sub(r"<(/*)(\w*)>", r"\<\1\2\>", outputs) text += outputs # Render the accumulated text as Markdown # NOTE: this is a workaround for the rendering "unstandard markdown" # in rich. The chatbots output treat "\n" as a new line for # better compatibility with real-world text. However, rendering # in markdown would break the format. It is because standard markdown # treat a single "\n" in normal text as a space. # Our workaround is adding two spaces at the end of each line. # This is not a perfect solution, as it would # introduce trailing spaces (only) in code block, but it works well # especially for console output, because in general the console does not # care about trailing spaces. lines = [] for line in text.splitlines(): lines.append(line) if line.startswith("```"): # Code block marker - do not add trailing spaces, as it would # break the syntax highlighting lines.append("\n") else: lines.append(" \n") markdown = Markdown("".join(lines).strip(), code_theme="github-dark") # Update the Live console output live.update(markdown, refresh=True) self._console.print() return text, finish_reason def input(self) -> str: """Gets user input from the console.""" input = self._console.input(f"[bold red]<{self.user_id}>:\n") self._console.print() return input def clear(self): """Clears the console.""" self._console.clear() def print_user_message(self, text: str): """Prints a user message to the console.""" self._console.print(f"[bold red]<{self.user_id}>:[/ bold red]\n{text}") self._console.print() def print_color(self, text: str, color: str): """Prints text in a given color to the console.""" self._console.print(f"[bold {color}]{text}") self._console.print() def confirm(self, message: str, default: bool = False) -> bool: """Displays a yes/no prompt to the user, returning True for confirmation.""" default_hint = "Y/n" if default else "y/N" response = self._console.input(f"[bold yellow]{message} ({default_hint}): ") self._console.print() response = response.strip().lower() if not response: return default return response in {"y", "yes"} def print_help(self, minimal: bool = False): """Prints the help message to the console.""" self._console.print(Markdown(HELP_STRING_MINIMAL if minimal else HELP_STRING)) self._console.print() def print_status(self, config: GenerationConfig): """Prints the status of the model and generation settings to the console.""" self._console.print(f"[bold blue]Model: {self.model_id}\n") self._console.print(f"[bold blue]{config}") self._console.print()
RichInterface
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-oci-data-science/tests/test_oci_data_science_client.py
{ "start": 8340, "end": 12848 }
class ____: """Unit tests for Client class.""" def setup_method(self): self.endpoint = "https://example.com/api" self.auth_mock = {"signer": Mock()} self.retries = 2 self.backoff_factor = 0.1 self.timeout = 10 self.client = Client( endpoint=self.endpoint, auth=self.auth_mock, retries=self.retries, backoff_factor=self.backoff_factor, timeout=self.timeout, ) # Mock the internal HTTPX client self.client._client = Mock() def test_auth_not_provided(self): """Ensures that error will be thrown what auth signer not provided.""" with pytest.raises(ImportError): Client( endpoint=self.endpoint, retries=self.retries, backoff_factor=self.backoff_factor, timeout=self.timeout, ) def test_request_success(self): """Ensures that _request returns JSON response on success.""" payload = {"prompt": "Hello"} response_json = {"choices": [{"text": "Hi"}]} response_mock = Mock() response_mock.json.return_value = response_json response_mock.status_code = 200 self.client._client.post.return_value = response_mock result = self.client._request(payload) assert result == response_json def test_request_http_error(self): """Ensures that _request raises ExtendedRequestException on HTTP error.""" payload = {"prompt": "Hello"} response_mock = Mock() response_mock.status_code = 500 response_mock.raise_for_status.side_effect = httpx.HTTPStatusError( "Server error", request=None, response=response_mock ) response_mock.text = "Internal Server Error" self.client._client.post.return_value = response_mock with pytest.raises(ExtendedRequestException) as exc_info: self.client._request(payload) assert "Request failed" in str(exc_info.value) assert exc_info.value.response_text == "Internal Server Error" def test_embeddings_request(self): """Ensures that embeddings method calls _request when stream=False.""" response_json = { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": [ -0.025584878, 0.023328023, -0.03014998, ], }, { "object": "embedding", "index": 1, "embedding": [ -0.025584878, 0.023328023, -0.03014998, ], }, ], } response_mock = Mock() response_mock.json.return_value = response_json response_mock.status_code = 200 self.client._client.post.return_value = response_mock result = self.client.embeddings( input=["Hello", "World"], payload={"param1": "value1"} ) assert result == response_json def test_close(self): """Ensures that close method closes the client.""" self.client._client.close = Mock() self.client.close() self.client._client.close.assert_called_once() def test_is_closed(self): """Ensures that is_closed returns the client's is_closed status.""" self.client._client.is_closed = False assert not self.client.is_closed() self.client._client.is_closed = True assert self.client.is_closed() def test_context_manager(self): """Ensures that the client can be used as a context manager.""" self.client.close = Mock() with self.client as client_instance: assert client_instance == self.client self.client.close.assert_called_once() def test_del(self): """Ensures that __del__ method closes the client.""" client = Client( endpoint=self.endpoint, auth=self.auth_mock, retries=self.retries, backoff_factor=self.backoff_factor, timeout=self.timeout, ) client.close = Mock() client.__del__() # Manually invoke __del__ client.close.assert_called_once() @pytest.mark.asyncio
TestClient
python
django__django
tests/template_tests/syntax_tests/test_with.py
{ "start": 165, "end": 2465 }
class ____(SimpleTestCase): at_least_with_one_msg = "'with' expected at least one variable assignment" @setup({"with01": "{% with key=dict.key %}{{ key }}{% endwith %}"}) def test_with01(self): output = self.engine.render_to_string("with01", {"dict": {"key": 50}}) self.assertEqual(output, "50") @setup({"legacywith01": "{% with dict.key as key %}{{ key }}{% endwith %}"}) def test_legacywith01(self): output = self.engine.render_to_string("legacywith01", {"dict": {"key": 50}}) self.assertEqual(output, "50") @setup( { "with02": "{{ key }}{% with key=dict.key %}" "{{ key }}-{{ dict.key }}-{{ key }}" "{% endwith %}{{ key }}" } ) def test_with02(self): output = self.engine.render_to_string("with02", {"dict": {"key": 50}}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID50-50-50INVALID") else: self.assertEqual(output, "50-50-50") @setup( { "legacywith02": "{{ key }}{% with dict.key as key %}" "{{ key }}-{{ dict.key }}-{{ key }}" "{% endwith %}{{ key }}" } ) def test_legacywith02(self): output = self.engine.render_to_string("legacywith02", {"dict": {"key": 50}}) if self.engine.string_if_invalid: self.assertEqual(output, "INVALID50-50-50INVALID") else: self.assertEqual(output, "50-50-50") @setup({"with03": "{% with a=alpha b=beta %}{{ a }}{{ b }}{% endwith %}"}) def test_with03(self): output = self.engine.render_to_string("with03", {"alpha": "A", "beta": "B"}) self.assertEqual(output, "AB") @setup({"with-error01": "{% with dict.key xx key %}{{ key }}{% endwith %}"}) def test_with_error01(self): with self.assertRaisesMessage(TemplateSyntaxError, self.at_least_with_one_msg): self.engine.render_to_string("with-error01", {"dict": {"key": 50}}) @setup({"with-error02": "{% with dict.key as %}{{ key }}{% endwith %}"}) def test_with_error02(self): with self.assertRaisesMessage(TemplateSyntaxError, self.at_least_with_one_msg): self.engine.render_to_string("with-error02", {"dict": {"key": 50}})
WithTagTests
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py
{ "start": 5422, "end": 5720 }
class ____(BaseModel): x: str = Field(..., alias=x_alias) # MYPY: error: Required dynamic aliases disallowed [pydantic-alias] z: int DynamicAliasModel(y='y', z='1') # MYPY: error: Argument "z" to "DynamicAliasModel" has incompatible type "str"; expected "int" [arg-type]
DynamicAliasModel
python
getsentry__sentry
src/sentry/utils/concurrent.py
{ "start": 1200, "end": 4438 }
class ____[T](Future[T]): _condition: threading.Condition _state: str def __init__(self, *args, **kwargs): self.__timing: list[float | None] = [None, None] # [started, finished/cancelled] super().__init__(*args, **kwargs) def get_timing(self): """\ Return the timing data for this future in the form ``(started, finished)``. The ``started`` value can be either a timestamp or ``None`` (if the future has not been started.) The ``finished`` value can also be either a timestamp or ``None`` (if the future has not been either completed or cancelled.) There are some idiosyncrasies with the way the timings are recorded: - The ``started`` value will generally not be ``None`` if the ``finished`` value is also not ``None``. However, for a future that was marked as cancelled and has yet to be attempted to be executed, the ``finished`` value may be set while the ``started`` value is ``None``. - Similarly, the ``started`` value will generally be equal to or less than the ``finished`` value (ignoring non-monotonic clock phenomena.) However, for a future was is marked as cancelled prior to execution, the ``finished`` time (when the future was cancelled) may be before the ``started`` time (when the future was attempted to be executed.) """ return tuple(self.__timing) def set_running_or_notify_cancel(self, *args, **kwargs): result = super().set_running_or_notify_cancel(*args, **kwargs) # This method can only be called once (the second invocation will raise # a ``RuntimeError``) so if we've gotten this far we can be reasonably # confident that the start time hasn't been set. self.__timing[0] = time() return result def cancel(self, *args, **kwargs): with self._condition: # Futures can only be marked as cancelled if they are neither # running or finished (we have to duplicate this check that is also # performed in the superclass to ensure the timing is set before # callbacks are invoked.) As long as the future is in the correct # state, this call is guaranteed to succeed. This method can be # called multiple times, but we only record the first time the # future was cancelled. if self._state not in [RUNNING, FINISHED] and self.__timing[1] is None: self.__timing[1] = time() return super().cancel(*args, **kwargs) @contextmanager def __set_finished_time_on_success(self): prev_value = self.__timing[1] self.__timing[1] = time() try: yield except InvalidStateError: self.__timing[1] = prev_value raise def set_result(self, *args, **kwargs): with self._condition, self.__set_finished_time_on_success(): return super().set_result(*args, **kwargs) def set_exception(self, *args, **kwargs): with self._condition, self.__set_finished_time_on_success(): return super().set_exception(*args, **kwargs)
TimedFuture
python
pydantic__pydantic
pydantic-core/tests/validators/test_dataclasses.py
{ "start": 46927, "end": 47019 }
class ____(FooDataclassSlots): pass @dataclasses.dataclass(**kwargs)
FooDataclassSameSlots
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 676773, "end": 678385 }
class ____(sgqlc.types.Type): """This aggregates issues opened by a user within one repository.""" __schema__ = github_schema __field_names__ = ("contributions", "repository") contributions = sgqlc.types.Field( sgqlc.types.non_null(CreatedIssueContributionConnection), graphql_name="contributions", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ("before", sgqlc.types.Arg(String, graphql_name="before", default=None)), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ("order_by", sgqlc.types.Arg(ContributionOrder, graphql_name="orderBy", default={"direction": "DESC"})), ) ), ) """The issue contributions. Arguments: * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. * `order_by` (`ContributionOrder`): Ordering options for contributions returned from the connection. (default: `{direction: DESC}`) """ repository = sgqlc.types.Field(sgqlc.types.non_null("Repository"), graphql_name="repository") """The repository in which the issues were opened."""
IssueContributionsByRepository
python
getsentry__sentry
src/sentry/db/models/fields/jsonfield.py
{ "start": 6690, "end": 7272 }
class ____(models.JSONField): """django JSONField but with `text` database backing allows migration off of our JSONField without needing a data type change for large tables do not use me for new things! """ def db_type(self, connection: BaseDatabaseWrapper) -> str: # usually `jsonb` return "text" def get_db_prep_value(self, *args: Any, **kwargs: Any) -> Any: jsonb = super().get_db_prep_value(*args, **kwargs) # convert JSONField's ::jsonb back to plain text return jsonb.dumps(jsonb.adapted)
LegacyTextJSONField
python
python-visualization__folium
folium/features.py
{ "start": 51042, "end": 63244 }
class ____(FeatureGroup): """Apply a GeoJSON overlay to the map. Plot a GeoJSON overlay on the base map. There is no requirement to bind data (passing just a GeoJSON plots a single-color overlay), but there is a data binding option to map your columnar data to different feature objects with a color scale. If data is passed as a Pandas DataFrame, the "columns" and "key-on" keywords must be included, the first to indicate which DataFrame columns to use, the second to indicate the layer in the GeoJSON on which to key the data. The 'columns' keyword does not need to be passed for a Pandas series. Colors are generated from color brewer (https://colorbrewer2.org/) sequential palettes. By default, linear binning is used between the min and the max of the values. Custom binning can be achieved with the `bins` parameter. TopoJSONs can be passed as "geo_data", but the "topojson" keyword must also be passed with the reference to the topojson objects to convert. See the topojson.feature method in the TopoJSON API reference: https://github.com/topojson/topojson/wiki/API-Reference Parameters ---------- geo_data: string/object URL, file path, or data (json, dict, geopandas, etc) to your GeoJSON geometries data: Pandas DataFrame or Series, default None Data to bind to the GeoJSON. columns: tuple with two values, default None If the data is a Pandas DataFrame, the columns of data to be bound. Must pass column 1 as the key, and column 2 the values. key_on: string, default None Variable in the `geo_data` GeoJSON file to bind the data to. Must start with 'feature' and be in JavaScript objection notation. Ex: 'feature.id' or 'feature.properties.statename'. bins: int or sequence of scalars or str, default 6 If `bins` is an int, it defines the number of equal-width bins between the min and the max of the values. If `bins` is a sequence, it directly defines the bin edges. For more information on this parameter, have a look at numpy.histogram function. fill_color: string, optional Area fill color, defaults to blue. Can pass a hex code, color name, or if you are binding data, one of the following color brewer palettes: 'BuGn', 'BuPu', 'GnBu', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'RdPu', 'YlGn', 'YlGnBu', 'YlOrBr', and 'YlOrRd'. nan_fill_color: string, default 'black' Area fill color for nan or missing values. Can pass a hex code, color name. fill_opacity: float, default 0.6 Area fill opacity, range 0-1. nan_fill_opacity: float, default fill_opacity Area fill opacity for nan or missing values, range 0-1. line_color: string, default 'black' GeoJSON geopath line color. line_weight: int, default 1 GeoJSON geopath line weight. line_opacity: float, default 1 GeoJSON geopath line opacity, range 0-1. legend_name: string, default empty string Title for data legend. topojson: string, default None If using a TopoJSON, passing "objects.yourfeature" to the topojson keyword argument will enable conversion to GeoJSON. smooth_factor: float, default None How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation. Leaflet defaults to 1.0. highlight: boolean, default False Enable highlight functionality when hovering over a GeoJSON area. use_jenks: bool, default False Use jenkspy to calculate bins using "natural breaks" (Fisher-Jenks algorithm). This is useful when your data is unevenly distributed. name : string, optional The name of the layer, as it will appear in LayerControls overlay : bool, default True Adds the layer as an optional overlay (True) or the base layer (False). control : bool, default True Whether the Layer will be included in LayerControls. show: bool, default True Whether the layer will be shown on opening. Returns ------- GeoJSON data layer in obj.template_vars Examples -------- >>> Choropleth(geo_data="us-states.json", line_color="blue", line_weight=3) >>> Choropleth( ... geo_data="geo.json", ... data=df, ... columns=["Data 1", "Data 2"], ... key_on="feature.properties.myvalue", ... fill_color="PuBu", ... bins=[0, 20, 30, 40, 50, 60], ... ) >>> Choropleth(geo_data="countries.json", topojson="objects.countries") >>> Choropleth( ... geo_data="geo.json", ... data=df, ... columns=["Data 1", "Data 2"], ... key_on="feature.properties.myvalue", ... fill_color="PuBu", ... bins=[0, 20, 30, 40, 50, 60], ... highlight=True, ... ) """ def __init__( self, geo_data: Any, data: Optional[Any] = None, columns: Optional[Sequence[Any]] = None, key_on: Optional[str] = None, bins: Union[int, Sequence[float]] = 6, fill_color: Optional[str] = None, nan_fill_color: str = "black", fill_opacity: float = 0.6, nan_fill_opacity: Optional[float] = None, line_color: str = "black", line_weight: float = 1, line_opacity: float = 1, name: Optional[str] = None, legend_name: str = "", overlay: bool = True, control: bool = True, show: bool = True, topojson: Optional[str] = None, smooth_factor: Optional[float] = None, highlight: bool = False, use_jenks: bool = False, **kwargs, ): super().__init__(name=name, overlay=overlay, control=control, show=show) self._name = "Choropleth" fill_color = fill_color or ("blue" if data is None else "Blues") if data is not None and not color_brewer(fill_color): raise ValueError( "Please pass a valid color brewer code to " "fill_local. See docstring for valid codes." ) if nan_fill_opacity is None: nan_fill_opacity = fill_opacity if "threshold_scale" in kwargs: if kwargs["threshold_scale"] is not None: bins = kwargs["threshold_scale"] warnings.warn( "choropleth `threshold_scale` parameter is now depreciated " "in favor of the `bins` parameter.", DeprecationWarning, ) # Create color_data dict if hasattr(data, "set_index"): # This is a pd.DataFrame assert columns is not None color_data = data.set_index(columns[0])[columns[1]].to_dict() # type: ignore elif hasattr(data, "to_dict"): # This is a pd.Series color_data = data.to_dict() # type: ignore elif data: color_data = dict(data) else: color_data = None self.color_scale = None if color_data is not None and key_on is not None: real_values = np.array(list(color_data.values())) real_values = real_values[~np.isnan(real_values)] if use_jenks: from jenkspy import jenks_breaks if not isinstance(bins, int): raise ValueError( f"bins value must be an integer when using Jenks." f' Invalid value "{bins}" received.' ) bin_edges = np.array(jenks_breaks(real_values, bins), dtype=float) else: _, bin_edges = np.histogram(real_values, bins=bins) bins_min, bins_max = min(bin_edges), max(bin_edges) if np.any((real_values < bins_min) | (real_values > bins_max)): raise ValueError( "All values are expected to fall into one of the provided " "bins (or to be Nan). Please check the `bins` parameter " "and/or your data." ) # We add the colorscale nb_bins = len(bin_edges) - 1 color_range = color_brewer(fill_color, n=nb_bins) self.color_scale = StepColormap( color_range, index=list(bin_edges), vmin=bins_min, vmax=bins_max, caption=legend_name, ) # then we 'correct' the last edge for numpy digitize # (we add a very small amount to fake an inclusive right interval) increasing = bin_edges[0] <= bin_edges[-1] bin_edges = bin_edges.astype(float) bin_edges[-1] = np.nextafter( bin_edges[-1], (1 if increasing else -1) * np.inf ) key_on = key_on[8:] if key_on.startswith("feature.") else key_on def color_scale_fun(x): key_of_x = self._get_by_key(x, key_on) if key_of_x is None: raise ValueError(f"key_on `{key_on!r}` not found in GeoJSON.") try: value_of_x = color_data[key_of_x] except KeyError: try: # try again but match str to int and vice versa if isinstance(key_of_x, int): value_of_x = color_data[str(key_of_x)] elif isinstance(key_of_x, str): value_of_x = color_data[int(key_of_x)] else: return nan_fill_color, nan_fill_opacity except (KeyError, ValueError): return nan_fill_color, nan_fill_opacity if np.isnan(value_of_x): return nan_fill_color, nan_fill_opacity color_idx = np.digitize(value_of_x, bin_edges, right=False) - 1 return color_range[color_idx], fill_opacity else: def color_scale_fun(x): return fill_color, fill_opacity def style_function(x): color, opacity = color_scale_fun(x) return { "weight": line_weight, "opacity": line_opacity, "color": line_color, "fillOpacity": opacity, "fillColor": color, } def highlight_function(x): return {"weight": line_weight + 2, "fillOpacity": fill_opacity + 0.2} if topojson: self.geojson: Union[TopoJson, GeoJson] = TopoJson( geo_data, topojson, style_function=style_function, smooth_factor=smooth_factor, ) else: self.geojson = GeoJson( geo_data, style_function=style_function, smooth_factor=smooth_factor, highlight_function=highlight_function if highlight else None, ) self.add_child(self.geojson) if self.color_scale: self.add_child(self.color_scale) @classmethod def _get_by_key(cls, obj: Union[dict, list], key: str) -> Union[float, str, None]: key_parts = key.split(".") first_key_part = key_parts[0] if first_key_part.isdigit(): value = obj[int(first_key_part)] else: value = obj.get(first_key_part, None) # type: ignore if len(key_parts) > 1: new_key = ".".join(key_parts[1:]) return cls._get_by_key(value, new_key) else: return value def render(self, **kwargs): """Render the GeoJson/TopoJson and color scale objects.""" if self.color_scale: # ColorMap needs Map as its parent assert isinstance( self._parent, Map ), "Choropleth must be added to a Map object." self.color_scale._parent = self._parent super().render(**kwargs)
Choropleth
python
apache__airflow
task-sdk/tests/task_sdk/io/test_path.py
{ "start": 6128, "end": 10957 }
class ____: @pytest.fixture def target(self, tmp_path): tmp = tmp_path.joinpath(str(uuid.uuid4())) tmp.touch() return tmp.as_posix() @pytest.fixture def another(self, tmp_path): tmp = tmp_path.joinpath(str(uuid.uuid4())) tmp.touch() return tmp.as_posix() def test_ls(self, tmp_path, target): d = ObjectStoragePath(f"file://{tmp_path.as_posix()}") o = ObjectStoragePath(f"file://{target}") data = list(d.iterdir()) assert len(data) == 1 assert data[0] == o d.rmdir(recursive=True) assert not o.exists() def test_read_write(self, target): o = ObjectStoragePath(f"file://{target}") with o.open("wb") as f: f.write(b"foo") assert o.open("rb").read() == b"foo" o.unlink() def test_read_line_by_line(self, target): o = ObjectStoragePath(f"file://{target}") with o.open("wb") as f: f.write(b"foo\nbar\n") with o.open("rb") as f: lines = list(f) assert lines == [b"foo\n", b"bar\n"] o.unlink() def test_stat(self, target): o = ObjectStoragePath(f"file://{target}") assert o.stat().st_size == 0 assert S_ISREG(o.stat().st_mode) assert S_ISDIR(o.parent.stat().st_mode) def test_replace(self, target, another): o = ObjectStoragePath(f"file://{target}") i = ObjectStoragePath(f"file://{another}") assert i.size() == 0 txt = "foo" o.write_text(txt) e = o.replace(i) assert o.exists() is False assert i == e assert e.size() == len(txt) def test_hash(self, target, another): file_uri_1 = f"file://{target}" file_uri_2 = f"file://{another}" s = set() for _ in range(10): s.add(ObjectStoragePath(file_uri_1)) s.add(ObjectStoragePath(file_uri_2)) assert len(s) == 2 def test_is_relative_to(self, tmp_path, target): o1 = ObjectStoragePath(f"file://{target}") o2 = ObjectStoragePath(f"file://{tmp_path.as_posix()}") o3 = ObjectStoragePath(f"file:///{uuid.uuid4()}") assert o1.is_relative_to(o2) assert not o1.is_relative_to(o3) def test_relative_to(self, tmp_path, target): o1 = ObjectStoragePath(f"file://{target}") o2 = ObjectStoragePath(f"file://{tmp_path.as_posix()}") o3 = ObjectStoragePath(f"file:///{uuid.uuid4()}") assert o1.relative_to(o2) == o1 with pytest.raises(ValueError, match="is not in the subpath of"): o1.relative_to(o3) def test_asset(self): p = "s3" f = "bucket/object" i = Asset(uri=f"{p}://{f}", name="test-asset", extra={"foo": "bar"}) o = ObjectStoragePath(i) assert o.protocol == p assert o.path == f def test_move_local(self, hook_lineage_collector, tmp_path, target): o1 = ObjectStoragePath(f"file://{target}") o2 = ObjectStoragePath(f"file://{tmp_path}/{uuid.uuid4()}") assert o1.exists() assert not o2.exists() o1.move(o2) assert o2.exists() assert not o1.exists() collected_assets = hook_lineage_collector.collected_assets assert len(collected_assets.inputs) == 1 assert len(collected_assets.outputs) == 1 assert collected_assets.inputs[0].asset.uri == str(o1) assert collected_assets.outputs[0].asset.uri == str(o2) def test_serde_objectstoragepath(self): path = "file:///bucket/key/part1/part2" o = ObjectStoragePath(path) s = o.serialize() assert s["path"] == path d = ObjectStoragePath.deserialize(s, 1) assert o == d o = ObjectStoragePath(path, my_setting="foo") s = o.serialize() assert "my_setting" in s["kwargs"] d = ObjectStoragePath.deserialize(s, 1) assert o == d store = attach("file", conn_id="mock") o = ObjectStoragePath(path, store=store) s = o.serialize() assert s["kwargs"]["store"] == store d = ObjectStoragePath.deserialize(s, 1) assert o == d def test_serde_store(self): store = attach("file", conn_id="mock") s = store.serialize() d = ObjectStore.deserialize(s, 1) assert s["protocol"] == "file" assert s["conn_id"] == "mock" assert s["filesystem"] == qualname(LocalFileSystem) assert store == d store = attach("localfs", fs=LocalFileSystem()) s = store.serialize() d = ObjectStore.deserialize(s, 1) assert s["protocol"] == "localfs" assert s["conn_id"] is None assert s["filesystem"] == qualname(LocalFileSystem) assert store == d
TestLocalPath
python
keras-team__keras
keras/src/dtype_policies/dtype_policy_test.py
{ "start": 27113, "end": 27855 }
class ____(test_case.TestCase): def setUp(self): """Reset the global dtype policy before each test.""" set_dtype_policy("float32") def test_set_policy_multiple_times(self): """Test setting the policy multiple times in a row.""" set_dtype_policy("mixed_float16") policy = dtype_policy() self.assertEqual(policy.name, "mixed_float16") set_dtype_policy("float32") policy = dtype_policy() self.assertEqual(policy.name, "float32") def test_set_policy_none(self): """Test setting the policy to None.""" with self.assertRaisesRegex(ValueError, "Invalid `policy` argument"): set_dtype_policy(None)
DTypePolicyGlobalFunctionsEdgeCasesTest
python
huggingface__transformers
tests/models/timesformer/test_modeling_timesformer.py
{ "start": 1559, "end": 5402 }
class ____: def __init__( self, parent, batch_size=13, image_size=10, num_channels=3, patch_size=2, num_frames=2, is_training=True, use_labels=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, num_labels=10, initializer_range=0.02, attention_type="divided_space_time", scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.num_channels = num_channels self.patch_size = patch_size self.num_frames = num_frames self.is_training = is_training self.use_labels = use_labels self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.attention_type = attention_type self.initializer_range = initializer_range self.scope = scope self.num_labels = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token self.num_patches_per_frame = (image_size // patch_size) ** 2 self.seq_length = (num_frames) * self.num_patches_per_frame + 1 def prepare_config_and_inputs(self): pixel_values = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) labels = None if self.use_labels: labels = ids_tensor([self.batch_size], self.num_labels) config = self.get_config() return config, pixel_values, labels def get_config(self): config = TimesformerConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, num_frames=self.num_frames, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, initializer_range=self.initializer_range, attention_type=self.attention_type, ) config.num_labels = self.num_labels return config def create_and_check_model(self, config, pixel_values, labels): model = TimesformerModel(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_for_video_classification(self, config, pixel_values, labels): model = TimesformerForVideoClassification(config) model.to(torch_device) model.eval() result = model(pixel_values) # verify the logits shape expected_shape = torch.Size((self.batch_size, self.num_labels)) self.parent.assertEqual(result.logits.shape, expected_shape) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, labels = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch
TimesformerModelTester
python
sympy__sympy
sympy/stats/joint_rv.py
{ "start": 8645, "end": 10602 }
class ____: """Returns the sample from pymc of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc(dist, size, seed) @classmethod def _sample_pymc(cls, dist, size, seed): """Sample from PyMC.""" try: import pymc except ImportError: import pymc3 as pymc pymc_rv_map = { 'MultivariateNormalDistribution': lambda dist: pymc.MvNormal('X', mu=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), shape=(1, dist.mu.shape[0])), 'MultivariateBetaDistribution': lambda dist: pymc.Dirichlet('X', a=list2numpy(dist.alpha, float).flatten()), 'MultinomialDistribution': lambda dist: pymc.Multinomial('X', n=int(dist.n), p=list2numpy(dist.p, float).flatten(), shape=(1, len(dist.p))) } sample_shape = { 'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape, 'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape, 'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape } dist_list = pymc_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None import logging logging.getLogger("pymc3").setLevel(logging.ERROR) with pymc.Model(): pymc_rv_map[dist.__class__.__name__](dist) samples = pymc.sample(draws=prod(size), chains=1, progressbar=False, random_seed=seed, return_inferencedata=False, compute_convergence_checks=False)[:]['X'] return samples.reshape(size + sample_shape[dist.__class__.__name__](dist)) _get_sample_class_jrv = { 'scipy': SampleJointScipy, 'pymc3': SampleJointPymc, 'pymc': SampleJointPymc, 'numpy': SampleJointNumpy }
SampleJointPymc
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/dependency_foo_bar/package.py
{ "start": 217, "end": 690 }
class ____(Package): """This package has a variant "bar", which is False by default, and variant "foo" which is True by default. """ homepage = "http://www.example.com" url = "http://www.example.com/dependency-foo-bar-1.0.tar.gz" version("1.0", md5="1234567890abcdefg1234567890098765") variant("foo", default=True, description="") variant("bar", default=False, description="") depends_on("second-dependency-foo-bar-fee")
DependencyFooBar
python
bokeh__bokeh
src/bokeh/core/property/descriptors.py
{ "start": 29844, "end": 34819 }
class ____(DataSpecPropertyDescriptor): """ A ``PropertyDescriptor`` for Bokeh ``UnitsSpec`` properties that contribute associated ``_units`` properties automatically as a side effect. """ def __init__(self, name, property, units_property) -> None: """ Args: name (str) : The attribute name that this property is for property (Property) : A basic property to create a descriptor for units_property (Property) : An associated property to hold units information """ super().__init__(name, property) self.units_prop = units_property def __set__(self, obj, value, *, setter=None): """ Implement the setter for the Python `descriptor protocol`_. This method first separately extracts and removes any ``units`` field in the JSON, and sets the associated units property directly. The remaining value is then passed to the superclass ``__set__`` to be handled. .. note:: An optional argument ``setter`` has been added to the standard setter arguments. When needed, this value should be provided by explicitly invoking ``__set__``. See below for more information. Args: obj (HasProps) : The instance to set a new property value on value (obj) : The new value to set the property to setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None """ value = self._extract_units(obj, value) super().__set__(obj, value, setter=setter) def set_from_json(self, obj, json, *, models=None, setter=None): """ Sets the value of this property from a JSON value. This method first separately extracts and removes any ``units`` field in the JSON, and sets the associated units property directly. The remaining JSON is then passed to the superclass ``set_from_json`` to be handled. Args: obj: (HasProps) : instance to set the property value on json: (JSON-value) : value to set to the attribute to models (dict or None, optional) : Mapping of model ids to models (default: None) This is needed in cases where the attributes to update also have values that have references. setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None """ json = self._extract_units(obj, json) super().set_from_json(obj, json, setter=setter) def _extract_units(self, obj, value): """ Internal helper for dealing with units associated units properties when setting values on ``UnitsSpec`` properties. When ``value`` is a dict, this function may mutate the value of the associated units property. Args: obj (HasProps) : instance to update units spec property value for value (obj) : new value to set for the property Returns: copy of ``value``, with 'units' key and value removed when applicable """ if isinstance(value, dict): if 'units' in value: value = copy(value) # so we can modify it units = value.pop("units", None) if units: self.units_prop.__set__(obj, units) return value #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
UnitsSpecPropertyDescriptor
python
lazyprogrammer__machine_learning_examples
unsupervised_class2/autoencoder_tf.py
{ "start": 3193, "end": 7866 }
class ____(object): def __init__(self, D, hidden_layer_sizes, K, UnsupervisedModel=AutoEncoder): self.hidden_layers = [] count = 0 input_size = D for output_size in hidden_layer_sizes: ae = UnsupervisedModel(input_size, output_size, count) self.hidden_layers.append(ae) count += 1 input_size = output_size self.build_final_layer(D, hidden_layer_sizes[-1], K) def set_session(self, session): self.session = session for layer in self.hidden_layers: layer.set_session(session) def build_final_layer(self, D, M, K): # initialize logistic regression layer self.W = tf.Variable(tf.random.normal(shape=(M, K))) self.b = tf.Variable(np.zeros(K).astype(np.float32)) self.X = tf.compat.v1.placeholder(tf.float32, shape=(None, D)) labels = tf.compat.v1.placeholder(tf.int32, shape=(None,)) self.Y = labels logits = self.forward(self.X) self.cost = tf.reduce_mean( input_tensor=tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels ) ) self.train_op = tf.compat.v1.train.AdamOptimizer(1e-2).minimize(self.cost) self.prediction = tf.argmax(input=logits, axis=1) def fit(self, X, Y, Xtest, Ytest, pretrain=True, epochs=1, batch_sz=100): N = len(X) # greedy layer-wise training of autoencoders pretrain_epochs = 1 if not pretrain: pretrain_epochs = 0 current_input = X for ae in self.hidden_layers: ae.fit(current_input, epochs=pretrain_epochs) # create current_input for the next layer current_input = ae.transform(current_input) n_batches = N // batch_sz costs = [] print("supervised training...") for i in range(epochs): print("epoch:", i) X, Y = shuffle(X, Y) for j in range(n_batches): Xbatch = X[j*batch_sz:(j*batch_sz + batch_sz)] Ybatch = Y[j*batch_sz:(j*batch_sz + batch_sz)] self.session.run( self.train_op, feed_dict={self.X: Xbatch, self.Y: Ybatch} ) c, p = self.session.run( (self.cost, self.prediction), feed_dict={self.X: Xtest, self.Y: Ytest }) error = error_rate(p, Ytest) if j % 10 == 0: print("j / n_batches:", j, "/", n_batches, "cost:", c, "error:", error) costs.append(c) plt.plot(costs) plt.show() def forward(self, X): current_input = X for ae in self.hidden_layers: Z = ae.forward_hidden(current_input) current_input = Z # logistic layer logits = tf.matmul(current_input, self.W) + self.b return logits def test_pretraining_dnn(): Xtrain, Ytrain, Xtest, Ytest = getKaggleMNIST() # dnn = DNN([1000, 750, 500]) # dnn.fit(Xtrain, Ytrain, Xtest, Ytest, epochs=3) # vs Xtrain = Xtrain.astype(np.float32) Xtest = Xtest.astype(np.float32) _, D = Xtrain.shape K = len(set(Ytrain)) dnn = DNN(D, [1000, 750, 500], K) init_op = tf.compat.v1.global_variables_initializer() with tf.compat.v1.Session() as session: session.run(init_op) dnn.set_session(session) dnn.fit(Xtrain, Ytrain, Xtest, Ytest, pretrain=True, epochs=10) def test_single_autoencoder(): Xtrain, Ytrain, Xtest, Ytest = getKaggleMNIST() Xtrain = Xtrain.astype(np.float32) Xtest = Xtest.astype(np.float32) _, D = Xtrain.shape autoencoder = AutoEncoder(D, 300, 0) init_op = tf.compat.v1.global_variables_initializer() with tf.compat.v1.Session() as session: session.run(init_op) autoencoder.set_session(session) autoencoder.fit(Xtrain, show_fig=True) done = False while not done: i = np.random.choice(len(Xtest)) x = Xtest[i] y = autoencoder.predict([x]) plt.subplot(1,2,1) plt.imshow(x.reshape(28,28), cmap='gray') plt.title('Original') plt.subplot(1,2,2) plt.imshow(y.reshape(28,28), cmap='gray') plt.title('Reconstructed') plt.show() ans = input("Generate another?") if ans and ans[0] in ('n' or 'N'): done = True if __name__ == '__main__': # test_single_autoencoder() test_pretraining_dnn()
DNN