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
huggingface__transformers
utils/collated_reports.py
{ "start": 2556, "end": 7251 }
class ____: path: Path machine_type: str gpu_name: str commit_hash: str job: str | None report_repo_id: str | None def get_arguments(args: argparse.Namespace) -> Args: path = validate_path(args.path) machine_type = args.machine_type gpu_name = get_gpu_name(args.gpu_name) commit_hash = get_commit_hash(args.commit_hash) job = args.job report_repo_id = args.report_repo_id return Args(path, machine_type, gpu_name, commit_hash, job, report_repo_id) def upload_collated_report(job: str, report_repo_id: str, filename: str): # Alternatively we can check for the existence of the collated_reports file and upload in notification_service.py import os from get_previous_daily_ci import get_last_daily_ci_run from huggingface_hub import HfApi api = HfApi() # if it is not a scheduled run, upload the reports to a subfolder under `report_repo_folder` report_repo_subfolder = "" if os.getenv("GITHUB_EVENT_NAME") != "schedule": report_repo_subfolder = f"{os.getenv('GITHUB_RUN_NUMBER')}-{os.getenv('GITHUB_RUN_ID')}" report_repo_subfolder = f"runs/{report_repo_subfolder}" workflow_run = get_last_daily_ci_run( token=os.environ["ACCESS_REPO_INFO_TOKEN"], workflow_run_id=os.getenv("GITHUB_RUN_ID") ) workflow_run_created_time = workflow_run["created_at"] report_repo_folder = workflow_run_created_time.split("T")[0] if report_repo_subfolder: report_repo_folder = f"{report_repo_folder}/{report_repo_subfolder}" api.upload_file( path_or_fileobj=f"{filename}", path_in_repo=f"{report_repo_folder}/ci_results_{job}/{filename}", repo_id=report_repo_id, repo_type="dataset", token=os.getenv("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN"), ) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Post process models test reports.") parser.add_argument("--path", "-p", help="Path to the reports folder") parser.add_argument( "--machine-type", "-m", help="Process single or multi GPU results", choices=["single-gpu", "multi-gpu"] ) parser.add_argument("--gpu-name", "-g", help="GPU name", default=None) parser.add_argument("--commit-hash", "-c", help="Commit hash", default=None) parser.add_argument("--job", "-j", help="Optional job name required for uploading reports", default=None) parser.add_argument( "--report-repo-id", "-r", help="Optional report repository ID required for uploading reports", default=None ) args = get_arguments(parser.parse_args()) # Initialize accumulators for collated report total_status_count = { "passed": 0, "failed": 0, "skipped": 0, "error": 0, None: 0, } collated_report_buffer = [] path = args.path machine_type = args.machine_type gpu_name = args.gpu_name commit_hash = args.commit_hash job = args.job report_repo_id = args.report_repo_id # Loop through model directories and create collated reports for model_dir in sorted(path.iterdir()): if not model_dir.name.startswith(machine_type): continue # Create a new entry for the model model_name = model_dir.name.split("models_")[-1].removesuffix("_test_reports") report = {"model": model_name, "results": []} results = [] # Read short summary with open(model_dir / "summary_short.txt", "r") as f: short_summary_lines = f.readlines() # Parse short summary for line in short_summary_lines[1:]: status, count = parse_short_summary_line(line) total_status_count[status] += count if status: result = { "status": status, "test": line.split(status.upper(), maxsplit=1)[1].strip(), "count": count, } results.append(result) # Add short summaries to report report["results"] = results collated_report_buffer.append(report) filename = f"collated_reports_{machine_type}_{commit_hash}.json" # Write collated report with open(filename, "w") as f: json.dump( { "gpu_name": gpu_name, "machine_type": machine_type, "commit_hash": commit_hash, "total_status_count": total_status_count, "results": collated_report_buffer, }, f, indent=2, ) # Upload collated report if job and report_repo_id: upload_collated_report(job, report_repo_id, filename)
Args
python
dagster-io__dagster
python_modules/dagster/dagster_tests/storage_tests/test_schedule_storage.py
{ "start": 984, "end": 1939 }
class ____(TestScheduleStorage): __test__ = True @pytest.fixture(name="storage", params=[create_sqlite_schedule_storage]) def schedule_storage(self, request): with request.param() as s: yield s def test_bucket_gating(self, storage): with mock.patch( "dagster._core.storage.schedules.sqlite.sqlite_schedule_storage.get_sqlite_version", return_value="3.7.17", ): assert not storage.supports_batch_queries with mock.patch( "dagster._core.storage.schedules.sqlite.sqlite_schedule_storage.get_sqlite_version", return_value="3.25.1", ): assert storage.supports_batch_queries with mock.patch( "dagster._core.storage.schedules.sqlite.sqlite_schedule_storage.get_sqlite_version", return_value="3.25.19", ): assert storage.supports_batch_queries
TestSqliteScheduleStorage
python
getsentry__sentry
tests/sentry/integrations/github/test_client.py
{ "start": 29806, "end": 34193 }
class ____(TestCase): @mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1") def setUp(self, get_jwt): ten_days = timezone.now() + timedelta(days=10) self.integration = self.create_integration( organization=self.organization, provider="github", name="Github Test Org", external_id="1", metadata={"access_token": "12345token", "expires_at": ten_days.isoformat()}, ) self.repo = self.create_repo( project=self.project, name="Test-Organization/foo", provider="integrations:github", external_id=123, integration_id=self.integration.id, ) self.install = get_installation_of_type( GitHubIntegration, self.integration, self.organization.id ) self.github_client = self.install.get_client() @mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1") @responses.activate def test_create_check_run(self, get_jwt) -> None: repo_name = "getsentry/sentry" check_data = { "name": "sentry/ci", "head_sha": "abc123", "status": "completed", "conclusion": "success", "details_url": "https://example.com/build/123", } responses.add( method=responses.POST, url=f"https://api.github.com/repos/{repo_name}/check-runs", json={ "id": 1, "name": "sentry/ci", "head_sha": "abc123", "status": "completed", "conclusion": "success", "details_url": "https://example.com/build/123", }, status=201, ) result = self.github_client.create_check_run(repo_name, check_data) assert result["id"] == 1 assert result["name"] == "sentry/ci" assert result["head_sha"] == "abc123" assert result["status"] == "completed" assert result["conclusion"] == "success" assert result["details_url"] == "https://example.com/build/123" @mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1") @responses.activate def test_get_check_runs(self, get_jwt) -> None: repo_name = "getsentry/sentry" sha = "abc123" responses.add( method=responses.GET, url=f"https://api.github.com/repos/{repo_name}/commits/{sha}/check-runs", json={ "total_count": 2, "check_runs": [ { "id": 1, "name": "sentry/ci", "head_sha": "abc123", "status": "completed", "conclusion": "success", "details_url": "https://example.com/build/123", }, { "id": 2, "name": "sentry/tests", "head_sha": "abc123", "status": "in_progress", "conclusion": None, "details_url": "https://example.com/tests/456", }, ], }, status=200, ) result = self.github_client.get_check_runs(repo_name, sha) assert result["total_count"] == 2 assert len(result["check_runs"]) == 2 assert result["check_runs"][0]["id"] == 1 assert result["check_runs"][0]["conclusion"] == "success" assert result["check_runs"][1]["id"] == 2 assert result["check_runs"][1]["status"] == "in_progress" @mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1") @responses.activate def test_create_check_run_error(self, get_jwt) -> None: repo_name = "getsentry/sentry" check_data = {"name": "sentry/ci", "head_sha": "abc123"} responses.add( method=responses.POST, url=f"https://api.github.com/repos/{repo_name}/check-runs", json={"message": "Validation Failed"}, status=422, ) with pytest.raises(ApiError): self.github_client.create_check_run(repo_name, check_data)
GitHubCommitContextClientTest
python
sqlalchemy__sqlalchemy
test/orm/test_dataclasses.py
{ "start": 7235, "end": 8844 }
class ____(DataclassesTest): run_setup_classes = "each" run_setup_mappers = "each" @classmethod def setup_classes(cls): accounts = cls.tables.accounts widgets = cls.tables.widgets declarative = declarative_registry().mapped @declarative @dataclasses.dataclass class Widget: __table__ = widgets name: Optional[str] = None __mapper_args__ = dict( polymorphic_on=widgets.c.type, polymorphic_identity="normal", ) @declarative @dataclasses.dataclass class SpecialWidget(Widget): magic: bool = False __mapper_args__ = dict( polymorphic_identity="special", ) @declarative @dataclasses.dataclass class Account: __table__ = accounts account_id: int widgets: List[Widget] = dataclasses.field(default_factory=list) widget_count: int = dataclasses.field(init=False) __mapper_args__ = dict( properties=dict(widgets=relationship("Widget")) ) def __post_init__(self): self.widget_count = len(self.widgets) def add_widget(self, widget: Widget): self.widgets.append(widget) self.widget_count += 1 cls.classes.Account = Account cls.classes.Widget = Widget cls.classes.SpecialWidget = SpecialWidget @classmethod def setup_mappers(cls): pass
PlainDeclarativeDataclassesTest
python
tensorflow__tensorflow
tensorflow/python/framework/meta_graph_test.py
{ "start": 14254, "end": 37808 }
class ____(test.TestCase): def _testScopedExport(self, test_dir, exported_filenames): graph = ops.Graph() with graph.as_default(): # Creates an inference graph. # Hidden 1 colocate_constraint = constant_op.constant(1.2, name="constraint") images = constant_op.constant( 1.2, dtypes.float32, shape=[100, 28], name="images") with ops.name_scope("hidden1"): with graph.colocate_with(colocate_constraint.op): weights1 = variables.Variable( random_ops.truncated_normal( [28, 128], stddev=1.0 / math.sqrt(float(28))), name="weights") # The use of cond.cond here is purely for adding test # coverage the save and restore of control flow context (which doesn't # make any sense here from a machine learning perspective). The typical # biases is a simple Variable without the conditions. biases1 = variables.Variable( cond.cond( math_ops.less(random.random(), 0.5), lambda: array_ops.ones([128]), lambda: array_ops.zeros([128])), name="biases") hidden1 = nn_ops.relu(math_ops.matmul(images, weights1) + biases1) # Hidden 2 with ops.name_scope("hidden2"): weights2 = variables.Variable( random_ops.truncated_normal( [128, 32], stddev=1.0 / math.sqrt(float(128))), name="weights") # The use of while_loop.while_loop here is purely for adding test # coverage the save and restore of control flow context (which doesn't # make any sense here from a machine learning perspective). The typical # biases is a simple Variable without the conditions. def loop_cond(it, _): return it < 2 def loop_body(it, biases2): biases2 += constant_op.constant(0.1, shape=[32]) return it + 1, biases2 _, biases2 = while_loop.while_loop(loop_cond, loop_body, [ constant_op.constant(0), variables.Variable(array_ops.zeros([32]), name="biases") ]) hidden2 = nn_ops.relu(math_ops.matmul(hidden1, weights2) + biases2) # Linear with ops.name_scope("softmax_linear"): weights3 = variables.Variable( random_ops.truncated_normal( [32, 10], stddev=1.0 / math.sqrt(float(32))), name="weights") biases3 = variables.Variable(array_ops.zeros([10]), name="biases") logits = math_ops.matmul(hidden2, weights3) + biases3 ops.add_to_collection("logits", logits) # Exports each sub-graph. # Exports the first one with unbound_inputs_col_name set to default. orig_meta_graph1, var_list = meta_graph.export_scoped_meta_graph( filename=os.path.join(test_dir, exported_filenames[0]), graph=ops.get_default_graph(), export_scope="hidden1") self.assertEqual(["biases:0", "weights:0"], sorted(var_list.keys())) var_names = [v.name for _, v in var_list.items()] self.assertEqual(["hidden1/biases:0", "hidden1/weights:0"], sorted(var_names)) # Exports the rest with no unbound_inputs_col_name. orig_meta_graph2, _ = meta_graph.export_scoped_meta_graph( filename=os.path.join(test_dir, exported_filenames[1]), graph=ops.get_default_graph(), export_scope="hidden2", unbound_inputs_col_name=None) orig_meta_graph3, _ = meta_graph.export_scoped_meta_graph( filename=os.path.join(test_dir, exported_filenames[2]), graph=ops.get_default_graph(), export_scope="softmax_linear", unbound_inputs_col_name=None) return [orig_meta_graph1, orig_meta_graph2, orig_meta_graph3] def _testScopedImport(self, test_dir, exported_filenames): graph = ops.Graph() # Create all the missing inputs. with graph.as_default(): new_image = constant_op.constant( 1.2, dtypes.float32, shape=[100, 28], name="images") with self.assertRaisesRegex(ValueError, "Graph contains unbound inputs"): meta_graph.import_scoped_meta_graph( os.path.join(test_dir, exported_filenames[0]), graph=graph, import_scope="new_hidden1") with self.assertRaisesRegex(ValueError, "Graph contains unbound inputs"): meta_graph.import_scoped_meta_graph( os.path.join(test_dir, exported_filenames[0]), graph=graph, input_map={"image:0": new_image}, import_scope="new_hidden1") # Verifies we can import the original "hidden1" into "new_hidden1". var_list = meta_graph.import_scoped_meta_graph( os.path.join(test_dir, exported_filenames[0]), graph=graph, input_map={"$unbound_inputs_images": new_image}, import_scope="new_hidden1") self.assertEqual(["biases:0", "weights:0"], sorted(var_list.keys())) new_var_names = [v.name for _, v in var_list.items()] self.assertEqual(["new_hidden1/biases:0", "new_hidden1/weights:0"], sorted(new_var_names)) # Verifies we can import the original "hidden2" into "new_hidden2". hidden1 = array_ops.identity( graph.as_graph_element("new_hidden1/Relu:0"), name="hidden1/Relu") var_list = meta_graph.import_scoped_meta_graph( os.path.join(test_dir, exported_filenames[1]), graph=graph, input_map={"$unbound_inputs_hidden1/Relu": hidden1}, import_scope="new_hidden2", unbound_inputs_col_name=None) self.assertEqual(["biases:0", "weights:0"], sorted(var_list.keys())) new_var_names = [v.name for _, v in var_list.items()] self.assertEqual(["new_hidden2/biases:0", "new_hidden2/weights:0"], sorted(new_var_names)) # Verifies we can import the original "softmax_linear" into # "new_softmax_linear". hidden2 = array_ops.identity( graph.as_graph_element("new_hidden2/Relu:0"), name="hidden2/Relu") var_list = meta_graph.import_scoped_meta_graph( os.path.join(test_dir, exported_filenames[2]), graph=graph, input_map={"$unbound_inputs_hidden2/Relu": hidden2}, import_scope="new_softmax_linear", unbound_inputs_col_name=None) self.assertEqual(["biases:0", "weights:0"], sorted(var_list.keys())) new_var_names = [v.name for _, v in var_list.items()] self.assertEqual( ["new_softmax_linear/biases:0", "new_softmax_linear/weights:0"], sorted(new_var_names)) # Exports the scoped meta graphs again. new_meta_graph1, var_list = meta_graph.export_scoped_meta_graph( graph=graph, export_scope="new_hidden1") self.assertEqual(["biases:0", "weights:0"], sorted(var_list.keys())) new_meta_graph2, var_list = meta_graph.export_scoped_meta_graph( graph=graph, export_scope="new_hidden2", unbound_inputs_col_name=None) self.assertEqual(["biases:0", "weights:0"], sorted(var_list.keys())) new_meta_graph3, var_list = meta_graph.export_scoped_meta_graph( graph=graph, export_scope="new_softmax_linear", unbound_inputs_col_name=None) self.assertEqual(["biases:0", "weights:0"], sorted(var_list.keys())) return [new_meta_graph1, new_meta_graph2, new_meta_graph3] # Verifies that we can export the subgraph under each layer and import # them into new layers in a new graph. @test_util.run_deprecated_v1 def testScopedExportAndImport(self): test_dir = _TestDir("scoped_export_import") filenames = [ "exported_hidden1.pbtxt", "exported_hidden2.pbtxt", "exported_softmax_linear.pbtxt" ] orig_meta_graphs = self._testScopedExport(test_dir, filenames) new_meta_graphs = self._testScopedImport(test_dir, filenames) for a, b in zip(orig_meta_graphs, new_meta_graphs): # The unbound input strings are slightly different with the C API enabled # ("images" vs "images:0") due to the original import_graph_def code # vs. ImportGraphDef in C++. # TODO(skyewm): update the pbtxts once _USE_C_API is removed. del a.collection_def["unbound_inputs"] del b.collection_def["unbound_inputs"] test_util.assert_meta_graph_protos_equal(self, a, b) def testWhileLoopGradients(self): # Create a simple while loop. with ops.Graph().as_default(): with ops.name_scope("export"): var = variables.Variable(0.) var_name = var.name _, output = while_loop.while_loop( lambda i, x: i < 5, lambda i, x: (i + 1, x + math_ops.cast(i, dtypes.float32)), [0, var]) output_name = output.name # Generate a MetaGraphDef containing the while loop with an export scope. meta_graph_def, _ = meta_graph.export_scoped_meta_graph( export_scope="export") # Build and run the gradients of the while loop. We use this below to # verify that the gradients are correct with the imported MetaGraphDef. init_op = variables.global_variables_initializer() grad = gradients_impl.gradients([output], [var]) with session.Session() as sess: self.evaluate(init_op) expected_grad_value = self.evaluate(grad) # Restore the MetaGraphDef into a new Graph with an import scope. with ops.Graph().as_default(): meta_graph.import_scoped_meta_graph(meta_graph_def, import_scope="import") # Re-export and make sure we get the same MetaGraphDef. new_meta_graph_def, _ = meta_graph.export_scoped_meta_graph( export_scope="import") test_util.assert_meta_graph_protos_equal( self, meta_graph_def, new_meta_graph_def) # Make sure we can still build gradients and get the same result. def new_name(tensor_name): base_tensor_name = tensor_name.replace("export/", "") return "import/" + base_tensor_name var = ops.get_default_graph().get_tensor_by_name(new_name(var_name)) output = ops.get_default_graph().get_tensor_by_name(new_name(output_name)) grad = gradients_impl.gradients([output], [var]) init_op = variables.global_variables_initializer() with session.Session() as sess: self.evaluate(init_op) actual_grad_value = self.evaluate(grad) self.assertEqual(expected_grad_value, actual_grad_value) @test_util.run_v1_only("b/120545219") def testImportWhileLoopInWhileLoop(self): # Create a simple while loop. with ops.Graph().as_default(): var = variables.Variable(0.0) _, output = while_loop.while_loop(lambda i, x: i < 5, lambda i, x: (i + 1, x * 2.0), [0, var]) output_name = output.name # Generate a MetaGraphDef containing the while loop with an export scope. meta_graph_def, _ = meta_graph.export_scoped_meta_graph() # Restore the MetaGraphDef in a while loop in a new graph. with ops.Graph().as_default(): def body(i, _): meta_graph.import_scoped_meta_graph(meta_graph_def) return i + 1, ops.get_default_graph().get_tensor_by_name(output_name) _, x = while_loop.while_loop(lambda i, x: i < 2, body, [0, 0.0], name="") with session.Session() as sess: self.evaluate(variables.global_variables_initializer()) self.evaluate(x) @test_util.run_deprecated_v1 def testScopedImportUnderNameScope(self): graph = ops.Graph() with graph.as_default(): variables.Variable(initial_value=1.0, trainable=True, name="myvar") meta_graph_def, _ = meta_graph.export_scoped_meta_graph(graph=graph) graph = ops.Graph() with graph.as_default(): with ops.name_scope("foo"): imported_variables = meta_graph.import_scoped_meta_graph( meta_graph_def, import_scope="bar") self.assertEqual(len(imported_variables), 1) self.assertEqual(list(imported_variables.values())[0].name, "foo/bar/myvar:0") @test_util.run_deprecated_v1 def testScopedImportUnderNameScopeNoVarScope(self): graph = ops.Graph() with graph.as_default(): variables.Variable(initial_value=1.0, trainable=True, name="myvar") meta_graph_def, _ = meta_graph.export_scoped_meta_graph(graph=graph) graph = ops.Graph() with graph.as_default(): with ops.name_scope("foo"): imported_variables = meta_graph.import_scoped_meta_graph( meta_graph_def) self.assertEqual(len(imported_variables), 1) self.assertEqual(list(imported_variables.values())[0].name, "foo/myvar:0") def testImportsUsingSameScopeName(self): with ops.Graph().as_default(): variables.Variable(0, name="v") meta_graph_def, _ = meta_graph.export_scoped_meta_graph() with ops.Graph().as_default(): for suffix in ["", "_1"]: imported_variables = meta_graph.import_scoped_meta_graph( meta_graph_def, import_scope="s") self.assertEqual(len(imported_variables), 1) self.assertEqual(list(imported_variables.keys())[0], "v:0") self.assertEqual(list(imported_variables.values())[0].name, "s" + suffix + "/v:0") @test_util.run_deprecated_v1 def testScopedImportWithSelectedCollections(self): meta_graph_filename = os.path.join( _TestDir("selected_collections_import"), "meta_graph.pb") graph = ops.Graph() # Add a variable to populate two collections. The functionality tested is # not specific to variables, but using variables in the test is convenient. with graph.as_default(): variables.Variable(initial_value=1.0, trainable=True) self.assertTrue( all( graph.get_collection(key) for key in [ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.TRAINABLE_VARIABLES] )) meta_graph.export_scoped_meta_graph( filename=meta_graph_filename, graph=graph) def _test_import(include_collection_keys, omit_collection_keys): assert set(include_collection_keys).isdisjoint(omit_collection_keys) newgraph = ops.Graph() import_scope = "some_scope_name" def _restore_collections_predicate(collection_key): return (collection_key in include_collection_keys and collection_key not in omit_collection_keys) meta_graph.import_scoped_meta_graph( meta_graph_filename, graph=newgraph, import_scope=import_scope, restore_collections_predicate=_restore_collections_predicate) collection_values = [ newgraph.get_collection(name=key, scope=import_scope) for key in include_collection_keys ] self.assertTrue(all(collection_values)) collection_values = [ newgraph.get_collection(name=key, scope=import_scope) for key in omit_collection_keys ] self.assertFalse(any(collection_values)) _test_import( include_collection_keys=[ ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.TRAINABLE_VARIABLES ], omit_collection_keys=[]) _test_import( include_collection_keys=[ops.GraphKeys.GLOBAL_VARIABLES], omit_collection_keys=[ops.GraphKeys.TRAINABLE_VARIABLES]) _test_import( include_collection_keys=[ops.GraphKeys.TRAINABLE_VARIABLES], omit_collection_keys=[ops.GraphKeys.GLOBAL_VARIABLES]) _test_import( include_collection_keys=[], omit_collection_keys=[ ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.TRAINABLE_VARIABLES ]) def _testScopedExportWithQueue(self, test_dir, exported_filename): graph = ops.Graph() with graph.as_default(): with ops.name_scope("queue1"): input_queue = data_flow_ops.FIFOQueue(10, dtypes.float32) enqueue = input_queue.enqueue((9876), name="enqueue") close = input_queue.close(name="close") qr = queue_runner_impl.QueueRunner(input_queue, [enqueue], close) queue_runner_impl.add_queue_runner(qr) input_queue.dequeue(name="dequeue") orig_meta_graph, _ = meta_graph.export_scoped_meta_graph( filename=os.path.join(test_dir, exported_filename), graph=ops.get_default_graph(), export_scope="queue1") return orig_meta_graph def _testScopedImportWithQueue(self, test_dir, exported_filename, new_exported_filename): graph = ops.Graph() meta_graph.import_scoped_meta_graph( os.path.join(test_dir, exported_filename), graph=graph, import_scope="new_queue1") graph.as_graph_element("new_queue1/dequeue:0") graph.as_graph_element("new_queue1/close") with graph.as_default(): new_meta_graph, _ = meta_graph.export_scoped_meta_graph( filename=os.path.join(test_dir, new_exported_filename), graph=graph, export_scope="new_queue1") return new_meta_graph # Verifies that we can export the subgraph containing a FIFOQueue under # "queue1" and import it into "new_queue1" in a new graph. @test_util.run_deprecated_v1 def testScopedWithQueue(self): test_dir = _TestDir("scoped_with_queue") orig_meta_graph = self._testScopedExportWithQueue(test_dir, "exported_queue1.pbtxt") new_meta_graph = self._testScopedImportWithQueue( test_dir, "exported_queue1.pbtxt", "exported_new_queue1.pbtxt") test_util.assert_meta_graph_protos_equal(self, orig_meta_graph, new_meta_graph) # Verifies that we can export a subgraph in a nested name scope containing a # "hidden1/hidden2" and import it into "new_hidden1/new_hidden2" in a new # graph. def doTestExportNestedNames(self, use_resource=False): graph1 = ops.Graph() with graph1.as_default(): with ops.name_scope("hidden1/hidden2/hidden3"): images = constant_op.constant( 1.0, dtypes.float32, shape=[3, 2], name="images") if use_resource: weights1 = variables.Variable( [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], name="weights") biases1 = resource_variable_ops.ResourceVariable( [0.1] * 3, name="biases") else: biases1 = variables.Variable([0.1] * 3, name="biases") weights1 = variables.Variable( [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], name="weights") nn_ops.relu(math_ops.matmul(images, weights1) + biases1, name="relu") orig_meta_graph, var_list = meta_graph.export_scoped_meta_graph( export_scope="hidden1/hidden2", graph=graph1) var_names = [v.name for _, v in var_list.items()] self.assertEqual(["hidden3/biases:0", "hidden3/weights:0"], sorted(var_list.keys())) self.assertEqual([ "hidden1/hidden2/hidden3/biases:0", "hidden1/hidden2/hidden3/weights:0" ], sorted(var_names)) for node in orig_meta_graph.graph_def.node: self.assertTrue(node.name.startswith("hidden3")) graph2 = ops.Graph() new_var_list = meta_graph.import_scoped_meta_graph( orig_meta_graph, import_scope="new_hidden1/new_hidden2", graph=graph2) self.assertEqual(["hidden3/biases:0", "hidden3/weights:0"], sorted(new_var_list.keys())) new_var_names = [v.name for _, v in new_var_list.items()] self.assertEqual([ "new_hidden1/new_hidden2/hidden3/biases:0", "new_hidden1/new_hidden2/hidden3/weights:0" ], sorted(new_var_names)) nodes = [ "new_hidden1/new_hidden2/hidden3/biases/Assign", "new_hidden1/new_hidden2/hidden3/weights/Assign" ] expected = [ b"loc:@new_hidden1/new_hidden2/hidden3/biases", b"loc:@new_hidden1/new_hidden2/hidden3/weights" ] @test_util.run_deprecated_v1 def testExportNestedNames(self): self.doTestExportNestedNames(use_resource=False) @test_util.run_deprecated_v1 def testExportNestedNamesResource(self): self.doTestExportNestedNames(use_resource=True) @test_util.run_deprecated_v1 def testPotentialCycle(self): graph1 = ops.Graph() with graph1.as_default(): a = constant_op.constant(1.0, shape=[2, 2]) b = constant_op.constant(2.0, shape=[2, 2]) matmul = math_ops.matmul(a, b) with ops.name_scope("hidden1"): c = nn_ops.relu(matmul) d = constant_op.constant(3.0, shape=[2, 2]) matmul = math_ops.matmul(c, d) orig_meta_graph, _ = meta_graph.export_scoped_meta_graph( export_scope="hidden1", graph=graph1) graph2 = ops.Graph() with graph2.as_default(): with self.assertRaisesRegex(ValueError, "Graph contains unbound inputs"): meta_graph.import_scoped_meta_graph( orig_meta_graph, import_scope="new_hidden1") meta_graph.import_scoped_meta_graph( orig_meta_graph, import_scope="new_hidden1", input_map={ "$unbound_inputs_MatMul": constant_op.constant( 4.0, shape=[2, 2]) }) @test_util.run_deprecated_v1 def testClearDevices(self): graph1 = ops.Graph() with graph1.as_default(): with ops.device("/device:CPU:0"): a = variables.Variable( constant_op.constant( 1.0, shape=[2, 2]), name="a") with ops.device("/job:ps/replica:0/task:0/device:GPU:0"): b = variables.Variable( constant_op.constant( 2.0, shape=[2, 2]), name="b") with ops.device("/job:localhost/replica:0/task:0/cpu:0"): math_ops.matmul(a, b, name="matmul") self.assertEqual("/device:CPU:0", str(graph1.as_graph_element("a").device)) self.assertEqual("/job:ps/replica:0/task:0/device:GPU:0", str(graph1.as_graph_element("b").device)) self.assertEqual("/job:localhost/replica:0/task:0/device:CPU:0", str(graph1.as_graph_element("matmul").device)) # Verifies that devices are cleared on export. orig_meta_graph, _ = meta_graph.export_scoped_meta_graph( graph=graph1, clear_devices=True) graph2 = ops.Graph() with graph2.as_default(): meta_graph.import_scoped_meta_graph(orig_meta_graph, clear_devices=False) self.assertEqual("", str(graph2.as_graph_element("a").device)) self.assertEqual("", str(graph2.as_graph_element("b").device)) self.assertEqual("", str(graph2.as_graph_element("matmul").device)) # Verifies that devices are cleared on export when passing in graph_def. orig_meta_graph, _ = meta_graph.export_scoped_meta_graph( graph_def=graph1.as_graph_def(), clear_devices=True) graph2 = ops.Graph() with graph2.as_default(): meta_graph.import_scoped_meta_graph(orig_meta_graph, clear_devices=False) self.assertEqual("", str(graph2.as_graph_element("a").device)) self.assertEqual("", str(graph2.as_graph_element("b").device)) self.assertEqual("", str(graph2.as_graph_element("matmul").device)) # Verifies that devices are cleared on import. orig_meta_graph, _ = meta_graph.export_scoped_meta_graph( graph=graph1, clear_devices=False) graph2 = ops.Graph() with graph2.as_default(): meta_graph.import_scoped_meta_graph(orig_meta_graph, clear_devices=True) self.assertEqual("", str(graph2.as_graph_element("a").device)) self.assertEqual("", str(graph2.as_graph_element("b").device)) self.assertEqual("", str(graph2.as_graph_element("matmul").device))
ScopedMetaGraphTest
python
huggingface__transformers
tests/models/wav2vec2/test_feature_extraction_wav2vec2.py
{ "start": 3099, "end": 10283 }
class ____(SequenceFeatureExtractionTestMixin, unittest.TestCase): feature_extraction_class = Wav2Vec2FeatureExtractor def setUp(self): self.feat_extract_tester = Wav2Vec2FeatureExtractionTester(self) def _check_zero_mean_unit_variance(self, input_vector): self.assertTrue(np.all(np.mean(input_vector, axis=0) < 1e-3)) self.assertTrue(np.all(np.abs(np.var(input_vector, axis=0) - 1) < 1e-3)) def test_call(self): # Tests that all call wrap to encode_plus and batch_encode_plus feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) # create three inputs of length 800, 1000, and 1200 speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] # Test not batched input encoded_sequences_1 = feat_extract(speech_inputs[0], return_tensors="np").input_values encoded_sequences_2 = feat_extract(np_speech_inputs[0], return_tensors="np").input_values self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) # Test batched encoded_sequences_1 = feat_extract(speech_inputs, return_tensors="np").input_values encoded_sequences_2 = feat_extract(np_speech_inputs, return_tensors="np").input_values for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) # Test 2-D numpy arrays are batched. speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] np_speech_inputs = np.asarray(speech_inputs) encoded_sequences_1 = feat_extract(speech_inputs, return_tensors="np").input_values encoded_sequences_2 = feat_extract(np_speech_inputs, return_tensors="np").input_values for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) def test_zero_mean_unit_variance_normalization_np(self): feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] paddings = ["longest", "max_length", "do_not_pad"] max_lengths = [None, 1600, None] for max_length, padding in zip(max_lengths, paddings): processed = feat_extract(speech_inputs, padding=padding, max_length=max_length, return_tensors="np") input_values = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800]) self.assertTrue(input_values[0][800:].sum() < 1e-6) self._check_zero_mean_unit_variance(input_values[1][:1000]) self.assertTrue(input_values[0][1000:].sum() < 1e-6) self._check_zero_mean_unit_variance(input_values[2][:1200]) def test_zero_mean_unit_variance_normalization(self): feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) lengths = range(800, 1400, 200) speech_inputs = [floats_list((1, x))[0] for x in lengths] paddings = ["longest", "max_length", "do_not_pad"] max_lengths = [None, 1600, None] for max_length, padding in zip(max_lengths, paddings): processed = feat_extract(speech_inputs, max_length=max_length, padding=padding) input_values = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800]) self._check_zero_mean_unit_variance(input_values[1][:1000]) self._check_zero_mean_unit_variance(input_values[2][:1200]) def test_zero_mean_unit_variance_normalization_trunc_np_max_length(self): feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] processed = feat_extract( speech_inputs, truncation=True, max_length=1000, padding="max_length", return_tensors="np" ) input_values = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800]) self._check_zero_mean_unit_variance(input_values[1]) self._check_zero_mean_unit_variance(input_values[2]) def test_zero_mean_unit_variance_normalization_trunc_np_longest(self): feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] processed = feat_extract( speech_inputs, truncation=True, max_length=1000, padding="longest", return_tensors="np" ) input_values = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800]) self._check_zero_mean_unit_variance(input_values[1, :1000]) self._check_zero_mean_unit_variance(input_values[2]) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000)) speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] processed = feat_extract( speech_inputs, truncation=True, max_length=2000, padding="longest", return_tensors="np" ) input_values = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800]) self._check_zero_mean_unit_variance(input_values[1, :1000]) self._check_zero_mean_unit_variance(input_values[2]) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200)) @require_torch def test_double_precision_pad(self): import torch feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) np_speech_inputs = np.random.rand(100).astype(np.float64) py_speech_inputs = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: np_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="np") self.assertTrue(np_processed.input_values.dtype == np.float32) pt_processed = feature_extractor.pad([{"input_values": inputs}], return_tensors="pt") self.assertTrue(pt_processed.input_values.dtype == torch.float32) @slow @require_torch def test_pretrained_checkpoints_are_set_correctly(self): # this test makes sure that models that are using # group norm don't have their feature extractor return the # attention_mask model_id = "facebook/wav2vec2-base-960h" config = Wav2Vec2Config.from_pretrained(model_id) feat_extract = Wav2Vec2FeatureExtractor.from_pretrained(model_id) # only "layer" feature extraction norm should make use of # attention_mask self.assertEqual(feat_extract.return_attention_mask, config.feat_extract_norm == "layer")
Wav2Vec2FeatureExtractionTest
python
Lightning-AI__lightning
examples/pytorch/basics/backbone_image_classifier.py
{ "start": 3179, "end": 4566 }
class ____(LightningDataModule): def __init__(self, batch_size: int = 32): super().__init__() dataset = MNIST(DATASETS_PATH, train=True, download=True, transform=transforms.ToTensor()) self.mnist_test = MNIST(DATASETS_PATH, train=False, download=True, transform=transforms.ToTensor()) self.mnist_train, self.mnist_val = random_split( dataset, [55000, 5000], generator=torch.Generator().manual_seed(42) ) self.batch_size = batch_size def train_dataloader(self): return DataLoader(self.mnist_train, batch_size=self.batch_size) def val_dataloader(self): return DataLoader(self.mnist_val, batch_size=self.batch_size) def test_dataloader(self): return DataLoader(self.mnist_test, batch_size=self.batch_size) def predict_dataloader(self): return DataLoader(self.mnist_test, batch_size=self.batch_size) def cli_main(): cli = LightningCLI( LitClassifier, MyDataModule, seed_everything_default=1234, save_config_kwargs={"overwrite": True}, run=False ) cli.trainer.fit(cli.model, datamodule=cli.datamodule) cli.trainer.test(ckpt_path="best", datamodule=cli.datamodule) predictions = cli.trainer.predict(ckpt_path="best", datamodule=cli.datamodule) print(predictions[0]) if __name__ == "__main__": cli_lightning_logo() cli_main()
MyDataModule
python
sanic-org__sanic
sanic/signals.py
{ "start": 507, "end": 2955 }
class ____(Enum): """Event names for the SignalRouter""" SERVER_EXCEPTION_REPORT = "server.exception.report" SERVER_INIT_AFTER = "server.init.after" SERVER_INIT_BEFORE = "server.init.before" SERVER_SHUTDOWN_AFTER = "server.shutdown.after" SERVER_SHUTDOWN_BEFORE = "server.shutdown.before" HTTP_LIFECYCLE_BEGIN = "http.lifecycle.begin" HTTP_LIFECYCLE_COMPLETE = "http.lifecycle.complete" HTTP_LIFECYCLE_EXCEPTION = "http.lifecycle.exception" HTTP_LIFECYCLE_HANDLE = "http.lifecycle.handle" HTTP_LIFECYCLE_READ_BODY = "http.lifecycle.read_body" HTTP_LIFECYCLE_READ_HEAD = "http.lifecycle.read_head" HTTP_LIFECYCLE_REQUEST = "http.lifecycle.request" HTTP_LIFECYCLE_RESPONSE = "http.lifecycle.response" HTTP_ROUTING_AFTER = "http.routing.after" HTTP_ROUTING_BEFORE = "http.routing.before" HTTP_HANDLER_AFTER = "http.handler.after" HTTP_HANDLER_BEFORE = "http.handler.before" HTTP_LIFECYCLE_SEND = "http.lifecycle.send" HTTP_MIDDLEWARE_AFTER = "http.middleware.after" HTTP_MIDDLEWARE_BEFORE = "http.middleware.before" WEBSOCKET_HANDLER_AFTER = "websocket.handler.after" WEBSOCKET_HANDLER_BEFORE = "websocket.handler.before" WEBSOCKET_HANDLER_EXCEPTION = "websocket.handler.exception" RESERVED_NAMESPACES = { "server": ( Event.SERVER_EXCEPTION_REPORT.value, Event.SERVER_INIT_AFTER.value, Event.SERVER_INIT_BEFORE.value, Event.SERVER_SHUTDOWN_AFTER.value, Event.SERVER_SHUTDOWN_BEFORE.value, ), "http": ( Event.HTTP_LIFECYCLE_BEGIN.value, Event.HTTP_LIFECYCLE_COMPLETE.value, Event.HTTP_LIFECYCLE_EXCEPTION.value, Event.HTTP_LIFECYCLE_HANDLE.value, Event.HTTP_LIFECYCLE_READ_BODY.value, Event.HTTP_LIFECYCLE_READ_HEAD.value, Event.HTTP_LIFECYCLE_REQUEST.value, Event.HTTP_LIFECYCLE_RESPONSE.value, Event.HTTP_ROUTING_AFTER.value, Event.HTTP_ROUTING_BEFORE.value, Event.HTTP_HANDLER_AFTER.value, Event.HTTP_HANDLER_BEFORE.value, Event.HTTP_LIFECYCLE_SEND.value, Event.HTTP_MIDDLEWARE_AFTER.value, Event.HTTP_MIDDLEWARE_BEFORE.value, ), "websocket": { Event.WEBSOCKET_HANDLER_AFTER.value, Event.WEBSOCKET_HANDLER_BEFORE.value, Event.WEBSOCKET_HANDLER_EXCEPTION.value, }, } GENERIC_SIGNAL_FORMAT = "__generic__.__signal__.%s" def _blank(): ...
Event
python
apache__airflow
providers/google/tests/unit/google/cloud/utils/test_credentials_provider.py
{ "start": 5310, "end": 6047 }
class ____: @mock.patch.dict(os.environ, {AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT: ENV_VALUE}) @mock.patch("airflow.providers.google.cloud.utils.credentials_provider.build_gcp_conn") def test_provide_gcp_connection(self, mock_builder): mock_builder.return_value = TEMP_VARIABLE path = "path/to/file.json" scopes = ["scopes"] project_id = "project_id" with provide_gcp_connection(path, scopes, project_id): mock_builder.assert_called_once_with(key_file_path=path, scopes=scopes, project_id=project_id) assert os.environ[AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT] == TEMP_VARIABLE assert os.environ[AIRFLOW_CONN_GOOGLE_CLOUD_DEFAULT] == ENV_VALUE
TestProvideGcpConnection
python
ansible__ansible
lib/ansible/parsing/vault/__init__.py
{ "start": 9769, "end": 10249 }
class ____: """Opaque/abstract objects for a single vault secret. ie, a password or a key.""" def __init__(self, _bytes=None): # FIXME: ? that seems wrong... Unset etc? self._bytes = _bytes @property def bytes(self): """The secret as a bytestring. Sub classes that store text types will need to override to encode the text to bytes. """ return self._bytes def load(self): return self._bytes
VaultSecret
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 23400, "end": 23550 }
class ____(DagsterUserCodeExecutionError): """Errors raised in a user process during the execution of a sensor (or its job)."""
SensorExecutionError
python
huggingface__transformers
src/transformers/models/llava_onevision/modular_llava_onevision.py
{ "start": 9127, "end": 9214 }
class ____(LlavaNextVideoModelOutputWithPast): pass
LlavaOnevisionModelOutputWithPast
python
ray-project__ray
release/llm_tests/serve/probes/test_json_mode.py
{ "start": 1601, "end": 1752 }
class ____(BaseModel): """The format of the answer.""" sorted_numbers: List[int] = Field(description="List of the sorted numbers")
ArrayResponse
python
crytic__slither
slither/detectors/functions/modifier.py
{ "start": 1037, "end": 3687 }
class ____(AbstractDetector): """ Detector for modifiers that return a default value """ ARGUMENT = "incorrect-modifier" HELP = "Modifiers that can return the default value" IMPACT = DetectorClassification.LOW CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-modifier" WIKI_TITLE = "Incorrect modifier" WIKI_DESCRIPTION = "If a modifier does not execute `_` or revert, the execution of the function will return the default value, which can be misleading for the caller." # region wiki_exploit_scenario WIKI_EXPLOIT_SCENARIO = """ ```solidity modidfier myModif(){ if(..){ _; } } function get() myModif returns(uint){ } ``` If the condition in `myModif` is false, the execution of `get()` will return 0.""" # endregion wiki_exploit_scenario WIKI_RECOMMENDATION = "All the paths in a modifier must execute `_` or revert." def _detect(self) -> List[Output]: results = [] # pylint: disable=too-many-nested-blocks for c in self.contracts: for mod in c.modifiers: if mod.contract_declarer != c: continue # Walk down the tree, only looking at nodes in the outer scope node = mod.entry_point node_seen = [] while node is not None: node_seen.append(node) # If any node in the outer scope executes _; or reverts, # we will never return a default value if node.type == NodeType.PLACEHOLDER or is_revert(node): break # Move down, staying on the outer scope in branches if len(node.sons) > 0: if node.contains_if(): node = _get_false_son(node) else: if node.sons[0] in node_seen: node = node.sons[1] else: node = node.sons[0] else: node = None else: # Nothing was found in the outer scope info: DETECTOR_INFO = [ "Modifier ", mod, " does not always execute _; or revert\n", ] res = self.generate_result(info) results.append(res) return results
ModifierDefaultDetection
python
tensorflow__tensorflow
tensorflow/python/ops/collective_ops_benchmark.py
{ "start": 1054, "end": 3280 }
class ____(test.Benchmark): """Benchmarks for local CPU collective op execution.""" def benchmark_collective(self): """Measures the performance of local CPU collective execution.""" shapes = [(10,), (1000,), (1000000,)] devices = [2, 4, 8] collective_key_counter = 0 for group_size in devices: group_key = collective_key_counter instance_key = collective_key_counter collective_key_counter += 1 for shape in shapes: config = config_pb2.ConfigProto(device_count={"CPU": group_size}) with session.Session(config=config) as sess: # Use a C++ callable to minimize the Python overhead in the benchmark. callable_opts = config_pb2.CallableOptions() reduce_ops = [] for device in range(group_size): with ops.device("CPU:{}".format(device)): t = constant_op.constant(np.multiply(range(shape[0]), 1.0)) r = collective_ops.all_reduce(t, group_size, group_key, instance_key, "Add", "Div") reduce_ops.append(r) callable_opts.target.append(r.name) op_callable = sess._make_callable_from_options(callable_opts) # pylint: disable=protected-access # Run five steps to warm up the session caches and do collective param # resolution before taking the first measurement. for _ in range(5): op_callable() deltas = [] overall_start = time.time() # Run at least five repetitions and for at least five seconds. while len(deltas) < 5 or time.time() - overall_start < 5.0: start = time.time() for _ in range(100): op_callable() end = time.time() deltas.append(end - start) del op_callable median_wall_time = np.median(deltas) / 100.0 iters = len(deltas) * 100 self.report_benchmark( iters=iters, wall_time=median_wall_time, name="num_elements_{}_num_devices_{}".format(np.prod(shape), group_size)) if __name__ == "__main__": test.main()
CollectiveOpBenchmark
python
langchain-ai__langchain
libs/core/langchain_core/output_parsers/list.py
{ "start": 6374, "end": 7253 }
class ____(ListOutputParser): """Parse a Markdown list.""" pattern: str = r"^\s*[-*]\s([^\n]+)$" """The pattern to match a Markdown list item.""" @override def get_format_instructions(self) -> str: """Return the format instructions for the Markdown list output.""" return "Your response should be a markdown list, eg: `- foo\n- bar\n- baz`" def parse(self, text: str) -> list[str]: """Parse the output of an LLM call. Args: text: The output of an LLM call. Returns: A list of strings. """ return re.findall(self.pattern, text, re.MULTILINE) @override def parse_iter(self, text: str) -> Iterator[re.Match]: return re.finditer(self.pattern, text, re.MULTILINE) @property def _type(self) -> str: return "markdown-list"
MarkdownListOutputParser
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/autoVariance3.py
{ "start": 2776, "end": 3243 }
class ____(Generic[T]): def __init__(self, value: T) -> None: self._value = value def get_value(self) -> T: return self._value def set_value(self, value: T): self._value = value # This should generate an error based on variance. vinv2_1: ShouldBeInvariant2[float] = ShouldBeInvariant2[int](1) # This should generate an error based on variance. vinv2_2: ShouldBeInvariant2[int] = ShouldBeInvariant2[float](1.1)
ShouldBeInvariant2
python
huggingface__transformers
src/transformers/models/qwen2_audio/configuration_qwen2_audio.py
{ "start": 5352, "end": 8673 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Qwen2AudioForConditionalGeneration`]. It is used to instantiate an Qwen2-Audio 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 Qwen2-Audio. e.g. [Qwen/Qwen2-Audio-7B](https://huggingface.co/Qwen/Qwen2-Audio-7B) Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: audio_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`): The config object or dictionary of the audio backbone. text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`): The config object or dictionary of the text backbone. audio_token_index (`int`, *optional*, defaults to 151646): The image token index to encode the image prompt. Example: ```python >>> from transformers import Qwen2AudioForConditionalGeneration, Qwen2AudioConfig, Qwen2AudioEncoderConfig, Qwen2Config >>> # Initializing a Qwen2AudioEncoder config >>> audio_config = Qwen2AudioEncoderConfig() >>> # Initializing a Qwen2 config >>> text_config = Qwen2Config() >>> # Initializing a Qwen2Audio configuration >>> configuration = Qwen2AudioConfig(audio_config, text_config) >>> # Initializing a model from the qwen2-audio style configuration >>> model = Qwen2AudioForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "qwen2_audio" attribute_map = { "audio_token_id": "audio_token_index", } sub_configs = {"text_config": AutoConfig, "audio_config": AutoConfig} def __init__( self, audio_config=None, text_config=None, audio_token_index=151646, **kwargs, ): self.audio_token_index = audio_token_index if isinstance(audio_config, dict): audio_config["model_type"] = audio_config.get("model_type", "qwen2_audio_encoder") audio_config = CONFIG_MAPPING[audio_config["model_type"]](**audio_config) elif audio_config is None: audio_config = CONFIG_MAPPING["qwen2_audio_encoder"]( d_model=1280, encoder_attention_heads=20, encoder_ffn_dim=5120, encoder_layerdrop=0.0, encoder_layers=32, num_mel_bins=128, max_source_positions=1500, scale_embedding=False, activation_function="gelu", ) self.audio_config = audio_config if isinstance(text_config, dict): text_config["model_type"] = text_config.get("model_type", "qwen2") text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config) elif text_config is None: text_config = CONFIG_MAPPING["qwen2"]() self.text_config = text_config super().__init__(**kwargs) __all__ = ["Qwen2AudioConfig", "Qwen2AudioEncoderConfig"]
Qwen2AudioConfig
python
astropy__astropy
astropy/table/tests/test_operations.py
{ "start": 35268, "end": 37674 }
class ____: def _setup(self, t_cls=Table): lines1 = [" a b ", " 0 foo ", " 1 foo ", " 1 bar ", " 2 bar "] lines2 = [" a b ", " 0 foo ", " 3 foo ", " 4 bar ", " 2 bar "] lines3 = [ " a b d ", " 0 foo R1", " 8 foo R2", " 1 bar R3", " 4 bar R4", ] self.t1 = t_cls.read(lines1, format="ascii") self.t2 = t_cls.read(lines2, format="ascii") self.t3 = t_cls.read(lines3, format="ascii") def test_default_same_columns(self, operation_table_type): self._setup(operation_table_type) out = table.setdiff(self.t1, self.t2) assert type(out["a"]) is type(self.t1["a"]) assert type(out["b"]) is type(self.t1["b"]) assert out.pformat() == [" a b ", "--- ---", " 1 bar", " 1 foo"] def test_default_same_tables(self, operation_table_type): self._setup(operation_table_type) out = table.setdiff(self.t1, self.t1) assert type(out["a"]) is type(self.t1["a"]) assert type(out["b"]) is type(self.t1["b"]) assert out.pformat() == [ " a b ", "--- ---", ] def test_extra_col_left_table(self, operation_table_type): self._setup(operation_table_type) with pytest.raises(ValueError): table.setdiff(self.t3, self.t1) def test_extra_col_right_table(self, operation_table_type): self._setup(operation_table_type) out = table.setdiff(self.t1, self.t3) assert type(out["a"]) is type(self.t1["a"]) assert type(out["b"]) is type(self.t1["b"]) assert out.pformat() == [ " a b ", "--- ---", " 1 foo", " 2 bar", ] def test_keys(self, operation_table_type): self._setup(operation_table_type) out = table.setdiff(self.t3, self.t1, keys=["a", "b"]) assert type(out["a"]) is type(self.t1["a"]) assert type(out["b"]) is type(self.t1["b"]) assert out.pformat() == [ " a b d ", "--- --- ---", " 4 bar R4", " 8 foo R2", ] def test_missing_key(self, operation_table_type): self._setup(operation_table_type) with pytest.raises(ValueError): table.setdiff(self.t3, self.t1, keys=["a", "d"])
TestSetdiff
python
sympy__sympy
sympy/core/function.py
{ "start": 73564, "end": 117239 }
class ____(Expr): """ Represents unevaluated substitutions of an expression. ``Subs(expr, x, x0)`` represents the expression resulting from substituting x with x0 in expr. Parameters ========== expr : Expr An expression. x : tuple, variable A variable or list of distinct variables. x0 : tuple or list of tuples A point or list of evaluation points corresponding to those variables. Examples ======== >>> from sympy import Subs, Function, sin, cos >>> from sympy.abc import x, y, z >>> f = Function('f') Subs are created when a particular substitution cannot be made. The x in the derivative cannot be replaced with 0 because 0 is not a valid variables of differentiation: >>> f(x).diff(x).subs(x, 0) Subs(Derivative(f(x), x), x, 0) Once f is known, the derivative and evaluation at 0 can be done: >>> _.subs(f, sin).doit() == sin(x).diff(x).subs(x, 0) == cos(0) True Subs can also be created directly with one or more variables: >>> Subs(f(x)*sin(y) + z, (x, y), (0, 1)) Subs(z + f(x)*sin(y), (x, y), (0, 1)) >>> _.doit() z + f(0)*sin(1) Notes ===== ``Subs`` objects are generally useful to represent unevaluated derivatives calculated at a point. The variables may be expressions, but they are subjected to the limitations of subs(), so it is usually a good practice to use only symbols for variables, since in that case there can be no ambiguity. There's no automatic expansion - use the method .doit() to effect all possible substitutions of the object and also of objects inside the expression. When evaluating derivatives at a point that is not a symbol, a Subs object is returned. One is also able to calculate derivatives of Subs objects - in this case the expression is always expanded (for the unevaluated form, use Derivative()). In order to allow expressions to combine before doit is done, a representation of the Subs expression is used internally to make expressions that are superficially different compare the same: >>> a, b = Subs(x, x, 0), Subs(y, y, 0) >>> a + b 2*Subs(x, x, 0) This can lead to unexpected consequences when using methods like `has` that are cached: >>> s = Subs(x, x, 0) >>> s.has(x), s.has(y) (True, False) >>> ss = s.subs(x, y) >>> ss.has(x), ss.has(y) (True, False) >>> s, ss (Subs(x, x, 0), Subs(y, y, 0)) """ def __new__(cls, expr, variables, point, **assumptions): if not is_sequence(variables, Tuple): variables = [variables] variables = Tuple(*variables) if has_dups(variables): repeated = [str(v) for v, i in Counter(variables).items() if i > 1] __ = ', '.join(repeated) raise ValueError(filldedent(''' The following expressions appear more than once: %s ''' % __)) point = Tuple(*(point if is_sequence(point, Tuple) else [point])) if len(point) != len(variables): raise ValueError('Number of point values must be the same as ' 'the number of variables.') if not point: return sympify(expr) # denest if isinstance(expr, Subs): variables = expr.variables + variables point = expr.point + point expr = expr.expr else: expr = sympify(expr) # use symbols with names equal to the point value (with prepended _) # to give a variable-independent expression pre = "_" pts = sorted(set(point), key=default_sort_key) from sympy.printing.str import StrPrinter class CustomStrPrinter(StrPrinter): def _print_Dummy(self, expr): return str(expr) + str(expr.dummy_index) def mystr(expr, **settings): p = CustomStrPrinter(settings) return p.doprint(expr) while 1: s_pts = {p: Symbol(pre + mystr(p)) for p in pts} reps = [(v, s_pts[p]) for v, p in zip(variables, point)] # if any underscore-prepended symbol is already a free symbol # and is a variable with a different point value, then there # is a clash, e.g. _0 clashes in Subs(_0 + _1, (_0, _1), (1, 0)) # because the new symbol that would be created is _1 but _1 # is already mapped to 0 so __0 and __1 are used for the new # symbols if any(r in expr.free_symbols and r in variables and Symbol(pre + mystr(point[variables.index(r)])) != r for _, r in reps): pre += "_" continue break obj = Expr.__new__(cls, expr, Tuple(*variables), point) obj._expr = expr.xreplace(dict(reps)) return obj def _eval_is_commutative(self): return self.expr.is_commutative def doit(self, **hints): e, v, p = self.args # remove self mappings for i, (vi, pi) in enumerate(zip(v, p)): if vi == pi: v = v[:i] + v[i + 1:] p = p[:i] + p[i + 1:] if not v: return self.expr if isinstance(e, Derivative): # apply functions first, e.g. f -> cos undone = [] for i, vi in enumerate(v): if isinstance(vi, FunctionClass): e = e.subs(vi, p[i]) else: undone.append((vi, p[i])) if not isinstance(e, Derivative): e = e.doit() if isinstance(e, Derivative): # do Subs that aren't related to differentiation undone2 = [] D = Dummy() arg = e.args[0] for vi, pi in undone: if D not in e.xreplace({vi: D}).free_symbols: if arg.has(vi): e = e.subs(vi, pi) else: undone2.append((vi, pi)) undone = undone2 # differentiate wrt variables that are present wrt = [] D = Dummy() expr = e.expr free = expr.free_symbols for vi, ci in e.variable_count: if isinstance(vi, Symbol) and vi in free: expr = expr.diff((vi, ci)) elif D in expr.subs(vi, D).free_symbols: expr = expr.diff((vi, ci)) else: wrt.append((vi, ci)) # inject remaining subs rv = expr.subs(undone) # do remaining differentiation *in order given* for vc in wrt: rv = rv.diff(vc) else: # inject remaining subs rv = e.subs(undone) else: rv = e.doit(**hints).subs(list(zip(v, p))) if hints.get('deep', True) and rv != self: rv = rv.doit(**hints) return rv def evalf(self, prec=None, **options): return self.doit().evalf(prec, **options) n = evalf # type:ignore @property def variables(self): """The variables to be evaluated""" return self._args[1] bound_symbols = variables @property def expr(self): """The expression on which the substitution operates""" return self._args[0] @property def point(self): """The values for which the variables are to be substituted""" return self._args[2] @property def free_symbols(self): return (self.expr.free_symbols - set(self.variables) | set(self.point.free_symbols)) @property def expr_free_symbols(self): sympy_deprecation_warning(""" The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") # Don't show the warning twice from the recursive call with ignore_warnings(SymPyDeprecationWarning): return (self.expr.expr_free_symbols - set(self.variables) | set(self.point.expr_free_symbols)) def __eq__(self, other): if not isinstance(other, Subs): return False return self._hashable_content() == other._hashable_content() def __ne__(self, other): return not(self == other) def __hash__(self): return super().__hash__() def _hashable_content(self): return (self._expr.xreplace(self.canonical_variables), ) + tuple(ordered([(v, p) for v, p in zip(self.variables, self.point) if not self.expr.has(v)])) def _eval_subs(self, old, new): # Subs doit will do the variables in order; the semantics # of subs for Subs is have the following invariant for # Subs object foo: # foo.doit().subs(reps) == foo.subs(reps).doit() pt = list(self.point) if old in self.variables: if _atomic(new) == {new} and not any( i.has(new) for i in self.args): # the substitution is neutral return self.xreplace({old: new}) # any occurrence of old before this point will get # handled by replacements from here on i = self.variables.index(old) for j in range(i, len(self.variables)): pt[j] = pt[j]._subs(old, new) return self.func(self.expr, self.variables, pt) v = [i._subs(old, new) for i in self.variables] if v != list(self.variables): return self.func(self.expr, self.variables + (old,), pt + [new]) expr = self.expr._subs(old, new) pt = [i._subs(old, new) for i in self.point] return self.func(expr, v, pt) def _eval_derivative(self, s): # Apply the chain rule of the derivative on the substitution variables: f = self.expr vp = V, P = self.variables, self.point val = Add.fromiter(p.diff(s)*Subs(f.diff(v), *vp).doit() for v, p in zip(V, P)) # these are all the free symbols in the expr efree = f.free_symbols # some symbols like IndexedBase include themselves and args # as free symbols compound = {i for i in efree if len(i.free_symbols) > 1} # hide them and see what independent free symbols remain dums = {Dummy() for i in compound} masked = f.xreplace(dict(zip(compound, dums))) ifree = masked.free_symbols - dums # include the compound symbols free = ifree | compound # remove the variables already handled free -= set(V) # add back any free symbols of remaining compound symbols free |= {i for j in free & compound for i in j.free_symbols} # if symbols of s are in free then there is more to do if free & s.free_symbols: val += Subs(f.diff(s), self.variables, self.point).doit() return val def _eval_nseries(self, x, n, logx, cdir=0): if x in self.point: # x is the variable being substituted into apos = self.point.index(x) other = self.variables[apos] else: other = x arg = self.expr.nseries(other, n=n, logx=logx) o = arg.getO() terms = Add.make_args(arg.removeO()) rv = Add(*[self.func(a, *self.args[1:]) for a in terms]) if o: rv += o.subs(other, x) return rv def _eval_as_leading_term(self, x, logx, cdir): if x in self.point: ipos = self.point.index(x) xvar = self.variables[ipos] return self.expr.as_leading_term(xvar) if x in self.variables: # if `x` is a dummy variable, it means it won't exist after the # substitution has been performed: return self # The variable is independent of the substitution: return self.expr.as_leading_term(x) def diff(f, *symbols, **kwargs): """ Differentiate f with respect to symbols. Explanation =========== This is just a wrapper to unify .diff() and the Derivative class; its interface is similar to that of integrate(). You can use the same shortcuts for multiple variables as with Derivative. For example, diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative of f(x). You can pass evaluate=False to get an unevaluated Derivative class. Note that if there are 0 symbols (such as diff(f(x), x, 0), then the result will be the function (the zeroth derivative), even if evaluate=False. Examples ======== >>> from sympy import sin, cos, Function, diff >>> from sympy.abc import x, y >>> f = Function('f') >>> diff(sin(x), x) cos(x) >>> diff(f(x), x, x, x) Derivative(f(x), (x, 3)) >>> diff(f(x), x, 3) Derivative(f(x), (x, 3)) >>> diff(sin(x)*cos(y), x, 2, y, 2) sin(x)*cos(y) >>> type(diff(sin(x), x)) cos >>> type(diff(sin(x), x, evaluate=False)) <class 'sympy.core.function.Derivative'> >>> type(diff(sin(x), x, 0)) sin >>> type(diff(sin(x), x, 0, evaluate=False)) sin >>> diff(sin(x)) cos(x) >>> diff(sin(x*y)) Traceback (most recent call last): ... ValueError: specify differentiation variables to differentiate sin(x*y) Note that ``diff(sin(x))`` syntax is meant only for convenience in interactive sessions and should be avoided in library code. References ========== .. [1] https://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AlgebraicComputation/Calculus/D.html See Also ======== Derivative idiff: computes the derivative implicitly """ if hasattr(f, 'diff'): return f.diff(*symbols, **kwargs) kwargs.setdefault('evaluate', True) return _derivative_dispatch(f, *symbols, **kwargs) def expand(e, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints): r""" Expand an expression using methods given as hints. Explanation =========== Hints evaluated unless explicitly set to False are: ``basic``, ``log``, ``multinomial``, ``mul``, ``power_base``, and ``power_exp`` The following hints are supported but not applied unless set to True: ``complex``, ``func``, and ``trig``. In addition, the following meta-hints are supported by some or all of the other hints: ``frac``, ``numer``, ``denom``, ``modulus``, and ``force``. ``deep`` is supported by all hints. Additionally, subclasses of Expr may define their own hints or meta-hints. The ``basic`` hint is used for any special rewriting of an object that should be done automatically (along with the other hints like ``mul``) when expand is called. This is a catch-all hint to handle any sort of expansion that may not be described by the existing hint names. To use this hint an object should override the ``_eval_expand_basic`` method. Objects may also define their own expand methods, which are not run by default. See the API section below. If ``deep`` is set to ``True`` (the default), things like arguments of functions are recursively expanded. Use ``deep=False`` to only expand on the top level. If the ``force`` hint is used, assumptions about variables will be ignored in making the expansion. Hints ===== These hints are run by default mul --- Distributes multiplication over addition: >>> from sympy import cos, exp, sin >>> from sympy.abc import x, y, z >>> (y*(x + z)).expand(mul=True) x*y + y*z multinomial ----------- Expand (x + y + ...)**n where n is a positive integer. >>> ((x + y + z)**2).expand(multinomial=True) x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2 power_exp --------- Expand addition in exponents into multiplied bases. >>> exp(x + y).expand(power_exp=True) exp(x)*exp(y) >>> (2**(x + y)).expand(power_exp=True) 2**x*2**y power_base ---------- Split powers of multiplied bases. This only happens by default if assumptions allow, or if the ``force`` meta-hint is used: >>> ((x*y)**z).expand(power_base=True) (x*y)**z >>> ((x*y)**z).expand(power_base=True, force=True) x**z*y**z >>> ((2*y)**z).expand(power_base=True) 2**z*y**z Note that in some cases where this expansion always holds, SymPy performs it automatically: >>> (x*y)**2 x**2*y**2 log --- Pull out power of an argument as a coefficient and split logs products into sums of logs. Note that these only work if the arguments of the log function have the proper assumptions--the arguments must be positive and the exponents must be real--or else the ``force`` hint must be True: >>> from sympy import log, symbols >>> log(x**2*y).expand(log=True) log(x**2*y) >>> log(x**2*y).expand(log=True, force=True) 2*log(x) + log(y) >>> x, y = symbols('x,y', positive=True) >>> log(x**2*y).expand(log=True) 2*log(x) + log(y) basic ----- This hint is intended primarily as a way for custom subclasses to enable expansion by default. These hints are not run by default: complex ------- Split an expression into real and imaginary parts. >>> x, y = symbols('x,y') >>> (x + y).expand(complex=True) re(x) + re(y) + I*im(x) + I*im(y) >>> cos(x).expand(complex=True) -I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x)) Note that this is just a wrapper around ``as_real_imag()``. Most objects that wish to redefine ``_eval_expand_complex()`` should consider redefining ``as_real_imag()`` instead. func ---- Expand other functions. >>> from sympy import gamma >>> gamma(x + 1).expand(func=True) x*gamma(x) trig ---- Do trigonometric expansions. >>> cos(x + y).expand(trig=True) -sin(x)*sin(y) + cos(x)*cos(y) >>> sin(2*x).expand(trig=True) 2*sin(x)*cos(x) Note that the forms of ``sin(n*x)`` and ``cos(n*x)`` in terms of ``sin(x)`` and ``cos(x)`` are not unique, due to the identity `\sin^2(x) + \cos^2(x) = 1`. The current implementation uses the form obtained from Chebyshev polynomials, but this may change. See `this MathWorld article <https://mathworld.wolfram.com/Multiple-AngleFormulas.html>`_ for more information. Notes ===== - You can shut off unwanted methods:: >>> (exp(x + y)*(x + y)).expand() x*exp(x)*exp(y) + y*exp(x)*exp(y) >>> (exp(x + y)*(x + y)).expand(power_exp=False) x*exp(x + y) + y*exp(x + y) >>> (exp(x + y)*(x + y)).expand(mul=False) (x + y)*exp(x)*exp(y) - Use deep=False to only expand on the top level:: >>> exp(x + exp(x + y)).expand() exp(x)*exp(exp(x)*exp(y)) >>> exp(x + exp(x + y)).expand(deep=False) exp(x)*exp(exp(x + y)) - Hints are applied in an arbitrary, but consistent order (in the current implementation, they are applied in alphabetical order, except multinomial comes before mul, but this may change). Because of this, some hints may prevent expansion by other hints if they are applied first. For example, ``mul`` may distribute multiplications and prevent ``log`` and ``power_base`` from expanding them. Also, if ``mul`` is applied before ``multinomial`, the expression might not be fully distributed. The solution is to use the various ``expand_hint`` helper functions or to use ``hint=False`` to this function to finely control which hints are applied. Here are some examples:: >>> from sympy import expand, expand_mul, expand_power_base >>> x, y, z = symbols('x,y,z', positive=True) >>> expand(log(x*(y + z))) log(x) + log(y + z) Here, we see that ``log`` was applied before ``mul``. To get the mul expanded form, either of the following will work:: >>> expand_mul(log(x*(y + z))) log(x*y + x*z) >>> expand(log(x*(y + z)), log=False) log(x*y + x*z) A similar thing can happen with the ``power_base`` hint:: >>> expand((x*(y + z))**x) (x*y + x*z)**x To get the ``power_base`` expanded form, either of the following will work:: >>> expand((x*(y + z))**x, mul=False) x**x*(y + z)**x >>> expand_power_base((x*(y + z))**x) x**x*(y + z)**x >>> expand((x + y)*y/x) y + y**2/x The parts of a rational expression can be targeted:: >>> expand((x + y)*y/x/(x + 1), frac=True) (x*y + y**2)/(x**2 + x) >>> expand((x + y)*y/x/(x + 1), numer=True) (x*y + y**2)/(x*(x + 1)) >>> expand((x + y)*y/x/(x + 1), denom=True) y*(x + y)/(x**2 + x) - The ``modulus`` meta-hint can be used to reduce the coefficients of an expression post-expansion:: >>> expand((3*x + 1)**2) 9*x**2 + 6*x + 1 >>> expand((3*x + 1)**2, modulus=5) 4*x**2 + x + 1 - Either ``expand()`` the function or ``.expand()`` the method can be used. Both are equivalent:: >>> expand((x + 1)**2) x**2 + 2*x + 1 >>> ((x + 1)**2).expand() x**2 + 2*x + 1 API === Objects can define their own expand hints by defining ``_eval_expand_hint()``. The function should take the form:: def _eval_expand_hint(self, **hints): # Only apply the method to the top-level expression ... See also the example below. Objects should define ``_eval_expand_hint()`` methods only if ``hint`` applies to that specific object. The generic ``_eval_expand_hint()`` method defined in Expr will handle the no-op case. Each hint should be responsible for expanding that hint only. Furthermore, the expansion should be applied to the top-level expression only. ``expand()`` takes care of the recursion that happens when ``deep=True``. You should only call ``_eval_expand_hint()`` methods directly if you are 100% sure that the object has the method, as otherwise you are liable to get unexpected ``AttributeError``s. Note, again, that you do not need to recursively apply the hint to args of your object: this is handled automatically by ``expand()``. ``_eval_expand_hint()`` should generally not be used at all outside of an ``_eval_expand_hint()`` method. If you want to apply a specific expansion from within another method, use the public ``expand()`` function, method, or ``expand_hint()`` functions. In order for expand to work, objects must be rebuildable by their args, i.e., ``obj.func(*obj.args) == obj`` must hold. Expand methods are passed ``**hints`` so that expand hints may use 'metahints'--hints that control how different expand methods are applied. For example, the ``force=True`` hint described above that causes ``expand(log=True)`` to ignore assumptions is such a metahint. The ``deep`` meta-hint is handled exclusively by ``expand()`` and is not passed to ``_eval_expand_hint()`` methods. Note that expansion hints should generally be methods that perform some kind of 'expansion'. For hints that simply rewrite an expression, use the .rewrite() API. Examples ======== >>> from sympy import Expr, sympify >>> class MyClass(Expr): ... def __new__(cls, *args): ... args = sympify(args) ... return Expr.__new__(cls, *args) ... ... def _eval_expand_double(self, *, force=False, **hints): ... ''' ... Doubles the args of MyClass. ... ... If there more than four args, doubling is not performed, ... unless force=True is also used (False by default). ... ''' ... if not force and len(self.args) > 4: ... return self ... return self.func(*(self.args + self.args)) ... >>> a = MyClass(1, 2, MyClass(3, 4)) >>> a MyClass(1, 2, MyClass(3, 4)) >>> a.expand(double=True) MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4)) >>> a.expand(double=True, deep=False) MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4)) >>> b = MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True) MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True, force=True) MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5) See Also ======== expand_log, expand_mul, expand_multinomial, expand_complex, expand_trig, expand_power_base, expand_power_exp, expand_func, sympy.simplify.hyperexpand.hyperexpand """ # don't modify this; modify the Expr.expand method hints['power_base'] = power_base hints['power_exp'] = power_exp hints['mul'] = mul hints['log'] = log hints['multinomial'] = multinomial hints['basic'] = basic return sympify(e).expand(deep=deep, modulus=modulus, **hints) # This is a special application of two hints def _mexpand(expr, recursive=False): # expand multinomials and then expand products; this may not always # be sufficient to give a fully expanded expression (see # test_issue_8247_8354 in test_arit) if expr is None: return was = None while was != expr: was, expr = expr, expand_mul(expand_multinomial(expr)) if not recursive: break return expr # These are simple wrappers around single hints. def expand_mul(expr, deep=True): """ Wrapper around expand that only uses the mul hint. See the expand docstring for more information. Examples ======== >>> from sympy import symbols, expand_mul, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_mul(exp(x+y)*(x+y)*log(x*y**2)) x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2) """ return sympify(expr).expand(deep=deep, mul=True, power_exp=False, power_base=False, basic=False, multinomial=False, log=False) def expand_multinomial(expr, deep=True): """ Wrapper around expand that only uses the multinomial hint. See the expand docstring for more information. Examples ======== >>> from sympy import symbols, expand_multinomial, exp >>> x, y = symbols('x y', positive=True) >>> expand_multinomial((x + exp(x + 1))**2) x**2 + 2*x*exp(x + 1) + exp(2*x + 2) """ return sympify(expr).expand(deep=deep, mul=False, power_exp=False, power_base=False, basic=False, multinomial=True, log=False) def expand_log(expr, deep=True, force=False, factor=False): """ Wrapper around expand that only uses the log hint. See the expand docstring for more information. Examples ======== >>> from sympy import symbols, expand_log, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_log(exp(x+y)*(x+y)*log(x*y**2)) (x + y)*(log(x) + 2*log(y))*exp(x + y) """ from sympy.functions.elementary.exponential import log from sympy.simplify.radsimp import fraction if factor is False: def _handleMul(x): # look for the simple case of expanded log(b**a)/log(b) -> a in args n, d = fraction(x) n = [i for i in n.atoms(log) if i.args[0].is_Integer] d = [i for i in d.atoms(log) if i.args[0].is_Integer] if len(n) == 1 and len(d) == 1: n = n[0] d = d[0] from sympy import multiplicity m = multiplicity(d.args[0], n.args[0]) if m: r = m + log(n.args[0]//d.args[0]**m)/d x = x.subs(n, d*r) x1 = expand_mul(expand_log(x, deep=deep, force=force, factor=True)) if x1.count(log) <= x.count(log): return x1 return x expr = expr.replace( lambda x: x.is_Mul and all(any(isinstance(i, log) and i.args[0].is_Rational for i in Mul.make_args(j)) for j in x.as_numer_denom()), _handleMul) return sympify(expr).expand(deep=deep, log=True, mul=False, power_exp=False, power_base=False, multinomial=False, basic=False, force=force, factor=factor) def expand_func(expr, deep=True): """ Wrapper around expand that only uses the func hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_func, gamma >>> from sympy.abc import x >>> expand_func(gamma(x + 2)) x*(x + 1)*gamma(x) """ return sympify(expr).expand(deep=deep, func=True, basic=False, log=False, mul=False, power_exp=False, power_base=False, multinomial=False) def expand_trig(expr, deep=True): """ Wrapper around expand that only uses the trig hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_trig, sin >>> from sympy.abc import x, y >>> expand_trig(sin(x+y)*(x+y)) (x + y)*(sin(x)*cos(y) + sin(y)*cos(x)) """ return sympify(expr).expand(deep=deep, trig=True, basic=False, log=False, mul=False, power_exp=False, power_base=False, multinomial=False) def expand_complex(expr, deep=True): """ Wrapper around expand that only uses the complex hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_complex, exp, sqrt, I >>> from sympy.abc import z >>> expand_complex(exp(z)) I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z)) >>> expand_complex(sqrt(I)) sqrt(2)/2 + sqrt(2)*I/2 See Also ======== sympy.core.expr.Expr.as_real_imag """ return sympify(expr).expand(deep=deep, complex=True, basic=False, log=False, mul=False, power_exp=False, power_base=False, multinomial=False) def expand_power_base(expr, deep=True, force=False): """ Wrapper around expand that only uses the power_base hint. A wrapper to expand(power_base=True) which separates a power with a base that is a Mul into a product of powers, without performing any other expansions, provided that assumptions about the power's base and exponent allow. deep=False (default is True) will only apply to the top-level expression. force=True (default is False) will cause the expansion to ignore assumptions about the base and exponent. When False, the expansion will only happen if the base is non-negative or the exponent is an integer. >>> from sympy.abc import x, y, z >>> from sympy import expand_power_base, sin, cos, exp, Symbol >>> (x*y)**2 x**2*y**2 >>> (2*x)**y (2*x)**y >>> expand_power_base(_) 2**y*x**y >>> expand_power_base((x*y)**z) (x*y)**z >>> expand_power_base((x*y)**z, force=True) x**z*y**z >>> expand_power_base(sin((x*y)**z), deep=False) sin((x*y)**z) >>> expand_power_base(sin((x*y)**z), force=True) sin(x**z*y**z) >>> expand_power_base((2*sin(x))**y + (2*cos(x))**y) 2**y*sin(x)**y + 2**y*cos(x)**y >>> expand_power_base((2*exp(y))**x) 2**x*exp(y)**x >>> expand_power_base((2*cos(x))**y) 2**y*cos(x)**y Notice that sums are left untouched. If this is not the desired behavior, apply full ``expand()`` to the expression: >>> expand_power_base(((x+y)*z)**2) z**2*(x + y)**2 >>> (((x+y)*z)**2).expand() x**2*z**2 + 2*x*y*z**2 + y**2*z**2 >>> expand_power_base((2*y)**(1+z)) 2**(z + 1)*y**(z + 1) >>> ((2*y)**(1+z)).expand() 2*2**z*y**(z + 1) The power that is unexpanded can be expanded safely when ``y != 0``, otherwise different values might be obtained for the expression: >>> prev = _ If we indicate that ``y`` is positive but then replace it with a value of 0 after expansion, the expression becomes 0: >>> p = Symbol('p', positive=True) >>> prev.subs(y, p).expand().subs(p, 0) 0 But if ``z = -1`` the expression would not be zero: >>> prev.subs(y, 0).subs(z, -1) 1 See Also ======== expand """ return sympify(expr).expand(deep=deep, log=False, mul=False, power_exp=False, power_base=True, multinomial=False, basic=False, force=force) def expand_power_exp(expr, deep=True): """ Wrapper around expand that only uses the power_exp hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_power_exp, Symbol >>> from sympy.abc import x, y >>> expand_power_exp(3**(y + 2)) 9*3**y >>> expand_power_exp(x**(y + 2)) x**(y + 2) If ``x = 0`` the value of the expression depends on the value of ``y``; if the expression were expanded the result would be 0. So expansion is only done if ``x != 0``: >>> expand_power_exp(Symbol('x', zero=False)**(y + 2)) x**2*x**y """ return sympify(expr).expand(deep=deep, complex=False, basic=False, log=False, mul=False, power_exp=True, power_base=False, multinomial=False) def count_ops(expr, visual=False): """ Return a representation (integer or expression) of the operations in expr. Parameters ========== expr : Expr If expr is an iterable, the sum of the op counts of the items will be returned. visual : bool, optional If ``False`` (default) then the sum of the coefficients of the visual expression will be returned. If ``True`` then the number of each type of operation is shown with the core class types (or their virtual equivalent) multiplied by the number of times they occur. Examples ======== >>> from sympy.abc import a, b, x, y >>> from sympy import sin, count_ops Although there is not a SUB object, minus signs are interpreted as either negations or subtractions: >>> (x - y).count_ops(visual=True) SUB >>> (-x).count_ops(visual=True) NEG Here, there are two Adds and a Pow: >>> (1 + a + b**2).count_ops(visual=True) 2*ADD + POW In the following, an Add, Mul, Pow and two functions: >>> (sin(x)*x + sin(x)**2).count_ops(visual=True) ADD + MUL + POW + 2*SIN for a total of 5: >>> (sin(x)*x + sin(x)**2).count_ops(visual=False) 5 Note that "what you type" is not always what you get. The expression 1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather than two DIVs: >>> (1/x/y).count_ops(visual=True) DIV + MUL The visual option can be used to demonstrate the difference in operations for expressions in different forms. Here, the Horner representation is compared with the expanded form of a polynomial: >>> eq=x*(1 + x*(2 + x*(3 + x))) >>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True) -MUL + 3*POW The count_ops function also handles iterables: >>> count_ops([x, sin(x), None, True, x + 2], visual=False) 2 >>> count_ops([x, sin(x), None, True, x + 2], visual=True) ADD + SIN >>> count_ops({x: sin(x), x + 2: y + 1}, visual=True) 2*ADD + SIN """ from .relational import Relational from sympy.concrete.summations import Sum from sympy.integrals.integrals import Integral from sympy.logic.boolalg import BooleanFunction from sympy.simplify.radsimp import fraction expr = sympify(expr) if isinstance(expr, Expr) and not expr.is_Relational: ops = [] args = [expr] NEG = Symbol('NEG') DIV = Symbol('DIV') SUB = Symbol('SUB') ADD = Symbol('ADD') EXP = Symbol('EXP') while args: a = args.pop() # if the following fails because the object is # not Basic type, then the object should be fixed # since it is the intention that all args of Basic # should themselves be Basic if a.is_Rational: #-1/3 = NEG + DIV if a is not S.One: if a.p < 0: ops.append(NEG) if a.q != 1: ops.append(DIV) continue elif a.is_Mul or a.is_MatMul: if _coeff_isneg(a): ops.append(NEG) if a.args[0] is S.NegativeOne: a = a.as_two_terms()[1] else: a = -a n, d = fraction(a) if n.is_Integer: ops.append(DIV) if n < 0: ops.append(NEG) args.append(d) continue # won't be -Mul but could be Add elif d is not S.One: if not d.is_Integer: args.append(d) ops.append(DIV) args.append(n) continue # could be -Mul elif a.is_Add or a.is_MatAdd: aargs = list(a.args) negs = 0 for i, ai in enumerate(aargs): if _coeff_isneg(ai): negs += 1 args.append(-ai) if i > 0: ops.append(SUB) else: args.append(ai) if i > 0: ops.append(ADD) if negs == len(aargs): # -x - y = NEG + SUB ops.append(NEG) elif _coeff_isneg(aargs[0]): # -x + y = SUB, but already recorded ADD ops.append(SUB - ADD) continue if a.is_Pow and a.exp is S.NegativeOne: ops.append(DIV) args.append(a.base) # won't be -Mul but could be Add continue if a == S.Exp1: ops.append(EXP) continue if a.is_Pow and a.base == S.Exp1: ops.append(EXP) args.append(a.exp) continue if a.is_Mul or isinstance(a, LatticeOp): o = Symbol(a.func.__name__.upper()) # count the args ops.append(o*(len(a.args) - 1)) elif a.args and ( a.is_Pow or a.is_Function or isinstance(a, (Derivative, Integral, Sum))): # if it's not in the list above we don't # consider a.func something to count, e.g. # Tuple, MatrixSymbol, etc... if isinstance(a.func, UndefinedFunction): o = Symbol("FUNC_" + a.func.__name__.upper()) else: o = Symbol(a.func.__name__.upper()) ops.append(o) if not a.is_Symbol: args.extend(a.args) elif isinstance(expr, Dict): ops = [count_ops(k, visual=visual) + count_ops(v, visual=visual) for k, v in expr.items()] elif iterable(expr): ops = [count_ops(i, visual=visual) for i in expr] elif isinstance(expr, (Relational, BooleanFunction)): ops = [] for arg in expr.args: ops.append(count_ops(arg, visual=True)) o = Symbol(func_name(expr, short=True).upper()) ops.append(o) elif not isinstance(expr, Basic): ops = [] else: # it's Basic not isinstance(expr, Expr): if not isinstance(expr, Basic): raise TypeError("Invalid type of expr") else: ops = [] args = [expr] while args: a = args.pop() if a.args: o = Symbol(type(a).__name__.upper()) if a.is_Boolean: ops.append(o*(len(a.args)-1)) else: ops.append(o) args.extend(a.args) if not ops: if visual: return S.Zero return 0 ops = Add(*ops) if visual: return ops if ops.is_Number: return int(ops) return sum(int((a.args or [1])[0]) for a in Add.make_args(ops)) def nfloat(expr, n=15, exponent=False, dkeys=False): """Make all Rationals in expr Floats except those in exponents (unless the exponents flag is set to True) and those in undefined functions. When processing dictionaries, do not modify the keys unless ``dkeys=True``. Examples ======== >>> from sympy import nfloat, cos, pi, sqrt >>> from sympy.abc import x, y >>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y)) x**4 + 0.5*x + sqrt(y) + 1.5 >>> nfloat(x**4 + sqrt(y), exponent=True) x**4.0 + y**0.5 Container types are not modified: >>> type(nfloat((1, 2))) is tuple True """ from sympy.matrices.matrixbase import MatrixBase kw = {"n": n, "exponent": exponent, "dkeys": dkeys} if isinstance(expr, MatrixBase): return expr.applyfunc(lambda e: nfloat(e, **kw)) # handling of iterable containers if iterable(expr, exclude=str): if isinstance(expr, (dict, Dict)): if dkeys: args = [tuple((nfloat(i, **kw) for i in a)) for a in expr.items()] else: args = [(k, nfloat(v, **kw)) for k, v in expr.items()] if isinstance(expr, dict): return type(expr)(args) else: return expr.func(*args) elif isinstance(expr, Basic): return expr.func(*[nfloat(a, **kw) for a in expr.args]) return type(expr)([nfloat(a, **kw) for a in expr]) rv = sympify(expr) if rv.is_Number: return Float(rv, n) elif rv.is_number: # evalf doesn't always set the precision rv = rv.n(n) if rv.is_Number: rv = Float(rv.n(n), n) else: pass # pure_complex(rv) is likely True return rv elif rv.is_Atom: return rv elif rv.is_Relational: args_nfloat = (nfloat(arg, **kw) for arg in rv.args) return rv.func(*args_nfloat) # watch out for RootOf instances that don't like to have # their exponents replaced with Dummies and also sometimes have # problems with evaluating at low precision (issue 6393) from sympy.polys.rootoftools import RootOf rv = rv.xreplace({ro: ro.n(n) for ro in rv.atoms(RootOf)}) from .power import Pow if not exponent: reps = [(p, Pow(p.base, Dummy())) for p in rv.atoms(Pow)] rv = rv.xreplace(dict(reps)) rv = rv.n(n) if not exponent: rv = rv.xreplace({d.exp: p.exp for p, d in reps}) else: # Pow._eval_evalf special cases Integer exponents so if # exponent is suppose to be handled we have to do so here rv = rv.xreplace(Transform( lambda x: Pow(x.base, Float(x.exp, n)), lambda x: x.is_Pow and x.exp.is_Integer)) return rv.xreplace(Transform( lambda x: x.func(*nfloat(x.args, n, exponent)), lambda x: isinstance(x, Function) and not isinstance(x, AppliedUndef))) from .symbol import Dummy, Symbol
Subs
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_generators.py
{ "start": 2654, "end": 4531 }
class ____(__TestCase): def test_frame_resurrect(self): # A generator frame can be resurrected by a generator's finalization. def gen(): nonlocal frame try: yield finally: frame = sys._getframe() g = gen() wr = weakref.ref(g) next(g) del g support.gc_collect() self.assertIs(wr(), None) self.assertTrue(frame) del frame support.gc_collect() def test_refcycle(self): # A generator caught in a refcycle gets finalized anyway. old_garbage = gc.garbage[:] finalized = False def gen(): nonlocal finalized try: g = yield yield 1 finally: finalized = True g = gen() next(g) g.send(g) self.assertGreater(sys.getrefcount(g), 2) self.assertFalse(finalized) del g support.gc_collect() self.assertTrue(finalized) self.assertEqual(gc.garbage, old_garbage) def test_lambda_generator(self): # bpo-23192, gh-119897: Test that a lambda returning a generator behaves # like the equivalent function f = lambda: (yield 1) self.assertIsInstance(f(), types.GeneratorType) self.assertEqual(next(f()), 1) def g(): return (yield 1) # test 'yield from' f2 = lambda: (yield from g()) def g2(): return (yield from g()) f3 = lambda: (yield from f()) def g3(): return (yield from f()) for gen_fun in (f, g, f2, g2, f3, g3): gen = gen_fun() self.assertEqual(next(gen), 1) with self.assertRaises(StopIteration) as cm: gen.send(2) self.assertEqual(cm.exception.value, 2)
FinalizationTest
python
HypothesisWorks__hypothesis
hypothesis-python/tests/typing_extensions/test_backported_types.py
{ "start": 2274, "end": 5764 }
class ____(TypedDict): a: int @given(from_type(A)) def test_simple_typeddict(value): assert type(value) == dict assert set(value) == {"a"} assert isinstance(value["a"], int) def test_typing_extensions_Type_int(): assert_simple_property(from_type(type[int]), lambda v: v is int) @given(from_type(Union[type[str], type[list]])) def test_typing_extensions_Type_Union(ex): assert ex in (str, list) def test_resolves_NewType(): typ = NewType("T", int) nested = NewType("NestedT", typ) uni = NewType("UnionT", Union[int, None]) uni_new = NewType("UnionT", int | None) assert_simple_property(from_type(typ), lambda x: isinstance(x, int)) assert_simple_property(from_type(nested), lambda x: isinstance(x, int)) assert_simple_property(from_type(uni), lambda x: isinstance(x, (int, type(None)))) assert_simple_property( from_type(uni_new), lambda x: isinstance(x, (int, type(None))) ) find_any(from_type(uni), lambda x: isinstance(x, int)) find_any(from_type(uni), lambda x: isinstance(x, type(None))) @given(from_type(DefaultDict[int, int]) | from_type(collections.defaultdict[int, int])) def test_defaultdict(ex): assert isinstance(ex, collections.defaultdict) assume(ex) assert all(isinstance(elem, int) for elem in ex) assert all(isinstance(elem, int) for elem in ex.values()) @pytest.mark.parametrize("non_runtime_type", NON_RUNTIME_TYPES) def test_non_runtime_type_cannot_be_resolved(non_runtime_type): strategy = st.from_type(non_runtime_type) with pytest.raises( InvalidArgument, match="there is no such thing as a runtime instance" ): check_can_generate_examples(strategy) @pytest.mark.parametrize("non_runtime_type", NON_RUNTIME_TYPES) def test_non_runtime_type_cannot_be_registered(non_runtime_type): with pytest.raises( InvalidArgument, match="there is no such thing as a runtime instance" ): st.register_type_strategy(non_runtime_type, st.none()) def test_callable_with_concatenate(): P = ParamSpec("P") func_type = Callable[Concatenate[int, P], None] strategy = st.from_type(func_type) with pytest.raises( InvalidArgument, match="Hypothesis can't yet construct a strategy for instances of a Callable type", ): check_can_generate_examples(strategy) with pytest.raises(InvalidArgument, match="Cannot register generic type"): st.register_type_strategy(func_type, st.none()) def test_callable_with_paramspec(): P = ParamSpec("P") func_type = Callable[P, None] strategy = st.from_type(func_type) with pytest.raises( InvalidArgument, match="Hypothesis can't yet construct a strategy for instances of a Callable type", ): check_can_generate_examples(strategy) with pytest.raises(InvalidArgument, match="Cannot register generic type"): st.register_type_strategy(func_type, st.none()) @pytest.mark.parametrize("typ", [TypeGuard, TypeIs]) def test_callable_return_typegard_type(typ): strategy = st.from_type(Callable[[], typ[int]]) with pytest.raises( InvalidArgument, match="Hypothesis cannot yet construct a strategy for callables " "which are PEP-647 TypeGuards or PEP-742 TypeIs", ): check_can_generate_examples(strategy) with pytest.raises(InvalidArgument, match="Cannot register generic type"): st.register_type_strategy(Callable[[], typ[int]], st.none())
A
python
tensorflow__tensorflow
tensorflow/python/distribute/values.py
{ "start": 60800, "end": 66248 }
class ____(VariablePolicy): """Policy defined for `tf.VariableSynchronization.ON_READ` synchronization. This policy is created when `synchronization` is set to `tf.VariableSynchronization.ON_READ` and `aggregation` is set to any of the values allowed by the `tf.VariableAggregation` enum such as `NONE`, `SUM`, `MEAN` or `ONLY_FIRST_REPLICA`when creating a `tf.Variable` in `tf.distribute` scope. """ def _is_mirrored(self): return False def value(self, var): with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): if (distribute_lib.in_cross_replica_context() and not values_util.in_replica_update_context()): if self._aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA: return var._get_replica(0).value() # pylint: disable=protected-access return var._get_cross_replica() # pylint: disable=protected-access else: return var._get_on_device_or_primary().value() # pylint: disable=protected-access def _as_graph_element(self, var): with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): if distribute_lib.in_cross_replica_context(): return ops.convert_to_tensor(var._get_cross_replica()) # pylint: disable=protected-access return var._get()._as_graph_element() # pylint: disable=protected-access def _get_cross_replica(self, var): if self._aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA: return var._get_replica(0) # pylint: disable=protected-access if self._aggregation == vs.VariableAggregation.SUM: values_util.mark_as_unsaveable() with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): return var.distribute_strategy.reduce( reduce_util.ReduceOp.from_variable_aggregation(self._aggregation), var, axis=None) def _update_replica(self, var, update_fn, value, **kwargs): return update_fn(var._get_on_device_or_primary(), value, **kwargs) # pylint: disable=protected-access def _scatter_not_implemented(self, method): raise NotImplementedError(f"ON_READ variables doesn't support `{method}` " "in cross replica context") def assign_sub(self, var, value, use_locking=False, name=None, read_value=True): """Subtracts a value from this variable.""" with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): if (distribute_lib.in_cross_replica_context() and not values_util.in_replica_update_context()): values_util.mark_as_unsaveable() return values_util.on_read_assign_sub_cross_replica( var, value, read_value=read_value) else: return values_util.on_write_assign_sub( var, value, use_locking=use_locking, name=name, read_value=read_value) def assign_add(self, var, value, use_locking=False, name=None, read_value=True): """Adds a value to this variable.""" with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): if (distribute_lib.in_cross_replica_context() and not values_util.in_replica_update_context()): values_util.mark_as_unsaveable() return values_util.on_read_assign_add_cross_replica( var, value, read_value=read_value) else: return values_util.on_write_assign_add( var, value, use_locking=use_locking, name=name, read_value=read_value) def assign(self, var, value, use_locking=False, name=None, read_value=True): with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): if (distribute_lib.in_cross_replica_context() and not values_util.in_replica_update_context()): values_util.mark_as_unsaveable() return values_util.on_read_assign_cross_replica( var, value, read_value=read_value) else: return values_util.on_write_assign( var, value, use_locking=use_locking, name=name, read_value=read_value) def scatter_sub(self, *args, **kwargs): del args, kwargs self._scatter_not_implemented("scatter_sub") def scatter_add(self, *args, **kwargs): del args, kwargs self._scatter_not_implemented("scatter_add") def scatter_mul(self, *args, **kwargs): del args, kwargs self._scatter_not_implemented("scatter_mul") def scatter_div(self, *args, **kwargs): del args, kwargs self._scatter_not_implemented("scatter_div") def scatter_min(self, *args, **kwargs): del args, kwargs self._scatter_not_implemented("scatter_min") def scatter_max(self, *args, **kwargs): del args, kwargs self._scatter_not_implemented("scatter_max") def scatter_update(self, *args, **kwargs): del args, kwargs self._scatter_not_implemented("scatter_update") def get_saveable(self, var, primary_var, name): """Create a saveable object for the given variable.""" return values_util.get_on_read_saveable(var, primary_var, name) def get_restore_ops(self, var, tensor): """Restore the same value into all variables.""" return values_util.get_on_read_restore_ops(var, tensor, self._aggregation)
OnReadPolicy
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/types.py
{ "start": 26234, "end": 26367 }
class ____(sqltypes._Binary): """MySQL TINYBLOB type, for binary data up to 2^8 bytes.""" __visit_name__ = "TINYBLOB"
TINYBLOB
python
pdm-project__pdm
src/pdm/_types.py
{ "start": 4259, "end": 4339 }
class ____: pass NotSet = NotSetType() @dc.dataclass(frozen=True)
NotSetType
python
django__django
tests/introspection/models.py
{ "start": 1458, "end": 1654 }
class ____(models.Model): article = models.ForeignKey(Article, models.CASCADE) reporter = models.ForeignKey(Reporter, models.CASCADE) class Meta: managed = False
ArticleReporter
python
getsentry__sentry
src/sentry/integrations/cursor/models.py
{ "start": 843, "end": 945 }
class ____(BaseModel): autoCreatePr: bool branchName: str url: str
CursorAgentResponseTarget
python
kamyu104__LeetCode-Solutions
Python/find-the-value-of-the-partition.py
{ "start": 40, "end": 267 }
class ____(object): def findValueOfPartition(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return min(nums[i+1]-nums[i] for i in xrange(len(nums)-1))
Solution
python
huggingface__transformers
src/transformers/optimization.py
{ "start": 38403, "end": 39891 }
class ____(LambdaLR): """ Since [`~optimization.Adafactor`] performs its own scheduling, if the training loop relies on a scheduler (e.g., for logging), this class creates a proxy object that retrieves the current lr values from the optimizer. It returns `initial_lr` during startup and the actual `lr` during stepping. """ def __init__(self, optimizer, initial_lr=0.0): def lr_lambda(_): return initial_lr for group in optimizer.param_groups: group["initial_lr"] = initial_lr super().__init__(optimizer, lr_lambda) for group in optimizer.param_groups: del group["initial_lr"] def get_lr(self): opt = self.optimizer lrs = [ opt._get_lr(group, opt.state[group["params"][0]]) for group in opt.param_groups if group["params"][0].grad is not None ] if len(lrs) == 0: lrs = self.base_lrs # if called before stepping return lrs def get_adafactor_schedule(optimizer, initial_lr=0.0): """ Get a proxy schedule for [`~optimization.Adafactor`] Args: optimizer ([`~torch.optim.Optimizer`]): The optimizer for which to schedule the learning rate. initial_lr (`float`, *optional*, defaults to 0.0): Initial lr Return: [`~optimization.Adafactor`] proxy schedule object. """ return AdafactorSchedule(optimizer, initial_lr)
AdafactorSchedule
python
PrefectHQ__prefect
tests/server/orchestration/test_core_policy.py
{ "start": 29186, "end": 34401 }
class ____: """ Following https://github.com/PrefectHQ/prefect/pull/9152 some of these test names may be stale however they are retained to simplify understanding of changed behavior. Generally, failed task runs can just retry whenever they want now. """ async def test_bypasses_terminal_state_rule_if_flow_is_retrying( self, session, initialize_orchestration, ): rerun_policy = [ HandleTaskTerminalStateTransitions, UpdateFlowRunTrackerOnTasks, ] initial_state_type = states.StateType.FAILED proposed_state_type = states.StateType.RUNNING intended_transition = (initial_state_type, proposed_state_type) ctx = await initialize_orchestration( session, "task", *intended_transition, flow_retries=10, ) flow_run = await ctx.flow_run() flow_run.run_count = 4 ctx.run.flow_run_run_count = 2 ctx.run.run_count = 2 async with contextlib.AsyncExitStack() as stack: for rule in rerun_policy: ctx = await stack.enter_async_context(rule(ctx, *intended_transition)) assert ctx.response_status == SetStateStatus.ACCEPT assert ctx.run.run_count == 0 assert ctx.proposed_state.name == "Retrying" assert ctx.run.flow_run_run_count == 4, ( "Orchestration should update the flow run run count tracker" ) async def test_can_run_again_even_if_exceeding_flow_runs_count( self, session, initialize_orchestration, ): rerun_policy = [ HandleTaskTerminalStateTransitions, UpdateFlowRunTrackerOnTasks, ] initial_state_type = states.StateType.FAILED proposed_state_type = states.StateType.RUNNING intended_transition = (initial_state_type, proposed_state_type) ctx = await initialize_orchestration( session, "task", *intended_transition, initial_state_data="test", flow_retries=10, ) flow_run = await ctx.flow_run() flow_run.run_count = 3 ctx.run.flow_run_run_count = 3 ctx.run.run_count = 2 async with contextlib.AsyncExitStack() as stack: for rule in rerun_policy: ctx = await stack.enter_async_context(rule(ctx, *intended_transition)) assert ctx.response_status == SetStateStatus.ACCEPT assert ctx.run.run_count == 0 assert ctx.proposed_state.type == StateType.RUNNING assert ctx.run.flow_run_run_count == 3 async def test_bypasses_terminal_state_rule_if_configured_automatic_retries_is_exceeded( self, session, initialize_orchestration, ): # this functionality enables manual retries to occur even if all automatic # retries have been consumed rerun_policy = [ HandleTaskTerminalStateTransitions, UpdateFlowRunTrackerOnTasks, ] initial_state_type = states.StateType.FAILED proposed_state_type = states.StateType.RUNNING intended_transition = (initial_state_type, proposed_state_type) ctx = await initialize_orchestration( session, "task", *intended_transition, flow_retries=1, ) flow_run = await ctx.flow_run() flow_run.run_count = 4 ctx.run.flow_run_run_count = 2 ctx.run.run_count = 2 async with contextlib.AsyncExitStack() as stack: for rule in rerun_policy: ctx = await stack.enter_async_context(rule(ctx, *intended_transition)) assert ctx.response_status == SetStateStatus.ACCEPT assert ctx.run.run_count == 0 assert ctx.proposed_state.name == "Retrying" assert ctx.run.flow_run_run_count == 4, ( "Orchestration should update the flow run run count tracker" ) async def test_cleans_up_after_invalid_transition( self, session, initialize_orchestration, fizzling_rule, ): rerun_policy = [ HandleTaskTerminalStateTransitions, UpdateFlowRunTrackerOnTasks, fizzling_rule, ] initial_state_type = states.StateType.FAILED proposed_state_type = states.StateType.RUNNING intended_transition = (initial_state_type, proposed_state_type) ctx = await initialize_orchestration( session, "task", *intended_transition, flow_retries=10, ) flow_run = await ctx.flow_run() flow_run.run_count = 4 ctx.run.flow_run_run_count = 2 ctx.run.run_count = 2 async with contextlib.AsyncExitStack() as stack: for rule in rerun_policy: ctx = await stack.enter_async_context(rule(ctx, *intended_transition)) assert ctx.response_status == SetStateStatus.REJECT assert ctx.run.run_count == 2 assert ctx.proposed_state.name == "Retrying" assert ctx.run.flow_run_run_count == 2
TestPermitRerunningFailedTaskRuns
python
numpy__numpy
numpy/lib/tests/test_arraypad.py
{ "start": 48371, "end": 49668 }
class ____: def test_check_simple(self): a = np.arange(12) a = np.reshape(a, (4, 3)) a = np.pad(a, ((2, 3), (3, 2)), 'edge') b = np.array( [[0, 0, 0, 0, 1, 2, 2, 2], [0, 0, 0, 0, 1, 2, 2, 2], [0, 0, 0, 0, 1, 2, 2, 2], [3, 3, 3, 3, 4, 5, 5, 5], [6, 6, 6, 6, 7, 8, 8, 8], [9, 9, 9, 9, 10, 11, 11, 11], [9, 9, 9, 9, 10, 11, 11, 11], [9, 9, 9, 9, 10, 11, 11, 11], [9, 9, 9, 9, 10, 11, 11, 11]] ) assert_array_equal(a, b) def test_check_width_shape_1_2(self): # Check a pad_width of the form ((1, 2),). # Regression test for issue gh-7808. a = np.array([1, 2, 3]) padded = np.pad(a, ((1, 2),), 'edge') expected = np.array([1, 1, 2, 3, 3, 3]) assert_array_equal(padded, expected) a = np.array([[1, 2, 3], [4, 5, 6]]) padded = np.pad(a, ((1, 2),), 'edge') expected = np.pad(a, ((1, 2), (1, 2)), 'edge') assert_array_equal(padded, expected) a = np.arange(24).reshape(2, 3, 4) padded = np.pad(a, ((1, 2),), 'edge') expected = np.pad(a, ((1, 2), (1, 2), (1, 2)), 'edge') assert_array_equal(padded, expected)
TestEdge
python
pytorch__pytorch
.ci/lumen_cli/tests/test_cli_helper.py
{ "start": 378, "end": 1324 }
class ____(BaseRunner): def run(self) -> None: # replaced by mock pass def add_foo_args(p: argparse.ArgumentParser) -> None: p.add_argument("--x", type=int, required=True, help="x value") def common_args(p: argparse.ArgumentParser) -> None: p.add_argument("--verbose", action="store_true", help="verbose flag") def build_parser(specs: dict[str, TargetSpec]) -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="app", formatter_class=RichHelp) register_targets( parser=parser, target_specs=specs, common_args=common_args, ) return parser def get_subparser( parser: argparse.ArgumentParser, name: str ) -> argparse.ArgumentParser: subparsers_action = next( a for a in parser._subparsers._group_actions # type: ignore[attr-defined] if isinstance(a, argparse._SubParsersAction) ) return subparsers_action.choices[name]
BarRunner
python
huggingface__transformers
tests/models/detr/test_modeling_detr.py
{ "start": 31106, "end": 32670 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return ( DetrImageProcessor.from_pretrained("facebook/detr-resnet-50", revision="no_timm") if is_vision_available() else None ) def test_inference_no_head(self): model = DetrModel.from_pretrained("facebook/detr-resnet-50", revision="no_timm").to(torch_device) image_processor = self.default_image_processor image = prepare_img() encoding = image_processor(images=image, return_tensors="pt").to(torch_device) with torch.no_grad(): outputs = model(**encoding) expected_shape = torch.Size((1, 100, 256)) assert outputs.last_hidden_state.shape == expected_shape expected_slices = Expectations( { (None, None): [ [0.0616, -0.5146, -0.4032], [-0.7629, -0.4934, -1.7153], [-0.4768, -0.6403, -0.7826], ], ("rocm", (9, 5)): [ [ 0.0616, -0.5146, -0.4032], [-0.7629, -0.4934, -1.7153], [-0.4768, -0.6403, -0.7826] ], } ) # fmt: skip expected_slice = torch.tensor(expected_slices.get_expectation(), device=torch_device) torch.testing.assert_close(outputs.last_hidden_state[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
DetrModelIntegrationTests
python
pennersr__django-allauth
allauth/socialaccount/providers/agave/provider.py
{ "start": 211, "end": 439 }
class ____(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get("web_url", "dflt") def get_avatar_url(self): return self.account.extra_data.get("avatar_url", "dflt")
AgaveAccount
python
facelessuser__soupsieve
soupsieve/css_types.py
{ "start": 3573, "end": 4252 }
class ____(ImmutableDict): """Namespaces.""" def __init__(self, arg: dict[str, str] | Iterable[tuple[str, str]]) -> None: """Initialize.""" super().__init__(arg) def _validate(self, arg: dict[str, str] | Iterable[tuple[str, str]]) -> None: """Validate arguments.""" if isinstance(arg, dict): if not all(isinstance(v, str) for v in arg.values()): raise TypeError(f'{self.__class__.__name__} values must be hashable') elif not all(isinstance(k, str) and isinstance(v, str) for k, v in arg): raise TypeError(f'{self.__class__.__name__} keys and values must be Unicode strings')
Namespaces
python
django__django
tests/admin_views/admin.py
{ "start": 19527, "end": 19743 }
class ____(admin.ModelAdmin): list_display = ("id", "title", "content") list_display_links = ("title", "id") # 'id' in list_display_links list_editable = ("content",) ordering = ["-id"]
OtherStoryAdmin
python
getsentry__sentry
tests/sentry/plugins/test_helpers.py
{ "start": 145, "end": 1111 }
class ____(TestCase): def test_set_option_with_project(self) -> None: with mock.patch("sentry.models.ProjectOption.objects.set_value") as set_value: project = mock.Mock() set_option("key", "value", project) set_value.assert_called_once_with(project, "key", "value") def test_get_option_with_project(self) -> None: with mock.patch("sentry.models.ProjectOption.objects.get_value") as get_value: project = mock.Mock() result = get_option("key", project) self.assertEqual(result, get_value.return_value) get_value.assert_called_once_with(project, "key", None) def test_unset_option_with_project(self) -> None: with mock.patch("sentry.models.ProjectOption.objects.unset_value") as unset_value: project = mock.Mock() unset_option("key", project) unset_value.assert_called_once_with(project, "key")
SentryPluginTest
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/richlog_width.py
{ "start": 143, "end": 1120 }
class ____(App[None]): def compose(self) -> ComposeResult: rich_log = RichLog(min_width=20) rich_log.display = False rich_log.write( Text("written in compose", style="black on white", justify="right"), expand=True, ) yield rich_log def key_p(self, event: Resize) -> None: rich_log: RichLog = self.query_one(RichLog) rich_log.display = True rich_log.write(Text("hello1", style="on red", justify="right"), expand=True) rich_log.visible = False rich_log.write(Text("world2", style="on green", justify="right"), expand=True) rich_log.visible = True rich_log.write(Text("hello3", style="on blue", justify="right"), expand=True) rich_log.display = False rich_log.write(Text("world4", style="on yellow", justify="right"), expand=True) rich_log.display = True app = RichLogWidth() if __name__ == "__main__": app.run()
RichLogWidth
python
getlogbook__logbook
src/logbook/more.py
{ "start": 9837, "end": 11590 }
class ____(Handler): """This handler invokes an external application to send parts of the log record to. The constructor takes a list of arguments that are passed to another application where each of the arguments is a format string, and optionally a format string for data that is passed to stdin. For example it can be used to invoke the ``say`` command on OS X:: from logbook.more import ExternalApplicationHandler say_handler = ExternalApplicationHandler(["say", "{record.message}"]) Note that the above example is blocking until ``say`` finished, so it's recommended to combine this handler with the :class:`logbook.ThreadedWrapperHandler` to move the execution into a background thread. .. versionadded:: 0.3 """ def __init__( self, arguments, stdin_format=None, encoding="utf-8", level=NOTSET, filter=None, bubble=False, ): Handler.__init__(self, level, filter, bubble) self.encoding = encoding self._arguments = list(arguments) if stdin_format is not None: stdin_format = stdin_format self._stdin_format = stdin_format import subprocess self._subprocess = subprocess def emit(self, record): args = [arg.format(record=record) for arg in self._arguments] if self._stdin_format is not None: stdin_data = self._stdin_format.format(record=record).encode(self.encoding) stdin = self._subprocess.PIPE else: stdin = None c = self._subprocess.Popen(args, stdin=stdin) if stdin is not None: c.communicate(stdin_data) c.wait()
ExternalApplicationHandler
python
tensorflow__tensorflow
tensorflow/python/autograph/converters/directives.py
{ "start": 1576, "end": 3114 }
class ____(object): def __init__(self): self.ast_node = None self.statements_visited = 0 def _map_args(call_node, function): """Maps AST call nodes to the actual function's arguments. Args: call_node: ast.Call function: Callable[..., Any], the actual function matching call_node Returns: Dict[Text, ast.AST], mapping each of the function's argument names to the respective AST node. Raises: ValueError: if the default arguments are not correctly set """ args = call_node.args kwds = {kwd.arg: kwd.value for kwd in call_node.keywords} call_args = tf_inspect.getcallargs(function, *args, **kwds) # Keyword arguments not specified in kwds will be mapped to their defaults, # which are Python values. Since we don't currently have a way to transform # those into AST references, we simply remove them. By convention, directives # use UNSPECIFIED as default value for optional arguments. No other # defaults should be present. unexpected_defaults = [] for k in call_args: if (k not in kwds and call_args[k] not in args and call_args[k] is not directives.UNSPECIFIED): unexpected_defaults.append(k) if unexpected_defaults: raise ValueError('Unexpected keyword argument values, %s, for function %s' % (zip(unexpected_defaults, [call_args[k] for k in unexpected_defaults]), function)) return {k: v for k, v in call_args.items() if v is not directives.UNSPECIFIED}
_LoopScope
python
Textualize__textual
tests/css/test_parse.py
{ "start": 29453, "end": 31752 }
class ____: @pytest.mark.parametrize( "offset_x, parsed_x, offset_y, parsed_y", [ [ "-5.5%", Scalar(-5.5, Unit.PERCENT, Unit.WIDTH), "-30%", Scalar(-30, Unit.PERCENT, Unit.HEIGHT), ], [ "5%", Scalar(5, Unit.PERCENT, Unit.WIDTH), "40%", Scalar(40, Unit.PERCENT, Unit.HEIGHT), ], [ "10", Scalar(10, Unit.CELLS, Unit.WIDTH), "40", Scalar(40, Unit.CELLS, Unit.HEIGHT), ], ], ) def test_composite_rule(self, offset_x, parsed_x, offset_y, parsed_y): css = f"""#some-widget {{ offset: {offset_x} {offset_y}; }} """ stylesheet = Stylesheet() stylesheet.add_source(css) styles = stylesheet.rules[0].styles assert len(stylesheet.rules) == 1 assert stylesheet.rules[0].errors == [] assert styles.offset.x == parsed_x assert styles.offset.y == parsed_y @pytest.mark.parametrize( "offset_x, parsed_x, offset_y, parsed_y", [ [ "-5.5%", Scalar(-5.5, Unit.PERCENT, Unit.WIDTH), "-30%", Scalar(-30, Unit.PERCENT, Unit.HEIGHT), ], [ "5%", Scalar(5, Unit.PERCENT, Unit.WIDTH), "40%", Scalar(40, Unit.PERCENT, Unit.HEIGHT), ], [ "-10", Scalar(-10, Unit.CELLS, Unit.WIDTH), "40", Scalar(40, Unit.CELLS, Unit.HEIGHT), ], ], ) def test_separate_rules(self, offset_x, parsed_x, offset_y, parsed_y): css = f"""#some-widget {{ offset-x: {offset_x}; offset-y: {offset_y}; }} """ stylesheet = Stylesheet() stylesheet.add_source(css) styles = stylesheet.rules[0].styles assert len(stylesheet.rules) == 1 assert stylesheet.rules[0].errors == [] assert styles.offset.x == parsed_x assert styles.offset.y == parsed_y
TestParseOffset
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF023.py
{ "start": 5229, "end": 5325 }
class ____: __slots__ = {'xp', 'yp', 'canvas' , }
BezierBuilder2
python
getsentry__sentry
src/sentry/auth/services/auth/model.py
{ "start": 1559, "end": 1651 }
class ____(RpcModel): sso_state: RpcMemberSsoState permissions: list[str]
RpcAuthState
python
sympy__sympy
sympy/codegen/fnodes.py
{ "start": 2197, "end": 3104 }
class ____(Token): """ Represents a use statement in Fortran. Examples ======== >>> from sympy.codegen.fnodes import use >>> from sympy import fcode >>> fcode(use('signallib'), source_format='free') 'use signallib' >>> fcode(use('signallib', [('metric', 'snr')]), source_format='free') 'use signallib, metric => snr' >>> fcode(use('signallib', only=['snr', 'convolution2d']), source_format='free') 'use signallib, only: snr, convolution2d' """ __slots__ = _fields = ('namespace', 'rename', 'only') defaults = {'rename': none, 'only': none} _construct_namespace = staticmethod(_name) _construct_rename = staticmethod(lambda args: Tuple(*[arg if isinstance(arg, use_rename) else use_rename(*arg) for arg in args])) _construct_only = staticmethod(lambda args: Tuple(*[arg if isinstance(arg, use_rename) else _name(arg) for arg in args]))
use
python
wandb__wandb
wandb/sdk/lib/fsm.py
{ "start": 1676, "end": 1836 }
class ____(Protocol[T_FsmInputs]): @abstractmethod def on_stay(self, inputs: T_FsmInputs) -> None: ... # pragma: no cover @runtime_checkable
FsmStateStay
python
readthedocs__readthedocs.org
readthedocs/audit/models.py
{ "start": 314, "end": 2057 }
class ____(models.Manager): """AuditLog manager.""" def new(self, action, user=None, request=None, **kwargs): """ Create an audit log for `action`. If user or request are given, other fields will be auto-populated from that information. """ actions_requiring_user = ( AuditLog.PAGEVIEW, AuditLog.DOWNLOAD, AuditLog.AUTHN, AuditLog.LOGOUT, AuditLog.INVITATION_SENT, AuditLog.INVITATION_ACCEPTED, AuditLog.INVITATION_REVOKED, ) if action in actions_requiring_user and (not user or not request): raise TypeError(f"A user and a request are required for the {action} action.") if action in (AuditLog.PAGEVIEW, AuditLog.DOWNLOAD) and "project" not in kwargs: raise TypeError(f"A project is required for the {action} action.") # Don't save anonymous users. if user and user.is_anonymous: user = None if request: kwargs["ip"] = get_client_ip(request) kwargs["browser"] = request.headers.get("User-Agent") kwargs.setdefault("resource", request.path_info) kwargs.setdefault("auth_backend", get_auth_backend(request)) # Fill the project from the request if available. # This is frequently on actions generated from a subdomain. unresolved_domain = getattr(request, "unresolved_domain", None) if "project" not in kwargs and unresolved_domain: kwargs["project"] = unresolved_domain.project return self.create( user=user, action=action, **kwargs, )
AuditLogManager
python
python__mypy
mypy/modulefinder.py
{ "start": 2147, "end": 4442 }
class ____(Enum): # The module was not found: we found neither stubs nor a plausible code # implementation (with or without a py.typed file). NOT_FOUND = 0 # The implementation for this module plausibly exists (e.g. we # found a matching folder or *.py file), but either the parent package # did not contain a py.typed file or we were unable to find a # corresponding *-stubs package. FOUND_WITHOUT_TYPE_HINTS = 1 # The module was not found in the current working directory, but # was able to be found in the parent directory. WRONG_WORKING_DIRECTORY = 2 # Stub PyPI package (typically types-pkgname) known to exist but not installed. APPROVED_STUBS_NOT_INSTALLED = 3 def error_message_templates(self, daemon: bool) -> tuple[str, list[str]]: doc_link = "See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports" if self is ModuleNotFoundReason.NOT_FOUND: msg = 'Cannot find implementation or library stub for module named "{module}"' notes = [doc_link] elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY: msg = 'Cannot find implementation or library stub for module named "{module}"' notes = [ "You may be running mypy in a subpackage, mypy should be run on the package root" ] elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: msg = ( 'Skipping analyzing "{module}": module is installed, but missing library stubs ' "or py.typed marker" ) notes = [doc_link] elif self is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED: msg = 'Library stubs not installed for "{module}"' notes = ['Hint: "python3 -m pip install {stub_dist}"'] if not daemon: notes.append( '(or run "mypy --install-types" to install all missing stub packages)' ) notes.append(doc_link) else: assert False return msg, notes # If we found the module, returns the path to the module as a str. # Otherwise, returns the reason why the module wasn't found. ModuleSearchResult = str | ModuleNotFoundReason
ModuleNotFoundReason
python
kamyu104__LeetCode-Solutions
Python/perfect-rectangle.py
{ "start": 66, "end": 871 }
class ____(object): def isRectangleCover(self, rectangles): """ :type rectangles: List[List[int]] :rtype: bool """ left = min(rec[0] for rec in rectangles) bottom = min(rec[1] for rec in rectangles) right = max(rec[2] for rec in rectangles) top = max(rec[3] for rec in rectangles) points = defaultdict(int) for l, b, r, t in rectangles: for p, q in zip(((l, b), (r, b), (l, t), (r, t)), (1, 2, 4, 8)): if points[p] & q: return False points[p] |= q for px, py in points: if left < px < right or bottom < py < top: if points[(px, py)] not in (3, 5, 10, 12, 15): return False return True
Solution
python
kamyu104__LeetCode-Solutions
Python/split-bst.py
{ "start": 29, "end": 523 }
class ____(object): def splitBST(self, root, V): """ :type root: TreeNode :type V: int :rtype: List[TreeNode] """ if not root: return None, None elif root.val <= V: result = self.splitBST(root.right, V) root.right = result[0] return root, result[1] else: result = self.splitBST(root.left, V) root.left = result[1] return result[0], root
Solution
python
bokeh__bokeh
src/bokeh/core/property/descriptors.py
{ "start": 4759, "end": 6048 }
class ____(Generic[T]): """ """ serialized: bool = False @property def aliased_name(self) -> str: return self.alias.aliased_name def __init__(self, name: str, alias: Alias[T]) -> None: self.name = name self.alias = alias self.property = alias self.__doc__ = f"This is a compatibility alias for the {self.aliased_name!r} property." def __get__(self, obj: HasProps | None, owner: type[HasProps] | None) -> T: if obj is not None: return getattr(obj, self.aliased_name) elif owner is not None: return self # This should really never happen. If it does, __get__ was called in a bad way. raise ValueError("both 'obj' and 'owner' are None, don't know what to do") def __set__(self, obj: HasProps | None, value: T) -> None: setattr(obj, self.aliased_name, value) @property def readonly(self) -> bool: return self.alias.readonly def has_unstable_default(self, obj: HasProps) -> bool: return obj.lookup(self.aliased_name).has_unstable_default(obj) def class_default(self, cls: type[HasProps], *, no_eval: bool = False): return cls.lookup(self.aliased_name).class_default(cls, no_eval=no_eval)
AliasPropertyDescriptor
python
getsentry__sentry
src/sentry/monitors/migrations/0008_fix_processing_error_keys.py
{ "start": 2588, "end": 6191 }
class ____: errors: Sequence[Any] checkin: CheckinItem id: uuid.UUID = field(default_factory=uuid.uuid4) @classmethod def from_dict(cls, data: CheckinProcessingErrorData) -> "CheckinProcessingError": return cls( id=uuid.UUID(data["id"]), checkin=CheckinItem.from_dict(data["checkin"]), errors=data["errors"], ) def to_dict(self) -> CheckinProcessingErrorData: return { "id": self.id.hex, "checkin": self.checkin.to_dict(), "errors": self.errors, } def _get_cluster() -> Any: return redis.redis_clusters.get(settings.SENTRY_MONITORS_REDIS_CLUSTER) def build_monitor_identifier(monitor: Any) -> str: return f"monitor:{monitor.id}" def build_error_identifier(uuid: uuid.UUID) -> str: return f"monitors.processing_errors.{uuid.hex}" def build_project_identifier(project_id: str) -> str: return f"project:{project_id}" def get_uuid_from_error_identifier(error_identifier: str) -> uuid.UUID: uuid_hex = error_identifier.split(".")[2] return uuid.UUID(hex=uuid_hex) def build_set_identifier(entity_identifier: str) -> str: return f"monitors.processing_errors_set.{entity_identifier}" def fetch_processing_errors(entity_identifier: str) -> dict[uuid.UUID, Any]: redis = _get_cluster() pipeline = redis.pipeline() pipeline.zrange(build_set_identifier(entity_identifier), 0, MAX_ERRORS_PER_SET, desc=True) processing_errors = {} error_identifiers = [ build_error_identifier(uuid.UUID(error_identifier)) for error_identifier in chain(*pipeline.execute()) ] for error_identifier in error_identifiers: raw_error = redis.mget(error_identifier)[0] if raw_error is not None: processing_errors[get_uuid_from_error_identifier(error_identifier)] = ( CheckinProcessingError.from_dict(json.loads(raw_error)) ) return processing_errors def fix_processing_error_keys(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None: Monitor = apps.get_model("monitors", "Monitor") Project = apps.get_model("sentry", "Project") redis = _get_cluster() pipeline = redis.pipeline() # step 1: fix all monitors for monitor in RangeQuerySetWrapper(Monitor.objects.all()): monitor_identifier = build_monitor_identifier(monitor) processing_errors = fetch_processing_errors(monitor_identifier) for error_id in processing_errors: processing_error = processing_errors[error_id] if processing_error.id != error_id: processing_error.id = error_id error_key = build_error_identifier(error_id) pipeline.set( error_key, json.dumps(processing_error.to_dict()), ex=MONITOR_ERRORS_LIFETIME ) pipeline.execute() # step 2: fix all projects for project in RangeQuerySetWrapper(Project.objects.all()): project_identifier = build_project_identifier(str(project.id)) processing_errors = fetch_processing_errors(project_identifier) for error_id in processing_errors: processing_error = processing_errors[error_id] if processing_error.id != error_id: processing_error.id = error_id error_key = build_error_identifier(error_id) pipeline.set( error_key, json.dumps(processing_error.to_dict()), ex=MONITOR_ERRORS_LIFETIME ) pipeline.execute()
CheckinProcessingError
python
dagster-io__dagster
python_modules/libraries/dagster-k8s/dagster_k8s/launcher.py
{ "start": 1003, "end": 16936 }
class ____(RunLauncher, ConfigurableClass): """RunLauncher that starts a Kubernetes Job for each Dagster job run. Encapsulates each run in a separate, isolated invocation of ``dagster-graphql``. You can configure a Dagster instance to use this RunLauncher by adding a section to your ``dagster.yaml`` like the following: .. code-block:: yaml run_launcher: module: dagster_k8s.launcher class: K8sRunLauncher config: service_account_name: your_service_account job_image: my_project/dagster_image:latest instance_config_map: dagster-instance postgres_password_secret: dagster-postgresql-secret """ def __init__( self, service_account_name, instance_config_map, postgres_password_secret=None, dagster_home=None, job_image=None, image_pull_policy=None, image_pull_secrets=None, load_incluster_config=True, kubeconfig_file=None, inst_data: Optional[ConfigurableClassData] = None, job_namespace="default", env_config_maps=None, env_secrets=None, env_vars=None, k8s_client_batch_api=None, k8s_client_core_api=None, volume_mounts=None, volumes=None, labels=None, fail_pod_on_run_failure=None, resources=None, scheduler_name=None, security_context=None, run_k8s_config=None, only_allow_user_defined_k8s_config_fields=None, only_allow_user_defined_env_vars=None, ): self._inst_data = check.opt_inst_param(inst_data, "inst_data", ConfigurableClassData) self.job_namespace = check.str_param(job_namespace, "job_namespace") self.load_incluster_config = load_incluster_config self.kubeconfig_file = kubeconfig_file if load_incluster_config: check.invariant( kubeconfig_file is None, "`kubeconfig_file` is set but `load_incluster_config` is True.", ) kubernetes.config.load_incluster_config() else: check.opt_str_param(kubeconfig_file, "kubeconfig_file") kubernetes.config.load_kube_config(kubeconfig_file) self._api_client = DagsterKubernetesClient.production_client( core_api_override=k8s_client_core_api, batch_api_override=k8s_client_batch_api, ) self._job_config = None self._job_image = check.opt_str_param(job_image, "job_image") self.dagster_home = check.str_param(dagster_home, "dagster_home") self._image_pull_policy = check.opt_str_param( image_pull_policy, "image_pull_policy", "IfNotPresent" ) self._image_pull_secrets = check.opt_list_param( image_pull_secrets, "image_pull_secrets", of_type=dict ) self._service_account_name = check.str_param(service_account_name, "service_account_name") self.instance_config_map = check.str_param(instance_config_map, "instance_config_map") self.postgres_password_secret = check.opt_str_param( postgres_password_secret, "postgres_password_secret" ) self._env_config_maps = check.opt_list_param( env_config_maps, "env_config_maps", of_type=str ) self._env_secrets = check.opt_list_param(env_secrets, "env_secrets", of_type=str) self._env_vars = check.opt_list_param(env_vars, "env_vars", of_type=str) self._volume_mounts = check.opt_list_param(volume_mounts, "volume_mounts") self._volumes = check.opt_list_param(volumes, "volumes") self._labels: Mapping[str, str] = check.opt_mapping_param( labels, "labels", key_type=str, value_type=str ) self._fail_pod_on_run_failure = check.opt_bool_param( fail_pod_on_run_failure, "fail_pod_on_run_failure" ) self._resources: Mapping[str, Any] = check.opt_mapping_param(resources, "resources") self._scheduler_name = check.opt_str_param(scheduler_name, "scheduler_name") self._security_context = check.opt_dict_param(security_context, "security_context") self._run_k8s_config = check.opt_dict_param(run_k8s_config, "run_k8s_config") self._only_allow_user_defined_k8s_config_fields = only_allow_user_defined_k8s_config_fields self._only_allow_user_defined_env_vars = only_allow_user_defined_env_vars super().__init__() @property def job_image(self): return self._job_image @property def image_pull_policy(self) -> str: return self._image_pull_policy @property def image_pull_secrets(self) -> Sequence[Mapping]: return self._image_pull_secrets @property def service_account_name(self) -> str: return self._service_account_name @property def env_config_maps(self) -> Sequence[str]: return self._env_config_maps @property def env_secrets(self) -> Sequence[str]: return self._env_secrets @property def volume_mounts(self) -> Sequence: return self._volume_mounts @property def volumes(self) -> Sequence: return self._volumes @property def resources(self) -> Mapping: return self._resources @property def scheduler_name(self) -> Optional[str]: return self._scheduler_name @property def security_context(self) -> Mapping[str, Any]: return self._security_context @property def env_vars(self) -> Sequence[str]: return self._env_vars @property def labels(self) -> Mapping[str, str]: return self._labels @property def run_k8s_config(self) -> Mapping[str, str]: return self._run_k8s_config @property def fail_pod_on_run_failure(self) -> Optional[bool]: return self._fail_pod_on_run_failure @property def only_allow_user_defined_k8s_config_fields(self) -> Optional[Mapping[str, Any]]: return self._only_allow_user_defined_k8s_config_fields @property def only_allow_user_defined_env_vars(self) -> Optional[Sequence[str]]: return self._only_allow_user_defined_env_vars @classmethod def config_type(cls): """Include all arguments required for DagsterK8sJobConfig along with additional arguments needed for the RunLauncher itself. """ return DagsterK8sJobConfig.config_type_run_launcher() @classmethod def from_config_value(cls, inst_data, config_value): return cls(inst_data=inst_data, **config_value) @property def inst_data(self) -> Optional[ConfigurableClassData]: return self._inst_data def get_container_context_for_run(self, dagster_run: DagsterRun) -> K8sContainerContext: return K8sContainerContext.create_for_run(dagster_run, self, include_run_tags=True) def _launch_k8s_job_with_args( self, job_name: str, args: Optional[Sequence[str]], run: DagsterRun ) -> None: container_context = self.get_container_context_for_run(run) pod_name = job_name job_origin = check.not_none(run.job_code_origin) user_defined_k8s_config = container_context.run_k8s_config repository_origin = job_origin.repository_origin job_config = container_context.get_k8s_job_config( job_image=repository_origin.container_image, run_launcher=self ) labels = { "dagster/job": job_origin.job_name, "dagster/run-id": run.run_id, } deployment_name_env_var = get_deployment_id_label(user_defined_k8s_config) if deployment_name_env_var: labels["dagster/deployment-name"] = deployment_name_env_var if run.remote_job_origin: labels["dagster/code-location"] = ( run.remote_job_origin.repository_origin.code_location_origin.location_name ) job = construct_dagster_k8s_job( job_config=job_config, args=args, job_name=job_name, pod_name=pod_name, component="run_worker", user_defined_k8s_config=user_defined_k8s_config, labels=labels, env_vars=[ { "name": "DAGSTER_RUN_JOB_NAME", "value": job_origin.job_name, }, ], ) # Set docker/image tag here, as it can also be provided by `user_defined_k8s_config`. self._instance.add_run_tags( run.run_id, {DOCKER_IMAGE_TAG: job.spec.template.spec.containers[0].image}, ) namespace = check.not_none(container_context.namespace) self._instance.report_engine_event( "Creating Kubernetes run worker job", run, EngineEventData( { "Kubernetes Job name": job_name, "Kubernetes Namespace": namespace, "Run ID": run.run_id, } ), cls=self.__class__, ) self._api_client.create_namespaced_job_with_retries(body=job, namespace=namespace) self._instance.report_engine_event( "Kubernetes run worker job created", run, cls=self.__class__, ) def launch_run(self, context: LaunchRunContext) -> None: run = context.dagster_run job_name = get_job_name_from_run_id(run.run_id) job_origin = check.not_none(run.job_code_origin) args = ExecuteRunArgs( job_origin=job_origin, run_id=run.run_id, instance_ref=self._instance.get_ref(), set_exit_code_on_failure=self._fail_pod_on_run_failure, ).get_command_args() self._launch_k8s_job_with_args(job_name, args, run) @property def supports_resume_run(self): return True def resume_run(self, context: ResumeRunContext) -> None: run = context.dagster_run job_name = get_job_name_from_run_id( run.run_id, resume_attempt_number=context.resume_attempt_number ) job_origin = check.not_none(run.job_code_origin) args = ResumeRunArgs( job_origin=job_origin, run_id=run.run_id, instance_ref=self._instance.get_ref(), set_exit_code_on_failure=self._fail_pod_on_run_failure, ).get_command_args() self._launch_k8s_job_with_args(job_name, args, run) def _get_resume_attempt_number(self, run: DagsterRun) -> Optional[int]: if not self.supports_run_worker_crash_recovery: return None return self._instance.count_resume_run_attempts(run.run_id) def terminate(self, run_id): # pyright: ignore[reportIncompatibleMethodOverride] check.str_param(run_id, "run_id") run = self._instance.get_run_by_id(run_id) if not run or run.is_finished: return False self._instance.report_run_canceling(run) container_context = self.get_container_context_for_run(run) job_name = get_job_name_from_run_id( run_id, resume_attempt_number=self._get_resume_attempt_number(run) ) try: termination_result = self._api_client.delete_job( job_name=job_name, namespace=container_context.namespace ) if termination_result: self._instance.report_engine_event( message="Run was terminated successfully.", dagster_run=run, cls=self.__class__, ) else: self._instance.report_engine_event( message=f"Run was not terminated successfully; delete_job returned {termination_result}", dagster_run=run, cls=self.__class__, ) return termination_result except Exception: self._instance.report_engine_event( message="Run was not terminated successfully; encountered error in delete_job", dagster_run=run, engine_event_data=EngineEventData.engine_error( serializable_error_info_from_exc_info(sys.exc_info()) ), cls=self.__class__, ) @property def supports_check_run_worker_health(self): return True @property def supports_run_worker_crash_recovery(self): return True def get_run_worker_debug_info( self, run: DagsterRun, include_container_logs: Optional[bool] = True ) -> Optional[str]: container_context = self.get_container_context_for_run(run) job_name = get_job_name_from_run_id( run.run_id, resume_attempt_number=self._get_resume_attempt_number(run) ) namespace = container_context.namespace pod_names = self._api_client.get_pod_names_in_job(job_name, namespace=namespace) full_msg = "" try: pod_debug_info = [ self._api_client.get_pod_debug_info( pod_name, namespace, include_container_logs=include_container_logs ) for pod_name in pod_names ] full_msg = "\n".join(pod_debug_info) except Exception: logging.exception( f"Error trying to get debug information for failed k8s job {job_name}" ) if pod_names: full_msg = ( full_msg + "\nFor more information about the failure, try running `kubectl describe pod" f" {pod_names[0]}`, `kubectl logs {pod_names[0]}`, or `kubectl describe job" f" {job_name}` in your cluster." ) else: job_debug_info = self._api_client.get_job_debug_info(job_name, namespace=namespace) # pyright: ignore[reportArgumentType] full_msg = ( full_msg + "\n\n" + job_debug_info + "\n\nFor more information about the failure, try running `kubectl describe job" f" {job_name}` in your cluster." ) return full_msg def check_run_worker_health(self, run: DagsterRun): container_context = self.get_container_context_for_run(run) job_name = get_job_name_from_run_id( run.run_id, resume_attempt_number=self._get_resume_attempt_number(run) ) try: status = self._api_client.get_job_status( namespace=container_context.namespace, # pyright: ignore[reportArgumentType] job_name=job_name, ) except Exception: return CheckRunHealthResult( WorkerStatus.UNKNOWN, str(serializable_error_info_from_exc_info(sys.exc_info())) ) if not status: return CheckRunHealthResult(WorkerStatus.UNKNOWN, f"Job {job_name} could not be found") inactive_job_with_finished_pods = bool( (not status.active) and (status.failed or status.succeeded) ) # If the run is in a non-terminal (and non-STARTING) state but the k8s job is not active, # something went wrong if ( run.status in (DagsterRunStatus.STARTED, DagsterRunStatus.CANCELING) and inactive_job_with_finished_pods ): return CheckRunHealthResult( WorkerStatus.FAILED, "Run has not completed but K8s job has no active pods" ) if status.succeeded: return CheckRunHealthResult(WorkerStatus.SUCCESS) if status.failed and not status.active: return CheckRunHealthResult(WorkerStatus.FAILED, "K8s job failed") return CheckRunHealthResult(WorkerStatus.RUNNING)
K8sRunLauncher
python
google__pytype
pytype/constant_folding.py
{ "start": 7396, "end": 19651 }
class ____(pyc.CodeVisitor): """Fold constant literals in pyc code.""" def visit_code(self, code: blocks.OrderedCode): """Visit code, folding literals.""" def build_tuple(tup): out = [] for e in tup: if isinstance(e, tuple): out.append(build_tuple(e)) else: out.append(('prim', type(e))) return ('tuple', tuple(out)) folds = _FoldedOps() for block in code.order: stack = _Stack() for op in block: if isinstance(op, opcodes.LOAD_CONST): elt = code.consts[op.arg] if isinstance(elt, tuple): typ = build_tuple(elt) stack.push(_Constant(typ, elt, typ[1], op)) else: stack.push(_Constant(('prim', type(elt)), elt, None, op)) elif isinstance(op, opcodes.BUILD_LIST): stack.build(list, op) elif isinstance(op, opcodes.BUILD_SET): stack.build(set, op) elif isinstance(op, opcodes.FORMAT_VALUE): if op.arg & pyc_marshal.Flags.FVS_MASK: stack.build_str(2, op) else: stack.build_str(1, op) elif isinstance(op, opcodes.BUILD_STRING): stack.build_str(op.arg, op) elif isinstance(op, opcodes.BUILD_MAP): map_ = stack.fold_map_args(op.arg, op) if map_: typ = ('map', (map_.key_types, map_.value_types)) val = dict(zip(map_.keys, map_.values)) stack.push(_Constant(typ, val, map_.elements, op)) elif isinstance(op, opcodes.BUILD_CONST_KEY_MAP): keys = stack.pop() vals = stack.fold_args(op.arg, op) if vals: keys.op.folded = op _, t = keys.typ typ = ('map', (frozenset(t), vals.types)) val = dict(zip(keys.value, vals.values)) elements = dict(zip(keys.value, vals.elements)) stack.push(_Constant(typ, val, elements, op)) elif isinstance(op, opcodes.LIST_APPEND): elements = stack.fold_args(2, op) if elements: lst, element = elements.elements tag, et = lst.typ assert tag == 'list' typ = (tag, et | {element.typ}) value = lst.value + [element.value] elements = lst.elements + (element,) stack.push(_Constant(typ, value, elements, op)) elif isinstance(op, opcodes.LIST_EXTEND): elements = stack.fold_args(2, op) if elements: lst, other = elements.elements tag, et = lst.typ assert tag == 'list' other_tag, other_et = other.typ if other_tag == 'tuple': # Deconstruct the tuple built in opcodes.LOAD_CONST above other_elts = tuple( _Constant(('prim', e), v, None, other.op) for (_, e), v in zip(other_et, other.value) ) elif other_tag == 'prim': if other_et == str: other_et = {other.typ} other_elts = tuple( _Constant(('prim', str), v, None, other.op) for v in other.value ) else: # We have some malformed code, e.g. [*42] name = other_et.__name__ msg = f'Value after * must be an iterable, not {name}' raise ConstantError(msg, op) else: other_elts = other.elements typ = (tag, et | set(other_et)) value = lst.value + list(other.value) elements = lst.elements + other_elts stack.push(_Constant(typ, value, elements, op)) elif isinstance(op, opcodes.MAP_ADD): elements = stack.fold_args(3, op) if elements: map_, key, val = elements.elements tag, (kt, vt) = map_.typ assert tag == 'map' typ = (tag, (kt | {key.typ}, vt | {val.typ})) value = {**map_.value, **{key.value: val.value}} elements = {**map_.elements, **{key.value: val}} stack.push(_Constant(typ, value, elements, op)) elif isinstance(op, opcodes.DICT_UPDATE): elements = stack.fold_args(2, op) if elements: map1, map2 = elements.elements if map2.typ[0] != 'map': # We have some malformed code, e.g. {**42} name = map2.typ[1].__name__ msg = f'Value after ** must be an mapping, not {name}' raise ConstantError(msg, op) tag1, (kt1, vt1) = map1.typ tag2, (kt2, vt2) = map2.typ assert tag1 == tag2 == 'map' typ = (tag1, (kt1 | kt2, vt1 | vt2)) value = {**map1.value, **map2.value} elements = {**map1.elements, **map2.elements} stack.push(_Constant(typ, value, elements, op)) else: # If we hit any other bytecode, we are no longer building a literal # constant. Insert a None as a sentinel to the next BUILD op to # not fold itself. stack.push(None) # Clear the stack to save any folded constants before exiting the block stack.clear() # Now rewrite the block to replace folded opcodes with a single # LOAD_FOLDED_CONSTANT opcode. out = [] for op in block: if id(op) in stack.consts: t = stack.consts[id(op)] arg = t argval = t o = opcodes.LOAD_FOLDED_CONST( op.index, op.line, op.endline, op.col, op.endcol, arg, argval ) o.next = op.next o.target = op.target o.block_target = op.block_target o.code = op.code op.folded = o folds.add(op) out.append(o) elif op.folded: folds.add(op) else: out.append(op) block.code = out # Adjust 'next' and 'target' pointers to account for folding. for op in code.code_iter: if op.next: op.next = folds.resolve(op.next) if op.target: op.target = folds.resolve(op.target) return code def to_literal(typ, always_tuple=False): """Convert a typestruct item to a simplified form for ease of use.""" def expand(params): return (to_literal(x) for x in params) def union(params): ret = tuple(sorted(expand(params), key=str)) if len(ret) == 1 and not always_tuple: (ret,) = ret # pylint: disable=self-assigning-variable return ret tag, params = typ if tag == 'prim': return params elif tag == 'tuple': vals = tuple(expand(params)) return (tag, *vals) elif tag == 'map': k, v = params return (tag, union(k), union(v)) else: return (tag, union(params)) def from_literal(tup): """Convert from simple literal form to the more uniform typestruct.""" def expand(vals): return [from_literal(x) for x in vals] def union(vals): if not isinstance(vals, tuple): vals = (vals,) v = expand(vals) return frozenset(v) if not isinstance(tup, tuple): return ('prim', tup) elif isinstance(tup[0], str): tag, *vals = tup if tag == 'prim': return tup elif tag == 'tuple': params = tuple(expand(vals)) return (tag, params) elif tag == 'map': k, v = vals return (tag, (union(k), union(v))) else: (vals,) = vals # pylint: disable=self-assigning-variable return (tag, union(vals)) else: return tuple(expand(tup)) def fold_constants(code: blocks.OrderedCode): """Fold all constant literals in the bytecode into LOAD_FOLDED_CONST ops.""" return pyc.visit(code, _FoldConstants()) def build_folded_type(ctx, state, const): """Convert a typestruct to a vm type.""" def typeconst(t): """Create a constant purely to hold types for a recursive call.""" return _Constant(t, None, None, const.op) def build_pyval(state, const): if const.value is not None and const.tag in ('prim', 'tuple'): return state, ctx.convert.constant_to_var(const.value) else: return build_folded_type(ctx, state, const) def expand(state, elements): vs = [] for e in elements: state, v = build_pyval(state, e) vs.append(v) return state, vs def join_types(state, ts): xs = [typeconst(t) for t in ts] state, vs = expand(state, xs) val = ctx.convert.build_content(vs) return state, val def collect(state, convert_type, params): state, t = join_types(state, params) ret = ctx.convert.build_collection_of_type(state.node, convert_type, t) return state, ret def collect_tuple(state, elements): state, vs = expand(state, elements) return state, ctx.convert.build_tuple(state.node, vs) def collect_list(state, params, elements): if elements is None: return collect(state, ctx.convert.list_type, params) elif len(elements) < MAX_VAR_SIZE: state, vs = expand(state, elements) return state, ctx.convert.build_list(state.node, vs) else: # Without constant folding we construct a variable wrapping every element # in the list and store it; however, we cannot retrieve them all. So as an # optimisation, we will add the first few elements as pyals, then add one # element for every contained type, and rely on the fact that the tail # elements will contribute to the overall list type, but will not be # retrievable as pyvals. # TODO(b/175443170): We should use a smaller MAX_SUBSCRIPT cutoff; this # behaviour is unrelated to MAX_VAR_SIZE (which limits the number of # distinct bindings for the overall typevar). n = MAX_VAR_SIZE - len(params) - 1 elts = elements[:n] + tuple(typeconst(t) for t in params) state, vs = expand(state, elts) return state, ctx.convert.build_list(state.node, vs) def collect_map(state, params, elements): m_var = ctx.convert.build_map(state.node) m = m_var.data[0] # Do not forward the state while creating dict literals. node = state.node # We want a single string type to store in the Dict.K type param. # Calling set_str_item on every k/v pair will lead to a type param with a # lot of literal strings as bindings, causing potentially severe performance # issues down the line. str_key = ctx.convert.str_type.instantiate(node) if elements is not None and len(elements) < MAX_VAR_SIZE: for k, v in elements.items(): _, v = build_pyval(state, v) k_var = ctx.convert.constant_to_var(k) m.setitem(node, k_var, v) if isinstance(k, str): m.merge_instance_type_params(node, str_key, v) else: m.merge_instance_type_params(node, k_var, v) else: # Treat a too-large dictionary as {Union[keys] : Union[vals]}. We could # store a subset of the k/v pairs, as with collect_list, but for # dictionaries it is less obvious which subset we should be storing. # Perhaps we could create one variable per unique value type, and then # store every key in the pyval but reuse the value variables. k_types, v_types = params _, v = join_types(state, v_types) for t in k_types: _, k = build_folded_type(ctx, state, typeconst(t)) m.setitem(node, k, v) m.merge_instance_type_params(node, k, v) return state, m_var tag, params = const.typ if tag == 'prim': if const.value: return state, ctx.convert.constant_to_var(const.value) else: val = ctx.convert.primitive_instances[params] return state, val.to_variable(state.node) elif tag == 'list': return collect_list(state, params, const.elements) elif tag == 'set': return collect(state, ctx.convert.set_type, params) elif tag == 'tuple': # If we get a tuple without const.elements, construct it from the type. # (e.g. this happens with a large dict with tuple keys) if not const.elements: elts = tuple(typeconst(t) for t in params) else: elts = const.elements return collect_tuple(state, elts) elif tag == 'map': return collect_map(state, params, const.elements) else: assert False, ('Unexpected type tag:', const.typ)
_FoldConstants
python
django__django
tests/auth_tests/models/proxy.py
{ "start": 116, "end": 256 }
class ____(Concrete): class Meta: proxy = True permissions = (("display_proxys", "May display proxys information"),)
Proxy
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/urlfetch/snippets/main.py
{ "start": 2878, "end": 3291 }
class ____(webapp2.RequestHandler): """Handler that receives UrlPostHandler POST request.""" def post(self): self.response.out.write((self.request.get("first_name"))) app = webapp2.WSGIApplication( [ ("/", UrlLibFetchHandler), ("/url_fetch", UrlFetchHandler), ("/url_post", UrlPostHandler), ("/submit_form", SubmitHandler), ], debug=True, )
SubmitHandler
python
PyCQA__pylint
tests/pyreverse/functional/class_diagrams/attributes/_monkey.py
{ "start": 114, "end": 449 }
class ____: def __init__(self, name): # pylint: disable=import-outside-toplevel from delayed_external_monkey_patching import Tree self.name = name self.tree = Tree() self.tree.has_tasty_bananas = True # This monkey patching will increase the number of items in instance_attrs for `Tree`
Monkey
python
getsentry__sentry
src/sentry/preprod/api/models/project_preprod_build_details_models.py
{ "start": 348, "end": 435 }
class ____(StrEnum): IOS = "ios" ANDROID = "android" MACOS = "macos"
Platform
python
RaRe-Technologies__gensim
gensim/test/test_lda_callback.py
{ "start": 655, "end": 1700 }
class ____(unittest.TestCase): def setUp(self): self.corpus = MmCorpus(datapath('testcorpus.mm')) self.ch_umass = CoherenceMetric(corpus=self.corpus, coherence="u_mass", logger="visdom", title="Coherence") self.callback = [self.ch_umass] self.model = LdaModel(id2word=common_dictionary, num_topics=2, passes=10, callbacks=self.callback) self.host = "http://localhost" self.port = 8097 def test_callback_update_graph(self): with subprocess.Popen(['python', '-m', 'visdom.server', '-port', str(self.port)]) as proc: # wait for visdom server startup (any better way?) viz = Visdom(server=self.host, port=self.port) for attempt in range(5): time.sleep(1.0) # seconds if viz.check_connection(): break assert viz.check_connection() viz.close() self.model.update(self.corpus) proc.kill() if __name__ == '__main__': unittest.main()
TestLdaCallback
python
xlwings__xlwings
xlwings/main.py
{ "start": 132022, "end": 134571 }
class ____: """ A collection of all :meth:`name <Name>` objects in the workbook: >>> import xlwings as xw >>> book = xw.books['Book1'] # book scope and sheet scope >>> book.names [<Name 'MyName': =Sheet1!$A$3>] >>> book.sheets[0].names # sheet scope only .. versionadded:: 0.9.0 """ def __init__(self, impl): self.impl = impl @property def api(self): """ Returns the native object (``pywin32`` or ``appscript`` obj) of the engine beingused. .. versionadded:: 0.9.0 """ return self.impl.api def __call__(self, name_or_index): return Name(impl=self.impl(name_or_index)) def contains(self, name_or_index): return self.impl.contains(name_or_index) def __len__(self): return len(self.impl) @property def count(self): """ Returns the number of objects in the collection. """ return len(self) def add(self, name, refers_to): """ Defines a new name for a range of cells. Parameters ---------- name : str Specifies the text to use as the name. Names cannot include spaces and cannot be formatted as cell references. refers_to : str Describes what the name refers to, in English, using A1-style notation. Returns ------- Name .. versionadded:: 0.9.0 """ return Name(impl=self.impl.add(name, refers_to)) def __getitem__(self, item): if isinstance(item, numbers.Number): return self(item + 1) else: return self(item) def __setitem__(self, key, value): if isinstance(value, Range): value.name = key elif key in self: self[key].refers_to = value else: self.add(key, value) def __contains__(self, item): if isinstance(item, numbers.Number): return 0 <= item < len(self) else: return self.contains(item) def __delitem__(self, key): if key in self: self[key].delete() else: raise KeyError(key) def __iter__(self): for i in range(len(self)): yield self(i + 1) def __repr__(self): r = [] for i, n in enumerate(self): if i == 3: r.append("...") break else: r.append(repr(n)) return "[" + ", ".join(r) + "]"
Names
python
getsentry__sentry
src/sentry/integrations/vercel/integration.py
{ "start": 2603, "end": 3907 }
class ____(IntegrationMetadata): def asdict(self): metadata = super().asdict() # We have to calculate this here since fetching options at the module level causes us to skip the cache. metadata["aspects"]["externalInstall"] = { "url": f"https://vercel.com/integrations/{options.get('vercel.integration-slug')}/add", "buttonText": _("Vercel Marketplace"), "noticeText": INSTALL_NOTICE_TEXT, } return metadata metadata = VercelIntegrationMetadata( description=DESCRIPTION.strip(), features=FEATURES, author="The Sentry Team", noun=_("Installation"), issue_url="https://github.com/getsentry/sentry/issues/new?assignees=&labels=Component:%20Integrations&template=bug.yml&title=Vercel%20Integration%20Problem", source_url="https://github.com/getsentry/sentry/tree/master/src/sentry/integrations/vercel", aspects={ "configure_integration": configure_integration, }, ) internal_integration_overview = ( "This internal integration was auto-generated during the installation process of your Vercel" " integration. It is needed to provide the token used to create a release. If this integration is " "deleted, your Vercel integration will stop working!" )
VercelIntegrationMetadata
python
scipy__scipy
scipy/signal/tests/test_waveforms.py
{ "start": 13285, "end": 13554 }
class ____: def test_dtype(self): waveform = waveforms.square(np.array(1, dtype=np.float32), duty=np.float32(0.5)) assert waveform.dtype == np.float64 waveform = waveforms.square(1) assert waveform.dtype == np.float64
TestSquareWaveform
python
doocs__leetcode
solution/1300-1399/1358.Number of Substrings Containing All Three Characters/Solution.py
{ "start": 0, "end": 246 }
class ____: def numberOfSubstrings(self, s: str) -> int: d = {"a": -1, "b": -1, "c": -1} ans = 0 for i, c in enumerate(s): d[c] = i ans += min(d["a"], d["b"], d["c"]) + 1 return ans
Solution
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-bilibili/llama_index/readers/bilibili/base.py
{ "start": 225, "end": 2374 }
class ____(BaseReader): """Bilibili Transcript and video info reader.""" @staticmethod def get_bilibili_info_and_subs(bili_url): import json import re import requests from bilibili_api import sync, video bvid = re.search(r"BV\w+", bili_url).group() # Create credential object v = video.Video(bvid=bvid) # Get video info and basic info video_info = sync(v.get_info()) title = video_info["title"] desc = video_info["desc"] # Get subtitle url sub_list = video_info["subtitle"]["list"] if sub_list: sub_url = sub_list[0]["subtitle_url"] result = requests.get(sub_url) raw_sub_titles = json.loads(result.content)["body"] raw_transcript = " ".join([c["content"] for c in raw_sub_titles]) # Add basic video info to transcript return ( f"Video Title: {title}, description: {desc}\nTranscript:" f" {raw_transcript}" ) else: raw_transcript = "" warnings.warn( f"No subtitles found for video: {bili_url}. Return Empty transcript." ) return raw_transcript def load_data(self, video_urls: List[str], **load_kwargs: Any) -> List[Document]: """ Load auto generated Video Transcripts from Bilibili, including additional metadata. Args: video_urls (List[str]): List of Bilibili links for which transcripts are to be read. Returns: List[Document]: A list of Document objects, each containing the transcript for a Bilibili video. """ results = [] for bili_url in video_urls: try: transcript = self.get_bilibili_info_and_subs(bili_url) results.append(Document(text=transcript)) except Exception as e: warnings.warn( f"Error loading transcript for video {bili_url}: {e!s}. Skipping" " video." ) return results
BilibiliTranscriptReader
python
cython__cython
Cython/Compiler/Dataclass.py
{ "start": 5643, "end": 29773 }
class ____: """ Field is based on the dataclasses.field class from the standard library module. It is used internally during the generation of Cython dataclasses to keep track of the settings for individual attributes. Attributes of this class are stored as nodes so they can be used in code construction more readily (i.e. we store BoolNode rather than bool) """ default = MISSING default_factory = MISSING private = False literal_keys = ("repr", "hash", "init", "compare", "metadata") # default values are defined by the CPython dataclasses.field def __init__(self, pos, default=MISSING, default_factory=MISSING, repr=None, hash=None, init=None, compare=None, metadata=None, is_initvar=False, is_classvar=False, **additional_kwds): if default is not MISSING: self.default = default if default_factory is not MISSING: self.default_factory = default_factory self.repr = repr or ExprNodes.BoolNode(pos, value=True) self.hash = hash or ExprNodes.NoneNode(pos) self.init = init or ExprNodes.BoolNode(pos, value=True) self.compare = compare or ExprNodes.BoolNode(pos, value=True) self.metadata = metadata or ExprNodes.NoneNode(pos) self.is_initvar = is_initvar self.is_classvar = is_classvar for k, v in additional_kwds.items(): # There should not be any additional keywords! error(v.pos, "cython.dataclasses.field() got an unexpected keyword argument '%s'" % k) for field_name in self.literal_keys: field_value = getattr(self, field_name) if not field_value.is_literal: error(field_value.pos, "cython.dataclasses.field parameter '%s' must be a literal value" % field_name) def iterate_record_node_arguments(self): for key in (self.literal_keys + ('default', 'default_factory')): value = getattr(self, key) if value is not MISSING: yield key, value def process_class_get_fields(node): var_entries = node.scope.var_entries # order of definition is used in the dataclass var_entries = sorted(var_entries, key=operator.attrgetter('pos')) var_names = [entry.name for entry in var_entries] # don't treat `x = 1` as an assignment of a class attribute within the dataclass transform = RemoveAssignmentsToNames(var_names) transform(node) default_value_assignments = transform.removed_assignments base_type = node.base_type fields = OrderedDict() while base_type: if base_type.is_external or not base_type.scope.implemented: warning(node.pos, "Cannot reliably handle Cython dataclasses with base types " "in external modules since it is not possible to tell what fields they have", 2) if base_type.dataclass_fields: fields = base_type.dataclass_fields.copy() break base_type = base_type.base_type for entry in var_entries: name = entry.name is_initvar = entry.declared_with_pytyping_modifier("dataclasses.InitVar") # TODO - classvars aren't included in "var_entries" so are missed here # and thus this code is never triggered is_classvar = entry.declared_with_pytyping_modifier("typing.ClassVar") if name in default_value_assignments: assignment = default_value_assignments[name] if (isinstance(assignment, ExprNodes.CallNode) and ( assignment.function.as_cython_attribute() == "dataclasses.field" or Builtin.exprnode_to_known_standard_library_name( assignment.function, node.scope) == "dataclasses.field")): # I believe most of this is well-enforced when it's treated as a directive # but it doesn't hurt to make sure valid_general_call = (isinstance(assignment, ExprNodes.GeneralCallNode) and isinstance(assignment.positional_args, ExprNodes.TupleNode) and not assignment.positional_args.args and (assignment.keyword_args is None or isinstance(assignment.keyword_args, ExprNodes.DictNode))) valid_simple_call = (isinstance(assignment, ExprNodes.SimpleCallNode) and not assignment.args) if not (valid_general_call or valid_simple_call): error(assignment.pos, "Call to 'cython.dataclasses.field' must only consist " "of compile-time keyword arguments") continue keyword_args = assignment.keyword_args.as_python_dict() if valid_general_call and assignment.keyword_args else {} if 'default' in keyword_args and 'default_factory' in keyword_args: error(assignment.pos, "cannot specify both default and default_factory") continue field = Field(node.pos, **keyword_args) else: if assignment.type in [Builtin.list_type, Builtin.dict_type, Builtin.set_type]: # The standard library module generates a TypeError at runtime # in this situation. # Error message is copied from CPython error(assignment.pos, "mutable default <class '{}'> for field {} is not allowed: " "use default_factory".format(assignment.type.name, name)) field = Field(node.pos, default=assignment) else: field = Field(node.pos) field.is_initvar = is_initvar field.is_classvar = is_classvar if entry.visibility == "private": field.private = True fields[name] = field node.entry.type.dataclass_fields = fields return fields def handle_cclass_dataclass(node, dataclass_args, analyse_decs_transform): # default argument values from https://docs.python.org/3/library/dataclasses.html kwargs = dict(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, kw_only=False, match_args=True) if dataclass_args is not None: if dataclass_args[0]: error(node.pos, "cython.dataclasses.dataclass takes no positional arguments") for k, v in dataclass_args[1].items(): if k in kwargs and isinstance(v, ExprNodes.BoolNode): kwargs[k] = v.value continue if k not in kwargs: error(node.pos, "cython.dataclasses.dataclass() got an unexpected keyword argument '%s'" % k) if not isinstance(v, ExprNodes.BoolNode): error(node.pos, "Arguments passed to cython.dataclasses.dataclass must be True or False") kw_only = kwargs['kw_only'] fields = process_class_get_fields(node) dataclass_module = make_dataclasses_module_callnode(node.pos) # create __dataclass_params__ attribute. I try to use the exact # `_DataclassParams` class defined in the standard library module if at all possible # for maximum duck-typing compatibility. dataclass_params_func = ExprNodes.AttributeNode(node.pos, obj=dataclass_module, attribute=EncodedString("_DataclassParams")) dataclass_params_keywords = ExprNodes.DictNode.from_pairs( node.pos, [ (ExprNodes.IdentifierStringNode(node.pos, value=EncodedString(k)), ExprNodes.BoolNode(node.pos, value=v, type=Builtin.bool_type)) for k, v in kwargs.items() ] + [ (ExprNodes.IdentifierStringNode(node.pos, value=EncodedString(k)), ExprNodes.BoolNode(node.pos, value=v, type=Builtin.bool_type)) for k, v in [('kw_only', kw_only), ('slots', False), ('weakref_slot', False)] ]) dataclass_params = make_dataclass_call_helper( node.pos, dataclass_params_func, dataclass_params_keywords) dataclass_params_assignment = Nodes.SingleAssignmentNode( node.pos, lhs = ExprNodes.NameNode(node.pos, name=EncodedString("__dataclass_params__")), rhs = dataclass_params) dataclass_fields_stats = _set_up_dataclass_fields(node, fields, dataclass_module) stats = Nodes.StatListNode(node.pos, stats=[dataclass_params_assignment] + dataclass_fields_stats) code = TemplateCode() generate_init_code(code, kwargs['init'], node, fields, kw_only) generate_match_args(code, kwargs['match_args'], node, fields, kw_only) generate_repr_code(code, kwargs['repr'], node, fields) generate_eq_code(code, kwargs['eq'], node, fields) generate_order_code(code, kwargs['order'], node, fields) generate_hash_code(code, kwargs['unsafe_hash'], kwargs['eq'], kwargs['frozen'], node, fields) stats.stats += code.generate_tree().stats # turn off annotation typing, so all arguments to __init__ are accepted as # generic objects and thus can accept _HAS_DEFAULT_FACTORY. # Type conversion comes later comp_directives = Nodes.CompilerDirectivesNode(node.pos, directives=copy_inherited_directives(node.scope.directives, annotation_typing=False), body=stats) comp_directives.analyse_declarations(node.scope) # probably already in this scope, but it doesn't hurt to make sure analyse_decs_transform.enter_scope(node, node.scope) analyse_decs_transform.visit(comp_directives) analyse_decs_transform.exit_scope() node.body.stats.append(comp_directives) def generate_init_code(code, init, node, fields, kw_only): """ Notes on CPython generated "__init__": * Implemented in `_init_fn`. * The use of the `dataclasses._HAS_DEFAULT_FACTORY` sentinel value as the default argument for fields that need constructing with a factory function is copied from the CPython implementation. (`None` isn't suitable because it could also be a value for the user to pass.) There's no real reason why it needs importing from the dataclasses module though - it could equally be a value generated by Cython when the module loads. * seen_default and the associated error message are copied directly from Python * Call to user-defined __post_init__ function (if it exists) is copied from CPython. Cython behaviour deviates a little here (to be decided if this is right...) Because the class variable from the assignment does not exist Cython fields will return None (or whatever their type default is) if not initialized while Python dataclasses will fall back to looking up the class variable. """ if not init or node.scope.lookup_here("__init__"): return # selfname behaviour copied from the cpython module selfname = "__dataclass_self__" if "self" in fields else "self" args = [selfname] if kw_only: args.append("*") function_start_point = code.insertion_point() code = code.insertion_point() code.indent() # create a temp to get _HAS_DEFAULT_FACTORY dataclass_module = make_dataclasses_module_callnode(node.pos) has_default_factory = ExprNodes.AttributeNode( node.pos, obj=dataclass_module, attribute=EncodedString("_HAS_DEFAULT_FACTORY") ) default_factory_placeholder = code.new_placeholder(fields, has_default_factory) seen_default = False for name, field in fields.items(): entry = node.scope.lookup(name) if entry.annotation: annotation = f": {entry.annotation.string.value}" else: annotation = "" assignment = '' if field.default is not MISSING or field.default_factory is not MISSING: if field.init.value: seen_default = True if field.default_factory is not MISSING: ph_name = default_factory_placeholder else: ph_name = code.new_placeholder(fields, field.default) # 'default' should be a node assignment = f" = {ph_name}" elif seen_default and not kw_only and field.init.value: error(entry.pos, ("non-default argument '%s' follows default argument " "in dataclass __init__") % name) code.reset() return if field.init.value: args.append(f"{name}{annotation}{assignment}") if field.is_initvar: continue elif field.default_factory is MISSING: if field.init.value: code.add_code_line(f"{selfname}.{name} = {name}") elif assignment: # not an argument to the function, but is still initialized code.add_code_line(f"{selfname}.{name}{assignment}") else: ph_name = code.new_placeholder(fields, field.default_factory) if field.init.value: # close to: # def __init__(self, name=_PLACEHOLDER_VALUE): # self.name = name_default_factory() if name is _PLACEHOLDER_VALUE else name code.add_code_line( f"{selfname}.{name} = {ph_name}() if {name} is {default_factory_placeholder} else {name}" ) else: # still need to use the default factory to initialize code.add_code_line(f"{selfname}.{name} = {ph_name}()") if node.scope.lookup("__post_init__"): post_init_vars = ", ".join(name for name, field in fields.items() if field.is_initvar) code.add_code_line(f"{selfname}.__post_init__({post_init_vars})") if code.empty(): code.add_code_line("pass") args = ", ".join(args) function_start_point.add_code_line(f"def __init__({args}):") def generate_match_args(code, match_args, node, fields, global_kw_only): """ Generates a tuple containing what would be the positional args to __init__ Note that this is generated even if the user overrides init """ if not match_args or node.scope.lookup_here("__match_args__"): return positional_arg_names = [] for field_name, field in fields.items(): # TODO hasattr and global_kw_only can be removed once full kw_only support is added field_is_kw_only = global_kw_only or ( hasattr(field, 'kw_only') and field.kw_only.value ) if not field_is_kw_only: positional_arg_names.append(field_name) code.add_code_line("__match_args__ = %s" % str(tuple(positional_arg_names))) def generate_repr_code(code, repr, node, fields): """ The core of the CPython implementation is just: ['return self.__class__.__qualname__ + f"(' + ', '.join([f"{f.name}={{self.{f.name}!r}}" for f in fields]) + ')"'], The only notable difference here is self.__class__.__qualname__ -> type(self).__name__ which is because Cython currently supports Python 2. However, it also has some guards for recursive repr invocations. In the standard library implementation they're done with a wrapper decorator that captures a set (with the set keyed by id and thread). Here we create a set as a thread local variable and key only by id. """ if not repr or node.scope.lookup("__repr__"): return # The recursive guard is likely a little costly, so skip it if possible. # is_gc_simple defines where it can contain recursive objects needs_recursive_guard = False for name in fields.keys(): entry = node.scope.lookup(name) type_ = entry.type if type_.is_memoryviewslice: type_ = type_.dtype if not type_.is_pyobject: continue # no GC if not type_.is_gc_simple: needs_recursive_guard = True break if needs_recursive_guard: code.add_code_chunk(""" __pyx_recursive_repr_guard = __import__('threading').local() __pyx_recursive_repr_guard.running = set() """) with code.indenter("def __repr__(self):"): if needs_recursive_guard: code.add_code_chunk(""" key = id(self) guard_set = self.__pyx_recursive_repr_guard.running if key in guard_set: return '...' guard_set.add(key) try: """) code.indent() strs = ["%s={self.%s!r}" % (name, name) for name, field in fields.items() if field.repr.value and not field.is_initvar] format_string = ", ".join(strs) code.add_code_chunk(f''' name = getattr(type(self), "__qualname__", None) or type(self).__name__ return f'{{name}}({format_string})' ''') if needs_recursive_guard: code.dedent() with code.indenter("finally:"): code.add_code_line("guard_set.remove(key)") def generate_cmp_code(code, op, funcname, node, fields): if node.scope.lookup_here(funcname): return names = [name for name, field in fields.items() if (field.compare.value and not field.is_initvar)] with code.indenter(f"def {funcname}(self, other):"): code.add_code_chunk(f""" if other.__class__ is not self.__class__: return NotImplemented cdef {node.class_name} other_cast other_cast = <{node.class_name}>other """) # The Python implementation of dataclasses.py does a tuple comparison # (roughly): # return self._attributes_to_tuple() {op} other._attributes_to_tuple() # # For the Cython implementation a tuple comparison isn't an option because # not all attributes can be converted to Python objects and stored in a tuple # # TODO - better diagnostics of whether the types support comparison before # generating the code. Plus, do we want to convert C structs to dicts and # compare them that way (I think not, but it might be in demand)? checks = [] op_without_equals = op.replace('=', '') for name in names: if op != '==': # tuple comparison rules - early elements take precedence code.add_code_line(f"if self.{name} {op_without_equals} other_cast.{name}: return True") code.add_code_line(f"if self.{name} != other_cast.{name}: return False") code.add_code_line(f"return {'True' if '=' in op else 'False'}") # "() == ()" is True def generate_eq_code(code, eq, node, fields): if not eq: return generate_cmp_code(code, "==", "__eq__", node, fields) def generate_order_code(code, order, node, fields): if not order: return for op, name in [("<", "__lt__"), ("<=", "__le__"), (">", "__gt__"), (">=", "__ge__")]: generate_cmp_code(code, op, name, node, fields) def generate_hash_code(code, unsafe_hash, eq, frozen, node, fields): """ Copied from CPython implementation - the intention is to follow this as far as is possible: # +------------------- unsafe_hash= parameter # | +----------- eq= parameter # | | +--- frozen= parameter # | | | # v v v | | | # | no | yes | <--- class has explicitly defined __hash__ # +=======+=======+=======+========+========+ # | False | False | False | | | No __eq__, use the base class __hash__ # +-------+-------+-------+--------+--------+ # | False | False | True | | | No __eq__, use the base class __hash__ # +-------+-------+-------+--------+--------+ # | False | True | False | None | | <-- the default, not hashable # +-------+-------+-------+--------+--------+ # | False | True | True | add | | Frozen, so hashable, allows override # +-------+-------+-------+--------+--------+ # | True | False | False | add | raise | Has no __eq__, but hashable # +-------+-------+-------+--------+--------+ # | True | False | True | add | raise | Has no __eq__, but hashable # +-------+-------+-------+--------+--------+ # | True | True | False | add | raise | Not frozen, but hashable # +-------+-------+-------+--------+--------+ # | True | True | True | add | raise | Frozen, so hashable # +=======+=======+=======+========+========+ # For boxes that are blank, __hash__ is untouched and therefore # inherited from the base class. If the base is object, then # id-based hashing is used. The Python implementation creates a tuple of all the fields, then hashes them. This implementation creates a tuple of all the hashes of all the fields and hashes that. The reason for this slight difference is to avoid to-Python conversions for anything that Cython knows how to hash directly (It doesn't look like this currently applies to anything though...). """ hash_entry = node.scope.lookup_here("__hash__") if hash_entry: # TODO ideally assignment of __hash__ to None shouldn't trigger this # but difficult to get the right information here if unsafe_hash: # error message taken from CPython dataclasses module error(node.pos, "Cannot overwrite attribute __hash__ in class %s" % node.class_name) return if not unsafe_hash: if not eq: return if not frozen: code.add_extra_statements([ Nodes.SingleAssignmentNode( node.pos, lhs=ExprNodes.NameNode(node.pos, name=EncodedString("__hash__")), rhs=ExprNodes.NoneNode(node.pos), ) ]) return names = [ name for name, field in fields.items() if not field.is_initvar and ( field.compare.value if field.hash.value is None else field.hash.value) ] # make a tuple of the hashes hash_tuple_items = ", ".join("self.%s" % name for name in names) if hash_tuple_items: hash_tuple_items += "," # ensure that one arg form is a tuple # if we're here we want to generate a hash with code.indenter("def __hash__(self):"): code.add_code_line(f"return hash(({hash_tuple_items}))") def get_field_type(pos, entry): """ sets the .type attribute for a field Returns the annotation if possible (since this is what the dataclasses module does). If not (for example, attributes defined with cdef) then it creates a string fallback. """ if entry.annotation: # Right now it doesn't look like cdef classes generate an # __annotations__ dict, therefore it's safe to just return # entry.annotation # (TODO: remove .string if we ditch PEP563) return entry.annotation.string # If they do in future then we may need to look up into that # to duplicating the node. The code below should do this: #class_name_node = ExprNodes.NameNode(pos, name=entry.scope.name) #annotations = ExprNodes.AttributeNode( # pos, obj=class_name_node, # attribute=EncodedString("__annotations__") #) #return ExprNodes.IndexNode( # pos, base=annotations, # index=ExprNodes.UnicodeNode(pos, value=entry.name) #) else: # it's slightly unclear what the best option is here - we could # try to return PyType_Type. This case should only happen with # attributes defined with cdef so Cython is free to make it's own # decision s = EncodedString(entry.type.declaration_code("", for_display=1)) return ExprNodes.UnicodeNode(pos, value=s)
Field
python
dask__dask
dask/array/ufunc.py
{ "start": 886, "end": 2120 }
class ____: """A serializable `frompyfunc` object""" def __init__(self, func, nin, nout): self._ufunc = np.frompyfunc(func, nin, nout) self._func = func self.nin = nin self.nout = nout self._name = funcname(func) self.__name__ = f"frompyfunc-{self._name}" def __repr__(self): return f"da.frompyfunc<{self._name}, {self.nin}, {self.nout}>" def __dask_tokenize__(self): return (normalize_token(self._func), self.nin, self.nout) def __reduce__(self): return (da_frompyfunc, (self._func, self.nin, self.nout)) def __call__(self, *args, **kwargs): return self._ufunc(*args, **kwargs) def __getattr__(self, a): if not a.startswith("_"): return getattr(self._ufunc, a) raise AttributeError(f"{type(self).__name__!r} object has no attribute {a!r}") def __dir__(self): o = set(dir(type(self))) o.update(self.__dict__) o.update(dir(self._ufunc)) return list(o) @derived_from(np) def frompyfunc(func, nin, nout): if nout > 1: raise NotImplementedError("frompyfunc with more than one output") return ufunc(da_frompyfunc(func, nin, nout))
da_frompyfunc
python
sphinx-doc__sphinx
doc/development/tutorials/examples/recipe.py
{ "start": 365, "end": 1046 }
class ____(ObjectDescription): """A custom directive that describes a recipe.""" has_content = True required_arguments = 1 option_spec = { 'contains': directives.unchanged_required, } def handle_signature(self, sig, signode): signode += addnodes.desc_name(text=sig) return sig def add_target_and_index(self, name_cls, sig, signode): signode['ids'].append('recipe' + '-' + sig) if 'contains' in self.options: ingredients = [x.strip() for x in self.options.get('contains').split(',')] recipes = self.env.get_domain('recipe') recipes.add_recipe(sig, ingredients)
RecipeDirective
python
tiangolo__fastapi
fastapi/params.py
{ "start": 17130, "end": 21478 }
class ____(FieldInfo): # type: ignore[misc] def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, embed: Union[bool, None] = None, media_type: str = "application/json", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, # TODO: update when deprecating Pydantic v1, import these types # validation_alias: str | AliasPath | AliasChoices | None validation_alias: Union[str, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[List[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): self.embed = embed self.media_type = media_type if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", category=DeprecationWarning, stacklevel=4, ) self.example = example self.include_in_schema = include_in_schema self.openapi_examples = openapi_examples kwargs = dict( default=default, default_factory=default_factory, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, ) if examples is not None: kwargs["examples"] = examples if regex is not None: warnings.warn( "`regex` has been deprecated, please use `pattern` instead", category=DeprecationWarning, stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7): self.deprecated = deprecated else: kwargs["deprecated"] = deprecated if PYDANTIC_V2: kwargs.update( { "annotation": annotation, "alias_priority": alias_priority, "validation_alias": validation_alias, "serialization_alias": serialization_alias, "strict": strict, "json_schema_extra": current_json_schema_extra, } ) kwargs["pattern"] = pattern or regex else: kwargs["regex"] = pattern or regex kwargs.update(**current_json_schema_extra) use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} super().__init__(**use_kwargs) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.default})"
Body
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/managed_kafka.py
{ "start": 48929, "end": 51527 }
class ____(ManagedKafkaBaseOperator): """ Delete a single consumer group. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param location: Required. The ID of the Google Cloud region that the service belongs to. :param cluster_id: Required. The ID of the cluster whose consumer group is to be deleted. :param consumer_group_id: Required. The ID of the consumer group to delete. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = tuple( {"cluster_id", "consumer_group_id"} | set(ManagedKafkaBaseOperator.template_fields) ) def __init__( self, cluster_id: str, consumer_group_id: str, *args, **kwargs, ) -> None: super().__init__(*args, **kwargs) self.cluster_id = cluster_id self.consumer_group_id = consumer_group_id def execute(self, context: Context): try: self.log.info("Deleting Apache Kafka consumer group: %s", self.consumer_group_id) self.hook.delete_consumer_group( project_id=self.project_id, location=self.location, cluster_id=self.cluster_id, consumer_group_id=self.consumer_group_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) self.log.info("Apache Kafka consumer group was deleted.") except NotFound as not_found_err: self.log.info("The Apache Kafka consumer group ID %s does not exist.", self.consumer_group_id) raise AirflowException(not_found_err)
ManagedKafkaDeleteConsumerGroupOperator
python
Lightning-AI__lightning
src/lightning/pytorch/loops/optimization/manual.py
{ "start": 1292, "end": 2502 }
class ____(OutputResult): """A container to hold the result returned by ``_ManualOptimization``. It is created from the output of :meth:`~lightning.pytorch.core.LightningModule.training_step`. Attributes: extra: Anything returned by the ``training_step``. """ extra: dict[str, Any] = field(default_factory=dict) @classmethod def from_training_step_output(cls, training_step_output: STEP_OUTPUT) -> "ManualResult": extra = {} if isinstance(training_step_output, Mapping): extra = training_step_output.copy() elif isinstance(training_step_output, Tensor): extra = {"loss": training_step_output} elif training_step_output is not None: raise MisconfigurationException( "In manual optimization, `training_step` must either return a Tensor or have no return." ) if "loss" in extra: # we detach manually as it's expected that it will have a `grad_fn` extra["loss"] = extra["loss"].detach() return cls(extra=extra) @override def asdict(self) -> dict[str, Any]: return self.extra _OUTPUTS_TYPE = dict[str, Any]
ManualResult
python
tensorflow__tensorflow
tensorflow/lite/python/lite_v2_test.py
{ "start": 3085, "end": 62052 }
class ____(lite_v2_test_util.ModelTest): @test_util.run_v2_only def testTypeInvalid(self): root = self._getSimpleVariableModel() with self.assertRaises(ValueError) as error: _ = lite.TFLiteConverterV2.from_concrete_functions([root.f], root) self.assertIn('call get_concrete_function', str(error.exception)) @test_util.run_v2_only def testFloat(self): root = self._getSimpleVariableModel() input_data = tf.constant(1.0, shape=[1]) concrete_func = root.f.get_concrete_function(input_data) # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) tflite_model = converter.convert() # Check output value from converted model. expected_value = root.f(input_data) actual_value = self._evaluateTFLiteModel(tflite_model, [input_data]) self.assertEqual(expected_value.numpy(), actual_value) @parameterized.named_parameters( ('_INT8InputOutput', dtypes.int8), ('_UINT8InputOutput', dtypes.uint8), ('_INT16InputOutput', dtypes.int16), ) @test_util.run_v2_only def testInvalidFloat(self, inference_input_output_type): root = self._getSimpleVariableModel() input_data = tf.constant(1.0, shape=[1]) concrete_func = root.f.get_concrete_function(input_data) # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) with self.assertRaises(ValueError) as error: converter.inference_input_type = inference_input_output_type converter.inference_output_type = inference_input_output_type converter.convert() self.assertEqual( 'The inference_input_type and inference_output_type ' 'must be tf.float32.', str(error.exception), ) @test_util.run_v2_only def testScalarInput(self): root = self._getSimpleVariableModel() input_data = tf.constant(1.0, shape=[]) concrete_func = root.f.get_concrete_function(input_data) # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) tflite_model = converter.convert() # Check values from converted model. expected_value = root.f(input_data) actual_value = self._evaluateTFLiteModel(tflite_model, [input_data]) self.assertEqual(expected_value.numpy(), actual_value) @test_util.run_v2_only def testStringInput(self): class Model(tf.Module): @tf.function def __call__(self, x): return x root = Model() concrete_func = root.__call__.get_concrete_function( tf.constant([str(x) for x in range(11)]) ) # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) tflite_model = converter.convert() input_data = tf.constant( [str(x) for x in range(11)], shape=(11,), dtype=tf.dtypes.string ) # Check values from converted model. interp = interpreter.Interpreter(model_content=tflite_model) interp.allocate_tensors() my_signature = interp.get_signature_runner() with self.assertRaises(ValueError) as error: _ = my_signature(x=input_data) self.assertIn( 'Passed in value type is not a numpy array, got type ', str(error.exception), ) @test_util.run_v2_only def testModelWithoutInputs(self): def _get_random_number_gen(): root = autotrackable.AutoTrackable() @tf.function(input_signature=[]) def func(): return tf.random.uniform(shape=[1], dtype=tf.float32) root.f = func to_save = root.f.get_concrete_function() return (root, to_save) # Model with no input root, concrete_func = _get_random_number_gen() # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) @test_util.run_v2_only def testMultiFunctionModel(self): """Convert a single model in a multi-functional model.""" root = self._getMultiFunctionModel() input_data = tf.constant(1.0, shape=[1]) concrete_func = root.add.get_concrete_function(input_data) # Convert model and ensure model is not None. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) tflite_model = converter.convert() # Check values from converted model. expected_value = root.add(input_data) actual_value = self._evaluateTFLiteModel(tflite_model, [input_data]) self.assertEqual(expected_value.numpy(), actual_value) @test_util.run_v2_only def testConvertMultipleFunctions(self): """Convert multiple functions in a multi-functional model.""" root = self._getMultiFunctionModel() input_data = tf.constant(1.0, shape=[1]) add_func = root.add.get_concrete_function(input_data) sub_func = root.sub.get_concrete_function(input_data) # Try converting multiple functions. converter = lite.TFLiteConverterV2.from_concrete_functions( [add_func, sub_func], root ) tflite_model = converter.convert() # Check signatures are valid from converted model. interp = interpreter.Interpreter(model_content=tflite_model) signature_defs = interp.get_signature_list() # Verify the SignatureDef structure returned is as expected. self.assertLen(signature_defs, 2) self.assertEqual(list(signature_defs.keys()), ['add', 'sub']) self.assertLen(signature_defs.values(), 2) self.assertEqual(list(signature_defs['add'].keys()), ['inputs', 'outputs']) self.assertCountEqual(signature_defs['add']['inputs'], ['x']) self.assertEqual(list(signature_defs['add']['outputs']), ['output_0']) self.assertEqual(list(signature_defs['sub'].keys()), ['inputs', 'outputs']) self.assertCountEqual(signature_defs['sub']['inputs'], ['x']) self.assertEqual(list(signature_defs['sub']['outputs']), ['output_0']) # Verify the Signature runner executions. add_signature_runner = interp.get_signature_runner('add') add_output = add_signature_runner(x=input_data) self.assertEqual(add_output['output_0'], 3) input_details = add_signature_runner.get_input_details() self.assertLen(input_details, 1) self.assertEqual('add_x:0', input_details['x']['name']) self.assertEqual(np.float32, input_details['x']['dtype']) self.assertTrue(([1] == input_details['x']['shape']).all()) self.assertEqual((0.0, 0), input_details['x']['quantization']) sub_signature_runner = interp.get_signature_runner('sub') sub_output = sub_signature_runner(x=input_data) self.assertEqual(sub_output['output_0'], -2) output_details = sub_signature_runner.get_output_details() self.assertLen(output_details, 1) self.assertEqual( 'StatefulPartitionedCall_1:0', output_details['output_0']['name'] ) self.assertEqual(np.float32, output_details['output_0']['dtype']) self.assertTrue(([1] == output_details['output_0']['shape']).all()) self.assertEqual((0.0, 0), output_details['output_0']['quantization']) # Check the conversion metadata. metadata = util.get_conversion_metadata(tflite_model) self.assertIsNotNone(metadata) self.assertEqual(metadata.environment.apiVersion, 2) self.assertEqual( metadata.environment.modelType, metadata_fb.ModelType.TF_CONCRETE_FUNCTIONS, ) self.assertAllEqual([], metadata.options.modelOptimizationModes) def _getIntegerQuantizeModel(self, num_filters=16): np.random.seed(0) root = autotrackable.AutoTrackable() @tf.function( input_signature=[tf.TensorSpec(shape=[1, 5, 5, 3], dtype=tf.float32)] ) def func(inp): conv = tf.nn.conv2d( inp, tf.ones([3, 3, 3, num_filters]), strides=[1, 1, 1, 1], padding='SAME', ) output = tf.nn.relu(conv, name='output') return output def calibration_gen(): for _ in range(5): yield [np.random.uniform(-1, 1, size=(1, 5, 5, 3)).astype(np.float32)] root.f = func to_save = root.f.get_concrete_function() return (root, to_save, calibration_gen) @parameterized.named_parameters( ('EnableMlirQuantizer', True), # enable mlir quantizer ('DisableMlirQuantizer', False), ) # disable mlir quantizer def testPostTrainingCalibrateAndQuantize(self, mlir_quantizer): root, func, calibration_gen = self._getIntegerQuantizeModel() # Convert float model. float_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) float_tflite_model = float_converter.convert() self.assertIsNotNone(float_tflite_model) # Convert quantized model. quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.representative_dataset = calibration_gen quantized_converter.experimental_new_quantizer = mlir_quantizer quantized_tflite_model = quantized_converter.convert() self.assertIsNotNone(quantized_tflite_model) # Check the conversion metadata. metadata = util.get_conversion_metadata(quantized_tflite_model) self.assertIsNotNone(metadata) self.assertEqual( metadata.environment.tensorflowVersion.decode('utf-8'), versions.__version__, ) self.assertEqual(metadata.environment.apiVersion, 2) self.assertEqual( metadata.environment.modelType, metadata_fb.ModelType.TF_CONCRETE_FUNCTIONS, ) self.assertEqual(metadata.options.allowCustomOps, False) self.assertEqual(metadata.options.enableSelectTfOps, False) self.assertEqual(metadata.options.forceSelectTfOps, False) self.assertAllEqual( [metadata_fb.ModelOptimizationMode.PTQ_FULL_INTEGER], metadata.options.modelOptimizationModes, ) # The default input and output types should be float. interp = interpreter.Interpreter(model_content=quantized_tflite_model) interp.allocate_tensors() input_details = interp.get_input_details() self.assertLen(input_details, 1) self.assertEqual(np.float32, input_details[0]['dtype']) output_details = interp.get_output_details() self.assertLen(output_details, 1) self.assertEqual(np.float32, output_details[0]['dtype']) # Ensure that the quantized weights tflite model is smaller. self.assertLess(len(quantized_tflite_model), len(float_tflite_model)) @parameterized.named_parameters( ('_INT8InputOutput', dtypes.int8), ('_UINT8InputOutput', dtypes.uint8), ('_INT16InputOutput', dtypes.int16), ) @test_util.run_v2_only def testInvalidPostTrainingDynamicRangeQuantization( self, inference_input_output_type ): root, func, _ = self._getIntegerQuantizeModel() # Convert float model. converter = lite.TFLiteConverterV2.from_concrete_functions([func], root) tflite_model = converter.convert() self.assertTrue(tflite_model) # Convert quantized model. quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.optimizations = [lite.Optimize.DEFAULT] with self.assertRaises(ValueError) as error: quantized_converter.inference_input_type = inference_input_output_type quantized_converter.inference_output_type = inference_input_output_type quantized_converter.convert() self.assertEqual( 'The inference_input_type and inference_output_type ' 'must be tf.float32.', str(error.exception), ) def _createV2QATSavedModelWithFloatOpsAtEnd(self): """Create a simple QAT SavedModel that includes float ops at the end.""" saved_model_dir = os.path.join(self.get_temp_dir(), 'qat_float_ops_at_end') input_tensor = tf.keras.layers.Input((32, 32, 128)) class _FakeQuantArgsLayer(tf.keras.layers.Layer): """A fake quantization layer with fake_quant_with_min_max_args. Keras 3 requires wrapping the tf function inside Keras layer. """ def call(self, x): return tf.quantization.fake_quant_with_min_max_args(x, -3.0, 3.0) x = _FakeQuantArgsLayer()(input_tensor) x = tf.keras.layers.Conv2D(1, (3, 3), bias_initializer='ones')(x) x = _FakeQuantArgsLayer()(x) # Exclude the quantization of the following Dense layer by not putting # fake quant layer after the dense layer. output_tensor = tf.keras.layers.Dense( 1, activation='sigmoid', bias_initializer='ones' )(x) model = tf.keras.Model(input_tensor, output_tensor) model.save(saved_model_dir) return saved_model_dir def testQuantizationRemovesQDQsForFloatIOInQAT(self): saved_model_dir = self._createV2QATSavedModelWithFloatOpsAtEnd() converter = lite.TFLiteConverterV2.from_saved_model(saved_model_dir) converter.optimizations = [lite.Optimize.DEFAULT] quantized_model = converter.convert() # Because assertions on the model later, we opt out applying default TFLite # delegates (i.e. the XNNPACK delegate). interp = interpreter.Interpreter( model_content=quantized_model, experimental_op_resolver_type=interpreter.OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES, ) interp.allocate_tensors() # The model should have LOGISTIC op, instead of DEQUANTIZE op. op_details = interp._get_ops_details() self.assertEqual(op_details[len(op_details) - 1]['op_name'], 'LOGISTIC') @parameterized.named_parameters( ('EnableMlirQuantizer', True), # enable mlir quantizer ('DisableMlirQuantizer', False), ) # disable mlir quantizer def testQuantizationRemovesQDQsForFloatIO(self, mlir_quantizer): func, calibration_gen = self._getCeilModel() converter = lite.TFLiteConverterV2.from_concrete_functions( [func.get_concrete_function()] ) converter.representative_dataset = calibration_gen converter.optimizations = [lite.Optimize.DEFAULT] converter.experimental_new_quantizer = mlir_quantizer quantized_model = converter.convert() # Because assertions on the model later, we opt out applying default TFLite # delegates (i.e. the XNNPACK delegate). interp = interpreter.Interpreter( model_content=quantized_model, experimental_op_resolver_type=interpreter.OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES, ) interp.allocate_tensors() # The model should have only one sqrt op. op_details = interp._get_ops_details() self.assertLen(op_details, 1) self.assertEqual(op_details[0]['op_name'], 'CEIL') @parameterized.named_parameters( ('_Default', False, False, dtypes.float32), ('_INT8InputOutput', False, False, dtypes.int8), ('_UINT8InputOutput', False, False, dtypes.uint8), ('_INT16Quantize', False, True, dtypes.float32), ('_INT16Quantize_INT16InputOutput', False, True, dtypes.int16), ('_IntOnly', True, False, dtypes.float32), ('_IntOnly_INT8InputOutput', True, False, dtypes.int8), ('_IntOnly_UINT8InputOutput', True, False, dtypes.uint8), ('_IntOnly_INT16Quantize', True, True, dtypes.float32), ('_IntOnly_INT16Quantize_INT16InputOutput', True, True, dtypes.int16), ) def testIntegerQuantization( self, is_int_only, is_int16_quantize, inference_input_output_type ): root, func, calibration_gen = self._getIntegerQuantizeModel() # Convert float model. converter = lite.TFLiteConverterV2.from_concrete_functions([func], root) tflite_model = converter.convert() self.assertTrue(tflite_model) # Convert quantized model. quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.representative_dataset = calibration_gen if is_int_only: if is_int16_quantize: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8 ] else: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS_INT8 ] else: if is_int16_quantize: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8, lite.OpsSet.TFLITE_BUILTINS, ] quantized_converter.inference_input_type = inference_input_output_type quantized_converter.inference_output_type = inference_input_output_type quantized_tflite_model = quantized_converter.convert() self.assertIsNotNone(quantized_tflite_model) # Check the conversion metadata. metadata = util.get_conversion_metadata(quantized_tflite_model) self.assertIsNotNone(metadata) expected_opt_options = [metadata_fb.ModelOptimizationMode.PTQ_FULL_INTEGER] if is_int16_quantize: expected_opt_options = [metadata_fb.ModelOptimizationMode.PTQ_INT16] self.assertAllEqual( expected_opt_options, metadata.options.modelOptimizationModes ) interp = interpreter.Interpreter(model_content=quantized_tflite_model) interp.allocate_tensors() input_details = interp.get_input_details() self.assertLen(input_details, 1) self.assertEqual( inference_input_output_type.as_numpy_dtype, input_details[0]['dtype'] ) output_details = interp.get_output_details() self.assertLen(output_details, 1) self.assertEqual( inference_input_output_type.as_numpy_dtype, output_details[0]['dtype'] ) # Ensure that the quantized tflite model is smaller. self.assertLess(len(quantized_tflite_model), len(tflite_model)) @parameterized.named_parameters(('_INT16Quantize_INT8InputOutput', True)) def testInvalidIntegerQuantization(self, is_int16_quantize): root, func, calibration_gen = self._getIntegerQuantizeModel() # Convert quantized model. quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.representative_dataset = calibration_gen if is_int16_quantize: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8, lite.OpsSet.TFLITE_BUILTINS, ] with self.assertRaises(ValueError) as error: quantized_converter.inference_input_type = dtypes.int8 quantized_converter.inference_output_type = dtypes.int8 quantized_converter.convert() self.assertEqual( 'The inference_input_type and inference_output_type ' "must be in ['tf.float32', 'tf.int16'].", str(error.exception), ) def testCalibrateAndQuantizeBuiltinInt16(self): root, func, calibration_gen = self._getIntegerQuantizeModel() # Convert float model. float_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) float_tflite_model = float_converter.convert() self.assertIsNotNone(float_tflite_model) converter = lite.TFLiteConverterV2.from_concrete_functions([func], root) converter.optimizations = [lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8 ] converter.representative_dataset = calibration_gen quantized_tflite_model = converter.convert() self.assertIsNotNone(quantized_tflite_model) # The default input and output types should be float. interp = interpreter.Interpreter(model_content=quantized_tflite_model) interp.allocate_tensors() input_details = interp.get_input_details() self.assertLen(input_details, 1) self.assertEqual(np.float32, input_details[0]['dtype']) output_details = interp.get_output_details() self.assertLen(output_details, 1) self.assertEqual(np.float32, output_details[0]['dtype']) # The weights tensor should be quantized to 8 bits, # the bias tensor should be 32 bits to utilize optimized kernels, # and the activations should be 16 bits. tensor_details = interp.get_tensor_details() self.assertEqual(np.int8, tensor_details[2]['dtype']) self.assertEqual(np.int64, tensor_details[1]['dtype']) self.assertEqual(np.int16, tensor_details[0]['dtype']) self.assertEqual(np.int16, tensor_details[3]['dtype']) # Ensure that the quantized weights tflite model is smaller. self.assertLess(len(quantized_tflite_model), len(float_tflite_model)) @test_util.run_v2_only def testSignatureDefs(self): """Test converting SignatureDef is correct and uses SignatureDef API.""" root = self._getMultiFunctionModel() input_data = tf.constant(1.0, shape=[1]) add_func = root.add.get_concrete_function(input_data) converter = lite.TFLiteConverterV2([add_func], trackable_obj=root) tflite_model = converter.convert() # Check values from converted model. expected_value = add_func(input_data) interp = interpreter.Interpreter(model_content=tflite_model) signature_defs = interp.get_signature_list() results = self._evaluateTFLiteModelUsingSignatureDef( tflite_model, 'serving_default', {'x': input_data} ) self.assertLen(list(results.keys()), 1) self.assertStartsWith(list(results.keys())[0], 'output') self.assertAllClose( expected_value.numpy(), results[signature_defs['serving_default']['outputs'][0]], ) # Verify the SignatureDef structure returned is as expected. self.assertLen(signature_defs, 1) self.assertEqual(list(signature_defs.keys()), ['serving_default']) self.assertLen(signature_defs.values(), 1) self.assertEqual( list(signature_defs['serving_default'].keys()), ['inputs', 'outputs'] ) self.assertCountEqual(signature_defs['serving_default']['inputs'], ['x']) self.assertLen(list(signature_defs['serving_default']['outputs']), 1) self.assertStartsWith( list(signature_defs['serving_default']['outputs'])[0], 'output' ) @test_util.run_v2_only def testNoSignatureDefsWhenTrackingObjIsNone(self): """Test converting SignatureDef is correct and uses SignatureDef API.""" root = self._getSimpleVariableModel() input_data = tf.constant(1.0, shape=[1]) concrete_func = root.f.get_concrete_function(input_data) converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], None ) tflite_model = converter.convert() # Check values from converted model. interp = interpreter.Interpreter(model_content=tflite_model) signature_defs = interp.get_signature_list() # Verify that there is no SignatureDef structure found. self.assertEmpty(signature_defs) @test_util.run_v2_only def testNoSignatureDefsWhenInvalidTrackingObjIsGiven(self): """Test converting SignatureDef is correct and uses SignatureDef API.""" root = self._getSimpleVariableModel() input_data = tf.constant(1.0, shape=[1]) concrete_func = root.f.get_concrete_function(input_data) converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], trackable_obj=autotrackable.AutoTrackable() ) tflite_model = converter.convert() # Check values from converted model. interp = interpreter.Interpreter(model_content=tflite_model) signature_defs = interp.get_signature_list() # Verify that there is no SignatureDef structure found. self.assertEmpty(signature_defs) @test_util.run_v2_only def testTrackbleObject(self): """Test converting with trackable objects.""" root = self._getMultiFunctionModel() input_data = tf.constant(1.0, shape=[1]) add_func = root.add.get_concrete_function(input_data) converter = lite.TFLiteConverterV2.from_concrete_functions( [add_func], trackable_obj=root ) tflite_model = converter.convert() # Check values from converted model. expected_value = add_func(input_data) actual_value = self._evaluateTFLiteModel(tflite_model, [input_data]) self.assertEqual(expected_value.numpy(), actual_value) def _getTrainingTimeQuantizedModel(self): class QLinear(tf.keras.layers.Layer): def __init__(self, units=3, **kwargs): super().__init__(**kwargs) self.units = units def build(self, input_shape): self.w = self.add_weight( 'weight', shape=(input_shape[-1], self.units), initializer='random_normal', trainable=True, ) self.min_var = self.add_weight( 'min', initializer=tf.keras.initializers.Constant(-6.0), trainable=False, ) self.max_var = self.add_weight( 'max', initializer=tf.keras.initializers.Constant(6.0), trainable=False, ) def call(self, inputs): x = tf.quantization.fake_quant_with_min_max_vars( inputs, self.min_var, self.max_var ) w_fq = tf.quantization.fake_quant_with_min_max_vars( self.w, self.min_var, self.max_var ) x = tf.matmul(x, w_fq) x = tf.quantization.fake_quant_with_min_max_vars( x, self.min_var, self.max_var ) return x return tf.keras.Sequential(QLinear(3, input_shape=(2,))) @parameterized.named_parameters( ('_DefaultFLOAT32InputOutput', dtypes.float32), ('_INT8InputOutput', dtypes.int8), ('_UINT8InputOutput', dtypes.uint8), ) @test_util.run_v2_only def testTrainingTimeQuantization(self, inference_input_output_type): model = self._getTrainingTimeQuantizedModel() float_converter = lite.TFLiteConverterV2.from_keras_model(model) float_tflite_model = float_converter.convert() self.assertIsNotNone(float_tflite_model) quantized_converter = lite.TFLiteConverterV2.from_keras_model(model) quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.inference_input_type = inference_input_output_type quantized_converter.inference_output_type = inference_input_output_type quantized_tflite_model = quantized_converter.convert() self.assertIsNotNone(quantized_tflite_model) # Check the conversion metadata. metadata = util.get_conversion_metadata(quantized_tflite_model) self.assertIsNotNone(metadata) self.assertAllEqual( [metadata_fb.ModelOptimizationMode.QUANTIZATION_AWARE_TRAINING], metadata.options.modelOptimizationModes, ) interp = interpreter.Interpreter(model_content=quantized_tflite_model) interp.allocate_tensors() input_details = interp.get_input_details() self.assertLen(input_details, 1) self.assertEqual( inference_input_output_type.as_numpy_dtype, input_details[0]['dtype'] ) output_details = interp.get_output_details() self.assertLen(output_details, 1) self.assertEqual( inference_input_output_type.as_numpy_dtype, output_details[0]['dtype'] ) # Ensure that the quantized tflite model is smaller. self.assertLess(len(quantized_tflite_model), len(float_tflite_model)) @test_util.run_v2_only def testNewQuantizer(self): """Test the model quantized by the new converter.""" root, func, calibration_gen = self._getIntegerQuantizeModel() quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS_INT8 ] quantized_converter.representative_dataset = calibration_gen # default quantizer quantized_converter.experimental_new_quantizer = False old_tflite = quantized_converter.convert() # new quantizer quantized_converter.experimental_new_quantizer = True new_tflite = quantized_converter.convert() for _ in range(5): input_data = tf.constant( np.random.uniform(-1, 1, size=(1, 5, 5, 3)).astype(np.float32) ) old_value = self._evaluateTFLiteModel(old_tflite, [input_data]) new_value = self._evaluateTFLiteModel(new_tflite, [input_data]) self.assertAllClose(old_value, new_value, atol=1e-01) @test_util.run_v2_only def testGatherNDQI8(self): """Test gather_nd with quantized i8 parameters.""" class GatherNDQI8QDQ(tf.keras.Model): @tf.function( input_signature=[tf.TensorSpec(shape=(2, 2), dtype=tf.float32)] ) def func(self, input_tensor): x = tf.quantization.fake_quant_with_min_max_args( input_tensor, -3.0, 3.0 ) x = tf.gather_nd(x, [[0, 0], [1, 1]]) return tf.quantization.fake_quant_with_min_max_args(x, -3.0, 3.0) # Build a QDQ model so that tfl.gather_nd will be converted to a QI8 version # with the `_experimental_qdq_conversion_mode`` flag root = GatherNDQI8QDQ() concrete_func = root.func.get_concrete_function() converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) converter._experimental_qdq_conversion_mode = 'STATIC' tflite_model = converter.convert() np_data = np.array([[1, 2], [3, 4]], dtype=np.float32) input_tensor = tf.constant(np_data, dtype=tf.int8) expected_value = [1, 4] actual_value = self._evaluateTFLiteModel(tflite_model, [input_tensor]) self.assertAllClose(expected_value, actual_value[0], atol=1e-05) @test_util.run_v2_only def testEmbeddings(self): """Test model with embeddings.""" input_data = tf.constant( np.array(np.random.random_sample((20)), dtype=np.int32) ) class EmbeddingModel(tf.keras.Model): def __init__(self): super().__init__() self.shared_weights = self.add_weight( 'weights', shape=(2000, 300), dtype=tf.float32, initializer=tf.random_normal_initializer( mean=0.0, stddev=300 ** (-0.5) ), ) @tf.function(input_signature=[tf.TensorSpec(shape=(20), dtype=tf.int32)]) def func(self, x): return tf.gather(self.shared_weights, x) # Building the model. root = EmbeddingModel() concrete_func = root.func.get_concrete_function() # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) tflite_model = converter.convert() # Check values from converted model. expected_value = root.func(input_data) actual_value = self._evaluateTFLiteModel(tflite_model, [input_data]) self.assertAllClose(expected_value.numpy(), actual_value[0], atol=1e-05) @test_util.run_v2_only def testGraphDebugInfo(self): """Test a concrete function has debug info captured.""" root = autotrackable.AutoTrackable() root.v1 = tf.Variable(3.0) root.f = tf.function(lambda x: root.v1 * x) input_data = tf.constant(1.0, shape=[1]) concrete_func = root.f.get_concrete_function(input_data) # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) converter.convert() self._assertValidDebugInfo(converter._debug_info) def _getIntegerQuantizationModelWithFlexOp(self): np.random.seed(0) root = autotrackable.AutoTrackable() @tf.function( input_signature=[tf.TensorSpec(shape=[3, 3, 3, 3, 3], dtype=tf.float32)] ) def func(inp): tanh = tf.math.tanh(inp) # Flex delegate will merge the consecutive conv3d and erf ops into one # Delegate node. conv3d = tf.nn.conv3d( tanh, tf.ones([3, 3, 3, 3, 3]), strides=[1, 1, 1, 1, 1], padding='SAME', ) erf = tf.math.erf(conv3d) output = tf.math.tanh(erf) return output def calibration_gen(): for _ in range(5): yield [ np.random.uniform(-1, 1, size=(3, 3, 3, 3, 3)).astype(np.float32) ] root.f = func return (root, root.f.get_concrete_function(), calibration_gen) @parameterized.named_parameters( ('_Default', False, False, dtypes.float32), ('_INT8InputOutput', False, False, dtypes.int8), ('_UINT8InputOutput', False, False, dtypes.uint8), ('_INT16Quantize', False, True, dtypes.float32), ('_INT16Quantize_INT16InputOutput', False, True, dtypes.int16), ('_IntOnly', True, False, dtypes.float32), ('_IntOnly_INT8InputOutput', True, False, dtypes.int8), ('_IntOnly_UINT8InputOutput', True, False, dtypes.uint8), ('_IntOnly_INT16Quantize', True, True, dtypes.float32), ('_IntOnly_INT16Quantize_INT16InputOutput', True, True, dtypes.int16), ) @test_util.run_v2_only def testIntegerQuantizationWithFlexOp( self, is_int_only, is_int16_quantize, inference_input_output_type ): root, func, calibration_gen = self._getIntegerQuantizationModelWithFlexOp() quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.representative_dataset = calibration_gen if is_int_only: if is_int16_quantize: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8, lite.OpsSet.SELECT_TF_OPS, ] else: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS_INT8, lite.OpsSet.SELECT_TF_OPS, ] else: if is_int16_quantize: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8, lite.OpsSet.TFLITE_BUILTINS, lite.OpsSet.SELECT_TF_OPS, ] else: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS, lite.OpsSet.SELECT_TF_OPS, ] quantized_converter.inference_input_type = inference_input_output_type quantized_converter.inference_output_type = inference_input_output_type quantized_tflite_model = quantized_converter.convert() self.assertIsNotNone(quantized_tflite_model) # Check the conversion metadata. metadata = util.get_conversion_metadata(quantized_tflite_model) self.assertIsNotNone(metadata) self.assertEqual(metadata.options.enableSelectTfOps, True) expected_opt_options = [metadata_fb.ModelOptimizationMode.PTQ_FULL_INTEGER] if is_int16_quantize: expected_opt_options = [metadata_fb.ModelOptimizationMode.PTQ_INT16] self.assertAllEqual( expected_opt_options, metadata.options.modelOptimizationModes ) interp = interpreter.Interpreter(model_content=quantized_tflite_model) interp.allocate_tensors() input_details = interp.get_input_details() self.assertLen(input_details, 1) self.assertEqual( inference_input_output_type.as_numpy_dtype, input_details[0]['dtype'] ) output_details = interp.get_output_details() self.assertLen(output_details, 1) self.assertEqual( inference_input_output_type.as_numpy_dtype, output_details[0]['dtype'] ) def _getIntegerQuantizationModelWithUnsupportedOps(self): np.random.seed(0) root = autotrackable.AutoTrackable() @tf.function( input_signature=[ tf.TensorSpec(shape=[3], dtype=tf.float32), tf.TensorSpec(shape=[3], dtype=tf.float32), ] ) def func(a, b): # ceil kernel does not support int8 nor int16 types neither. left = tf.math.ceil(a) right = tf.nn.tanh(b) add = tf.math.add(left, right) # ceil kernel does not support int8 nor int16 types neither. output = tf.math.ceil(add) return (output, right) def calibration_gen(): for _ in range(5): yield [ np.random.uniform(-1, 1, size=(3)).astype(np.float32), np.random.uniform(-1, 1, size=(3)).astype(np.float32), ] root.f = func return (root, root.f.get_concrete_function(), calibration_gen) @parameterized.named_parameters( ('_INT8InputOutput', False, False, dtypes.int8), ('_UINT8InputOutput', False, False, dtypes.uint8), ('_INT16Quantize_INT16InputOutput', False, True, dtypes.int16), ('_IntOnly_INT8InputOutput', True, False, dtypes.int8), ('_IntOnly_UINT8InputOutput', True, False, dtypes.uint8), ('_IntOnly_INT16Quantize_INT16InputOutput', True, True, dtypes.int16), ('_IntOnly_INT8InputOutputMlirQuant', True, False, dtypes.int8, True), ('_IntOnly_UINT8InputOutputMlirQuant', True, False, dtypes.uint8, True), ) @test_util.run_v2_only def testIntegerQuantizationWithUnsupportedOps( self, is_int_only, is_int16_quantize, inference_input_output_type, enable_mlir_quantizer=False, ): root, func, calib_gen = ( self._getIntegerQuantizationModelWithUnsupportedOps() ) quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.representative_dataset = calib_gen if is_int_only: if is_int16_quantize: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8, lite.OpsSet.TFLITE_BUILTINS, ] else: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS_INT8, lite.OpsSet.TFLITE_BUILTINS, ] else: if is_int16_quantize: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8, lite.OpsSet.TFLITE_BUILTINS, ] else: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS ] quantized_converter.inference_input_type = inference_input_output_type quantized_converter.inference_output_type = inference_input_output_type quantized_converter.experimental_new_quantizer = enable_mlir_quantizer quantized_tflite_model = quantized_converter.convert() self.assertIsNotNone(quantized_tflite_model) expected_dtype = inference_input_output_type.as_numpy_dtype # Allow float32 for fallback on non-quantizable op. expected_ceil_dtype = ( expected_dtype if enable_mlir_quantizer else dtypes.float32 ) interp = interpreter.Interpreter(model_content=quantized_tflite_model) interp.allocate_tensors() input_details = interp.get_input_details() self.assertLen(input_details, 2) self.assertEqual(input_details[0]['dtype'], expected_dtype) self.assertEqual(input_details[1]['dtype'], expected_ceil_dtype) output_details = interp.get_output_details() self.assertLen(output_details, 2) self.assertEqual(output_details[0]['dtype'], expected_dtype) self.assertEqual(output_details[1]['dtype'], expected_ceil_dtype) def _getIntegerQuantizationModelWithControlFlow(self): def true_fn(x): return x def false_fn(x): return x @tf.function( input_signature=[ tf.TensorSpec(shape=[1, 2], dtype=tf.float32), tf.TensorSpec(shape=(), dtype=tf.bool), ] ) def model(x, b): x = x + x x = tf.cond(b, true_fn=lambda: true_fn(x), false_fn=lambda: false_fn(x)) return x + x def calibration_gen(): for _ in range(5): yield [ np.random.uniform( -1, 1, size=( 1, 2, ), ).astype(np.float32), tf.constant(True), ] for _ in range(5): yield [ np.random.uniform( -1, 1, size=( 1, 2, ), ).astype(np.float32), tf.constant(False), ] return (model, model.get_concrete_function(), calibration_gen) @parameterized.named_parameters( ('_INT8InputOutput', False, False, dtypes.int8), ('_UINT8InputOutput', False, False, dtypes.uint8), ('_INT16Quantize_INT16InputOutput', False, True, dtypes.int16), ('_IntOnly_INT8InputOutput', True, False, dtypes.int8), ('_IntOnly_UINT8InputOutput', True, False, dtypes.uint8), ('_IntOnly_INT16Quantize_INT16InputOutput', True, True, dtypes.int16), ) @test_util.run_v2_only def testIntegerQuantizationWithControlFlow( self, is_int_only, is_int16_quantize, inference_input_output_type, enable_mlir_quantizer=False, ): root, func, calib_gen = self._getIntegerQuantizationModelWithControlFlow() quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.representative_dataset = calib_gen if is_int_only: if is_int16_quantize: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8, lite.OpsSet.TFLITE_BUILTINS, ] else: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS_INT8, lite.OpsSet.TFLITE_BUILTINS, ] else: if is_int16_quantize: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8, lite.OpsSet.TFLITE_BUILTINS, ] else: quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS ] quantized_converter.inference_input_type = inference_input_output_type quantized_converter.inference_output_type = inference_input_output_type quantized_converter.experimental_new_quantizer = enable_mlir_quantizer quantized_tflite_model = quantized_converter.convert() self.assertIsNotNone(quantized_tflite_model) expected_dtype = inference_input_output_type.as_numpy_dtype interp = interpreter.Interpreter(model_content=quantized_tflite_model) interp.allocate_tensors() input_details = interp.get_input_details() self.assertLen(input_details, 2) self.assertEqual(input_details[0]['dtype'], expected_dtype) self.assertEqual(input_details[1]['dtype'], dtypes.bool) output_details = interp.get_output_details() self.assertLen(output_details, 1) self.assertEqual(output_details[0]['dtype'], expected_dtype) @parameterized.named_parameters( ('_BlocklistedNoneWithLowering', None, None, True), ('_BlocklistedNoneWithoutLowering', None, None, False), ('_BlocklistedOpsWithLowering', {'CONV_2D'}, None, True), ('_BlocklistedOpsWithoutLowering', {'CONV_2D'}, None, False), ('_BlocklistedNodesWithLowering', None, {'PartitionedCall:0'}, True), ('_BlocklistedNodesWithoutLowering', None, {'Identity'}, False), ) @test_util.run_v2_only def testNewQuantizerBlocklistingArgs( self, denylisted_ops, denylisted_nodes, lower_to_saved_model ): """Test the model quantized by the new converter and denylisted options.""" root, func, calibration_gen = self._getIntegerQuantizeModel() quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS_INT8 ] quantized_converter.representative_dataset = calibration_gen quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.experimental_new_quantizer = True quantized_converter._experimental_calibrate_only = True quantized_converter.experimental_lower_to_saved_model = lower_to_saved_model calibrated = quantized_converter.convert() quantized_tflite_model = convert.mlir_quantize( calibrated, denylisted_ops=denylisted_ops, denylisted_nodes=denylisted_nodes, ) interp = interpreter.Interpreter(model_content=quantized_tflite_model) details = interp.get_tensor_details() num_quantized_tensors = sum([ 1 for detail in details if len(detail['quantization_parameters']['scales']) ]) if denylisted_nodes or denylisted_ops: self.assertEqual(num_quantized_tensors, 0) return self.assertEqual(num_quantized_tensors, 4) # quant, filter, bias, dequant @parameterized.named_parameters( ('_SingleLayer', False), ('_WholeModel', True), ) @test_util.run_v2_only def testNewQuantizerNumericVerificationDebugMode(self, whole_model_verify): """Test the model quantized by the new converter with numeric verify ops.""" root, func, calibration_gen = self._getIntegerQuantizeModel() quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS_INT8 ] quantized_converter.representative_dataset = calibration_gen # Create a TFLite model with new quantizer. quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.experimental_new_quantizer = True production_tflite = quantized_converter.convert() # Create a TFLite model with new quantizer and numeric verify ops. quantized_converter._experimental_calibrate_only = True calibrated = quantized_converter.convert() debug_mode_tflite = convert.mlir_quantize( calibrated, enable_numeric_verify=True, enable_whole_model_verify=whole_model_verify, ) # Check if adding debug mode should output a different flatbuffer. self.assertNotEqual(production_tflite, debug_mode_tflite) # Check if newly added ops are numeric verify ops. input_data = tf.constant( np.random.uniform(-1, 1, size=(1, 5, 5, 3)).astype(np.float32) ) def examine_tflite_model(tflite_content, input_data): interp = interpreter.Interpreter( model_content=tflite_content, experimental_op_resolver_type=interpreter.OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES, ) interp.allocate_tensors() input_details = interp.get_input_details() interp.set_tensor(input_details[0]['index'], input_data.numpy()) interp.invoke() tensor_details = interp.get_tensor_details() return { details['name']: interp.get_tensor(details['index']) for details in interp.get_tensor_details() }, tensor_details tflite_result, _ = examine_tflite_model(production_tflite, input_data) debug_mode_tflite_result, debug_tensor_details = examine_tflite_model( debug_mode_tflite, input_data ) # MLIR-based quantizer should output flatbuffer model with `tfl.quantize`. num_production_quantize_ops = len([ None for output_tensor_name in tflite_result if 'tfl.quantize' in output_tensor_name ]) self.assertEqual(num_production_quantize_ops, 1) # MLIR-based quantizer should output flatbuffer model with `tfl.quantize`. num_debug_quantize_ops = len([ None for output_tensor_name in debug_mode_tflite_result if 'tfl.quantize' in output_tensor_name ]) # Two numbers should be equal. self.assertEqual(num_production_quantize_ops, num_debug_quantize_ops) # DebugMode TFLite flatbuffer should have NumericVerifyOps more than zero. # The name has the prefix "NumericVerify/{name}:{id} # where {name} is the tensor name of the original quantized op's activation, # and {id} is its tensor id. num_debug_ops = 0 for output_tensor_name in debug_mode_tflite_result: if 'NumericVerify' in output_tensor_name: pos_end_prefix = len('NumericVerify/') pos_colon = output_tensor_name.rfind(':') self.assertEqual('NumericVerify/', output_tensor_name[:pos_end_prefix]) tensor_id = int(output_tensor_name[pos_colon + 1 :]) original_tensor_name = output_tensor_name[pos_end_prefix:pos_colon] self.assertEqual( original_tensor_name, debug_tensor_details[tensor_id]['name'] ) num_debug_ops += 1 self.assertEqual(num_debug_ops, 1) # The number of debug ops should be equal to that of quantized ops. self.assertEqual(num_debug_ops, num_debug_quantize_ops) @parameterized.named_parameters( ('_PerChannelQuant', False, False), ('_PerChannelMlirQuant', False, True), ('_PerTensorQuant', True, False), ('_PerTensorMlirQuant', True, True), ('_PerChannelDynamicRange', False, False), ('_PerTensorDynamicRange', True, False), ) @test_util.run_v2_only def testDisablePerChannelQuantization( self, disable_per_channel=False, enable_mlir_quantizer=False, ): k_conv_name = 'Conv2D' # Dynamic range quant requires total num elements of filters > 1024. k_num_filters = 38 root, func, calib_gen = self._getIntegerQuantizeModel(k_num_filters) quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.optimizations = [lite.Optimize.DEFAULT] quantized_converter.representative_dataset = calib_gen quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS ] quantized_converter.experimental_new_quantizer = enable_mlir_quantizer if disable_per_channel: quantized_converter._experimental_disable_per_channel = ( disable_per_channel ) quantized_tflite_model = quantized_converter.convert() self.assertIsNotNone(quantized_tflite_model) interp = interpreter.Interpreter(model_content=quantized_tflite_model) interp.allocate_tensors() detail = next(( d for d in interp.get_tensor_details() if d['name'].startswith(k_conv_name) )) quant_params = detail['quantization_parameters'] expected_num_params = 1 if disable_per_channel else k_num_filters self.assertLen(quant_params['scales'], expected_num_params) if len(quant_params['zero_points']) != 1: self.assertLen(quant_params['zero_points'], expected_num_params) def _getIntegerQuantizeDenseModel(self, num_filters=32): np.random.seed(0) root = autotrackable.AutoTrackable() @tf.function( input_signature=[tf.TensorSpec(shape=[1, 16], dtype=tf.float32)] ) def func(inp): dense = tf.matmul(a=inp, b=tf.ones([16, num_filters])) output = tf.nn.relu(dense, name='output') return output def calibration_gen(): for _ in range(5): yield [np.random.uniform(-1, 1, size=(1, 16)).astype(np.float32)] root.f = func to_save = root.f.get_concrete_function() return (root, to_save, calibration_gen) @parameterized.named_parameters( ('_PerChannelQuant', False, False), ('_PerChannelMlirQuant', False, True), ('_PerTensorQuant', True, False), ('_PerTensorMlirQuant', True, True), ('_PerChannelDynamicRange', False, True, True), ('_PerTensorDynamicRange', True, True, True), ) @test_util.run_v2_only def testDisablePerChannelQuantizationForDenseLayers( self, disable_per_channel_for_dense=False, enable_mlir_quantizer=False, representative_dataset=False, ): k_dense_name = 'MatMul' # Dynamic range quant requires total num elements of filters > 1024. k_num_filters = 64 root, func, calib_gen = self._getIntegerQuantizeDenseModel(k_num_filters) quantized_converter = lite.TFLiteConverterV2.from_concrete_functions( [func], root ) quantized_converter.optimizations = [lite.Optimize.DEFAULT] if representative_dataset: quantized_converter.representative_dataset = calib_gen quantized_converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS ] quantized_converter.experimental_new_quantizer = enable_mlir_quantizer if disable_per_channel_for_dense: quantized_converter._experimental_disable_per_channel_quantization_for_dense_layers = ( disable_per_channel_for_dense ) quantized_tflite_model = quantized_converter.convert() self.assertIsNotNone(quantized_tflite_model) # Do not apply delegates as XNNPack converts per tensor to per channel. interp = interpreter.Interpreter( model_content=quantized_tflite_model, experimental_op_resolver_type=interpreter.OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES, ) interp.allocate_tensors() detail = next(( d for d in interp.get_tensor_details() if d['name'].startswith(k_dense_name) )) quant_params = detail['quantization_parameters'] expected_num_params = 1 if disable_per_channel_for_dense else k_num_filters self.assertLen(quant_params['scales'], expected_num_params) if len(quant_params['zero_points']) != 1: self.assertLen(quant_params['zero_points'], expected_num_params) @parameterized.named_parameters( ('MlirQuantize', True), ('TocoQuantize', False) ) @test_util.run_v2_only def testQuantizeBiasOverflow(self, enable_mlir_quantizer): """Tests if the quantizer handles bias overflow by adjusting scales.""" input_data = np.array([[-1e-3, 1e-3]], dtype=np.float32) def calibration_gen(): yield {'x': input_data} root = self._getMatMulModelWithSmallWeights() input_data = tf.constant([-1e-3, 1e-3], shape=(1, 2)) concrete_func = root.matmul.get_concrete_function(input_data) converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) converter.optimizations = [lite.Optimize.DEFAULT] converter.representative_dataset = calibration_gen converter.experimental_new_quantizer = enable_mlir_quantizer quantized_model = converter.convert() interp = interpreter.Interpreter(model_content=quantized_model) interp.allocate_tensors() input_details = interp.get_input_details() interp.set_tensor(input_details[0]['index'], input_data) interp.invoke() output_details = interp.get_output_details() output = interp.get_tensor(output_details[0]['index']) # the inputs and weights are far smaller than the biases, so the final # result should be equal to the biases. self.assertAllClose(root.bias, output.flatten()) @test_util.run_v2_only def testOpVersion(self): @tf.function( input_signature=[tf.TensorSpec(shape=[5, 5], dtype=tf.float32)] ) def custom_resize(image): # Add "batch" and "channels" dimensions image = image[tf.newaxis, ..., tf.newaxis] # ResizeBilinear version 3. resize1 = tf.compat.v1.image.resize_bilinear( image, [2, 2], half_pixel_centers=True ) # ResizeBilinear version 1. resize2 = tf.compat.v1.image.resize_bilinear(image, [2, 2]) return resize1 + resize2 concrete_func = custom_resize.get_concrete_function() converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], custom_resize ) tflite_model = converter.convert() model_object = schema_fb.Model.GetRootAsModel(tflite_model, 0) model = schema_fb.ModelT.InitFromObj(model_object) for operator in model.operatorCodes: if operator.builtinCode == schema_fb.BuiltinOperator.RESIZE_BILINEAR: # half_pixel_centers is supported by ResizeBilinear version 3. self.assertEqual(operator.version, 3) break @test_util.run_v2_only def testForceSelectTFOps(self): root = self._getSimpleVariableModel() input_data = tf.constant(1.0, shape=[1]) concrete_func = root.f.get_concrete_function(input_data) # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) converter.target_spec.supported_ops = [lite.OpsSet.SELECT_TF_OPS] tflite_model = converter.convert() # Check the conversion metadata. metadata = util.get_conversion_metadata(tflite_model) self.assertIsNotNone(metadata) self.assertEqual(metadata.options.forceSelectTfOps, True) # Check output value from converted model. expected_value = root.f(input_data) actual_value = self._evaluateTFLiteModel(tflite_model, [input_data]) self.assertEqual(expected_value.numpy(), actual_value) def testExcludeConversionMetadata(self): root = self._getSimpleVariableModel() input_data = tf.constant(1.0, shape=[1]) concrete_func = root.f.get_concrete_function(input_data) # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) converter.exclude_conversion_metadata = True tflite_model = converter.convert() # Check the conversion metadata. metadata = util.get_conversion_metadata(tflite_model) self.assertIsNone(metadata) def testConversionMetadataForDynamicRange(self): func, _ = self._getCeilModel() converter = lite.TFLiteConverterV2.from_concrete_functions( [func.get_concrete_function()] ) converter.optimizations = [lite.Optimize.DEFAULT] quantized_model = converter.convert() # Check the conversion metadata. metadata = util.get_conversion_metadata(quantized_model) self.assertIsNotNone(metadata) self.assertAllEqual( [metadata_fb.ModelOptimizationMode.PTQ_DYNAMIC_RANGE], metadata.options.modelOptimizationModes, ) def testConversionMetadataForFloat16(self): root, func, calibration_gen = self._getIntegerQuantizeModel() converter = lite.TFLiteConverterV2.from_concrete_functions([func], root) converter.optimizations = [lite.Optimize.DEFAULT] converter.representative_dataset = calibration_gen converter.target_spec.supported_types = [dtypes.float16] quantized_model = converter.convert() # Check the conversion metadata. metadata = util.get_conversion_metadata(quantized_model) self.assertIsNotNone(metadata) self.assertAllEqual( [metadata_fb.ModelOptimizationMode.PTQ_FLOAT16], metadata.options.modelOptimizationModes, ) def testSerializeDebugMetadata(self): root = self._getSimpleVariableModel() input_data = tf.constant(1.0, shape=[1]) concrete_func = root.f.get_concrete_function(input_data) # Convert model. converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], root ) converter.serialize_debug_metadata = True tflite_model = flatbuffer_utils.convert_bytearray_to_object( converter.convert() ) # Check the debug metadata. metadata_names = [m.name for m in tflite_model.metadata] self.assertIn(b'debug_metadata', metadata_names)
FromConcreteFunctionTest
python
ray-project__ray
doc/source/ray-core/doc_code/cgraph_nccl.py
{ "start": 260, "end": 1052 }
class ____: def process(self, tensor: torch.Tensor): assert tensor.device.type == "cuda" return tensor.shape actor = GPUActor.remote() # __cgraph_cpu_to_gpu_actor_end__ # __cgraph_cpu_to_gpu_start__ with ray.dag.InputNode() as inp: inp = inp.with_tensor_transport(device="cuda") dag = actor.process.bind(inp) cdag = dag.experimental_compile() print(ray.get(cdag.execute(torch.zeros(10)))) # __cgraph_cpu_to_gpu_end__ # __cgraph_nccl_setup_start__ import torch import ray import ray.dag from ray.experimental.channel.torch_tensor_type import TorchTensorType # Note that the following example requires at least 2 GPUs. assert ( ray.available_resources().get("GPU") >= 2 ), "At least 2 GPUs are required to run this example." @ray.remote(num_gpus=1)
GPUActor
python
readthedocs__readthedocs.org
readthedocs/doc_builder/python_environments.py
{ "start": 718, "end": 4007 }
class ____: """An isolated environment into which Python packages can be installed.""" def __init__(self, version, build_env, config=None): self.version = version self.project = version.project self.build_env = build_env if config: self.config = config else: self.config = load_yaml_config(version) # Compute here, since it's used a lot self.checkout_path = self.project.checkout_path(self.version.slug) structlog.contextvars.bind_contextvars( project_slug=self.project.slug, version_slug=self.version.slug, ) def install_requirements(self): """Install all requirements from the config object.""" for install in self.config.python.install: if isinstance(install, PythonInstallRequirements): self.install_requirements_file(install) if isinstance(install, PythonInstall): self.install_package(install) def install_package(self, install): """ Install the package using pip or setuptools. :param install: A install object from the config module. :type install: readthedocs.config.models.PythonInstall """ # NOTE: `venv_bin` requires `prefixes`. # However, it's overwritten in the subclasses and # it forces passing the `prefixes=` attribute. # I'm not sure how to solve this, so I'm skipping this check for now. # pylint: disable=no-value-for-parameter if install.method == PIP: # Prefix ./ so pip installs from a local path rather than pypi local_path = os.path.join(".", install.path) if install.path != "." else install.path extra_req_param = "" if install.extra_requirements: extra_req_param = "[{}]".format(",".join(install.extra_requirements)) self.build_env.run( self.venv_bin(filename="python"), "-m", "pip", "install", "--upgrade", "--upgrade-strategy", "only-if-needed", "--no-cache-dir", "{path}{extra_requirements}".format( path=local_path, extra_requirements=extra_req_param, ), cwd=self.checkout_path, bin_path=self.venv_bin(), ) elif install.method == SETUPTOOLS: self.build_env.run( self.venv_bin(filename="python"), os.path.join(install.path, "setup.py"), "install", "--force", cwd=self.checkout_path, bin_path=self.venv_bin(), ) def venv_bin(self, prefixes, filename=None): """ Return path to the virtualenv bin path, or a specific binary. :param filename: If specified, add this filename to the path return :param prefixes: List of path prefixes to include in the resulting path :returns: Path to virtualenv bin or filename in virtualenv bin """ if filename is not None: prefixes.append(filename) return os.path.join(*prefixes)
PythonEnvironment
python
celery__celery
celery/states.py
{ "start": 1563, "end": 3324 }
class ____(str): """Task state. State is a subclass of :class:`str`, implementing comparison methods adhering to state precedence rules:: >>> from celery.states import state, PENDING, SUCCESS >>> state(PENDING) < state(SUCCESS) True Any custom state is considered to be lower than :state:`FAILURE` and :state:`SUCCESS`, but higher than any of the other built-in states:: >>> state('PROGRESS') > state(STARTED) True >>> state('PROGRESS') > state('SUCCESS') False """ def __gt__(self, other: str) -> bool: return precedence(self) < precedence(other) def __ge__(self, other: str) -> bool: return precedence(self) <= precedence(other) def __lt__(self, other: str) -> bool: return precedence(self) > precedence(other) def __le__(self, other: str) -> bool: return precedence(self) >= precedence(other) #: Task state is unknown (assumed pending since you know the id). PENDING = 'PENDING' #: Task was received by a worker (only used in events). RECEIVED = 'RECEIVED' #: Task was started by a worker (:setting:`task_track_started`). STARTED = 'STARTED' #: Task succeeded SUCCESS = 'SUCCESS' #: Task failed FAILURE = 'FAILURE' #: Task was revoked. REVOKED = 'REVOKED' #: Task was rejected (only used in events). REJECTED = 'REJECTED' #: Task is waiting for retry. RETRY = 'RETRY' IGNORED = 'IGNORED' READY_STATES = frozenset({SUCCESS, FAILURE, REVOKED}) UNREADY_STATES = frozenset({PENDING, RECEIVED, STARTED, REJECTED, RETRY}) EXCEPTION_STATES = frozenset({RETRY, FAILURE, REVOKED}) PROPAGATE_STATES = frozenset({FAILURE, REVOKED}) ALL_STATES = frozenset({ PENDING, RECEIVED, STARTED, SUCCESS, FAILURE, RETRY, REVOKED, })
state
python
davidhalter__jedi
test/test_api/test_call_signatures.py
{ "start": 16500, "end": 18719 }
class ____(): def __init__(self, foo, bar): self.foo = foo ''') def test_class_creation(Script): sig, = Script(CLASS_CODE + 'X(').get_signatures() assert sig.index == 0 assert sig.name == 'X' assert [p.name for p in sig.params] == ['foo', 'bar'] def test_call_init_on_class(Script): sig, = Script(CLASS_CODE + 'X.__init__(').get_signatures() assert [p.name for p in sig.params] == ['self', 'foo', 'bar'] def test_call_init_on_instance(Script): sig, = Script(CLASS_CODE + 'X().__init__(').get_signatures() assert [p.name for p in sig.params] == ['foo', 'bar'] def test_call_magic_method(Script): code = dedent('''\ class X(): def __call__(self, baz): pass ''') sig, = Script(code + 'X()(').get_signatures() assert sig.index == 0 assert sig.name == 'X' assert [p.name for p in sig.params] == ['baz'] sig, = Script(code + 'X.__call__(').get_signatures() assert [p.name for p in sig.params] == ['self', 'baz'] sig, = Script(code + 'X().__call__(').get_signatures() assert [p.name for p in sig.params] == ['baz'] @pytest.mark.parametrize('column', [6, 9]) def test_cursor_after_signature(Script, column): source = dedent(""" def foo(*args): pass foo() # _ """) script = Script(source) assert not script.get_signatures(4, column) @pytest.mark.parametrize( 'code, line, column, name, index', [ ('abs(()\ndef foo(): pass', 1, None, 'abs', 0), ('abs(chr() \ndef foo(): pass', 1, 10, 'abs', 0), ('abs(chr()\ndef foo(): pass', 1, None, 'abs', 0), ('abs(chr()\ndef foo(): pass', 1, 8, 'chr', 0), ('abs(chr()\ndef foo(): pass', 1, 7, 'abs', 0), ('abs(chr ( \nclass y: pass', 1, None, 'chr', 0), ('abs(chr ( \nclass y: pass', 1, 8, 'abs', 0), ('abs(chr ( \nclass y: pass', 1, 9, 'abs', 0), ('abs(chr ( \nclass y: pass', 1, 10, 'chr', 0), ('abs(foo.bar=3)', 1, 13, 'abs', 0), ] ) def test_base_signatures(Script, code, line, column, name, index): sig, = Script(code).get_signatures(line=line, column=column) assert sig.name == name assert sig.index == index
X
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 233209, "end": 235212 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, realm: str, consumer_key: str, consumer_secret: str, token_key: str, token_secret: str, start_datetime: str, object_types: Optional[list[str]] = None, window_in_days: Optional[int] = None, ): """Airbyte Source for Netsuite. Args: name (str): The name of the destination. realm (str): Netsuite realm e.g. 2344535, as for `production` or 2344535_SB1, as for the `sandbox` consumer_key (str): Consumer key associated with your integration consumer_secret (str): Consumer secret associated with your integration token_key (str): Access token key token_secret (str): Access token secret object_types (Optional[List[str]]): The API names of the Netsuite objects you want to sync. Setting this speeds up the connection setup process by limiting the number of schemas that need to be retrieved from Netsuite. start_datetime (str): Starting point for your data replication, in format of "YYYY-MM-DDTHH:mm:ssZ" window_in_days (Optional[int]): The amount of days used to query the data with date chunks. Set smaller value, if you have lots of data. """ self.realm = check.str_param(realm, "realm") self.consumer_key = check.str_param(consumer_key, "consumer_key") self.consumer_secret = check.str_param(consumer_secret, "consumer_secret") self.token_key = check.str_param(token_key, "token_key") self.token_secret = check.str_param(token_secret, "token_secret") self.object_types = check.opt_nullable_list_param(object_types, "object_types", str) self.start_datetime = check.str_param(start_datetime, "start_datetime") self.window_in_days = check.opt_int_param(window_in_days, "window_in_days") super().__init__("Netsuite", name)
NetsuiteSource
python
django__django
tests/migrations/migrations_test_apps/unmigrated_app_syncdb/models.py
{ "start": 73, "end": 172 }
class ____(models.Model): classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE)
Lesson
python
ray-project__ray
rllib/env/tests/test_multi_agent_env.py
{ "start": 13762, "end": 16615 }
class ____(MultiAgentEnv): DICT_SPACE = gym.spaces.Dict( { "sensors": gym.spaces.Dict( { "position": gym.spaces.Box(low=-100, high=100, shape=(3,)), "velocity": gym.spaces.Box(low=-1, high=1, shape=(3,)), "front_cam": gym.spaces.Tuple( ( gym.spaces.Box(low=0, high=1, shape=(10, 10, 3)), gym.spaces.Box(low=0, high=1, shape=(10, 10, 3)), ) ), "rear_cam": gym.spaces.Box(low=0, high=1, shape=(10, 10, 3)), } ), "inner_state": gym.spaces.Dict( { "charge": gym.spaces.Discrete(100), "job_status": gym.spaces.Dict( { "task": gym.spaces.Discrete(5), "progress": gym.spaces.Box(low=0, high=100, shape=()), } ), } ), } ) TUPLE_SPACE = gym.spaces.Tuple( [ gym.spaces.Box(low=-100, high=100, shape=(3,)), gym.spaces.Tuple( ( gym.spaces.Box(low=0, high=1, shape=(10, 10, 3)), gym.spaces.Box(low=0, high=1, shape=(10, 10, 3)), ) ), gym.spaces.Discrete(5), ] ) def __init__(self): super().__init__() self.observation_space = gym.spaces.Dict( {"dict_agent": self.DICT_SPACE, "tuple_agent": self.TUPLE_SPACE} ) self.action_space = gym.spaces.Dict( { "dict_agent": gym.spaces.Discrete(1), "tuple_agent": gym.spaces.Discrete(1), } ) self._agent_ids = {"dict_agent", "tuple_agent"} self.steps = 0 self.DICT_SAMPLES = [self.DICT_SPACE.sample() for _ in range(10)] self.TUPLE_SAMPLES = [self.TUPLE_SPACE.sample() for _ in range(10)] def reset(self, *, seed=None, options=None): self.steps = 0 return { "dict_agent": self.DICT_SAMPLES[0], "tuple_agent": self.TUPLE_SAMPLES[0], }, {} def step(self, actions): self.steps += 1 obs = { "dict_agent": self.DICT_SAMPLES[self.steps], "tuple_agent": self.TUPLE_SAMPLES[self.steps], } rew = { "dict_agent": 0, "tuple_agent": 0, } terminateds = {"__all__": self.steps >= 5} truncateds = {"__all__": self.steps >= 5} infos = { "dict_agent": {}, "tuple_agent": {}, } return obs, rew, terminateds, truncateds, infos
NestedMultiAgentEnv
python
ansible__ansible
lib/ansible/inventory/group.py
{ "start": 1953, "end": 2015 }
class ____(Enum): HOST = 0 GROUP = 1
InventoryObjectType
python
numpy__numpy
numpy/lib/tests/test_shape_base.py
{ "start": 10206, "end": 10421 }
class ____: def test_simple(self): a = np.arange(24).reshape(2, 3, 4) aoa_a = apply_over_axes(np.sum, a, [0, 2]) assert_array_equal(aoa_a, np.array([[[60], [92], [124]]]))
TestApplyOverAxes
python
crytic__slither
slither/slithir/operations/unpack.py
{ "start": 441, "end": 1310 }
class ____(OperationWithLValue): def __init__( self, result: Union[LocalVariableInitFromTuple, LocalIRVariable], tuple_var: Union[TupleVariable, TupleVariableSSA], idx: int, ) -> None: assert is_valid_lvalue(result) assert isinstance(tuple_var, TupleVariable) assert isinstance(idx, int) super().__init__() self._tuple = tuple_var self._idx = idx self._lvalue = result @property def read(self) -> List[Union[TupleVariableSSA, TupleVariable]]: return [self.tuple] @property def tuple(self) -> Union[TupleVariable, TupleVariableSSA]: return self._tuple @property def index(self) -> int: return self._idx def __str__(self): return f"{self.lvalue}({self.lvalue.type})= UNPACK {self.tuple} index: {self.index} "
Unpack
python
getsentry__sentry
tests/sentry/notifications/notification_action/test_metric_alert_registry_handlers.py
{ "start": 2236, "end": 10274 }
class ____(BaseWorkflowTest): def create_models(self): self.workflow, self.detector, _, _ = self.create_detector_and_workflow() self.snuba_query = self.create_snuba_query() self.subscription = self.create_snuba_query_subscription(snuba_query_id=self.snuba_query.id) self.data_source = self.create_data_source( organization=self.organization, source_id=str(self.subscription.id), ) self.create_data_source_detector(data_source=self.data_source, detector=self.detector) self.alert_rule = self.create_alert_rule() self.create_alert_rule_detector(detector=self.detector, alert_rule_id=self.alert_rule.id) self.evidence_data = MetricIssueEvidenceData( value=123.45, detector_id=self.detector.id, data_packet_source_id=int(self.data_source.source_id), conditions=[ { "id": 1, "type": Condition.GREATER_OR_EQUAL, "comparison": 123, "condition_result": DetectorPriorityLevel.HIGH.value, }, { "id": 2, "type": Condition.GREATER_OR_EQUAL, "comparison": 100, "condition_result": DetectorPriorityLevel.MEDIUM.value, }, { "id": 3, "type": Condition.LESS, "comparison": 100, "condition_result": DetectorPriorityLevel.OK.value, }, ], data_sources=[], alert_id=self.alert_rule.id, ) self.anomaly_detection_evidence_data = MetricIssueEvidenceData( value={ "source_id": "12345", "subscription_id": "some-subscription-id-123", "timestamp": "2025-06-07", "value": 6789, }, detector_id=self.detector.id, data_packet_source_id=int(self.data_source.source_id), conditions=[ { "id": 1, "type": Condition.ANOMALY_DETECTION, "comparison": { "sensitivity": AnomalyDetectionSensitivity.MEDIUM.value, "seasonality": AnomalyDetectionSeasonality.AUTO.value, "threshold_type": AnomalyDetectionThresholdType.ABOVE_AND_BELOW.value, }, # This is the placeholder for the anomaly detection condition "condition_result": DetectorPriorityLevel.HIGH.value, }, ], data_sources=[], alert_id=self.alert_rule.id, ) self.group, self.event, self.group_event = self.create_group_event( occurrence=self.create_issue_occurrence( priority=PriorityLevel.HIGH.value, level="error", evidence_data=asdict(self.evidence_data), ), ) self.group.priority = PriorityLevel.HIGH.value self.group.save() self.create_detector_group(detector=self.detector, group=self.group) self.open_period, _ = GroupOpenPeriod.objects.get_or_create( group=self.group, project=self.project, date_started=self.group_event.group.first_seen, ) self.event_data = WorkflowEventData( event=self.group_event, workflow_env=self.workflow.environment, group=self.group, ) def setUp(self) -> None: self.create_models() def create_issue_occurrence( self, priority: int | None = None, level: str = "error", evidence_data: Mapping[str, Any] | None = None, ): if evidence_data is None: evidence_data = {} return IssueOccurrence( id=str(uuid.uuid4()), project_id=self.project.id, event_id=str(uuid.uuid4()), fingerprint=["test_fingerprint"], issue_title="test_issue_title", subtitle="test_subtitle", resource_id="test_resource_id", evidence_data=evidence_data, evidence_display=[], type=MetricIssue, detection_time=timezone.now(), level=level, culprit="test_culprit", priority=priority, assignee=None, ) def assert_notification_context( self, notification_context: NotificationContext, integration_id: int | None = None, target_identifier: str | None = None, target_display: str | None = None, sentry_app_config: list[dict[str, Any]] | dict[str, Any] | None = None, sentry_app_id: str | None = None, target_type: ActionTarget | None = None, ): assert asdict(notification_context) == { "id": notification_context.id, "integration_id": integration_id, "target_identifier": target_identifier, "target_display": target_display, "sentry_app_config": sentry_app_config, "sentry_app_id": sentry_app_id, "target_type": target_type, } def assert_alert_context( self, alert_context: AlertContext, name: str, action_identifier_id: int, threshold_type: AlertRuleThresholdType | AnomalyDetectionThresholdType | None = None, detection_type: AlertRuleDetectionType | None = None, comparison_delta: int | None = None, sensitivity: AlertRuleSensitivity | AnomalyDetectionSensitivity | None = None, resolve_threshold: float | None = None, alert_threshold: float | None = None, ): assert asdict(alert_context) == { "name": name, "action_identifier_id": action_identifier_id, "threshold_type": threshold_type, "detection_type": detection_type, "comparison_delta": comparison_delta, "sensitivity": sensitivity, "resolve_threshold": resolve_threshold, "alert_threshold": alert_threshold, } def assert_metric_issue_context( self, metric_issue_context: MetricIssueContext, open_period_identifier: int, snuba_query: SnubaQuery, new_status: IncidentStatus, title: str, metric_value: float | dict | None = None, subscription: QuerySubscription | None = None, group: Group | None = None, ): assert asdict(metric_issue_context) == { "id": metric_issue_context.id, "open_period_identifier": open_period_identifier, "snuba_query": snuba_query, "subscription": subscription, "new_status": new_status, "metric_value": metric_value, "title": title, "group": group, } def assert_open_period_context( self, open_period_context: OpenPeriodContext, id: int, date_started: datetime, date_closed: datetime | None, ): assert asdict(open_period_context) == { "id": id, "date_started": date_started, "date_closed": date_closed, } def unpack_kwargs(self, mock_send_alert): _, kwargs = mock_send_alert.call_args notification_context = kwargs["notification_context"] alert_context = kwargs["alert_context"] metric_issue_context = kwargs["metric_issue_context"] open_period_context = kwargs["open_period_context"] organization = kwargs["organization"] notification_uuid = kwargs["notification_uuid"] return ( notification_context, alert_context, metric_issue_context, open_period_context, organization, notification_uuid, )
MetricAlertHandlerBase
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-valyu/llama_index/tools/valyu/retriever.py
{ "start": 272, "end": 7543 }
class ____(BaseRetriever): """Valyu retriever for extracting content from URLs.""" def __init__( self, api_key: str, verbose: bool = False, # Contents API parameters contents_summary: Optional[Union[bool, str, Dict[str, Any]]] = None, contents_extract_effort: Optional[str] = "normal", contents_response_length: Optional[Union[str, int]] = "short", callback_manager: Optional[CallbackManager] = None, ) -> None: """ Initialize Valyu retriever. Args: api_key (str): Valyu API key verbose (bool): Enable verbose logging. Defaults to False contents_summary (Optional[Union[bool, str, Dict[str, Any]]]): AI summary configuration: - False/None: No AI processing (raw content) - True: Basic automatic summarization - str: Custom instructions (max 500 chars) - dict: JSON schema for structured extraction contents_extract_effort (Optional[str]): Extraction thoroughness: - "normal": Fast extraction (default) - "high": More thorough but slower - "auto": Automatically determine extraction effort but slowest contents_response_length (Optional[Union[str, int]]): Content length per URL: - "short": 25,000 characters (default) - "medium": 50,000 characters - "large": 100,000 characters - "max": No limit - int: Custom character limit callback_manager (Optional[CallbackManager]): Callback manager for tracking operations """ from valyu import Valyu # Validate parameters if not api_key or not isinstance(api_key, str) or not api_key.strip(): raise ValueError("api_key must be a non-empty string") if not isinstance(verbose, bool): raise ValueError("verbose must be a boolean") # Validate contents_summary if contents_summary is not None: if isinstance(contents_summary, str): if len(contents_summary) > 500: raise ValueError( f"contents_summary string must be 500 characters or less. " f"Current length: {len(contents_summary)} characters." ) elif not isinstance(contents_summary, (bool, dict)): raise ValueError( "contents_summary must be a boolean, string, dict, or None" ) # Validate contents_extract_effort valid_extract_efforts = ["normal", "high", "auto"] if ( contents_extract_effort is not None and contents_extract_effort not in valid_extract_efforts ): raise ValueError( f"contents_extract_effort must be one of {valid_extract_efforts}" ) # Validate contents_response_length if contents_response_length is not None: valid_preset_lengths = ["short", "medium", "large", "max"] if isinstance(contents_response_length, str): if contents_response_length not in valid_preset_lengths: raise ValueError( f"contents_response_length string must be one of {valid_preset_lengths}" ) elif isinstance(contents_response_length, int): if contents_response_length < 1: raise ValueError( "contents_response_length must be a positive integer when using custom length" ) else: raise ValueError( "contents_response_length must be a string preset, positive integer, or None" ) self.client = Valyu(api_key=api_key) self._verbose = verbose self._contents_summary = contents_summary self._contents_extract_effort = contents_extract_effort self._contents_response_length = contents_response_length super().__init__(callback_manager=callback_manager) def _retrieve(self, query_bundle) -> List[NodeWithScore]: """ Retrieve content from URLs. The query_bundle.query_str should contain URLs (space or comma separated). This method extracts content from those URLs and returns them as scored nodes. Args: query_bundle: Query bundle containing URLs to extract content from Returns: List[NodeWithScore]: List of nodes with extracted content and relevance scores """ # Parse URLs from query string urls = self._parse_urls_from_query(query_bundle.query_str) if not urls: return [] # Get content using Valyu API response = self.client.contents( urls=urls, summary=self._contents_summary, extract_effort=self._contents_extract_effort, response_length=self._contents_response_length, ) if self._verbose: print(f"[Valyu Retriever] Contents Response: {response}") nodes = [] if response and response.results: for result in response.results: metadata = { "url": result.url, "title": result.title, "source": result.source, "length": result.length, "data_type": result.data_type, "citation": result.citation, } # Add summary info if available if hasattr(result, "summary") and result.summary: metadata["summary"] = result.summary if ( hasattr(result, "summary_success") and result.summary_success is not None ): metadata["summary_success"] = result.summary_success # Add image URL if available if hasattr(result, "image_url") and result.image_url: metadata["image_url"] = result.image_url # Create text node node = TextNode( text=str(result.content), metadata=metadata, ) # Add as scored node (all retrieved content gets score of 1.0) nodes.append(NodeWithScore(node=node, score=1.0)) return nodes def _parse_urls_from_query(self, query_str: str) -> List[str]: """ Parse URLs from query string. Args: query_str: String containing URLs (space or comma separated) Returns: List[str]: List of valid URLs """ # Split by common separators import re # Split by whitespace or commas potential_urls = re.split(r"[,\s]+", query_str.strip()) # Filter for valid URLs urls = [] for url in potential_urls: url = url.strip() if url and url.startswith(("http://", "https://")): urls.append(url) return urls[:10] # Limit to 10 URLs as per API constraint
ValyuRetriever
python
protocolbuffers__protobuf
cmake/dependencies_generator.py
{ "start": 2216, "end": 3320 }
class ____(object): def __init__(self): self.toplevel = "" self.if_lua = "" def convert(self): return self.template % { "toplevel": converter.toplevel, } template = textwrap.dedent("""\ # Auto-generated by @//cmake:make_dependencies # # This file contains lists of external dependencies based on our Bazel # config. It should be included from a hand-written CMake file that uses # them. # # Changes to this file will be overwritten based on Bazel definitions. if(${CMAKE_VERSION} VERSION_GREATER 3.16 OR ${CMAKE_VERSION} VERSION_EQUAL 3.16) include_guard() endif() %(toplevel)s """) data = {} converter = Converter() def GetDict(obj): ret = {} for k in dir(obj): if not k.startswith("_"): ret[k] = getattr(obj, k) return ret # We take the MODULE path as a command-line argument to ensure that we can find # it regardless of how exactly Bazel was invoked. exec(open(sys.argv[1]).read(), GetDict(ModuleFileFunctions(converter))) with open(sys.argv[2], "w") as f: f.write(converter.convert())
Converter
python
realpython__materials
django-diary/source_code_step_5/entries/views.py
{ "start": 482, "end": 677 }
class ____(UpdateView): model = Entry fields = ["title", "content"] def get_success_url(self): return reverse_lazy("entry-detail", kwargs={"pk": self.entry.id})
EntryUpdateView
python
django-extensions__django-extensions
tests/testapp/models.py
{ "start": 11203, "end": 11400 }
class ____(models.Model): random_char_field = RandomCharField(length=8, lowercase=True, include_digits=False) class Meta: app_label = "django_extensions"
RandomCharTestModelLowercase
python
rushter__MLAlgorithms
mla/ensemble/gbm.py
{ "start": 4058, "end": 4237 }
class ____(GradientBoosting): def fit(self, X, y=None): self.loss = LeastSquaresLoss() super(GradientBoostingRegressor, self).fit(X, y)
GradientBoostingRegressor
python
getsentry__sentry
src/sentry/hybridcloud/services/organization_mapping/model.py
{ "start": 831, "end": 883 }
class ____(RpcModel): value: str | None
CustomerId
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_set_start_page03.py
{ "start": 315, "end": 1017 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("set_start_page03.xlsx") self.ignore_elements = {"xl/worksheets/sheet1.xml": ["<pageMargins"]} def test_create_file(self): """Test the creation of a simple XlsxWriter file with printer settings.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_start_page(101) worksheet.set_paper(9) worksheet.vertical_dpi = 200 worksheet.write("A1", "Foo") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
django__django
tests/utils_tests/test_autoreload.py
{ "start": 12988, "end": 13666 }
class ____(SimpleTestCase): @mock.patch("django.utils.autoreload.WatchmanReloader") def test_watchman_unavailable(self, mocked_watchman): mocked_watchman.check_availability.side_effect = WatchmanUnavailable self.assertIsInstance(autoreload.get_reloader(), autoreload.StatReloader) @mock.patch.object(autoreload.WatchmanReloader, "check_availability") def test_watchman_available(self, mocked_available): # If WatchmanUnavailable isn't raised, Watchman will be chosen. mocked_available.return_value = None result = autoreload.get_reloader() self.assertIsInstance(result, autoreload.WatchmanReloader)
GetReloaderTests
python
kamyu104__LeetCode-Solutions
Python/maximum-width-ramp.py
{ "start": 29, "end": 433 }
class ____(object): def maxWidthRamp(self, A): """ :type A: List[int] :rtype: int """ result = 0 s = [] for i in A: if not s or A[s[-1]] > A[i]: s.append(i) for j in reversed(xrange(len(A))): while s and A[s[-1]] <= A[j]: result = max(result, j-s.pop()) return result
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py
{ "start": 26433, "end": 26952 }
class ____(MetadataValue[AssetKey]): """Representation of a dagster asset. Args: asset_key (AssetKey): The dagster asset key """ asset_key: PublicAttr[AssetKey] @public @property def value(self) -> AssetKey: """AssetKey: The wrapped :py:class:`AssetKey`.""" return self.asset_key # This should be deprecated or fixed so that `value` does not return itself. @public @whitelist_for_serdes(storage_name="TableMetadataEntryData") @record_custom
DagsterAssetMetadataValue
python
weaviate__weaviate-python-client
weaviate/debug/async_.py
{ "start": 163, "end": 224 }
class ____(_DebugExecutor[ConnectionAsync]): pass
_DebugAsync
python
spyder-ide__spyder
spyder/plugins/findinfiles/widgets/results_browser.py
{ "start": 2233, "end": 3878 }
class ____(QTreeWidgetItem): def __init__(self, parent, path, filename, sorting, text_color): self.sorting = sorting self.filename = osp.basename(filename) # Get relative dirname according to the path we're searching in. dirname = osp.dirname(filename) # Catch errors when it's not possible to get the relative directory # name. This happens when the user is searching in a single file. # Fixes spyder-ide/spyder#17443 and spyder-ide/spyder#20964 try: rel_dirname = dirname.split(path)[1] if rel_dirname.startswith(osp.sep): rel_dirname = rel_dirname[1:] except IndexError: rel_dirname = dirname self.rel_dirname = rel_dirname title = ( f'<!-- FileMatchItem -->' f'<b style="color:{text_color}">{osp.basename(filename)}</b>' f'&nbsp;&nbsp;&nbsp;' f'<span style="color:{text_color}">' f'<em>{self.rel_dirname}</em>' f'</span>' ) super().__init__(parent, [title], QTreeWidgetItem.Type) self.setIcon(0, ima.get_icon_by_extension_or_type(filename, 1.0)) self.setToolTip(0, filename) def __lt__(self, x): if self.sorting['status'] == ON: return self.filename < x.filename else: return False def __ge__(self, x): if self.sorting['status'] == ON: return self.filename >= x.filename else: return False # ---- Browser # ----------------------------------------------------------------------------
FileMatchItem
python
spyder-ide__spyder
spyder/plugins/editor/widgets/recover.py
{ "start": 737, "end": 13407 }
class ____(QDialog): """Dialog window to allow users to recover from autosave files.""" def __init__(self, autosave_mapping, parent=None): """ Constructor Parameters ---------- autosave_mapping : List[Tuple[str]] List of tuples, containing the name of the original file and the name of the corresponding autosave file. The first entry of the tuple may be `None` to indicate that the original file is unknown. parent : QWidget, optional Parent of the dialog window. The default is None. """ QDialog.__init__(self, parent) self.layout = QVBoxLayout(self) self.setLayout(self.layout) self.layout.setSpacing(self.layout.spacing() * 3) self.files_to_open = [] self.gather_data(autosave_mapping) self.add_label() self.add_table() self.add_cancel_button() self.setWindowTitle(_('Recover from autosave')) self.setFixedSize(670, 400) self.setWindowFlags( Qt.Dialog | Qt.MSWindowsFixedSizeDialogHint | Qt.WindowStaysOnTopHint) # This is needed because of an error in MacOS. # See https://bugreports.qt.io/browse/QTBUG-49576 if parent and hasattr(parent, 'splash'): self.splash = parent.splash self.splash.hide() else: self.splash = None def accept(self): """Reimplement Qt method.""" if self.splash is not None: self.splash.show() super().accept() def reject(self): """Reimplement Qt method.""" if self.splash is not None: self.splash.show() super().reject() def gather_file_data(self, name): """ Gather data about a given file. Returns a dict with fields 'name', 'mtime' and 'size', containing the relevant data for the file. If the file does not exists, then the dict contains only the field `name`. """ res = {'name': name} try: res['mtime'] = osp.getmtime(name) res['size'] = osp.getsize(name) except OSError: pass return res def gather_data(self, autosave_mapping): """ Gather data about files which may be recovered. The data is stored in self.data as a list of tuples with the data pertaining to the original file and the autosave file. Each element of the tuple is a dict as returned by gather_file_data(). Autosave files which do not exist, are ignored. """ self.data = [] for orig, autosave in autosave_mapping: if orig: orig_dict = self.gather_file_data(orig) else: orig_dict = None autosave_dict = self.gather_file_data(autosave) if 'mtime' not in autosave_dict: # autosave file does not exist continue self.data.append((orig_dict, autosave_dict)) self.data.sort(key=self.recovery_data_key_function) self.num_enabled = len(self.data) def recovery_data_key_function(self, item): """ Convert item in `RecoveryDialog.data` to tuple so that it can be sorted. Sorting the tuples returned by this function will sort first by name of the original file, then by name of the autosave file. All items without an original file name will be at the end. """ orig_dict, autosave_dict = item if orig_dict: return (0, orig_dict['name'], autosave_dict['name']) else: return (1, 0, autosave_dict['name']) def add_label(self): """Add label with explanation at top of dialog window.""" txt = _('Autosave files found. What would you like to do?\n\n' 'This dialog will be shown again on next startup if any ' 'autosave files are not restored, moved or deleted.') label = QLabel(txt, self) label.setWordWrap(True) self.layout.addWidget(label) def add_label_to_table(self, row, col, txt): """Add a label to specified cell in table.""" label = QLabel(txt) label.setMargin(5) label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.table.setCellWidget(row, col, label) def add_table(self): """Add table with info about files to be recovered.""" table = QTableWidget(len(self.data), 3, self) self.table = table labels = [_('Original file'), _('Autosave file'), _('Actions')] table.setHorizontalHeaderLabels(labels) table.verticalHeader().hide() table.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) table.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) table.setSelectionMode(QTableWidget.NoSelection) # Show horizontal grid lines table.setShowGrid(False) table.setStyleSheet('::item { border-bottom: 1px solid gray }') for idx, (original, autosave) in enumerate(self.data): self.add_label_to_table(idx, 0, self.file_data_to_str(original)) self.add_label_to_table(idx, 1, self.file_data_to_str(autosave)) widget = QWidget() layout = QHBoxLayout() tooltip = _('Recover the autosave file to its original location, ' 'replacing the original if it exists.') button = QPushButton(_('Restore')) button.setToolTip(tooltip) button.clicked[bool].connect( lambda checked, my_idx=idx: self.restore(my_idx)) layout.addWidget(button) tooltip = _('Delete the autosave file.') button = QPushButton(_('Discard')) button.setToolTip(tooltip) button.clicked[bool].connect( lambda checked, my_idx=idx: self.discard(my_idx)) layout.addWidget(button) tooltip = _('Display the autosave file (and the original, if it ' 'exists) in Spyder\'s Editor. You will have to move ' 'or delete it manually.') button = QPushButton(_('Open')) button.setToolTip(tooltip) button.clicked[bool].connect( lambda checked, my_idx=idx: self.open_files(my_idx)) layout.addWidget(button) widget.setLayout(layout) self.table.setCellWidget(idx, 2, widget) table.resizeRowsToContents() table.resizeColumnsToContents() self.layout.addWidget(table) def file_data_to_str(self, data): """ Convert file data to a string for display. This function takes the file data produced by gather_file_data(). """ if not data: return _('<i>File name not recorded</i>') res = data['name'] try: mtime_as_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['mtime'])) res += '<br><i>{}</i>: {}'.format(_('Last modified'), mtime_as_str) res += u'<br><i>{}</i>: {} {}'.format( _('Size'), data['size'], _('bytes')) except KeyError: res += '<br>' + _('<i>File no longer exists</i>') return res def add_cancel_button(self): """Add a cancel button at the bottom of the dialog window.""" button_box = SpyderDialogButtonBox( QDialogButtonBox.Cancel, parent=self ) button_box.rejected.connect(self.reject) self.layout.addWidget(button_box) def center(self): """Center the dialog.""" screen = self.screen().geometry() x = int(screen.center().x() - self.width() / 2) y = int(screen.center().y() - self.height() / 2) self.move(x, y) def restore(self, idx): orig, autosave = self.data[idx] if orig: orig_name = orig['name'] else: orig_name, ignored = getsavefilename( self, _('Restore autosave file to ...'), osp.basename(autosave['name'])) if not orig_name: return try: try: os.replace(autosave['name'], orig_name) except (AttributeError, OSError): # os.replace() does not exist on Python 2 and fails if the # files are on different file systems. # See spyder-ide/spyder#8631. shutil.copy2(autosave['name'], orig_name) os.remove(autosave['name']) self.deactivate(idx) except EnvironmentError as error: text = (_('Unable to restore {} using {}') .format(orig_name, autosave['name'])) self.report_error(text, error) def discard(self, idx): ignored, autosave = self.data[idx] try: os.remove(autosave['name']) self.deactivate(idx) except EnvironmentError as error: text = _('Unable to discard {}').format(autosave['name']) self.report_error(text, error) def open_files(self, idx): orig, autosave = self.data[idx] if orig: self.files_to_open.append(orig['name']) self.files_to_open.append(autosave['name']) self.deactivate(idx) def report_error(self, text, error): heading = _('Error message:') msgbox = QMessageBox( QMessageBox.Critical, _('Restore'), _('<b>{}</b><br><br>{}<br>{}').format(text, heading, error), parent=self) msgbox.exec_() def deactivate(self, idx): for col in range(self.table.columnCount()): self.table.cellWidget(idx, col).setEnabled(False) self.num_enabled -= 1 if self.num_enabled == 0: self.accept() def exec_if_nonempty(self): """Execute dialog window if there is data to show.""" if self.data: self.center() return self.exec_() else: return QDialog.Accepted def exec_(self): """Execute dialog window.""" if running_under_pytest(): return QDialog.Accepted return super().exec_() def make_temporary_files(tempdir): """ Make temporary files to simulate a recovery use case. Create a directory under tempdir containing some original files and another directory with autosave files. Return a tuple with the name of the directory with the original files, the name of the directory with the autosave files, and the autosave mapping. """ orig_dir = osp.join(tempdir, 'orig') os.mkdir(orig_dir) autosave_dir = osp.join(tempdir, 'autosave') os.mkdir(autosave_dir) autosave_mapping = {} # ham.py: Both original and autosave files exist, mentioned in mapping orig_file = osp.join(orig_dir, 'ham.py') with open(orig_file, 'w') as f: f.write('ham = "original"\n') autosave_file = osp.join(autosave_dir, 'ham.py') with open(autosave_file, 'w') as f: f.write('ham = "autosave"\n') autosave_mapping = [(orig_file, autosave_file)] # spam.py: Only autosave file exists, mentioned in mapping orig_file = osp.join(orig_dir, 'spam.py') autosave_file = osp.join(autosave_dir, 'spam.py') with open(autosave_file, 'w') as f: f.write('spam = "autosave"\n') autosave_mapping += [(orig_file, autosave_file)] # eggs.py: Only original files exists, mentioned in mapping orig_file = osp.join(orig_dir, 'eggs.py') with open(orig_file, 'w') as f: f.write('eggs = "original"\n') autosave_file = osp.join(autosave_dir, 'eggs.py') autosave_mapping += [(orig_file, autosave_file)] # cheese.py: Only autosave file exists autosave_file = osp.join(autosave_dir, 'cheese.py') with open(autosave_file, 'w') as f: f.write('cheese = "autosave"\n') autosave_mapping += [(None, autosave_file)] return orig_dir, autosave_dir, autosave_mapping def test(): # pragma: no cover """Display recovery dialog for manual testing.""" import shutil import tempfile from spyder.utils.qthelpers import qapplication app = qapplication() # noqa tempdir = tempfile.mkdtemp() unused, unused, autosave_mapping = make_temporary_files(tempdir) dialog = RecoveryDialog(autosave_mapping) dialog.exec_() print('files_to_open =', dialog.files_to_open) # spyder: test-skip shutil.rmtree(tempdir) if __name__ == "__main__": # pragma: no cover test()
RecoveryDialog
python
dagster-io__dagster
scripts/gen_airbyte_classes.py
{ "start": 4435, "end": 5410 }
class ____(SchemaType): def __init__(self, inner: SchemaType): self.inner = inner def __str__(self): return f"Optional[{self.inner}]" def annotation( self, scope: Optional[str] = None, quote: bool = False, hide_default: bool = False ): return f"Optional[{self.inner.annotation(scope, quote, hide_default)}]{' = None' if not hide_default else ''}" def get_check(self, name: str, scope: Optional[str] = None): inner_check = self.inner.get_check(name, scope) # For ListType, we want to make sure that the value does not default to an empty list # if it is not provided, so we use opt_nullable_list_param instead of opt_list_param # see https://github.com/dagster-io/dagster/pull/10272#discussion_r1016035044 for more if isinstance(self.inner, ListType): return ".opt_nullable_".join(inner_check.split(".", 1)) return ".opt_".join(inner_check.split(".", 1))
OptType
python
dagster-io__dagster
python_modules/libraries/dagster-dlt/dagster_dlt/components/dlt_load_collection/scaffolder.py
{ "start": 3532, "end": 6327 }
class ____(Scaffolder[DltScaffolderParams]): @classmethod def get_scaffold_params(cls) -> type[DltScaffolderParams]: return DltScaffolderParams def scaffold(self, request: ScaffoldRequest[DltScaffolderParams]) -> None: with pushd(str(request.target_path)): Path.cwd().mkdir(parents=True, exist_ok=True) # Given source and destination, we can use dlt init to scaffold the source # code and some sample pipelines and sources. if request.params and request.params.source and request.params.destination: yes = subprocess.Popen(["yes", "y"], stdout=subprocess.PIPE) try: subprocess.check_call( ["dlt", "init", request.params.source, request.params.destination], stdin=yes.stdout, ) finally: yes.kill() # dlt init scaffolds a Python file with some example pipelines, nested in functions # we extract them into top-level objects which we stash in loads.py as a sample examples_python_file = next(Path(".").glob("*.py")) examples_python_file.unlink() for file in DLT_INIT_FILES_TO_CLEAN_UP: if Path(file).is_dir(): shutil.rmtree(file) else: Path(file).unlink() elif request.params and (request.params.source or request.params.destination): raise ValueError("Must provide neither or both of source and destination") Path("loads.py").write_text( textwrap.dedent( """ import dlt @dlt.source def my_source(): @dlt.resource def hello_world(): yield "hello, world!" return hello_world my_load_source = my_source() my_load_pipeline = dlt.pipeline({destination}) """ ).format( destination=f'destination="{request.params.destination}"' if request.params and request.params.destination else "", ) ) _format_file_if_ruff_installed(Path("loads.py")) scaffold_component( request=request, yaml_attributes={ "loads": [ { "source": ".loads.my_load_source", "pipeline": ".loads.my_load_pipeline", } ] }, )
DltLoadCollectionScaffolder
python
huggingface__transformers
src/transformers/models/sam2/modular_sam2.py
{ "start": 48949, "end": 64307 }
class ____(SamModel): _keys_to_ignore_on_load_unexpected = [ r"^memory_.*", r"^mask_downsample.*", r"^object_pointer_proj.*", r"^temporal_positional_encoding_projection_layer.*", "no_memory_positional_encoding", "no_object_pointer", "occlusion_spatial_embedding_parameter", ] def __init__(self, config: Sam2Config): PreTrainedModel.__init__(self, config) self.shared_image_embedding = Sam2PositionalEmbedding(config.prompt_encoder_config) self.vision_encoder = AutoModel.from_config(config.vision_config) self.prompt_encoder = Sam2PromptEncoder(config.prompt_encoder_config) # The module using it is not a PreTrainedModel subclass so we need this config.mask_decoder_config._attn_implementation = config._attn_implementation self.mask_decoder = Sam2MaskDecoder(config.mask_decoder_config) self.num_feature_levels = config.vision_config.num_feature_levels self.backbone_feature_sizes = config.vision_config.backbone_feature_sizes # a single token to indicate no memory embedding from previous frames self.hidden_dim = config.vision_config.fpn_hidden_size self.no_memory_embedding = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) self.post_init() def get_image_wide_positional_embeddings(self) -> torch.Tensor: size = self.prompt_encoder.image_embedding_size target_device = self.shared_image_embedding.positional_embedding.device target_dtype = self.shared_image_embedding.positional_embedding.dtype grid = torch.ones(size, device=target_device, dtype=target_dtype) y_embed = grid.cumsum(dim=0) - 0.5 x_embed = grid.cumsum(dim=1) - 0.5 y_embed = y_embed / size[0] x_embed = x_embed / size[1] positional_embedding = self.shared_image_embedding(torch.stack([x_embed, y_embed], dim=-1)) return positional_embedding.permute(2, 0, 1).unsqueeze(0) # channel x height x width @torch.no_grad() def get_image_embeddings( self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs], ) -> list[torch.Tensor]: r""" Returns the image embeddings by passing the pixel values through the vision encoder. Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Input pixel values """ batch_size = pixel_values.shape[0] feature_maps, _, _, _ = self.get_image_features(pixel_values, **kwargs) # add no memory embedding to the last feature map feature_maps[-1] = feature_maps[-1] + self.no_memory_embedding # reshape feature maps to the same shape as the backbone feature sizes image_embeddings = [ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) for feat, feat_size in zip(feature_maps, self.backbone_feature_sizes) ] return image_embeddings def get_image_features( self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs], ) -> tuple[ list[torch.Tensor], list[torch.Tensor], Optional[tuple[torch.FloatTensor, ...]], Optional[tuple[torch.FloatTensor, ...]], ]: r""" Extract and preprocess image features using the vision encoder. Args: pixel_values (`torch.FloatTensor`): Input pixel values of shape `(batch_size, num_channels, height, width)`. Returns: `tuple`: A tuple containing: - feature_maps (`list[torch.Tensor]`): List of feature maps from different levels. - feature_maps_position_embeddings (`list[torch.Tensor]`): List of positional embeddings for each feature level. - vision_hidden_states (`tuple[torch.FloatTensor]`, *optional*): Hidden states from the vision encoder. - vision_attentions (`tuple[torch.FloatTensor]`, *optional*): Attention weights from the vision encoder. """ vision_outputs: Sam2VisionEncoderOutput = self.vision_encoder( pixel_values, **kwargs, ) feature_maps = vision_outputs.fpn_hidden_states feature_maps_position_embeddings = vision_outputs.fpn_position_encoding # precompute projected level 0 and level 1 features in SAM decoder # to avoid running it again on every SAM click feature_maps = list(feature_maps) feature_maps[0] = self.mask_decoder.conv_s0(feature_maps[0]) feature_maps[1] = self.mask_decoder.conv_s1(feature_maps[1]) # flatten NxCxHxW to HWxNxC feature_maps = [feature_map.flatten(2).permute(2, 0, 1) for feature_map in feature_maps] feature_maps_position_embeddings = [ feature_map_position_embedding.flatten(2).permute(2, 0, 1) for feature_map_position_embedding in feature_maps_position_embeddings ] return feature_maps, feature_maps_position_embeddings, vision_outputs.hidden_states, vision_outputs.attentions @check_model_inputs() @auto_docstring def forward( self, pixel_values: Optional[torch.FloatTensor] = None, input_points: Optional[torch.FloatTensor] = None, input_labels: Optional[torch.LongTensor] = None, input_boxes: Optional[torch.FloatTensor] = None, input_masks: Optional[torch.LongTensor] = None, image_embeddings: Optional[torch.FloatTensor] = None, multimask_output: bool = True, attention_similarity: Optional[torch.FloatTensor] = None, target_embedding: Optional[torch.FloatTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Sam2ImageSegmentationOutput: r""" input_points (`torch.FloatTensor` of shape `(batch_size, num_points, 2)`): Input 2D spatial points, this is used by the prompt encoder to encode the prompt. Generally yields to much better results. The points can be obtained by passing a list of list of list to the processor that will create corresponding `torch` tensors of dimension 4. The first dimension is the image batch size, the second dimension is the point batch size (i.e. how many segmentation masks do we want the model to predict per input point), the third dimension is the number of points per segmentation mask (it is possible to pass multiple points for a single mask), and the last dimension is the x (vertical) and y (horizontal) coordinates of the point. If a different number of points is passed either for each image, or for each mask, the processor will create "PAD" points that will correspond to the (0, 0) coordinate, and the computation of the embedding will be skipped for these points using the labels. input_labels (`torch.LongTensor` of shape `(batch_size, point_batch_size, num_points)`): Input labels for the points, this is used by the prompt encoder to encode the prompt. According to the official implementation, there are 3 types of labels - `1`: the point is a point that contains the object of interest - `0`: the point is a point that does not contain the object of interest - `-1`: the point corresponds to the background We added the label: - `-10`: the point is a padding point, thus should be ignored by the prompt encoder The padding labels should be automatically done by the processor. input_boxes (`torch.FloatTensor` of shape `(batch_size, num_boxes, 4)`): Input boxes for the points, this is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks. The boxes can be obtained by passing a list of list of list to the processor, that will generate a `torch` tensor, with each dimension corresponding respectively to the image batch size, the number of boxes per image and the coordinates of the top left and bottom right point of the box. In the order (`x1`, `y1`, `x2`, `y2`): - `x1`: the x coordinate of the top left point of the input box - `y1`: the y coordinate of the top left point of the input box - `x2`: the x coordinate of the bottom right point of the input box - `y2`: the y coordinate of the bottom right point of the input box input_masks (`torch.FloatTensor` of shape `(batch_size, image_size, image_size)`): SAM model also accepts segmentation masks as input. The mask will be embedded by the prompt encoder to generate a corresponding embedding, that will be fed later on to the mask decoder. These masks needs to be manually fed by the user, and they need to be of shape (`batch_size`, `image_size`, `image_size`). image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_channels, window_size, window_size)`): Image embeddings, this is used by the mask decoder to generate masks and iou scores. For more memory efficient computation, users can first retrieve the image embeddings using the `get_image_embeddings` method, and then feed them to the `forward` method instead of feeding the `pixel_values`. multimask_output (`bool`, *optional*): In the original implementation and paper, the model always outputs 3 masks per image (or per point / per bounding box if relevant). However, it is possible to just output a single mask, that corresponds to the "best" mask, by specifying `multimask_output=False`. attention_similarity (`torch.FloatTensor`, *optional*): Attention similarity tensor, to be provided to the mask decoder for target-guided attention in case the model is used for personalization as introduced in [PerSAM](https://huggingface.co/papers/2305.03048). target_embedding (`torch.FloatTensor`, *optional*): Embedding of the target concept, to be provided to the mask decoder for target-semantic prompting in case the model is used for personalization as introduced in [PerSAM](https://huggingface.co/papers/2305.03048). Example: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoModel, AutoProcessor >>> model = AutoModel.from_pretrained("danelcsb/sam2.1_hiera_tiny") >>> processor = AutoProcessor.from_pretrained("danelcsb/sam2.1_hiera_tiny") >>> img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png" >>> raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB") >>> input_points = [[[400, 650]]] # 2D location of a window on the car >>> inputs = processor(images=raw_image, input_points=input_points, return_tensors="pt") >>> # Get segmentation mask >>> outputs = model(**inputs) >>> # Postprocess masks >>> masks = processor.post_process_masks( ... outputs.pred_masks, inputs["original_sizes"] ... ) ``` """ if not ((pixel_values is None) ^ (image_embeddings is None)): raise ValueError("Exactly one of pixel_values or image_embeddings must be provided.") if input_points is not None and input_boxes is not None: if input_points.shape[1] != input_boxes.shape[1]: raise ValueError( f"You should provide as many bounding boxes as input points per box. Got {input_points.shape[1]} and {input_boxes.shape[1]}." ) image_positional_embeddings = self.get_image_wide_positional_embeddings() # repeat with batch size batch_size = pixel_values.shape[0] if pixel_values is not None else image_embeddings[-1].shape[0] image_positional_embeddings = image_positional_embeddings.repeat(batch_size, 1, 1, 1) vision_attentions = None vision_hidden_states = None if pixel_values is not None: feature_maps, _, vision_hidden_states, vision_attentions = self.get_image_features( pixel_values, **kwargs, ) # add no memory embedding to the last feature map feature_maps[-1] = feature_maps[-1] + self.no_memory_embedding # reshape feature maps to the same shape as the backbone feature sizes image_embeddings = [ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) for feat, feat_size in zip(feature_maps, self.backbone_feature_sizes) ] if input_points is not None and input_labels is None: input_labels = torch.ones_like(input_points[:, :, :, 0], dtype=torch.int, device=input_points.device) if input_points is None and input_boxes is None: # If no points are provide, pad with an empty point (with label -1) input_points = torch.zeros( batch_size, 1, 1, 2, dtype=image_embeddings[-1].dtype, device=image_embeddings[-1].device ) input_labels = -torch.ones(batch_size, 1, 1, dtype=torch.int32, device=image_embeddings[-1].device) if input_masks is not None: # If mask_inputs is provided, downsize it into low-res mask input if needed # and feed it as a dense mask prompt into the SAM mask encoder if input_masks.shape[-2:] != self.prompt_encoder.mask_input_size: input_masks = F.interpolate( input_masks.float(), size=self.prompt_encoder.mask_input_size, align_corners=False, mode="bilinear", antialias=True, # use antialias for downsampling ).to(input_masks.dtype) sparse_embeddings, dense_embeddings = self.prompt_encoder( input_points=input_points, input_labels=input_labels, input_boxes=input_boxes, input_masks=input_masks, ) low_res_multimasks, iou_scores, _, object_score_logits = self.mask_decoder( image_embeddings=image_embeddings[-1], image_positional_embeddings=image_positional_embeddings, sparse_prompt_embeddings=sparse_embeddings, dense_prompt_embeddings=dense_embeddings, multimask_output=multimask_output, high_resolution_features=image_embeddings[:-1], attention_similarity=attention_similarity, target_embedding=target_embedding, **kwargs, ) return Sam2ImageSegmentationOutput( iou_scores=iou_scores, pred_masks=low_res_multimasks, object_score_logits=object_score_logits, image_embeddings=image_embeddings, vision_hidden_states=vision_hidden_states, vision_attentions=vision_attentions, ) __all__ = [ "Sam2Model", "Sam2VisionModel", "Sam2PreTrainedModel", "Sam2ImageProcessorFast", "Sam2HieraDetModel", ]
Sam2Model
python
getsentry__sentry
src/sentry/preprod/migrations/0008_make_preprod_analysis_file_id_in_size_metrics_table.py
{ "start": 186, "end": 1543 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("preprod", "0007_add_install_file"), ] operations = [ migrations.AddField( model_name="preprodartifactsizemetrics", name="analysis_file_id", field=sentry.db.models.fields.bounded.BoundedBigIntegerField(db_index=True, null=True), ), ]
Migration
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 63678, "end": 64173 }
class ____(OrderedSetAgg[_T]): """Implement the ``percentile_disc`` ordered-set aggregate function. This function must be used with the :meth:`.FunctionElement.within_group` modifier to supply a sort expression to operate upon. The return type of this function is the same as the sort expression, or if the arguments are an array, an :class:`_types.ARRAY` of the sort expression's type. """ array_for_multi_clause = True inherit_cache = True
percentile_disc
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/util_test.py
{ "start": 17426, "end": 18991 }
class ____(test.TestCase): def _np_rotate_transpose(self, x, shift): if not isinstance(x, np.ndarray): x = np.array(x) return np.transpose(x, np.roll(np.arange(len(x.shape)), shift)) @test_util.run_in_graph_and_eager_modes def testRollStatic(self): if context.executing_eagerly(): error_message = r"Attempt to convert a value \(None\)" else: error_message = "None values not supported." with self.assertRaisesRegex(ValueError, error_message): du.rotate_transpose(None, 1) for x in (np.ones(1), np.ones((2, 1)), np.ones((3, 2, 1))): for shift in np.arange(-5, 5): y = du.rotate_transpose(x, shift) self.assertAllEqual( self._np_rotate_transpose(x, shift), self.evaluate(y)) self.assertAllEqual(np.roll(x.shape, shift), y.get_shape().as_list()) @test_util.run_deprecated_v1 def testRollDynamic(self): with self.cached_session() as sess: x = array_ops.placeholder(dtypes.float32) shift = array_ops.placeholder(dtypes.int32) for x_value in (np.ones( 1, dtype=x.dtype.as_numpy_dtype()), np.ones( (2, 1), dtype=x.dtype.as_numpy_dtype()), np.ones( (3, 2, 1), dtype=x.dtype.as_numpy_dtype())): for shift_value in np.arange(-5, 5): self.assertAllEqual( self._np_rotate_transpose(x_value, shift_value), sess.run(du.rotate_transpose(x, shift), feed_dict={x: x_value, shift: shift_value}))
RotateTransposeTest