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
PrefectHQ__prefect
scripts/all_links_should_be_ok.py
{ "start": 464, "end": 4435 }
class ____: url: str status: int | None ok: bool sources: frozenset[Path] error: str | None = None async def extract_links(path: Path) -> set[str]: try: content = await anyio.to_thread.run_sync(path.read_text, "utf-8", "ignore") return {m.group(0).rstrip(".,)") for m in _URL_RE.finditer(content)} except Exception: return set() async def _probe(client: httpx.AsyncClient, url: str) -> LinkResult: try: r = await client.head(url, follow_redirects=True) if r.status_code in {405, 403}: r = await client.get(url, follow_redirects=True) return LinkResult(url, r.status_code, 200 <= r.status_code < 400, frozenset()) except Exception as exc: return LinkResult(url, None, False, frozenset(), str(exc)) async def check_links(urls: Iterable[str], concurrency: int) -> list[LinkResult]: sem = anyio.Semaphore(concurrency) results: list[LinkResult] = [] async with httpx.AsyncClient(timeout=10) as client: async def bound(u: str) -> None: async with sem: results.append(await _probe(client, u)) async with anyio.create_task_group() as tg: for url in urls: tg.start_soon(bound, url) return results async def audit( paths: set[Path], ignored_prefixes: tuple[str, ...], concurrency: int, ) -> list[LinkResult]: link_to_files: dict[str, set[Path]] = {} async def process_file(p: Path) -> None: for url in await extract_links(p): if any(url.startswith(pref) for pref in ignored_prefixes): continue if re.search(r"{[^}]+}", url): # skip template tokens like {var} continue link_to_files.setdefault(url, set()).add(p) chunk_size = 100 for i in range(0, len(paths), chunk_size): paths_chunk = list(paths)[i : i + chunk_size] async with anyio.create_task_group() as tg: for path in paths_chunk: tg.start_soon(process_file, path) return [ LinkResult( url=r.url, status=r.status, ok=r.ok, sources=frozenset(link_to_files[r.url]), error=r.error, ) for r in await check_links(link_to_files, concurrency) ] async def main() -> None: parser = argparse.ArgumentParser( description="Fail the build if any HTTP link is unreachable." ) parser.add_argument("include", nargs="+", help="Glob pattern(s) to scan.") parser.add_argument( "--exclude", nargs="*", default=[], help="Glob pattern(s) to skip." ) parser.add_argument( "--ignore-url", nargs="*", default=("http://localhost", "https://localhost"), metavar="PREFIX", help="URL prefixes to ignore.", ) parser.add_argument("-c", "--concurrency", type=int, default=50) ns = parser.parse_args() include = {Path(p) for pat in ns.include for p in glob.glob(pat, recursive=True)} exclude = {Path(p) for pat in ns.exclude for p in glob.glob(pat, recursive=True)} if not (files := include - exclude): print("No files to scan.", file=sys.stderr) sys.exit(2) links = await audit(files, tuple(ns.ignore_url), concurrency=ns.concurrency) broken_links: list[LinkResult] = [] for r in sorted(links, key=lambda x: sorted(x.sources)[0].as_posix()): status = r.status or "ERR" icon = f"{GREEN}✓{_END}" if r.ok else f"{RED}✗{_END}" url_repr = r.url if r.ok else f"{RED}{r.url}{_END}" srcs = ", ".join(s.as_posix() for s in sorted(r.sources)) print(f"{GREY}{srcs}:{_END} {status:>4} {icon} {url_repr}") if not r.ok: broken_links.append(r) if broken_links: print(f"\n{len(broken_links)} broken link(s) detected.", file=sys.stderr) sys.exit(1) if __name__ == "__main__": anyio.run(main)
LinkResult
python
jazzband__django-simple-history
simple_history/tests/tests/test_models.py
{ "start": 97445, "end": 99557 }
class ____(TestCase): def setUp(self): self.user_one = get_user_model().objects.create( username="username_one", email="first@user.com", password="top_secret" ) self.user_two = get_user_model().objects.create( username="username_two", email="second@user.com", password="top_secret" ) self.one = Street(name="Test Street") self.one._history_user = self.user_one self.one.save() self.two = Street(name="Sesame Street") self.two._history_user = self.user_two self.two.save() self.one.name = "ABC Street" self.one._history_user = self.user_two self.one.save() def test_relation(self): self.assertEqual(self.one.history.count(), 2) self.assertEqual(self.two.history.count(), 1) def test_filter(self): self.assertEqual( Street.objects.filter(history__history_user=self.user_one.pk).count(), 1 ) self.assertEqual( Street.objects.filter(history__history_user=self.user_two.pk).count(), 2 ) def test_name_equals_manager(self): with self.assertRaises(RelatedNameConflictError): register(Place, manager_name="history", related_name="history") def test_deletion(self): self.two.delete() self.assertEqual(Street.log.filter(history_relation=2).count(), 2) self.assertEqual(Street.log.count(), 4) def test_revert(self): id = self.one.pk self.one.delete() self.assertEqual( Street.objects.filter(history__history_user=self.user_one.pk).count(), 0 ) self.assertEqual(Street.objects.filter(pk=id).count(), 0) old = Street.log.filter(id=id).first() old.history_object.save() self.assertEqual( Street.objects.filter(history__history_user=self.user_one.pk).count(), 1 ) self.one = Street.objects.get(pk=id) self.assertEqual(self.one.history.count(), 4) @override_settings(**database_router_override_settings_history_in_diff_db)
RelatedNameTest
python
ray-project__ray
release/nightly_tests/dask_on_ray/large_scale_test.py
{ "start": 5133, "end": 10102 }
class ____: @staticmethod def fft_xarray(xr_input: xarray.Dataset, n_fft: int, hop_length: int): """ Perform FFT on an Xarray and return it as another Xarray. """ # Infer the output chunk shape since FFT does # not preserve input chunk shape. output_chunk_shape = TransformRoutines.infer_chunk_shape_after_fft( n_fft=n_fft, hop_length=hop_length, time_chunk_sizes=xr_input.chunks["time"], ) transformed_audio = dask.array.map_overlap( TransformRoutines.fft_algorithm, xr_input.data_var.data, depth={0: 0, 1: (0, n_fft - hop_length)}, boundary={0: "none", 1: "none"}, chunks=output_chunk_shape, dtype=np.float32, trim=True, algorithm_params={"hop_length": hop_length, "n_fft": n_fft}, ) return xarray.Dataset( data_vars={ "data_var": ( ["channel", "freq", "time"], transformed_audio, ), }, coords={ "freq": ("freq", np.arange(transformed_audio.shape[1])), "channel": ("channel", np.arange(INPUT_SHAPE[0])), }, attrs={"hello": "world2"}, ) @staticmethod def decimate_xarray_after_load(xr_input: xarray.Dataset, decimate_factor: int): """ Downsample an Xarray. """ # Infer the output chunk shape since FFT does # not preserve input chunk shape. start_chunks = xr_input.data_var.data.chunks data_0 = xr_input.data_var.data[0] - xr_input.data_var.data[2] data_1 = xr_input.data_var.data[2] data_2 = xr_input.data_var.data[0] stacked_data = dask.array.stack([data_0, data_1, data_2], axis=0) stacked_chunks = stacked_data.chunks rechunking_to_chunks = (start_chunks[0], stacked_chunks[1]) xr_input.data_var.data = stacked_data.rechunk(rechunking_to_chunks) in_chunks = xr_input.data_var.data.chunks out_chunks = ( in_chunks[0], tuple([int(chunk / decimate_factor) for chunk in in_chunks[1]]), ) data_ds_data = xr_input.data_var.data.map_overlap( TransformRoutines.decimate_raw_data, decimate_time=decimate_factor, overlap_time=10, depth=(0, decimate_factor * 10), trim=False, dtype="float32", chunks=out_chunks, ) data_ds = copy(xr_input) data_ds = data_ds.isel(time=slice(0, data_ds_data.shape[1])) data_ds.data_var.data = data_ds_data return data_ds @staticmethod def decimate_raw_data(data: np.ndarray, decimate_time: int, overlap_time=0): from scipy.signal import decimate data = np.nan_to_num(data) if decimate_time > 1: data = decimate(data, q=decimate_time, axis=1) if overlap_time > 0: data = data[:, overlap_time:-overlap_time] return data @staticmethod def fft_algorithm(data: np.ndarray, algorithm_params: dict) -> np.ndarray: """ Apply FFT algorithm to an input xarray. """ from scipy import signal hop_length = algorithm_params["hop_length"] n_fft = algorithm_params["n_fft"] noverlap = n_fft - hop_length _, _, spectrogram = signal.stft( data, nfft=n_fft, nperseg=n_fft, noverlap=noverlap, return_onesided=False, boundary=None, ) spectrogram = np.abs(spectrogram) spectrogram = 10 * np.log10(spectrogram**2) return spectrogram @staticmethod def infer_chunk_shape_after_fft( n_fft: int, hop_length: int, time_chunk_sizes: List ) -> tuple: """ Infer the chunk shapes after applying FFT transformation. Infer is necessary for lazy transformations in Dask when transformations do not preserve chunk shape. """ output_time_chunk_sizes = list() for time_chunk_size in time_chunk_sizes: output_time_chunk_sizes.append(math.ceil(time_chunk_size / hop_length)) num_freq = int(n_fft / 2 + 1) return (INPUT_SHAPE[0],), (num_freq,), tuple(output_time_chunk_sizes) @staticmethod def fix_last_chunk_error(xr_input: xarray.Dataset, n_overlap): time_chunks = list(xr_input.chunks["time"]) # purging chunks that are too small if time_chunks[-1] < n_overlap: current_len = len(xr_input.time) xr_input = xr_input.isel(time=slice(0, current_len - time_chunks[-1])) if time_chunks[0] < n_overlap: current_len = len(xr_input.time) xr_input = xr_input.isel(time=slice(time_chunks[0], current_len)) return xr_input
TransformRoutines
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 392066, "end": 393452 }
class ____(ComprehensionAppendNode): child_attrs = ['key_expr', 'value_expr'] def analyse_expressions(self, env): self.key_expr = self.key_expr.analyse_expressions(env) if not self.key_expr.type.is_pyobject: self.key_expr = self.key_expr.coerce_to_pyobject(env) self.value_expr = self.value_expr.analyse_expressions(env) if not self.value_expr.type.is_pyobject: self.value_expr = self.value_expr.coerce_to_pyobject(env) return self def generate_execution_code(self, code): self.key_expr.generate_evaluation_code(code) self.value_expr.generate_evaluation_code(code) code.putln(code.error_goto_if("PyDict_SetItem(%s, (PyObject*)%s, (PyObject*)%s)" % ( self.target.result(), self.key_expr.result(), self.value_expr.result() ), self.pos)) self.key_expr.generate_disposal_code(code) self.key_expr.free_temps(code) self.value_expr.generate_disposal_code(code) self.value_expr.free_temps(code) def generate_function_definitions(self, env, code): self.key_expr.generate_function_definitions(env, code) self.value_expr.generate_function_definitions(env, code) def annotate(self, code): self.key_expr.annotate(code) self.value_expr.annotate(code)
DictComprehensionAppendNode
python
sqlalchemy__sqlalchemy
test/dialect/sqlite/test_reflection.py
{ "start": 2555, "end": 40289 }
class ____(fixtures.TestBase): __only_on__ = "sqlite" __backend__ = True @classmethod def setup_test_class(cls): with testing.db.begin() as conn: conn.exec_driver_sql("CREATE TABLE a1 (id INTEGER PRIMARY KEY)") conn.exec_driver_sql("CREATE TABLE a2 (id INTEGER PRIMARY KEY)") conn.exec_driver_sql( "CREATE TABLE b (id INTEGER PRIMARY KEY, " "FOREIGN KEY(id) REFERENCES a1(id)," "FOREIGN KEY(id) REFERENCES a2(id)" ")" ) conn.exec_driver_sql( "CREATE TABLE c (id INTEGER, " "CONSTRAINT bar PRIMARY KEY(id)," "CONSTRAINT foo1 FOREIGN KEY(id) REFERENCES a1(id)," "CONSTRAINT foo2 FOREIGN KEY(id) REFERENCES a2(id)" ")" ) conn.exec_driver_sql( # the lower casing + inline is intentional here "CREATE TABLE d (id INTEGER, x INTEGER unique)" ) conn.exec_driver_sql( # the lower casing + inline is intentional here "CREATE TABLE d1 " '(id INTEGER, "some ( STUPID n,ame" INTEGER unique)' ) conn.exec_driver_sql( # the lower casing + inline is intentional here 'CREATE TABLE d2 ( "some STUPID n,ame" INTEGER unique)' ) conn.exec_driver_sql( # the lower casing + inline is intentional here 'CREATE TABLE d3 ( "some STUPID n,ame" INTEGER NULL unique)' ) conn.exec_driver_sql( # lower casing + inline is intentional "CREATE TABLE e (id INTEGER, x INTEGER references a2(id))" ) conn.exec_driver_sql( 'CREATE TABLE e1 (id INTEGER, "some ( STUPID n,ame" INTEGER ' 'references a2 ("some ( STUPID n,ame"))' ) conn.exec_driver_sql( "CREATE TABLE e2 (id INTEGER, " '"some ( STUPID n,ame" INTEGER NOT NULL ' 'references a2 ("some ( STUPID n,ame"))' ) conn.exec_driver_sql( "CREATE TABLE f (x INTEGER, CONSTRAINT foo_fx UNIQUE(x))" ) conn.exec_driver_sql( # intentional broken casing "CREATE TABLE h (x INTEGER, COnstraINT foo_hx unIQUE(x))" ) conn.exec_driver_sql( "CREATE TABLE i (x INTEGER, y INTEGER, PRIMARY KEY(x, y))" ) conn.exec_driver_sql( "CREATE TABLE j (id INTEGER, q INTEGER, p INTEGER, " "PRIMARY KEY(id), FOreiGN KEY(q,p) REFERENCes i(x,y))" ) conn.exec_driver_sql( "CREATE TABLE k (id INTEGER, q INTEGER, p INTEGER, " "PRIMARY KEY(id), " "conSTRAINT my_fk FOreiGN KEY ( q , p ) " "REFERENCes i ( x , y ))" ) meta = MetaData() Table("l", meta, Column("bar", String, index=True), schema="main") Table( "m", meta, Column("id", Integer, primary_key=True), Column("x", String(30)), UniqueConstraint("x"), ) Table( "p", meta, Column("id", Integer), PrimaryKeyConstraint("id", name="pk_name"), ) Table("q", meta, Column("id", Integer), PrimaryKeyConstraint("id")) # intentional new line Table( "r", meta, Column("id", Integer), Column("value", Integer), Column("prefix", String), CheckConstraint("id > 0"), UniqueConstraint("prefix", name="prefix_named"), # Constraint definition with newline and tab characters CheckConstraint( """((value > 0) AND \n\t(value < 100) AND \n\t (value != 50))""", name="ck_r_value_multiline", ), UniqueConstraint("value"), # Constraint name with special chars and 'check' in the name CheckConstraint("value IS NOT NULL", name="^check-r* #\n\t"), PrimaryKeyConstraint("id", name="pk_name"), # Constraint definition with special characters. CheckConstraint("prefix NOT GLOB '*[^-. /#,]*'"), ) meta.create_all(conn) # will contain an "autoindex" conn.exec_driver_sql( "create table o (foo varchar(20) primary key)" ) conn.exec_driver_sql( "CREATE TABLE onud_test (id INTEGER PRIMARY KEY, " "c1 INTEGER, c2 INTEGER, c3 INTEGER, c4 INTEGER, " "CONSTRAINT fk1 FOREIGN KEY (c1) REFERENCES a1(id) " "ON DELETE SET NULL, " "CONSTRAINT fk2 FOREIGN KEY (c2) REFERENCES a1(id) " "ON UPDATE CASCADE, " "CONSTRAINT fk3 FOREIGN KEY (c3) REFERENCES a2(id) " "ON DELETE CASCADE ON UPDATE SET NULL," "CONSTRAINT fk4 FOREIGN KEY (c4) REFERENCES a2(id) " "ON UPDATE NO ACTION)" ) conn.exec_driver_sql( "CREATE TABLE deferrable_test (id INTEGER PRIMARY KEY, " "c1 INTEGER, c2 INTEGER, c3 INTEGER, c4 INTEGER, " "CONSTRAINT fk1 FOREIGN KEY (c1) REFERENCES a1(id) " "DEFERRABLE," "CONSTRAINT fk2 FOREIGN KEY (c2) REFERENCES a1(id) " "NOT DEFERRABLE," "CONSTRAINT fk3 FOREIGN KEY (c3) REFERENCES a2(id) " "ON UPDATE CASCADE " "DEFERRABLE INITIALLY DEFERRED," "CONSTRAINT fk4 FOREIGN KEY (c4) REFERENCES a2(id) " "NOT DEFERRABLE INITIALLY IMMEDIATE)" ) conn.exec_driver_sql( "CREATE TABLE cp (" "id INTEGER NOT NULL,\n" "q INTEGER, \n" "p INTEGER, \n" "CONSTRAINT cq CHECK (p = 1 OR (p > 2 AND p < 5)),\n" "PRIMARY KEY (id)\n" ")" ) conn.exec_driver_sql( "CREATE TABLE cp_inline (\n" "id INTEGER NOT NULL,\n" "q INTEGER CHECK (q > 1 AND q < 6), \n" "p INTEGER CONSTRAINT cq CHECK (p = 1 OR (p > 2 AND p < 5)),\n" "PRIMARY KEY (id)\n" ")" ) conn.exec_driver_sql( "CREATE TABLE implicit_referred (pk integer primary key)" ) # single col foreign key with no referred column given, # must assume primary key of referred table conn.exec_driver_sql( "CREATE TABLE implicit_referrer " "(id integer REFERENCES implicit_referred)" ) conn.exec_driver_sql( "CREATE TABLE implicit_referred_comp " "(pk1 integer, pk2 integer, primary key (pk1, pk2))" ) # composite foreign key with no referred columns given, # must assume primary key of referred table conn.exec_driver_sql( "CREATE TABLE implicit_referrer_comp " "(id1 integer, id2 integer, foreign key(id1, id2) " "REFERENCES implicit_referred_comp)" ) # worst case - FK that refers to nonexistent table so we can't # get pks. requires FK pragma is turned off conn.exec_driver_sql( "CREATE TABLE implicit_referrer_comp_fake " "(id1 integer, id2 integer, foreign key(id1, id2) " "REFERENCES fake_table)" ) # tables for issue #12924 - table names with CHECK/CONSTRAINT conn.exec_driver_sql( "CREATE TABLE oneline ( field INTEGER CHECK(field>0))" ) conn.exec_driver_sql( "CREATE TABLE oneline_nested ( field INTEGER " "CHECK((field>0 and field<22) or (field>99 and field<1010)))" ) conn.exec_driver_sql( "CREATE TABLE oneline_2constraints ( pk INTEGER " "CONSTRAINT pkname PRIMARY KEY, field INTEGER " "CONSTRAINT chname CHECK((field>0 and field<22) or " "(field>99 and field<1010)))" ) conn.exec_driver_sql( "CREATE TABLE oneline_nameCHECK ( pk INTEGER " "CONSTRAINT pkname PRIMARY KEY )" ) conn.exec_driver_sql( "CREATE TABLE oneline_nameCONSTRAINT " "( field INTEGER CHECK (field IN (1, 0, -1)) )" ) conn.exec_driver_sql( "CREATE TABLE twochecks_oneline (\n" "field INTEGER,\n" "CHECK (field>1), CHECK( field<9)\n" ")" ) # Test all SQLite quote styles for constraint names conn.exec_driver_sql( "CREATE TABLE quote_styles ( " "field INTEGER, " 'CONSTRAINT "double_quoted" CHECK (field > 0), ' "CONSTRAINT 'single_quoted' CHECK (field < 100), " "CONSTRAINT [bracket_quoted] CHECK (field != 50), " "CONSTRAINT `backtick_quoted` CHECK (field >= 10)" ")" ) # Test CHECK constraints with parentheses in string literals # These cases have unbalanced parens if we naively count all parens conn.exec_driver_sql( "CREATE TABLE parens_in_strings (" " field TEXT," " CHECK (field != '(')," " CHECK (field != ')')," " CHECK (field NOT LIKE '%(')," " CHECK (field IN (')', '(', 'test'))," # Escaped quotes (SQLite uses '' to escape quotes) " CHECK (field != 'it''s (not) valid')," ' CHECK (field != "say ""(hello)"" "),' " CHECK (field NOT IN ('()', 'a''b''c', ')'))," # Complex nested cases with lots of unbalanced parens in # strings " CHECK (field != '((' OR field = ')))')," ' CHECK (field LIKE "%))(%" OR field LIKE "%)(%")' ")" ) @classmethod def teardown_test_class(cls): with testing.db.begin() as conn: for name in [ "implicit_referrer_comp_fake", "implicit_referrer", "implicit_referred", "implicit_referrer_comp", "implicit_referred_comp", "m", "main.l", "k", "j", "i", "h", "f", "e", "e1", "d", "d1", "d2", "c", "b", "a1", "a2", "r", "oneline", "oneline_nested", "oneline_2constraints", "oneline_nameCHECK", "oneline_nameCONSTRAINT", "twochecks_oneline", "quote_styles", "parens_in_strings", ]: conn.exec_driver_sql("drop table %s" % name) @testing.fixture def temp_table_fixture(self, connection): connection.exec_driver_sql( "CREATE TEMPORARY TABLE g " "(x INTEGER, CONSTRAINT foo_gx UNIQUE(x))" ) n = Table( "n", MetaData(), Column("id", Integer, primary_key=True), Column("x", String(30)), UniqueConstraint("x"), prefixes=["TEMPORARY"], ) n.create(connection) try: yield finally: connection.exec_driver_sql("DROP TABLE g") n.drop(connection) def test_legacy_quoted_identifiers_unit(self): dialect = sqlite.dialect() dialect._broken_fk_pragma_quotes = True for row in [ (0, None, "target", "tid", "id", None), (0, None, '"target"', "tid", "id", None), (0, None, "[target]", "tid", "id", None), (0, None, "'target'", "tid", "id", None), (0, None, "`target`", "tid", "id", None), ]: def _get_table_pragma(*arg, **kw): return [row] def _get_table_sql(*arg, **kw): return ( "CREATE TABLE foo " "(tid INTEGER, " "FOREIGN KEY(tid) REFERENCES %s (id))" % row[2] ) with mock.patch.object( dialect, "_get_table_pragma", _get_table_pragma ): with mock.patch.object( dialect, "_get_table_sql", _get_table_sql ): fkeys = dialect.get_foreign_keys(None, "foo") eq_( fkeys, [ { "referred_table": "target", "referred_columns": ["id"], "referred_schema": None, "name": None, "constrained_columns": ["tid"], "options": {}, } ], ) def test_foreign_key_name_is_none(self): # and not "0" inspector = inspect(testing.db) fks = inspector.get_foreign_keys("b") eq_( fks, [ { "referred_table": "a1", "referred_columns": ["id"], "referred_schema": None, "name": None, "constrained_columns": ["id"], "options": {}, }, { "referred_table": "a2", "referred_columns": ["id"], "referred_schema": None, "name": None, "constrained_columns": ["id"], "options": {}, }, ], ) def test_foreign_key_name_is_not_none(self): inspector = inspect(testing.db) fks = inspector.get_foreign_keys("c") eq_( fks, [ { "referred_table": "a1", "referred_columns": ["id"], "referred_schema": None, "name": "foo1", "constrained_columns": ["id"], "options": {}, }, { "referred_table": "a2", "referred_columns": ["id"], "referred_schema": None, "name": "foo2", "constrained_columns": ["id"], "options": {}, }, ], ) def test_foreign_key_implicit_parent(self): inspector = inspect(testing.db) fks = inspector.get_foreign_keys("implicit_referrer") eq_( fks, [ { "name": None, "constrained_columns": ["id"], "referred_schema": None, "referred_table": "implicit_referred", "referred_columns": ["pk"], "options": {}, } ], ) def test_foreign_key_composite_implicit_parent(self): inspector = inspect(testing.db) fks = inspector.get_foreign_keys("implicit_referrer_comp") eq_( fks, [ { "name": None, "constrained_columns": ["id1", "id2"], "referred_schema": None, "referred_table": "implicit_referred_comp", "referred_columns": ["pk1", "pk2"], "options": {}, } ], ) def test_foreign_key_implicit_missing_parent(self): # test when the FK refers to a non-existent table and column names # aren't given. only sqlite allows this case to exist inspector = inspect(testing.db) fks = inspector.get_foreign_keys("implicit_referrer_comp_fake") # the referred table doesn't exist but the operation does not fail eq_( fks, [ { "name": None, "constrained_columns": ["id1", "id2"], "referred_schema": None, "referred_table": "fake_table", "referred_columns": [], "options": {}, } ], ) def test_foreign_key_implicit_missing_parent_reflection(self): # full Table reflection fails however, which is not a new behavior m = MetaData() assert_raises_message( exc.NoSuchTableError, "fake_table", Table, "implicit_referrer_comp_fake", m, autoload_with=testing.db, ) def test_unnamed_inline_foreign_key(self): inspector = inspect(testing.db) fks = inspector.get_foreign_keys("e") eq_( fks, [ { "referred_table": "a2", "referred_columns": ["id"], "referred_schema": None, "name": None, "constrained_columns": ["x"], "options": {}, } ], ) def test_unnamed_inline_foreign_key_quoted(self): inspector = inspect(testing.db) fks = inspector.get_foreign_keys("e1") eq_( fks, [ { "referred_table": "a2", "referred_columns": ["some ( STUPID n,ame"], "referred_schema": None, "options": {}, "name": None, "constrained_columns": ["some ( STUPID n,ame"], } ], ) fks = inspector.get_foreign_keys("e2") eq_( fks, [ { "referred_table": "a2", "referred_columns": ["some ( STUPID n,ame"], "referred_schema": None, "options": {}, "name": None, "constrained_columns": ["some ( STUPID n,ame"], } ], ) def test_foreign_key_composite_broken_casing(self): inspector = inspect(testing.db) fks = inspector.get_foreign_keys("j") eq_( fks, [ { "referred_table": "i", "referred_columns": ["x", "y"], "referred_schema": None, "name": None, "constrained_columns": ["q", "p"], "options": {}, } ], ) fks = inspector.get_foreign_keys("k") eq_( fks, [ { "referred_table": "i", "referred_columns": ["x", "y"], "referred_schema": None, "name": "my_fk", "constrained_columns": ["q", "p"], "options": {}, } ], ) def test_foreign_key_ondelete_onupdate(self): inspector = inspect(testing.db) fks = inspector.get_foreign_keys("onud_test") eq_( fks, [ { "referred_table": "a1", "referred_columns": ["id"], "referred_schema": None, "name": "fk1", "constrained_columns": ["c1"], "options": {"ondelete": "SET NULL"}, }, { "referred_table": "a1", "referred_columns": ["id"], "referred_schema": None, "name": "fk2", "constrained_columns": ["c2"], "options": {"onupdate": "CASCADE"}, }, { "referred_table": "a2", "referred_columns": ["id"], "referred_schema": None, "name": "fk3", "constrained_columns": ["c3"], "options": {"ondelete": "CASCADE", "onupdate": "SET NULL"}, }, { "referred_table": "a2", "referred_columns": ["id"], "referred_schema": None, "name": "fk4", "constrained_columns": ["c4"], "options": {}, }, ], ) def test_foreign_key_deferrable_initially(self): inspector = inspect(testing.db) fks = inspector.get_foreign_keys("deferrable_test") eq_( fks, [ { "referred_table": "a1", "referred_columns": ["id"], "referred_schema": None, "name": "fk1", "constrained_columns": ["c1"], "options": {"deferrable": True}, }, { "referred_table": "a1", "referred_columns": ["id"], "referred_schema": None, "name": "fk2", "constrained_columns": ["c2"], "options": {"deferrable": False}, }, { "referred_table": "a2", "referred_columns": ["id"], "referred_schema": None, "name": "fk3", "constrained_columns": ["c3"], "options": { "deferrable": True, "initially": "DEFERRED", "onupdate": "CASCADE", }, }, { "referred_table": "a2", "referred_columns": ["id"], "referred_schema": None, "name": "fk4", "constrained_columns": ["c4"], "options": {"deferrable": False, "initially": "IMMEDIATE"}, }, ], ) def test_foreign_key_options_unnamed_inline(self): with testing.db.begin() as conn: conn.exec_driver_sql( "create table foo (id integer, " "foreign key (id) references bar (id) on update cascade)" ) insp = inspect(conn) eq_( insp.get_foreign_keys("foo"), [ { "name": None, "referred_columns": ["id"], "referred_table": "bar", "constrained_columns": ["id"], "referred_schema": None, "options": {"onupdate": "CASCADE"}, } ], ) def test_dont_reflect_autoindex(self): inspector = inspect(testing.db) eq_(inspector.get_indexes("o"), []) eq_( inspector.get_indexes("o", include_auto_indexes=True), [ { "unique": 1, "name": "sqlite_autoindex_o_1", "column_names": ["foo"], "dialect_options": {}, } ], ) def test_create_index_with_schema(self): """Test creation of index with explicit schema""" inspector = inspect(testing.db) eq_( inspector.get_indexes("l", schema="main"), [ { "unique": 0, "name": "ix_main_l_bar", "column_names": ["bar"], "dialect_options": {}, } ], ) @testing.requires.sqlite_partial_indexes def test_reflect_partial_indexes(self, connection): connection.exec_driver_sql( "create table foo_with_partial_index (x integer, y integer)" ) connection.exec_driver_sql( "create unique index ix_partial on " "foo_with_partial_index (x) where y > 10" ) connection.exec_driver_sql( "create unique index ix_no_partial on " "foo_with_partial_index (x)" ) connection.exec_driver_sql( "create unique index ix_partial2 on " "foo_with_partial_index (x, y) where " "y = 10 or abs(x) < 5" ) inspector = inspect(connection) indexes = inspector.get_indexes("foo_with_partial_index") eq_( indexes, [ { "unique": 1, "name": "ix_no_partial", "column_names": ["x"], "dialect_options": {}, }, { "unique": 1, "name": "ix_partial", "column_names": ["x"], "dialect_options": {"sqlite_where": mock.ANY}, }, { "unique": 1, "name": "ix_partial2", "column_names": ["x", "y"], "dialect_options": {"sqlite_where": mock.ANY}, }, ], ) eq_(indexes[1]["dialect_options"]["sqlite_where"].text, "y > 10") eq_( indexes[2]["dialect_options"]["sqlite_where"].text, "y = 10 or abs(x) < 5", ) def test_unique_constraint_named(self): inspector = inspect(testing.db) eq_( inspector.get_unique_constraints("f"), [{"column_names": ["x"], "name": "foo_fx"}], ) def test_unique_constraint_named_broken_casing(self): inspector = inspect(testing.db) eq_( inspector.get_unique_constraints("h"), [{"column_names": ["x"], "name": "foo_hx"}], ) def test_unique_constraint_named_broken_temp( self, connection, temp_table_fixture ): inspector = inspect(connection) eq_( inspector.get_unique_constraints("g"), [{"column_names": ["x"], "name": "foo_gx"}], ) def test_unique_constraint_unnamed_inline(self): inspector = inspect(testing.db) eq_( inspector.get_unique_constraints("d"), [{"column_names": ["x"], "name": None}], ) def test_unique_constraint_unnamed_inline_quoted(self): inspector = inspect(testing.db) eq_( inspector.get_unique_constraints("d1"), [{"column_names": ["some ( STUPID n,ame"], "name": None}], ) eq_( inspector.get_unique_constraints("d2"), [{"column_names": ["some STUPID n,ame"], "name": None}], ) eq_( inspector.get_unique_constraints("d3"), [{"column_names": ["some STUPID n,ame"], "name": None}], ) def test_unique_constraint_unnamed_normal(self): inspector = inspect(testing.db) eq_( inspector.get_unique_constraints("m"), [{"column_names": ["x"], "name": None}], ) def test_unique_constraint_unnamed_normal_temporary( self, connection, temp_table_fixture ): inspector = inspect(connection) eq_( inspector.get_unique_constraints("n"), [{"column_names": ["x"], "name": None}], ) def test_unique_constraint_mixed_into_ck(self, connection): """test #11832""" inspector = inspect(connection) eq_( inspector.get_unique_constraints("r"), [ {"name": "prefix_named", "column_names": ["prefix"]}, {"name": None, "column_names": ["value"]}, ], ) def test_primary_key_constraint_mixed_into_ck(self, connection): """test #11832""" inspector = inspect(connection) eq_( inspector.get_pk_constraint("r"), {"constrained_columns": ["id"], "name": "pk_name"}, ) def test_primary_key_constraint_named(self): inspector = inspect(testing.db) eq_( inspector.get_pk_constraint("p"), {"constrained_columns": ["id"], "name": "pk_name"}, ) def test_primary_key_constraint_unnamed(self): inspector = inspect(testing.db) eq_( inspector.get_pk_constraint("q"), {"constrained_columns": ["id"], "name": None}, ) def test_primary_key_constraint_no_pk(self): inspector = inspect(testing.db) eq_( inspector.get_pk_constraint("d"), {"constrained_columns": [], "name": None}, ) def test_check_constraint_plain(self): inspector = inspect(testing.db) eq_( inspector.get_check_constraints("cp"), [ {"sqltext": "p = 1 OR (p > 2 AND p < 5)", "name": "cq"}, ], ) def test_check_constraint_inline_plain(self): inspector = inspect(testing.db) eq_( inspector.get_check_constraints("cp_inline"), [ {"sqltext": "p = 1 OR (p > 2 AND p < 5)", "name": "cq"}, {"sqltext": "q > 1 AND q < 6", "name": None}, ], ) def test_check_constraint_multiline(self): """test for #11677""" inspector = inspect(testing.db) eq_( inspector.get_check_constraints("r"), [ {"sqltext": "value IS NOT NULL", "name": "^check-r* #\n\t"}, # Triple-quote multi-line definition should have added a # newline and whitespace: { "sqltext": "((value > 0) AND \n\t(value < 100) AND \n\t\n" " (value != 50))", "name": "ck_r_value_multiline", }, {"sqltext": "id > 0", "name": None}, {"sqltext": "prefix NOT GLOB '*[^-. /#,]*'", "name": None}, ], ) @testing.combinations( ("plain_name", "plain_name"), ("name with spaces", "name with spaces"), ("plainname", "plainname"), ("[Code]", "[Code]"), (quoted_name("[Code]", quote=False), "Code"), argnames="colname,expected", ) @testing.combinations( "uq", "uq_inline", "uq_inline_tab_before", # tab before column params "uq_inline_tab_within", # tab within column params "pk", "ix", argnames="constraint_type", ) def test_constraint_cols( self, colname, expected, constraint_type, connection, metadata ): if constraint_type.startswith("uq_inline"): inline_create_sql = { "uq_inline": "CREATE TABLE t (%s INTEGER UNIQUE)", "uq_inline_tab_before": "CREATE TABLE t (%s\tINTEGER UNIQUE)", "uq_inline_tab_within": "CREATE TABLE t (%s INTEGER\tUNIQUE)", } t = Table("t", metadata, Column(colname, Integer)) connection.exec_driver_sql( inline_create_sql[constraint_type] % connection.dialect.identifier_preparer.quote(colname) ) else: t = Table("t", metadata, Column(colname, Integer)) if constraint_type == "uq": constraint = UniqueConstraint(t.c[colname]) elif constraint_type == "pk": constraint = PrimaryKeyConstraint(t.c[colname]) elif constraint_type == "ix": constraint = Index("some_index", t.c[colname]) else: assert False t.append_constraint(constraint) t.create(connection) if constraint_type in ( "uq", "uq_inline", "uq_inline_tab_before", "uq_inline_tab_within", ): const = inspect(connection).get_unique_constraints("t")[0] eq_(const["column_names"], [expected]) elif constraint_type == "pk": const = inspect(connection).get_pk_constraint("t") eq_(const["constrained_columns"], [expected]) elif constraint_type == "ix": const = inspect(connection).get_indexes("t")[0] eq_(const["column_names"], [expected]) else: assert False def test_check_constraint_oneline(self): inspector = inspect(testing.db) eq_( inspector.get_check_constraints("oneline"), [ {"sqltext": "field>0", "name": None}, ], ) def test_check_constraint_oneline_nested(self): inspector = inspect(testing.db) eq_( inspector.get_check_constraints("oneline_nested"), [ { "sqltext": "(field>0 and field<22) " "or (field>99 and field<1010)", "name": None, }, ], ) def test_check_constraint_oneline_2constraints(self): inspector = inspect(testing.db) eq_( inspector.get_check_constraints("oneline_2constraints"), [ { "sqltext": "(field>0 and field<22) " "or (field>99 and field<1010)", "name": "chname", }, ], ) def test_check_constraint_oneline_nameCHECK(self): inspector = inspect(testing.db) eq_( inspector.get_check_constraints("oneline_nameCHECK"), [], ) def test_check_constraint_oneline_nameCONSTRAINT(self): inspector = inspect(testing.db) eq_( inspector.get_check_constraints("oneline_nameCONSTRAINT"), [ {"sqltext": "field IN (1, 0, -1)", "name": None}, ], ) def test_check_constraint_twochecks_oneline(self): inspector = inspect(testing.db) eq_( inspector.get_check_constraints("twochecks_oneline"), [ {"sqltext": "field>1", "name": None}, {"sqltext": "field<9", "name": None}, ], ) def test_check_constraint_quote_styles(self): """Test all SQLite identifier quote styles for constraint names. SQLite supports 4 quote styles: double quotes, single quotes, brackets, and backticks (for compatibility with other databases). """ inspector = inspect(testing.db) eq_( inspector.get_check_constraints("quote_styles"), [ {"sqltext": "field >= 10", "name": "backtick_quoted"}, {"sqltext": "field != 50", "name": "bracket_quoted"}, {"sqltext": "field > 0", "name": "double_quoted"}, {"sqltext": "field < 100", "name": "single_quoted"}, ], ) def test_check_constraint_parens_in_strings(self): """Test CHECK constraints with parentheses inside string literals. Parentheses inside quoted strings should not be counted when matching balanced parentheses in the constraint expression. These test cases have unbalanced parens if strings are not handled, and include escaped quotes (SQLite uses '' to escape, not backslash). """ inspector = inspect(testing.db) eq_( inspector.get_check_constraints("parens_in_strings"), [ {"sqltext": "field != '('", "name": None}, {"sqltext": "field != ')'", "name": None}, {"sqltext": "field NOT LIKE '%('", "name": None}, {"sqltext": "field IN (')', '(', 'test')", "name": None}, # Escaped quotes with parens {"sqltext": "field != 'it''s (not) valid'", "name": None}, {"sqltext": 'field != "say ""(hello)"" "', "name": None}, { "sqltext": "field NOT IN ('()', 'a''b''c', ')')", "name": None, }, # Complex nested cases {"sqltext": "field != '((' OR field = ')))'", "name": None}, { "sqltext": 'field LIKE "%))(%" OR field LIKE "%)(%"', "name": None, }, ], )
ConstraintReflectionTest
python
huggingface__transformers
examples/pytorch/question-answering/trainer_qa.py
{ "start": 945, "end": 5678 }
class ____(Trainer): def __init__(self, *args, eval_examples=None, post_process_function=None, **kwargs): super().__init__(*args, **kwargs) self.eval_examples = eval_examples self.post_process_function = post_process_function def evaluate(self, eval_dataset=None, eval_examples=None, ignore_keys=None, metric_key_prefix: str = "eval"): eval_dataset = self.eval_dataset if eval_dataset is None else eval_dataset eval_dataloader = self.get_eval_dataloader(eval_dataset) eval_examples = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. compute_metrics = self.compute_metrics self.compute_metrics = None start_time = time.time() try: output = self.evaluation_loop( eval_dataloader, description="Evaluation", # No point gathering the predictions if there are no metrics, otherwise we defer to # self.args.prediction_loss_only prediction_loss_only=True if compute_metrics is None else None, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix, ) finally: self.compute_metrics = compute_metrics total_batch_size = self.args.eval_batch_size * self.args.world_size output.metrics.update( speed_metrics( metric_key_prefix, start_time, num_samples=output.num_samples, num_steps=math.ceil(output.num_samples / total_batch_size), ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default eval_preds = self.post_process_function(eval_examples, eval_dataset, output.predictions) metrics = self.compute_metrics(eval_preds) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f"{metric_key_prefix}_"): metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key) metrics.update(output.metrics) else: metrics = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(metrics) if self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, metrics) return metrics def predict(self, predict_dataset, predict_examples, ignore_keys=None, metric_key_prefix: str = "test"): predict_dataloader = self.get_test_dataloader(predict_dataset) # Temporarily disable metric computation, we will do it in the loop here. compute_metrics = self.compute_metrics self.compute_metrics = None start_time = time.time() try: output = self.evaluation_loop( predict_dataloader, description="Prediction", # No point gathering the predictions if there are no metrics, otherwise we defer to # self.args.prediction_loss_only prediction_loss_only=True if compute_metrics is None else None, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix, ) finally: self.compute_metrics = compute_metrics total_batch_size = self.args.eval_batch_size * self.args.world_size output.metrics.update( speed_metrics( metric_key_prefix, start_time, num_samples=output.num_samples, num_steps=math.ceil(output.num_samples / total_batch_size), ) ) if self.post_process_function is None or self.compute_metrics is None: return output predictions = self.post_process_function(predict_examples, predict_dataset, output.predictions, "predict") metrics = self.compute_metrics(predictions) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f"{metric_key_prefix}_"): metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key) metrics.update(output.metrics) return PredictionOutput(predictions=predictions.predictions, label_ids=predictions.label_ids, metrics=metrics)
QuestionAnsweringTrainer
python
allegroai__clearml
clearml/backend_api/services/v2_23/projects.py
{ "start": 83256, "end": 86757 }
class ____(Request): """ Get a list of all hyper parameter sections and names used in tasks within the given project. :param project: Project ID :type project: str :param page: Page number :type page: int :param page_size: Page size :type page_size: int :param include_subprojects: If set to 'true' and the project field is set then the result includes hyper parameters from the subproject tasks :type include_subprojects: bool """ _service = "projects" _action = "get_hyper_parameters" _version = "2.23" _schema = { "definitions": {}, "properties": { "include_subprojects": { "default": True, "description": "If set to 'true' and the project field is set then the result includes hyper parameters from the subproject tasks", "type": "boolean", }, "page": {"default": 0, "description": "Page number", "type": "integer"}, "page_size": { "default": 500, "description": "Page size", "type": "integer", }, "project": {"description": "Project ID", "type": "string"}, }, "required": ["project"], "type": "object", } def __init__( self, project: str, page: Optional[int] = 0, page_size: Optional[int] = 500, include_subprojects: Optional[bool] = True, **kwargs: Any ) -> None: super(GetHyperParametersRequest, self).__init__(**kwargs) self.project = project self.page = page self.page_size = page_size self.include_subprojects = include_subprojects @schema_property("project") def project(self) -> str: return self._property_project @project.setter def project(self, value: str) -> None: if value is None: self._property_project = None return self.assert_isinstance(value, "project", six.string_types) self._property_project = value @schema_property("page") def page(self) -> Optional[int]: return self._property_page @page.setter def page(self, value: Optional[int]) -> None: if value is None: self._property_page = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "page", six.integer_types) self._property_page = value @schema_property("page_size") def page_size(self) -> Optional[int]: return self._property_page_size @page_size.setter def page_size(self, value: Optional[int]) -> None: if value is None: self._property_page_size = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "page_size", six.integer_types) self._property_page_size = value @schema_property("include_subprojects") def include_subprojects(self) -> Optional[bool]: return self._property_include_subprojects @include_subprojects.setter def include_subprojects(self, value: Optional[bool]) -> None: if value is None: self._property_include_subprojects = None return self.assert_isinstance(value, "include_subprojects", (bool,)) self._property_include_subprojects = value
GetHyperParametersRequest
python
django__django
tests/urlpatterns_reverse/tests.py
{ "start": 58624, "end": 59240 }
class ____(SimpleTestCase): """Tests for handler404 and handler500 if ROOT_URLCONF is None""" def test_no_handler_exception(self): msg = ( "The included URLconf 'None' does not appear to have any patterns " "in it. If you see the 'urlpatterns' variable with valid patterns " "in the file then the issue is probably caused by a circular " "import." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/test/me/") @override_settings(ROOT_URLCONF="urlpatterns_reverse.namespace_urls")
NoRootUrlConfTests
python
great-expectations__great_expectations
tests/expectations/test_conditions.py
{ "start": 19395, "end": 20071 }
class ____: """Tests for round-trip serialization and deserialization.""" def test_and_condition_round_trip(self): """Test round-trip serialization/deserialization preserves condition structure.""" col = Column("quantity") original = AndCondition( conditions=[ ComparisonCondition(column=col, operator=Operator.GREATER_THAN, parameter=0), ComparisonCondition(column=col, operator=Operator.LESS_THAN, parameter=10), ] ) serialized = original.dict() deserialized = deserialize_row_condition(serialized) assert deserialized == original
TestConditionRoundTrip
python
apache__thrift
lib/py/src/protocol/TJSONProtocol.py
{ "start": 18855, "end": 18984 }
class ____(TProtocolFactory): def getProtocol(self, trans): return TSimpleJSONProtocol(trans)
TSimpleJSONProtocolFactory
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/operators/dep_operators.py
{ "start": 3441, "end": 7552 }
class ____(BuiltinAutomationCondition[T_EntityKey]): operand: AutomationCondition # Should be AssetSelection, but this causes circular reference issues allow_selection: Optional[Any] = None ignore_selection: Optional[Any] = None @property @abstractmethod def base_name(self) -> str: ... @property def name(self) -> str: name = self.base_name props = [] if self.allow_selection is not None: props.append(f"allow_selection={self.allow_selection}") if self.ignore_selection is not None: props.append(f"ignore_selection={self.ignore_selection}") if props: name += f"({','.join(props)})" return name @property def children(self) -> Sequence[AutomationCondition]: return [self.operand] @property def requires_cursor(self) -> bool: return False def get_node_unique_id( self, *, parent_unique_id: Optional[str], index: Optional[int], target_key: Optional[EntityKey], ) -> str: """Ignore allow_selection / ignore_selection for the cursor hash.""" parts = [str(parent_unique_id), str(index), self.base_name] return non_secure_md5_hash_str("".join(parts).encode()) def get_backcompat_node_unique_ids( self, *, parent_unique_id: Optional[str] = None, index: Optional[int] = None, target_key: Optional[EntityKey] = None, ) -> Sequence[str]: # backcompat for previous cursors where the allow/ignore selection influenced the hash return [ super().get_node_unique_id( parent_unique_id=parent_unique_id, index=index, target_key=target_key ) ] @public def allow(self, selection: "AssetSelection") -> "DepsAutomationCondition": """Returns a copy of this condition that will only consider dependencies within the provided AssetSelection. """ from dagster._core.definitions.asset_selection import AssetSelection check.inst_param(selection, "selection", AssetSelection) allow_selection = ( selection if self.allow_selection is None else selection | self.allow_selection ) return copy(self, allow_selection=allow_selection) @public def ignore(self, selection: "AssetSelection") -> "DepsAutomationCondition": """Returns a copy of this condition that will ignore dependencies within the provided AssetSelection. """ from dagster._core.definitions.asset_selection import AssetSelection check.inst_param(selection, "selection", AssetSelection) ignore_selection = ( selection if self.ignore_selection is None else selection | self.ignore_selection ) return copy(self, ignore_selection=ignore_selection) def _get_dep_keys( self, key: T_EntityKey, asset_graph: BaseAssetGraph[BaseAssetNode] ) -> AbstractSet[AssetKey]: dep_keys = asset_graph.get(key).parent_entity_keys if self.allow_selection is not None: dep_keys &= self.allow_selection.resolve(asset_graph, allow_missing=True) if self.ignore_selection is not None: dep_keys -= self.ignore_selection.resolve(asset_graph, allow_missing=True) return dep_keys @public def replace( self, old: Union[AutomationCondition, str], new: T_AutomationCondition ) -> Union[Self, T_AutomationCondition]: """Replaces all instances of ``old`` across any sub-conditions with ``new``. If ``old`` is a string, then conditions with a label or name matching that string will be replaced. Args: old (Union[AutomationCondition, str]): The condition to replace. new (AutomationCondition): The condition to replace with. """ return ( new if old in [self, self.name, self.get_label()] else copy(self, operand=self.operand.replace(old, new)) ) @whitelist_for_serdes
DepsAutomationCondition
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/runs_feed.py
{ "start": 580, "end": 1241 }
class ____(graphene.Interface): id = graphene.NonNull(graphene.ID) runStatus = graphene.Field("dagster_graphql.schema.pipelines.pipeline.GrapheneRunStatus") creationTime = graphene.NonNull(graphene.Float) startTime = graphene.Float() endTime = graphene.Float() tags = non_null_list("dagster_graphql.schema.tags.GraphenePipelineTag") jobName = graphene.String() assetSelection = graphene.List(graphene.NonNull(GrapheneAssetKey)) assetCheckSelection = graphene.List( graphene.NonNull("dagster_graphql.schema.entity_key.GrapheneAssetCheckHandle") ) class Meta: name = "RunsFeedEntry"
GrapheneRunsFeedEntry
python
sqlalchemy__sqlalchemy
test/orm/test_assorted_eager.py
{ "start": 29643, "end": 33474 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "prj", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("created", sa.DateTime), Column("title", sa.String(100)), ) Table( "task", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column( "status_id", Integer, ForeignKey("task_status.id"), nullable=False, ), Column("title", sa.String(100)), Column( "task_type_id", Integer, ForeignKey("task_type.id"), nullable=False, ), Column("prj_id", Integer, ForeignKey("prj.id"), nullable=False), ) Table( "task_status", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), ) Table( "task_type", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), ) Table( "msg", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("posted", sa.DateTime, index=True), Column("type_id", Integer, ForeignKey("msg_type.id")), Column("task_id", Integer, ForeignKey("task.id")), ) Table( "msg_type", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", sa.String(20)), Column("display_name", sa.String(20)), ) @classmethod def fixtures(cls): return dict( prj=(("id",), (1,)), task_status=(("id",), (1,)), task_type=(("id",), (1,)), task=( ("title", "task_type_id", "status_id", "prj_id"), ("task 1", 1, 1, 1), ), ) @classmethod def setup_classes(cls): class Task_Type(cls.Comparable): pass class Joined(cls.Comparable): pass def test_nested_joins(self): task, Task_Type, Joined, task_type, msg = ( self.tables.task, self.classes.Task_Type, self.classes.Joined, self.tables.task_type, self.tables.msg, ) # this is testing some subtle column resolution stuff, # concerning corresponding_column() being extremely accurate # as well as how mapper sets up its column properties self.mapper_registry.map_imperatively(Task_Type, task_type) j = sa.outerjoin(task, msg, task.c.id == msg.c.task_id) jj = ( sa.select( task.c.id.label("task_id"), sa.func.count(msg.c.id).label("props_cnt"), ) .select_from(j) .group_by(task.c.id) .alias("prop_c_s") ) jjj = sa.join(task, jj, task.c.id == jj.c.task_id) self.mapper_registry.map_imperatively( Joined, jjj, properties=dict(type=relationship(Task_Type, lazy="joined")), ) session = fixture_session() eq_( session.query(Joined) .order_by(Joined.id) .limit(10) .offset(0) .one(), Joined(id=1, title="task 1", props_cnt=0), )
EagerTest8
python
FactoryBoy__factory_boy
factory/declarations.py
{ "start": 3222, "end": 3728 }
class ____(BaseDeclaration): """Specific BaseDeclaration computed using a lambda. Attributes: function (function): a function, expecting the current LazyStub and returning the computed value. """ def __init__(self, function): super().__init__() self.function = function def evaluate(self, instance, step, extra): logger.debug("LazyAttribute: Evaluating %r on %r", self.function, instance) return self.function(instance)
LazyAttribute
python
getlogbook__logbook
src/logbook/handlers.py
{ "start": 60145, "end": 62969 }
class ____(Handler, StringFormatterHandlerMixin): """A handler that sends to the NT event log system.""" dllname = None default_format_string = NTLOG_FORMAT_STRING def __init__( self, application_name, log_type="Application", level=NOTSET, format_string=None, filter=None, bubble=False, ): Handler.__init__(self, level, filter, bubble) StringFormatterHandlerMixin.__init__(self, format_string) if os.name != "nt": raise RuntimeError( "NTLogEventLogHandler requires a Windows operating system." ) try: import win32evtlog import win32evtlogutil except ImportError: raise RuntimeError( "The pywin32 library is required for the NTEventLogHandler." ) self.application_name = application_name self._welu = win32evtlogutil dllname = self.dllname if not dllname: dllname = os.path.join( os.path.dirname(self._welu.__file__), "../win32service.pyd" ) self.log_type = log_type self._welu.AddSourceToRegistry(self.application_name, dllname, log_type) self._default_type = win32evtlog.EVENTLOG_INFORMATION_TYPE self._type_map = { DEBUG: win32evtlog.EVENTLOG_INFORMATION_TYPE, INFO: win32evtlog.EVENTLOG_INFORMATION_TYPE, NOTICE: win32evtlog.EVENTLOG_INFORMATION_TYPE, WARNING: win32evtlog.EVENTLOG_WARNING_TYPE, ERROR: win32evtlog.EVENTLOG_ERROR_TYPE, CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, } def unregister_logger(self): """Removes the application binding from the registry. If you call this, the log viewer will no longer be able to provide any information about the message. """ self._welu.RemoveSourceFromRegistry(self.application_name, self.log_type) def get_event_type(self, record): return self._type_map.get(record.level, self._default_type) def get_event_category(self, record): """Returns the event category for the record. Override this if you want to specify your own categories. This version returns 0. """ return 0 def get_message_id(self, record): """Returns the message ID (EventID) for the record. Override this if you want to specify your own ID. This version returns 1. """ return 1 def emit(self, record): id = self.get_message_id(record) cat = self.get_event_category(record) type = self.get_event_type(record) self._welu.ReportEvent( self.application_name, id, cat, type, [self.format(record)] )
NTEventLogHandler
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 57933, "end": 58272 }
class ____(CBaseTypeNode): # base_type CBaseTypeNode # declarator CDeclaratorNode child_attrs = ["base_type", "declarator"] def analyse(self, env, could_be_name=False): base = self.base_type.analyse(env, could_be_name) _, type = self.declarator.analyse(base, env) return type
CComplexBaseTypeNode
python
pytorch__pytorch
benchmarks/gpt_fast/mixtral_moe_model.py
{ "start": 8233, "end": 9179 }
class ____(nn.Module): def __init__(self, config) -> None: super().__init__() self.gate = nn.Linear(config.dim, config.num_experts, bias=False) self.cond_ffn = ConditionalFeedForward(config) self.dim = config.dim self.num_activated_experts = config.num_activated_experts def forward(self, x: Tensor) -> Tensor: x = x.view(-1, self.dim) # T = num_tokens, E = num_experts, D = hidden dim, A = activated experts # x: [T, D] scores = self.gate(x) # [T, E] expert_weights = F.softmax(scores, dim=-1) expert_weights, expert_indices = torch.topk( expert_weights, self.num_activated_experts, dim=-1 ) # [T, A], [T, A] expert_weights /= expert_weights.sum(dim=-1, keepdim=True) # [T, A] expert_outs = self.cond_ffn(x, expert_indices) return torch.einsum("tai,ta -> ti", expert_outs, expert_weights)
MOEFeedForward
python
scipy__scipy
benchmarks/benchmarks/fft_basic.py
{ "start": 3567, "end": 4531 }
class ____(Benchmark): params = [ [75, 100, 135, 256, 313, 512, 675, 1024, 2025, 2048], ['I', 'II', 'III', 'IV'], ['scipy.fftpack', 'scipy.fft'] ] param_names = ['size', 'type', 'module'] def setup(self, size, type, module): module = get_module(module) self.dct = getattr(module, 'dct') self.dst = getattr(module, 'dst') self.type = {'I':1, 'II':2, 'III':3, 'IV':4}[type] # The "logical" transform size should be smooth, which for dct/dst # type 1 is offset by -1/+1 respectively if self.type == 1: size += 1 self.x = random([size]).astype(double) if self.type == 1: self.x_dst = self.x[:-2].copy() def time_dct(self, size, type, module): self.dct(self.x, self.type) def time_dst(self, size, type, module): x = self.x if self.type != 1 else self.x_dst self.dst(x, self.type)
RealTransforms1D
python
wandb__wandb
wandb/vendor/pygments/lexers/textfmts.py
{ "start": 2817, "end": 3716 }
class ____(RegexLexer): """ Lexer for Gettext catalog files. .. versionadded:: 0.9 """ name = 'Gettext Catalog' aliases = ['pot', 'po'] filenames = ['*.pot', '*.po'] mimetypes = ['application/x-gettext', 'text/x-gettext', 'text/gettext'] tokens = { 'root': [ (r'^#,\s.*?$', Keyword.Type), (r'^#:\s.*?$', Keyword.Declaration), # (r'^#$', Comment), (r'^(#|#\.\s|#\|\s|#~\s|#\s).*$', Comment.Single), (r'^(")([A-Za-z-]+:)(.*")$', bygroups(String, Name.Property, String)), (r'^".*"$', String), (r'^(msgid|msgid_plural|msgstr|msgctxt)(\s+)(".*")$', bygroups(Name.Variable, Text, String)), (r'^(msgstr\[)(\d)(\])(\s+)(".*")$', bygroups(Name.Variable, Number.Integer, Name.Variable, Text, String)), ] }
GettextLexer
python
scipy__scipy
scipy/sparse/_coo.py
{ "start": 896, "end": 66794 }
class ____(_data_matrix, _minmax_mixin): _format = 'coo' _allow_nd = range(1, 65) def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None): _data_matrix.__init__(self, arg1, maxprint=maxprint) if not copy: copy = copy_if_needed if isinstance(arg1, tuple): if isshape(arg1, allow_nd=self._allow_nd): self._shape = check_shape(arg1, allow_nd=self._allow_nd) idx_dtype = self._get_index_dtype(maxval=max(self._shape)) data_dtype = getdtype(dtype, default=float) self.coords = tuple(np.array([], dtype=idx_dtype) for _ in range(len(self._shape))) self.data = np.array([], dtype=data_dtype) self.has_canonical_format = True else: try: obj, coords = arg1 except (TypeError, ValueError) as e: raise TypeError('invalid input format') from e if shape is None: if any(len(idx) == 0 for idx in coords): raise ValueError('cannot infer dimensions from zero ' 'sized index arrays') shape = tuple(operator.index(np.max(idx)) + 1 for idx in coords) self._shape = check_shape(shape, allow_nd=self._allow_nd) idx_dtype = self._get_index_dtype(coords, maxval=max(self.shape), check_contents=True) self.coords = tuple(np.array(idx, copy=copy, dtype=idx_dtype) for idx in coords) self.data = getdata(obj, copy=copy, dtype=dtype) self.has_canonical_format = False else: if issparse(arg1): if arg1.format == self.format and copy: self.coords = tuple(idx.copy() for idx in arg1.coords) self.data = arg1.data.astype(getdtype(dtype, arg1)) # copy=True self._shape = check_shape(arg1.shape, allow_nd=self._allow_nd) self.has_canonical_format = arg1.has_canonical_format else: coo = arg1.tocoo(copy=copy) self.coords = tuple(coo.coords) self.data = coo.data.astype(getdtype(dtype, coo), copy=False) self._shape = check_shape(coo.shape, allow_nd=self._allow_nd) self.has_canonical_format = False else: # dense argument M = np.asarray(arg1) if not isinstance(self, sparray): M = np.atleast_2d(M) if M.ndim != 2: raise TypeError(f'expected 2D array or matrix, not {M.ndim}D') self._shape = check_shape(M.shape, allow_nd=self._allow_nd) if shape is not None: if check_shape(shape, allow_nd=self._allow_nd) != self._shape: message = f'inconsistent shapes: {shape} != {self._shape}' raise ValueError(message) index_dtype = self._get_index_dtype(maxval=max(self._shape)) coords = M.nonzero() self.coords = tuple(idx.astype(index_dtype, copy=False) for idx in coords) self.data = getdata(M[coords], copy=copy, dtype=dtype) self.has_canonical_format = True if len(self._shape) > 2: self.coords = tuple(idx.astype(np.int64, copy=False) for idx in self.coords) self._check() @property def row(self): if self.ndim > 1: return self.coords[-2] result = np.zeros_like(self.col) result.setflags(write=False) return result @row.setter def row(self, new_row): if self.ndim < 2: raise ValueError('cannot set row attribute of a 1-dimensional sparse array') new_row = np.asarray(new_row, dtype=self.coords[-2].dtype) self.coords = self.coords[:-2] + (new_row,) + self.coords[-1:] @property def col(self): return self.coords[-1] @col.setter def col(self, new_col): new_col = np.asarray(new_col, dtype=self.coords[-1].dtype) self.coords = self.coords[:-1] + (new_col,) def reshape(self, *args, **kwargs): shape = check_shape(args, self.shape, allow_nd=self._allow_nd) order, copy = check_reshape_kwargs(kwargs) # Return early if reshape is not required if shape == self.shape: if copy: return self.copy() else: return self # When reducing the number of dimensions, we need to be careful about # index overflow. This is why we can't simply call # `np.ravel_multi_index()` followed by `np.unravel_index()` here. flat_coords = _ravel_coords(self.coords, self.shape, order=order) if len(shape) == 2: if order == 'C': new_coords = divmod(flat_coords, shape[1]) else: new_coords = divmod(flat_coords, shape[0])[::-1] else: new_coords = np.unravel_index(flat_coords, shape, order=order) idx_dtype = self._get_index_dtype(self.coords, maxval=max(shape)) new_coords = tuple(np.asarray(co, dtype=idx_dtype) for co in new_coords) # Handle copy here rather than passing on to the constructor so that no # copy will be made of `new_coords` regardless. if copy: new_data = self.data.copy() else: new_data = self.data return self.__class__((new_data, new_coords), shape=shape, copy=False) reshape.__doc__ = _spbase.reshape.__doc__ def _getnnz(self, axis=None): if axis is None or (axis == 0 and self.ndim == 1): nnz = len(self.data) if any(len(idx) != nnz for idx in self.coords): raise ValueError('all index and data arrays must have the ' 'same length') if self.data.ndim != 1 or any(idx.ndim != 1 for idx in self.coords): raise ValueError('coordinates and data arrays must be 1-D') return int(nnz) if axis < 0: axis += self.ndim if axis >= self.ndim: raise ValueError('axis out of bounds') return np.bincount(downcast_intp_index(self.coords[1 - axis]), minlength=self.shape[1 - axis]) _getnnz.__doc__ = _spbase._getnnz.__doc__ def count_nonzero(self, axis=None): self.sum_duplicates() if axis is None: return np.count_nonzero(self.data) if axis < 0: axis += self.ndim if axis < 0 or axis >= self.ndim: raise ValueError('axis out of bounds') mask = self.data != 0 coord = self.coords[1 - axis][mask] return np.bincount(downcast_intp_index(coord), minlength=self.shape[1 - axis]) count_nonzero.__doc__ = _spbase.count_nonzero.__doc__ def _check(self): """ Checks data structure for consistency """ if self.ndim != len(self.coords): raise ValueError('mismatching number of index arrays for shape; ' f'got {len(self.coords)}, expected {self.ndim}') # index arrays should have integer data types for i, idx in enumerate(self.coords): if idx.dtype.kind != 'i': warn(f'index array {i} has non-integer dtype ({idx.dtype.name})', stacklevel=3) idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.shape)) self.coords = tuple(np.asarray(idx, dtype=idx_dtype) for idx in self.coords) self.data = to_native(self.data) if self.nnz > 0: for i, idx in enumerate(self.coords): if idx.max() >= self.shape[i]: raise ValueError(f'axis {i} index {idx.max()} exceeds ' f'matrix dimension {self.shape[i]}') if idx.min() < 0: raise ValueError(f'negative axis {i} index: {idx.min()}') def transpose(self, axes=None, copy=False): if axes is None: axes = range(self.ndim)[::-1] elif isinstance(self, sparray): if not hasattr(axes, "__len__") or len(axes) != self.ndim: raise ValueError("axes don't match matrix dimensions") if len(set(axes)) != self.ndim: raise ValueError("repeated axis in transpose") elif axes != (1, 0): raise ValueError("Sparse matrices do not support an 'axes' " "parameter because swapping dimensions is the " "only logical permutation.") permuted_shape = tuple(self._shape[i] for i in axes) permuted_coords = tuple(self.coords[i] for i in axes) return self.__class__((self.data, permuted_coords), shape=permuted_shape, copy=copy) transpose.__doc__ = _spbase.transpose.__doc__ def resize(self, *shape) -> None: shape = check_shape(shape, allow_nd=self._allow_nd) if self.ndim > 2: raise ValueError("only 1-D or 2-D input accepted") if len(shape) > 2: raise ValueError("shape argument must be 1-D or 2-D") # Check for added dimensions. if len(shape) > self.ndim: flat_coords = _ravel_coords(self.coords, self.shape) max_size = math.prod(shape) self.coords = np.unravel_index(flat_coords[:max_size], shape) self.data = self.data[:max_size] self._shape = shape return # Check for removed dimensions. if len(shape) < self.ndim: tmp_shape = ( self._shape[:len(shape) - 1] # Original shape without last axis + (-1,) # Last axis is used to flatten the array + (1,) * (self.ndim - len(shape)) # Pad with ones ) tmp = self.reshape(tmp_shape) self.coords = tmp.coords[:len(shape)] self._shape = tmp.shape[:len(shape)] # Handle truncation of existing dimensions. is_truncating = any(old > new for old, new in zip(self.shape, shape)) if is_truncating: mask = np.logical_and.reduce([ idx < size for idx, size in zip(self.coords, shape) ]) if not mask.all(): self.coords = tuple(idx[mask] for idx in self.coords) self.data = self.data[mask] self._shape = shape resize.__doc__ = _spbase.resize.__doc__ def toarray(self, order=None, out=None): B = self._process_toarray_args(order, out) fortran = int(B.flags.f_contiguous) if not fortran and not B.flags.c_contiguous: raise ValueError("Output array must be C or F contiguous") # This handles both 0D and 1D cases correctly regardless of the # original shape. if self.ndim == 1: coo_todense_nd(np.array([1]), self.nnz, self.ndim, self.coords[0], self.data, B.ravel('A'), fortran) elif self.ndim == 2: M, N = self.shape coo_todense(M, N, self.nnz, self.row, self.col, self.data, B.ravel('A'), fortran) else: # dim>2 if fortran: strides = np.append(1, np.cumprod(self.shape[:-1])) else: strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1) coords = np.concatenate(self.coords) coo_todense_nd(strides, self.nnz, self.ndim, coords, self.data, B.ravel('A'), fortran) # Note: reshape() doesn't copy here, but does return a new array (view). return B.reshape(self.shape) toarray.__doc__ = _spbase.toarray.__doc__ def tocsc(self, copy=False): """Convert this array/matrix to Compressed Sparse Column format Duplicate entries will be summed together. Examples -------- >>> from numpy import array >>> from scipy.sparse import coo_array >>> row = array([0, 0, 1, 3, 1, 0, 0]) >>> col = array([0, 2, 1, 3, 1, 0, 0]) >>> data = array([1, 1, 1, 1, 1, 1, 1]) >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsc() >>> A.toarray() array([[3, 0, 1, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]) """ if self.ndim != 2: raise ValueError(f'Cannot convert. CSC format must be 2D. Got {self.ndim}D') if self.nnz == 0: return self._csc_container(self.shape, dtype=self.dtype) else: from ._csc import csc_array indptr, indices, data, shape = self._coo_to_compressed(csc_array._swap) x = self._csc_container((data, indices, indptr), shape=shape) if not self.has_canonical_format: x.sum_duplicates() return x def tocsr(self, copy=False): """Convert this array/matrix to Compressed Sparse Row format Duplicate entries will be summed together. Examples -------- >>> from numpy import array >>> from scipy.sparse import coo_array >>> row = array([0, 0, 1, 3, 1, 0, 0]) >>> col = array([0, 2, 1, 3, 1, 0, 0]) >>> data = array([1, 1, 1, 1, 1, 1, 1]) >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsr() >>> A.toarray() array([[3, 0, 1, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]) """ if self.ndim > 2: raise ValueError(f'Cannot convert. CSR must be 1D or 2D. Got {self.ndim}D') if self.nnz == 0: return self._csr_container(self.shape, dtype=self.dtype) else: from ._csr import csr_array arrays = self._coo_to_compressed(csr_array._swap, copy=copy) indptr, indices, data, shape = arrays x = self._csr_container((data, indices, indptr), shape=self.shape) if not self.has_canonical_format: x.sum_duplicates() return x def _coo_to_compressed(self, swap, copy=False): """convert (shape, coords, data) to (indptr, indices, data, shape)""" M, N = swap(self._shape_as_2d) # convert idx_dtype intc to int32 for pythran. # tested in scipy/optimize/tests/test__numdiff.py::test_group_columns idx_dtype = self._get_index_dtype(self.coords, maxval=max(self.nnz, N)) if self.ndim == 1: indices = self.coords[0].copy() if copy else self.coords[0] nnz = len(indices) indptr = np.array([0, nnz], dtype=idx_dtype) data = self.data.copy() if copy else self.data return indptr, indices, data, self.shape # ndim == 2 major, minor = swap(self.coords) nnz = len(major) major = major.astype(idx_dtype, copy=False) minor = minor.astype(idx_dtype, copy=False) indptr = np.empty(M + 1, dtype=idx_dtype) indices = np.empty_like(minor, dtype=idx_dtype) data = np.empty_like(self.data, dtype=self.dtype) coo_tocsr(M, N, nnz, major, minor, self.data, indptr, indices, data) return indptr, indices, data, self.shape def tocoo(self, copy=False): if copy: return self.copy() else: return self tocoo.__doc__ = _spbase.tocoo.__doc__ def todia(self, copy=False): if self.ndim != 2: raise ValueError(f'Cannot convert. DIA format must be 2D. Got {self.ndim}D') self.sum_duplicates() ks = self.col - self.row # the diagonal for each nonzero diags, diag_idx = np.unique(ks, return_inverse=True) if len(diags) > 100: # probably undesired, should todia() have a maxdiags parameter? warn(f"Constructing a DIA matrix with {len(diags)} diagonals " "is inefficient", SparseEfficiencyWarning, stacklevel=2) #initialize and fill in data array if self.data.size == 0: data = np.zeros((0, 0), dtype=self.dtype) else: data = np.zeros((len(diags), self.col.max()+1), dtype=self.dtype) data[diag_idx, self.col] = self.data return self._dia_container((data, diags), shape=self.shape) todia.__doc__ = _spbase.todia.__doc__ def todok(self, copy=False): if self.ndim > 2: raise ValueError(f'Cannot convert. DOK must be 1D or 2D. Got {self.ndim}D') self.sum_duplicates() dok = self._dok_container(self.shape, dtype=self.dtype) # ensure that 1d coordinates are not tuples if self.ndim == 1: coords = self.coords[0] else: coords = zip(*self.coords) dok._dict = dict(zip(coords, self.data)) return dok todok.__doc__ = _spbase.todok.__doc__ def diagonal(self, k=0): if self.ndim != 2: raise ValueError("diagonal requires two dimensions") rows, cols = self.shape if k <= -rows or k >= cols: return np.empty(0, dtype=self.data.dtype) diag = np.zeros(min(rows + min(k, 0), cols - max(k, 0)), dtype=self.dtype) diag_mask = (self.row + k) == self.col if self.has_canonical_format: row = self.row[diag_mask] data = self.data[diag_mask] else: inds = tuple(idx[diag_mask] for idx in self.coords) (row, _), data = self._sum_duplicates(inds, self.data[diag_mask]) diag[row + min(k, 0)] = data return diag diagonal.__doc__ = _data_matrix.diagonal.__doc__ def _setdiag(self, values, k): if self.ndim != 2: raise ValueError("setting a diagonal requires two dimensions") M, N = self.shape if values.ndim and not len(values): return idx_dtype = self.row.dtype # Determine which triples to keep and where to put the new ones. full_keep = self.col - self.row != k if k < 0: max_index = min(M+k, N) if values.ndim: max_index = min(max_index, len(values)) keep = np.logical_or(full_keep, self.col >= max_index) new_row = np.arange(-k, -k + max_index, dtype=idx_dtype) new_col = np.arange(max_index, dtype=idx_dtype) else: max_index = min(M, N-k) if values.ndim: max_index = min(max_index, len(values)) keep = np.logical_or(full_keep, self.row >= max_index) new_row = np.arange(max_index, dtype=idx_dtype) new_col = np.arange(k, k + max_index, dtype=idx_dtype) # Define the array of data consisting of the entries to be added. if values.ndim: new_data = values[:max_index] else: new_data = np.empty(max_index, dtype=self.dtype) new_data[:] = values # Update the internal structure. self.coords = (np.concatenate((self.row[keep], new_row)), np.concatenate((self.col[keep], new_col))) self.data = np.concatenate((self.data[keep], new_data)) self.has_canonical_format = False # needed by _data_matrix def _with_data(self, data, copy=True): """Returns a matrix with the same sparsity structure as self, but with different data. By default the index arrays are copied. """ if copy: coords = tuple(idx.copy() for idx in self.coords) else: coords = self.coords return self.__class__((data, coords), shape=self.shape, dtype=data.dtype) def __getitem__(self, key): index, new_shape, arr_int_pos, none_pos = _validate_indices( key, self.shape, self.format ) # handle int, slice and int-array indices index_mask = np.ones(len(self.data), dtype=np.bool_) slice_coords = [] arr_coords = [] arr_indices = [] for i, (idx, co) in enumerate(zip(index, self.coords)): if isinstance(idx, int): index_mask &= (co == idx) elif isinstance(idx, slice): if idx == slice(None): slice_coords.append(co) else: start, stop, step = idx.indices(self.shape[i]) if step != 1: if step < 0: in_range = (co <= start) & (co > stop) else: in_range = (co >= start) & (co < stop) new_ix, m = np.divmod(co - start, step) index_mask &= (m == 0) & in_range else: in_range = (co >= start) & (co < stop) new_ix = co - start index_mask &= in_range slice_coords.append(new_ix) else: # array arr_coords.append(co) arr_indices.append(idx) # shortcut for scalar output if new_shape == (): return self.data[index_mask].sum().astype(self.dtype, copy=False) new_coords = [co[index_mask] for co in slice_coords] new_data = self.data[index_mask] # handle array indices if arr_indices: arr_shape = arr_indices[0].shape # already broadcast in validate_indices # There are three dimensions required to check array indices against coords # Their lengths are described as: # a) number of indices that are arrays - arr_dim # b) number of coords to check - masked_nnz (already masked by slices) # c) size of the index arrays - arr_size # Note for this, integer indices are treated like slices, not like arrays. # # Goal: # Find new_coords and index positions that match across all arr_dim axes. # Approach: Track matches using bool array. Size: masked_nnz by arr_size. # True means all arr_indices match at that coord and index position. # Equate with broadcasting and check for all equal across (arr_dim) axis 0. # 1st array is "keyarr" (arr_dim by 1 by arr_size) from arr_indices. # 2nd array is "arr_coords" (arr_dim by masked_nnz by 1) from arr_coords. keyarr = np.array(arr_indices).reshape(len(arr_indices), 1, -1) arr_coords = np.array([co[index_mask] for co in arr_coords])[:, :, None] found = (keyarr == arr_coords).all(axis=0) arr_co, arr_ix = found.nonzero() new_data = new_data[arr_co] new_coords = [co[arr_co] for co in new_coords] new_arr_coords = list(np.unravel_index(arr_ix, shape=arr_shape)) # check for contiguous positions of array and int indices if len(arr_int_pos) == arr_int_pos[-1] - arr_int_pos[0] + 1: # Contiguous. Put all array index shape at pos of array indices pos = arr_int_pos[0] new_coords = new_coords[:pos] + new_arr_coords + new_coords[pos:] else: # Not contiguous. Put all array coords at front new_coords = new_arr_coords + new_coords if none_pos: if new_coords: coord_like = np.zeros_like(new_coords[0]) else: coord_like = np.zeros(len(new_data), dtype=self.coords[0].dtype) new_coords.insert(none_pos[0], coord_like) for i in none_pos[1:]: new_coords.insert(i, coord_like.copy()) return coo_array((new_data, new_coords), shape=new_shape, dtype=self.dtype) def __setitem__(self, key, x): # enact self[key] = x index, new_shape, arr_int_pos, none_pos = _validate_indices( key, self.shape, self.format ) # remove None's at beginning of index. Should not impact indexing coords # and will mistakenly align with x_coord columns if not removed. if none_pos: new_shape = list(new_shape) for j in none_pos[::-1]: new_shape.pop(j) new_shape = tuple(new_shape) # get coords and data from x if issparse(x): if 0 in x.shape: return # Nothing to set. x_data, x_coords = _get_sparse_data_and_coords(x, new_shape, self.dtype) else: x = np.asarray(x, dtype=self.dtype) if x.size == 0: return # Nothing to set. x_data, x_coords = _get_dense_data_and_coords(x, new_shape) # Approach: # Set indexed values to zero (drop from `self.coords` and `self.data`) # create new coords and data arrays for setting nonzeros # concatenate old (undropped) values with new coords and data old_data, old_coords = self._zero_many(index) if len(x_coords) == 1 and len(x_coords[0]) == 0: self.data, self.coords = old_data, old_coords # leave self.has_canonical_format unchanged return # To process array indices, need the x_coords for those axes # and need to ravel the array part of x_coords to build new_coords # Along the way, Find pos and shape of array-index portion of key. # arr_shape is None and pos = -1 when no arrays are used as indices. arr_shape = None pos = -1 if arr_int_pos: # Get arr_shape if any arrays are in the index. # Also ravel the corresponding x_coords. for idx in index: if not isinstance(idx, slice) and not isintlike(idx): arr_shape = idx.shape # Find x_coord pos of integer and array portion of index. # If contiguous put int and array axes at pos of those indices. # If not contiguous, put all int and array axes at pos=0. if len(arr_int_pos) == (arr_int_pos[-1] - arr_int_pos[0] + 1): pos = arr_int_pos[0] else: pos = 0 # compute the raveled coords of the array part of x_coords. # Used to build the new coords from the index arrays. x_arr_coo = x_coords[pos:pos + len(arr_shape)] # could use np.ravel_multi_index but _ravel_coords avoids overflow x_arr_coo_ravel = _ravel_coords(x_arr_coo, arr_shape) break # find map from x_coord slice axes to index axes x_ax = 0 x_axes = {} for i, idx in enumerate(index): if i == pos: x_ax += len(arr_shape) if isinstance(idx, slice): x_axes[i] = x_ax x_ax += 1 # Build new_coords and new_data new_coords = [None] * self.ndim new_nnz = len(x_data) for i, idx in enumerate(index): if isintlike(idx): new_coords[i] = (np.broadcast_to(idx, (new_nnz,))) continue elif isinstance(idx, slice): start, stop, step = idx.indices(self.shape[i]) new_coords[i] = (start + x_coords[x_axes[i]] * step) else: # array idx new_coords[i] = idx.ravel()[x_arr_coo_ravel] # seems like a copy is prudent when setting data in this array new_data = x_data.copy() # deduplicate entries created by multiple coords matching in the array index # NumPy does not specify which value is put into the spot (last one assigned) # so only one value should appear if we want to match NumPy. # If matching NumPy is not crucial, we could make dups a feature where # integer array indices with repeated indices creates duplicate values. # Not doing that here. We are just removing duplicates (keep 1st data found) new_coords = np.array(new_coords) _, ind = np.unique(new_coords, axis=1, return_index=True) # update values with stack of old and new data and coords. self.data = np.hstack([old_data, new_data[ind]]) self.coords = tuple(np.hstack(c) for c in zip(old_coords, new_coords[:, ind])) self.has_canonical_format = False def _zero_many(self, index): # handle int, slice and integer-array indices # index_mask accumulates a bool array of nonzeros that match index index_mask=np.ones(len(self.data), dtype=np.bool_) arr_coords = [] arr_indices = [] for i, (idx, co) in enumerate(zip(index, self.coords)): if isinstance(idx, int): index_mask &= (co == idx) elif isinstance(idx, slice) and idx != slice(None): start, stop, step = idx.indices(self.shape[i]) if step != 1: if step < 0: in_range = (co <= start) & (co > stop) else: in_range = (co >= start) & (co < stop) m = np.mod(co - start, step) index_mask &= (m == 0) & in_range else: in_range = (co >= start) & (co < stop) index_mask &= in_range elif isinstance(idx, slice) and idx == slice(None): # slice is full axis so no changes to index_mask pass else: # array arr_coords.append(co) arr_indices.append(idx) # match array indices with masked coords. See comments in __getitem__ if arr_indices: keyarr = np.array(arr_indices).reshape(len(arr_indices), 1, -1) arr_coords = np.array([co[index_mask] for co in arr_coords])[:, :, None] found = (keyarr == arr_coords).all(axis=0) arr_coo, _ = found.nonzero() arr_index_mask = np.zeros_like(index_mask) arr_index_mask[index_mask.nonzero()[0][arr_coo]] = True index_mask &= arr_index_mask # remove matching coords and data to set them to zero pruned_coords = [co[~index_mask] for co in self.coords] pruned_data = self.data[~index_mask] return pruned_data, pruned_coords def sum_duplicates(self) -> None: """Eliminate duplicate entries by adding them together This is an *in place* operation """ if self.has_canonical_format: return summed = self._sum_duplicates(self.coords, self.data) self.coords, self.data = summed self.has_canonical_format = True def _sum_duplicates(self, coords, data): # Assumes coords not in canonical format. if len(data) == 0: return coords, data # Sort coords w.r.t. rows, then cols. This corresponds to C-order, # which we rely on for argmin/argmax to return the first index in the # same way that numpy does (in the case of ties). order = np.lexsort(coords[::-1]) coords = tuple(idx[order] for idx in coords) data = data[order] unique_mask = np.logical_or.reduce([ idx[1:] != idx[:-1] for idx in coords ]) unique_mask = np.append(True, unique_mask) coords = tuple(idx[unique_mask] for idx in coords) unique_inds, = np.nonzero(unique_mask) data = np.add.reduceat(data, downcast_intp_index(unique_inds), dtype=self.dtype) return coords, data def eliminate_zeros(self): """Remove zero entries from the array/matrix This is an *in place* operation """ mask = self.data != 0 self.data = self.data[mask] self.coords = tuple(idx[mask] for idx in self.coords) ####################### # Arithmetic handlers # ####################### def _add_dense(self, other): if other.shape != self.shape: raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') dtype = upcast_char(self.dtype.char, other.dtype.char) result = np.array(other, dtype=dtype, copy=True) fortran = int(result.flags.f_contiguous) if self.ndim == 1: coo_todense_nd(np.array([1]), self.nnz, self.ndim, self.coords[0], self.data, result.ravel('A'), fortran) elif self.ndim == 2: M, N = self._shape_as_2d coo_todense(M, N, self.nnz, self.row, self.col, self.data, result.ravel('A'), fortran) else: if fortran: strides = np.append(1, np.cumprod(self.shape[:-1])) else: strides = np.append(np.cumprod(self.shape[1:][::-1])[::-1], 1) coords = np.concatenate(self.coords) coo_todense_nd(strides, self.nnz, self.ndim, coords, self.data, result.ravel('A'), fortran) return self._container(result, copy=False) def _add_sparse(self, other): if self.ndim < 3: return self.tocsr()._add_sparse(other) if other.shape != self.shape: raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') other = self.__class__(other) new_data = np.concatenate((self.data, other.data)) new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1)) A = self.__class__((new_data, new_coords), shape=self.shape) return A def _sub_sparse(self, other): if self.ndim < 3: return self.tocsr()._sub_sparse(other) if other.shape != self.shape: raise ValueError(f'Incompatible shapes ({self.shape} and {other.shape})') other = self.__class__(other) new_data = np.concatenate((self.data, -other.data)) new_coords = tuple(np.concatenate((self.coords, other.coords), axis=1)) A = coo_array((new_data, new_coords), shape=self.shape) return A def _matmul_vector(self, other): if self.ndim > 2: result = np.zeros(math.prod(self.shape[:-1]), dtype=upcast_char(self.dtype.char, other.dtype.char)) shape = np.array(self.shape) strides = np.append(np.cumprod(shape[:-1][::-1])[::-1][1:], 1) coords = np.concatenate(self.coords) coo_matvec_nd(self.nnz, len(self.shape), strides, coords, self.data, other, result) result = result.reshape(self.shape[:-1]) return result # self.ndim <= 2 result_shape = self.shape[0] if self.ndim > 1 else 1 result = np.zeros(result_shape, dtype=upcast_char(self.dtype.char, other.dtype.char)) if self.ndim == 2: col = self.col row = self.row elif self.ndim == 1: col = self.coords[0] row = np.zeros_like(col) else: raise NotImplementedError( f"coo_matvec not implemented for ndim={self.ndim}") coo_matvec(self.nnz, row, col, self.data, other, result) # Array semantics return a scalar here, not a single-element array. if isinstance(self, sparray) and result_shape == 1: return result[0] return result def _rmatmul_dispatch(self, other): if isscalarlike(other): return self._mul_scalar(other) else: # Don't use asarray unless we have to try: o_ndim = other.ndim except AttributeError: other = np.asarray(other) o_ndim = other.ndim perm = tuple(range(o_ndim)[:-2]) + tuple(range(o_ndim)[-2:][::-1]) tr = other.transpose(perm) s_ndim = self.ndim perm = tuple(range(s_ndim)[:-2]) + tuple(range(s_ndim)[-2:][::-1]) ret = self.transpose(perm)._matmul_dispatch(tr) if ret is NotImplemented: return NotImplemented if s_ndim == 1 or o_ndim == 1: perm = range(ret.ndim) else: perm = tuple(range(ret.ndim)[:-2]) + tuple(range(ret.ndim)[-2:][::-1]) return ret.transpose(perm) def _matmul_dispatch(self, other): if isscalarlike(other): return self.multiply(other) if not (issparse(other) or isdense(other)): # If it's a list or whatever, treat it like an array other_a = np.asanyarray(other) if other_a.ndim == 0 and other_a.dtype == np.object_: # Not interpretable as an array; return NotImplemented so that # other's __rmatmul__ can kick in if that's implemented. return NotImplemented # Allow custom sparse class indicated by attr sparse gh-6520 try: other.shape except AttributeError: other = other_a if self.ndim < 3 and other.ndim < 3: return _spbase._matmul_dispatch(self, other) N = self.shape[-1] err_prefix = "matmul: dimension mismatch with signature" if other.__class__ is np.ndarray: if other.shape == (N,): return self._matmul_vector(other) if other.shape == (N, 1): result = self._matmul_vector(other.ravel()) return result.reshape(*self.shape[:-1], 1) if other.ndim == 1: msg = f"{err_prefix} (n,k={N}),(k={other.shape[0]},)->(n,)" raise ValueError(msg) if other.shape[-2] == N: # check for batch dimensions compatibility batch_shape_A = self.shape[:-2] batch_shape_B = other.shape[:-2] if batch_shape_A != batch_shape_B: try: # This will raise an error if the shapes are not broadcastable np.broadcast_shapes(batch_shape_A, batch_shape_B) except ValueError: raise ValueError("Batch dimensions are not broadcastable") return self._matmul_multivector(other) else: raise ValueError( f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)" ) if isscalarlike(other): # scalar value return self._mul_scalar(other) if issparse(other): self_is_1d = self.ndim == 1 other_is_1d = other.ndim == 1 # reshape to 2-D if self or other is 1-D if self_is_1d: self = self.reshape(self._shape_as_2d) # prepend 1 to shape if other_is_1d: other = other.reshape((other.shape[0], 1)) # append 1 to shape # Check if the inner dimensions match for matrix multiplication if N != other.shape[-2]: raise ValueError( f"{err_prefix} (n,..,k={N}),(k={other.shape[-2]},..,m)->(n,..,m)" ) # If A or B has more than 2 dimensions, check for # batch dimensions compatibility if self.ndim > 2 or other.ndim > 2: batch_shape_A = self.shape[:-2] batch_shape_B = other.shape[:-2] if batch_shape_A != batch_shape_B: try: # This will raise an error if the shapes are not broadcastable np.broadcast_shapes(batch_shape_A, batch_shape_B) except ValueError: raise ValueError("Batch dimensions are not broadcastable") result = self._matmul_sparse(other) # reshape back if a or b were originally 1-D if self_is_1d: # if self was originally 1-D, reshape result accordingly result = result.reshape(tuple(result.shape[:-2]) + tuple(result.shape[-1:])) if other_is_1d: result = result.reshape(result.shape[:-1]) return result def _matmul_multivector(self, other): result_dtype = upcast_char(self.dtype.char, other.dtype.char) if self.ndim >= 3 or other.ndim >= 3: # if self has shape (N,), reshape to (1,N) if self.ndim == 1: result = self.reshape(1, self.shape[0])._matmul_multivector(other) return result.reshape(tuple(other.shape[:-2]) + tuple(other.shape[-1:])) broadcast_shape = np.broadcast_shapes(self.shape[:-2], other.shape[:-2]) self_shape = broadcast_shape + self.shape[-2:] other_shape = broadcast_shape + other.shape[-2:] self = self._broadcast_to(self_shape) other = np.broadcast_to(other, other_shape) result_shape = broadcast_shape + self.shape[-2:-1] + other.shape[-1:] result = np.zeros(result_shape, dtype=result_dtype) coo_matmat_dense_nd(self.nnz, len(self.shape), other.shape[-1], np.array(other_shape), np.array(result_shape), np.concatenate(self.coords), self.data, other.ravel('C'), result) return result if self.ndim == 2: result_shape = (self.shape[0], other.shape[1]) col = self.col row = self.row elif self.ndim == 1: result_shape = (other.shape[1],) col = self.coords[0] row = np.zeros_like(col) result = np.zeros(result_shape, dtype=result_dtype) coo_matmat_dense(self.nnz, other.shape[-1], row, col, self.data, other.ravel('C'), result) return result.view(type=type(other)) def dot(self, other): """Return the dot product of two arrays. Strictly speaking a dot product involves two vectors. But in the sense that an array with ndim >= 1 is a collection of vectors, the function computes the collection of dot products between each vector in the first array with each vector in the second array. The axis upon which the sum of products is performed is the last axis of the first array and the second to last axis of the second array. If the second array is 1-D, the last axis is used. Thus, if both arrays are 1-D, the inner product is returned. If both are 2-D, we have matrix multiplication. If `other` is 1-D, the sum product is taken along the last axis of each array. If `other` is N-D for N>=2, the sum product is over the last axis of the first array and the second-to-last axis of the second array. Parameters ---------- other : array_like (dense or sparse) Second array Returns ------- output : array (sparse or dense) The dot product of this array with `other`. It will be dense/sparse if `other` is dense/sparse. Examples -------- >>> import numpy as np >>> from scipy.sparse import coo_array >>> A = coo_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) >>> v = np.array([1, 0, -1]) >>> A.dot(v) array([ 1, -3, -1], dtype=int64) For 2-D arrays it is the matrix product: >>> A = coo_array([[1, 0], [0, 1]]) >>> B = coo_array([[4, 1], [2, 2]]) >>> A.dot(B).toarray() array([[4, 1], [2, 2]]) For 3-D arrays the shape extends unused axes by other unused axes. >>> A = coo_array(np.arange(3*4*5*6)).reshape((3,4,5,6)) >>> B = coo_array(np.arange(3*4*5*6)).reshape((5,4,6,3)) >>> A.dot(B).shape (3, 4, 5, 5, 4, 3) """ # handle non-array input: lists, ints, etc if not (issparse(other) or isdense(other) or isscalarlike(other)): # If it's a list or whatever, treat it like an array o_array = np.asanyarray(other) if o_array.ndim == 0 and o_array.dtype == np.object_: raise TypeError(f"dot argument not supported type: '{type(other)}'") try: other.shape except AttributeError: other = o_array # Handle scalar multiplication if isscalarlike(other): return self * other # other.shape[-2:][0] gets last index of 1d, next to last index of >1d if self.shape[-1] != other.shape[-2:][0]: raise ValueError(f"shapes {self.shape} and {other.shape}" " are not aligned for n-D dot") if self.ndim < 3 and other.ndim < 3: return self @ other if isdense(other): return self._dense_dot(other) return self._sparse_dot(other.tocoo()) def _sparse_dot(self, other): # already checked: at least one is >2d, neither scalar, both are coo # Ravel non-reduced axes coordinates self_2d, s_new_shape = _convert_to_2d(self, [self.ndim - 1]) other_2d, o_new_shape = _convert_to_2d(other, [max(0, other.ndim - 2)]) prod = self_2d @ other_2d.T # routes via 2-D CSR prod = prod.tocoo() # Combine the shapes of the non-contracted axes combined_shape = s_new_shape + o_new_shape # Unravel the 2D coordinates to get multi-dimensional coordinates coords = [] new_shapes = (s_new_shape, o_new_shape) if s_new_shape else (o_new_shape,) for c, s in zip(prod.coords, new_shapes): coords.extend(np.unravel_index(c, s)) # Construct the resulting COO array with coords and shape return coo_array((prod.data, coords), shape=combined_shape) def _dense_dot(self, other): # already checked: self is >0d, other is dense and >0d # Ravel non-reduced axes coordinates s_ndim = self.ndim if s_ndim <= 2: s_new_shape = () if s_ndim == 1 else (self.shape[0],) self_2d = self else: self_2d, s_new_shape = _convert_to_2d(self, [self.ndim - 1]) o_ndim = other.ndim if o_ndim <= 2: o_new_shape = () if o_ndim == 1 else (other.shape[-1],) other_2d = other else: o_new_shape = other.shape[:-2] + other.shape[-1:] reorder_dims = (o_ndim - 2, *range(o_ndim - 2), o_ndim - 1) o_reorg = np.transpose(other, reorder_dims) other_2d = o_reorg.reshape((other.shape[-2], math.prod(o_new_shape))) prod = self_2d @ other_2d # routes via 2-D CSR # Combine the shapes of the non-contracted axes combined_shape = s_new_shape + o_new_shape return prod.reshape(combined_shape) def tensordot(self, other, axes=2): """Return the tensordot product with another array along the given axes. The tensordot differs from dot and matmul in that any axis can be chosen for each of the first and second array and the sum of the products is computed just like for matrix multiplication, only not just for the rows of the first times the columns of the second. It takes the dot product of the collection of vectors along the specified axes. Here we can even take the sum of the products along two or even more axes if desired. So, tensordot is a dot product computation applied to arrays of any dimension >= 1. It is like matmul but over arbitrary axes for each matrix. Given two tensors, `a` and `b`, and the desired axes specified as a 2-tuple/list/array containing two sequences of axis numbers, ``(a_axes, b_axes)``, sum the products of `a`'s and `b`'s elements (components) over the axes specified by ``a_axes`` and ``b_axes``. The `axes` input can be a single non-negative integer, ``N``; if it is, then the last ``N`` dimensions of `a` and the first ``N`` dimensions of `b` are summed over. Parameters ---------- a, b : array_like Tensors to "dot". axes : int or (2,) array_like * integer_like If an int N, sum over the last N axes of `a` and the first N axes of `b` in order. The sizes of the corresponding axes must match. * (2,) array_like A 2-tuple of sequences of axes to be summed over, the first applying to `a`, the second to `b`. The sequences must be the same length. The shape of the corresponding axes must match between `a` and `b`. Returns ------- output : coo_array The tensor dot product of this array with `other`. It will be dense/sparse if `other` is dense/sparse. See Also -------- dot Examples -------- >>> import numpy as np >>> import scipy.sparse >>> A = scipy.sparse.coo_array([[[2, 3], [0, 0]], [[0, 1], [0, 5]]]) >>> A.shape (2, 2, 2) Integer axes N are shorthand for (range(-N, 0), range(0, N)): >>> A.tensordot(A, axes=1).toarray() array([[[[ 4, 9], [ 0, 15]], <BLANKLINE> [[ 0, 0], [ 0, 0]]], <BLANKLINE> <BLANKLINE> [[[ 0, 1], [ 0, 5]], <BLANKLINE> [[ 0, 5], [ 0, 25]]]]) >>> A.tensordot(A, axes=2).toarray() array([[ 4, 6], [ 0, 25]]) >>> A.tensordot(A, axes=3) array(39) Using tuple for axes: >>> a = scipy.sparse.coo_array(np.arange(60).reshape(3,4,5)) >>> b = np.arange(24).reshape(4,3,2) >>> c = a.tensordot(b, axes=([1,0],[0,1])) >>> c.shape (5, 2) >>> c array([[4400, 4730], [4532, 4874], [4664, 5018], [4796, 5162], [4928, 5306]]) """ if not isdense(other) and not issparse(other): # If it's a list or whatever, treat it like an array other_array = np.asanyarray(other) if other_array.ndim == 0 and other_array.dtype == np.object_: raise TypeError(f"tensordot arg not supported type: '{type(other)}'") try: other.shape except AttributeError: other = other_array axes_self, axes_other = _process_axes(self.ndim, other.ndim, axes) # Check for shape compatibility along specified axes if any(self.shape[ax] != other.shape[bx] for ax, bx in zip(axes_self, axes_other)): raise ValueError("sizes of the corresponding axes must match") if isdense(other): return self._dense_tensordot(other, axes_self, axes_other) else: return self._sparse_tensordot(other, axes_self, axes_other) def _sparse_tensordot(self, other, s_axes, o_axes): # Prepare the tensors for tensordot operation # Ravel non-reduced axes coordinates self_2d, s_new_shape = _convert_to_2d(self, s_axes) other_2d, o_new_shape = _convert_to_2d(other, o_axes) # Perform matrix multiplication (routed via 2-D CSR) prod = self_2d @ other_2d.T # handle case of scalar result (axis includes all axes for both) if not issparse(prod): return prod prod = prod.tocoo() # Combine the shapes of the non-contracted axes combined_shape = s_new_shape + o_new_shape # Unravel the 2D coordinates to get multi-dimensional coordinates coords = [] new_shapes = (s_new_shape, o_new_shape) if s_new_shape else (o_new_shape,) for c, s in zip(prod.coords, new_shapes): if s: coords.extend(np.unravel_index(c, s)) # Construct the resulting COO array with coords and shape return coo_array((prod.data, coords), shape=combined_shape) def _dense_tensordot(self, other, s_axes, o_axes): s_ndim = len(self.shape) o_ndim = len(other.shape) s_non_axes = [i for i in range(s_ndim) if i not in s_axes] s_axes_shape = [self.shape[i] for i in s_axes] s_non_axes_shape = [self.shape[i] for i in s_non_axes] o_non_axes = [i for i in range(o_ndim) if i not in o_axes] o_axes_shape = [other.shape[i] for i in o_axes] o_non_axes_shape = [other.shape[i] for i in o_non_axes] left = self.transpose(s_non_axes + s_axes) right = np.transpose(other, o_non_axes[:-1] + o_axes + o_non_axes[-1:]) reshape_left = (*s_non_axes_shape, math.prod(s_axes_shape)) reshape_right = (*o_non_axes_shape[:-1], math.prod(o_axes_shape), *o_non_axes_shape[-1:]) return left.reshape(reshape_left).dot(right.reshape(reshape_right)) def _matmul_sparse(self, other): """ Perform sparse-sparse matrix multiplication for two n-D COO arrays. The method converts input n-D arrays to 2-D block array format, uses csr_matmat to multiply them, and then converts the result back to n-D COO array. Parameters: self (COO): The first n-D sparse array in COO format. other (COO): The second n-D sparse array in COO format. Returns: prod (COO): The resulting n-D sparse array after multiplication. """ if self.ndim < 3 and other.ndim < 3: return _spbase._matmul_sparse(self, other) # Get the shapes of self and other self_shape = self.shape other_shape = other.shape # Determine the new shape to broadcast self and other broadcast_shape = np.broadcast_shapes(self_shape[:-2], other_shape[:-2]) self_new_shape = tuple(broadcast_shape) + self_shape[-2:] other_new_shape = tuple(broadcast_shape) + other_shape[-2:] self_broadcasted = self._broadcast_to(self_new_shape) other_broadcasted = other._broadcast_to(other_new_shape) # Convert n-D COO arrays to 2-D block diagonal arrays self_block_diag = _block_diag(self_broadcasted) other_block_diag = _block_diag(other_broadcasted) # Use csr_matmat to perform sparse matrix multiplication prod_block_diag = (self_block_diag @ other_block_diag).tocoo() # Convert the 2-D block diagonal array back to n-D return _extract_block_diag( prod_block_diag, shape=(*broadcast_shape, self.shape[-2], other.shape[-1]), ) def _broadcast_to(self, new_shape, copy=False): if self.shape == new_shape: return self.copy() if copy else self old_shape = self.shape # Check if the new shape is compatible for broadcasting if len(new_shape) < len(old_shape): raise ValueError("New shape must have at least as many dimensions" " as the current shape") # Add leading ones to shape to ensure same length as `new_shape` shape = (1,) * (len(new_shape) - len(old_shape)) + tuple(old_shape) # Ensure the old shape can be broadcast to the new shape if any((o != 1 and o != n) for o, n in zip(shape, new_shape)): raise ValueError(f"current shape {old_shape} cannot be " "broadcast to new shape {new_shape}") # Reshape the COO array to match the new dimensions self = self.reshape(shape) idx_dtype = get_index_dtype(self.coords, maxval=max(new_shape)) coords = self.coords new_data = self.data new_coords = coords[-1:] # Copy last coordinate to start cum_repeat = 1 # Cumulative repeat factor for broadcasting if shape[-1] != new_shape[-1]: # broadcasting the n-th (col) dimension repeat_count = new_shape[-1] cum_repeat *= repeat_count new_data = np.tile(new_data, repeat_count) new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), self.nnz) new_coords = (new_dim,) for i in range(-2, -(len(shape)+1), -1): if shape[i] != new_shape[i]: repeat_count = new_shape[i] # number of times to repeat data, coords cum_repeat *= repeat_count # update cumulative repeat factor nnz = len(new_data) # Number of non-zero elements so far # Tile data and coordinates to match the new repeat count new_data = np.tile(new_data, repeat_count) new_coords = tuple(np.tile(new_coords[i+1:], repeat_count)) # Create new dimensions and stack them new_dim = np.repeat(np.arange(0, repeat_count, dtype=idx_dtype), nnz) new_coords = (new_dim,) + new_coords else: # If no broadcasting needed, tile the coordinates new_dim = np.tile(coords[i], cum_repeat) new_coords = (new_dim,) + new_coords return coo_array((new_data, new_coords), new_shape) def _sum_nd(self, axis, res_dtype, out): # axis and out are preprocessed. out.shape is new_shape A2d, new_shape = _convert_to_2d(self, axis) ones = np.ones((A2d.shape[1], 1), dtype=res_dtype) # sets dtype while loading into out out[...] = (A2d @ ones).reshape(new_shape) return out def _min_or_max_axis_nd(self, axis, min_or_max, explicit): A2d, new_shape = _convert_to_2d(self, axis) res = A2d._min_or_max_axis(1, min_or_max, explicit) unraveled_coords = np.unravel_index(res.coords[0], new_shape) return coo_array((res.data, unraveled_coords), new_shape) def _argminmax_axis_nd(self, axis, argminmax, compare, explicit): A2d, new_shape = _convert_to_2d(self, axis) res_flat = A2d._argminmax_axis(1, argminmax, compare, explicit) return res_flat.reshape(new_shape) def _block_diag(self): """ Converts an N-D COO array into a 2-D COO array in block diagonal form. Parameters: self (coo_array): An N-Dimensional COO sparse array. Returns: coo_array: A 2-Dimensional COO sparse array in block diagonal form. """ if self.ndim<2: raise ValueError("array must have atleast dim=2") num_blocks = math.prod(self.shape[:-2]) n_col = self.shape[-1] n_row = self.shape[-2] res_arr = self.reshape((num_blocks, n_row, n_col)) new_coords = ( res_arr.coords[1] + res_arr.coords[0] * res_arr.shape[1], res_arr.coords[2] + res_arr.coords[0] * res_arr.shape[2], ) new_shape = (num_blocks * n_row, num_blocks * n_col) return coo_array((self.data, tuple(new_coords)), shape=new_shape) def _extract_block_diag(self, shape): n_row, n_col = shape[-2], shape[-1] # Extract data and coordinates from the block diagonal COO array data = self.data row, col = self.row, self.col # Initialize new coordinates array new_coords = np.empty((len(shape), self.nnz), dtype=int) # Calculate within-block indices new_coords[-2] = row % n_row new_coords[-1] = col % n_col # Calculate coordinates for higher dimensions temp_block_idx = row // n_row for i in range(len(shape) - 3, -1, -1): size = shape[i] new_coords[i] = temp_block_idx % size temp_block_idx = temp_block_idx // size # Create the new COO array with the original n-D shape return coo_array((data, tuple(new_coords)), shape=shape) def _get_sparse_data_and_coords(x, new_shape, dtype): x = x.tocoo() x.sum_duplicates() x_coords = list(x.coords) x_data = x.data.astype(dtype, copy=False) x_shape = x.shape if new_shape == x_shape: return x_data, x_coords # broadcasting needed len_diff = len(new_shape) - len(x_shape) if len_diff > 0: # prepend ones to shape of x to match ndim x_shape = [1] * len_diff + list(x_shape) coord_zeros = np.zeroslike(x_coords[0]) x_coords = tuple([coord_zeros] * len_diff + x_coords) # taking away axes (squeezing) is not part of broadcasting, but long # spmatrix history of using 2d vectors in 1d space, so we manually # squeeze the front and back axes here to be compatible if len_diff < 0: for _ in range(-len_diff): if x_shape[0] == 1: x_shape = x_shape[1:] x_coords = x_coords[1:] elif x_shape[-1] == 1: x_shape = x_shape[:-1] x_coords = x_coords[:-1] else: raise ValueError("shape mismatch in assignment") # broadcast with copy (will need to copy eventually anyway) tot_expand = 1 for i, (nn, nx) in enumerate(zip(new_shape, x_shape)): if nn == nx: continue if nx != 1: raise ValueError("shape mismatch in assignment") x_nnz = len(x_coords[0]) x_coords[i] = np.repeat(np.arange(nn), x_nnz) for j, co in enumerate(x_coords): if j == i: continue x_coords[j] = np.tile(co, nn) tot_expand *= nn x_data = np.tile(x_data.ravel(), tot_expand) return x_data, x_coords def _get_dense_data_and_coords(x, new_shape): if x.shape != new_shape: x = np.broadcast_to(x.squeeze(), new_shape) # shift scalar input to 1d so has coords if new_shape == (): x_coords = tuple([np.array([0])] * len(new_shape)) x_data = x.ravel() else: x_coords = x.nonzero() x_data = x[x_coords] return x_data, x_coords def _process_axes(ndim_a, ndim_b, axes): if isinstance(axes, int): if axes < 1 or axes > min(ndim_a, ndim_b): raise ValueError("axes integer is out of bounds for input arrays") axes_a = list(range(ndim_a - axes, ndim_a)) axes_b = list(range(axes)) elif isinstance(axes, tuple | list): if len(axes) != 2: raise ValueError("axes must be a tuple/list of length 2") axes_a, axes_b = axes if len(axes_a) != len(axes_b): raise ValueError("axes lists/tuples must be of the same length") if any(ax >= ndim_a or ax < -ndim_a for ax in axes_a) or \ any(bx >= ndim_b or bx < -ndim_b for bx in axes_b): raise ValueError("axes indices are out of bounds for input arrays") else: raise TypeError("axes must be an integer or a tuple/list of integers") axes_a = [axis + ndim_a if axis < 0 else axis for axis in axes_a] axes_b = [axis + ndim_b if axis < 0 else axis for axis in axes_b] return axes_a, axes_b def _convert_to_2d(coo, axis): axis_coords = tuple(coo.coords[i] for i in axis) axis_shape = tuple(coo.shape[i] for i in axis) axis_ravel = _ravel_coords(axis_coords, axis_shape) ndim = len(coo.coords) non_axis = tuple(i for i in range(ndim) if i not in axis) if non_axis: non_axis_coords = tuple(coo.coords[i] for i in non_axis) non_axis_shape = tuple(coo.shape[i] for i in non_axis) non_axis_ravel = _ravel_coords(non_axis_coords, non_axis_shape) coords_2d = (non_axis_ravel, axis_ravel) shape_2d = (math.prod(non_axis_shape), math.prod(axis_shape)) else: # all axes included in axis so result will have 1 element coords_2d = (axis_ravel,) shape_2d = (math.prod(axis_shape),) non_axis_shape = () new_coo = coo_array((coo.data, coords_2d), shape=shape_2d) return new_coo, non_axis_shape def _ravel_coords(coords, shape, order='C'): """Like np.ravel_multi_index, but avoids some overflow issues.""" if len(coords) == 1: return coords[0] # Handle overflow as in https://github.com/scipy/scipy/pull/9132 if len(coords) == 2: nrows, ncols = shape row, col = coords if order == 'C': maxval = (ncols * max(0, nrows - 1) + max(0, ncols - 1)) idx_dtype = get_index_dtype(maxval=maxval) return np.multiply(ncols, row, dtype=idx_dtype) + col elif order == 'F': maxval = (nrows * max(0, ncols - 1) + max(0, nrows - 1)) idx_dtype = get_index_dtype(maxval=maxval) return np.multiply(nrows, col, dtype=idx_dtype) + row else: raise ValueError("'order' must be 'C' or 'F'") return np.ravel_multi_index(coords, shape, order=order) def isspmatrix_coo(x): """Is `x` of coo_matrix type? Parameters ---------- x object to check for being a coo matrix Returns ------- bool True if `x` is a coo matrix, False otherwise Examples -------- >>> from scipy.sparse import coo_array, coo_matrix, csr_matrix, isspmatrix_coo >>> isspmatrix_coo(coo_matrix([[5]])) True >>> isspmatrix_coo(coo_array([[5]])) False >>> isspmatrix_coo(csr_matrix([[5]])) False """ return isinstance(x, coo_matrix) # This namespace class separates array from matrix with isinstance
_coo_base
python
pypa__warehouse
warehouse/packaging/services.py
{ "start": 3858, "end": 4060 }
class ____(GenericLocalBlobStorage): @classmethod def create_service(cls, context, request): return cls(request.registry.settings["files.path"]) @implementer(IFileStorage)
LocalFileStorage
python
pytorch__pytorch
test/test_dynamic_shapes.py
{ "start": 118069, "end": 125434 }
class ____(TestCase): @skipIfTorchDynamo("https://github.com/pytorch/pytorch/issues/156135") @torch._dynamo.config.patch("capture_scalar_outputs", True) @parametrize("backend", ["inductor", "eager"]) def test_deferred_neq_assert(self, backend): @torch.compile(fullgraph=True, backend=backend) def func(a): torch._check(a.item() != 5) return a.item() * 10 func(torch.tensor([100])) with self.assertRaises(RuntimeError): func(torch.tensor([5])) # Test a situation where we generate a runtime assert i.e: u1==s1, then we specialize s1 # later on to a constant. @torch._dynamo.config.patch("capture_scalar_outputs", True) @parametrize("backend", ["inductor", "eager"]) def test_post_specialize_runtime_assert1(self, backend): @torch.compile(dynamic=True, backend=backend) def func(x, y): u0 = y.item() s0 = x.size()[0] s1 = x.size()[1] torch._check(u0 + s0 + s1 == 102) assert s0 == 2 return x * 10 func(torch.rand(2, 50), torch.tensor([50])) with self.assertRaises(RuntimeError): func(torch.rand(2, 50), torch.tensor([51])) @torch._dynamo.config.patch("capture_scalar_outputs", True) @torch._inductor.config.patch(post_grad_custom_pre_pass=custom_pass) @parametrize("backend", ["inductor", "eager"]) def test_post_specialize_runtime_assert2(self, backend): @torch.compile(dynamic=True, backend=backend) def func(x, y): u0 = y.item() s0 = x.size()[0] s1 = x.size()[1] torch._check(u0 + s0 + s1 == 102) return x * 10 func(torch.rand(2, 50), torch.tensor([50])) with self.assertRaises(RuntimeError): func(torch.rand(2, 50), torch.tensor([51])) @skipIfTorchDynamo("https://github.com/pytorch/pytorch/issues/156135") @torch._dynamo.config.patch("capture_scalar_outputs", True) @parametrize("backend", ["inductor", "eager"]) def test_deferred_sym_or_assert(self, backend): @torch.compile(fullgraph=True, backend=backend) def func(a, b): torch._check(operator.or_(a.item() == 5, b.item() == 5)) return a.item() * 10 func(torch.tensor([5]), torch.tensor([100])) func(torch.tensor([100]), torch.tensor([5])) def test_has_free_symbols(self): self.assertFalse(has_free_symbols(sympy.S.true)) self.assertFalse(has_free_symbols(sympy.Max(1, 10, evaluate=False))) self.assertFalse(has_free_symbols(sympy.sympify("1"))) self.assertFalse(has_free_symbols(sympy.sympify("1.1"))) self.assertTrue(has_free_symbols(sympy.sympify("a"))) self.assertTrue(has_free_symbols(sympy.sympify("a*2"))) self.assertTrue(has_free_symbols(sympy.sympify("a+b"))) @skipIfTorchDynamo("https://github.com/pytorch/pytorch/issues/156135") @torch._dynamo.config.patch("capture_scalar_outputs", True) @parametrize("backend", ["inductor", "eager"]) def test_deferred_sym_eq_assert(self, backend): @torch.compile(fullgraph=True, backend=backend) def func(a, b): torch._check(b.item() == 5) return a * 10 func(torch.tensor([5]), torch.tensor([5])) with self.assertRaises(RuntimeError): func(torch.tensor([100]), torch.tensor([1])) @torch._dynamo.config.patch("capture_scalar_outputs", True) @parametrize("backend", ["inductor", "eager"]) @skipIfTorchDynamo("mark_unbacked is not traceable") def test_deferred_with_unbacked_input(self, backend): @torch.compile(fullgraph=True, dynamic=True, backend=backend) def func(a, b): torch._check(a.size()[0] == b.size()[0]) return a * 10 a = torch.rand(1, 1) b = torch.rand(1, 1) torch._dynamo.decorators.mark_unbacked(a, 0) torch._dynamo.decorators.mark_unbacked(b, 0) func(a, b) # inductor adds the check sometimes itself so it will be reflected # as AssertionError. with self.assertRaises((AssertionError, RuntimeError)): func(a, torch.rand(2, 1)) @pytest.mark.xfail(reason="https://github.com/pytorch/pytorch/issues/163785") @skipIfTorchDynamo("mark_unbacked is not traceable") def test_do_not_guard_unbacked_inputs(self): @torch.compile(fullgraph=True, dynamic=True, backend="inductor") def func(a, b): a.expand(b.shape) return a * 10 a = torch.rand(1, 1) b = torch.rand(1, 1) torch._dynamo.decorators.mark_unbacked(a, 0) torch._dynamo.decorators.mark_unbacked(a, 1) torch._dynamo.decorators.mark_unbacked(b, 0) torch._dynamo.decorators.mark_unbacked(b, 1) log_stream, ctx = logs_to_string("torch._dynamo.guards", "guards") with ctx(): func(a, b) func(torch.rand(4, 5), torch.rand(4, 5)) guards = "\n".join(log_stream.getvalue().strip().split("\n")[4:]).strip() self.assertFalse("SYMBOLIC_SHAPE_GUARD" in guards) @skipIfTorchDynamo("mark_unbacked is not traceable") def test_div_unbacked_eq_input_tensors(self): @torch.compile(fullgraph=True) def func(a, b): x = a.size()[0] y = b.size()[0] torch._check(x == y) if x // y == 1: a = a * 10 if 2 * x // y == 2: a = a * 20 return a a = torch.randn(10, 10) b = torch.randn(10, 20) torch._dynamo.decorators.mark_unbacked(a, 0) torch._dynamo.decorators.mark_unbacked(b, 0) func(a, b) @torch.compiler.config.patch(unbacked_sources="L['x'],L['y']") def test_div_unbacked_eq_input_ints(self): @torch.compile(fullgraph=True) def func(x, y): a = torch.rand(1) torch._check(x == y) if x // y == 1: a = a * 10 if 2 * x // y == 2: a = a * 20 return a func(10, 10) @skipIfTorchDynamo("mark_unbacked is not traceable") @torch.compiler.config.patch(unbacked_sources="L['y']") def test_div_unbacked_eq_globals(self): tensor = torch.rand(10, 44) y = 10 @torch.compile(fullgraph=True, dynamic=True) def func(): a = torch.rand(1) x = tensor.size()[0] torch._check(x == y) if x // y == 1: a = a * 10 if 2 * x // y == 2: a = a * 20 return a torch._dynamo.decorators.mark_unbacked(tensor, 0) func() @torch._dynamo.config.patch("capture_scalar_outputs", True) def test_div_unbacked_eq_item(self): @torch.compile(fullgraph=True) def func(a, b): x = a.item() y = b.item() torch._check(x == y) # TODO we should not need those torch checks. torch._check(x // y == 1) torch._check(2 * x // y == 2) if x // y == 1: a = a * 10 if 2 * x // y == 2: a = a * 20 return a a = torch.tensor([1]) b = torch.tensor([1]) func(a, b)
TestUnbacked
python
astropy__astropy
astropy/extern/ply/yacc.py
{ "start": 56042, "end": 57690 }
class ____(object): def __init__(self, str, name, len, func, file, line): self.name = name self.len = len self.func = func self.callable = None self.file = file self.line = line self.str = str def __str__(self): return self.str def __repr__(self): return 'MiniProduction(%s)' % self.str # Bind the production function name to a callable def bind(self, pdict): if self.func: self.callable = pdict[self.func] # ----------------------------------------------------------------------------- # class LRItem # # This class represents a specific stage of parsing a production rule. For # example: # # expr : expr . PLUS term # # In the above, the "." represents the current location of the parse. Here # basic attributes: # # name - Name of the production. For example 'expr' # prod - A list of symbols on the right side ['expr','.', 'PLUS','term'] # number - Production number. # # lr_next Next LR item. Example, if we are ' expr -> expr . PLUS term' # then lr_next refers to 'expr -> expr PLUS . term' # lr_index - LR item index (location of the ".") in the prod list. # lookaheads - LALR lookahead symbols for this item # len - Length of the production (number of symbols on right hand side) # lr_after - List of all productions that immediately follow # lr_before - Grammar symbol immediately before # -----------------------------------------------------------------------------
MiniProduction
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/override1.py
{ "start": 1971, "end": 2340 }
class ____(H, Protocol): @override # This should generate an error because method1 isn't present # in the base. def method1(self): pass @overload @override # This should generate an error because method2 isn't present # in the base. def method2(self, x: int) -> int: ... @overload def method2(self, x: str) -> str: ...
I
python
ray-project__ray
rllib/algorithms/appo/appo.py
{ "start": 14558, "end": 18151 }
class ____(IMPALA): def __init__(self, config, *args, **kwargs): """Initializes an APPO instance.""" super().__init__(config, *args, **kwargs) # After init: Initialize target net. # TODO(avnishn): Does this need to happen in __init__? I think we can move it # to setup() if not self.config.enable_rl_module_and_learner: self.env_runner.foreach_policy_to_train(lambda p, _: p.update_target()) @override(IMPALA) def training_step(self) -> None: if self.config.enable_rl_module_and_learner: return super().training_step() train_results = super().training_step() # Update the target network and the KL coefficient for the APPO-loss. # The target network update frequency is calculated automatically by the product # of `num_epochs` setting (usually 1 for APPO) and `minibatch_buffer_size`. last_update = self._counters[LAST_TARGET_UPDATE_TS] cur_ts = self._counters[ ( NUM_AGENT_STEPS_SAMPLED if self.config.count_steps_by == "agent_steps" else NUM_ENV_STEPS_SAMPLED ) ] target_update_freq = self.config.num_epochs * self.config.minibatch_buffer_size if cur_ts - last_update > target_update_freq: self._counters[NUM_TARGET_UPDATES] += 1 self._counters[LAST_TARGET_UPDATE_TS] = cur_ts # Update our target network. self.env_runner.foreach_policy_to_train(lambda p, _: p.update_target()) # Also update the KL-coefficient for the APPO loss, if necessary. if self.config.use_kl_loss: def update(pi, pi_id): assert LEARNER_STATS_KEY not in train_results, ( "{} should be nested under policy id key".format( LEARNER_STATS_KEY ), train_results, ) if pi_id in train_results: kl = train_results[pi_id][LEARNER_STATS_KEY].get("kl") assert kl is not None, (train_results, pi_id) # Make the actual `Policy.update_kl()` call. pi.update_kl(kl) else: logger.warning("No data for {}, not updating kl".format(pi_id)) # Update KL on all trainable policies within the local (trainer) # Worker. self.env_runner.foreach_policy_to_train(update) return train_results @classmethod @override(IMPALA) def get_default_config(cls) -> APPOConfig: return APPOConfig() @classmethod @override(IMPALA) def get_default_policy_class( cls, config: AlgorithmConfig ) -> Optional[Type[Policy]]: if config["framework"] == "torch": from ray.rllib.algorithms.appo.appo_torch_policy import APPOTorchPolicy return APPOTorchPolicy elif config["framework"] == "tf": if config.enable_rl_module_and_learner: raise ValueError( "RLlib's RLModule and Learner API is not supported for" " tf1. Use " "framework='tf2' instead." ) from ray.rllib.algorithms.appo.appo_tf_policy import APPOTF1Policy return APPOTF1Policy else: from ray.rllib.algorithms.appo.appo_tf_policy import APPOTF2Policy return APPOTF2Policy
APPO
python
numpy__numpy
numpy/_core/tests/test_arrayobject.py
{ "start": 955, "end": 2596 }
class ____(np.ndarray): pass @pytest.mark.parametrize("subclass_self", [np.ndarray, MyArr, MyArrNoWrap]) @pytest.mark.parametrize("subclass_arr", [np.ndarray, MyArr, MyArrNoWrap]) def test_array_wrap(subclass_self, subclass_arr): # NumPy should allow `__array_wrap__` to be called on arrays, it's logic # is designed in a way that: # # * Subclasses never return scalars by default (to preserve their # information). They can choose to if they wish. # * NumPy returns scalars, if `return_scalar` is passed as True to allow # manual calls to `arr.__array_wrap__` to do the right thing. # * The type of the input should be ignored (it should be a base-class # array, but I am not sure this is guaranteed). arr = np.arange(3).view(subclass_self) arr0d = np.array(3, dtype=np.int8).view(subclass_arr) # With third argument True, ndarray allows "decay" to scalar. # (I don't think NumPy would pass `None`, but it seems clear to support) if subclass_self is np.ndarray: assert type(arr.__array_wrap__(arr0d, None, True)) is np.int8 else: assert type(arr.__array_wrap__(arr0d, None, True)) is type(arr) # Otherwise, result should be viewed as the subclass assert type(arr.__array_wrap__(arr0d)) is type(arr) assert type(arr.__array_wrap__(arr0d, None, None)) is type(arr) assert type(arr.__array_wrap__(arr0d, None, False)) is type(arr) # Non 0-D array can't be converted to scalar, so we ignore that arr1d = np.array([3], dtype=np.int8).view(subclass_arr) assert type(arr.__array_wrap__(arr1d, None, True)) is type(arr)
MyArrNoWrap
python
modin-project__modin
modin/tests/pandas/extensions/test_groupby_extensions.py
{ "start": 4624, "end": 10737 }
class ____: @pytest.mark.parametrize("df_backend", ["Pandas", "Python_Test"]) def test_add_read_only_property_for_all_backends( self, df_backend, get_groupby, register_accessor ): expected_string_val = "expected_string_val" property_name = "new_property" @register_dataframe_groupby_accessor(property_name) @property def new_property(self): return expected_string_val with config_context(Backend=df_backend): df = pd.DataFrame({"col0": [1, 2, 3], "col1": [4, 5, 6]}) assert get_groupby(df).new_property == expected_string_val with pytest.raises(AttributeError): del df.groupby("col0").new_property with pytest.raises(AttributeError): df.groupby("col0").new_property = "new_value" def test_override_ngroups_getter_for_one_backend( self, get_groupby, register_accessor ): accessor_ngroups = -1 property_name = "ngroups" @register_accessor(property_name, backend="Pandas") @property def ngroups(self): return accessor_ngroups pandas_df = pd.DataFrame({"col0": [1, 2, 3], "col1": [4, 5, 6]}).move_to( "pandas" ) groupby = get_groupby(pandas_df) assert groupby.ngroups == accessor_ngroups # Check that the accessor doesn't work on the Python_Test backend. python_test_df = pandas_df.move_to("Python_Test") groupby = get_groupby(python_test_df) with warns_that_defaulting_to_pandas_if(not current_execution_is_native()): assert groupby.ngroups == 3 def test_add_ngroups_setter_and_deleter_for_one_backend( self, get_groupby, register_accessor ): def _get_ngroups(self): return self._ngroups def _delete_ngroups(self): delattr(self, "_ngroups") def _set_ngroups(self, value): self._ngroups = value register_accessor("ngroups", backend="Pandas")( property(fget=_get_ngroups, fset=_set_ngroups, fdel=_delete_ngroups) ) python_test_df = pd.DataFrame({"col0": [1, 2, 3], "col1": [4, 5, 6]}).move_to( "python_test" ) python_test_groupby = get_groupby(python_test_df) with warns_that_defaulting_to_pandas_if(not current_execution_is_native()): assert python_test_groupby.ngroups == 3 with pytest.raises(AttributeError): python_test_groupby.ngroups = 4 with pytest.raises(AttributeError): del python_test_groupby.ngroups pandas_groupby = get_groupby(python_test_df.move_to("Pandas")) assert not hasattr(pandas_groupby, "ngroups") pandas_groupby.ngroups = -1 assert pandas_groupby.ngroups == -1 # Deleting ngroups should delete the private attribute _ngroups. del pandas_groupby.ngroups # now getting ngroups should raise an AttributeError because the # private attribute _ngroups is missing. assert not hasattr(pandas_groupby, "ngroups") def test_add_deletable_property_for_one_backend( self, get_groupby, register_accessor ): public_property_name = "property_name" private_property_name = "_property_name" # register a public property `public_property_name` that is backed by # a private attribute `private_property_name`. def get_property(self): return getattr(self, private_property_name) def set_property(self, value): setattr(self, private_property_name, value) def del_property(self): # Note that deleting the public property deletes the private # attribute, not the public property itself. delattr(self, private_property_name) register_accessor(name=public_property_name, backend="Pandas")( property(get_property, set_property, del_property) ) python_test_df = pd.DataFrame({"col0": [1, 2, 3], "col1": [4, 5, 6]}).move_to( "python_test" ) python_test_groupby = get_groupby(python_test_df) assert not hasattr(python_test_groupby, public_property_name) pandas_df = python_test_df.move_to("pandas") pandas_groupby = get_groupby(pandas_df) setattr(pandas_groupby, public_property_name, "value") assert getattr(pandas_groupby, public_property_name) == "value" delattr(pandas_groupby, public_property_name) assert not hasattr(pandas_groupby, private_property_name) @pytest.mark.filterwarnings(default_to_pandas_ignore_string) def test_override_cached_property(self, get_groupby, register_accessor): @cached_property def groups(self): return {"group": pd.Index(["test"])} register_accessor("groups", backend="Pandas")(groups) pandas_df = pd.DataFrame({"col0": [1], "col1": [2]}).move_to("pandas") assert get_groupby(pandas_df).groups == {"group": pd.Index(["test"])} def test_deleting_extension_that_is_not_property_raises_attribute_error(): expected_string_val = "Some string value" method_name = "new_method" @register_dataframe_groupby_accessor(name=method_name) def my_method_implementation(self): return expected_string_val groupby = pd.DataFrame({"col0": [1, 2, 3], "col1": [4, 5, 6]}).groupby("col0") assert hasattr(DataFrameGroupBy, method_name) assert getattr(groupby, method_name)() == expected_string_val with pytest.raises(AttributeError): delattr(groupby, method_name) @pytest.mark.skipif(Backend.get() == "Pandas", reason="already on pandas backend") def test_get_extension_from_dataframe_that_is_on_non_default_backend_when_auto_switch_is_false(): assert not AutoSwitchBackend.get() pandas_df = pd.DataFrame([1, 2]).move_to("Pandas") register_dataframe_groupby_accessor("sum", backend="Pandas")( lambda df: "small_sum_result" ) assert pandas_df.groupby(0).sum() == "small_sum_result"
TestProperty
python
huggingface__transformers
src/transformers/models/depth_pro/configuration_depth_pro.py
{ "start": 872, "end": 10675 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`DepthProModel`]. It is used to instantiate a DepthPro model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the DepthPro [apple/DepthPro](https://huggingface.co/apple/DepthPro) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: fusion_hidden_size (`int`, *optional*, defaults to 256): The number of channels before fusion. patch_size (`int`, *optional*, defaults to 384): The size (resolution) of each patch. This is also the image_size for backbone model. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. intermediate_hook_ids (`list[int]`, *optional*, defaults to `[11, 5]`): Indices of the intermediate hidden states from the patch encoder to use for fusion. intermediate_feature_dims (`list[int]`, *optional*, defaults to `[256, 256]`): Hidden state dimensions during upsampling for each intermediate hidden state in `intermediate_hook_ids`. scaled_images_ratios (`list[float]`, *optional*, defaults to `[0.25, 0.5, 1]`): Ratios of scaled images to be used by the patch encoder. scaled_images_overlap_ratios (`list[float]`, *optional*, defaults to `[0.0, 0.5, 0.25]`): Overlap ratios between patches for each scaled image in `scaled_images_ratios`. scaled_images_feature_dims (`list[int]`, *optional*, defaults to `[1024, 1024, 512]`): Hidden state dimensions during upsampling for each scaled image in `scaled_images_ratios`. merge_padding_value (`int`, *optional*, defaults to 3): When merging smaller patches back to the image size, overlapping sections of this size are removed. use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`): Whether to use batch normalization in the pre-activate residual units of the fusion blocks. use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`): Whether to use bias in the pre-activate residual units of the fusion blocks. use_fov_model (`bool`, *optional*, defaults to `False`): Whether to use `DepthProFovModel` to generate the field of view. num_fov_head_layers (`int`, *optional*, defaults to 2): Number of convolution layers in the head of `DepthProFovModel`. image_model_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*): The configuration of the image encoder model, which is loaded using the [`AutoModel`] API. By default, Dinov2 model is used as backbone. patch_model_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*): The configuration of the patch encoder model, which is loaded using the [`AutoModel`] API. By default, Dinov2 model is used as backbone. fov_model_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*): The configuration of the fov encoder model, which is loaded using the [`AutoModel`] API. By default, Dinov2 model is used as backbone. Example: ```python >>> from transformers import DepthProConfig, DepthProModel >>> # Initializing a DepthPro apple/DepthPro style configuration >>> configuration = DepthProConfig() >>> # Initializing a model (with random weights) from the apple/DepthPro style configuration >>> model = DepthProModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "depth_pro" sub_configs = {"image_model_config": AutoConfig, "patch_model_config": AutoConfig, "fov_model_config": AutoConfig} def __init__( self, fusion_hidden_size=256, patch_size=384, initializer_range=0.02, intermediate_hook_ids=[11, 5], intermediate_feature_dims=[256, 256], scaled_images_ratios=[0.25, 0.5, 1], scaled_images_overlap_ratios=[0.0, 0.5, 0.25], scaled_images_feature_dims=[1024, 1024, 512], merge_padding_value=3, use_batch_norm_in_fusion_residual=False, use_bias_in_fusion_residual=True, use_fov_model=False, num_fov_head_layers=2, image_model_config=None, patch_model_config=None, fov_model_config=None, **kwargs, ): # scaled_images_ratios is sorted if scaled_images_ratios != sorted(scaled_images_ratios): raise ValueError( f"Values in scaled_images_ratios={scaled_images_ratios} should be sorted from low to high" ) # scaled_images_ratios, scaled_images_overlap_ratios, scaled_images_feature_dims should be consistent if not (len(scaled_images_ratios) == len(scaled_images_overlap_ratios) == len(scaled_images_feature_dims)): raise ValueError( f"len(scaled_images_ratios)={len(scaled_images_ratios)} and " f"len(scaled_images_overlap_ratios)={len(scaled_images_overlap_ratios)} and " f"len(scaled_images_feature_dims)={len(scaled_images_feature_dims)}, " f"should match in config." ) # intermediate_hook_ids, intermediate_feature_dims should be consistent if not (len(intermediate_hook_ids) == len(intermediate_feature_dims)): raise ValueError( f"len(intermediate_hook_ids)={len(intermediate_hook_ids)} and " f"len(intermediate_feature_dims)={len(intermediate_feature_dims)}, " f"should match in config." ) # fusion_hidden_size should be consistent with num_fov_head_layers if fusion_hidden_size // 2**num_fov_head_layers == 0: raise ValueError( f"fusion_hidden_size={fusion_hidden_size} should be consistent with num_fov_head_layers={num_fov_head_layers} " "i.e fusion_hidden_size // 2**num_fov_head_layers > 0" ) self.fusion_hidden_size = fusion_hidden_size self.patch_size = patch_size self.initializer_range = initializer_range self.use_batch_norm_in_fusion_residual = use_batch_norm_in_fusion_residual self.use_bias_in_fusion_residual = use_bias_in_fusion_residual self.use_fov_model = use_fov_model self.num_fov_head_layers = num_fov_head_layers self.intermediate_hook_ids = intermediate_hook_ids self.intermediate_feature_dims = intermediate_feature_dims self.scaled_images_ratios = scaled_images_ratios self.scaled_images_overlap_ratios = scaled_images_overlap_ratios self.scaled_images_feature_dims = scaled_images_feature_dims self.merge_padding_value = merge_padding_value self.image_model_config = image_model_config self.patch_model_config = patch_model_config self.fov_model_config = fov_model_config for sub_config_key in self.sub_configs: sub_config = getattr(self, sub_config_key) if sub_config is None: sub_config = CONFIG_MAPPING["dinov2"](image_size=patch_size) logger.info( f"`{sub_config_key}` is `None`. Initializing `{sub_config_key}` with the `Dinov2Config` " f"with default values except `{sub_config_key}.image_size` is set to `config.patch_size`." ) elif isinstance(sub_config, dict): sub_config = deepcopy(sub_config) if "model_type" not in sub_config: raise KeyError( f"The `model_type` key is missing in the `{sub_config_key}` dictionary. Please provide the model type." ) elif sub_config["model_type"] not in CONFIG_MAPPING: raise ValueError( f"The model type `{sub_config['model_type']}` in `{sub_config_key}` is not supported. Please provide a valid model type." ) image_size = sub_config.get("image_size") if image_size != patch_size: logger.info( f"The `image_size` in `{sub_config_key}` is set to `{image_size}`, " f"but it does not match the required `patch_size` of `{patch_size}`. " f"Updating `image_size` to `{patch_size}` for consistency. " f"Ensure that `image_size` aligns with `patch_size` in the configuration." ) sub_config.update({"image_size": patch_size}) sub_config = CONFIG_MAPPING[sub_config["model_type"]](**sub_config) elif isinstance(sub_config, PreTrainedConfig): image_size = getattr(sub_config, "image_size", None) if image_size != patch_size: raise ValueError( f"`config.{sub_config_key}.image_size={image_size}` should match `config.patch_size={patch_size}`." ) else: raise TypeError( f"Invalid type for `sub_config`. Expected `PreTrainedConfig`, `dict`, or `None`, but got {type(sub_config)}." ) setattr(self, sub_config_key, sub_config) super().__init__(**kwargs) __all__ = ["DepthProConfig"]
DepthProConfig
python
tornadoweb__tornado
tornado/gen.py
{ "start": 10127, "end": 24376 }
class ____: """Provides an iterator to yield the results of awaitables as they finish. Yielding a set of awaitables like this: ``results = yield [awaitable1, awaitable2]`` pauses the coroutine until both ``awaitable1`` and ``awaitable2`` return, and then restarts the coroutine with the results of both awaitables. If either awaitable raises an exception, the expression will raise that exception and all the results will be lost. If you need to get the result of each awaitable as soon as possible, or if you need the result of some awaitables even if others produce errors, you can use ``WaitIterator``:: wait_iterator = gen.WaitIterator(awaitable1, awaitable2) while not wait_iterator.done(): try: result = yield wait_iterator.next() except Exception as e: print("Error {} from {}".format(e, wait_iterator.current_future)) else: print("Result {} received from {} at {}".format( result, wait_iterator.current_future, wait_iterator.current_index)) Because results are returned as soon as they are available the output from the iterator *will not be in the same order as the input arguments*. If you need to know which future produced the current result, you can use the attributes ``WaitIterator.current_future``, or ``WaitIterator.current_index`` to get the index of the awaitable from the input list. (if keyword arguments were used in the construction of the `WaitIterator`, ``current_index`` will use the corresponding keyword). `WaitIterator` implements the async iterator protocol, so it can be used with the ``async for`` statement (note that in this version the entire iteration is aborted if any value raises an exception, while the previous example can continue past individual errors):: async for result in gen.WaitIterator(future1, future2): print("Result {} received from {} at {}".format( result, wait_iterator.current_future, wait_iterator.current_index)) .. versionadded:: 4.1 .. versionchanged:: 4.3 Added ``async for`` support in Python 3.5. """ _unfinished = {} # type: Dict[Future, Union[int, str]] def __init__(self, *args: Future, **kwargs: Future) -> None: if args and kwargs: raise ValueError("You must provide args or kwargs, not both") if kwargs: self._unfinished = {f: k for (k, f) in kwargs.items()} futures = list(kwargs.values()) # type: Sequence[Future] else: self._unfinished = {f: i for (i, f) in enumerate(args)} futures = args self._finished = collections.deque() # type: Deque[Future] self.current_index = None # type: Optional[Union[str, int]] self.current_future = None # type: Optional[Future] self._running_future = None # type: Optional[Future] for future in futures: future_add_done_callback(future, self._done_callback) def done(self) -> bool: """Returns True if this iterator has no more results.""" if self._finished or self._unfinished: return False # Clear the 'current' values when iteration is done. self.current_index = self.current_future = None return True def next(self) -> Future: """Returns a `.Future` that will yield the next available result. Note that this `.Future` will not be the same object as any of the inputs. """ self._running_future = Future() if self._finished: return self._return_result(self._finished.popleft()) return self._running_future def _done_callback(self, done: Future) -> None: if self._running_future and not self._running_future.done(): self._return_result(done) else: self._finished.append(done) def _return_result(self, done: Future) -> Future: """Called set the returned future's state that of the future we yielded, and set the current future for the iterator. """ if self._running_future is None: raise Exception("no future is running") chain_future(done, self._running_future) res = self._running_future self._running_future = None self.current_future = done self.current_index = self._unfinished.pop(done) return res def __aiter__(self) -> typing.AsyncIterator: return self def __anext__(self) -> Future: if self.done(): # Lookup by name to silence pyflakes on older versions. raise getattr(builtins, "StopAsyncIteration")() return self.next() @overload def multi( children: Sequence[_Yieldable], quiet_exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = (), ) -> Future[List]: ... @overload def multi( children: Mapping[Any, _Yieldable], quiet_exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = (), ) -> Future[Dict]: ... def multi( children: Union[Sequence[_Yieldable], Mapping[Any, _Yieldable]], quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> "Union[Future[List], Future[Dict]]": """Runs multiple asynchronous operations in parallel. ``children`` may either be a list or a dict whose values are yieldable objects. ``multi()`` returns a new yieldable object that resolves to a parallel structure containing their results. If ``children`` is a list, the result is a list of results in the same order; if it is a dict, the result is a dict with the same keys. That is, ``results = yield multi(list_of_futures)`` is equivalent to:: results = [] for future in list_of_futures: results.append(yield future) If any children raise exceptions, ``multi()`` will raise the first one. All others will be logged, unless they are of types contained in the ``quiet_exceptions`` argument. In a ``yield``-based coroutine, it is not normally necessary to call this function directly, since the coroutine runner will do it automatically when a list or dict is yielded. However, it is necessary in ``await``-based coroutines, or to pass the ``quiet_exceptions`` argument. This function is available under the names ``multi()`` and ``Multi()`` for historical reasons. Cancelling a `.Future` returned by ``multi()`` does not cancel its children. `asyncio.gather` is similar to ``multi()``, but it does cancel its children. .. versionchanged:: 4.2 If multiple yieldables fail, any exceptions after the first (which is raised) will be logged. Added the ``quiet_exceptions`` argument to suppress this logging for selected exception types. .. versionchanged:: 4.3 Replaced the class ``Multi`` and the function ``multi_future`` with a unified function ``multi``. Added support for yieldables other than ``YieldPoint`` and `.Future`. """ return multi_future(children, quiet_exceptions=quiet_exceptions) Multi = multi def multi_future( children: Union[Sequence[_Yieldable], Mapping[Any, _Yieldable]], quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> "Union[Future[List], Future[Dict]]": """Wait for multiple asynchronous futures in parallel. Since Tornado 6.0, this function is exactly the same as `multi`. .. versionadded:: 4.0 .. versionchanged:: 4.2 If multiple ``Futures`` fail, any exceptions after the first (which is raised) will be logged. Added the ``quiet_exceptions`` argument to suppress this logging for selected exception types. .. deprecated:: 4.3 Use `multi` instead. """ if isinstance(children, dict): keys = list(children.keys()) # type: Optional[List] children_seq = children.values() # type: Iterable else: keys = None children_seq = children children_futs = list(map(convert_yielded, children_seq)) assert all(is_future(i) or isinstance(i, _NullFuture) for i in children_futs) unfinished_children = set(children_futs) future = _create_future() if not children_futs: future_set_result_unless_cancelled(future, {} if keys is not None else []) def callback(fut: Future) -> None: unfinished_children.remove(fut) if not unfinished_children: result_list = [] for f in children_futs: try: result_list.append(f.result()) except Exception as e: if future.done(): if not isinstance(e, quiet_exceptions): app_log.error( "Multiple exceptions in yield list", exc_info=True ) else: future_set_exc_info(future, sys.exc_info()) if not future.done(): if keys is not None: future_set_result_unless_cancelled( future, dict(zip(keys, result_list)) ) else: future_set_result_unless_cancelled(future, result_list) listening = set() # type: Set[Future] for f in children_futs: if f not in listening: listening.add(f) future_add_done_callback(f, callback) return future def maybe_future(x: Any) -> Future: """Converts ``x`` into a `.Future`. If ``x`` is already a `.Future`, it is simply returned; otherwise it is wrapped in a new `.Future`. This is suitable for use as ``result = yield gen.maybe_future(f())`` when you don't know whether ``f()`` returns a `.Future` or not. .. deprecated:: 4.3 This function only handles ``Futures``, not other yieldable objects. Instead of `maybe_future`, check for the non-future result types you expect (often just ``None``), and ``yield`` anything unknown. """ if is_future(x): return x else: fut = _create_future() fut.set_result(x) return fut def with_timeout( timeout: Union[float, datetime.timedelta], future: _Yieldable, quiet_exceptions: "Union[Type[Exception], Tuple[Type[Exception], ...]]" = (), ) -> Future: """Wraps a `.Future` (or other yieldable object) in a timeout. Raises `tornado.util.TimeoutError` if the input future does not complete before ``timeout``, which may be specified in any form allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time relative to `.IOLoop.time`) If the wrapped `.Future` fails after it has timed out, the exception will be logged unless it is either of a type contained in ``quiet_exceptions`` (which may be an exception type or a sequence of types), or an ``asyncio.CancelledError``. The wrapped `.Future` is not canceled when the timeout expires, permitting it to be reused. `asyncio.wait_for` is similar to this function but it does cancel the wrapped `.Future` on timeout. .. versionadded:: 4.0 .. versionchanged:: 4.1 Added the ``quiet_exceptions`` argument and the logging of unhandled exceptions. .. versionchanged:: 4.4 Added support for yieldable objects other than `.Future`. .. versionchanged:: 6.0.3 ``asyncio.CancelledError`` is now always considered "quiet". .. versionchanged:: 6.2 ``tornado.util.TimeoutError`` is now an alias to ``asyncio.TimeoutError``. """ # It's tempting to optimize this by cancelling the input future on timeout # instead of creating a new one, but A) we can't know if we are the only # one waiting on the input future, so cancelling it might disrupt other # callers and B) concurrent futures can only be cancelled while they are # in the queue, so cancellation cannot reliably bound our waiting time. future_converted = convert_yielded(future) result = _create_future() chain_future(future_converted, result) io_loop = IOLoop.current() def error_callback(future: Future) -> None: try: future.result() except asyncio.CancelledError: pass except Exception as e: if not isinstance(e, quiet_exceptions): app_log.error( "Exception in Future %r after timeout", future, exc_info=True ) def timeout_callback() -> None: if not result.done(): result.set_exception(TimeoutError("Timeout")) # In case the wrapped future goes on to fail, log it. future_add_done_callback(future_converted, error_callback) timeout_handle = io_loop.add_timeout(timeout, timeout_callback) if isinstance(future_converted, Future): # We know this future will resolve on the IOLoop, so we don't # need the extra thread-safety of IOLoop.add_future (and we also # don't care about StackContext here. future_add_done_callback( future_converted, lambda future: io_loop.remove_timeout(timeout_handle) ) else: # concurrent.futures.Futures may resolve on any thread, so we # need to route them back to the IOLoop. io_loop.add_future( future_converted, lambda future: io_loop.remove_timeout(timeout_handle) ) return result def sleep(duration: float) -> "Future[None]": """Return a `.Future` that resolves after the given number of seconds. When used with ``yield`` in a coroutine, this is a non-blocking analogue to `time.sleep` (which should not be used in coroutines because it is blocking):: yield gen.sleep(0.5) Note that calling this function on its own does nothing; you must wait on the `.Future` it returns (usually by yielding it). .. versionadded:: 4.1 """ f = _create_future() IOLoop.current().call_later( duration, lambda: future_set_result_unless_cancelled(f, None) ) return f
WaitIterator
python
pypa__pipenv
pipenv/patched/pip/_internal/exceptions.py
{ "start": 1776, "end": 5448 }
class ____(PipError): """An error, that presents diagnostic information to the user. This contains a bunch of logic, to enable pretty presentation of our error messages. Each error gets a unique reference. Each error can also include additional context, a hint and/or a note -- which are presented with the main error message in a consistent style. This is adapted from the error output styling in `sphinx-theme-builder`. """ reference: str def __init__( self, *, kind: 'Literal["error", "warning"]' = "error", reference: Optional[str] = None, message: Union[str, Text], context: Optional[Union[str, Text]], hint_stmt: Optional[Union[str, Text]], note_stmt: Optional[Union[str, Text]] = None, link: Optional[str] = None, ) -> None: # Ensure a proper reference is provided. if reference is None: assert hasattr(self, "reference"), "error reference not provided!" reference = self.reference assert _is_kebab_case(reference), "error reference must be kebab-case!" self.kind = kind self.reference = reference self.message = message self.context = context self.note_stmt = note_stmt self.hint_stmt = hint_stmt self.link = link super().__init__(f"<{self.__class__.__name__}: {self.reference}>") def __repr__(self) -> str: return ( f"<{self.__class__.__name__}(" f"reference={self.reference!r}, " f"message={self.message!r}, " f"context={self.context!r}, " f"note_stmt={self.note_stmt!r}, " f"hint_stmt={self.hint_stmt!r}" ")>" ) def __rich_console__( self, console: Console, options: ConsoleOptions, ) -> RenderResult: colour = "red" if self.kind == "error" else "yellow" yield f"[{colour} bold]{self.kind}[/]: [bold]{self.reference}[/]" yield "" if not options.ascii_only: # Present the main message, with relevant context indented. if self.context is not None: yield _prefix_with_indent( self.message, console, prefix=f"[{colour}]×[/] ", indent=f"[{colour}]│[/] ", ) yield _prefix_with_indent( self.context, console, prefix=f"[{colour}]╰─>[/] ", indent=f"[{colour}] [/] ", ) else: yield _prefix_with_indent( self.message, console, prefix="[red]×[/] ", indent=" ", ) else: yield self.message if self.context is not None: yield "" yield self.context if self.note_stmt is not None or self.hint_stmt is not None: yield "" if self.note_stmt is not None: yield _prefix_with_indent( self.note_stmt, console, prefix="[magenta bold]note[/]: ", indent=" ", ) if self.hint_stmt is not None: yield _prefix_with_indent( self.hint_stmt, console, prefix="[cyan bold]hint[/]: ", indent=" ", ) if self.link is not None: yield "" yield f"Link: {self.link}" # # Actual Errors #
DiagnosticPipError
python
sympy__sympy
sympy/vector/basisdependent.py
{ "start": 536, "end": 5578 }
class ____(Expr): """ Super class containing functionality common to vectors and dyadics. Named so because the representation of these quantities in sympy.vector is dependent on the basis they are expressed in. """ zero: BasisDependentZero @call_highest_priority('__radd__') def __add__(self, other): return self._add_func(self, other) @call_highest_priority('__add__') def __radd__(self, other): return self._add_func(other, self) @call_highest_priority('__rsub__') def __sub__(self, other): return self._add_func(self, -other) @call_highest_priority('__sub__') def __rsub__(self, other): return self._add_func(other, -self) @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __mul__(self, other): return self._mul_func(self, other) @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmul__(self, other): return self._mul_func(other, self) def __neg__(self): return self._mul_func(S.NegativeOne, self) @_sympifyit('other', NotImplemented) @call_highest_priority('__rtruediv__') def __truediv__(self, other): return self._div_helper(other) @call_highest_priority('__truediv__') def __rtruediv__(self, other): return TypeError("Invalid divisor for division") def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): """ Implements the SymPy evalf routine for this quantity. evalf's documentation ===================== """ options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict, 'quad':quad, 'verbose':verbose} vec = self.zero for k, v in self.components.items(): vec += v.evalf(n, **options) * k return vec evalf.__doc__ += Expr.evalf.__doc__ # type: ignore n = evalf # type: ignore def simplify(self, **kwargs): """ Implements the SymPy simplify routine for this quantity. simplify's documentation ======================== """ simp_components = [simp(v, **kwargs) * k for k, v in self.components.items()] return self._add_func(*simp_components) simplify.__doc__ += simp.__doc__ # type: ignore def trigsimp(self, **opts): """ Implements the SymPy trigsimp routine, for this quantity. trigsimp's documentation ======================== """ trig_components = [tsimp(v, **opts) * k for k, v in self.components.items()] return self._add_func(*trig_components) trigsimp.__doc__ += tsimp.__doc__ # type: ignore def _eval_simplify(self, **kwargs): return self.simplify(**kwargs) def _eval_trigsimp(self, **opts): return self.trigsimp(**opts) def _eval_derivative(self, wrt): return self.diff(wrt) def _eval_Integral(self, *symbols, **assumptions): integral_components = [Integral(v, *symbols, **assumptions) * k for k, v in self.components.items()] return self._add_func(*integral_components) def as_numer_denom(self): """ Returns the expression as a tuple wrt the following transformation - expression -> a/b -> a, b """ return self, S.One def factor(self, *args, **kwargs): """ Implements the SymPy factor routine, on the scalar parts of a basis-dependent expression. factor's documentation ======================== """ fctr_components = [fctr(v, *args, **kwargs) * k for k, v in self.components.items()] return self._add_func(*fctr_components) factor.__doc__ += fctr.__doc__ # type: ignore def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product.""" return (S.One, self) def as_coeff_add(self, *deps): """Efficiently extract the coefficient of a summation.""" return 0, tuple(x * self.components[x] for x in self.components) def diff(self, *args, **kwargs): """ Implements the SymPy diff routine, for vectors. diff's documentation ======================== """ for x in args: if isinstance(x, BasisDependent): raise TypeError("Invalid arg for differentiation") diff_components = [df(v, *args, **kwargs) * k for k, v in self.components.items()] return self._add_func(*diff_components) diff.__doc__ += df.__doc__ # type: ignore def doit(self, **hints): """Calls .doit() on each term in the Dyadic""" doit_components = [self.components[x].doit(**hints) * x for x in self.components] return self._add_func(*doit_components)
BasisDependent
python
catalyst-team__catalyst
catalyst/metrics/_metric.py
{ "start": 3056, "end": 4894 }
class ____(IMetric): """Interface for all loader-based Metrics. Args: compute_on_call: Computes and returns metric value during metric call. Used for per-batch logging. default: ``True`` prefix: metrics prefix suffix: metrics suffix """ def __init__( self, compute_on_call: bool = True, prefix: str = None, suffix: str = None ): """Init.""" super().__init__(compute_on_call=compute_on_call) self.prefix = prefix or "" self.suffix = suffix or "" @abstractmethod def reset(self, num_batches: int, num_samples: int) -> None: """Resets the metric to it's initial state. By default, this is called at the start of each loader (`on_loader_start` event). Args: num_batches: number of expected batches. num_samples: number of expected samples. """ pass @abstractmethod def update(self, *args, **kwargs) -> None: """Updates the metrics state using the passed data. By default, this is called at the end of each batch (`on_batch_end` event). Args: *args: some args :) **kwargs: some kwargs ;) """ pass @abstractmethod def compute_key_value(self) -> Dict[str, float]: """Computes the metric based on it's accumulated state. By default, this is called at the end of each loader (`on_loader_end` event). Returns: Dict: computed value in key-value format. # noqa: DAR202 """ # @TODO: could be refactored - we need custom exception here # we need this method only for callback metric logging pass __all__ = ["IMetric", "ICallbackBatchMetric", "ICallbackLoaderMetric"]
ICallbackLoaderMetric
python
facelessuser__pymdown-extensions
pymdownx/betterem.py
{ "start": 10365, "end": 12491 }
class ____(Extension): """Add extension to Markdown class.""" def __init__(self, *args, **kwargs): """Initialize.""" self.config = { 'smart_enable': ["underscore", "Treat connected words intelligently - Default: underscore"] } super().__init__(*args, **kwargs) def extendMarkdown(self, md): """Modify inline patterns.""" # Not better yet, so let's make it better md.registerExtension(self) self.make_better(md) def make_better(self, md): """ Configure all the pattern rules. This should be used instead of smart_strong package. pymdownx.extra should be used in place of markdown.extensions.extra. """ config = self.getConfigs() enabled = config["smart_enable"] enable_all = enabled == "all" enable_under = enabled == "underscore" or enable_all enable_star = enabled == "asterisk" or enable_all # If we don't have to move an existing extension, use the same priority, # but if we do have to, move it closely to the relative needed position. md.inlinePatterns.deregister('not_strong', False) md.inlinePatterns.deregister('strong_em', False) md.inlinePatterns.deregister('em_strong', False) md.inlinePatterns.deregister('em_strong2', False) md.inlinePatterns.deregister('strong', False) md.inlinePatterns.deregister('emphasis', False) md.inlinePatterns.deregister('strong2', False) md.inlinePatterns.deregister('emphasis2', False) md.inlinePatterns.register(SimpleTextInlineProcessor(NOT_STRONG), 'not_strong', 70) asterisk = SmartAsteriskProcessor(r'\*') if enable_star else AsteriskProcessor(r'\*') md.inlinePatterns.register(asterisk, "strong_em", 50) underscore = SmartUnderscoreProcessor('_') if enable_under else UnderscoreProcessor('_') md.inlinePatterns.register(underscore, "strong_em2", 40) def makeExtension(*args, **kwargs): """Return extension.""" return BetterEmExtension(*args, **kwargs)
BetterEmExtension
python
ray-project__ray
python/ray/tune/examples/mnist_ptl_mini.py
{ "start": 1647, "end": 5527 }
class ____(pl.LightningModule): def __init__(self, config, data_dir=None): super(LightningMNISTClassifier, self).__init__() self.data_dir = data_dir or os.getcwd() self.lr = config["lr"] layer_1, layer_2 = config["layer_1"], config["layer_2"] self.batch_size = config["batch_size"] # mnist images are (1, 28, 28) (channels, width, height) self.layer_1 = torch.nn.Linear(28 * 28, layer_1) self.layer_2 = torch.nn.Linear(layer_1, layer_2) self.layer_3 = torch.nn.Linear(layer_2, 10) self.accuracy = Accuracy(task="multiclass", num_classes=10, top_k=1) def forward(self, x): batch_size, channels, width, height = x.size() x = x.view(batch_size, -1) x = self.layer_1(x) x = torch.relu(x) x = self.layer_2(x) x = torch.relu(x) x = self.layer_3(x) x = torch.log_softmax(x, dim=1) return x def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.lr) def training_step(self, train_batch, batch_idx): x, y = train_batch logits = self.forward(x) loss = F.nll_loss(logits, y) acc = self.accuracy(logits, y) self.log("ptl/train_loss", loss) self.log("ptl/train_accuracy", acc) return loss def validation_step(self, val_batch, batch_idx): x, y = val_batch logits = self.forward(x) loss = F.nll_loss(logits, y) acc = self.accuracy(logits, y) return {"val_loss": loss, "val_accuracy": acc} def validation_epoch_end(self, outputs): avg_loss = torch.stack([x["val_loss"] for x in outputs]).mean() avg_acc = torch.stack([x["val_accuracy"] for x in outputs]).mean() self.log("ptl/val_loss", avg_loss) self.log("ptl/val_accuracy", avg_acc) def train_mnist_tune(config, num_epochs=10, num_gpus=0): data_dir = os.path.abspath("./data") model = LightningMNISTClassifier(config, data_dir) with FileLock(os.path.expanduser("~/.data.lock")): dm = MNISTDataModule(data_dir=data_dir, batch_size=config["batch_size"]) metrics = {"loss": "ptl/val_loss", "acc": "ptl/val_accuracy"} trainer = pl.Trainer( max_epochs=num_epochs, # If fractional GPUs passed in, convert to int. gpus=math.ceil(num_gpus), enable_progress_bar=False, callbacks=[ TuneReportCheckpointCallback( metrics, on="validation_end", save_checkpoints=False ) ], ) trainer.fit(model, dm) def tune_mnist(num_samples=10, num_epochs=10, gpus_per_trial=0): config = { "layer_1": tune.choice([32, 64, 128]), "layer_2": tune.choice([64, 128, 256]), "lr": tune.loguniform(1e-4, 1e-1), "batch_size": tune.choice([32, 64, 128]), } trainable = tune.with_parameters( train_mnist_tune, num_epochs=num_epochs, num_gpus=gpus_per_trial ) tuner = tune.Tuner( tune.with_resources(trainable, resources={"cpu": 1, "gpu": gpus_per_trial}), tune_config=tune.TuneConfig( metric="loss", mode="min", num_samples=num_samples, ), run_config=tune.RunConfig( name="tune_mnist", ), param_space=config, ) results = tuner.fit() print("Best hyperparameters found were: ", results.get_best_result().config) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument( "--smoke-test", action="store_true", help="Finish quickly for testing" ) args, _ = parser.parse_known_args() if args.smoke_test: tune_mnist(num_samples=1, num_epochs=1, gpus_per_trial=0) else: tune_mnist(num_samples=10, num_epochs=10, gpus_per_trial=0)
LightningMNISTClassifier
python
zarr-developers__zarr-python
src/zarr/core/indexing.py
{ "start": 21631, "end": 24468 }
class ____: dim_sel: npt.NDArray[np.bool_] dim_len: int dim_chunk_len: int nchunks: int chunk_nitems: npt.NDArray[Any] chunk_nitems_cumsum: npt.NDArray[Any] nitems: int dim_chunk_ixs: npt.NDArray[np.intp] def __init__(self, dim_sel: npt.NDArray[np.bool_], dim_len: int, dim_chunk_len: int) -> None: # check number of dimensions if not is_bool_array(dim_sel, 1): raise IndexError("Boolean arrays in an orthogonal selection must be 1-dimensional only") # check shape if dim_sel.shape[0] != dim_len: raise IndexError( f"Boolean array has the wrong length for dimension; expected {dim_len}, got {dim_sel.shape[0]}" ) # precompute number of selected items for each chunk nchunks = ceildiv(dim_len, dim_chunk_len) chunk_nitems = np.zeros(nchunks, dtype="i8") for dim_chunk_ix in range(nchunks): dim_offset = dim_chunk_ix * dim_chunk_len chunk_nitems[dim_chunk_ix] = np.count_nonzero( dim_sel[dim_offset : dim_offset + dim_chunk_len] ) chunk_nitems_cumsum = np.cumsum(chunk_nitems) nitems = chunk_nitems_cumsum[-1] dim_chunk_ixs = np.nonzero(chunk_nitems)[0] # store attributes object.__setattr__(self, "dim_sel", dim_sel) object.__setattr__(self, "dim_len", dim_len) object.__setattr__(self, "dim_chunk_len", dim_chunk_len) object.__setattr__(self, "nchunks", nchunks) object.__setattr__(self, "chunk_nitems", chunk_nitems) object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum) object.__setattr__(self, "nitems", nitems) object.__setattr__(self, "dim_chunk_ixs", dim_chunk_ixs) def __iter__(self) -> Iterator[ChunkDimProjection]: # iterate over chunks with at least one item for dim_chunk_ix in self.dim_chunk_ixs: # find region in chunk dim_offset = dim_chunk_ix * self.dim_chunk_len dim_chunk_sel = self.dim_sel[dim_offset : dim_offset + self.dim_chunk_len] # pad out if final chunk if dim_chunk_sel.shape[0] < self.dim_chunk_len: tmp = np.zeros(self.dim_chunk_len, dtype=bool) tmp[: dim_chunk_sel.shape[0]] = dim_chunk_sel dim_chunk_sel = tmp # find region in output if dim_chunk_ix == 0: start = 0 else: start = self.chunk_nitems_cumsum[dim_chunk_ix - 1] stop = self.chunk_nitems_cumsum[dim_chunk_ix] dim_out_sel = slice(start, stop) is_complete_chunk = False # TODO yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk)
BoolArrayDimIndexer
python
apache__airflow
airflow-core/tests/unit/always/test_project_structure.py
{ "start": 37720, "end": 39988 }
class ____(ExampleCoverageTest): PROVIDER = "amazon" CLASS_DIRS = ProjectStructureTest.CLASS_DIRS BASE_CLASSES = { "airflow.providers.amazon.aws.operators.base_aws.AwsBaseOperator", "airflow.providers.amazon.aws.operators.rds.RdsBaseOperator", "airflow.providers.amazon.aws.operators.sagemaker.SageMakerBaseOperator", "airflow.providers.amazon.aws.sensors.base_aws.AwsBaseSensor", "airflow.providers.amazon.aws.sensors.bedrock.BedrockBaseSensor", "airflow.providers.amazon.aws.sensors.dms.DmsTaskBaseSensor", "airflow.providers.amazon.aws.sensors.emr.EmrBaseSensor", "airflow.providers.amazon.aws.sensors.rds.RdsBaseSensor", "airflow.providers.amazon.aws.sensors.sagemaker.SageMakerBaseSensor", "airflow.providers.amazon.aws.operators.appflow.AppflowBaseOperator", "airflow.providers.amazon.aws.operators.ecs.EcsBaseOperator", "airflow.providers.amazon.aws.sensors.ecs.EcsBaseSensor", "airflow.providers.amazon.aws.sensors.eks.EksBaseSensor", "airflow.providers.amazon.aws.transfers.base.AwsToAwsBaseOperator", "airflow.providers.amazon.aws.operators.comprehend.ComprehendBaseOperator", "airflow.providers.amazon.aws.sensors.comprehend.ComprehendBaseSensor", "airflow.providers.amazon.aws.sensors.kinesis_analytics.KinesisAnalyticsV2BaseSensor", } MISSING_EXAMPLES_FOR_CLASSES = { # S3 Exasol transfer difficult to test, see: https://github.com/apache/airflow/issues/22632 "airflow.providers.amazon.aws.transfers.exasol_to_s3.ExasolToS3Operator", # These operations take a lot of time, there are commented out in the system tests for this reason "airflow.providers.amazon.aws.operators.dms.DmsStartReplicationOperator", "airflow.providers.amazon.aws.operators.dms.DmsStopReplicationOperator", # These modules are used in the SageMakerNotebookOperator and therefore don't have their own examples "airflow.providers.amazon.aws.sensors.sagemaker_unified_studio.SageMakerNotebookSensor", } DEPRECATED_CLASSES = { "airflow.providers.amazon.aws.operators.lambda_function.AwsLambdaInvokeFunctionOperator", }
TestAmazonProviderProjectStructure
python
eventlet__eventlet
eventlet/support/stacklesss.py
{ "start": 651, "end": 1357 }
class ____: def __init__(self, run=None, parent=None): self.dead = False if parent is None: parent = getcurrent() self.parent = parent if run is not None: self.run = run self.switch = FirstSwitch(self) def switch(self, *args): # print("switch", args) global caller caller = stackless.getcurrent() coro_args[self] = args self.t.insert() stackless.schedule() if caller is not self.t: caller.remove() rval = coro_args[self] return rval def run(self): pass def __bool__(self): return self.run is None and not self.dead
greenlet
python
pandas-dev__pandas
pandas/tests/indexing/multiindex/test_slice.py
{ "start": 326, "end": 27152 }
class ____: def test_per_axis_per_level_getitem(self): # GH6134 # example test case ix = MultiIndex.from_product( [_mklbl("A", 5), _mklbl("B", 7), _mklbl("C", 4), _mklbl("D", 2)] ) df = DataFrame(np.arange(len(ix.to_numpy())), index=ix) result = df.loc[(slice("A1", "A3"), slice(None), ["C1", "C3"]), :] expected = df.loc[ [ ( a, b, c, d, ) for a, b, c, d in df.index.values if a in ("A1", "A2", "A3") and c in ("C1", "C3") ] ] tm.assert_frame_equal(result, expected) expected = df.loc[ [ ( a, b, c, d, ) for a, b, c, d in df.index.values if a in ("A1", "A2", "A3") and c in ("C1", "C2", "C3") ] ] result = df.loc[(slice("A1", "A3"), slice(None), slice("C1", "C3")), :] tm.assert_frame_equal(result, expected) # test multi-index slicing with per axis and per index controls index = MultiIndex.from_tuples( [("A", 1), ("A", 2), ("A", 3), ("B", 1)], names=["one", "two"] ) columns = MultiIndex.from_tuples( [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], names=["lvl0", "lvl1"], ) df = DataFrame( np.arange(16, dtype="int64").reshape(4, 4), index=index, columns=columns ) df = df.sort_index(axis=0).sort_index(axis=1) # identity result = df.loc[(slice(None), slice(None)), :] tm.assert_frame_equal(result, df) result = df.loc[(slice(None), slice(None)), (slice(None), slice(None))] tm.assert_frame_equal(result, df) result = df.loc[:, (slice(None), slice(None))] tm.assert_frame_equal(result, df) # index result = df.loc[(slice(None), [1]), :] expected = df.iloc[[0, 3]] tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), 1), :] expected = df.iloc[[0, 3]] tm.assert_frame_equal(result, expected) # columns result = df.loc[:, (slice(None), ["foo"])] expected = df.iloc[:, [1, 3]] tm.assert_frame_equal(result, expected) # both result = df.loc[(slice(None), 1), (slice(None), ["foo"])] expected = df.iloc[[0, 3], [1, 3]] tm.assert_frame_equal(result, expected) result = df.loc["A", "a"] expected = DataFrame( {"bar": [1, 5, 9], "foo": [0, 4, 8]}, index=Index([1, 2, 3], name="two"), columns=Index(["bar", "foo"], name="lvl1"), ) tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), [1, 2]), :] expected = df.iloc[[0, 1, 3]] tm.assert_frame_equal(result, expected) # multi-level series s = Series(np.arange(len(ix.to_numpy())), index=ix) result = s.loc["A1":"A3", :, ["C1", "C3"]] expected = s.loc[ [ ( a, b, c, d, ) for a, b, c, d in s.index.values if a in ("A1", "A2", "A3") and c in ("C1", "C3") ] ] tm.assert_series_equal(result, expected) # boolean indexers result = df.loc[(slice(None), df.loc[:, ("a", "bar")] > 5), :] expected = df.iloc[[2, 3]] tm.assert_frame_equal(result, expected) msg = ( "cannot index with a boolean indexer " "that is not the same length as the index" ) with pytest.raises(ValueError, match=msg): df.loc[(slice(None), np.array([True, False])), :] with pytest.raises(KeyError, match=r"\[1\] not in index"): # slice(None) is on the index, [1] is on the columns, but 1 is # not in the columns, so we raise # This used to treat [1] as positional GH#16396 df.loc[slice(None), [1]] # not lexsorted assert df.index._lexsort_depth == 2 df = df.sort_index(level=1, axis=0) assert df.index._lexsort_depth == 0 msg = ( "MultiIndex slicing requires the index to be " r"lexsorted: slicing on levels \[1\], lexsort depth 0" ) with pytest.raises(UnsortedIndexError, match=msg): df.loc[(slice(None), slice("bar")), :] # GH 16734: not sorted, but no real slicing result = df.loc[(slice(None), df.loc[:, ("a", "bar")] > 5), :] tm.assert_frame_equal(result, df.iloc[[1, 3], :]) def test_multiindex_slicers_non_unique(self): # GH 7106 # non-unique mi index support df = ( DataFrame( { "A": ["foo", "foo", "foo", "foo"], "B": ["a", "a", "a", "a"], "C": [1, 2, 1, 3], "D": [1, 2, 3, 4], } ) .set_index(["A", "B", "C"]) .sort_index() ) assert not df.index.is_unique expected = ( DataFrame({"A": ["foo", "foo"], "B": ["a", "a"], "C": [1, 1], "D": [1, 3]}) .set_index(["A", "B", "C"]) .sort_index() ) result = df.loc[(slice(None), slice(None), 1), :] tm.assert_frame_equal(result, expected) # this is equivalent of an xs expression result = df.xs(1, level=2, drop_level=False) tm.assert_frame_equal(result, expected) df = ( DataFrame( { "A": ["foo", "foo", "foo", "foo"], "B": ["a", "a", "a", "a"], "C": [1, 2, 1, 2], "D": [1, 2, 3, 4], } ) .set_index(["A", "B", "C"]) .sort_index() ) assert not df.index.is_unique expected = ( DataFrame({"A": ["foo", "foo"], "B": ["a", "a"], "C": [1, 1], "D": [1, 3]}) .set_index(["A", "B", "C"]) .sort_index() ) result = df.loc[(slice(None), slice(None), 1), :] assert not result.index.is_unique tm.assert_frame_equal(result, expected) # GH12896 # numpy-implementation dependent bug ints = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12, 13, 14, 14, 16, 17, 18, 19, 200000, 200000, ] n = len(ints) idx = MultiIndex.from_arrays([["a"] * n, ints]) result = Series([1] * n, index=idx) result = result.sort_index() result = result.loc[(slice(None), slice(100000))] expected = Series([1] * (n - 2), index=idx[:-2]).sort_index() tm.assert_series_equal(result, expected) def test_multiindex_slicers_datetimelike(self): # GH 7429 # buggy/inconsistent behavior when slicing with datetime-like dates = [datetime(2012, 1, 1, 12, 12, 12) + timedelta(days=i) for i in range(6)] freq = [1, 2] index = MultiIndex.from_product([dates, freq], names=["date", "frequency"]) df = DataFrame( np.arange(6 * 2 * 4, dtype="int64").reshape(-1, 4), index=index, columns=list("ABCD"), ) # multi-axis slicing idx = pd.IndexSlice expected = df.iloc[[0, 2, 4], [0, 1]] result = df.loc[ ( slice( Timestamp("2012-01-01 12:12:12"), Timestamp("2012-01-03 12:12:12") ), slice(1, 1), ), slice("A", "B"), ] tm.assert_frame_equal(result, expected) result = df.loc[ ( idx[ Timestamp("2012-01-01 12:12:12") : Timestamp("2012-01-03 12:12:12") ], idx[1:1], ), slice("A", "B"), ] tm.assert_frame_equal(result, expected) result = df.loc[ ( slice( Timestamp("2012-01-01 12:12:12"), Timestamp("2012-01-03 12:12:12") ), 1, ), slice("A", "B"), ] tm.assert_frame_equal(result, expected) # with strings result = df.loc[ (slice("2012-01-01 12:12:12", "2012-01-03 12:12:12"), slice(1, 1)), slice("A", "B"), ] tm.assert_frame_equal(result, expected) result = df.loc[ (idx["2012-01-01 12:12:12":"2012-01-03 12:12:12"], 1), idx["A", "B"] ] tm.assert_frame_equal(result, expected) def test_multiindex_slicers_edges(self): # GH 8132 # various edge cases df = DataFrame( { "A": ["A0"] * 5 + ["A1"] * 5 + ["A2"] * 5, "B": ["B0", "B0", "B1", "B1", "B2"] * 3, "DATE": [ "2013-06-11", "2013-07-02", "2013-07-09", "2013-07-30", "2013-08-06", "2013-06-11", "2013-07-02", "2013-07-09", "2013-07-30", "2013-08-06", "2013-09-03", "2013-10-01", "2013-07-09", "2013-08-06", "2013-09-03", ], "VALUES": [22, 35, 14, 9, 4, 40, 18, 4, 2, 5, 1, 2, 3, 4, 2], } ) df["DATE"] = pd.to_datetime(df["DATE"]) df1 = df.set_index(["A", "B", "DATE"]) df1 = df1.sort_index() # A1 - Get all values under "A0" and "A1" result = df1.loc[(slice("A1")), :] expected = df1.iloc[0:10] tm.assert_frame_equal(result, expected) # A2 - Get all values from the start to "A2" result = df1.loc[(slice("A2")), :] expected = df1 tm.assert_frame_equal(result, expected) # A3 - Get all values under "B1" or "B2" result = df1.loc[(slice(None), slice("B1", "B2")), :] expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13, 14]] tm.assert_frame_equal(result, expected) # A4 - Get all values between 2013-07-02 and 2013-07-09 result = df1.loc[(slice(None), slice(None), slice("20130702", "20130709")), :] expected = df1.iloc[[1, 2, 6, 7, 12]] tm.assert_frame_equal(result, expected) # B1 - Get all values in B0 that are also under A0, A1 and A2 result = df1.loc[(slice("A2"), slice("B0")), :] expected = df1.iloc[[0, 1, 5, 6, 10, 11]] tm.assert_frame_equal(result, expected) # B2 - Get all values in B0, B1 and B2 (similar to what #2 is doing for # the As) result = df1.loc[(slice(None), slice("B2")), :] expected = df1 tm.assert_frame_equal(result, expected) # B3 - Get all values from B1 to B2 and up to 2013-08-06 result = df1.loc[(slice(None), slice("B1", "B2"), slice("2013-08-06")), :] expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13]] tm.assert_frame_equal(result, expected) # B4 - Same as A4 but the start of the date slice is not a key. # shows indexing on a partial selection slice result = df1.loc[(slice(None), slice(None), slice("20130701", "20130709")), :] expected = df1.iloc[[1, 2, 6, 7, 12]] tm.assert_frame_equal(result, expected) def test_per_axis_per_level_doc_examples(self): # test index maker idx = pd.IndexSlice # from indexing.rst / advanced index = MultiIndex.from_product( [_mklbl("A", 4), _mklbl("B", 2), _mklbl("C", 4), _mklbl("D", 2)] ) columns = MultiIndex.from_tuples( [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], names=["lvl0", "lvl1"], ) df = DataFrame( np.arange(len(index) * len(columns), dtype="int64").reshape( (len(index), len(columns)) ), index=index, columns=columns, ) result = df.loc[(slice("A1", "A3"), slice(None), ["C1", "C3"]), :] expected = df.loc[ [ ( a, b, c, d, ) for a, b, c, d in df.index.values if a in ("A1", "A2", "A3") and c in ("C1", "C3") ] ] tm.assert_frame_equal(result, expected) result = df.loc[idx["A1":"A3", :, ["C1", "C3"]], :] tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), slice(None), ["C1", "C3"]), :] expected = df.loc[ [ ( a, b, c, d, ) for a, b, c, d in df.index.values if c in ("C1", "C3") ] ] tm.assert_frame_equal(result, expected) result = df.loc[idx[:, :, ["C1", "C3"]], :] tm.assert_frame_equal(result, expected) # not sorted msg = ( "MultiIndex slicing requires the index to be lexsorted: " r"slicing on levels \[1\], lexsort depth 1" ) with pytest.raises(UnsortedIndexError, match=msg): df.loc["A1", ("a", slice("foo"))] # GH 16734: not sorted, but no real slicing tm.assert_frame_equal( df.loc["A1", (slice(None), "foo")], df.loc["A1"].iloc[:, [0, 2]] ) df = df.sort_index(axis=1) # slicing df.loc["A1", (slice(None), "foo")] df.loc[(slice(None), slice(None), ["C1", "C3"]), (slice(None), "foo")] # setitem df.loc(axis=0)[:, :, ["C1", "C3"]] = -10 def test_loc_axis_arguments(self): index = MultiIndex.from_product( [_mklbl("A", 4), _mklbl("B", 2), _mklbl("C", 4), _mklbl("D", 2)] ) columns = MultiIndex.from_tuples( [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], names=["lvl0", "lvl1"], ) df = ( DataFrame( np.arange(len(index) * len(columns), dtype="int64").reshape( (len(index), len(columns)) ), index=index, columns=columns, ) .sort_index() .sort_index(axis=1) ) # axis 0 result = df.loc(axis=0)["A1":"A3", :, ["C1", "C3"]] expected = df.loc[ [ ( a, b, c, d, ) for a, b, c, d in df.index.values if a in ("A1", "A2", "A3") and c in ("C1", "C3") ] ] tm.assert_frame_equal(result, expected) result = df.loc(axis="index")[:, :, ["C1", "C3"]] expected = df.loc[ [ ( a, b, c, d, ) for a, b, c, d in df.index.values if c in ("C1", "C3") ] ] tm.assert_frame_equal(result, expected) # axis 1 result = df.loc(axis=1)[:, "foo"] expected = df.loc[:, (slice(None), "foo")] tm.assert_frame_equal(result, expected) result = df.loc(axis="columns")[:, "foo"] expected = df.loc[:, (slice(None), "foo")] tm.assert_frame_equal(result, expected) # invalid axis for i in [-1, 2, "foo"]: msg = f"No axis named {i} for object type DataFrame" with pytest.raises(ValueError, match=msg): df.loc(axis=i)[:, :, ["C1", "C3"]] def test_loc_axis_single_level_multi_col_indexing_multiindex_col_df(self): # GH29519 df = DataFrame( np.arange(27).reshape(3, 9), columns=MultiIndex.from_product([["a1", "a2", "a3"], ["b1", "b2", "b3"]]), ) result = df.loc(axis=1)["a1":"a2"] expected = df.iloc[:, :-3] tm.assert_frame_equal(result, expected) def test_loc_axis_single_level_single_col_indexing_multiindex_col_df(self): # GH29519 df = DataFrame( np.arange(27).reshape(3, 9), columns=MultiIndex.from_product([["a1", "a2", "a3"], ["b1", "b2", "b3"]]), ) result = df.loc(axis=1)["a1"] expected = df.iloc[:, :3] expected.columns = ["b1", "b2", "b3"] tm.assert_frame_equal(result, expected) def test_loc_ax_single_level_indexer_simple_df(self): # GH29519 # test single level indexing on single index column data frame df = DataFrame(np.arange(9).reshape(3, 3), columns=["a", "b", "c"]) result = df.loc(axis=1)["a"] expected = Series(np.array([0, 3, 6]), name="a") tm.assert_series_equal(result, expected) def test_per_axis_per_level_setitem(self): # test index maker idx = pd.IndexSlice # test multi-index slicing with per axis and per index controls index = MultiIndex.from_tuples( [("A", 1), ("A", 2), ("A", 3), ("B", 1)], names=["one", "two"] ) columns = MultiIndex.from_tuples( [("a", "foo"), ("a", "bar"), ("b", "foo"), ("b", "bah")], names=["lvl0", "lvl1"], ) df_orig = DataFrame( np.arange(16, dtype="int64").reshape(4, 4), index=index, columns=columns ) df_orig = df_orig.sort_index(axis=0).sort_index(axis=1) # identity df = df_orig.copy() df.loc[(slice(None), slice(None)), :] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc(axis=0)[:, :] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), slice(None)), (slice(None), slice(None))] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[:, (slice(None), slice(None))] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) # index df = df_orig.copy() df.loc[(slice(None), [1]), :] = 100 expected = df_orig.copy() expected.iloc[[0, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), 1), :] = 100 expected = df_orig.copy() expected.iloc[[0, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc(axis=0)[:, 1] = 100 expected = df_orig.copy() expected.iloc[[0, 3]] = 100 tm.assert_frame_equal(df, expected) # columns df = df_orig.copy() df.loc[:, (slice(None), ["foo"])] = 100 expected = df_orig.copy() expected.iloc[:, [1, 3]] = 100 tm.assert_frame_equal(df, expected) # both df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ["foo"])] = 100 expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[idx[:, 1], idx[:, ["foo"]]] = 100 expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc["A", "a"] = 100 expected = df_orig.copy() expected.iloc[0:3, 0:2] = 100 tm.assert_frame_equal(df, expected) # setting with a list-like df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array( [[100, 100], [100, 100]], dtype="int64" ) expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = 100 tm.assert_frame_equal(df, expected) # not enough values df = df_orig.copy() msg = "setting an array element with a sequence." with pytest.raises(ValueError, match=msg): df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array( [[100], [100, 100]], dtype="int64" ) msg = "Must have equal len keys and value when setting with an iterable" with pytest.raises(ValueError, match=msg): df.loc[(slice(None), 1), (slice(None), ["foo"])] = np.array( [100, 100, 100, 100], dtype="int64" ) # with an alignable rhs df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ["foo"])] = ( df.loc[(slice(None), 1), (slice(None), ["foo"])] * 5 ) expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = expected.iloc[[0, 3], [1, 3]] * 5 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ["foo"])] *= df.loc[ (slice(None), 1), (slice(None), ["foo"]) ] expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]] tm.assert_frame_equal(df, expected) rhs = df_orig.loc[(slice(None), 1), (slice(None), ["foo"])].copy() rhs.loc[:, ("c", "bah")] = 10 df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ["foo"])] *= rhs expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]] tm.assert_frame_equal(df, expected) def test_multiindex_label_slicing_with_negative_step(self): ser = Series( np.arange(20), MultiIndex.from_product([list("abcde"), np.arange(4)]) ) SLC = pd.IndexSlice tm.assert_indexing_slices_equivalent(ser, SLC[::-1], SLC[::-1]) tm.assert_indexing_slices_equivalent(ser, SLC["d"::-1], SLC[15::-1]) tm.assert_indexing_slices_equivalent(ser, SLC[("d",) :: -1], SLC[15::-1]) tm.assert_indexing_slices_equivalent(ser, SLC[:"d":-1], SLC[:11:-1]) tm.assert_indexing_slices_equivalent(ser, SLC[: ("d",) : -1], SLC[:11:-1]) tm.assert_indexing_slices_equivalent(ser, SLC["d":"b":-1], SLC[15:3:-1]) tm.assert_indexing_slices_equivalent(ser, SLC[("d",) : "b" : -1], SLC[15:3:-1]) tm.assert_indexing_slices_equivalent(ser, SLC["d" : ("b",) : -1], SLC[15:3:-1]) tm.assert_indexing_slices_equivalent( ser, SLC[("d",) : ("b",) : -1], SLC[15:3:-1] ) tm.assert_indexing_slices_equivalent(ser, SLC["b":"d":-1], SLC[:0]) tm.assert_indexing_slices_equivalent(ser, SLC[("c", 2) :: -1], SLC[10::-1]) tm.assert_indexing_slices_equivalent(ser, SLC[: ("c", 2) : -1], SLC[:9:-1]) tm.assert_indexing_slices_equivalent( ser, SLC[("e", 0) : ("c", 2) : -1], SLC[16:9:-1] ) def test_multiindex_slice_first_level(self): # GH 12697 freq = ["a", "b", "c", "d"] idx = MultiIndex.from_product([freq, range(500)]) df = DataFrame(list(range(2000)), index=idx, columns=["Test"]) df_slice = df.loc[pd.IndexSlice[:, 30:70], :] result = df_slice.loc["a"] expected = DataFrame(list(range(30, 71)), columns=["Test"], index=range(30, 71)) tm.assert_frame_equal(result, expected) result = df_slice.loc["d"] expected = DataFrame( list(range(1530, 1571)), columns=["Test"], index=range(30, 71) ) tm.assert_frame_equal(result, expected) def test_int_series_slicing(self, multiindex_year_month_day_dataframe_random_data): ymd = multiindex_year_month_day_dataframe_random_data s = ymd["A"] result = s[5:] expected = s.reindex(s.index[5:]) tm.assert_series_equal(result, expected) s = ymd["A"].copy() exp = ymd["A"].copy() s[5:] = 0 exp.iloc[5:] = 0 tm.assert_numpy_array_equal(s.values, exp.values) result = ymd[5:] expected = ymd.reindex(s.index[5:]) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "dtype, loc, iloc", [ # dtype = int, step = -1 ("int", slice(None, None, -1), slice(None, None, -1)), ("int", slice(3, None, -1), slice(3, None, -1)), ("int", slice(None, 1, -1), slice(None, 0, -1)), ("int", slice(3, 1, -1), slice(3, 0, -1)), # dtype = int, step = -2 ("int", slice(None, None, -2), slice(None, None, -2)), ("int", slice(3, None, -2), slice(3, None, -2)), ("int", slice(None, 1, -2), slice(None, 0, -2)), ("int", slice(3, 1, -2), slice(3, 0, -2)), # dtype = str, step = -1 ("str", slice(None, None, -1), slice(None, None, -1)), ("str", slice("d", None, -1), slice(3, None, -1)), ("str", slice(None, "b", -1), slice(None, 0, -1)), ("str", slice("d", "b", -1), slice(3, 0, -1)), # dtype = str, step = -2 ("str", slice(None, None, -2), slice(None, None, -2)), ("str", slice("d", None, -2), slice(3, None, -2)), ("str", slice(None, "b", -2), slice(None, 0, -2)), ("str", slice("d", "b", -2), slice(3, 0, -2)), ], ) def test_loc_slice_negative_stepsize(self, dtype, loc, iloc): # GH#38071 labels = { "str": list("abcde"), "int": range(5), }[dtype] mi = MultiIndex.from_arrays([labels] * 2) df = DataFrame(1.0, index=mi, columns=["A"]) SLC = pd.IndexSlice expected = df.iloc[iloc, :] result_get_loc = df.loc[SLC[loc], :] result_get_locs_level_0 = df.loc[SLC[loc, :], :] result_get_locs_level_1 = df.loc[SLC[:, loc], :] tm.assert_frame_equal(result_get_loc, expected) tm.assert_frame_equal(result_get_locs_level_0, expected) tm.assert_frame_equal(result_get_locs_level_1, expected)
TestMultiIndexSlicers
python
google__pytype
pytype/directors/parser.py
{ "start": 2723, "end": 2789 }
class ____: start: int end: int cases: list[_MatchCase]
_Match
python
plotly__plotly.py
plotly/graph_objs/choroplethmapbox/marker/_line.py
{ "start": 233, "end": 5318 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "choroplethmapbox.marker" _path_str = "choroplethmapbox.marker.line" _valid_props = {"color", "colorsrc", "width", "widthsrc"} @property def color(self): """ Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. 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 - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def colorsrc(self): """ Sets the source reference on Chart Studio Cloud for `color`. The 'colorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["colorsrc"] @colorsrc.setter def colorsrc(self, val): self["colorsrc"] = val @property def width(self): """ Sets the width (in px) of the lines bounding the marker points. The 'width' property is a number and may be specified as: - An int or float in the interval [0, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["width"] @width.setter def width(self, val): self["width"] = val @property def widthsrc(self): """ Sets the source reference on Chart Studio Cloud for `width`. The 'widthsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["widthsrc"] @widthsrc.setter def widthsrc(self, val): self["widthsrc"] = val @property def _prop_descriptions(self): return """\ color Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. colorsrc Sets the source reference on Chart Studio Cloud for `color`. width Sets the width (in px) of the lines bounding the marker points. widthsrc Sets the source reference on Chart Studio Cloud for `width`. """ def __init__( self, arg=None, color=None, colorsrc=None, width=None, widthsrc=None, **kwargs ): """ Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.choroplethmapbox.marker.Line` color Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. colorsrc Sets the source reference on Chart Studio Cloud for `color`. width Sets the width (in px) of the lines bounding the marker points. widthsrc Sets the source reference on Chart Studio Cloud for `width`. Returns ------- Line """ super().__init__("line") 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.choroplethmapbox.marker.Line constructor must be a dict or an instance of :class:`plotly.graph_objs.choroplethmapbox.marker.Line`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("colorsrc", arg, colorsrc) self._set_property("width", arg, width) self._set_property("widthsrc", arg, widthsrc) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Line
python
numba__numba
numba/tests/support.py
{ "start": 27590, "end": 32259 }
class ____(object): """Mixin to mark test for serial execution. """ _numba_parallel_test_ = False # Various helpers @contextlib.contextmanager def override_config(name, value): """ Return a context manager that temporarily sets Numba config variable *name* to *value*. *name* must be the name of an existing variable in numba.config. """ old_value = getattr(config, name) setattr(config, name, value) try: yield finally: setattr(config, name, old_value) @contextlib.contextmanager def override_env_config(name, value): """ Return a context manager that temporarily sets an Numba config environment *name* to *value*. """ old = os.environ.get(name) os.environ[name] = value config.reload_config() try: yield finally: if old is None: # If it wasn't set originally, delete the environ var del os.environ[name] else: # Otherwise, restore to the old value os.environ[name] = old # Always reload config config.reload_config() def compile_function(name, code, globs): """ Given a *code* string, compile it with globals *globs* and return the function named *name*. """ co = compile(code.rstrip(), "<string>", "single") ns = {} eval(co, globs, ns) return ns[name] _trashcan_dir = 'numba-tests' if os.name == 'nt': # Under Windows, gettempdir() points to the user-local temp dir _trashcan_dir = os.path.join(tempfile.gettempdir(), _trashcan_dir) else: # Mix the UID into the directory name to allow different users to # run the test suite without permission errors (issue #1586) _trashcan_dir = os.path.join(tempfile.gettempdir(), "%s.%s" % (_trashcan_dir, os.getuid())) # Stale temporary directories are deleted after they are older than this value. # The test suite probably won't ever take longer than this... _trashcan_timeout = 24 * 3600 # 1 day def _create_trashcan_dir(): try: os.mkdir(_trashcan_dir) except FileExistsError: pass def _purge_trashcan_dir(): freshness_threshold = time.time() - _trashcan_timeout for fn in sorted(os.listdir(_trashcan_dir)): fn = os.path.join(_trashcan_dir, fn) try: st = os.stat(fn) if st.st_mtime < freshness_threshold: shutil.rmtree(fn, ignore_errors=True) except OSError as e: # In parallel testing, several processes can attempt to # remove the same entry at once, ignore. pass def _create_trashcan_subdir(prefix): _purge_trashcan_dir() path = tempfile.mkdtemp(prefix=prefix + '-', dir=_trashcan_dir) return path def temp_directory(prefix): """ Create a temporary directory with the given *prefix* that will survive at least as long as this process invocation. The temporary directory will be eventually deleted when it becomes stale enough. This is necessary because a DLL file can't be deleted while in use under Windows. An interesting side-effect is to be able to inspect the test files shortly after a test suite run. """ _create_trashcan_dir() return _create_trashcan_subdir(prefix) def import_dynamic(modname): """ Import and return a module of the given name. Care is taken to avoid issues due to Python's internal directory caching. """ import importlib importlib.invalidate_caches() __import__(modname) return sys.modules[modname] # From CPython @contextlib.contextmanager def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO.""" orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name, io.StringIO()) try: yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stdout) def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") """ return captured_output("stdout") def captured_stderr(): """Capture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") """ return captured_output("stderr") @contextlib.contextmanager def capture_cache_log(): with captured_stdout() as out: with override_config('DEBUG_CACHE', True): yield out
SerialMixin
python
python__mypy
mypy/semanal_typeddict.py
{ "start": 1366, "end": 26079 }
class ____: def __init__( self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder ) -> None: self.options = options self.api = api self.msg = msg def analyze_typeddict_classdef(self, defn: ClassDef) -> tuple[bool, TypeInfo | None]: """Analyze a class that may define a TypedDict. Assume that base classes have been analyzed already. Note: Unlike normal classes, we won't create a TypeInfo until the whole definition of the TypeDict (including the body and all key names and types) is complete. This is mostly because we store the corresponding TypedDictType in the TypeInfo. Return (is this a TypedDict, new TypeInfo). Specifics: * If we couldn't finish due to incomplete reference anywhere in the definition, return (True, None). * If this is not a TypedDict, return (False, None). """ possible = False for base_expr in defn.base_type_exprs: if isinstance(base_expr, CallExpr): base_expr = base_expr.callee if isinstance(base_expr, IndexExpr): base_expr = base_expr.base if isinstance(base_expr, RefExpr): self.api.accept(base_expr) if base_expr.fullname in TPDICT_NAMES or self.is_typeddict(base_expr): possible = True if isinstance(base_expr.node, TypeInfo) and base_expr.node.is_final: err = message_registry.CANNOT_INHERIT_FROM_FINAL self.fail(err.format(base_expr.node.name).value, defn, code=err.code) if not possible: return False, None existing_info = None if isinstance(defn.analyzed, TypedDictExpr): existing_info = defn.analyzed.info field_types: dict[str, Type] | None if ( len(defn.base_type_exprs) == 1 and isinstance(defn.base_type_exprs[0], RefExpr) and defn.base_type_exprs[0].fullname in TPDICT_NAMES ): # Building a new TypedDict field_types, statements, required_keys, readonly_keys = ( self.analyze_typeddict_classdef_fields(defn) ) if field_types is None: return True, None # Defer if self.api.is_func_scope() and "@" not in defn.name: defn.name += "@" + str(defn.line) info = self.build_typeddict_typeinfo( defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info ) defn.analyzed = TypedDictExpr(info) defn.analyzed.line = defn.line defn.analyzed.column = defn.column defn.defs.body = statements return True, info # Extending/merging existing TypedDicts typeddict_bases: list[Expression] = [] typeddict_bases_set = set() for expr in defn.base_type_exprs: ok, maybe_type_info, _ = self.check_typeddict(expr, None, False) if ok and maybe_type_info is not None: # expr is a CallExpr info = maybe_type_info typeddict_bases_set.add(info.fullname) typeddict_bases.append(expr) elif isinstance(expr, RefExpr) and expr.fullname in TPDICT_NAMES: if "TypedDict" not in typeddict_bases_set: typeddict_bases_set.add("TypedDict") else: self.fail('Duplicate base class "TypedDict"', defn) elif ( isinstance(expr, RefExpr) and self.is_typeddict(expr) or isinstance(expr, IndexExpr) and self.is_typeddict(expr.base) ): info = self._parse_typeddict_base(expr, defn) if info.fullname not in typeddict_bases_set: typeddict_bases_set.add(info.fullname) typeddict_bases.append(expr) else: self.fail(f'Duplicate base class "{info.name}"', defn) else: self.fail("All bases of a new TypedDict must be TypedDict types", defn) field_types = {} required_keys = set() readonly_keys = set() # Iterate over bases in reverse order so that leftmost base class' keys take precedence for base in reversed(typeddict_bases): self.add_keys_and_types_from_base( base, field_types, required_keys, readonly_keys, defn ) (new_field_types, new_statements, new_required_keys, new_readonly_keys) = ( self.analyze_typeddict_classdef_fields(defn, oldfields=field_types) ) if new_field_types is None: return True, None # Defer field_types.update(new_field_types) required_keys.update(new_required_keys) readonly_keys.update(new_readonly_keys) info = self.build_typeddict_typeinfo( defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info ) defn.analyzed = TypedDictExpr(info) defn.analyzed.line = defn.line defn.analyzed.column = defn.column defn.defs.body = new_statements return True, info def add_keys_and_types_from_base( self, base: Expression, field_types: dict[str, Type], required_keys: set[str], readonly_keys: set[str], ctx: Context, ) -> None: info = self._parse_typeddict_base(base, ctx) base_args: list[Type] = [] if isinstance(base, IndexExpr): args = self.analyze_base_args(base, ctx) if args is None: return base_args = args assert info.typeddict_type is not None base_typed_dict = info.typeddict_type base_items = base_typed_dict.items valid_items = base_items.copy() # Always fix invalid bases to avoid crashes. tvars = info.defn.type_vars if len(base_args) != len(tvars): any_kind = TypeOfAny.from_omitted_generics if base_args: self.fail(f'Invalid number of type arguments for "{info.name}"', ctx) any_kind = TypeOfAny.from_error base_args = [AnyType(any_kind) for _ in tvars] with state.strict_optional_set(self.options.strict_optional): valid_items = self.map_items_to_base(valid_items, tvars, base_args) for key in base_items: if key in field_types: self.fail(TYPEDDICT_OVERRIDE_MERGE.format(key), ctx) field_types.update(valid_items) required_keys.update(base_typed_dict.required_keys) readonly_keys.update(base_typed_dict.readonly_keys) def _parse_typeddict_base(self, base: Expression, ctx: Context) -> TypeInfo: if isinstance(base, RefExpr): if isinstance(base.node, TypeInfo): return base.node elif isinstance(base.node, TypeAlias): # Only old TypeAlias / plain assignment, PEP695 `type` stmt # cannot be used as a base class target = get_proper_type(base.node.target) assert isinstance(target, TypedDictType) return target.fallback.type else: assert False elif isinstance(base, IndexExpr): assert isinstance(base.base, RefExpr) return self._parse_typeddict_base(base.base, ctx) else: assert isinstance(base, CallExpr) assert isinstance(base.analyzed, TypedDictExpr) return base.analyzed.info def analyze_base_args(self, base: IndexExpr, ctx: Context) -> list[Type] | None: """Analyze arguments of base type expressions as types. We need to do this, because normal base class processing happens after the TypedDict special-casing (plus we get a custom error message). """ base_args = [] if isinstance(base.index, TupleExpr): args = base.index.items else: args = [base.index] for arg_expr in args: try: type = expr_to_unanalyzed_type(arg_expr, self.options, self.api.is_stub_file) except TypeTranslationError: self.fail("Invalid TypedDict type argument", ctx) return None analyzed = self.api.anal_type( type, allow_typed_dict_special_forms=True, allow_placeholder=not self.api.is_func_scope(), ) if analyzed is None: return None base_args.append(analyzed) return base_args def map_items_to_base( self, valid_items: dict[str, Type], tvars: list[TypeVarLikeType], base_args: list[Type] ) -> dict[str, Type]: """Map item types to how they would look in their base with type arguments applied. Note it is safe to use expand_type() during semantic analysis, because it should never (indirectly) call is_subtype(). """ mapped_items = {} for key in valid_items: type_in_base = valid_items[key] if not tvars: mapped_items[key] = type_in_base continue # TODO: simple zip can't be used for variadic types. mapped_items[key] = expand_type( type_in_base, {t.id: a for (t, a) in zip(tvars, base_args)} ) return mapped_items def analyze_typeddict_classdef_fields( self, defn: ClassDef, oldfields: Collection[str] | None = None ) -> tuple[dict[str, Type] | None, list[Statement], set[str], set[str]]: """Analyze fields defined in a TypedDict class definition. This doesn't consider inherited fields (if any). Also consider totality, if given. Return tuple with these items: * Dict of key -> type (or None if found an incomplete reference -> deferral) * List of statements from defn.defs.body that are legally allowed to be a part of a TypedDict definition * Set of required keys """ fields: dict[str, Type] = {} readonly_keys = set[str]() required_keys = set[str]() statements: list[Statement] = [] total: bool | None = True for key in defn.keywords: if key == "total": total = require_bool_literal_argument( self.api, defn.keywords["total"], "total", True ) continue for_function = ' for "__init_subclass__" of "TypedDict"' self.msg.unexpected_keyword_argument_for_function(for_function, key, defn) for stmt in defn.defs.body: if not isinstance(stmt, AssignmentStmt): # Still allow pass or ... (for empty TypedDict's) and docstrings if isinstance(stmt, PassStmt) or ( isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, (EllipsisExpr, StrExpr)) ): statements.append(stmt) else: defn.removed_statements.append(stmt) self.fail(TPDICT_CLASS_ERROR, stmt) elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr): # An assignment, but an invalid one. defn.removed_statements.append(stmt) self.fail(TPDICT_CLASS_ERROR, stmt) else: name = stmt.lvalues[0].name if name in (oldfields or []): self.fail(f'Overwriting TypedDict field "{name}" while extending', stmt) if name in fields: self.fail(f'Duplicate TypedDict key "{name}"', stmt) continue # Append stmt, name, and type in this case... statements.append(stmt) field_type: Type if stmt.unanalyzed_type is None: field_type = AnyType(TypeOfAny.unannotated) else: analyzed = self.api.anal_type( stmt.unanalyzed_type, allow_typed_dict_special_forms=True, allow_placeholder=not self.api.is_func_scope(), prohibit_self_type="TypedDict item type", prohibit_special_class_field_types="TypedDict", ) if analyzed is None: return None, [], set(), set() # Need to defer field_type = analyzed if not has_placeholder(analyzed): stmt.type = self.extract_meta_info(analyzed, stmt)[0] field_type, required, readonly = self.extract_meta_info(field_type) fields[name] = field_type if (total or required is True) and required is not False: required_keys.add(name) if readonly: readonly_keys.add(name) # ...despite possible minor failures that allow further analysis. if stmt.type is None or hasattr(stmt, "new_syntax") and not stmt.new_syntax: self.fail(TPDICT_CLASS_ERROR, stmt) elif not isinstance(stmt.rvalue, TempNode): # x: int assigns rvalue to TempNode(AnyType()) self.fail("Right hand side values are not supported in TypedDict", stmt) return fields, statements, required_keys, readonly_keys def extract_meta_info( self, typ: Type, context: Context | None = None ) -> tuple[Type, bool | None, bool]: """Unwrap all metadata types.""" is_required = None # default, no modification readonly = False # by default all is mutable seen_required = False seen_readonly = False while isinstance(typ, (RequiredType, ReadOnlyType)): if isinstance(typ, RequiredType): if context is not None and seen_required: self.fail( '"{}" type cannot be nested'.format( "Required[]" if typ.required else "NotRequired[]" ), context, code=codes.VALID_TYPE, ) is_required = typ.required seen_required = True typ = typ.item if isinstance(typ, ReadOnlyType): if context is not None and seen_readonly: self.fail('"ReadOnly[]" type cannot be nested', context, code=codes.VALID_TYPE) readonly = True seen_readonly = True typ = typ.item return typ, is_required, readonly def check_typeddict( self, node: Expression, var_name: str | None, is_func_scope: bool ) -> tuple[bool, TypeInfo | None, list[TypeVarLikeType]]: """Check if a call defines a TypedDict. The optional var_name argument is the name of the variable to which this is assigned, if any. Return a pair (is it a typed dict, corresponding TypeInfo). If the definition is invalid but looks like a TypedDict, report errors but return (some) TypeInfo. If some type is not ready, return (True, None). """ if not isinstance(node, CallExpr): return False, None, [] call = node callee = call.callee if not isinstance(callee, RefExpr): return False, None, [] fullname = callee.fullname if fullname not in TPDICT_NAMES: return False, None, [] res = self.parse_typeddict_args(call) if res is None: # This is a valid typed dict, but some type is not ready. # The caller should defer this until next iteration. return True, None, [] name, items, types, total, tvar_defs, ok = res if not ok: # Error. Construct dummy return value. if var_name: name = var_name if is_func_scope: name += "@" + str(call.line) else: name = var_name = "TypedDict@" + str(call.line) info = self.build_typeddict_typeinfo(name, {}, set(), set(), call.line, None) else: if var_name is not None and name != var_name: self.fail( 'First argument "{}" to TypedDict() does not match variable name "{}"'.format( name, var_name ), node, code=codes.NAME_MATCH, ) if name != var_name or is_func_scope: # Give it a unique name derived from the line number. name += "@" + str(call.line) required_keys = { field for (field, t) in zip(items, types) if (total or (isinstance(t, RequiredType) and t.required)) and not (isinstance(t, RequiredType) and not t.required) } readonly_keys = { field for (field, t) in zip(items, types) if isinstance(t, ReadOnlyType) } types = [ # unwrap Required[T] or ReadOnly[T] to just T t.item if isinstance(t, (RequiredType, ReadOnlyType)) else t for t in types ] # Perform various validations after unwrapping. for t in types: check_for_explicit_any( t, self.options, self.api.is_typeshed_stub_file, self.msg, context=call ) if self.options.disallow_any_unimported: for t in types: if has_any_from_unimported_type(t): self.msg.unimported_type_becomes_any("Type of a TypedDict key", t, call) existing_info = None if isinstance(node.analyzed, TypedDictExpr): existing_info = node.analyzed.info info = self.build_typeddict_typeinfo( name, dict(zip(items, types)), required_keys, readonly_keys, call.line, existing_info, ) info.line = node.line # Store generated TypeInfo under both names, see semanal_namedtuple for more details. if name != var_name or is_func_scope: self.api.add_symbol_skip_local(name, info) if var_name: self.api.add_symbol(var_name, info, node) call.analyzed = TypedDictExpr(info) call.analyzed.set_line(call) return True, info, tvar_defs def parse_typeddict_args( self, call: CallExpr ) -> tuple[str, list[str], list[Type], bool, list[TypeVarLikeType], bool] | None: """Parse typed dict call expression. Return names, types, totality, was there an error during parsing. If some type is not ready, return None. """ # TODO: Share code with check_argument_count in checkexpr.py? args = call.args if len(args) < 2: return self.fail_typeddict_arg("Too few arguments for TypedDict()", call) if len(args) > 3: return self.fail_typeddict_arg("Too many arguments for TypedDict()", call) # TODO: Support keyword arguments if call.arg_kinds not in ([ARG_POS, ARG_POS], [ARG_POS, ARG_POS, ARG_NAMED]): return self.fail_typeddict_arg("Unexpected arguments to TypedDict()", call) if len(args) == 3 and call.arg_names[2] != "total": return self.fail_typeddict_arg( f'Unexpected keyword argument "{call.arg_names[2]}" for "TypedDict"', call ) if not isinstance(args[0], StrExpr): return self.fail_typeddict_arg( "TypedDict() expects a string literal as the first argument", call ) if not isinstance(args[1], DictExpr): return self.fail_typeddict_arg( "TypedDict() expects a dictionary literal as the second argument", call ) total: bool | None = True if len(args) == 3: total = require_bool_literal_argument(self.api, call.args[2], "total") if total is None: return "", [], [], True, [], False dictexpr = args[1] tvar_defs = self.api.get_and_bind_all_tvars([t for k, t in dictexpr.items]) res = self.parse_typeddict_fields_with_types(dictexpr.items) if res is None: # One of the types is not ready, defer. return None items, types, ok = res assert total is not None return args[0].value, items, types, total, tvar_defs, ok def parse_typeddict_fields_with_types( self, dict_items: list[tuple[Expression | None, Expression]] ) -> tuple[list[str], list[Type], bool] | None: """Parse typed dict items passed as pairs (name expression, type expression). Return names, types, was there an error. If some type is not ready, return None. """ seen_keys = set() items: list[str] = [] types: list[Type] = [] for field_name_expr, field_type_expr in dict_items: if isinstance(field_name_expr, StrExpr): key = field_name_expr.value items.append(key) if key in seen_keys: self.fail(f'Duplicate TypedDict key "{key}"', field_name_expr) seen_keys.add(key) else: name_context = field_name_expr or field_type_expr self.fail_typeddict_arg("Invalid TypedDict() field name", name_context) return [], [], False try: type = expr_to_unanalyzed_type( field_type_expr, self.options, self.api.is_stub_file ) except TypeTranslationError: self.fail_typeddict_arg("Use dict literal for nested TypedDict", field_type_expr) return [], [], False analyzed = self.api.anal_type( type, allow_typed_dict_special_forms=True, allow_placeholder=not self.api.is_func_scope(), prohibit_self_type="TypedDict item type", prohibit_special_class_field_types="TypedDict", ) if analyzed is None: return None types.append(analyzed) return items, types, True def fail_typeddict_arg( self, message: str, context: Context ) -> tuple[str, list[str], list[Type], bool, list[TypeVarLikeType], bool]: self.fail(message, context) return "", [], [], True, [], False def build_typeddict_typeinfo( self, name: str, item_types: dict[str, Type], required_keys: set[str], readonly_keys: set[str], line: int, existing_info: TypeInfo | None, ) -> TypeInfo: # Prefer typing then typing_extensions if available. fallback = ( self.api.named_type_or_none("typing._TypedDict", []) or self.api.named_type_or_none("typing_extensions._TypedDict", []) or self.api.named_type_or_none("mypy_extensions._TypedDict", []) ) assert fallback is not None info = existing_info or self.api.basic_new_typeinfo(name, fallback, line) typeddict_type = TypedDictType(item_types, required_keys, readonly_keys, fallback) if info.special_alias and has_placeholder(info.special_alias.target): self.api.process_placeholder( None, "TypedDict item", info, force_progress=typeddict_type != info.typeddict_type ) info.update_typeddict_type(typeddict_type) return info # Helpers def is_typeddict(self, expr: Expression) -> bool: return isinstance(expr, RefExpr) and ( isinstance(expr.node, TypeInfo) and expr.node.typeddict_type is not None or isinstance(expr.node, TypeAlias) and isinstance(get_proper_type(expr.node.target), TypedDictType) ) def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: self.api.fail(msg, ctx, code=code) def note(self, msg: str, ctx: Context) -> None: self.api.note(msg, ctx)
TypedDictAnalyzer
python
huggingface__transformers
src/transformers/models/mask2former/image_processing_mask2former.py
{ "start": 1661, "end": 13477 }
class ____(ImagesKwargs, total=False): r""" ignore_index (`int`, *optional*): Label to be assigned to background pixels in segmentation maps. If provided, segmentation map pixels denoted with 0 (background) will be replaced with `ignore_index`. do_reduce_labels (`bool`, *optional*, defaults to `False`): Whether or not to decrement all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background, and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by `ignore_index`. num_labels (`int`, *optional*): The number of labels in the segmentation map. """ size_divisor: int ignore_index: Optional[int] do_reduce_labels: bool num_labels: Optional[int] def max_across_indices(values: Iterable[Any]) -> list[Any]: """ Return the maximum value across all indices of an iterable of values. """ return [max(values_i) for values_i in zip(*values)] # Copied from transformers.models.detr.image_processing_detr.get_max_height_width def get_max_height_width( images: list[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None ) -> list[int]: """ Get the maximum height and width across all images in a batch. """ if input_data_format is None: input_data_format = infer_channel_dimension_format(images[0]) if input_data_format == ChannelDimension.FIRST: _, max_height, max_width = max_across_indices([img.shape for img in images]) elif input_data_format == ChannelDimension.LAST: max_height, max_width, _ = max_across_indices([img.shape for img in images]) else: raise ValueError(f"Invalid channel dimension format: {input_data_format}") return (max_height, max_width) # Copied from transformers.models.detr.image_processing_detr.make_pixel_mask def make_pixel_mask( image: np.ndarray, output_size: tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None ) -> np.ndarray: """ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding. Args: image (`np.ndarray`): Image to make the pixel mask for. output_size (`tuple[int, int]`): Output size of the mask. """ input_height, input_width = get_image_size(image, channel_dim=input_data_format) mask = np.zeros(output_size, dtype=np.int64) mask[:input_height, :input_width] = 1 return mask # Copied from transformers.models.detr.image_processing_detr.binary_mask_to_rle def binary_mask_to_rle(mask): """ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format. Args: mask (`torch.Tensor` or `numpy.array`): A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target segment_id or class_id. Returns: `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE format. """ if is_torch_tensor(mask): mask = mask.numpy() pixels = mask.flatten() pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return list(runs) # Copied from transformers.models.detr.image_processing_detr.convert_segmentation_to_rle def convert_segmentation_to_rle(segmentation): """ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format. Args: segmentation (`torch.Tensor` or `numpy.array`): A segmentation map of shape `(height, width)` where each value denotes a segment or class id. Returns: `list[List]`: A list of lists, where each list is the run-length encoding of a segment / class id. """ segment_ids = torch.unique(segmentation) run_length_encodings = [] for idx in segment_ids: mask = torch.where(segmentation == idx, 1, 0) rle = binary_mask_to_rle(mask) run_length_encodings.append(rle) return run_length_encodings # Copied from transformers.models.detr.image_processing_detr.remove_low_and_no_objects def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels): """ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`. Args: masks (`torch.Tensor`): A tensor of shape `(num_queries, height, width)`. scores (`torch.Tensor`): A tensor of shape `(num_queries)`. labels (`torch.Tensor`): A tensor of shape `(num_queries)`. object_mask_threshold (`float`): A number between 0 and 1 used to binarize the masks. Raises: `ValueError`: Raised when the first dimension doesn't match in all input tensors. Returns: `tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region < `object_mask_threshold`. """ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]): raise ValueError("mask, scores and labels must have the same shape!") to_keep = labels.ne(num_labels) & (scores > object_mask_threshold) return masks[to_keep], scores[to_keep], labels[to_keep] # Copied from transformers.models.detr.image_processing_detr.check_segment_validity def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8): # Get the mask associated with the k class mask_k = mask_labels == k mask_k_area = mask_k.sum() # Compute the area of all the stuff in query k original_area = (mask_probs[k] >= mask_threshold).sum() mask_exists = mask_k_area > 0 and original_area > 0 # Eliminate disconnected tiny segments if mask_exists: area_ratio = mask_k_area / original_area if not area_ratio.item() > overlap_mask_area_threshold: mask_exists = False return mask_exists, mask_k # Copied from transformers.models.detr.image_processing_detr.compute_segments def compute_segments( mask_probs, pred_scores, pred_labels, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, label_ids_to_fuse: Optional[set[int]] = None, target_size: Optional[tuple[int, int]] = None, ): height = mask_probs.shape[1] if target_size is None else target_size[0] width = mask_probs.shape[2] if target_size is None else target_size[1] segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device) segments: list[dict] = [] if target_size is not None: mask_probs = nn.functional.interpolate( mask_probs.unsqueeze(0), size=target_size, mode="bilinear", align_corners=False )[0] current_segment_id = 0 # Weigh each mask by its prediction score mask_probs *= pred_scores.view(-1, 1, 1) mask_labels = mask_probs.argmax(0) # [height, width] # Keep track of instances of each class stuff_memory_list: dict[str, int] = {} for k in range(pred_labels.shape[0]): pred_class = pred_labels[k].item() should_fuse = pred_class in label_ids_to_fuse # Check if mask exists and large enough to be a segment mask_exists, mask_k = check_segment_validity( mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold ) if mask_exists: if pred_class in stuff_memory_list: current_segment_id = stuff_memory_list[pred_class] else: current_segment_id += 1 # Add current object segment to final segmentation map segmentation[mask_k] = current_segment_id segment_score = round(pred_scores[k].item(), 6) segments.append( { "id": current_segment_id, "label_id": pred_class, "was_fused": should_fuse, "score": segment_score, } ) if should_fuse: stuff_memory_list[pred_class] = current_segment_id return segmentation, segments # TODO: (Amy) Move to image_transforms # Copied from transformers.models.maskformer.image_processing_maskformer.convert_segmentation_map_to_binary_masks def convert_segmentation_map_to_binary_masks( segmentation_map: np.ndarray, instance_id_to_semantic_id: Optional[dict[int, int]] = None, ignore_index: Optional[int] = None, do_reduce_labels: bool = False, ): if do_reduce_labels and ignore_index is None: raise ValueError("If `do_reduce_labels` is True, `ignore_index` must be provided.") if do_reduce_labels: segmentation_map = np.where(segmentation_map == 0, ignore_index, segmentation_map - 1) # Get unique ids (class or instance ids based on input) all_labels = np.unique(segmentation_map) # Drop background label if applicable if ignore_index is not None: all_labels = all_labels[all_labels != ignore_index] # Generate a binary mask for each object instance binary_masks = [(segmentation_map == i) for i in all_labels] # Stack the binary masks if binary_masks: binary_masks = np.stack(binary_masks, axis=0) else: binary_masks = np.zeros((0, *segmentation_map.shape)) # Convert instance ids to class ids if instance_id_to_semantic_id is not None: labels = np.zeros(all_labels.shape[0]) for label in all_labels: class_id = instance_id_to_semantic_id[label + 1 if do_reduce_labels else label] labels[all_labels == label] = class_id - 1 if do_reduce_labels else class_id else: labels = all_labels return binary_masks.astype(np.float32), labels.astype(np.int64) # Copied from transformers.models.maskformer.image_processing_maskformer.get_maskformer_resize_output_image_size with maskformer->mask2former def get_mask2former_resize_output_image_size( image: np.ndarray, size: Union[int, tuple[int, int], list[int], tuple[int]], max_size: Optional[int] = None, size_divisor: int = 0, default_to_square: bool = True, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> tuple[int, int]: """ Computes the output size given the desired size. Args: image (`np.ndarray`): The input image. size (`int` or `tuple[int, int]` or `list[int]` or `tuple[int]`): The size of the output image. max_size (`int`, *optional*): The maximum size of the output image. size_divisor (`int`, *optional*, defaults to 0): If `size_divisor` is given, the output image size will be divisible by the number. default_to_square (`bool`, *optional*, defaults to `True`): Whether to default to square if no size is provided. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format of the input image. If unset, will use the inferred format from the input. Returns: `tuple[int, int]`: The output size. """ output_size = get_resize_output_image_size( input_image=image, size=size, default_to_square=default_to_square, max_size=max_size, input_data_format=input_data_format, ) if size_divisor > 0: height, width = output_size height = int(math.ceil(height / size_divisor) * size_divisor) width = int(math.ceil(width / size_divisor) * size_divisor) output_size = (height, width) return output_size
Mask2FormerImageProcessorKwargs
python
apache__airflow
providers/standard/tests/unit/standard/hooks/test_filesystem.py
{ "start": 937, "end": 1359 }
class ____: def test_get_ui_field_behaviour(self): fs_hook = FSHook() assert fs_hook.get_ui_field_behaviour() == { "hidden_fields": ["host", "schema", "port", "login", "password", "extra"], "relabeling": {}, "placeholders": {}, } def test_get_path(self): fs_hook = FSHook(fs_conn_id="fs_default") assert fs_hook.get_path() == "/"
TestFSHook
python
openai__gym
tests/wrappers/test_flatten.py
{ "start": 1667, "end": 3314 }
class ____: @pytest.mark.parametrize("observation_space, ordered_values", OBSERVATION_SPACES) def test_flattened_environment(self, observation_space, ordered_values): """ make sure that flattened observations occur in the order expected """ env = FakeEnvironment(observation_space=observation_space) wrapped_env = FlattenObservation(env) flattened, info = wrapped_env.reset() unflattened = unflatten(env.observation_space, flattened) original = env.observation self._check_observations(original, flattened, unflattened, ordered_values) @pytest.mark.parametrize("observation_space, ordered_values", OBSERVATION_SPACES) def test_flatten_unflatten(self, observation_space, ordered_values): """ test flatten and unflatten functions directly """ original = observation_space.sample() flattened = flatten(observation_space, original) unflattened = unflatten(observation_space, flattened) self._check_observations(original, flattened, unflattened, ordered_values) def _check_observations(self, original, flattened, unflattened, ordered_values): # make sure that unflatten(flatten(original)) == original assert set(unflattened.keys()) == set(original.keys()) for k, v in original.items(): np.testing.assert_allclose(unflattened[k], v) if ordered_values: # make sure that the values were flattened in the order they appeared in the # OrderedDict np.testing.assert_allclose(sorted(flattened), flattened)
TestFlattenEnvironment
python
huggingface__transformers
src/transformers/models/qwen3_next/modular_qwen3_next.py
{ "start": 35501, "end": 37971 }
class ____(MixtralForCausalLM): def __init__(self, config): super().__init__(config) self.num_experts = config.num_experts def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Qwen3NextDynamicCache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_router_logits: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> MoeCausalLMOutputWithPast: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Example: ```python >>> from transformers import AutoTokenizer, Qwen3NextForCausalLM >>> model = Qwen3NextForCausalLM.from_pretrained("Qwen/Qwen3-Next-80B-A3B-Instruct") >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Next-80B-A3B-Instruct") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" return super().forward( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_router_logits=output_router_logits, cache_position=cache_position, logits_to_keep=logits_to_keep, **kwargs, )
Qwen3NextForCausalLM
python
getsentry__sentry
src/sentry/rules/filters/base.py
{ "start": 122, "end": 297 }
class ____(RuleBase, abc.ABC): rule_type = "filter/event" @abc.abstractmethod def passes(self, event: GroupEvent, state: EventState) -> bool: pass
EventFilter
python
allegroai__clearml
clearml/backend_api/services/v2_20/queues.py
{ "start": 81321, "end": 82618 }
class ____(Response): """ Response of queues.move_task_to_front endpoint. :param position: The new position of the task entry in the queue (index, -1 represents bottom of queue) :type position: int """ _service = "queues" _action = "move_task_to_front" _version = "2.20" _schema = { "definitions": {}, "properties": { "position": { "description": "The new position of the task entry in the queue (index, -1 represents bottom of queue)", "type": ["integer", "null"], } }, "type": "object", } def __init__(self, position: Optional[int] = None, **kwargs: Any) -> None: super(MoveTaskToFrontResponse, self).__init__(**kwargs) self.position = position @schema_property("position") def position(self) -> Optional[int]: return self._property_position @position.setter def position(self, value: Optional[int]) -> None: if value is None: self._property_position = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "position", six.integer_types) self._property_position = value
MoveTaskToFrontResponse
python
pypa__pip
src/pip/_vendor/pygments/util.py
{ "start": 8330, "end": 9892 }
class ____: """Generic class to defer some work. Handled specially in RegexLexerMeta, to support regex string construction at first use. """ def get(self): raise NotImplementedError def guess_decode(text): """Decode *text* with guessed encoding. First try UTF-8; this should fail for non-UTF-8 encodings. Then try the preferred locale encoding. Fall back to latin-1, which always works. """ try: text = text.decode('utf-8') return text, 'utf-8' except UnicodeDecodeError: try: import locale prefencoding = locale.getpreferredencoding() text = text.decode() return text, prefencoding except (UnicodeDecodeError, LookupError): text = text.decode('latin1') return text, 'latin1' def guess_decode_from_terminal(text, term): """Decode *text* coming from terminal *term*. First try the terminal encoding, if given. Then try UTF-8. Then try the preferred locale encoding. Fall back to latin-1, which always works. """ if getattr(term, 'encoding', None): try: text = text.decode(term.encoding) except UnicodeDecodeError: pass else: return text, term.encoding return guess_decode(text) def terminal_encoding(term): """Return our best guess of encoding for the given *term*.""" if getattr(term, 'encoding', None): return term.encoding import locale return locale.getpreferredencoding()
Future
python
scipy__scipy
scipy/integrate/_ode.py
{ "start": 792, "end": 3160 }
class ____ ----------------- This class has the same generic interface as ode, except it can handle complex f, y and Jacobians by transparently translating them into the equivalent real-valued system. It supports the real-valued solvers (i.e., not zvode) and is an alternative to ode with the zvode solver, sometimes performing better. """ # XXX: Integrators must have: # =========================== # cvode - C version of vode and vodpk with many improvements. # Get it from http://www.netlib.org/ode/cvode.tar.gz. # To wrap cvode to Python, one must write the extension module by # hand. Its interface is too much 'advanced C' that using f2py # would be too complicated (or impossible). # # How to define a new integrator: # =============================== # # class myodeint(IntegratorBase): # # runner = <odeint function> or None # # def __init__(self,...): # required # <initialize> # # def reset(self,n,has_jac): # optional # # n - the size of the problem (number of equations) # # has_jac - whether user has supplied its own routine for Jacobian # <allocate memory,initialize further> # # def run(self,f,jac,y0,t0,t1,f_params,jac_params): # required # # this method is called to integrate from t=t0 to t=t1 # # with initial condition y0. f and jac are user-supplied functions # # that define the problem. f_params,jac_params are additional # # arguments # # to these functions. # <calculate y1> # if <calculation was unsuccessful>: # self.success = 0 # return t1,y1 # # # In addition, one can define step() and run_relax() methods (they # # take the same arguments as run()) if the integrator can support # # these features (see IntegratorBase doc strings). # # if myodeint.runner: # IntegratorBase.integrator_classes.append(myodeint) __all__ = ['ode', 'complex_ode'] import re import types import warnings import numpy as np from numpy import asarray, array, zeros, isscalar, real, imag from . import _vode from . import _dop from ._odepack import lsoda as lsoda_step # ------------------------------------------------------------------------------ # User interface # ------------------------------------------------------------------------------
complex_ode
python
ray-project__ray
rllib/examples/envs/classes/gpu_requiring_env.py
{ "start": 194, "end": 1447 }
class ____(SimpleCorridor): """A dummy env that requires a GPU in order to work. The env here is a simple corridor env that additionally simulates a GPU check in its constructor via `ray.get_gpu_ids()`. If this returns an empty list, we raise an error. To make this env work, use `num_gpus_per_env_runner > 0` (RolloutWorkers requesting this many GPUs each) and - maybe - `num_gpus > 0` in case your local worker/driver must have an env as well. However, this is only the case if `create_local_env_runner`=True (default is False). """ def __init__(self, config=None): super().__init__(config) # Fake-require some GPUs (at least one). # If your local worker's env (`create_local_env_runner`=True) does not # necessarily require a GPU, you can perform the below assertion only # if `config.worker_index != 0`. gpus_available = ray.get_gpu_ids() print(f"{type(self).__name__} can see GPUs={gpus_available}") # Create a dummy tensor on the GPU. if len(gpus_available) > 0 and torch: self._tensor = torch.from_numpy(np.random.random_sample(size=(42, 42))).to( f"cuda:{gpus_available[0]}" )
GPURequiringEnv
python
huggingface__transformers
tests/trainer/test_trainer.py
{ "start": 254114, "end": 254373 }
class ____(unittest.TestCase): def test_hyperparameter_search_backends(self): self.assertEqual( list(ALL_HYPERPARAMETER_SEARCH_BACKENDS.keys()), list(HPSearchBackend), ) @require_torch
HyperParameterSearchBackendsTest
python
mlflow__mlflow
mlflow/gateway/schemas/embeddings.py
{ "start": 492, "end": 1981 }
class ____(ResponseModel): prompt_tokens: int | None = None total_tokens: int | None = None _RESPONSE_PAYLOAD_EXTRA_SCHEMA = { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": [ 0.017291732, -0.017291732, 0.014577783, -0.02902633, -0.037271563, 0.019333655, -0.023055641, -0.007359971, -0.015818445, -0.030654699, 0.008348623, 0.018312693, -0.017149571, -0.0044424757, -0.011165961, 0.01018377, ], }, { "object": "embedding", "index": 1, "embedding": [ 0.0060126893, -0.008691099, -0.0040095365, 0.019889368, 0.036211833, -0.0013270887, 0.013401738, -0.0036735237, -0.0049594184, 0.035229642, -0.03435084, 0.019798903, -0.0006110424, 0.0073793563, 0.005657291, 0.022487005, ], }, ], "model": "text-embedding-ada-002-v2", "usage": {"prompt_tokens": 400, "total_tokens": 400}, }
EmbeddingsUsage
python
pytorch__pytorch
torch/_dynamo/polyfills/builtins.py
{ "start": 1438, "end": 2087 }
class ____: def __init__(self, fn, sentinel): # type: ignore[no-untyped-def] self.fn = fn self.sentinel = sentinel def __iter__(self): # type: ignore[no-untyped-def] return self def __next__(self): # type: ignore[no-untyped-def] # The iterator created in this case will call object with no arguments # for each call to its __next__() method; r = self.fn() # If the value returned is equal to sentinel, StopIteration will be raised if r == self.sentinel: raise StopIteration # otherwise the value will be returned. return r
_CallableIterator
python
numpy__numpy
numpy/distutils/cpuinfo.py
{ "start": 12915, "end": 15809 }
class ____(CPUInfoBase): info = None def __init__(self): if self.info is not None: return info = command_info(arch='arch', mach='mach', uname_i='uname_i', isainfo_b='isainfo -b', isainfo_n='isainfo -n', ) info['uname_X'] = key_value_from_command('uname -X', sep='=') for line in command_by_line('psrinfo -v 0'): m = re.match(r'\s*The (?P<p>[\w\d]+) processor operates at', line) if m: info['processor'] = m.group('p') break self.__class__.info = info def _not_impl(self): pass def _is_i386(self): return self.info['isainfo_n']=='i386' def _is_sparc(self): return self.info['isainfo_n']=='sparc' def _is_sparcv9(self): return self.info['isainfo_n']=='sparcv9' def _getNCPUs(self): return int(self.info['uname_X'].get('NumCPU', 1)) def _is_sun4(self): return self.info['arch']=='sun4' def _is_SUNW(self): return re.match(r'SUNW', self.info['uname_i']) is not None def _is_sparcstation5(self): return re.match(r'.*SPARCstation-5', self.info['uname_i']) is not None def _is_ultra1(self): return re.match(r'.*Ultra-1', self.info['uname_i']) is not None def _is_ultra250(self): return re.match(r'.*Ultra-250', self.info['uname_i']) is not None def _is_ultra2(self): return re.match(r'.*Ultra-2', self.info['uname_i']) is not None def _is_ultra30(self): return re.match(r'.*Ultra-30', self.info['uname_i']) is not None def _is_ultra4(self): return re.match(r'.*Ultra-4', self.info['uname_i']) is not None def _is_ultra5_10(self): return re.match(r'.*Ultra-5_10', self.info['uname_i']) is not None def _is_ultra5(self): return re.match(r'.*Ultra-5', self.info['uname_i']) is not None def _is_ultra60(self): return re.match(r'.*Ultra-60', self.info['uname_i']) is not None def _is_ultra80(self): return re.match(r'.*Ultra-80', self.info['uname_i']) is not None def _is_ultraenterprice(self): return re.match(r'.*Ultra-Enterprise', self.info['uname_i']) is not None def _is_ultraenterprice10k(self): return re.match(r'.*Ultra-Enterprise-10000', self.info['uname_i']) is not None def _is_sunfire(self): return re.match(r'.*Sun-Fire', self.info['uname_i']) is not None def _is_ultra(self): return re.match(r'.*Ultra', self.info['uname_i']) is not None def _is_cpusparcv7(self): return self.info['processor']=='sparcv7' def _is_cpusparcv8(self): return self.info['processor']=='sparcv8' def _is_cpusparcv9(self): return self.info['processor']=='sparcv9'
SunOSCPUInfo
python
python__mypy
mypy/test/testinfer.py
{ "start": 481, "end": 5591 }
class ____(Suite): """Test cases for argmap.map_actuals_to_formals.""" def test_basic(self) -> None: self.assert_map([], [], []) def test_positional_only(self) -> None: self.assert_map([ARG_POS], [ARG_POS], [[0]]) self.assert_map([ARG_POS, ARG_POS], [ARG_POS, ARG_POS], [[0], [1]]) def test_optional(self) -> None: self.assert_map([], [ARG_OPT], [[]]) self.assert_map([ARG_POS], [ARG_OPT], [[0]]) self.assert_map([ARG_POS], [ARG_OPT, ARG_OPT], [[0], []]) def test_callee_star(self) -> None: self.assert_map([], [ARG_STAR], [[]]) self.assert_map([ARG_POS], [ARG_STAR], [[0]]) self.assert_map([ARG_POS, ARG_POS], [ARG_STAR], [[0, 1]]) def test_caller_star(self) -> None: self.assert_map([ARG_STAR], [ARG_STAR], [[0]]) self.assert_map([ARG_POS, ARG_STAR], [ARG_STAR], [[0, 1]]) self.assert_map([ARG_STAR], [ARG_POS, ARG_STAR], [[0], [0]]) self.assert_map([ARG_STAR], [ARG_OPT, ARG_STAR], [[0], [0]]) def test_too_many_caller_args(self) -> None: self.assert_map([ARG_POS], [], []) self.assert_map([ARG_STAR], [], []) self.assert_map([ARG_STAR], [ARG_POS], [[0]]) def test_tuple_star(self) -> None: any_type = AnyType(TypeOfAny.special_form) self.assert_vararg_map([ARG_STAR], [ARG_POS], [[0]], self.make_tuple(any_type)) self.assert_vararg_map( [ARG_STAR], [ARG_POS, ARG_POS], [[0], [0]], self.make_tuple(any_type, any_type) ) self.assert_vararg_map( [ARG_STAR], [ARG_POS, ARG_OPT, ARG_OPT], [[0], [0], []], self.make_tuple(any_type, any_type), ) def make_tuple(self, *args: Type) -> TupleType: return TupleType(list(args), TypeFixture().std_tuple) def test_named_args(self) -> None: self.assert_map(["x"], [(ARG_POS, "x")], [[0]]) self.assert_map(["y", "x"], [(ARG_POS, "x"), (ARG_POS, "y")], [[1], [0]]) def test_some_named_args(self) -> None: self.assert_map(["y"], [(ARG_OPT, "x"), (ARG_OPT, "y"), (ARG_OPT, "z")], [[], [0], []]) def test_missing_named_arg(self) -> None: self.assert_map(["y"], [(ARG_OPT, "x")], [[]]) def test_duplicate_named_arg(self) -> None: self.assert_map(["x", "x"], [(ARG_OPT, "x")], [[0, 1]]) def test_varargs_and_bare_asterisk(self) -> None: self.assert_map([ARG_STAR], [ARG_STAR, (ARG_NAMED, "x")], [[0], []]) self.assert_map([ARG_STAR, "x"], [ARG_STAR, (ARG_NAMED, "x")], [[0], [1]]) def test_keyword_varargs(self) -> None: self.assert_map(["x"], [ARG_STAR2], [[0]]) self.assert_map(["x", ARG_STAR2], [ARG_STAR2], [[0, 1]]) self.assert_map(["x", ARG_STAR2], [(ARG_POS, "x"), ARG_STAR2], [[0], [1]]) self.assert_map([ARG_POS, ARG_STAR2], [(ARG_POS, "x"), ARG_STAR2], [[0], [1]]) def test_both_kinds_of_varargs(self) -> None: self.assert_map([ARG_STAR, ARG_STAR2], [(ARG_POS, "x"), (ARG_POS, "y")], [[0, 1], [0, 1]]) def test_special_cases(self) -> None: self.assert_map([ARG_STAR], [ARG_STAR, ARG_STAR2], [[0], []]) self.assert_map([ARG_STAR, ARG_STAR2], [ARG_STAR, ARG_STAR2], [[0], [1]]) self.assert_map([ARG_STAR2], [(ARG_POS, "x"), ARG_STAR2], [[0], [0]]) self.assert_map([ARG_STAR2], [ARG_STAR2], [[0]]) def assert_map( self, caller_kinds_: list[ArgKind | str], callee_kinds_: list[ArgKind | tuple[ArgKind, str]], expected: list[list[int]], ) -> None: caller_kinds, caller_names = expand_caller_kinds(caller_kinds_) callee_kinds, callee_names = expand_callee_kinds(callee_kinds_) result = map_actuals_to_formals( caller_kinds, caller_names, callee_kinds, callee_names, lambda i: AnyType(TypeOfAny.special_form), ) assert_equal(result, expected) def assert_vararg_map( self, caller_kinds: list[ArgKind], callee_kinds: list[ArgKind], expected: list[list[int]], vararg_type: Type, ) -> None: result = map_actuals_to_formals(caller_kinds, [], callee_kinds, [], lambda i: vararg_type) assert_equal(result, expected) def expand_caller_kinds( kinds_or_names: list[ArgKind | str], ) -> tuple[list[ArgKind], list[str | None]]: kinds = [] names: list[str | None] = [] for k in kinds_or_names: if isinstance(k, str): kinds.append(ARG_NAMED) names.append(k) else: kinds.append(k) names.append(None) return kinds, names def expand_callee_kinds( kinds_and_names: list[ArgKind | tuple[ArgKind, str]], ) -> tuple[list[ArgKind], list[str | None]]: kinds = [] names: list[str | None] = [] for v in kinds_and_names: if isinstance(v, tuple): kinds.append(v[0]) names.append(v[1]) else: kinds.append(v) names.append(None) return kinds, names
MapActualsToFormalsSuite
python
django__django
django/contrib/sessions/backends/cache.py
{ "start": 206, "end": 4674 }
class ____(SessionBase): """ A cache-based session store. """ cache_key_prefix = KEY_PREFIX def __init__(self, session_key=None): self._cache = caches[settings.SESSION_CACHE_ALIAS] super().__init__(session_key) @property def cache_key(self): return self.cache_key_prefix + self._get_or_create_session_key() async def acache_key(self): return self.cache_key_prefix + await self._aget_or_create_session_key() def load(self): try: session_data = self._cache.get(self.cache_key) except Exception: # Some backends (e.g. memcache) raise an exception on invalid # cache keys. If this happens, reset the session. See #17810. session_data = None if session_data is not None: return session_data self._session_key = None return {} async def aload(self): try: session_data = await self._cache.aget(await self.acache_key()) except Exception: session_data = None if session_data is not None: return session_data self._session_key = None return {} def create(self): # Because a cache can fail silently (e.g. memcache), we don't know if # we are failing to create a new session because of a key collision or # because the cache is missing. So we try for a (large) number of times # and then raise an exception. That's the risk you shoulder if using # cache backing. for i in range(10000): self._session_key = self._get_new_session_key() try: self.save(must_create=True) except CreateError: continue self.modified = True return raise RuntimeError( "Unable to create a new session key. " "It is likely that the cache is unavailable." ) async def acreate(self): for i in range(10000): self._session_key = await self._aget_new_session_key() try: await self.asave(must_create=True) except CreateError: continue self.modified = True return raise RuntimeError( "Unable to create a new session key. " "It is likely that the cache is unavailable." ) def save(self, must_create=False): if self.session_key is None: return self.create() if must_create: func = self._cache.add elif self._cache.get(self.cache_key) is not None: func = self._cache.set else: raise UpdateError result = func( self.cache_key, self._get_session(no_load=must_create), self.get_expiry_age(), ) if must_create and not result: raise CreateError async def asave(self, must_create=False): if self.session_key is None: return await self.acreate() if must_create: func = self._cache.aadd elif await self._cache.aget(await self.acache_key()) is not None: func = self._cache.aset else: raise UpdateError result = await func( await self.acache_key(), await self._aget_session(no_load=must_create), await self.aget_expiry_age(), ) if must_create and not result: raise CreateError def exists(self, session_key): return ( bool(session_key) and (self.cache_key_prefix + session_key) in self._cache ) async def aexists(self, session_key): return bool(session_key) and await self._cache.ahas_key( self.cache_key_prefix + session_key ) def delete(self, session_key=None): if session_key is None: if self.session_key is None: return session_key = self.session_key self._cache.delete(self.cache_key_prefix + session_key) async def adelete(self, session_key=None): if session_key is None: if self.session_key is None: return session_key = self.session_key await self._cache.adelete(self.cache_key_prefix + session_key) @classmethod def clear_expired(cls): pass @classmethod async def aclear_expired(cls): pass
SessionStore
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 107274, "end": 109160 }
class ____(TypedDict, total=False): type: Required[Literal['model-field']] schema: Required[CoreSchema] validation_alias: Union[str, list[Union[str, int]], list[list[Union[str, int]]]] serialization_alias: str serialization_exclude: bool # default: False serialization_exclude_if: Callable[[Any], bool] # default: None frozen: bool metadata: dict[str, Any] def model_field( schema: CoreSchema, *, validation_alias: str | list[str | int] | list[list[str | int]] | None = None, serialization_alias: str | None = None, serialization_exclude: bool | None = None, serialization_exclude_if: Callable[[Any], bool] | None = None, frozen: bool | None = None, metadata: dict[str, Any] | None = None, ) -> ModelField: """ Returns a schema for a model field, e.g.: ```py from pydantic_core import core_schema field = core_schema.model_field(schema=core_schema.int_schema()) ``` Args: schema: The schema to use for the field validation_alias: The alias(es) to use to find the field in the validation data serialization_alias: The alias to use as a key when serializing serialization_exclude: Whether to exclude the field when serializing serialization_exclude_if: A Callable that determines whether to exclude a field during serialization based on its value. frozen: Whether the field is frozen metadata: Any other information you want to include with the schema, not used by pydantic-core """ return _dict_not_none( type='model-field', schema=schema, validation_alias=validation_alias, serialization_alias=serialization_alias, serialization_exclude=serialization_exclude, serialization_exclude_if=serialization_exclude_if, frozen=frozen, metadata=metadata, )
ModelField
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py
{ "start": 160, "end": 199 }
class ____( # object ): ...
A
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 268709, "end": 276410 }
class ____: # Test that a frozen distribution gives the same results as the original # object. # # Only tested for the normal distribution (with loc and scale specified) # and for the gamma distribution (with a shape parameter specified). def test_norm(self): dist = stats.norm frozen = stats.norm(loc=10.0, scale=3.0) result_f = frozen.pdf(20.0) result = dist.pdf(20.0, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.cdf(20.0) result = dist.cdf(20.0, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.ppf(0.25) result = dist.ppf(0.25, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.isf(0.25) result = dist.isf(0.25, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.sf(10.0) result = dist.sf(10.0, loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.median() result = dist.median(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.mean() result = dist.mean(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.var() result = dist.var(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.std() result = dist.std(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.entropy() result = dist.entropy(loc=10.0, scale=3.0) assert_equal(result_f, result) result_f = frozen.moment(2) result = dist.moment(2, loc=10.0, scale=3.0) assert_equal(result_f, result) assert_equal(frozen.a, dist.a) assert_equal(frozen.b, dist.b) def test_gamma(self): a = 2.0 dist = stats.gamma frozen = stats.gamma(a) result_f = frozen.pdf(20.0) result = dist.pdf(20.0, a) assert_equal(result_f, result) result_f = frozen.cdf(20.0) result = dist.cdf(20.0, a) assert_equal(result_f, result) result_f = frozen.ppf(0.25) result = dist.ppf(0.25, a) assert_equal(result_f, result) result_f = frozen.isf(0.25) result = dist.isf(0.25, a) assert_equal(result_f, result) result_f = frozen.sf(10.0) result = dist.sf(10.0, a) assert_equal(result_f, result) result_f = frozen.median() result = dist.median(a) assert_equal(result_f, result) result_f = frozen.mean() result = dist.mean(a) assert_equal(result_f, result) result_f = frozen.var() result = dist.var(a) assert_equal(result_f, result) result_f = frozen.std() result = dist.std(a) assert_equal(result_f, result) result_f = frozen.entropy() result = dist.entropy(a) assert_equal(result_f, result) result_f = frozen.moment(2) result = dist.moment(2, a) assert_equal(result_f, result) assert_equal(frozen.a, frozen.dist.a) assert_equal(frozen.b, frozen.dist.b) def test_regression_ticket_1293(self): # Create a frozen distribution. frozen = stats.lognorm(1) # Call one of its methods that does not take any keyword arguments. m1 = frozen.moment(2) # Now call a method that takes a keyword argument. frozen.stats(moments='mvsk') # Call moment(2) again. # After calling stats(), the following was raising an exception. # So this test passes if the following does not raise an exception. m2 = frozen.moment(2) # The following should also be true, of course. But it is not # the focus of this test. assert_equal(m1, m2) def test_ab(self): # test that the support of a frozen distribution # (i) remains frozen even if it changes for the original one # (ii) is actually correct if the shape parameters are such that # the values of [a, b] are not the default [0, inf] # take a genpareto as an example where the support # depends on the value of the shape parameter: # for c > 0: a, b = 0, inf # for c < 0: a, b = 0, -1/c c = -0.1 rv = stats.genpareto(c=c) a, b = rv.dist._get_support(c) assert_equal([a, b], [0., 10.]) c = 0.1 stats.genpareto.pdf(0, c=c) assert_equal(rv.dist._get_support(c), [0, np.inf]) c = -0.1 rv = stats.genpareto(c=c) a, b = rv.dist._get_support(c) assert_equal([a, b], [0., 10.]) c = 0.1 stats.genpareto.pdf(0, c) # this should NOT change genpareto.b assert_equal((rv.dist.a, rv.dist.b), stats.genpareto._get_support(c)) rv1 = stats.genpareto(c=0.1) assert_(rv1.dist is not rv.dist) # c >= 0: a, b = [0, inf] for c in [1., 0.]: c = np.asarray(c) rv = stats.genpareto(c=c) a, b = rv.a, rv.b assert_equal(a, 0.) assert_(np.isposinf(b)) # c < 0: a=0, b=1/|c| c = np.asarray(-2.) a, b = stats.genpareto._get_support(c) assert_allclose([a, b], [0., 0.5]) def test_rv_frozen_in_namespace(self): # Regression test for gh-3522 assert_(hasattr(stats.distributions, 'rv_frozen')) def test_random_state(self): # only check that the random_state attribute exists, frozen = stats.norm() assert_(hasattr(frozen, 'random_state')) # ... that it can be set, frozen.random_state = 42 assert_equal(frozen.random_state.get_state(), np.random.RandomState(42).get_state()) # ... and that .rvs method accepts it as an argument rndm = np.random.RandomState(1234) frozen.rvs(size=8, random_state=rndm) def test_pickling(self): # test that a frozen instance pickles and unpickles # (this method is a clone of common_tests.check_pickling) beta = stats.beta(2.3098496451481823, 0.62687954300963677) poiss = stats.poisson(3.) sample = stats.rv_discrete(values=([0, 1, 2, 3], [0.1, 0.2, 0.3, 0.4])) for distfn in [beta, poiss, sample]: distfn.random_state = 1234 distfn.rvs(size=8) s = pickle.dumps(distfn) r0 = distfn.rvs(size=8) unpickled = pickle.loads(s) r1 = unpickled.rvs(size=8) assert_equal(r0, r1) # also smoke test some methods medians = [distfn.ppf(0.5), unpickled.ppf(0.5)] assert_equal(medians[0], medians[1]) assert_equal(distfn.cdf(medians[0]), unpickled.cdf(medians[1])) def test_expect(self): # smoke test the expect method of the frozen distribution # only take a gamma w/loc and scale and poisson with loc specified def func(x): return x gm = stats.gamma(a=2, loc=3, scale=4) with np.errstate(invalid="ignore", divide="ignore"): gm_val = gm.expect(func, lb=1, ub=2, conditional=True) gamma_val = stats.gamma.expect(func, args=(2,), loc=3, scale=4, lb=1, ub=2, conditional=True) assert_allclose(gm_val, gamma_val) p = stats.poisson(3, loc=4) p_val = p.expect(func) poisson_val = stats.poisson.expect(func, args=(3,), loc=4) assert_allclose(p_val, poisson_val)
TestFrozen
python
jazzband__django-oauth-toolkit
tests/test_token_view.py
{ "start": 1093, "end": 4322 }
class ____(TestAuthorizedTokenViews): """ Tests for the Authorized Token ListView """ def test_list_view_authorization_required(self): """ Test that the view redirects to login page if user is not logged-in. """ response = self.client.get(reverse("oauth2_provider:authorized-token-list")) self.assertEqual(response.status_code, 302) self.assertTrue("/accounts/login/?next=" in response["Location"]) def test_empty_list_view(self): """ Test that when you have no tokens, an appropriate message is shown """ self.client.login(username="foo_user", password="123456") response = self.client.get(reverse("oauth2_provider:authorized-token-list")) self.assertEqual(response.status_code, 200) self.assertIn(b"There are no authorized tokens yet.", response.content) def test_list_view_one_token(self): """ Test that the view shows your token """ self.client.login(username="bar_user", password="123456") AccessToken.objects.create( user=self.bar_user, token="1234567890", application=self.application, expires=timezone.now() + datetime.timedelta(days=1), scope="read write", ) response = self.client.get(reverse("oauth2_provider:authorized-token-list")) self.assertEqual(response.status_code, 200) self.assertIn(b"read", response.content) self.assertIn(b"write", response.content) self.assertNotIn(b"There are no authorized tokens yet.", response.content) def test_list_view_two_tokens(self): """ Test that the view shows your tokens """ self.client.login(username="bar_user", password="123456") AccessToken.objects.create( user=self.bar_user, token="1234567890", application=self.application, expires=timezone.now() + datetime.timedelta(days=1), scope="read write", ) AccessToken.objects.create( user=self.bar_user, token="0123456789", application=self.application, expires=timezone.now() + datetime.timedelta(days=1), scope="read write", ) response = self.client.get(reverse("oauth2_provider:authorized-token-list")) self.assertEqual(response.status_code, 200) self.assertNotIn(b"There are no authorized tokens yet.", response.content) def test_list_view_shows_correct_user_token(self): """ Test that only currently logged-in user"s tokens are shown """ self.client.login(username="bar_user", password="123456") AccessToken.objects.create( user=self.foo_user, token="1234567890", application=self.application, expires=timezone.now() + datetime.timedelta(days=1), scope="read write", ) response = self.client.get(reverse("oauth2_provider:authorized-token-list")) self.assertEqual(response.status_code, 200) self.assertIn(b"There are no authorized tokens yet.", response.content)
TestAuthorizedTokenListView
python
falconry__falcon
falcon/http_error.py
{ "start": 1089, "end": 9176 }
class ____(Exception): """Represents a generic HTTP error. Raise an instance or subclass of ``HTTPError`` to have Falcon return a formatted error response and an appropriate HTTP status code to the client when something goes wrong. JSON and XML media types are supported by default. To customize the error presentation, implement a custom error serializer and set it on the :class:`~.App` instance via :meth:`~.App.set_error_serializer`. To customize what data is passed to the serializer, subclass ``HTTPError`` and override the ``to_dict()`` method (``to_json()`` is implemented via ``to_dict()``). `status` is the only positional argument allowed, the other arguments are defined as keyword-only. Args: status (Union[str,int]): HTTP status code or line (e.g., ``'400 Bad Request'``). This may be set to a member of :class:`http.HTTPStatus`, an HTTP status line string or byte string (e.g., ``'200 OK'``), or an ``int``. Keyword Args: title (str): Human-friendly error title. If not provided, defaults to the HTTP status line as determined by the ``status`` argument. description (str): Human-friendly description of the error, along with a helpful suggestion or two (default ``None``). headers (dict or list): A ``dict`` of header names and values to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and *value* must be of type ``str`` or ``StringType``, and only character values 0x00 through 0xFF may be used on platforms that use wide characters. Note: The Content-Type header, if present, will be overridden. If you wish to return custom error messages, you can create your own HTTP error class, and install an error handler to convert it into an appropriate HTTP response for the client Note: Falcon can process a list of ``tuple`` slightly faster than a ``dict``. href (str): A URL someone can visit to find out more information (default ``None``). Unicode characters are percent-encoded. href_text (str): If href is given, use this as the friendly title/description for the link (default 'App documentation for this error'). code (int): An internal code that customers can reference in their support request or to help them when searching for knowledge base articles related to this error (default ``None``). """ __slots__ = ( 'status', 'title', 'description', 'headers', 'link', 'code', ) status: ResponseStatus """HTTP status code or line (e.g., ``'200 OK'``). This may be set to a member of :class:`http.HTTPStatus`, an HTTP status line string or byte string (e.g., ``'200 OK'``), or an ``int``. """ title: str """Error title to send to the client. Derived from the ``status`` if not provided. """ description: str | None """Description of the error to send to the client.""" headers: HeaderArg | None """Extra headers to add to the response.""" link: Link | None """An href that the client can provide to the user for getting help.""" code: int | None """An internal application code that a user can reference when requesting support for the error. """ def __init__( self, status: ResponseStatus, *, title: str | None = None, description: str | None = None, headers: HeaderArg | None = None, href: str | None = None, href_text: str | None = None, code: int | None = None, ): self.status = status # TODO(kgriffs): HTTP/2 does away with the "reason phrase". Eventually # we'll probably switch over to making everything code-based to more # easily support HTTP/2. When that happens, should we continue to # include the reason phrase in the title? self.title = title or misc.code_to_http_status(status) self.description = description self.headers = headers self.code = code if href: self.link = { 'text': href_text or 'Documentation related to this error', 'href': uri.encode(href), 'rel': 'help', } else: self.link = None def __repr__(self) -> str: return '<%s: %s>' % (self.__class__.__name__, self.status) __str__ = __repr__ @property def status_code(self) -> int: """HTTP status code normalized from the ``status`` argument passed to the initializer. """ # noqa: D205 return misc.http_status_to_code(self.status) def to_dict( self, obj_type: type[MutableMapping[str, str | int | None | Link]] = dict ) -> MutableMapping[str, str | int | None | Link]: """Return a basic dictionary representing the error. This method can be useful when serializing the error to hash-like media types, such as YAML, JSON, and MessagePack. Args: obj_type: A dict-like type that will be used to store the error information (default ``dict``). Returns: dict: A dictionary populated with the error's title, description, etc. """ obj = obj_type() obj['title'] = self.title if self.description is not None: obj['description'] = self.description if self.code is not None: obj['code'] = self.code if self.link is not None: obj['link'] = self.link return obj def to_json(self, handler: BaseHandler | None = None) -> bytes: """Return a JSON representation of the error. Args: handler: Handler object that will be used to serialize the representation of this error to JSON. When not provided, a default handler using the builtin JSON library will be used (default ``None``). Returns: bytes: A JSON document for the error. """ obj = self.to_dict() if handler is None: handler = _DEFAULT_JSON_HANDLER # NOTE: the json handler requires the sync serialize interface return handler.serialize(obj, MEDIA_JSON) def _to_xml(self) -> bytes: """Return an XML-encoded representation of the error.""" error_element = et.Element('error') et.SubElement(error_element, 'title').text = self.title if self.description is not None: et.SubElement(error_element, 'description').text = self.description if self.code is not None: et.SubElement(error_element, 'code').text = str(self.code) if self.link is not None: link_element = et.SubElement(error_element, 'link') for key in ('text', 'href', 'rel'): et.SubElement(link_element, key).text = self.link[key] return b'<?xml version="1.0" encoding="UTF-8"?>' + et.tostring( error_element, encoding='utf-8' ) @deprecation.deprecated( 'The internal error serialization to XML is deprecated. ' 'Please serialize the output of to_dict() to XML instead.' ) def to_xml(self) -> bytes: """Return an XML-encoded representation of the error. Returns: bytes: An XML document for the error. .. deprecated:: 4.0 Automatic error serialization to XML is deprecated. Please serialize the output of :meth:`to_dict` to XML instead. """ return self._to_xml() # NOTE: initialized in falcon.media.json, that is always imported since Request/Response # are imported by falcon init. if TYPE_CHECKING: _DEFAULT_JSON_HANDLER: BaseHandler else: _DEFAULT_JSON_HANDLER = None
HTTPError
python
huggingface__transformers
tests/models/zoedepth/test_modeling_zoedepth.py
{ "start": 4926, "end": 7535 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as ZoeDepth does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (ZoeDepthForDepthEstimation,) if is_torch_available() else () pipeline_model_mapping = {"depth-estimation": ZoeDepthForDepthEstimation} if is_torch_available() else {} test_resize_embeddings = False # `strict=True/False` are both failing with torch 2.7, see #38677 test_torch_exportable = get_torch_major_and_minor_version() != "2.7" def setUp(self): self.model_tester = ZoeDepthModelTester(self) self.config_tester = ConfigTester( self, config_class=ZoeDepthConfig, has_text_modality=False, hidden_size=37, common_properties=[] ) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="ZoeDepth with AutoBackbone does not have a base model and hence no input_embeddings") def test_inputs_embeds(self): pass @unittest.skip(reason="ZoeDepth with AutoBackbone does not have a base model and hence no input_embeddings") def test_model_get_set_embeddings(self): pass def test_for_depth_estimation(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*config_and_inputs) @unittest.skip(reason="ZoeDepth with AutoBackbone does not have a base model and hence no input_embeddings") def test_model_common_attributes(self): pass @unittest.skip(reason="ZoeDepth does not support training yet") def test_training(self): pass @unittest.skip(reason="ZoeDepth does not support training yet") def test_training_gradient_checkpointing(self): pass @unittest.skip(reason="ZoeDepth does not support training yet") def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip(reason="ZoeDepth does not support training yet") def test_training_gradient_checkpointing_use_reentrant_false(self): pass @slow def test_model_from_pretrained(self): model_name = "Intel/zoedepth-nyu" model = ZoeDepthForDepthEstimation.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_vision @slow
ZoeDepthModelTest
python
wandb__wandb
wandb/wandb_agent.py
{ "start": 426, "end": 5274 }
class ____: """Launch and manage a process.""" def __init__( self, env=None, command=None, function=None, run_id=None, in_jupyter=None ): self._popen = None self._proc = None self._finished_q = multiprocessing.Queue() self._proc_killed = False if command: if platform.system() == "Windows": kwargs = dict(creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) env.pop(wandb.env.SERVICE, None) # TODO: Determine if we need the same stdin workaround as POSIX case below. self._popen = subprocess.Popen(command, env=env, **kwargs) else: if sys.version_info >= (3, 11): # preexec_fn=os.setpgrp is not thread-safe; process_group was introduced in # python 3.11 to replace it, so use that when possible kwargs = dict(process_group=0) else: kwargs = dict(preexec_fn=os.setpgrp) env.pop(wandb.env.SERVICE, None) # Upon spawning the subprocess in a new process group, the child's process group is # not connected to the controlling terminal's stdin. If it tries to access stdin, # it gets a SIGTTIN and blocks until we give it the terminal, which we don't want # to do. # # By using subprocess.PIPE, we give it an independent stdin. However, it will still # block if it tries to read from stdin, because we're not writing anything to it. # We immediately close the subprocess's stdin here so it can fail fast and get an # EOF. # # (One situation that makes this relevant is that importing `readline` even # indirectly can cause the child to attempt to access stdin, which can trigger the # deadlock. In Python 3.13, `import torch` indirectly imports `readline` via `pdb`, # meaning `import torch` in a run script can deadlock unless we override stdin. # See https://github.com/wandb/wandb/pull/10489 description for more details.) # # Also, we avoid spawning a new session because that breaks preempted child process # handling. self._popen = subprocess.Popen( command, env=env, stdin=subprocess.PIPE, **kwargs, ) self._popen.stdin.close() elif function: self._proc = multiprocessing.Process( target=self._start, args=(self._finished_q, env, function, run_id, in_jupyter), ) self._proc.start() else: raise AgentError("Agent Process requires command or function") def _start(self, finished_q, env, function, run_id, in_jupyter): if env: for k, v in env.items(): os.environ[k] = v # call user function wandb.termlog(f"Agent Started Run: {run_id}") if function: function() wandb.termlog(f"Agent Finished Run: {run_id}\n") # complete the run run = wandb.run if run: wandb.join() # signal that the process is finished finished_q.put(True) def poll(self): if self._popen: return self._popen.poll() if self._proc_killed: # we need to join process to prevent zombies self._proc.join() return True try: finished = self._finished_q.get(False, 0) if finished: return True except queue.Empty: pass return def wait(self): if self._popen: # if on windows, wait() will block and we won't be able to interrupt if platform.system() == "Windows": while True: p = self._popen.poll() if p is not None: return p time.sleep(1) return self._popen.wait() return self._proc.join() def kill(self): if self._popen: return self._popen.kill() pid = self._proc.pid if pid: ret = os.kill(pid, signal.SIGKILL) self._proc_killed = True return ret return def terminate(self): if self._popen: # windows terminate is too strong, send Ctrl-C instead if platform.system() == "Windows": return self._popen.send_signal(signal.CTRL_C_EVENT) return self._popen.terminate() return self._proc.terminate()
AgentProcess
python
plotly__plotly.py
_plotly_utils/basevalidators.py
{ "start": 21360, "end": 25244 }
class ____(BaseValidator): """ "number": { "description": "A number or a numeric value (e.g. a number inside a string). When applicable, values greater (less) than `max` (`min`) are coerced to the `dflt`.", "requiredOpts": [], "otherOpts": [ "dflt", "min", "max", "arrayOk" ] }, """ def __init__( self, plotly_name, parent_name, min=None, max=None, array_ok=False, **kwargs ): super(NumberValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, **kwargs ) # Handle min if min is None and max is not None: # Max was specified, so make min -inf self.min_val = float("-inf") else: self.min_val = min # Handle max if max is None and min is not None: # Min was specified, so make min inf self.max_val = float("inf") else: self.max_val = max if min is not None or max is not None: self.has_min_max = True else: self.has_min_max = False self.array_ok = array_ok def description(self): desc = """\ The '{plotly_name}' property is a number and may be specified as:""".format( plotly_name=self.plotly_name ) if not self.has_min_max: desc = ( desc + """ - An int or float""" ) else: desc = ( desc + """ - An int or float in the interval [{min_val}, {max_val}]""".format( min_val=self.min_val, max_val=self.max_val ) ) if self.array_ok: desc = ( desc + """ - A tuple, list, or one-dimensional numpy array of the above""" ) return desc def validate_coerce(self, v): if is_none_or_typed_array_spec(v): pass elif self.array_ok and is_homogeneous_array(v): np = get_module("numpy") try: v_array = copy_to_readonly_numpy_array(v, force_numeric=True) except (ValueError, TypeError, OverflowError): self.raise_invalid_val(v) # Check min/max if self.has_min_max: v_valid = np.logical_and( self.min_val <= v_array, v_array <= self.max_val ) if not np.all(v_valid): # Grab up to the first 10 invalid values v_invalid = np.logical_not(v_valid) some_invalid_els = np.array(v, dtype="object")[v_invalid][ :10 ].tolist() self.raise_invalid_elements(some_invalid_els) v = v_array # Always numeric numpy array elif self.array_ok and is_simple_array(v): # Check numeric invalid_els = [e for e in v if not isinstance(e, numbers.Number)] if invalid_els: self.raise_invalid_elements(invalid_els[:10]) # Check min/max if self.has_min_max: invalid_els = [e for e in v if not (self.min_val <= e <= self.max_val)] if invalid_els: self.raise_invalid_elements(invalid_els[:10]) v = to_scalar_or_list(v) else: # Check numeric if not isinstance(v, numbers.Number): self.raise_invalid_val(v) # Check min/max if self.has_min_max: if not (self.min_val <= v <= self.max_val): self.raise_invalid_val(v) return v
NumberValidator
python
tornadoweb__tornado
maint/benchmark/parsing_benchmark.py
{ "start": 2194, "end": 2973 }
class ____(Enum): def __new__(cls, arg_value: str, func: Callable[[], None]): member = object.__new__(cls) member._value_ = arg_value member.func = func return member HEADERS_SPLIT = ("headers-split", run_headers_split) HEADERS_FULL = ("headers-full", run_headers_full) def main(): parse_command_line() try: func = Benchmark(options.benchmark).func except ValueError: known_benchmarks = [benchmark.value for benchmark in Benchmark] print( "Unknown benchmark: '{}', supported values are: {}" .format(options.benchmark, ", ".join(known_benchmarks)) ) return for _ in range(options.num_runs): func() if __name__ == '__main__': main()
Benchmark
python
astropy__astropy
astropy/nddata/tests/test_decorators.py
{ "start": 326, "end": 12516 }
class ____(NDData): pass @support_nddata def wrapped_function_1(data, wcs=None, unit=None): return data, wcs, unit def test_pass_numpy(): data_in = np.array([1, 2, 3]) data_out, wcs_out, unit_out = wrapped_function_1(data=data_in) assert data_out is data_in assert wcs_out is None assert unit_out is None def test_pass_all_separate(): data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy data_out, wcs_out, unit_out = wrapped_function_1( data=data_in, wcs=wcs_in, unit=unit_in ) assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in def test_pass_nddata(): data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy nddata_in = NDData(data_in, wcs=wcs_in, unit=unit_in) data_out, wcs_out, unit_out = wrapped_function_1(nddata_in) assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in @pytest.mark.parametrize( "func", ( lambda *, data, wcs, unit=None: (data, wcs, unit), lambda *, wcs=None, data, unit=None: (data, wcs, unit), ), ) def test_pass_nddata_kwarg_only(func): wrapped_function = support_nddata(func) data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy nddata_in = NDData(data_in, wcs=wcs_in, unit=unit_in) data_out, wcs_out, unit_out = wrapped_function(data=nddata_in) assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in @pytest.mark.parametrize( "func, call_type", ( pytest.param( lambda data, wcs=None, mask=None, /, *, unit=None: (data, wcs, unit, mask), "data_as_pos", id="data_wcs_mask_pos-only", ), pytest.param( lambda data, wcs=None, /, mask=None, *, unit: (data, wcs, unit, mask), "data_as_pos", id="data_wcs_pos-only", ), pytest.param( lambda wcs=None, /, data=None, mask=None, *, unit: (data, wcs, unit, mask), "data_as_kw", id="data_pos-or-kw", ), pytest.param( lambda wcs=None, /, mask=None, *, data, unit: (data, wcs, unit, mask), "data_as_kw", id="data_kw-only", ), ), ) def test_pass_nddata_constrained_signature(func, call_type): wrapped_function = support_nddata(func) data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy mask_in = np.array([True, False, False]) nddata_in = NDData(data_in, wcs=wcs_in, unit=unit_in, mask=mask_in) if call_type == "data_as_pos": args = (nddata_in,) kwargs = {} elif call_type == "data_as_kw": args = () kwargs = {"data": nddata_in} data_out, wcs_out, unit_out, mask_out = wrapped_function(*args, **kwargs) assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in assert mask_out is mask_in nddata2 = NDData(data_in, unit=unit_in, mask=mask_in) if call_type == "data_as_pos": args = (nddata2,) kwargs = {} elif call_type == "data_as_kw": args = () kwargs = {"data": nddata2} data_out, wcs_out, unit_out, mask_out = wrapped_function(*args, **kwargs) assert data_out is data_in assert wcs_out is None assert unit_out is unit_in assert mask_out is mask_in if call_type == "data_as_pos": args = (nddata2, wcs_in) kwargs = {} elif call_type == "data_as_kw": args = (wcs_in,) kwargs = {"data": nddata2} data_out, wcs_out, unit_out, mask_out = wrapped_function(*args, **kwargs) assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in assert mask_out is mask_in if call_type == "data_as_pos": args = (nddata_in, wcs_in) kwargs = {} elif call_type == "data_as_kw": args = (wcs_in,) kwargs = {"data": nddata_in} with pytest.warns( AstropyUserWarning, match=( "Property wcs has been passed explicitly and as " "an NDData property, using explicitly specified value" ), ): data_out, wcs_out, unit_out, mask_out = wrapped_function(*args, **kwargs) assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in assert mask_out is mask_in def test_pass_nddata_and_explicit(): data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy unit_in_alt = u.mJy nddata_in = NDData(data_in, wcs=wcs_in, unit=unit_in) with pytest.warns( AstropyUserWarning, match=( "Property unit has been passed explicitly and as " "an NDData property, using explicitly specified value" ), ) as w: data_out, wcs_out, unit_out = wrapped_function_1(nddata_in, unit=unit_in_alt) assert len(w) == 1 assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in_alt def test_pass_nddata_ignored(): data_in = np.array([1, 2, 3]) wcs_in = WCS(naxis=1) unit_in = u.Jy nddata_in = NDData(data_in, wcs=wcs_in, unit=unit_in, mask=[0, 1, 0]) with pytest.warns( AstropyUserWarning, match=( "The following attributes were set on the data " "object, but will be ignored by the function: mask" ), ) as w: data_out, wcs_out, unit_out = wrapped_function_1(nddata_in) assert len(w) == 1 assert data_out is data_in assert wcs_out is wcs_in assert unit_out is unit_in @pytest.mark.parametrize( "func", ( lambda something, wcs=None, unit=None: None, lambda wcs=None, unit=None: None, ), ) def test_incorrect_first_argument(func): with pytest.raises( ValueError, match="Can only wrap a function with a data argument" ): support_nddata(func) def test_wrap_function_no_kwargs(): @support_nddata def wrapped_function_5(data, other_data): return data data_in = np.array([1, 2, 3]) nddata_in = NDData(data_in) assert wrapped_function_5(nddata_in, [1, 2, 3]) is data_in def test_wrap_function_repack_valid(): @support_nddata(repack=True, returns=["data"]) def wrapped_function_5(data, other_data): return data data_in = np.array([1, 2, 3]) nddata_in = NDData(data_in) nddata_out = wrapped_function_5(nddata_in, [1, 2, 3]) assert isinstance(nddata_out, NDData) assert nddata_out.data is data_in def test_wrap_function_accepts(): class MyData(NDData): pass @support_nddata(accepts=MyData) def wrapped_function_5(data, other_data): return data data_in = np.array([1, 2, 3]) nddata_in = NDData(data_in) mydata_in = MyData(data_in) assert wrapped_function_5(mydata_in, [1, 2, 3]) is data_in with pytest.raises( TypeError, match=( "Only NDData sub-classes that inherit " "from MyData can be used by this function" ), ): wrapped_function_5(nddata_in, [1, 2, 3]) def test_wrap_preserve_signature_docstring(): @support_nddata def wrapped_function_6(data, wcs=None, unit=None): """ An awesome function """ if wrapped_function_6.__doc__ is not None: assert wrapped_function_6.__doc__.strip() == "An awesome function" signature = inspect.signature(wrapped_function_6) assert str(signature) == "(data, wcs=None, unit=None)" def test_setup_failures1(): # repack but no returns with pytest.raises(ValueError): support_nddata(repack=True) def test_setup_failures2(): # returns but no repack with pytest.raises(ValueError): support_nddata(returns=["data"]) def test_setup_failures9(): # keeps but no repack with pytest.raises(ValueError): support_nddata(keeps=["unit"]) def test_setup_failures3(): # same attribute in keeps and returns with pytest.raises(ValueError): support_nddata(repack=True, keeps=["mask"], returns=["data", "mask"]) def test_setup_failures4(): # function accepts *args with pytest.raises(ValueError): @support_nddata def test(data, *args): pass def test_setup_failures10(): # function accepts **kwargs with pytest.raises(ValueError): @support_nddata def test(data, **kwargs): pass def test_setup_failures5(): # function accepts *args (or **kwargs) with pytest.raises(ValueError): @support_nddata def test(data, *args): pass def test_setup_failures6(): # First argument is not data with pytest.raises(ValueError): @support_nddata def test(img): pass def test_setup_failures7(): # accepts CCDData but was given just an NDData with pytest.raises(TypeError): @support_nddata(accepts=CCDData) def test(data): pass test(NDData(np.ones((3, 3)))) def test_setup_failures8(): # function returns a different amount of arguments than specified. Using # NDData here so we don't get into troubles when creating a CCDData without # unit! with pytest.raises(ValueError): @support_nddata(repack=True, returns=["data", "mask"]) def test(data): return 10 test(NDData(np.ones((3, 3)))) # do NOT use CCDData here. def test_setup_failures11(): # function accepts no arguments with pytest.raises(ValueError): @support_nddata def test(): pass def test_setup_numpyarray_default(): # It should be possible (even if it's not advisable to use mutable # defaults) to have a numpy array as default value. @support_nddata def func(data, wcs=np.array([1, 2, 3])): return wcs def test_still_accepts_other_input(): @support_nddata(repack=True, returns=["data"]) def test(data): return data assert isinstance(test(NDData(np.ones((3, 3)))), NDData) assert isinstance(test(10), int) assert isinstance(test([1, 2, 3]), list) def test_accepting_property_normal(): # Accepts a mask attribute and takes it from the input @support_nddata def test(data, mask=None): return mask ndd = NDData(np.ones((3, 3))) assert test(ndd) is None ndd._mask = np.zeros((3, 3)) assert np.all(test(ndd) == 0) # Use the explicitly given one (raises a Warning) with pytest.warns(AstropyUserWarning) as w: assert test(ndd, mask=10) == 10 assert len(w) == 1 def test_parameter_default_identical_to_explicit_passed_argument(): # If the default is identical to the explicitly passed argument this # should still raise a Warning and use the explicit one. @support_nddata def func(data, meta={"a": 1}): return meta with pytest.warns(AstropyUserWarning) as w: assert func(NDData(1, meta={"b": 2}), {"a": 1}) == {"a": 1} assert len(w) == 1 assert func(NDData(1, meta={"b": 2})) == {"b": 2} def test_accepting_property_notexist(): # Accepts flags attribute but NDData doesn't have one @support_nddata def test(data, flags=10): return flags ndd = NDData(np.ones((3, 3))) test(ndd) def test_accepting_property_translated(): # Accepts a error attribute and we want to pass in uncertainty! @support_nddata(mask="masked") def test(data, masked=None): return masked ndd = NDData(np.ones((3, 3))) assert test(ndd) is None ndd._mask = np.zeros((3, 3)) assert np.all(test(ndd) == 0) # Use the explicitly given one (raises a Warning) with pytest.warns(AstropyUserWarning) as w: assert test(ndd, masked=10) == 10 assert len(w) == 1 def test_accepting_property_meta_empty(): # Meta is always set (dict) so it has a special case that it's # ignored if it's empty but not None @support_nddata def test(data, meta=None): return meta ndd = NDData(np.ones((3, 3))) assert test(ndd) is None ndd._meta = {"a": 10} assert test(ndd) == {"a": 10}
CCDData
python
PrefectHQ__prefect
src/prefect/task_engine.py
{ "start": 33811, "end": 67439 }
class ____(BaseTaskRunEngine[P, R]): task_run: TaskRun | None = None _client: Optional[PrefectClient] = None @property def client(self) -> PrefectClient: if not self._is_started or self._client is None: raise RuntimeError("Engine has not started.") return self._client async def can_retry(self, exc_or_state: Exception | State[R]) -> bool: retry_condition: Optional[ Callable[["Task[P, Coroutine[Any, Any, R]]", TaskRun, State[R]], bool] ] = self.task.retry_condition_fn failure_type = "exception" if isinstance(exc_or_state, Exception) else "state" if not self.task_run: raise ValueError("Task run is not set") try: self.logger.debug( f"Running `retry_condition_fn` check {retry_condition!r} for task" f" {self.task.name!r}" ) state = Failed( data=exc_or_state, message=f"Task run encountered unexpected {failure_type}: {repr(exc_or_state)}", ) if inspect.iscoroutinefunction(retry_condition): should_retry = await retry_condition(self.task, self.task_run, state) elif inspect.isfunction(retry_condition): should_retry = retry_condition(self.task, self.task_run, state) else: should_retry = not retry_condition return should_retry except Exception: self.logger.error( ( "An error was encountered while running `retry_condition_fn` check" f" '{retry_condition!r}' for task {self.task.name!r}" ), exc_info=True, ) return False async def call_hooks(self, state: Optional[State] = None) -> None: if state is None: state = self.state task = self.task task_run = self.task_run if not task_run: raise ValueError("Task run is not set") if state.is_failed() and task.on_failure_hooks: hooks = task.on_failure_hooks elif state.is_completed() and task.on_completion_hooks: hooks = task.on_completion_hooks elif state.is_running() and task.on_running_hooks: hooks = task.on_running_hooks else: hooks = None for hook in hooks or []: hook_name = get_hook_name(hook) try: self.logger.info( f"Running hook {hook_name!r} in response to entering state" f" {state.name!r}" ) result = hook(task, task_run, state) if inspect.isawaitable(result): await result except Exception: self.logger.error( f"An error was encountered while running hook {hook_name!r}", exc_info=True, ) else: self.logger.info(f"Hook {hook_name!r} finished running successfully") async def begin_run(self) -> None: try: self._resolve_parameters() self._set_custom_task_run_name() except UpstreamTaskError as upstream_exc: state = await self.set_state( Pending( name="NotReady", message=str(upstream_exc), ), # if orchestrating a run already in a pending state, force orchestration to # update the state name force=self.state.is_pending(), ) return new_state = Running() self.task_run.start_time = new_state.timestamp flow_run_context = FlowRunContext.get() if flow_run_context: # Carry forward any task run information from the flow run flow_run = flow_run_context.flow_run self.task_run.flow_run_run_count = flow_run.run_count state = await self.set_state(new_state) # TODO: this is temporary until the API stops rejecting state transitions # and the client / transaction store becomes the source of truth # this is a bandaid caused by the API storing a Completed state with a bad # result reference that no longer exists if state.is_completed(): try: await state.result(retry_result_failure=False) except Exception: state = await self.set_state(new_state, force=True) backoff_count = 0 # TODO: Could this listen for state change events instead of polling? while state.is_pending() or state.is_paused(): if backoff_count < BACKOFF_MAX: backoff_count += 1 interval = clamped_poisson_interval( average_interval=backoff_count, clamping_factor=0.3 ) await anyio.sleep(interval) state = await self.set_state(new_state) # Call on_running hooks after the task has entered the Running state if state.is_running(): await self.call_hooks(state) async def set_state(self, state: State, force: bool = False) -> State: last_state = self.state if not self.task_run: raise ValueError("Task run is not set") self.task_run.state = new_state = state if last_state.timestamp == new_state.timestamp: # Ensure that the state timestamp is unique, or at least not equal to the last state. # This might occur especially on Windows where the timestamp resolution is limited. new_state.timestamp += timedelta(microseconds=1) # Ensure that the state_details are populated with the current run IDs new_state.state_details.task_run_id = self.task_run.id new_state.state_details.flow_run_id = self.task_run.flow_run_id # Predictively update the de-normalized task_run.state_* attributes self.task_run.state_id = new_state.id self.task_run.state_type = new_state.type self.task_run.state_name = new_state.name if last_state.is_running(): self.task_run.total_run_time += new_state.timestamp - last_state.timestamp if new_state.is_running(): self.task_run.run_count += 1 if new_state.is_final(): if ( self.task_run and self.task_run.start_time and not self.task_run.end_time ): self.task_run.end_time = new_state.timestamp if isinstance(new_state.data, ResultRecord): result = new_state.data.result else: result = new_state.data link_state_to_task_run_result(new_state, result) # emit a state change event self._last_event = emit_task_run_state_change_event( task_run=self.task_run, initial_state=last_state, validated_state=self.task_run.state, follows=self._last_event, ) self._telemetry.update_state(new_state) return new_state async def result(self, raise_on_failure: bool = True) -> "Union[R, State, None]": if self._return_value is not NotSet: if isinstance(self._return_value, ResultRecord): return self._return_value.result # otherwise, return the value as is return self._return_value if self._raised is not NotSet: # if the task raised an exception, raise it if raise_on_failure: raise self._raised # otherwise, return the exception return self._raised async def handle_success( self, result: R, transaction: AsyncTransaction ) -> Union[ResultRecord[R], None, Coroutine[Any, Any, R], R]: if isinstance(result, State) and result.is_failed(): if await self.handle_retry(result): return None if self.task.cache_expiration is not None: expiration = prefect.types._datetime.now("UTC") + self.task.cache_expiration else: expiration = None terminal_state = await return_value_to_state( result, result_store=get_result_store(), key=transaction.key, expiration=expiration, ) # Avoid logging when running this rollback hook since it is not user-defined handle_rollback = partial(self.handle_rollback) handle_rollback.log_on_run = False transaction.stage( terminal_state.data, on_rollback_hooks=[handle_rollback] + self.task.on_rollback_hooks, on_commit_hooks=self.task.on_commit_hooks, ) if transaction.is_committed(): terminal_state.name = "Cached" await self.set_state(terminal_state) self._return_value = result self._telemetry.end_span_on_success() return result async def handle_retry(self, exc_or_state: Exception | State[R]) -> bool: """Handle any task run retries. - If the task has retries left, and the retry condition is met, set the task to retrying and return True. - If the task has a retry delay, place in AwaitingRetry state with a delayed scheduled time. - If the task has no retries left, or the retry condition is not met, return False. """ failure_type = "exception" if isinstance(exc_or_state, Exception) else "state" if self.retries < self.task.retries and await self.can_retry(exc_or_state): if self.task.retry_delay_seconds: delay = ( self.task.retry_delay_seconds[ min(self.retries, len(self.task.retry_delay_seconds) - 1) ] # repeat final delay value if attempts exceed specified delays if isinstance(self.task.retry_delay_seconds, Sequence) else self.task.retry_delay_seconds ) new_state = AwaitingRetry( scheduled_time=prefect.types._datetime.now("UTC") + timedelta(seconds=delay) ) else: delay = None new_state = Retrying() self.logger.info( "Task run failed with %s: %r - Retry %s/%s will start %s", failure_type, exc_or_state, self.retries + 1, self.task.retries, str(delay) + " second(s) from now" if delay else "immediately", ) await self.set_state(new_state, force=True) # Call on_running hooks if we transitioned to a Running state (immediate retry) if new_state.is_running(): await self.call_hooks(new_state) self.retries: int = self.retries + 1 return True elif self.retries >= self.task.retries: if self.task.retries > 0: self.logger.error( f"Task run failed with {failure_type}: {exc_or_state!r} - Retries are exhausted", exc_info=True, ) else: self.logger.error( f"Task run failed with {failure_type}: {exc_or_state!r}", exc_info=True, ) return False return False async def handle_exception(self, exc: Exception) -> None: # If the task fails, and we have retries left, set the task to retrying. self._telemetry.record_exception(exc) if not await self.handle_retry(exc): # If the task has no retries left, or the retry condition is not met, set the task to failed. state = await exception_to_failed_state( exc, message="Task run encountered an exception", result_store=get_result_store(), ) await self.set_state(state) self._raised = exc self._telemetry.end_span_on_failure(state.message) async def handle_timeout(self, exc: TimeoutError) -> None: self._telemetry.record_exception(exc) if not await self.handle_retry(exc): if isinstance(exc, TaskRunTimeoutError): message = f"Task run exceeded timeout of {self.task.timeout_seconds} second(s)" else: message = f"Task run failed due to timeout: {exc!r}" self.logger.error(message) state = Failed( data=exc, message=message, name="TimedOut", ) await self.set_state(state) self._raised = exc self._telemetry.end_span_on_failure(state.message) async def handle_crash(self, exc: BaseException) -> None: state = await exception_to_crashed_state(exc) self.logger.error(f"Crash detected! {state.message}") self.logger.debug("Crash details:", exc_info=exc) await self.set_state(state, force=True) self._raised = exc self._telemetry.record_exception(exc) self._telemetry.end_span_on_failure(state.message) @asynccontextmanager async def setup_run_context(self, client: Optional[PrefectClient] = None): from prefect.utilities.engine import ( should_log_prints, ) settings = get_current_settings() if client is None: client = self.client if not self.task_run: raise ValueError("Task run is not set") with ExitStack() as stack: if log_prints := should_log_prints(self.task): stack.enter_context(patch_print()) if self.task.persist_result is not None: persist_result = self.task.persist_result elif settings.tasks.default_persist_result is not None: persist_result = settings.tasks.default_persist_result else: persist_result = should_persist_result() stack.enter_context( TaskRunContext( task=self.task, log_prints=log_prints, task_run=self.task_run, parameters=self.parameters, result_store=await get_result_store().update_for_task( self.task, _sync=False ), client=client, persist_result=persist_result, ) ) stack.enter_context(ConcurrencyContext()) self.logger: "logging.Logger" = task_run_logger( task_run=self.task_run, task=self.task ) # type: ignore yield @asynccontextmanager async def asset_context(self): parent_asset_ctx = AssetContext.get() if parent_asset_ctx and parent_asset_ctx.copy_to_child_ctx: asset_ctx = parent_asset_ctx.model_copy() asset_ctx.copy_to_child_ctx = False else: asset_ctx = AssetContext.from_task_and_inputs( self.task, self.task_run.id, self.task_run.task_inputs ) with asset_ctx as ctx: try: yield finally: ctx.emit_events(self.state) @asynccontextmanager async def initialize_run( self, task_run_id: Optional[UUID] = None, dependencies: Optional[dict[str, set[RunInput]]] = None, ) -> AsyncGenerator[Self, Any]: """ Enters a client context and creates a task run if needed. """ with hydrated_context(self.context): async with AsyncClientContext.get_or_create(): self._client = get_client() self._is_started = True parent_flow_run_context = FlowRunContext.get() parent_task_run_context = TaskRunContext.get() try: if not self.task_run: self.task_run = await self.task.create_local_run( id=task_run_id, parameters=self.parameters, flow_run_context=parent_flow_run_context, parent_task_run_context=parent_task_run_context, wait_for=self.wait_for, extra_task_inputs=dependencies, ) # Emit an event to capture that the task run was in the `PENDING` state. self._last_event = emit_task_run_state_change_event( task_run=self.task_run, initial_state=None, validated_state=self.task_run.state, ) async with self.setup_run_context(): # setup_run_context might update the task run name, so log creation here self.logger.debug( f"Created task run {self.task_run.name!r} for task {self.task.name!r}" ) await self._telemetry.async_start_span( run=self.task_run, client=self.client, parameters=self.parameters, ) yield self except TerminationSignal as exc: # TerminationSignals are caught and handled as crashes await self.handle_crash(exc) raise exc except Exception: # regular exceptions are caught and re-raised to the user raise except (Pause, Abort) as exc: # Do not capture internal signals as crashes if isinstance(exc, Abort): self.logger.error("Task run was aborted: %s", exc) raise except GeneratorExit: # Do not capture generator exits as crashes raise except BaseException as exc: # BaseExceptions are caught and handled as crashes await self.handle_crash(exc) raise finally: self.log_finished_message() self._is_started = False self._client = None async def wait_until_ready(self) -> None: """Waits until the scheduled time (if its the future), then enters Running.""" if scheduled_time := self.state.state_details.scheduled_time: sleep_time = ( scheduled_time - prefect.types._datetime.now("UTC") ).total_seconds() await anyio.sleep(sleep_time if sleep_time > 0 else 0) new_state = Retrying() if self.state.name == "AwaitingRetry" else Running() await self.set_state( new_state, force=True, ) # Call on_running hooks if we transitioned to a Running state if self.state.is_running(): await self.call_hooks() # -------------------------- # # The following methods compose the main task run loop # # -------------------------- @asynccontextmanager async def start( self, task_run_id: Optional[UUID] = None, dependencies: Optional[dict[str, set[RunInput]]] = None, ) -> AsyncGenerator[None, None]: async with self.initialize_run( task_run_id=task_run_id, dependencies=dependencies ): with ( trace.use_span(self._telemetry.span) if self._telemetry.span else nullcontext() ): try: self._resolve_parameters() self._set_custom_task_run_name() self._wait_for_dependencies() except UpstreamTaskError as upstream_exc: await self.set_state( Pending( name="NotReady", message=str(upstream_exc), ), # if orchestrating a run already in a pending state, force orchestration to # update the state name force=self.state.is_pending(), ) yield await self.call_hooks() return async with _aconcurrency( names=[f"tag:{tag}" for tag in self.task_run.tags], occupy=1, holder=ConcurrencyLeaseHolder(type="task_run", id=self.task_run.id), lease_duration=60, suppress_warnings=True, ): await self.begin_run() try: yield finally: await self.call_hooks() @asynccontextmanager async def transaction_context(self) -> AsyncGenerator[AsyncTransaction, None]: # refresh cache setting is now repurposes as overwrite transaction record overwrite = ( self.task.refresh_cache if self.task.refresh_cache is not None else PREFECT_TASKS_REFRESH_CACHE.value() ) isolation_level = ( IsolationLevel(self.task.cache_policy.isolation_level) if self.task.cache_policy and self.task.cache_policy is not NotSet and self.task.cache_policy.isolation_level is not None else None ) async with atransaction( key=self.compute_transaction_key(), store=get_result_store(), overwrite=overwrite, logger=self.logger, write_on_commit=should_persist_result(), isolation_level=isolation_level, ) as txn: yield txn @asynccontextmanager async def run_context(self): # reenter the run context to ensure it is up to date for every run async with self.setup_run_context(): try: with timeout_async( seconds=self.task.timeout_seconds, timeout_exc_type=TaskRunTimeoutError, ): self.logger.debug( f"Executing task {self.task.name!r} for task run {self.task_run.name!r}..." ) if self.is_cancelled(): raise CancelledError("Task run cancelled by the task runner") yield self except TimeoutError as exc: await self.handle_timeout(exc) except Exception as exc: await self.handle_exception(exc) async def call_task_fn( self, transaction: AsyncTransaction ) -> Union[ResultRecord[Any], None, Coroutine[Any, Any, R], R]: """ Convenience method to call the task function. Returns a coroutine if the task is async. """ parameters = self.parameters or {} if transaction.is_committed(): result = await transaction.read() else: result = await call_with_parameters(self.task.fn, parameters) await self.handle_success(result, transaction=transaction) return result def run_task_sync( task: "Task[P, R]", task_run_id: Optional[UUID] = None, task_run: Optional[TaskRun] = None, parameters: Optional[dict[str, Any]] = None, wait_for: Optional["OneOrManyFutureOrResult[Any]"] = None, return_type: Literal["state", "result"] = "result", dependencies: Optional[dict[str, set[RunInput]]] = None, context: Optional[dict[str, Any]] = None, ) -> Union[R, State, None]: engine = SyncTaskRunEngine[P, R]( task=task, parameters=parameters, task_run=task_run, wait_for=wait_for, context=context, ) with engine.start(task_run_id=task_run_id, dependencies=dependencies): while engine.is_running(): run_coro_as_sync(engine.wait_until_ready()) with ( engine.asset_context(), engine.run_context(), engine.transaction_context() as txn, ): engine.call_task_fn(txn) return engine.state if return_type == "state" else engine.result() async def run_task_async( task: "Task[P, R]", task_run_id: Optional[UUID] = None, task_run: Optional[TaskRun] = None, parameters: Optional[dict[str, Any]] = None, wait_for: Optional["OneOrManyFutureOrResult[Any]"] = None, return_type: Literal["state", "result"] = "result", dependencies: Optional[dict[str, set[RunInput]]] = None, context: Optional[dict[str, Any]] = None, ) -> Union[R, State, None]: engine = AsyncTaskRunEngine[P, R]( task=task, parameters=parameters, task_run=task_run, wait_for=wait_for, context=context, ) async with engine.start(task_run_id=task_run_id, dependencies=dependencies): while engine.is_running(): await engine.wait_until_ready() async with ( engine.asset_context(), engine.run_context(), engine.transaction_context() as txn, ): await engine.call_task_fn(txn) return engine.state if return_type == "state" else await engine.result() def run_generator_task_sync( task: "Task[P, R]", task_run_id: Optional[UUID] = None, task_run: Optional[TaskRun] = None, parameters: Optional[dict[str, Any]] = None, wait_for: Optional["OneOrManyFutureOrResult[Any]"] = None, return_type: Literal["state", "result"] = "result", dependencies: Optional[dict[str, set[RunInput]]] = None, context: Optional[dict[str, Any]] = None, ) -> Generator[R, None, None]: if return_type != "result": raise ValueError("The return_type for a generator task must be 'result'") engine = SyncTaskRunEngine[P, R]( task=task, parameters=parameters, task_run=task_run, wait_for=wait_for, context=context, ) with engine.start(task_run_id=task_run_id, dependencies=dependencies): while engine.is_running(): run_coro_as_sync(engine.wait_until_ready()) with ( engine.asset_context(), engine.run_context(), engine.transaction_context() as txn, ): # TODO: generators should default to commit_mode=OFF # because they are dynamic by definition # for now we just prevent this branch explicitly if False and txn.is_committed(): txn.read() else: call_args, call_kwargs = parameters_to_args_kwargs( task.fn, engine.parameters or {} ) gen = task.fn(*call_args, **call_kwargs) try: while True: gen_result = next(gen) # link the current state to the result for dependency tracking # # TODO: this could grow the task_run_result # dictionary in an unbounded way, so finding a # way to periodically clean it up (using # weakrefs or similar) would be good link_state_to_task_run_result(engine.state, gen_result) yield gen_result except StopIteration as exc: engine.handle_success(exc.value, transaction=txn) except GeneratorExit as exc: engine.handle_success(None, transaction=txn) gen.throw(exc) return engine.result() async def run_generator_task_async( task: "Task[P, R]", task_run_id: Optional[UUID] = None, task_run: Optional[TaskRun] = None, parameters: Optional[dict[str, Any]] = None, wait_for: Optional["OneOrManyFutureOrResult[Any]"] = None, return_type: Literal["state", "result"] = "result", dependencies: Optional[dict[str, set[RunInput]]] = None, context: Optional[dict[str, Any]] = None, ) -> AsyncGenerator[R, None]: if return_type != "result": raise ValueError("The return_type for a generator task must be 'result'") engine = AsyncTaskRunEngine[P, R]( task=task, parameters=parameters, task_run=task_run, wait_for=wait_for, context=context, ) async with engine.start(task_run_id=task_run_id, dependencies=dependencies): while engine.is_running(): await engine.wait_until_ready() async with ( engine.asset_context(), engine.run_context(), engine.transaction_context() as txn, ): # TODO: generators should default to commit_mode=OFF # because they are dynamic by definition # for now we just prevent this branch explicitly if False and txn.is_committed(): txn.read() else: call_args, call_kwargs = parameters_to_args_kwargs( task.fn, engine.parameters or {} ) gen = task.fn(*call_args, **call_kwargs) try: while True: # can't use anext in Python < 3.10 gen_result = await gen.__anext__() # link the current state to the result for dependency tracking # # TODO: this could grow the task_run_result # dictionary in an unbounded way, so finding a # way to periodically clean it up (using # weakrefs or similar) would be good link_state_to_task_run_result(engine.state, gen_result) yield gen_result except (StopAsyncIteration, GeneratorExit) as exc: await engine.handle_success(None, transaction=txn) if isinstance(exc, GeneratorExit): gen.throw(exc) # async generators can't return, but we can raise failures here if engine.state.is_failed(): await engine.result() @overload def run_task( task: "Task[P, R]", task_run_id: Optional[UUID] = None, task_run: Optional[TaskRun] = None, parameters: Optional[dict[str, Any]] = None, wait_for: Optional["OneOrManyFutureOrResult[Any]"] = None, return_type: Literal["state"] = "state", dependencies: Optional[dict[str, set[RunInput]]] = None, context: Optional[dict[str, Any]] = None, ) -> State[R]: ... @overload def run_task( task: "Task[P, R]", task_run_id: Optional[UUID] = None, task_run: Optional[TaskRun] = None, parameters: Optional[dict[str, Any]] = None, wait_for: Optional["OneOrManyFutureOrResult[Any]"] = None, return_type: Literal["result"] = "result", dependencies: Optional[dict[str, set[RunInput]]] = None, context: Optional[dict[str, Any]] = None, ) -> R: ... def run_task( task: "Task[P, Union[R, Coroutine[Any, Any, R]]]", task_run_id: Optional[UUID] = None, task_run: Optional[TaskRun] = None, parameters: Optional[dict[str, Any]] = None, wait_for: Optional["OneOrManyFutureOrResult[Any]"] = None, return_type: Literal["state", "result"] = "result", dependencies: Optional[dict[str, set[RunInput]]] = None, context: Optional[dict[str, Any]] = None, ) -> Union[R, State, None, Coroutine[Any, Any, Union[R, State, None]]]: """ Runs the provided task. Args: task: The task to run task_run_id: The ID of the task run; if not provided, a new task run will be created task_run: The task run object; if not provided, a new task run will be created parameters: The parameters to pass to the task wait_for: A list of futures to wait for before running the task return_type: The return type to return; either "state" or "result" dependencies: A dictionary of task run inputs to use for dependency tracking context: A dictionary containing the context to use for the task run; only required if the task is running on in a remote environment Returns: The result of the task run """ kwargs: dict[str, Any] = dict( task=task, task_run_id=task_run_id, task_run=task_run, parameters=parameters, wait_for=wait_for, return_type=return_type, dependencies=dependencies, context=context, ) if task.isasync and task.isgenerator: return run_generator_task_async(**kwargs) elif task.isgenerator: return run_generator_task_sync(**kwargs) elif task.isasync: return run_task_async(**kwargs) else: return run_task_sync(**kwargs)
AsyncTaskRunEngine
python
django__django
tests/mail/tests.py
{ "start": 86019, "end": 86939 }
class ____(MailTestsMixin, SimpleTestCase): @override_settings( EMAIL_USE_LOCALTIME=False, USE_TZ=True, TIME_ZONE="Africa/Algiers" ) def test_date_header_utc(self): """ EMAIL_USE_LOCALTIME=False creates a datetime in UTC. """ email = EmailMessage() # Per RFC 2822/5322 section 3.3, "The form '+0000' SHOULD be used # to indicate a time zone at Universal Time." self.assertEndsWith(email.message()["Date"], "+0000") @override_settings( EMAIL_USE_LOCALTIME=True, USE_TZ=True, TIME_ZONE="Africa/Algiers" ) def test_date_header_localtime(self): """ EMAIL_USE_LOCALTIME=True creates a datetime in the local time zone. """ email = EmailMessage() # Africa/Algiers is UTC+1 year round. self.assertEndsWith(email.message()["Date"], "+0100") # RemovedInDjango70Warning.
MailTimeZoneTests
python
walkccc__LeetCode
solutions/1694. Reformat Phone Number/1694.py
{ "start": 0, "end": 460 }
class ____: def reformatNumber(self, number: str) -> str: ans = [] number = number.replace("-", "").replace(" ", "") i = 0 # number's index while i + 4 < len(number): ans.append(number[i:i + 3] + '-') i += 3 countFinalDigits = len(number) - i if countFinalDigits < 4: ans.append(number[i:]) else: # countFinalDigits == 4 ans.append(number[i:i + 2] + '-' + number[i + 2:]) return ''.join(ans)
Solution
python
ansible__ansible
lib/ansible/module_utils/_internal/_concurrent/_futures.py
{ "start": 172, "end": 936 }
class ____(concurrent.futures.ThreadPoolExecutor): """ThreadPoolExecutor subclass that creates non-joinable daemon threads for non-blocking pool and process shutdown with abandoned threads.""" atc = concurrent.futures.ThreadPoolExecutor._adjust_thread_count # clone the base class `_adjust_thread_count` method with a copy of its globals dict _adjust_thread_count = types.FunctionType(atc.__code__, atc.__globals__.copy(), name=atc.__name__, argdefs=atc.__defaults__, closure=atc.__closure__) # patch the method closure's `threading` module import to use our daemon-only thread factory instead _adjust_thread_count.__globals__.update(threading=_daemon_threading) del atc # don't expose this as a class attribute
DaemonThreadPoolExecutor
python
google__jax
tests/api_test.py
{ "start": 253632, "end": 254419 }
class ____(jtu.BufferDonationTestCase): @jtu.device_supports_buffer_donation() def test_pmap_donate_argnums_invalidates_input(self): move = api.pmap(lambda x: x + x - x, donate_argnums=0) n = jax.local_device_count() x = api.pmap(lambda x: x)(jnp.ones([n])) y = move(x) self.assertDeleted(x) np.testing.assert_allclose(y, [1.] * n) @jtu.device_supports_buffer_donation() def test_pmap_nested_donate_ignored(self): pmap_fun = jit(lambda x: api.pmap(lambda y: y ** 2, donate_argnums=0)(x)) a = api.pmap(lambda x: x)(jnp.array([1])) # NOTE(mattjj): stopped raising error here and instead just ignored # with self.assertRaisesRegex(ValueError, "nested.*not supported"): # pmap_fun(a) pmap_fun(a) # doesn't crash
BufferDonationTest
python
psf__black
tests/data/cases/composition_no_trailing_comma.py
{ "start": 0, "end": 5600 }
class ____: def test(self) -> None: with patch("black.out", print): self.assertEqual( unstyle(str(report)), "1 file reformatted, 1 file failed to reformat." ) self.assertEqual( unstyle(str(report)), "1 file reformatted, 1 file left unchanged, 1 file failed to reformat.", ) self.assertEqual( unstyle(str(report)), "2 files reformatted, 1 file left unchanged, 1 file failed to" " reformat.", ) self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 2 files failed to" " reformat.", ) for i in (a,): if ( # Rule 1 i % 2 == 0 # Rule 2 and i % 3 == 0 ): while ( # Just a comment call() # Another ): print(i) xxxxxxxxxxxxxxxx = Yyyy2YyyyyYyyyyy( push_manager=context.request.resource_manager, max_items_to_push=num_items, batch_size=Yyyy2YyyyYyyyyYyyy.FULL_SIZE ).push( # Only send the first n items. items=items[:num_items] ) return ( 'Utterly failed doctest test for %s\n File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err) ) def omitting_trailers(self) -> None: get_collection( hey_this_is_a_very_long_call, it_has_funny_attributes, really=True )[OneLevelIndex] get_collection( hey_this_is_a_very_long_call, it_has_funny_attributes, really=True )[OneLevelIndex][TwoLevelIndex][ThreeLevelIndex][FourLevelIndex] d[0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][ 22 ] assignment = ( some.rather.elaborate.rule() and another.rule.ending_with.index[123] ) def easy_asserts(self) -> None: assert { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } == expected, "Not what we expected" assert expected == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 }, "Not what we expected" assert expected == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } def tricky_asserts(self) -> None: assert { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } == expected( value, is_going_to_be="too long to fit in a single line", srsly=True ), "Not what we expected" assert { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } == expected, ( "Not what we expected and the message is too long to fit in one line" ) assert expected( value, is_going_to_be="too long to fit in a single line", srsly=True ) == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 }, "Not what we expected" assert expected == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 }, ( "Not what we expected and the message is too long to fit in one line" " because it's too long" ) dis_c_instance_method = """\ %3d 0 LOAD_FAST 1 (x) 2 LOAD_CONST 1 (1) 4 COMPARE_OP 2 (==) 6 LOAD_FAST 0 (self) 8 STORE_ATTR 0 (x) 10 LOAD_CONST 0 (None) 12 RETURN_VALUE """ % ( _C.__init__.__code__.co_firstlineno + 1, ) assert ( expectedexpectedexpectedexpectedexpectedexpectedexpectedexpectedexpect == { key1: value1, key2: value2, key3: value3, key4: value4, key5: value5, key6: value6, key7: value7, key8: value8, key9: value9 } ) # output
C
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_numeric_tower.py
{ "start": 6770, "end": 8637 }
class ____(__TestCase): def test_mixed_comparisons(self): # ordered list of distinct test values of various types: # int, float, Fraction, Decimal test_values = [ float('-inf'), D('-1e425000000'), -1e308, F(-22, 7), -3.14, -2, 0.0, 1e-320, True, F('1.2'), D('1.3'), float('1.4'), F(275807, 195025), D('1.414213562373095048801688724'), F(114243, 80782), F(473596569, 84615), 7e200, D('infinity'), ] for i, first in enumerate(test_values): for second in test_values[i+1:]: self.assertLess(first, second) self.assertLessEqual(first, second) self.assertGreater(second, first) self.assertGreaterEqual(second, first) def test_complex(self): # comparisons with complex are special: equality and inequality # comparisons should always succeed, but order comparisons should # raise TypeError. z = 1.0 + 0j w = -3.14 + 2.7j for v in 1, 1.0, F(1), D(1), complex(1): self.assertEqual(z, v) self.assertEqual(v, z) for v in 2, 2.0, F(2), D(2), complex(2): self.assertNotEqual(z, v) self.assertNotEqual(v, z) self.assertNotEqual(w, v) self.assertNotEqual(v, w) for v in (1, 1.0, F(1), D(1), complex(1), 2, 2.0, F(2), D(2), complex(2), w): for op in operator.le, operator.lt, operator.ge, operator.gt: self.assertRaises(TypeError, op, z, v) self.assertRaises(TypeError, op, v, z) if __name__ == '__main__': run_tests()
ComparisonTest
python
django__django
tests/defer_regress/models.py
{ "start": 433, "end": 519 }
class ____(models.Model): item = models.ForeignKey(Item, models.CASCADE)
RelatedItem
python
apache__thrift
lib/py/src/transport/TTransport.py
{ "start": 3560, "end": 5576 }
class ____(TTransportBase, CReadableTransport): """Class that wraps another transport and buffers its I/O. The implementation uses a (configurable) fixed-size read buffer but buffers all writes until a flush is performed. """ DEFAULT_BUFFER = 4096 def __init__(self, trans, rbuf_size=DEFAULT_BUFFER): self.__trans = trans self.__wbuf = BytesIO() # Pass string argument to initialize read buffer as cStringIO.InputType self.__rbuf = BytesIO(b'') self.__rbuf_size = rbuf_size def isOpen(self): return self.__trans.isOpen() def open(self): return self.__trans.open() def close(self): return self.__trans.close() def read(self, sz): ret = self.__rbuf.read(sz) if len(ret) != 0: return ret self.__rbuf = BytesIO(self.__trans.read(max(sz, self.__rbuf_size))) return self.__rbuf.read(sz) def write(self, buf): try: self.__wbuf.write(buf) except Exception as e: # on exception reset wbuf so it doesn't contain a partial function call self.__wbuf = BytesIO() raise e def flush(self): out = self.__wbuf.getvalue() # reset wbuf before write/flush to preserve state on underlying failure self.__wbuf = BytesIO() self.__trans.write(out) self.__trans.flush() # Implement the CReadableTransport interface. @property def cstringio_buf(self): return self.__rbuf def cstringio_refill(self, partialread, reqlen): retstring = partialread if reqlen < self.__rbuf_size: # try to make a read of as much as we can. retstring += self.__trans.read(self.__rbuf_size) # but make sure we do read reqlen bytes. if len(retstring) < reqlen: retstring += self.__trans.readAll(reqlen - len(retstring)) self.__rbuf = BytesIO(retstring) return self.__rbuf
TBufferedTransport
python
apache__airflow
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/callbacks.py
{ "start": 1295, "end": 6085 }
class ____: """ `KubernetesPodOperator` callbacks methods. Currently, the callbacks methods are not called in the async mode, this support will be added in the future. """ @staticmethod def on_sync_client_creation(*, client: k8s.CoreV1Api, operator: KubernetesPodOperator, **kwargs) -> None: """ Invoke this callback after creating the sync client. :param client: the created `kubernetes.client.CoreV1Api` client. """ pass @staticmethod def on_pod_manifest_created( *, pod_request: k8s.V1Pod, client: client_type, mode: str, operator: KubernetesPodOperator, context: Context, **kwargs, ) -> None: """ Invoke this callback after KPO creates the V1Pod manifest but before the pod is created. :param pod_request: the kubernetes pod manifest :param client: the Kubernetes client that can be used in the callback. :param mode: the current execution mode, it's one of (`sync`, `async`). """ pass @staticmethod def on_pod_creation( *, pod: k8s.V1Pod, client: client_type, mode: str, operator: KubernetesPodOperator, context: Context, **kwargs, ) -> None: """ Invoke this callback after creating the pod. :param pod: the created pod. :param client: the Kubernetes client that can be used in the callback. :param mode: the current execution mode, it's one of (`sync`, `async`). """ pass @staticmethod def on_pod_starting( *, pod: k8s.V1Pod, client: client_type, mode: str, operator: KubernetesPodOperator, context: Context, **kwargs, ) -> None: """ Invoke this callback when the pod starts. :param pod: the started pod. :param client: the Kubernetes client that can be used in the callback. :param mode: the current execution mode, it's one of (`sync`, `async`). """ pass @staticmethod def on_pod_completion( *, pod: k8s.V1Pod, client: client_type, mode: str, operator: KubernetesPodOperator, context: Context, **kwargs, ) -> None: """ Invoke this callback when the pod completes. :param pod: the completed pod. :param client: the Kubernetes client that can be used in the callback. :param mode: the current execution mode, it's one of (`sync`, `async`). """ pass @staticmethod def on_pod_teardown( *, pod: k8s.V1Pod, client: client_type, mode: str, operator: KubernetesPodOperator, context: Context, **kwargs, ) -> None: """ Invoke this callback after all pod completion callbacks but before the pod is deleted. :param pod: the completed pod. :param client: the Kubernetes client that can be used in the callback. :param mode: the current execution mode, it's one of (`sync`, `async`). """ pass @staticmethod def on_pod_cleanup( *, pod: k8s.V1Pod, client: client_type, mode: str, operator: KubernetesPodOperator, context: Context, **kwargs, ): """ Invoke this callback after cleaning/deleting the pod. :param pod: the completed pod. :param client: the Kubernetes client that can be used in the callback. :param mode: the current execution mode, it's one of (`sync`, `async`). """ pass @staticmethod def on_operator_resuming( *, pod: k8s.V1Pod, event: dict, client: client_type, mode: str, operator: KubernetesPodOperator, context: Context, **kwargs, ) -> None: """ Invoke this callback when resuming the `KubernetesPodOperator` from deferred state. :param pod: the current state of the pod. :param event: the returned event from the Trigger. :param client: the Kubernetes client that can be used in the callback. :param mode: the current execution mode, it's one of (`sync`, `async`). """ pass @staticmethod def progress_callback(*, line: str, client: client_type, mode: str, **kwargs) -> None: """ Invoke this callback to process pod container logs. :param line: the read line of log. :param client: the Kubernetes client that can be used in the callback. :param mode: the current execution mode, it's one of (`sync`, `async`). """ pass
KubernetesPodOperatorCallback
python
sqlalchemy__sqlalchemy
test/orm/test_immediate_load.py
{ "start": 381, "end": 5698 }
class ____(_fixtures.FixtureTest): run_inserts = "once" run_deletes = None @testing.combinations( ("raise",), ("raise_on_sql",), ("select",), ("immediate"), ) def test_basic_option(self, default_lazy): Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, self.tables.users, self.classes.User, ) self.mapper_registry.map_imperatively(Address, addresses) self.mapper_registry.map_imperatively( User, users, properties={"addresses": relationship(Address, lazy=default_lazy)}, ) sess = fixture_session() result = ( sess.query(User) .options(immediateload(User.addresses)) .filter(users.c.id == 7) .all() ) eq_(len(sess.identity_map), 2) sess.close() eq_( [ User( id=7, addresses=[Address(id=1, email_address="jack@bean.com")], ) ], result, ) @testing.combinations( ("raise",), ("raise_on_sql",), ("select",), ("immediate"), ) def test_basic_option_m2o(self, default_lazy): Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, self.tables.users, self.classes.User, ) self.mapper_registry.map_imperatively( Address, addresses, properties={"user": relationship(User, lazy=default_lazy)}, ) self.mapper_registry.map_imperatively(User, users) sess = fixture_session() result = ( sess.query(Address) .options(immediateload(Address.user)) .filter(Address.id == 1) .all() ) eq_(len(sess.identity_map), 2) sess.close() eq_( [Address(id=1, email_address="jack@bean.com", user=User(id=7))], result, ) def test_basic(self): Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, self.tables.users, self.classes.User, ) self.mapper_registry.map_imperatively(Address, addresses) self.mapper_registry.map_imperatively( User, users, properties={"addresses": relationship(Address, lazy="immediate")}, ) sess = fixture_session() result = sess.query(User).filter(users.c.id == 7).all() eq_(len(sess.identity_map), 2) sess.close() eq_( [ User( id=7, addresses=[Address(id=1, email_address="jack@bean.com")], ) ], result, ) @testing.combinations( ("joined",), ("selectin",), ("subquery",), ) def test_m2one_side(self, o2m_lazy): Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, self.tables.users, self.classes.User, ) self.mapper_registry.map_imperatively( Address, addresses, properties={ "user": relationship( User, lazy="immediate", back_populates="addresses" ) }, ) self.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship( Address, lazy=o2m_lazy, back_populates="user" ) }, ) sess = fixture_session() u1 = sess.query(User).filter(users.c.id == 7).one() sess.close() assert "addresses" in u1.__dict__ assert "user" in u1.addresses[0].__dict__ @testing.combinations( ("immediate",), ("joined",), ("selectin",), ("subquery",), ) def test_o2mone_side(self, m2o_lazy): Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, self.tables.users, self.classes.User, ) self.mapper_registry.map_imperatively( Address, addresses, properties={ "user": relationship( User, lazy=m2o_lazy, back_populates="addresses" ) }, ) self.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship( Address, lazy="immediate", back_populates="user" ) }, ) sess = fixture_session() u1 = sess.query(User).filter(users.c.id == 7).one() sess.close() assert "addresses" in u1.__dict__ # current behavior of "immediate" is that subsequent eager loaders # aren't fired off. This is because the "lazyload" strategy # does not invoke eager loaders. assert "user" not in u1.addresses[0].__dict__
ImmediateTest
python
keon__algorithms
tests/test_dp.py
{ "start": 3684, "end": 3865 }
class ____(unittest.TestCase): def test_job_scheduling(self): job1, job2 = Job(1, 3, 2), Job(2, 3, 4) self.assertEqual(4, schedule([job1, job2]))
TestJobScheduling
python
django__django
tests/template_tests/filter_tests/test_force_escape.py
{ "start": 169, "end": 2650 }
class ____(SimpleTestCase): """ Force_escape is applied immediately. It can be used to provide double-escaping, for example. """ @setup( { "force-escape01": ( "{% autoescape off %}{{ a|force_escape }}{% endautoescape %}" ) } ) def test_force_escape01(self): output = self.engine.render_to_string("force-escape01", {"a": "x&y"}) self.assertEqual(output, "x&amp;y") @setup({"force-escape02": "{{ a|force_escape }}"}) def test_force_escape02(self): output = self.engine.render_to_string("force-escape02", {"a": "x&y"}) self.assertEqual(output, "x&amp;y") @setup( { "force-escape03": ( "{% autoescape off %}{{ a|force_escape|force_escape }}" "{% endautoescape %}" ) } ) def test_force_escape03(self): output = self.engine.render_to_string("force-escape03", {"a": "x&y"}) self.assertEqual(output, "x&amp;amp;y") @setup({"force-escape04": "{{ a|force_escape|force_escape }}"}) def test_force_escape04(self): output = self.engine.render_to_string("force-escape04", {"a": "x&y"}) self.assertEqual(output, "x&amp;amp;y") # Because the result of force_escape is "safe", an additional # escape filter has no effect. @setup( { "force-escape05": ( "{% autoescape off %}{{ a|force_escape|escape }}{% endautoescape %}" ) } ) def test_force_escape05(self): output = self.engine.render_to_string("force-escape05", {"a": "x&y"}) self.assertEqual(output, "x&amp;y") @setup({"force-escape06": "{{ a|force_escape|escape }}"}) def test_force_escape06(self): output = self.engine.render_to_string("force-escape06", {"a": "x&y"}) self.assertEqual(output, "x&amp;y") @setup( { "force-escape07": ( "{% autoescape off %}{{ a|escape|force_escape }}{% endautoescape %}" ) } ) def test_force_escape07(self): output = self.engine.render_to_string("force-escape07", {"a": "x&y"}) self.assertEqual(output, "x&amp;amp;y") @setup({"force-escape08": "{{ a|escape|force_escape }}"}) def test_force_escape08(self): output = self.engine.render_to_string("force-escape08", {"a": "x&y"}) self.assertEqual(output, "x&amp;amp;y")
ForceEscapeTests
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 36975, "end": 37963 }
class ____(PipesMappingParamsLoader): """Params loader that extracts params from environment variables.""" def __init__(self): super().__init__(mapping=os.environ) def _env_var_to_cli_argument(env_var: str) -> str: return f"--{env_var}".lower().replace("_", "-") DAGSTER_PIPES_CONTEXT_CLI_ARGUMENT = _env_var_to_cli_argument(DAGSTER_PIPES_CONTEXT_ENV_VAR) DAGSTER_PIPES_MESSAGES_CLI_ARGUMENT = _env_var_to_cli_argument(DAGSTER_PIPES_MESSAGES_ENV_VAR) DAGSTER_PIPES_CLI_PARSER = argparse.ArgumentParser(description="Dagster Pipes CLI interface") DAGSTER_PIPES_CLI_PARSER.add_argument( DAGSTER_PIPES_CONTEXT_CLI_ARGUMENT, type=str, help="Argument with base64 encoded and zlib-compressed JSON string containing the Pipes context", ) DAGSTER_PIPES_CLI_PARSER.add_argument( DAGSTER_PIPES_MESSAGES_CLI_ARGUMENT, type=str, help="Argument with base64 encoded and zlib-compressed JSON string containing the Pipes messages", )
PipesEnvVarParamsLoader
python
scipy__scipy
scipy/optimize/tests/test_nnls.py
{ "start": 152, "end": 27195 }
class ____: def setup_method(self): self.rng = np.random.default_rng(1685225766635251) def test_nnls(self): a = np.arange(25.0).reshape(-1, 5) x = np.arange(5.0) y = a @ x x, res = nnls(a, y) assert res < 1e-7 assert np.linalg.norm((a @ x) - y) < 1e-7 def test_nnls_tall(self): a = self.rng.uniform(low=-10, high=10, size=[50, 10]) x = np.abs(self.rng.uniform(low=-2, high=2, size=[10])) x[::2] = 0 b = a @ x xact, rnorm = nnls(a, b) assert_allclose(xact, x, rtol=0., atol=1e-10) assert rnorm < 1e-12 def test_nnls_wide(self): # If too wide then problem becomes too ill-conditioned ans starts # emitting warnings, hence small m, n difference. a = self.rng.uniform(low=-10, high=10, size=[100, 120]) x = np.abs(self.rng.uniform(low=-2, high=2, size=[120])) x[::2] = 0 b = a @ x xact, rnorm = nnls(a, b) assert_allclose(xact, x, rtol=0., atol=1e-10) assert rnorm < 1e-12 def test_maxiter(self): # test that maxiter argument does stop iterations a = self.rng.uniform(size=(5, 10)) b = self.rng.uniform(size=5) with assert_raises(RuntimeError): nnls(a, b, maxiter=1) def test_nnls_inner_loop_case1(self): # See gh-20168 n = np.array( [3, 2, 0, 1, 1, 1, 3, 8, 14, 16, 29, 23, 41, 47, 53, 57, 67, 76, 103, 89, 97, 94, 85, 95, 78, 78, 78, 77, 73, 50, 50, 56, 68, 98, 95, 112, 134, 145, 158, 172, 213, 234, 222, 215, 216, 216, 206, 183, 135, 156, 110, 92, 63, 60, 52, 29, 20, 16, 12, 5, 5, 5, 1, 2, 3, 0, 2]) k = np.array( [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.7205812007860187, 0., 1.4411624015720375, 0.7205812007860187, 2.882324803144075, 5.76464960628815, 5.76464960628815, 12.249880413362318, 15.132205216506394, 20.176273622008523, 27.382085629868712, 48.27894045266326, 47.558359251877235, 68.45521407467177, 97.99904330689854, 108.0871801179028, 135.46926574777152, 140.51333415327366, 184.4687874012208, 171.49832578707245, 205.36564222401535, 244.27702706646033, 214.01261663344755, 228.42424064916793, 232.02714665309804, 205.36564222401535, 172.9394881886445, 191.67459940908097, 162.1307701768542, 153.48379576742198, 110.96950492104689, 103.04311171240067, 86.46974409432225, 60.528820866025576, 43.234872047161126, 23.779179625938617, 24.499760826724636, 17.29394881886445, 11.5292992125763, 5.76464960628815, 5.044068405502131, 3.6029060039300935, 0., 2.882324803144075, 0., 0., 0.]) d = np.array( [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.003889242101538, 0., 0.007606268390096, 0., 0.025457371599973, 0.036952882091577, 0., 0.08518359183449, 0.048201126400243, 0.196234990022205, 0.144116240157247, 0.171145134062442, 0., 0., 0.269555036538714, 0., 0., 0., 0.010893241091872, 0., 0., 0., 0., 0., 0., 0., 0., 0.048167058272886, 0.011238724891049, 0., 0., 0.055162603456078, 0., 0., 0., 0., 0.027753339088588, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) # The following code sets up a system of equations such that # $k_i-p_i*n_i$ is minimized for $p_i$ with weights $n_i$ and # monotonicity constraints on $p_i$. This translates to a system of # equations of the form $k_i - (d_1 + ... + d_i) * n_i$ and # non-negativity constraints on the $d_i$. If $n_i$ is zero the # system is modified such that $d_i - d_{i+1}$ is then minimized. N = len(n) A = np.diag(n) @ np.tril(np.ones((N, N))) w = n ** 0.5 nz = (n == 0).nonzero()[0] A[nz, nz] = 1 A[nz, np.minimum(nz + 1, N - 1)] = -1 w[nz] = 1 k[nz] = 0 W = np.diag(w) # Small perturbations can already make the infinite loop go away (just # uncomment the next line) # k = k + 1e-10 * np.random.normal(size=N) dact, _ = nnls(W @ A, W @ k) assert_allclose(dact, d, rtol=0., atol=1e-10) def test_nnls_inner_loop_case2(self): # See gh-20168 n = np.array( [1, 0, 1, 2, 2, 2, 3, 3, 5, 4, 14, 14, 19, 26, 36, 42, 36, 64, 64, 64, 81, 85, 85, 95, 95, 95, 75, 76, 69, 81, 62, 59, 68, 64, 71, 67, 74, 78, 118, 135, 153, 159, 210, 195, 218, 243, 236, 215, 196, 175, 185, 149, 144, 103, 104, 75, 56, 40, 32, 26, 17, 9, 12, 8, 2, 1, 1, 1]) k = np.array( [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.7064355064917867, 0., 0., 2.11930651947536, 0.7064355064917867, 0., 3.5321775324589333, 7.064355064917867, 11.302968103868587, 16.95445215580288, 20.486629688261814, 20.486629688261814, 37.44108184406469, 55.808405012851146, 78.41434122058831, 103.13958394780086, 105.965325973768, 125.74552015553803, 149.057891869767, 176.60887662294667, 197.09550631120848, 211.930651947536, 204.86629688261814, 233.8301526487814, 221.1143135319292, 195.6826352982249, 197.80194181770025, 191.4440222592742, 187.91184472681525, 144.11284332432447, 131.39700420747232, 116.5618585711448, 93.24948685691584, 89.01087381796512, 53.68909849337579, 45.211872415474346, 31.083162285638615, 24.72524272721253, 16.95445215580288, 9.890097090885014, 9.890097090885014, 2.8257420259671466, 2.8257420259671466, 1.4128710129835733, 0.7064355064917867, 1.4128710129835733]) d = np.array( [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.0021916146355674473, 0., 0., 0.011252740799789484, 0., 0., 0.037746623295934395, 0.03602328132946222, 0.09509167709829734, 0.10505765870204821, 0.01391037014274718, 0.0188296228752321, 0.20723559202324254, 0.3056220879462608, 0.13304643490426477, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.043185876949706214, 0.0037266261379722554, 0., 0., 0., 0., 0., 0.094797899357143, 0., 0., 0., 0., 0., 0., 0., 0., 0.23450935613672663, 0., 0., 0.07064355064917871]) # The following code sets up a system of equations such that # $k_i-p_i*n_i$ is minimized for $p_i$ with weights $n_i$ and # monotonicity constraints on $p_i$. This translates to a system of # equations of the form $k_i - (d_1 + ... + d_i) * n_i$ and # non-negativity constraints on the $d_i$. If $n_i$ is zero the # system is modified such that $d_i - d_{i+1}$ is then minimized. N = len(n) A = np.diag(n) @ np.tril(np.ones((N, N))) w = n ** 0.5 nz = (n == 0).nonzero()[0] A[nz, nz] = 1 A[nz, np.minimum(nz + 1, N - 1)] = -1 w[nz] = 1 k[nz] = 0 W = np.diag(w) dact, _ = nnls(W @ A, W @ k) p = np.cumsum(dact) assert np.all(dact >= 0) assert np.linalg.norm(k - n * p, ord=np.inf) < 28 assert_allclose(dact, d, rtol=0., atol=1e-10) def test_nnls_gh20302(self): # See gh-20302 A = np.array( [0.33408569134321575, 0.11136189711440525, 0.049140798007949286, 0.03712063237146841, 0.055680948557202625, 0.16642814595936478, 0.11095209730624318, 0.09791993030943345, 0.14793612974165757, 0.44380838922497273, 0.11099502671044059, 0.11099502671044059, 0.14693672599330593, 0.3329850801313218, 1.498432860590948, 0.0832374225132955, 0.11098323001772734, 0.19589481249472837, 0.5919105600945457, 3.5514633605672747, 0.06658716751427037, 0.11097861252378394, 0.24485832778293645, 0.9248217710315328, 6.936163282736496, 0.05547609388181014, 0.11095218776362029, 0.29376003042571264, 1.3314262531634435, 11.982836278470993, 0.047506113282944136, 0.11084759766020298, 0.3423969672933396, 1.8105107617833156, 19.010362998724812, 0.041507335004505576, 0.11068622667868154, 0.39074115283013344, 2.361306169145206, 28.335674029742474, 0.03682846280947718, 0.11048538842843154, 0.4387861797121048, 2.9831054875676517, 40.2719240821633, 0.03311278164362387, 0.11037593881207958, 0.4870572300443105, 3.6791979604026523, 55.187969406039784, 0.030079304092299915, 0.11029078167176636, 0.5353496017200152, 4.448394860761242, 73.3985152025605, 0.02545939709595835, 0.11032405408248619, 0.6328767609778363, 6.214921713313388, 121.19097340961108, 0.022080881724881523, 0.11040440862440762, 0.7307742886903428, 8.28033064683057, 186.30743955368786, 0.020715838214945492, 0.1104844704797093, 0.7800578384588346, 9.42800814760186, 226.27219554244465, 0.01843179728340054, 0.11059078370040323, 0.8784095015912599, 11.94380463964355, 322.48272527037585, 0.015812787653789077, 0.11068951357652354, 1.0257259848595766, 16.27135849574896, 512.5477926160922, 0.014438550529330062, 0.11069555405819713, 1.1234754801775881, 19.519316032262093, 673.4164031130423, 0.012760770585072577, 0.110593345070629, 1.2688431112524712, 24.920367089248398, 971.8943164806875, 0.011427556646114315, 0.11046638091243838, 1.413623342459821, 30.967408782453557, 1347.0822820367298, 0.010033330264470307, 0.11036663290917338, 1.6071533470570285, 40.063087746029936, 1983.122843428482, 0.008950061496507258, 0.11038409179025618, 1.802244865119193, 50.37194055362024, 2795.642700725923, 0.008071078821135658, 0.11030474388885401, 1.9956465761433504, 61.80742482572119, 3801.1566267818534, 0.007191031207777556, 0.11026247851925586, 2.238160187262168, 77.7718015155818, 5366.2543045751445, 0.00636834224248, 0.11038459886965334, 2.5328963107984297, 99.49331844784753, 7760.4788389321075, 0.005624259098118485, 0.11061042892966355, 2.879742607664547, 128.34496770138628, 11358.529641572684, 0.0050354270614989555, 0.11077939535297703, 3.2263279459292575, 160.85168205252265, 15924.316523199741, 0.0044997853165982555, 0.1109947044760903, 3.6244287189055613, 202.60233390369015, 22488.859063309606, 0.004023601950058174, 0.1113196539516095, 4.07713905729421, 255.6270320242126, 31825.565487014468, 0.0036024117873727094, 0.111674765408554, 4.582933773135057, 321.9583486728612, 44913.18963986413, 0.003201503089582304, 0.11205260813538065, 5.191786833370116, 411.79333489752383, 64857.45024636, 0.0028633044552448853, 0.11262330857296549, 5.864295861648949, 522.7223161899905, 92521.84996562831, 0.0025691897303891965, 0.11304434813712465, 6.584584405106342, 656.5615739804199, 129999.19164812315, 0.0022992911894424675, 0.11343169867916175, 7.4080129906658305, 828.2026426227864, 183860.98666225857, 0.0020449922071108764, 0.11383789952917212, 8.388975556433872, 1058.2750599896935, 265097.9025274183, 0.001831274615120854, 0.11414945100919989, 9.419351803810935, 1330.564050780237, 373223.2162438565, 0.0016363333454631633, 0.11454333418242145, 10.6143816579462, 1683.787012481595, 530392.9089317025, 0.0014598610433380044, 0.11484240207592301, 11.959688127956882, 2132.0874753402027, 754758.9662704318, 0.0012985240015312626, 0.11513579480243862, 13.514425358573531, 2715.5160990137824, 1083490.9235064993, 0.0011614735761289934, 0.11537304189548002, 15.171418602667567, 3415.195870828736, 1526592.554260445, 0.0010347472698811352, 0.11554677847006009, 17.080800985009617, 4322.412404600832, 2172012.2333119176, 0.0009232988811258664, 0.1157201264344419, 19.20004861829407, 5453.349531598553, 3075689.135821584, 0.0008228871862975205, 0.11602709326795038, 21.65735242414206, 6920.203923780365, 4390869.389638642, 0.00073528900066722, 0.11642075843897651, 24.40223571298994, 8755.811207598026, 6238515.485413593, 0.0006602764384729194, 0.11752920604817965, 27.694443541914293, 11171.386093291572, 8948280.260726549, 0.0005935538977939806, 0.11851292825953147, 31.325508920763063, 14174.185724149384, 12735505.873148222, 0.0005310755355633124, 0.11913794514470308, 35.381052949627765, 17987.010118815077, 18157886.71494382, 0.00047239949671590953, 0.1190446731724092, 39.71342528048061, 22679.438775422022, 25718483.571328573, 0.00041829129789387623, 0.11851586773659825, 44.45299332965028, 28542.57147989741, 36391778.63686921, 0.00037321512015419886, 0.11880681324908665, 50.0668539579632, 36118.26128449941, 51739409.29004541, 0.0003315539616702064, 0.1184752823034871, 56.04387059062639, 45383.29960621684, 72976345.76679668, 0.00029456064937920213, 0.11831519416731286, 62.91195073220101, 57265.53993693082, 103507463.43600245, 0.00026301867496859703, 0.11862142241083726, 70.8217262087034, 72383.14781936012, 146901598.49939138, 0.00023618734450420032, 0.11966825454879482, 80.26535457124461, 92160.51176984518, 210125966.835247, 0.00021165918071578316, 0.12043407382728061, 90.7169587544247, 116975.56852918258, 299515943.218972, 0.00018757727511329545, 0.11992440455576689, 101.49899864101785, 147056.26174166967, 423080865.0307836, 0.00016654469159895833, 0.11957908856805206, 113.65970431102812, 184937.67016486943, 597533612.3026931, 0.00014717439179415048, 0.11872067604728138, 126.77899683346702, 231758.58906776624, 841283678.3159915, 0.00012868496382376066, 0.1166314722122684, 139.93635237349534, 287417.30847929465, 1172231492.6328032, 0.00011225559452625302, 0.11427619522772557, 154.0034283704458, 355281.4912295324, 1627544511.322488, 9.879511142981067e-05, 0.11295574406808354, 170.96532050841535, 442971.0111288653, 2279085852.2580123, 8.71257780313587e-05, 0.11192758284428547, 190.35067416684697, 554165.2523674504, 3203629323.93623, 7.665069027765277e-05, 0.11060694607065294, 211.28835951100046, 690933.608546013, 4486577387.093535, 6.734021094824451e-05, 0.10915848194710433, 234.24338803525194, 860487.9079859136, 6276829044.8032465, 5.9191625040287665e-05, 0.10776821865668373, 259.7454711820425, 1071699.0387579766, 8780430224.544102, 5.1856803674907676e-05, 0.10606444911641115, 287.1843540288165, 1331126.3723998806, 12251687131.5685, 4.503421404759231e-05, 0.10347361247668461, 314.7338642485931, 1638796.0697522392, 16944331963.203278, 3.90470387455642e-05, 0.1007804070023012, 344.3427560918527, 2014064.4865519698, 23392351979.057854, 3.46557661636393e-05, 0.10046706610839032, 385.56603915081587, 2533036.2523656, 33044724430.235435, 3.148745865254635e-05, 0.1025441570117926, 442.09038234164746, 3262712.3882769793, 47815050050.199135, 2.9790762078715404e-05, 0.1089845379379672, 527.8068231298969, 4375751.903321453, 72035815708.42941, 2.8772639817606534e-05, 0.11823636789048445, 643.2048194503195, 5989838.001888927, 110764084330.93005, 2.7951691815106586e-05, 0.12903432664913705, 788.5500418523591, 8249371.000613411, 171368308481.2427, 2.6844392423114212e-05, 0.1392060709754626, 955.6296403631383, 11230229.319931043, 262063016295.25085, 2.499458273851386e-05, 0.14559344445184325, 1122.7022399726002, 14820229.698461473, 388475270970.9214, 2.337386729019776e-05, 0.15294300496886065, 1324.8158105672455, 19644861.137128454, 578442936182.7473, 2.0081014872174113e-05, 0.14760215298210377, 1436.2385042492353, 23923681.729276657, 791311658718.4193, 1.773374462991839e-05, 0.14642752940923615, 1600.5596278736678, 29949429.82503553, 1112815989293.9326, 1.5303115839590797e-05, 0.14194150045081785, 1742.873058605698, 36634451.931305364, 1529085389160.7544, 1.3148448731163076e-05, 0.13699368732998807, 1889.5284359054356, 44614279.74469635, 2091762812969.9607, 1.1739194407590062e-05, 0.13739553134643406, 2128.794599579694, 56462810.11822766, 2973783283306.8145, 1.0293367506254706e-05, 0.13533033372723272, 2355.372854690074, 70176508.28667311, 4151852759764.441, 9.678312586863569e-06, 0.14293577249119244, 2794.531827932675, 93528671.31952812, 6215821967224.52, -1.174086323572049e-05, 0.1429501325944908, 3139.4804810720925, 118031680.16618933, -6466892421886.174, -2.1188265307407812e-05, 0.1477108290912869, 3644.1133424610953, 153900132.62392554, -4828013117542.036, -8.614483025123122e-05, 0.16037100755883044, 4444.386620899393, 210846007.89660168, -1766340937974.433, 4.981445776141726e-05, 0.16053420251962536, 4997.558254401547, 266327328.4755411, 3862250287024.725, 1.8500019169456637e-05, 0.15448417164977674, 5402.289867444643, 323399508.1475582, 12152445411933.408, -5.647882376069748e-05, 0.1406372975946189, 5524.633133597753, 371512945.9909363, -4162951345292.1514, 2.8048523486337994e-05, 0.13183417571186926, 5817.462495763679, 439447252.3728975, 9294740538175.03]).reshape(89, 5) b = np.ones(89, dtype=np.float64) sol, rnorm = nnls(A, b) assert_allclose(sol, np.array([0.61124315, 8.22262829, 0., 0., 0.])) assert_allclose(rnorm, 1.0556460808977297) def test_nnls_gh21021_ex1(self): # Review examples used in gh-21021 A = [[0.004734199143798789, -0.09661916455815653, -0.04308779048103441, 0.4039475561867938, -0.27742598780954364, -0.20816924034369574, -0.17264070902176, 0.05251808558963846], [-0.030263548855047975, -0.30356483926431466, 0.18080406600591398, -0.06892233941254086, -0.41837298885432317, 0.30245352819647003, -0.19008975278116397, -0.00990809825429995], [-0.2561747595787612, -0.04376282125249583, 0.4422181991706678, -0.13720906318924858, -0.0069523811763796475, -0.059238287107464795, 0.028663214369642594, 0.5415531284893763], [0.2949336072968401, 0.33997647534935094, 0.38441519339815755, -0.306001783010386, 0.18120773805949028, -0.36669767490747895, -0.021539960590992304, -0.2784251712424615], [0.5009075736232653, -0.20161970347571165, 0.08404512586550646, 0.2520496489348788, 0.14812015101612894, -0.25823455803981266, -0.1596872058396596, 0.5960141613922691] ] b = [18.036779281222124, -18.126530733870887, 13.535652034584029, -2.6654275476795966, 9.166315328199575] # Obtained from matlab's lstnonneg des_sol = np.array([0., 118.017802006619, 45.1996532316584, 102.62156313537, 0., 55.8590204314398, 0., 29.7328833253434]) sol, res = nnls(A, b) assert_allclose(sol, des_sol) assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14 def test_nnls_gh21021_ex2(self): A = np.array([ [0.2508259992635229, -0.24031300195203256], [0.510647748500133, 0.2872936081767836], [0.8196387904102849, -0.03520620107046682], [0.030739759120097084, -0.07768656359879388]]) b = np.array([24.456141951303913, 28.047143273432333, 41.10526799545987, -1.2078282698324068]) sol, res = nnls(A, b) assert_allclose(sol, np.array([54.3047953202271, 0.0])) assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14 def test_nnls_gh21021_ex3(self): A = np.array([ [0.08247592017366788, 0.058398241636675674, -0.1031496693415968, 0.03156983127072098, -0.029503680182026665], [0.21463607509982277, -0.2164518969308173, -0.10816833396662294, 0.12133867146012027, -0.15025010408668332], [0.07251900316494089, -0.003044559315020767, 0.042682817961676424, -0.018157525489298176, 0.11561953260568134], [0.2328797918159187, -0.09112909645892767, 0.21348169727099078, 0.00449447624089599, -0.16615256386885716], [-0.02440856024843897, -0.20131427208575386, 0.030275781997161483, -0.04560777213546784, 0.11007266012013553], [-0.2928391429686263, -0.20437574856615687, -0.020892110811574407, -0.10455040720819309, 0.05337267000160461], [0.22041503019400316, 0.014262782992311842, 0.08274606359871121, -0.17933172096518907, -0.11809690350702161], [0.10440436007469953, 0.09171452270577712, 0.03942347724809893, 0.11457669688231396, 0.07529747295631585], [-0.052087576116032056, -0.15787717158077047, -0.08232202515883282, -0.03194837933710708, -0.0546812506025729], [-0.010388407673304468, 0.015174707581808923, 0.04764509565386281, -0.1781221936030805, 0.10218894080536609], [0.03272263140115928, -0.27576456949442574, 0.024897570959901753, -0.1417129166632282, -0.03320796462136591], [-0.12490006751823997, -0.03012003515442302, -0.051495264012509506, 0.012070729698374614, 0.04811700123118234], [0.15254854117990788, -0.051863547789218374, 0.058012914127346174, -0.06717991061422621, -0.14514671564242257], [0.12251250415395559, -0.17462495626695362, -0.025334728552179834, 0.11425350676877533, 0.06183915953812639], [0.19334259720491218, 0.2164301986218955, -0.018882278726614483, 0.07950236716817938, -0.2220529357431092], [-0.01822205701890852, 0.12630444976752267, -0.03118092027244001, 0.02773743885242581, 0.06444433740044248], [0.13344116850581977, -0.05142877469996826, 0.3385702016705455, -0.25814970787123004, 0.2679034842977378], [0.1309747058619377, 0.12090608957940627, -0.13957978654106512, 0.17048819760322642, -0.241775259969348], [0.28613102173467275, -0.47153463906732174, 0.20359970518269746, -0.0962095202871843, -0.07703076550836387], [0.2212788380372723, 0.02569245145758152, -0.021596152392209966, 0.04610005150029433, -0.2024454395619734], [-0.043225338359410316, 0.17816095186290315, -0.014709092962616079, 0.06993970293287989, -0.09033722782555903], [0.17747622942563512, -0.20991014784011458, 0.06265720409894943, 0.0689704059061795, 0.024474319398401525], [-0.1163880385601698, 0.29989570587630027, 0.033443765320984545, 0.008470296514656, -0.0014457113271462002], [0.024375314902718406, 0.05279830705548363, 0.02691082431023144, 0.05265079368002343, 0.15542988147487913], [-0.01855218360922308, -0.050265869142888164, 0.2567912677240452, -0.2606428528561333, 0.25334396245022245]]) b = np.array([-7.876625373734849, -8.259856278691373, 3.2593082374900963, 16.30170376973345, 2.311892943629045, -1.595345202555738, 6.318582970536518, 3.0104212955340093, -6.286202915842167, 3.6382333725029294, 1.9012066681249356, -3.932236581436514, 4.4299317131740406, -1.9345885161292682, -1.4418721521970805, -2.3810103256943926, 25.853603392922526, -10.658470311610483, 15.547103681119214, -1.6491066136547277, -1.1232029689817422, 4.7845749463206975, 2.553803732013229, 2.0549409701753705, 19.60887153608244]) sol, res = nnls(A, b) assert_allclose(sol, np.array([0.0, 0.0, 76.3611306173957, 0.0, 0.0]), atol=5e-14) assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14 def test_atol_deprecation_warning(self): """Test that using atol parameter triggers deprecation warning""" a = np.array([[1, 0], [1, 0], [0, 1]]) b = np.array([2, 1, 1]) with pytest.warns(DeprecationWarning, match="{'atol'}"): nnls(a, b, atol=1e-8) def test_2D_singleton_RHS_input(self): # Test that a 2D singleton RHS input is accepted A = np.array([[1.0, 0.5, -1.], [1.0, 0.5, 0.0], [-1., 0.0, 1.0]]) b = np.array([[-1.0, 2.0, 2.0]]).T x, r = nnls(A, b) assert_allclose(x, np.array([1.0, 2.0, 3.0])) assert_allclose(r, 0.0) def test_2D_not_singleton_RHS_input_2(self): # Test that a 2D but not a column vector RHS input is rejected A = np.array([[1.0, 0.5, -1.], [1.0, 0.5, 0.0], [1.0, 0.5, 0.0], [0.0, 0.0, 1.0]]) b = np.ones(shape=[4, 2], dtype=np.float64) with pytest.raises(ValueError, match="Expected a 1D array"): nnls(A, b) def test_gh_22791_32bit(self): # Scikit-learn got hit by this problem on 32-bit arch. desired = [0, 0, 1.05617285, 0, 0, 0, 0, 0.23123048, 0, 0, 0, 0.26128651] rng = np.random.RandomState(42) n_samples, n_features = 5, 12 X = rng.randn(n_samples, n_features) X[:2, :] = 0 y = rng.randn(n_samples) coef, _ = nnls(X, y) assert_allclose(coef, desired)
TestNNLS
python
kamyu104__LeetCode-Solutions
Python/number-of-ways-to-earn-points.py
{ "start": 553, "end": 1069 }
class ____(object): def waysToReachTarget(self, target, types): """ :type target: int :type types: List[List[int]] :rtype: int """ MOD = 10**9+7 dp = [0]*(target+1) dp[0] = 1 for c, m in types: new_dp = [0]*(target+1) for i in xrange(target+1): for j in xrange(min((target-i)//m, c)+1): new_dp[i+j*m] = (new_dp[i+j*m]+dp[i])%MOD dp = new_dp return dp[-1]
Solution2
python
wandb__wandb
wandb/vendor/pygments/lexers/javascript.py
{ "start": 45696, "end": 49395 }
class ____(RegexLexer): """ For `Mask <http://github.com/atmajs/MaskJS>`__ markup. .. versionadded:: 2.0 """ name = 'Mask' aliases = ['mask'] filenames = ['*.mask'] mimetypes = ['text/x-mask'] flags = re.MULTILINE | re.IGNORECASE | re.DOTALL tokens = { 'root': [ (r'\s+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline), (r'[{};>]', Punctuation), (r"'''", String, 'string-trpl-single'), (r'"""', String, 'string-trpl-double'), (r"'", String, 'string-single'), (r'"', String, 'string-double'), (r'([\w-]+)', Name.Tag, 'node'), (r'([^.#;{>\s]+)', Name.Class, 'node'), (r'(#[\w-]+)', Name.Function, 'node'), (r'(\.[\w-]+)', Name.Variable.Class, 'node') ], 'string-base': [ (r'\\.', String.Escape), (r'~\[', String.Interpol, 'interpolation'), (r'.', String.Single), ], 'string-single': [ (r"'", String.Single, '#pop'), include('string-base') ], 'string-double': [ (r'"', String.Single, '#pop'), include('string-base') ], 'string-trpl-single': [ (r"'''", String.Single, '#pop'), include('string-base') ], 'string-trpl-double': [ (r'"""', String.Single, '#pop'), include('string-base') ], 'interpolation': [ (r'\]', String.Interpol, '#pop'), (r'\s*:', String.Interpol, 'expression'), (r'\s*\w+:', Name.Other), (r'[^\]]+', String.Interpol) ], 'expression': [ (r'[^\]]+', using(JavascriptLexer), '#pop') ], 'node': [ (r'\s+', Text), (r'\.', Name.Variable.Class, 'node-class'), (r'\#', Name.Function, 'node-id'), (r'style[ \t]*=', Name.Attribute, 'node-attr-style-value'), (r'[\w:-]+[ \t]*=', Name.Attribute, 'node-attr-value'), (r'[\w:-]+', Name.Attribute), (r'[>{;]', Punctuation, '#pop') ], 'node-class': [ (r'[\w-]+', Name.Variable.Class), (r'~\[', String.Interpol, 'interpolation'), default('#pop') ], 'node-id': [ (r'[\w-]+', Name.Function), (r'~\[', String.Interpol, 'interpolation'), default('#pop') ], 'node-attr-value': [ (r'\s+', Text), (r'\w+', Name.Variable, '#pop'), (r"'", String, 'string-single-pop2'), (r'"', String, 'string-double-pop2'), default('#pop') ], 'node-attr-style-value': [ (r'\s+', Text), (r"'", String.Single, 'css-single-end'), (r'"', String.Single, 'css-double-end'), include('node-attr-value') ], 'css-base': [ (r'\s+', Text), (r";", Punctuation), (r"[\w\-]+\s*:", Name.Builtin) ], 'css-single-end': [ include('css-base'), (r"'", String.Single, '#pop:2'), (r"[^;']+", Name.Entity) ], 'css-double-end': [ include('css-base'), (r'"', String.Single, '#pop:2'), (r'[^;"]+', Name.Entity) ], 'string-single-pop2': [ (r"'", String.Single, '#pop:2'), include('string-base') ], 'string-double-pop2': [ (r'"', String.Single, '#pop:2'), include('string-base') ], }
MaskLexer
python
django__django
tests/mail/tests.py
{ "start": 107799, "end": 109416 }
class ____(BaseEmailBackendTests, SimpleTestCase): email_backend = "django.core.mail.backends.console.EmailBackend" def setUp(self): super().setUp() self.__stdout = sys.stdout self.stream = sys.stdout = StringIO() def tearDown(self): del self.stream sys.stdout = self.__stdout del self.__stdout super().tearDown() def flush_mailbox(self): self.stream = sys.stdout = StringIO() def get_mailbox_content(self): messages = self.stream.getvalue().split("\n" + ("-" * 79) + "\n") return [message_from_bytes(m.encode()) for m in messages if m] def test_console_stream_kwarg(self): """ The console backend can be pointed at an arbitrary stream. """ s = StringIO() connection = mail.get_connection( "django.core.mail.backends.console.EmailBackend", stream=s ) send_mail( "Subject", "Content", "from@example.com", ["to@example.com"], connection=connection, ) message = s.getvalue().split("\n" + ("-" * 79) + "\n")[0].encode() self.assertMessageHasHeaders( message, { ("MIME-Version", "1.0"), ("Content-Type", 'text/plain; charset="utf-8"'), ("Content-Transfer-Encoding", "7bit"), ("Subject", "Subject"), ("From", "from@example.com"), ("To", "to@example.com"), }, ) self.assertIn(b"\nDate: ", message)
ConsoleBackendTests
python
pytorch__pytorch
torch/nn/modules/conv.py
{ "start": 57353, "end": 57724 }
class ____(_ConvTransposeNd): @deprecated( "`_ConvTransposeMixin` is a deprecated internal class. " "Please consider using public APIs.", category=FutureWarning, ) def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) # TODO: Conv2dLocal # TODO: Conv2dMap # TODO: ConvTranspose2dMap
_ConvTransposeMixin
python
automl__auto-sklearn
autosklearn/pipeline/components/classification/multinomial_nb.py
{ "start": 490, "end": 3315 }
class ____(AutoSklearnClassificationAlgorithm): def __init__(self, alpha, fit_prior, random_state=None, verbose=0): self.alpha = alpha self.fit_prior = fit_prior self.random_state = random_state self.verbose = int(verbose) self.estimator = None def fit(self, X, y): import scipy.sparse import sklearn.naive_bayes self.fit_prior = check_for_bool(self.fit_prior) self.alpha = float(self.alpha) self.n_iter = 0 self.fully_fit_ = False self.estimator = sklearn.naive_bayes.MultinomialNB( alpha=self.alpha, fit_prior=self.fit_prior, ) self.classes_ = np.unique(y.astype(int)) # Because the pipeline guarantees that each feature is positive, # clip all values below zero to zero if scipy.sparse.issparse(X): X.data[X.data < 0] = 0.0 else: X[X < 0] = 0.0 # Fallback for multilabel classification if len(y.shape) > 1 and y.shape[1] > 1: import sklearn.multiclass self.estimator = sklearn.multiclass.OneVsRestClassifier( self.estimator, n_jobs=1 ) self.estimator.fit(X, y) return self def predict(self, X): if self.estimator is None: raise NotImplementedError return self.estimator.predict(X) def predict_proba(self, X): if self.estimator is None: raise NotImplementedError() return self.estimator.predict_proba(X) @staticmethod def get_properties(dataset_properties=None): return { "shortname": "MultinomialNB", "name": "Multinomial Naive Bayes classifier", "handles_regression": False, "handles_classification": True, "handles_multiclass": True, "handles_multilabel": True, "handles_multioutput": False, "is_deterministic": True, "input": (DENSE, SPARSE, SIGNED_DATA), "output": (PREDICTIONS,), } @staticmethod def get_hyperparameter_search_space( feat_type: Optional[FEAT_TYPE_TYPE] = None, dataset_properties=None ): cs = ConfigurationSpace() # the smoothing parameter is a non-negative float # I will limit it to 100 and put it on a logarithmic scale. (SF) # Please adjust that, if you know a proper range, this is just a guess. alpha = UniformFloatHyperparameter( name="alpha", lower=1e-2, upper=100, default_value=1, log=True ) fit_prior = CategoricalHyperparameter( name="fit_prior", choices=["True", "False"], default_value="True" ) cs.add_hyperparameters([alpha, fit_prior]) return cs
MultinomialNB
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/verified_permissions.py
{ "start": 1041, "end": 1799 }
class ____(AwsGenericHook["VerifiedPermissionsClient"]): """ Interact with Amazon Verified Permissions. Provide thin wrapper around :external+boto3:py:class:`boto3.client("verifiedpermissions") <VerifiedPermissions.Client>`. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying AwsBaseHook. .. seealso:: - :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` - `Amazon Appflow API Reference <https://docs.aws.amazon.com/verifiedpermissions/latest/apireference/Welcome.html>`__ """ def __init__(self, *args, **kwargs) -> None: kwargs["client_type"] = "verifiedpermissions" super().__init__(*args, **kwargs)
VerifiedPermissionsHook
python
oauthlib__oauthlib
oauthlib/oauth1/rfc5849/endpoints/request_token.py
{ "start": 518, "end": 9291 }
class ____(BaseEndpoint): """An endpoint responsible for providing OAuth 1 request tokens. Typical use is to instantiate with a request validator and invoke the ``create_request_token_response`` from a view function. The tuple returned has all information necessary (body, status, headers) to quickly form and return a proper response. See :doc:`/oauth1/validator` for details on which validator methods to implement for this endpoint. """ def create_request_token(self, request, credentials): """Create and save a new request token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param credentials: A dict of extra token credentials. :returns: The token as an urlencoded string. """ token = { 'oauth_token': self.token_generator(), 'oauth_token_secret': self.token_generator(), 'oauth_callback_confirmed': 'true' } token.update(credentials) self.request_validator.save_request_token(token, request) return urlencode(token.items()) def create_request_token_response(self, uri, http_method='GET', body=None, headers=None, credentials=None): """Create a request token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :param credentials: A list of extra credentials to include in the token. :returns: A tuple of 3 elements. 1. A dict of headers to set on the response. 2. The response body as a string. 3. The response status code as an integer. An example of a valid request:: >>> from your_validator import your_validator >>> from oauthlib.oauth1 import RequestTokenEndpoint >>> endpoint = RequestTokenEndpoint(your_validator) >>> h, b, s = endpoint.create_request_token_response( ... 'https://your.provider/request_token?foo=bar', ... headers={ ... 'Authorization': 'OAuth realm=movies user, oauth_....' ... }, ... credentials={ ... 'my_specific': 'argument', ... }) >>> h {'Content-Type': 'application/x-www-form-urlencoded'} >>> b 'oauth_token=lsdkfol23w54jlksdef&oauth_token_secret=qwe089234lkjsdf&oauth_callback_confirmed=true&my_specific=argument' >>> s 200 An response to invalid request would have a different body and status:: >>> b 'error=invalid_request&description=missing+callback+uri' >>> s 400 The same goes for an an unauthorized request: >>> b '' >>> s 401 """ resp_headers = {'Content-Type': 'application/x-www-form-urlencoded'} try: request = self._create_request(uri, http_method, body, headers) valid, processed_request = self.validate_request_token_request( request) if valid: token = self.create_request_token(request, credentials or {}) return resp_headers, token, 200 else: return {}, None, 401 except errors.OAuth1Error as e: return resp_headers, e.urlencoded, e.status_code def validate_request_token_request(self, request): """Validate a request token request. :param request: OAuthlib request. :type request: oauthlib.common.Request :raises: OAuth1Error if the request is invalid. :returns: A tuple of 2 elements. 1. The validation result (True or False). 2. The request object. """ self._check_transport_security(request) self._check_mandatory_parameters(request) if request.realm: request.realms = request.realm.split(' ') else: request.realms = self.request_validator.get_default_realms( request.client_key, request) if not self.request_validator.check_realms(request.realms): raise errors.InvalidRequestError( description='Invalid realm {}. Allowed are {!r}.'.format( request.realms, self.request_validator.realms)) if not request.redirect_uri: raise errors.InvalidRequestError( description='Missing callback URI.') if not self.request_validator.validate_timestamp_and_nonce( request.client_key, request.timestamp, request.nonce, request, request_token=request.resource_owner_key): return False, request # The server SHOULD return a 401 (Unauthorized) status code when # receiving a request with invalid client credentials. # Note: This is postponed in order to avoid timing attacks, instead # a dummy client is assigned and used to maintain near constant # time request verification. # # Note that early exit would enable client enumeration valid_client = self.request_validator.validate_client_key( request.client_key, request) if not valid_client: request.client_key = self.request_validator.dummy_client # Note that `realm`_ is only used in authorization headers and how # it should be interpreted is not included in the OAuth spec. # However they could be seen as a scope or realm to which the # client has access and as such every client should be checked # to ensure it is authorized access to that scope or realm. # .. _`realm`: https://tools.ietf.org/html/rfc2617#section-1.2 # # Note that early exit would enable client realm access enumeration. # # The require_realm indicates this is the first step in the OAuth # workflow where a client requests access to a specific realm. # This first step (obtaining request token) need not require a realm # and can then be identified by checking the require_resource_owner # flag and absence of realm. # # Clients obtaining an access token will not supply a realm and it will # not be checked. Instead the previously requested realm should be # transferred from the request token to the access token. # # Access to protected resources will always validate the realm but note # that the realm is now tied to the access token and not provided by # the client. valid_realm = self.request_validator.validate_requested_realms( request.client_key, request.realms, request) # Callback is normally never required, except for requests for # a Temporary Credential as described in `Section 2.1`_ # .._`Section 2.1`: https://tools.ietf.org/html/rfc5849#section-2.1 valid_redirect = self.request_validator.validate_redirect_uri( request.client_key, request.redirect_uri, request) if not request.redirect_uri: raise NotImplementedError('Redirect URI must either be provided ' 'or set to a default during validation.') valid_signature = self._check_signature(request) # log the results to the validator_log # this lets us handle internal reporting and analysis request.validator_log['client'] = valid_client request.validator_log['realm'] = valid_realm request.validator_log['callback'] = valid_redirect request.validator_log['signature'] = valid_signature # We delay checking validity until the very end, using dummy values for # calculations and fetching secrets/keys to ensure the flow of every # request remains almost identical regardless of whether valid values # have been supplied. This ensures near constant time execution and # prevents malicious users from guessing sensitive information v = all((valid_client, valid_realm, valid_redirect, valid_signature)) if not v: log.info("[Failure] request verification failed.") log.info("Valid client: %s.", valid_client) log.info("Valid realm: %s.", valid_realm) log.info("Valid callback: %s.", valid_redirect) log.info("Valid signature: %s.", valid_signature) return v, request
RequestTokenEndpoint
python
fastapi__sqlmodel
docs_src/tutorial/fastapi/relationships/tutorial001.py
{ "start": 635, "end": 848 }
class ____(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id")
HeroBase
python
astropy__astropy
astropy/time/formats.py
{ "start": 21080, "end": 22268 }
class ____(TimeNumeric): """ Modified Julian Date time format. This represents the number of days since midnight on November 17, 1858. For example, 51544.0 in MJD is midnight on January 1, 2000. """ name = "mjd" def set_jds(self, val1, val2): self._check_scale(self._scale) # Validate scale. jd1, jd2 = day_frac(val1, val2) jd1 += erfa.DJM0 # erfa.DJM0=2400000.5 (from erfam.h). self.jd1, self.jd2 = day_frac(jd1, jd2) def to_value(self, **kwargs): jd1 = self.jd1 - erfa.DJM0 # This cannot lose precision. jd2 = self.jd2 return super().to_value(jd1=jd1, jd2=jd2, **kwargs) value = property(to_value) def _check_val_type_not_quantity(format_name, val1, val2): # If val2 is a Quantity, the super() call that follows this check # will raise a TypeError. if hasattr(val1, "to") and getattr(val1, "unit", None) is not None: raise ValueError( f"cannot use Quantities for {format_name!r} format, as the unit of year " "is defined as 365.25 days, while the length of year is variable " "in this format. Use float instead." )
TimeMJD
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 24860, "end": 24983 }
class ____(str, Enum): """ Perimssion that represents ownership of the job. """ isowner = "IS_OWNER"
IsOwner
python
numba__llvmlite
llvmlite/binding/executionengine.py
{ "start": 9690, "end": 11022 }
class ____(Structure): _fields_ = [ ('module_ptr', ffi.LLVMModuleRef), ('buf_ptr', c_void_p), ('buf_len', c_size_t), ] _ObjectCacheNotifyFunc = CFUNCTYPE(None, py_object, POINTER(_ObjectCacheData)) _ObjectCacheGetBufferFunc = CFUNCTYPE(None, py_object, POINTER(_ObjectCacheData)) # XXX The ctypes function wrappers are created at the top-level, otherwise # there are issues when creating CFUNCTYPEs in child processes on CentOS 5 # 32 bits. _notify_c_hook = _ObjectCacheNotifyFunc( ExecutionEngine._raw_object_cache_notify) _getbuffer_c_hook = _ObjectCacheGetBufferFunc( ExecutionEngine._raw_object_cache_getbuffer) ffi.lib.LLVMPY_CreateObjectCache.argtypes = [_ObjectCacheNotifyFunc, _ObjectCacheGetBufferFunc, py_object] ffi.lib.LLVMPY_CreateObjectCache.restype = ffi.LLVMObjectCacheRef ffi.lib.LLVMPY_DisposeObjectCache.argtypes = [ffi.LLVMObjectCacheRef] ffi.lib.LLVMPY_SetObjectCache.argtypes = [ffi.LLVMExecutionEngineRef, ffi.LLVMObjectCacheRef] ffi.lib.LLVMPY_CreateByteString.restype = c_void_p ffi.lib.LLVMPY_CreateByteString.argtypes = [c_void_p, c_size_t]
_ObjectCacheData
python
getsentry__sentry
src/sentry/explore/endpoints/serializers.py
{ "start": 393, "end": 568 }
class ____(serializers.Serializer): chartType = serializers.IntegerField(required=False) yAxes = serializers.ListField(child=serializers.CharField())
VisualizeSerializer
python
matplotlib__matplotlib
lib/matplotlib/backends/_backend_tk.py
{ "start": 7029, "end": 19601 }
class ____(FigureCanvasBase): required_interactive_framework = "tk" manager_class = _api.classproperty(lambda cls: FigureManagerTk) def __init__(self, figure=None, master=None): super().__init__(figure) self._idle_draw_id = None self._event_loop_id = None w, h = self.get_width_height(physical=True) self._tkcanvas = tk.Canvas( master=master, background="white", width=w, height=h, borderwidth=0, highlightthickness=0) self._tkphoto = tk.PhotoImage( master=self._tkcanvas, width=w, height=h) self._tkcanvas_image_region = self._tkcanvas.create_image( w//2, h//2, image=self._tkphoto) self._tkcanvas.bind("<Configure>", self.resize) self._tkcanvas.bind("<Map>", self._update_device_pixel_ratio) self._tkcanvas.bind("<Key>", self.key_press) self._tkcanvas.bind("<Motion>", self.motion_notify_event) self._tkcanvas.bind("<Enter>", self.enter_notify_event) self._tkcanvas.bind("<Leave>", self.leave_notify_event) self._tkcanvas.bind("<KeyRelease>", self.key_release) for name in ["<Button-1>", "<Button-2>", "<Button-3>"]: self._tkcanvas.bind(name, self.button_press_event) for name in [ "<Double-Button-1>", "<Double-Button-2>", "<Double-Button-3>"]: self._tkcanvas.bind(name, self.button_dblclick_event) for name in [ "<ButtonRelease-1>", "<ButtonRelease-2>", "<ButtonRelease-3>"]: self._tkcanvas.bind(name, self.button_release_event) # Mouse wheel on Linux generates button 4/5 events for name in "<Button-4>", "<Button-5>": self._tkcanvas.bind(name, self.scroll_event) # Mouse wheel for windows goes to the window with the focus. # Since the canvas won't usually have the focus, bind the # event to the window containing the canvas instead. # See https://wiki.tcl-lang.org/3893 (mousewheel) for details root = self._tkcanvas.winfo_toplevel() # Prevent long-lived references via tkinter callback structure GH-24820 weakself = weakref.ref(self) weakroot = weakref.ref(root) def scroll_event_windows(event): self = weakself() if self is None: root = weakroot() if root is not None: root.unbind("<MouseWheel>", scroll_event_windows_id) return return self.scroll_event_windows(event) scroll_event_windows_id = root.bind("<MouseWheel>", scroll_event_windows, "+") # Can't get destroy events by binding to _tkcanvas. Therefore, bind # to the window and filter. def filter_destroy(event): self = weakself() if self is None: root = weakroot() if root is not None: root.unbind("<Destroy>", filter_destroy_id) return if event.widget is self._tkcanvas: CloseEvent("close_event", self)._process() filter_destroy_id = root.bind("<Destroy>", filter_destroy, "+") self._tkcanvas.focus_set() self._rubberband_rect_black = None self._rubberband_rect_white = None def _update_device_pixel_ratio(self, event=None): ratio = None if sys.platform == 'win32': # Tk gives scaling with respect to 72 DPI, but Windows screens are # scaled vs 96 dpi, and pixel ratio settings are given in whole # percentages, so round to 2 digits. ratio = round(self._tkcanvas.tk.call('tk', 'scaling') / (96 / 72), 2) elif sys.platform == "linux": ratio = self._tkcanvas.winfo_fpixels('1i') / 96 if ratio is not None and self._set_device_pixel_ratio(ratio): # The easiest way to resize the canvas is to resize the canvas # widget itself, since we implement all the logic for resizing the # canvas backing store on that event. w, h = self.get_width_height(physical=True) self._tkcanvas.configure(width=w, height=h) def resize(self, event): width, height = event.width, event.height # compute desired figure size in inches dpival = self.figure.dpi winch = width / dpival hinch = height / dpival self.figure.set_size_inches(winch, hinch, forward=False) self._tkcanvas.delete(self._tkcanvas_image_region) self._tkphoto.configure(width=int(width), height=int(height)) self._tkcanvas_image_region = self._tkcanvas.create_image( int(width / 2), int(height / 2), image=self._tkphoto) ResizeEvent("resize_event", self)._process() self.draw_idle() def draw_idle(self): # docstring inherited if self._idle_draw_id: return def idle_draw(*args): try: self.draw() finally: self._idle_draw_id = None self._idle_draw_id = self._tkcanvas.after_idle(idle_draw) def get_tk_widget(self): """ Return the Tk widget used to implement FigureCanvasTkAgg. Although the initial implementation uses a Tk canvas, this routine is intended to hide that fact. """ return self._tkcanvas def _event_mpl_coords(self, event): # calling canvasx/canvasy allows taking scrollbars into account (i.e. # the top of the widget may have been scrolled out of view). return (self._tkcanvas.canvasx(event.x), # flipy so y=0 is bottom of canvas self.figure.bbox.height - self._tkcanvas.canvasy(event.y)) def motion_notify_event(self, event): MouseEvent("motion_notify_event", self, *self._event_mpl_coords(event), buttons=self._mpl_buttons(event), modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def enter_notify_event(self, event): LocationEvent("figure_enter_event", self, *self._event_mpl_coords(event), modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def leave_notify_event(self, event): LocationEvent("figure_leave_event", self, *self._event_mpl_coords(event), modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def button_press_event(self, event, dblclick=False): # set focus to the canvas so that it can receive keyboard events self._tkcanvas.focus_set() num = getattr(event, 'num', None) if sys.platform == 'darwin': # 2 and 3 are reversed. num = {2: 3, 3: 2}.get(num, num) MouseEvent("button_press_event", self, *self._event_mpl_coords(event), num, dblclick=dblclick, modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def button_dblclick_event(self, event): self.button_press_event(event, dblclick=True) def button_release_event(self, event): num = getattr(event, 'num', None) if sys.platform == 'darwin': # 2 and 3 are reversed. num = {2: 3, 3: 2}.get(num, num) MouseEvent("button_release_event", self, *self._event_mpl_coords(event), num, modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def scroll_event(self, event): num = getattr(event, 'num', None) step = 1 if num == 4 else -1 if num == 5 else 0 MouseEvent("scroll_event", self, *self._event_mpl_coords(event), step=step, modifiers=self._mpl_modifiers(event), guiEvent=event)._process() def scroll_event_windows(self, event): """MouseWheel event processor""" # need to find the window that contains the mouse w = event.widget.winfo_containing(event.x_root, event.y_root) if w != self._tkcanvas: return x = self._tkcanvas.canvasx(event.x_root - w.winfo_rootx()) y = (self.figure.bbox.height - self._tkcanvas.canvasy(event.y_root - w.winfo_rooty())) step = event.delta / 120 MouseEvent("scroll_event", self, x, y, step=step, modifiers=self._mpl_modifiers(event), guiEvent=event)._process() @staticmethod def _mpl_buttons(event): # See _mpl_modifiers. # NOTE: This fails to report multiclicks on macOS; only one button is # reported (multiclicks work correctly on Linux & Windows). modifiers = [ # macOS appears to swap right and middle (look for "Swap buttons # 2/3" in tk/macosx/tkMacOSXMouseEvent.c). (MouseButton.LEFT, 1 << 8), (MouseButton.RIGHT, 1 << 9), (MouseButton.MIDDLE, 1 << 10), (MouseButton.BACK, 1 << 11), (MouseButton.FORWARD, 1 << 12), ] if sys.platform == "darwin" else [ (MouseButton.LEFT, 1 << 8), (MouseButton.MIDDLE, 1 << 9), (MouseButton.RIGHT, 1 << 10), (MouseButton.BACK, 1 << 11), (MouseButton.FORWARD, 1 << 12), ] # State *before* press/release. return [name for name, mask in modifiers if event.state & mask] @staticmethod def _mpl_modifiers(event, *, exclude=None): # Add modifier keys to the key string. Bit values are inferred from # the implementation of tkinter.Event.__repr__ (1, 2, 4, 8, ... = # Shift, Lock, Control, Mod1, ..., Mod5, Button1, ..., Button5) # In general, the modifier key is excluded from the modifier flag, # however this is not the case on "darwin", so double check that # we aren't adding repeat modifier flags to a modifier key. modifiers = [ ("ctrl", 1 << 2, "control"), ("alt", 1 << 17, "alt"), ("shift", 1 << 0, "shift"), ] if sys.platform == "win32" else [ ("ctrl", 1 << 2, "control"), ("alt", 1 << 4, "alt"), ("shift", 1 << 0, "shift"), ("cmd", 1 << 3, "cmd"), ] if sys.platform == "darwin" else [ ("ctrl", 1 << 2, "control"), ("alt", 1 << 3, "alt"), ("shift", 1 << 0, "shift"), ("super", 1 << 6, "super"), ] return [name for name, mask, key in modifiers if event.state & mask and exclude != key] def _get_key(self, event): unikey = event.char key = cbook._unikey_or_keysym_to_mplkey(unikey, event.keysym) if key is not None: mods = self._mpl_modifiers(event, exclude=key) # shift is not added to the keys as this is already accounted for. if "shift" in mods and unikey: mods.remove("shift") return "+".join([*mods, key]) def key_press(self, event): KeyEvent("key_press_event", self, self._get_key(event), *self._event_mpl_coords(event), guiEvent=event)._process() def key_release(self, event): KeyEvent("key_release_event", self, self._get_key(event), *self._event_mpl_coords(event), guiEvent=event)._process() def new_timer(self, *args, **kwargs): # docstring inherited return TimerTk(self._tkcanvas, *args, **kwargs) def flush_events(self): # docstring inherited self._tkcanvas.update() def start_event_loop(self, timeout=0): # docstring inherited if timeout > 0: milliseconds = int(1000 * timeout) if milliseconds > 0: self._event_loop_id = self._tkcanvas.after( milliseconds, self.stop_event_loop) else: self._event_loop_id = self._tkcanvas.after_idle( self.stop_event_loop) self._tkcanvas.mainloop() def stop_event_loop(self): # docstring inherited if self._event_loop_id: self._tkcanvas.after_cancel(self._event_loop_id) self._event_loop_id = None self._tkcanvas.quit() def set_cursor(self, cursor): try: self._tkcanvas.configure(cursor=cursord[cursor]) except tkinter.TclError: pass
FigureCanvasTk
python
PrefectHQ__prefect
src/integrations/prefect-aws/tests/test_secrets_manager.py
{ "start": 1764, "end": 4561 }
class ____: """Test synchronous AwsSecret methods""" async def test_read_secret(self, secret_under_test, aws_credentials): expected_value = secret_under_test.pop("expected_value") secret_name = secret_under_test.pop( "secret_name" ) # Remove secret_name from kwargs @flow async def test_flow(): secret = AwsSecret( aws_credentials=aws_credentials, secret_name=secret_name, # Use for AwsSecret initialization ) # Pass remaining kwargs (version_id, version_stage) if present return await secret.read_secret(**secret_under_test) assert (await test_flow()) == expected_value async def test_write_secret(self, aws_credentials, secretsmanager_client): secret = AwsSecret(aws_credentials=aws_credentials, secret_name="my-test") secret_value = b"test-secret-value" @flow async def test_flow(): return await secret.write_secret(secret_value) arn = await test_flow() assert arn.startswith("arn:aws:secretsmanager") # Verify the secret was written correctly response = secretsmanager_client.get_secret_value(SecretId="my-test") assert response["SecretBinary"] == secret_value async def test_delete_secret(self, aws_credentials, secretsmanager_client): # First create a secret to delete secret = AwsSecret(aws_credentials=aws_credentials, secret_name="test-delete") secret_value = b"delete-me" @flow async def setup_flow(): return await secret.write_secret(secret_value) arn = await setup_flow() # Now test deletion @flow async def test_flow(): return await secret.delete_secret( recovery_window_in_days=7, force_delete_without_recovery=False ) deleted_arn = await test_flow() assert deleted_arn == arn # Verify the secret is scheduled for deletion with pytest.raises(secretsmanager_client.exceptions.InvalidRequestException): secretsmanager_client.get_secret_value(SecretId="test-delete") async def test_delete_secret_validation(self, aws_credentials): secret = AwsSecret( aws_credentials=aws_credentials, secret_name="test-validation" ) with pytest.raises(ValueError, match="Cannot specify recovery window"): await secret.delete_secret( force_delete_without_recovery=True, recovery_window_in_days=10 ) with pytest.raises( ValueError, match="Recovery window must be between 7 and 30 days" ): await secret.delete_secret(recovery_window_in_days=42)
TestAwsSecretSync
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 67196, "end": 69227 }
class ____(_TestOperationsMutating): def test_eq_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a == b) def test_ne_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a != b) def test_lt_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a < b) def test_le_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a <= b) def test_gt_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a > b) def test_ge_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a >= b) def test_and_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a & b) def test_or_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a | b) def test_sub_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a - b) def test_xor_with_mutation(self): self.check_set_op_does_not_crash(lambda a, b: a ^ b) def test_iadd_with_mutation(self): def f(a, b): a &= b self.check_set_op_does_not_crash(f) def test_ior_with_mutation(self): def f(a, b): a |= b self.check_set_op_does_not_crash(f) def test_isub_with_mutation(self): def f(a, b): a -= b self.check_set_op_does_not_crash(f) def test_ixor_with_mutation(self): def f(a, b): a ^= b self.check_set_op_does_not_crash(f) def test_iteration_with_mutation(self): def f1(a, b): for x in a: pass for y in b: pass def f2(a, b): for y in b: pass for x in a: pass def f3(a, b): for x, y in zip(a, b): pass self.check_set_op_does_not_crash(f1) self.check_set_op_does_not_crash(f2) self.check_set_op_does_not_crash(f3)
_TestBinaryOpsMutating
python
GoogleCloudPlatform__python-docs-samples
speech/microphone/transcribe_streaming_mic.py
{ "start": 1021, "end": 7603 }
class ____: """Opens a recording stream as a generator yielding the audio chunks.""" def __init__(self: object, rate: int = RATE, chunk: int = CHUNK) -> None: """The audio -- and generator -- is guaranteed to be on the main thread.""" self._rate = rate self._chunk = chunk # Create a thread-safe buffer of audio data self._buff = queue.Queue() self.closed = True def __enter__(self: object) -> object: self._audio_interface = pyaudio.PyAudio() self._audio_stream = self._audio_interface.open( format=pyaudio.paInt16, # The API currently only supports 1-channel (mono) audio # https://goo.gl/z757pE channels=1, rate=self._rate, input=True, frames_per_buffer=self._chunk, # Run the audio stream asynchronously to fill the buffer object. # This is necessary so that the input device's buffer doesn't # overflow while the calling thread makes network requests, etc. stream_callback=self._fill_buffer, ) self.closed = False return self def __exit__( self: object, type: object, value: object, traceback: object, ) -> None: """Closes the stream, regardless of whether the connection was lost or not.""" self._audio_stream.stop_stream() self._audio_stream.close() self.closed = True # Signal the generator to terminate so that the client's # streaming_recognize method will not block the process termination. self._buff.put(None) self._audio_interface.terminate() def _fill_buffer( self: object, in_data: object, frame_count: int, time_info: object, status_flags: object, ) -> object: """Continuously collect data from the audio stream, into the buffer. Args: in_data: The audio data as a bytes object frame_count: The number of frames captured time_info: The time information status_flags: The status flags Returns: The audio data as a bytes object """ self._buff.put(in_data) return None, pyaudio.paContinue def generator(self: object) -> object: """Generates audio chunks from the stream of audio data in chunks. Args: self: The MicrophoneStream object Returns: A generator that outputs audio chunks. """ while not self.closed: # Use a blocking get() to ensure there's at least one chunk of # data, and stop iteration if the chunk is None, indicating the # end of the audio stream. chunk = self._buff.get() if chunk is None: return data = [chunk] # Now consume whatever other data's still buffered. while True: try: chunk = self._buff.get(block=False) if chunk is None: return data.append(chunk) except queue.Empty: break yield b"".join(data) def listen_print_loop(responses: object) -> str: """Iterates through server responses and prints them. The responses passed is a generator that will block until a response is provided by the server. Each response may contain multiple results, and each result may contain multiple alternatives; for details, see https://goo.gl/tjCPAU. Here we print only the transcription for the top alternative of the top result. In this case, responses are provided for interim results as well. If the response is an interim one, print a line feed at the end of it, to allow the next result to overwrite it, until the response is a final one. For the final one, print a newline to preserve the finalized transcription. Args: responses: List of server responses Returns: The transcribed text. """ num_chars_printed = 0 for response in responses: if not response.results: continue # The `results` list is consecutive. For streaming, we only care about # the first result being considered, since once it's `is_final`, it # moves on to considering the next utterance. result = response.results[0] if not result.alternatives: continue # Display the transcription of the top alternative. transcript = result.alternatives[0].transcript # Display interim results, but with a carriage return at the end of the # line, so subsequent lines will overwrite them. # # If the previous result was longer than this one, we need to print # some extra spaces to overwrite the previous result overwrite_chars = " " * (num_chars_printed - len(transcript)) if not result.is_final: sys.stdout.write(transcript + overwrite_chars + "\r") sys.stdout.flush() num_chars_printed = len(transcript) else: print(transcript + overwrite_chars) # Exit recognition if any of the transcribed phrases could be # one of our keywords. if re.search(r"\b(exit|quit)\b", transcript, re.I): print("Exiting..") break num_chars_printed = 0 return transcript def main() -> None: """Transcribe speech from audio file.""" # See http://g.co/cloud/speech/docs/languages # for a list of supported languages. language_code = "en-US" # a BCP-47 language tag client = speech.SpeechClient() config = speech.RecognitionConfig( encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=RATE, language_code=language_code, ) streaming_config = speech.StreamingRecognitionConfig( config=config, interim_results=True ) with MicrophoneStream(RATE, CHUNK) as stream: audio_generator = stream.generator() requests = ( speech.StreamingRecognizeRequest(audio_content=content) for content in audio_generator ) responses = client.streaming_recognize(streaming_config, requests) # Now, put the transcription responses to use. listen_print_loop(responses) if __name__ == "__main__": main() # [END speech_transcribe_streaming_mic]
MicrophoneStream
python
psf__black
tests/data/cases/class_blank_parentheses.py
{ "start": 604, "end": 737 }
class ____: first_test_data = 90 second_test_data = 100 def test_func(self): return None
ClassWithSpaceParentheses
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/models/secrets.py
{ "start": 796, "end": 1088 }
class ____(ABC): @abstractmethod def _fetch_secret(self, name: str) -> str: raise NotImplementedError("SecretStore subclasses must implement a _fetch_secret method") def fetch_secret(self, name: str) -> str: return SecretString(self._fetch_secret(name))
SecretStore