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
great-expectations__great_expectations
great_expectations/core/expectation_diagnostics/supporting_types.py
{ "start": 3728, "end": 4070 }
class ____(SerializableDictDot): """Captures which of the three Execution Engines are supported by an Expectation. Used within the ExpectationDiagnostic object.""" # noqa: E501 # FIXME CoP PandasExecutionEngine: bool SqlAlchemyExecutionEngine: bool SparkDFExecutionEngine: bool @dataclass
ExpectationExecutionEngineDiagnostics
python
run-llama__llama_index
docs/examples/output_parsing/directory.py
{ "start": 1112, "end": 1414 }
class ____(BaseModel): """ Container class representing a directory tree. Args: root (Node): The root node of the tree. """ root: Node = Field(..., description="Root folder of the directory tree") Node.update_forward_refs() DirectoryTree.update_forward_refs()
DirectoryTree
python
pytorch__pytorch
torch/_functorch/pyfunctorch.py
{ "start": 6510, "end": 7830 }
class ____(FuncTorchInterpreter): def __init__(self, cdata: CInterpreter): assert cdata.key() == TransformType.Jvp # See NOTE: [Interpreter cdata vs cptr] self._cdata = cdata @cached_property # pyrefly: ignore [bad-override] def _cptr(self): return CJvpInterpreterPtr(self._cdata) def lift(self, args, kwargs): args, kwargs = pytree.tree_map_only( torch.Tensor, self._cptr.lift, [args, kwargs] ) return args, kwargs def process(self, op, args, kwargs): kernel = op.functorch_table[TransformType.Jvp] args, kwargs = self.lift(args, kwargs) return kernel(self, *args, **kwargs) # Jvp has custom lower because of the no_fwd_grad interaction # See NOTE [grad and vjp interaction with no_grad] for related info. # This logic is mirrored from C++ JvpInterpreterPtr::sendToNextInterpreter def lower(self): prev_fwd_grad_mode = self.prev_fwd_grad_mode() if not prev_fwd_grad_mode: return nested(_set_fwd_grad_enabled(False), super().lower()) return super().lower() def prev_fwd_grad_mode(self): return self._cptr.prevFwdGradMode() def get_state(self): return (self.key().name, self.level(), self.prev_fwd_grad_mode())
JvpInterpreter
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 384982, "end": 388205 }
class ____(Request): """ Mark a task status as in_progress. Optionally allows to set the task's execution progress. :param force: If not true, call fails if the task status is not 'not_started' :type force: bool :param task: Task ID :type task: str :param status_reason: Reason for status change :type status_reason: str :param status_message: Extra information regarding status change :type status_message: str """ _service = "tasks" _action = "started" _version = "2.20" _schema = { "definitions": {}, "properties": { "force": { "default": False, "description": "If not true, call fails if the task status is not 'not_started'", "type": ["boolean", "null"], }, "status_message": { "description": "Extra information regarding status change", "type": "string", }, "status_reason": { "description": "Reason for status change", "type": "string", }, "task": {"description": "Task ID", "type": "string"}, }, "required": ["task"], "type": "object", } def __init__( self, task: str, force: Optional[bool] = False, status_reason: Optional[str] = None, status_message: Optional[str] = None, **kwargs: Any ) -> None: super(StartedRequest, self).__init__(**kwargs) self.force = force self.task = task self.status_reason = status_reason self.status_message = status_message @schema_property("force") def force(self) -> Optional[bool]: return self._property_force @force.setter def force(self, value: Optional[bool]) -> None: if value is None: self._property_force = None return self.assert_isinstance(value, "force", (bool,)) self._property_force = value @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("status_reason") def status_reason(self) -> Optional[str]: return self._property_status_reason @status_reason.setter def status_reason(self, value: Optional[str]) -> None: if value is None: self._property_status_reason = None return self.assert_isinstance(value, "status_reason", six.string_types) self._property_status_reason = value @schema_property("status_message") def status_message(self) -> Optional[str]: return self._property_status_message @status_message.setter def status_message(self, value: Optional[str]) -> None: if value is None: self._property_status_message = None return self.assert_isinstance(value, "status_message", six.string_types) self._property_status_message = value
StartedRequest
python
PrefectHQ__prefect
src/prefect/server/utilities/messaging/memory.py
{ "start": 10820, "end": 13092 }
class ____(_Consumer): def __init__( self, topic: str, subscription: Optional[Subscription] = None, concurrency: int = 2, **kwargs: Any, ): self.topic: Topic = Topic.by_name(topic) if not subscription: subscription = self.topic.subscribe() assert subscription.topic is self.topic self.subscription = subscription self.concurrency = concurrency async def run(self, handler: MessageHandler) -> None: try: async with anyio.create_task_group() as tg: for _ in range(self.concurrency): tg.start_soon(self._consume_loop, handler) except BaseExceptionGroup as group: # novermin if all(isinstance(exc, StopConsumer) for exc in group.exceptions): logger.debug("StopConsumer received") return # Exit cleanly when all tasks stop # Re-raise if any non-StopConsumer exceptions raise group async def cleanup(self) -> None: """ Cleanup resources by unsubscribing from the topic. This should be called when the consumer is no longer needed to prevent memory leaks from orphaned subscriptions. """ self.topic.unsubscribe(self.subscription) logger.debug("Unsubscribed from topic=%r", self.topic.name) async def _consume_loop(self, handler: MessageHandler) -> None: while True: message = await self.subscription.get() try: await handler(message) await update_metric(self.topic.name, "consumed") except StopConsumer as e: if not e.ack: await self.subscription.retry(message) raise # Propagate to task group except Exception: logger.exception("Failed in consume_loop") await self.subscription.retry(message) @asynccontextmanager async def ephemeral_subscription(topic: str) -> AsyncGenerator[Mapping[str, Any], None]: subscription = Topic.by_name(topic).subscribe() try: yield {"topic": topic, "subscription": subscription} finally: Topic.by_name(topic).unsubscribe(subscription)
Consumer
python
kamyu104__LeetCode-Solutions
Python/paint-house.py
{ "start": 790, "end": 1254 }
class ____(object): def minCost(self, costs): """ :type costs: List[List[int]] :rtype: int """ if not costs: return 0 n = len(costs) for i in xrange(1, n): costs[i][0] += min(costs[i - 1][1], costs[i - 1][2]) costs[i][1] += min(costs[i - 1][0], costs[i - 1][2]) costs[i][2] += min(costs[i - 1][0], costs[i - 1][1]) return min(costs[n - 1])
Solution2
python
coleifer__peewee
tests/sqlite.py
{ "start": 2702, "end": 2894 }
class ____(FTSModel, TestModel): c1 = SearchField() c2 = SearchField() c3 = SearchField() c4 = IntegerField() class Meta: options = {'tokenize': 'porter'}
MultiColumn
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 319063, "end": 320412 }
class ____(StatNode): # Generated in the optimization of an if-elif-else node # # conditions [ExprNode] # body StatNode child_attrs = ['conditions', 'body'] def generate_condition_evaluation_code(self, code): for cond in self.conditions: cond.generate_evaluation_code(code) def generate_execution_code(self, code): num_conditions = len(self.conditions) line_tracing_enabled = code.globalstate.directives['linetrace'] for i, cond in enumerate(self.conditions, 1): code.putln("case %s:" % cond.result()) code.mark_pos(cond.pos) # Tracing code must appear *after* the 'case' statement. if line_tracing_enabled and i < num_conditions: # Allow fall-through after the line tracing code. code.putln('CYTHON_FALLTHROUGH;') self.body.generate_execution_code(code) code.mark_pos(self.pos, trace=False) code.putln("break;") def generate_function_definitions(self, env, code): for cond in self.conditions: cond.generate_function_definitions(env, code) self.body.generate_function_definitions(env, code) def annotate(self, code): for cond in self.conditions: cond.annotate(code) self.body.annotate(code)
SwitchCaseNode
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1263518, "end": 1263713 }
class ____(VegaLiteSchema): """StandardType schema wrapper.""" _schema = {"$ref": "#/definitions/StandardType"} def __init__(self, *args): super().__init__(*args)
StandardType
python
ansible__ansible
test/lib/ansible_test/_internal/bootstrap.py
{ "start": 1686, "end": 2085 }
class ____(Bootstrap): """Bootstrap docker instances.""" def get_variables(self) -> dict[str, t.Union[str, list[str]]]: """The variables to template in the bootstrapping script.""" variables = super().get_variables() variables.update( platform='', platform_version='', ) return variables @dataclasses.dataclass
BootstrapDocker
python
sympy__sympy
sympy/physics/quantum/piab.py
{ "start": 671, "end": 1016 }
class ____(HermitianOperator): """Particle in a box Hamiltonian operator.""" @classmethod def _eval_hilbert_space(cls, label): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PIABKet(self, ket, **options): n = ket.label[0] return (n**2*pi**2*hbar**2)/(2*m*L**2)*ket
PIABHamiltonian
python
wandb__wandb
wandb/apis/public/registries/registries_search.py
{ "start": 1100, "end": 4402 }
class ____(RelayPaginator["RegistryFragment", "Registry"]): """A lazy iterator of `Registry` objects.""" QUERY: ClassVar[Document | None] = None last_response: RegistryConnection | None def __init__( self, client: RetryingClient, organization: str, filter: dict[str, Any] | None = None, per_page: PositiveInt = 100, ): if self.QUERY is None: from wandb.sdk.artifacts._generated import FETCH_REGISTRIES_GQL type(self).QUERY = gql(FETCH_REGISTRIES_GQL) self.client = client self.organization = organization self.filter = ensure_registry_prefix_on_names(filter or {}) variables = {"organization": organization, "filters": json.dumps(self.filter)} super().__init__(client, variables=variables, per_page=per_page) def __next__(self): # Implement custom next since its possible to load empty pages because of auth self.index += 1 while len(self.objects) <= self.index: if not self._load_page(): raise StopIteration return self.objects[self.index] @tracked def collections( self, filter: dict[str, Any] | None = None, per_page: PositiveInt = 100 ) -> Collections: return Collections( client=self.client, organization=self.organization, registry_filter=self.filter, collection_filter=filter, per_page=per_page, ) @tracked def versions( self, filter: dict[str, Any] | None = None, per_page: PositiveInt = 100 ) -> Versions: return Versions( client=self.client, organization=self.organization, registry_filter=self.filter, collection_filter=None, artifact_filter=filter, per_page=per_page, ) @property def length(self): if self.last_response is None: return None return len(self.last_response.edges) @override def _update_response(self) -> None: from wandb.sdk.artifacts._generated import FetchRegistries from wandb.sdk.artifacts._models.pagination import RegistryConnection data = self.client.execute(self.QUERY, variable_values=self.variables) result = FetchRegistries.model_validate(data) if not ((org := result.organization) and (org_entity := org.org_entity)): raise ValueError( f"Organization {self.organization!r} not found. Please verify the organization name is correct." ) try: conn = org_entity.projects self.last_response = RegistryConnection.model_validate(conn) except (LookupError, AttributeError, ValidationError) as e: raise ValueError("Unexpected response data") from e def _convert(self, node: RegistryFragment) -> Registry: from wandb.apis.public.registries.registry import Registry from wandb.sdk.artifacts._validators import remove_registry_prefix return Registry( client=self.client, organization=self.organization, entity=node.entity.name, name=remove_registry_prefix(node.name), attrs=node, )
Registries
python
joke2k__faker
faker/providers/internet/fr_CH/__init__.py
{ "start": 46, "end": 754 }
class ____(InternetProvider): safe_email_tlds = ("org", "com", "net", "ch") free_email_domains = ( "gmail.com", "hotmail.fr", "yahoo.fr", "bluewin.ch", "romandie.com", "hispeed.ch", "sunrise.ch", "vtxnet.ch", ) tlds = ("com", "com", "com", "net", "org", "ch", "ch", "ch") replacements = ( ("ä", "ae"), ("à", "a"), ("â", "a"), ("ç", "c"), ("é", "e"), ("è", "e"), ("ê", "e"), ("ë", "e"), ("ï", "i"), ("î", "i"), ("ö", "oe"), ("ô", "o"), ("ü", "ue"), ("ù", "u"), ("ü", "u"), ("ß", "ss"), )
Provider
python
PyCQA__pylint
tests/functional/u/unused/unused_import_everything_disabled.py
{ "start": 277, "end": 444 }
class ____: """For the bug reported in #6089 it is important to use the same names for the class attributes as in the imports.""" e = float(e) pi = pi
MyClass
python
fabric__fabric
tests/transfer.py
{ "start": 301, "end": 12204 }
class ____: class init: "__init__" def requires_connection(self): # Transfer() -> explodes try: Transfer() except TypeError: pass else: assert False, "Did not raise ArgumentError" # Transfer(Connection()) -> happy, exposes an attribute cxn = Connection("host") assert Transfer(cxn).connection is cxn class is_remote_dir: def returns_bool_of_stat_ISDIR_flag(self, sftp_objs): xfer, sftp = sftp_objs # Default mocked st_mode is file-like (first octal digit is 1) assert xfer.is_remote_dir("whatever") is False # Set mode directory-ish (first octal digit is 4) sftp.stat.return_value.st_mode = 0o41777 assert xfer.is_remote_dir("whatever") is True def returns_False_if_stat_raises_IOError(self, sftp_objs): xfer, sftp = sftp_objs sftp.stat.side_effect = IOError assert xfer.is_remote_dir("whatever") is False class get: class basics: def accepts_single_remote_path_posarg(self, sftp_objs): transfer, client = sftp_objs transfer.get("file") client.get.assert_called_with( localpath="/local/file", remotepath="/remote/file" ) def accepts_local_and_remote_kwargs(self, sftp_objs): transfer, client = sftp_objs transfer.get(remote="path1", local="path2") client.get.assert_called_with( remotepath="/remote/path1", localpath="/local/path2" ) def returns_rich_Result_object(self, sftp_objs): transfer, client = sftp_objs cxn = Connection("host") result = Transfer(cxn).get("file") assert result.orig_remote == "file" assert result.remote == "/remote/file" assert result.orig_local is None assert result.local == "/local/file" assert result.connection is cxn # TODO: timing info # TODO: bytes-transferred info class path_arg_edge_cases: def local_None_uses_remote_filename(self, transfer): assert transfer.get("file").local == "/local/file" def local_empty_string_uses_remote_filename(self, transfer): assert transfer.get("file", local="").local == "/local/file" @raises(TypeError) def remote_arg_is_required(self, transfer): transfer.get() @raises(ValueError) def remote_arg_cannot_be_None(self, transfer): transfer.get(None) @raises(ValueError) def remote_arg_cannot_be_empty_string(self, transfer): transfer.get("") class local_arg_interpolation: def connection_params(self, transfer): result = transfer.get("somefile", "{user}@{host}-{port}") expected = "/local/{}@host-22".format(transfer.connection.user) assert result.local == expected def connection_params_as_dir(self, transfer): result = transfer.get("somefile", "{host}/") assert result.local == "/local/host/somefile" def remote_path_posixpath_bits(self, transfer): result = transfer.get( "parent/mid/leaf", "foo/{dirname}/bar/{basename}" ) # Recall that test harness sets remote apparent cwd as # /remote/, thus dirname is /remote/parent/mid assert result.local == "/local/foo/remote/parent/mid/bar/leaf" class file_like_local_paths: "file-like local paths" def _get_to_stringio(self, sftp_objs): transfer, client = sftp_objs fd = StringIO() result = transfer.get("file", local=fd) # Note: getfo, not get client.getfo.assert_called_with( remotepath="/remote/file", fl=fd ) return result, fd def remote_path_to_local_StringIO(self, sftp_objs): self._get_to_stringio(sftp_objs) def result_contains_fd_for_local_path(self, sftp_objs): result, fd = self._get_to_stringio(sftp_objs) assert result.remote == "/remote/file" assert result.local is fd class mode_concerns: def setup(self): self.attrs = SFTPAttributes() self.attrs.st_mode = 0o100644 def preserves_remote_mode_by_default(self, sftp): transfer, client, mock_os = sftp # Attributes obj reflecting a realistic 'extended' octal mode client.stat.return_value = self.attrs transfer.get("file", local="meh") # Expect os.chmod to be called with the scrubbed/shifted # version of same. mock_os.chmod.assert_called_with("/local/meh", 0o644) def allows_disabling_remote_mode_preservation(self, sftp): transfer, client, mock_os = sftp client.stat.return_value = self.attrs transfer.get("file", local="meh", preserve_mode=False) assert not mock_os.chmod.called class local_directory_creation: @patch("fabric.transfer.Path") def without_trailing_slash_means_leaf_file(self, Path, sftp_objs): transfer, client = sftp_objs transfer.get(remote="file", local="top/middle/leaf") client.get.assert_called_with( localpath="/local/top/middle/leaf", remotepath="/remote/file", ) Path.assert_called_with("top/middle") Path.return_value.mkdir.assert_called_with( parents=True, exist_ok=True ) @patch("fabric.transfer.Path") def with_trailing_slash_means_mkdir_entire_arg( self, Path, sftp_objs ): transfer, client = sftp_objs transfer.get(remote="file", local="top/middle/leaf/") client.get.assert_called_with( localpath="/local/top/middle/leaf/file", remotepath="/remote/file", ) Path.assert_called_with("top/middle/leaf/") Path.return_value.mkdir.assert_called_with( parents=True, exist_ok=True ) class put: class basics: def accepts_single_local_path_posarg(self, sftp_objs): transfer, client = sftp_objs transfer.put("file") client.put.assert_called_with( localpath="/local/file", remotepath="/remote/file" ) def accepts_local_and_remote_kwargs(self, sftp_objs): transfer, sftp = sftp_objs # NOTE: default mock stat is file-ish, so path won't be munged transfer.put(local="path2", remote="path1") sftp.put.assert_called_with( localpath="/local/path2", remotepath="/remote/path1" ) def returns_rich_Result_object(self, transfer): cxn = Connection("host") result = Transfer(cxn).put("file") assert result.orig_remote is None assert result.remote == "/remote/file" assert result.orig_local == "file" assert result.local == "/local/file" assert result.connection is cxn # TODO: timing info # TODO: bytes-transferred info class remote_end_is_directory: def appends_local_file_basename(self, sftp_objs): xfer, sftp = sftp_objs sftp.stat.return_value.st_mode = 0o41777 xfer.put(local="file.txt", remote="/dir/path/") sftp.stat.assert_called_once_with("/dir/path/") sftp.put.assert_called_with( localpath="/local/file.txt", remotepath="/dir/path/file.txt", ) class file_like_local_objects: def name_attribute_present_appends_like_basename( self, sftp_objs ): xfer, sftp = sftp_objs sftp.stat.return_value.st_mode = 0o41777 local = StringIO("sup\n") local.name = "sup.txt" xfer.put(local, remote="/dir/path") sftp.putfo.assert_called_with( fl=local, remotepath="/dir/path/sup.txt" ) @raises(ValueError) def no_name_attribute_raises_ValueError(self, sftp_objs): xfer, sftp = sftp_objs sftp.stat.return_value.st_mode = 0o41777 local = StringIO("sup\n") xfer.put(local, remote="/dir/path") class path_arg_edge_cases: def remote_None_uses_local_filename(self, transfer): assert transfer.put("file").remote == "/remote/file" def remote_empty_string_uses_local_filename(self, transfer): assert transfer.put("file", remote="").remote == "/remote/file" @raises(ValueError) def remote_cant_be_empty_if_local_file_like(self, transfer): transfer.put(StringIO()) @raises(TypeError) def local_arg_is_required(self, transfer): transfer.put() @raises(ValueError) def local_arg_cannot_be_None(self, transfer): transfer.put(None) @raises(ValueError) def local_arg_cannot_be_empty_string(self, transfer): transfer.put("") class file_like_local_paths: "file-like local paths" def _put_from_stringio(self, sftp_objs): transfer, client = sftp_objs fd = StringIO() result = transfer.put(fd, remote="file") # Note: putfo, not put client.putfo.assert_called_with( remotepath="/remote/file", fl=fd ) return result, fd def remote_path_from_local_StringIO(self, sftp_objs): self._put_from_stringio(sftp_objs) def local_FLOs_are_rewound_before_putting(self, transfer): fd = Mock() fd.tell.return_value = 17 transfer.put(fd, remote="file") seek_calls = fd.seek.call_args_list assert seek_calls, [call(0) == call(17)] def result_contains_fd_for_local_path(self, sftp_objs): result, fd = self._put_from_stringio(sftp_objs) assert result.remote == "/remote/file" assert result.local is fd class mode_concerns: def preserves_local_mode_by_default(self, sftp): transfer, client, mock_os = sftp # This is a realistic stat for 0o644 mock_os.stat.return_value.st_mode = 33188 transfer.put("file") client.chmod.assert_called_with("/remote/file", 0o644) def allows_disabling_local_mode_preservation(self, sftp_objs): transfer, client = sftp_objs transfer.put("file", preserve_mode=False) assert not client.chmod.called
Transfer_
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 51209, "end": 52025 }
class ____(CBaseTypeNode): # For C++ classes that live inside other C++ classes. # name string # base_type CBaseTypeNode child_attrs = ['base_type'] def analyse(self, env, could_be_name=None): base_type = self.base_type.analyse(env) if base_type is PyrexTypes.error_type: return PyrexTypes.error_type if not base_type.is_cpp_class: error(self.pos, "'%s' is not a valid type scope" % base_type) return PyrexTypes.error_type type_entry = base_type.scope.lookup_here(self.name) if not type_entry or not type_entry.is_type: error(self.pos, "'%s.%s' is not a type identifier" % (base_type, self.name)) return PyrexTypes.error_type return type_entry.type
CNestedBaseTypeNode
python
facebookresearch__faiss
tests/test_rabitq.py
{ "start": 11582, "end": 18789 }
class ____(unittest.TestCase): def do_comparison_vs_pq_test(self, metric_type=faiss.METRIC_L2): nlist = 64 nprobe = 8 nq = 1000 ds = datasets.SyntheticDataset(TEST_DIM, TEST_N, TEST_N, nq) k = 10 d = ds.d xb = ds.get_database() xt = ds.get_train() xq = ds.get_queries() quantizer = faiss.IndexFlat(d, metric_type) index_flat = faiss.IndexIVFFlat(quantizer, d, nlist, metric_type) index_flat.train(xt) index_flat.add(xb) _, I_f = index_flat.search( xq, k, params=faiss.IVFSearchParameters(nprobe=nprobe) ) def eval_I(I): return faiss.eval_intersection(I, I_f) / I_f.ravel().shape[0] print() for random_rotate in [False, True]: quantizer = faiss.IndexFlat(d, metric_type) index_rbq = faiss.IndexIVFRaBitQ(quantizer, d, nlist, metric_type) if random_rotate: # wrap with random rotations rrot = faiss.RandomRotationMatrix(d, d) rrot.init(123) index_rbq = faiss.IndexPreTransform(rrot, index_rbq) index_rbq.train(xt) index_rbq.add(xb) # PQ{D/4}x4fs, also 1 bit per query dimension, # reusing quantizer from index_rbq. index_pq = faiss.IndexIVFPQFastScan( quantizer, d, nlist, d // 4, 4, metric_type ) # Share a single quantizer (much faster, minimal recall change) index_pq.pq.train_type = faiss.ProductQuantizer.Train_shared if random_rotate: # wrap with random rotations rrot = faiss.RandomRotationMatrix(d, d) rrot.init(123) index_pq = faiss.IndexPreTransform(rrot, index_pq) index_pq.train(xt) index_pq.add(xb) _, I_pq = index_pq.search( xq, k, params=faiss.IVFPQSearchParameters(nprobe=nprobe) ) loss_pq = 1 - eval_I(I_pq) print(f"{random_rotate=:1}, {loss_pq=:5.3f}") np.testing.assert_(loss_pq < 0.25, f"{loss_pq}") def test(params, ratio_threshold, index, rotate, loss_pq_val): _, I_rbq = index.search(xq, k, params=params) # ensure that RaBitQ and PQ are relatively close loss_rbq = 1 - eval_I(I_rbq) print( f"{rotate=:1}, {params.qb=}, {params.centered=:1}: " f"{loss_rbq=:5.3f} = loss_pq * " f"{loss_rbq / loss_pq_val:5.3f}" f" < {ratio_threshold=:.2f}" ) np.testing.assert_(loss_rbq < loss_pq_val * ratio_threshold) for qb in [1, 2, 3, 4, 8]: print() for centered in [False, True]: params = faiss.IVFRaBitQSearchParameters( nprobe=nprobe, qb=qb, centered=centered ) ratio_threshold = 2 ** (1 / qb) test( params, ratio_threshold, index_rbq, random_rotate, loss_pq, ) def test_comparison_vs_pq_L2(self): self.do_comparison_vs_pq_test(faiss.METRIC_L2) def test_comparison_vs_pq_IP(self): self.do_comparison_vs_pq_test(faiss.METRIC_INNER_PRODUCT) def test_comparison_vs_ref_L2(self): ds = datasets.SyntheticDataset(TEST_DIM, TEST_N, TEST_N, 100) k = 10 nlist = 200 ref_rbq = ReferenceIVFRabitQ(ds.d, nlist, Bq=4) ref_rbq.train(ds.get_train(), np.identity(ds.d)) ref_rbq.add(ds.get_database()) index_flat = faiss.IndexFlat(ds.d, faiss.METRIC_L2) index_rbq = faiss.IndexIVFRaBitQ( index_flat, ds.d, nlist, faiss.METRIC_L2 ) index_rbq.qb = 4 index_rbq.train(ds.get_train()) index_rbq.add(ds.get_database()) for nprobe in 1, 4, 16: ref_rbq.nprobe = nprobe _, Iref = ref_rbq.search(ds.get_queries(), k) r_ref_k = faiss.eval_intersection( Iref[:, :k], ds.get_groundtruth()[:, :k] ) / (ds.nq * k) print(f"{nprobe=} k-recall@10={r_ref_k}") params = faiss.IVFRaBitQSearchParameters() params.qb = index_rbq.qb params.nprobe = nprobe _, Inew, _ = faiss.search_with_parameters( index_rbq, ds.get_queries(), k, params, output_stats=True ) r_new_k = faiss.eval_intersection( Inew[:, :k], ds.get_groundtruth()[:, :k] ) / (ds.nq * k) print(f"{nprobe=} k-recall@10={r_new_k}") np.testing.assert_almost_equal(r_ref_k, r_new_k, 3) def test_comparison_vs_ref_L2_rrot(self): ds = datasets.SyntheticDataset(128, 4096, 4096, 100) k = 10 nlist = 200 rrot_seed = 123 ref_rbq = ReferenceIVFRabitQ(ds.d, nlist, Bq=4) ref_rbq.train(ds.get_train(), random_rotation(ds.d, rrot_seed)) ref_rbq.add(ds.get_database()) index_flat = faiss.IndexFlat(ds.d, faiss.METRIC_L2) index_rbq = faiss.IndexIVFRaBitQ( index_flat, ds.d, nlist, faiss.METRIC_L2 ) index_rbq.qb = 4 # wrap with random rotations rrot = faiss.RandomRotationMatrix(ds.d, ds.d) rrot.init(rrot_seed) index_cand = faiss.IndexPreTransform(rrot, index_rbq) index_cand.train(ds.get_train()) index_cand.add(ds.get_database()) for nprobe in 1, 4, 16: ref_rbq.nprobe = nprobe _, Iref = ref_rbq.search(ds.get_queries(), k) r_ref_k = faiss.eval_intersection( Iref[:, :k], ds.get_groundtruth()[:, :k] ) / (ds.nq * k) print(f"{nprobe=} k-recall@10={r_ref_k}") params = faiss.IVFRaBitQSearchParameters() params.qb = index_rbq.qb params.nprobe = nprobe _, Inew, _ = faiss.search_with_parameters( index_cand, ds.get_queries(), k, params, output_stats=True ) r_new_k = faiss.eval_intersection( Inew[:, :k], ds.get_groundtruth()[:, :k] ) / (ds.nq * k) print(f"{nprobe=} k-recall@10={r_new_k}") np.testing.assert_almost_equal(r_ref_k, r_new_k, 2) def do_test_serde(self, description): ds = datasets.SyntheticDataset(32, 1000, 100, 20) xt = ds.get_train() xb = ds.get_database() index = faiss.index_factory(ds.d, description) index.train(xt) index.add(xb) Dref, Iref = index.search(ds.get_queries(), 10) b = faiss.serialize_index(index) index2 = faiss.deserialize_index(b) Dnew, Inew = index2.search(ds.get_queries(), 10) np.testing.assert_equal(Dref, Dnew) np.testing.assert_equal(Iref, Inew) def test_serde_ivfrabitq(self): self.do_test_serde("IVF16,RaBitQ")
TestIVFRaBitQ
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/blur_on_disabled.py
{ "start": 79, "end": 416 }
class ____(App): BINDINGS = [("f3", "disable")] def compose(self) -> ComposeResult: yield Input() def on_ready(self) -> None: self.query_one(Input).focus() def action_disable(self) -> None: self.query_one(Input).disabled = True if __name__ == "__main__": app = BlurApp() app.run()
BlurApp
python
django-haystack__django-haystack
haystack/utils/loading.py
{ "start": 4061, "end": 5523 }
class ____: def __init__(self): self._routers = None @property def routers(self): if self._routers is None: default_routers = ["haystack.routers.DefaultRouter"] router_list = getattr(settings, "HAYSTACK_ROUTERS", default_routers) # in case HAYSTACK_ROUTERS is empty, fallback to default routers if not len(router_list): router_list = default_routers self._routers = [] for router_path in router_list: router_class = load_router(router_path) self._routers.append(router_class()) return self._routers def _for_action(self, action, many, **hints): conns = [] for router in self.routers: if hasattr(router, action): action_callable = getattr(router, action) connection_to_use = action_callable(**hints) if connection_to_use is not None: if isinstance(connection_to_use, str): conns.append(connection_to_use) else: conns.extend(connection_to_use) if not many: break return conns def for_write(self, **hints): return self._for_action("for_write", True, **hints) def for_read(self, **hints): return self._for_action("for_read", False, **hints)[0]
ConnectionRouter
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_qt.py
{ "start": 22222, "end": 25996 }
class ____(FigureManagerBase): """ Attributes ---------- canvas : `FigureCanvas` The FigureCanvas instance num : int or str The Figure number toolbar : qt.QToolBar The qt.QToolBar window : qt.QMainWindow The qt.QMainWindow """ def __init__(self, canvas, num): self.window = MainWindow() super().__init__(canvas, num) self.window.closing.connect(self._widgetclosed) if sys.platform != "darwin": image = str(cbook._get_data_path('images/matplotlib.svg')) icon = QtGui.QIcon(image) self.window.setWindowIcon(icon) self.window._destroying = False if self.toolbar: self.window.addToolBar(self.toolbar) tbs_height = self.toolbar.sizeHint().height() else: tbs_height = 0 # resize the main window so it will display the canvas with the # requested size: cs = canvas.sizeHint() cs_height = cs.height() height = cs_height + tbs_height self.window.resize(cs.width(), height) self.window.setCentralWidget(self.canvas) if mpl.is_interactive(): self.window.show() self.canvas.draw_idle() # Give the keyboard focus to the figure instead of the manager: # StrongFocus accepts both tab and click to focus and will enable the # canvas to process event without clicking. # https://doc.qt.io/qt-5/qt.html#FocusPolicy-enum self.canvas.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) self.canvas.setFocus() self.window.raise_() def full_screen_toggle(self): if self.window.isFullScreen(): self.window.showNormal() else: self.window.showFullScreen() def _widgetclosed(self): CloseEvent("close_event", self.canvas)._process() if self.window._destroying: return self.window._destroying = True try: Gcf.destroy(self) except AttributeError: pass # It seems that when the python session is killed, # Gcf can get destroyed before the Gcf.destroy # line is run, leading to a useless AttributeError. def resize(self, width, height): # The Qt methods return sizes in 'virtual' pixels so we do need to # rescale from physical to logical pixels. width = int(width / self.canvas.device_pixel_ratio) height = int(height / self.canvas.device_pixel_ratio) extra_width = self.window.width() - self.canvas.width() extra_height = self.window.height() - self.canvas.height() self.canvas.resize(width, height) self.window.resize(width + extra_width, height + extra_height) @classmethod def start_main_loop(cls): qapp = QtWidgets.QApplication.instance() if qapp: with _allow_interrupt_qt(qapp): qt_compat._exec(qapp) def show(self): self.window._destroying = False self.window.show() if mpl.rcParams['figure.raise_window']: self.window.activateWindow() self.window.raise_() def destroy(self, *args): # check for qApp first, as PySide deletes it in its atexit handler if QtWidgets.QApplication.instance() is None: return if self.window._destroying: return self.window._destroying = True if self.toolbar: self.toolbar.destroy() self.window.close() super().destroy() def get_window_title(self): return self.window.windowTitle() def set_window_title(self, title): self.window.setWindowTitle(title)
FigureManagerQT
python
redis__redis-py
redis/multidb/database.py
{ "start": 991, "end": 1629 }
class ____(AbstractDatabase): def __init__( self, weight: float, health_check_url: Optional[str] = None, ): self._weight = weight self._health_check_url = health_check_url @property def weight(self) -> float: return self._weight @weight.setter def weight(self, weight: float): self._weight = weight @property def health_check_url(self) -> Optional[str]: return self._health_check_url @health_check_url.setter def health_check_url(self, health_check_url: Optional[str]): self._health_check_url = health_check_url
BaseDatabase
python
networkx__networkx
networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py
{ "start": 3314, "end": 5839 }
class ____: def test_K4_normalized(self): """Betweenness centrality: K4""" G = nx.complete_graph(4) b = edge_current_flow_subset(G, list(G), list(G), normalized=True) b_answer = edge_current_flow(G, normalized=True) for (s, t), v1 in b_answer.items(): v2 = b.get((s, t), b.get((t, s))) assert v1 == pytest.approx(v2, abs=1e-7) def test_K4(self): """Betweenness centrality: K4""" G = nx.complete_graph(4) b = edge_current_flow_subset(G, list(G), list(G), normalized=False) b_answer = edge_current_flow(G, normalized=False) for (s, t), v1 in b_answer.items(): v2 = b.get((s, t), b.get((t, s))) assert v1 == pytest.approx(v2, abs=1e-7) # test weighted network G.add_edge(0, 1, weight=0.5, other=0.3) b = edge_current_flow_subset(G, list(G), list(G), normalized=False, weight=None) # weight is None => same as unweighted network for (s, t), v1 in b_answer.items(): v2 = b.get((s, t), b.get((t, s))) assert v1 == pytest.approx(v2, abs=1e-7) b = edge_current_flow_subset(G, list(G), list(G), normalized=False) b_answer = edge_current_flow(G, normalized=False) for (s, t), v1 in b_answer.items(): v2 = b.get((s, t), b.get((t, s))) assert v1 == pytest.approx(v2, abs=1e-7) b = edge_current_flow_subset( G, list(G), list(G), normalized=False, weight="other" ) b_answer = edge_current_flow(G, normalized=False, weight="other") for (s, t), v1 in b_answer.items(): v2 = b.get((s, t), b.get((t, s))) assert v1 == pytest.approx(v2, abs=1e-7) def test_C4(self): """Edge betweenness centrality: C4""" G = nx.cycle_graph(4) b = edge_current_flow_subset(G, list(G), list(G), normalized=True) b_answer = edge_current_flow(G, normalized=True) for (s, t), v1 in b_answer.items(): v2 = b.get((s, t), b.get((t, s))) assert v1 == pytest.approx(v2, abs=1e-7) def test_P4(self): """Edge betweenness centrality: P4""" G = nx.path_graph(4) b = edge_current_flow_subset(G, list(G), list(G), normalized=True) b_answer = edge_current_flow(G, normalized=True) for (s, t), v1 in b_answer.items(): v2 = b.get((s, t), b.get((t, s))) assert v1 == pytest.approx(v2, abs=1e-7)
TestEdgeFlowBetweennessCentrality
python
pytorch__pytorch
torch/utils/data/datapipes/iter/routeddecoder.py
{ "start": 586, "end": 2731 }
class ____(IterDataPipe[tuple[str, Any]]): r""" Decodes binary streams from input DataPipe, yields pathname and decoded data in a tuple. (functional name: ``routed_decode``) Args: datapipe: Iterable datapipe that provides pathname and binary stream in tuples handlers: Optional user defined decoder handlers. If ``None``, basic and image decoder handlers will be set as default. If multiple handles are provided, the priority order follows the order of handlers (the first handler has the top priority) key_fn: Function for decoder to extract key from pathname to dispatch handlers. Default is set to extract file extension from pathname Note: When ``key_fn`` is specified returning anything other than extension, the default handler will not work and users need to specify custom handler. Custom handler could use regex to determine the eligibility to handle data. """ def __init__( self, datapipe: Iterable[tuple[str, BufferedIOBase]], *handlers: Callable, key_fn: Callable = extension_extract_fn, ) -> None: super().__init__() self.datapipe: Iterable[tuple[str, BufferedIOBase]] = datapipe if not handlers: handlers = (decoder_basichandlers, decoder_imagehandler("torch")) self.decoder = Decoder(*handlers, key_fn=key_fn) _deprecation_warning( type(self).__name__, deprecation_version="1.12", removal_version="1.13", old_functional_name="routed_decode", ) def add_handler(self, *handler: Callable) -> None: self.decoder.add_handler(*handler) def __iter__(self) -> Iterator[tuple[str, Any]]: for data in self.datapipe: pathname = data[0] result = self.decoder(data) yield (pathname, result[pathname]) def __len__(self) -> int: if isinstance(self.datapipe, Sized): return len(self.datapipe) raise TypeError(f"{type(self).__name__} instance doesn't have valid length")
RoutedDecoderIterDataPipe
python
matplotlib__matplotlib
lib/matplotlib/_type1font.py
{ "start": 2369, "end": 2489 }
class ____(_Token): kind = 'keyword' def is_keyword(self, *names): return self.raw in names
_KeywordToken
python
dagster-io__dagster
python_modules/dagster/dagster/_core/pipes/utils.py
{ "start": 23662, "end": 24627 }
class ____(ABC): @abstractmethod def start(self, params: PipesParams, is_session_closed: Event) -> None: ... @abstractmethod def stop(self) -> None: ... @abstractmethod def is_running(self) -> bool: ... @abstractmethod def target_is_readable(self, params: PipesParams) -> bool: ... @property def name(self) -> str: """Override this to distinguish different log readers in error messages.""" return self.__class__.__name__ @property def debug_info(self) -> Optional[str]: """An optional message containing debug information about the log reader. It will be included in error messages when the log reader fails to start or throws an exception. """ def with_debug_info(self, message: str) -> str: """Helper method to include debug info in error messages.""" return f"{message}\nDebug info: {self.debug_info}" if self.debug_info else message
PipesLogReader
python
PrefectHQ__prefect
src/prefect/runner/storage.py
{ "start": 2161, "end": 3458 }
class ____(Protocol): """ Protocol for credential blocks that can format themselves for git URLs. Implementing this protocol allows credential blocks to own their auth formatting logic instead of having it centralized in core Prefect. This enables proper separation of concerns where each git provider (GitLab, GitHub, BitBucket) can handle their own authentication format requirements without core needing provider-specific knowledge. """ def format_git_credentials(self, url: str) -> str: """ Format and return the full git URL with credentials embedded. Args: url: The repository URL (e.g., "https://gitlab.com/org/repo.git"). Returns: Complete URL with credentials embedded in the appropriate format for the provider. Examples: - GitLab PAT: "https://oauth2:my-token@gitlab.com/org/repo.git" - GitLab Deploy Token: "https://username:token@gitlab.com/org/repo.git" - GitHub: "https://my-token@github.com/org/repo.git" - BitBucket Cloud: "https://x-token-auth:my-token@bitbucket.org/org/repo.git" - BitBucket Server: "https://username:token@bitbucketserver.com/scm/project/repo.git" """ ...
_GitCredentialsFormatter
python
django__django
tests/template_tests/syntax_tests/test_resetcycle.py
{ "start": 116, "end": 4329 }
class ____(SimpleTestCase): @setup({"resetcycle01": "{% resetcycle %}"}) def test_resetcycle01(self): with self.assertRaisesMessage(TemplateSyntaxError, "No cycles in template."): self.engine.get_template("resetcycle01") @setup({"resetcycle02": "{% resetcycle undefinedcycle %}"}) def test_resetcycle02(self): with self.assertRaisesMessage( TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist." ): self.engine.get_template("resetcycle02") @setup({"resetcycle03": "{% cycle 'a' 'b' %}{% resetcycle undefinedcycle %}"}) def test_resetcycle03(self): with self.assertRaisesMessage( TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist." ): self.engine.get_template("resetcycle03") @setup({"resetcycle04": "{% cycle 'a' 'b' as ab %}{% resetcycle undefinedcycle %}"}) def test_resetcycle04(self): with self.assertRaisesMessage( TemplateSyntaxError, "Named cycle 'undefinedcycle' does not exist." ): self.engine.get_template("resetcycle04") @setup( { "resetcycle05": ( "{% for i in test %}{% cycle 'a' 'b' %}{% resetcycle %}{% endfor %}" ) } ) def test_resetcycle05(self): output = self.engine.render_to_string("resetcycle05", {"test": list(range(5))}) self.assertEqual(output, "aaaaa") @setup( { "resetcycle06": "{% cycle 'a' 'b' 'c' as abc %}" "{% for i in test %}" "{% cycle abc %}" "{% cycle '-' '+' %}" "{% resetcycle %}" "{% endfor %}" } ) def test_resetcycle06(self): output = self.engine.render_to_string("resetcycle06", {"test": list(range(5))}) self.assertEqual(output, "ab-c-a-b-c-") @setup( { "resetcycle07": "{% cycle 'a' 'b' 'c' as abc %}" "{% for i in test %}" "{% resetcycle abc %}" "{% cycle abc %}" "{% cycle '-' '+' %}" "{% endfor %}" } ) def test_resetcycle07(self): output = self.engine.render_to_string("resetcycle07", {"test": list(range(5))}) self.assertEqual(output, "aa-a+a-a+a-") @setup( { "resetcycle08": "{% for i in outer %}" "{% for j in inner %}" "{% cycle 'a' 'b' %}" "{% endfor %}" "{% resetcycle %}" "{% endfor %}" } ) def test_resetcycle08(self): output = self.engine.render_to_string( "resetcycle08", {"outer": list(range(2)), "inner": list(range(3))} ) self.assertEqual(output, "abaaba") @setup( { "resetcycle09": "{% for i in outer %}" "{% cycle 'a' 'b' %}" "{% for j in inner %}" "{% cycle 'X' 'Y' %}" "{% endfor %}" "{% resetcycle %}" "{% endfor %}" } ) def test_resetcycle09(self): output = self.engine.render_to_string( "resetcycle09", {"outer": list(range(2)), "inner": list(range(3))} ) self.assertEqual(output, "aXYXbXYX") @setup( { "resetcycle10": "{% for i in test %}" "{% cycle 'X' 'Y' 'Z' as XYZ %}" "{% cycle 'a' 'b' 'c' as abc %}" "{% if i == 1 %}" "{% resetcycle abc %}" "{% endif %}" "{% endfor %}" } ) def test_resetcycle10(self): output = self.engine.render_to_string("resetcycle10", {"test": list(range(5))}) self.assertEqual(output, "XaYbZaXbYc") @setup( { "resetcycle11": "{% for i in test %}" "{% cycle 'X' 'Y' 'Z' as XYZ %}" "{% cycle 'a' 'b' 'c' as abc %}" "{% if i == 1 %}" "{% resetcycle XYZ %}" "{% endif %}" "{% endfor %}" } ) def test_resetcycle11(self): output = self.engine.render_to_string("resetcycle11", {"test": list(range(5))}) self.assertEqual(output, "XaYbXcYaZb")
ResetCycleTagTests
python
walkccc__LeetCode
solutions/3433. Count Mentions Per User/3433.py
{ "start": 60, "end": 202 }
class ____: returnTimestamp: int userId: int def __lt__(self, other): return self.returnTimestamp < other.returnTimestamp
OfflineUser
python
google__jax
jax/_src/state/types.py
{ "start": 19214, "end": 19528 }
class ____(core.AbstractValue): inner_aval: core.AbstractValue memory_space: Any = None shape = property(lambda self: self.inner_aval.shape) # type: ignore dtype = property(lambda self: self.inner_aval.dtype) # type: ignore ndim = property(lambda self: self.inner_aval.ndim) # type: ignore
AbstractLinVal
python
numpy__numpy
numpy/_core/tests/test_numerictypes.py
{ "start": 13361, "end": 16023 }
class ____: # scalar types can be promoted into dtypes wrappers = [np.dtype, lambda x: x] def test_both_abstract(self): assert_(np.issubdtype(np.floating, np.inexact)) assert_(not np.issubdtype(np.inexact, np.floating)) def test_same(self): for cls in (np.float32, np.int32): for w1, w2 in itertools.product(self.wrappers, repeat=2): assert_(np.issubdtype(w1(cls), w2(cls))) def test_subclass(self): # note we cannot promote floating to a dtype, as it would turn into a # concrete type for w in self.wrappers: assert_(np.issubdtype(w(np.float32), np.floating)) assert_(np.issubdtype(w(np.float64), np.floating)) def test_subclass_backwards(self): for w in self.wrappers: assert_(not np.issubdtype(np.floating, w(np.float32))) assert_(not np.issubdtype(np.floating, w(np.float64))) def test_sibling_class(self): for w1, w2 in itertools.product(self.wrappers, repeat=2): assert_(not np.issubdtype(w1(np.float32), w2(np.float64))) assert_(not np.issubdtype(w1(np.float64), w2(np.float32))) def test_nondtype_nonscalartype(self): # See gh-14619 and gh-9505 which introduced the deprecation to fix # this. These tests are directly taken from gh-9505 assert not np.issubdtype(np.float32, 'float64') assert not np.issubdtype(np.float32, 'f8') assert not np.issubdtype(np.int32, str) assert not np.issubdtype(np.int32, 'int64') assert not np.issubdtype(np.str_, 'void') # for the following the correct spellings are # np.integer, np.floating, or np.complexfloating respectively: assert not np.issubdtype(np.int8, int) # np.int8 is never np.int_ assert not np.issubdtype(np.float32, float) assert not np.issubdtype(np.complex64, complex) assert not np.issubdtype(np.float32, "float") assert not np.issubdtype(np.float64, "f") # Test the same for the correct first datatype and abstract one # in the case of int, float, complex: assert np.issubdtype(np.float64, 'float64') assert np.issubdtype(np.float64, 'f8') assert np.issubdtype(np.str_, str) assert np.issubdtype(np.int64, 'int64') assert np.issubdtype(np.void, 'void') assert np.issubdtype(np.int8, np.integer) assert np.issubdtype(np.float32, np.floating) assert np.issubdtype(np.complex64, np.complexfloating) assert np.issubdtype(np.float64, "float") assert np.issubdtype(np.float32, "f")
TestIsSubDType
python
fastapi__sqlmodel
docs_src/tutorial/relationship_attributes/back_populates/tutorial003.py
{ "start": 752, "end": 1584 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") team: Optional[Team] = Relationship(back_populates="heroes") weapon_id: Optional[int] = Field(default=None, foreign_key="weapon.id") weapon: Optional[Weapon] = Relationship(back_populates="hero") powers: List[Power] = Relationship(back_populates="hero") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def main(): create_db_and_tables() if __name__ == "__main__": main()
Hero
python
openai__openai-python
src/openai/resources/beta/realtime/realtime.py
{ "start": 32699, "end": 32851 }
class ____: def __init__(self, connection: AsyncRealtimeConnection) -> None: self._connection = connection
BaseAsyncRealtimeConnectionResource
python
pytorch__pytorch
test/test_subclass.py
{ "start": 1239, "end": 10879 }
class ____(TestCase): def _create_tensor(self, tensor_cls): return subclass_db[tensor_cls].create_fn(3) @parametrize_tensor_cls @parametrize("tensor_requires_grad", [False, True]) def test_param_invariants(self, tensor_cls, tensor_requires_grad): x = self._create_tensor(tensor_cls).requires_grad_(tensor_requires_grad) param = nn.Parameter(x, requires_grad=(not tensor_requires_grad)) self.assertIsInstance(param, nn.Parameter) # Ensure requires_grad passed to Parameter's constructor takes precedence. self.assertEqual(param.requires_grad, not tensor_requires_grad) # Ensure original tensor is not mutated by Parameter construction. self.assertNotIsInstance(x, nn.Parameter) self.assertEqual(x.requires_grad, tensor_requires_grad) class UninitializedParam(nn.Parameter): pass self.assertNotIsInstance(param, UninitializedParam) @skipIfTorchDynamo() @parametrize_tensor_cls @parametrize("as_param", [False, True]) def test_deepcopy(self, tensor_cls, as_param): x = self._create_tensor(tensor_cls) if as_param: x = nn.Parameter(x) x_copy = deepcopy(x) self.assertEqual(x, x_copy) self.assertEqual(x.__class__, x_copy.__class__) self.assertIsNot(x, x_copy) self.assertIsInstance(x_copy, tensor_cls) if as_param: # Deepcopy should preserve both custom type and "parameter-ness". self.assertIsInstance(x_copy, nn.Parameter) @parametrize_tensor_cls @parametrize("as_param", [False, True]) def test_serialization(self, tensor_cls, as_param): with tempfile.TemporaryFile() as f: x = self._create_tensor(tensor_cls) if as_param: x = nn.Parameter(x) torch.save(x, f) f.seek(0) with torch.serialization.safe_globals([tensor_cls]): x_loaded = torch.load(f) self.assertEqual(x, x_loaded) self.assertIsNot(x, x_loaded) self.assertIsInstance(x_loaded, tensor_cls) if as_param: # Serialization should preserve both custom type and "parameter-ness". self.assertIsInstance(x_loaded, nn.Parameter) @skipIfTorchDynamo("Visible only with functorch as functorch monkeypatches tensor str") @parametrize_tensor_cls @parametrize("as_param", [False, True]) def test_repr(self, tensor_cls, as_param): x = self._create_tensor(tensor_cls) if as_param: x = nn.Parameter(x) str_repr = x.__repr__() if tensor_cls is not torch.Tensor: self.assertEqual(str_repr.count(f"{tensor_cls.__name__}("), 1) self.assertEqual(str_repr.count("Parameter"), 1 if as_param else 0) @parametrize_tensor_cls @parametrize("as_param", [False, True]) def test_type_propagation(self, tensor_cls, as_param): x = self._create_tensor(tensor_cls) if as_param: x = nn.Parameter(x) # Call the add operator to produce an output tensor. output = x + self._create_tensor(torch.Tensor) # Custom type should be propagated across operations if closed under the op, but # "parameter-ness" should not be. if subclass_db[tensor_cls].closed_under_ops: self.assertIsInstance(output, tensor_cls) else: self.assertIsInstance(output, torch.Tensor) self.assertNotIsInstance(output, nn.Parameter) @parametrize_tensor_cls def test_module_optimization(self, tensor_cls): create_fn = partial(self._create_tensor, tensor_cls) class MyModule(nn.Module): def __init__(self) -> None: super().__init__() self.p1 = nn.Parameter(create_fn()) self.p_list = nn.ParameterList([create_fn() for _ in range(3)]) self.p_list.append(create_fn()) self.p_dict = nn.ParameterDict({ 'foo': create_fn(), 'bar': create_fn(), }) self.p_dict['baz'] = create_fn() with torch.no_grad(): nn.init.normal_(self.p1) for p in self.p_list: nn.init.uniform_(p) for p in self.p_dict.values(): nn.init.uniform_(p) def forward(self, x): out = self.p1 + x for p in self.p_list: out = p + out for v in self.p_dict.values(): out = v + out return out m = MyModule() self.assertEqual(len(m.state_dict()), 8) optimizer = torch.optim.SGD(m.parameters(), lr=0.1) m(create_fn()).sum().backward(torch.tensor(1)) optimizer.step() @parametrize_tensor_cls @parametrize("leave_parametrized", [False, True]) def test_parametrization(self, tensor_cls, leave_parametrized): # TODO: Either implement set_() properly for these tensor subclasses or apply a # more general fix to avoid the need for special set_() handling. For now, skip # testing these as they're expected to fail. if tensor_cls in [LoggingTensor, DiagTensorBelow]: return create_fn = partial(self._create_tensor, tensor_cls) class MyModule(nn.Module): def __init__(self) -> None: super().__init__() self.weight = nn.Parameter(create_fn()) def forward(self, x): return self.weight + x class MyParametrization(nn.Module): def forward(self, X): return -X m = MyModule() self.assertEqual(len(m.state_dict()), 1) register_parametrization(m, 'weight', MyParametrization()) self.assertIsInstance(m.weight, tensor_cls) output = m(self._create_tensor(torch.Tensor)) self.assertIsInstance(output, tensor_cls) remove_parametrizations(m, 'weight', leave_parametrized=leave_parametrized) # Lazy modules with custom tensors are not supported yet. @expectedFailure @parametrize_tensor_cls def test_lazy_module(self, tensor_cls): if tensor_cls is torch.Tensor: self.fail('dummy fail for base tensor until the test passes for subclasses') class MyLazyModule(LazyModuleMixin, nn.Module): def __init__(self) -> None: super().__init__() self.param = nn.UninitializedParameter() def initialize_parameters(self, input) -> None: # type: ignore[override] if self.has_uninitialized_params(): with torch.no_grad(): self.param.materialize(input.shape) nn.init.uniform_(self.param) def forward(self, x): return self.param + x m = MyLazyModule() self.assertTrue(m.has_uninitialized_params()) m(self._create_tensor(tensor_cls)) self.assertFalse(m.has_uninitialized_params()) self.assertIsInstance(m.param, tensor_cls) def test_non_rewrapping_torch_dispatch_subclass_as_parameter_throws_for_detach(self): # Define a subclass that does not rewrap for any function in its __torch_dispatch__ impl. class NonRewrappingTensor(torch.Tensor): @staticmethod def __new__( cls, t: torch.Tensor ): r = super()._make_wrapper_subclass( cls, t.shape, dtype=t.dtype, requires_grad=t.requires_grad, device=t.device) return r def __init__(self, t) -> None: self.tensor: torch.Tensor = t @classmethod def __torch_dispatch__(cls, func, types, args=(), kwargs=None): def unwrap(e) -> torch.Tensor: if isinstance(e, NonRewrappingTensor): t = e.tensor return t else: return e r = func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs)) # Return an unwrapped tensor no longer of original subclass type. return r with self.assertRaisesRegex(RuntimeError, r"requires that detach\(\) returns an instance of the same type"): nn.Parameter(NonRewrappingTensor(torch.randn(3))) def test_tensor_subclass_storage_data_accesses_throw(self): from torch.testing._internal.logging_tensor import LoggingTensor x = torch.ones(2) x_log = LoggingTensor(x) # Accessing storage on a tensor subclass is valid storage = x_log.untyped_storage() # This includes accessing metadata on the storage # But storage methods that access data will throw with self.assertRaisesRegex(RuntimeError, "on an invalid python storage"): storage.data_ptr() with self.assertRaisesRegex(RuntimeError, "on an invalid python storage"): storage.resize_(0) with self.assertRaisesRegex(RuntimeError, "on an invalid python storage"): storage.copy_(storage) with self.assertRaisesRegex(RuntimeError, "on an invalid python storage"): storage.fill_(0) with self.assertRaisesRegex(RuntimeError, "on an invalid python storage"): storage._write_file("file") instantiate_parametrized_tests(TestSubclass) if __name__ == '__main__': run_tests()
TestSubclass
python
pyca__cryptography
tests/hazmat/primitives/decrepit/test_algorithms.py
{ "start": 2477, "end": 3246 }
class ____: @pytest.mark.parametrize( ("key", "keysize"), [(b"0" * (keysize // 4), keysize) for keysize in range(32, 449, 8)], ) def test_key_size(self, key, keysize): cipher = Blowfish(binascii.unhexlify(key)) assert cipher.key_size == keysize def test_invalid_key_size(self): with pytest.raises(ValueError): Blowfish(binascii.unhexlify(b"0" * 6)) def test_invalid_key_type(self): with pytest.raises(TypeError, match="key must be bytes"): Blowfish("0" * 8) # type: ignore[arg-type] @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( Blowfish(b"\x00" * 56), modes.ECB() ), skip_message="Does not support Blowfish ECB", )
TestBlowfish
python
jackfrued__Python-100-Days
Day31-35/code/example16.py
{ "start": 631, "end": 1437 }
class ____(): def __init__(self, name): self.name = name self.students = {} def __setitem__(self, key, student): self.students[key] = student def __getitem__(self, key): return self.students[key] def main(): # students = set() # students.add(Student(1001, '王大锤')) # students.add(Student(1001, '王大锤')) # students.add(Student(1001, '白元芳')) # print(len(students)) # print(students) stu = Student(1234, '骆昊') stu.gender = 'Male' # stu.birth = '1980-11-28' print(stu.name, stu.birth) school = School('千锋教育') school[1001] = Student(1001, '王大锤') school[1002] = Student(1002, '白元芳') school[1003] = Student(1003, '白洁') print(school[1002]) print(school[1003]) if __name__ == '__main__': main()
School
python
pandas-dev__pandas
pandas/tests/arrays/test_datetimes.py
{ "start": 10227, "end": 29394 }
class ____: def test_astype_ns_to_ms_near_bounds(self): # GH#55979 ts = pd.Timestamp("1677-09-21 00:12:43.145225") target = ts.as_unit("ms") dta = DatetimeArray._from_sequence([ts], dtype="M8[ns]") assert (dta.view("i8") == ts.as_unit("ns").value).all() result = dta.astype("M8[ms]") assert result[0] == target expected = DatetimeArray._from_sequence([ts], dtype="M8[ms]") assert (expected.view("i8") == target._value).all() tm.assert_datetime_array_equal(result, expected) def test_astype_non_nano_tznaive(self): dti = pd.date_range("2016-01-01", periods=3) res = dti.astype("M8[s]") assert res.dtype == "M8[s]" dta = dti._data res = dta.astype("M8[s]") assert res.dtype == "M8[s]" assert isinstance(res, pd.core.arrays.DatetimeArray) # used to be ndarray def test_astype_non_nano_tzaware(self): dti = pd.date_range("2016-01-01", periods=3, tz="UTC") res = dti.astype("M8[s, US/Pacific]") assert res.dtype == "M8[s, US/Pacific]" dta = dti._data res = dta.astype("M8[s, US/Pacific]") assert res.dtype == "M8[s, US/Pacific]" # from non-nano to non-nano, preserving reso res2 = res.astype("M8[s, UTC]") assert res2.dtype == "M8[s, UTC]" assert not tm.shares_memory(res2, res) res3 = res.astype("M8[s, UTC]", copy=False) assert res2.dtype == "M8[s, UTC]" assert tm.shares_memory(res3, res) def test_astype_to_same(self): arr = DatetimeArray._from_sequence( ["2000"], dtype=DatetimeTZDtype(tz="US/Central") ) result = arr.astype(DatetimeTZDtype(tz="US/Central"), copy=False) assert result is arr @pytest.mark.parametrize("dtype", ["datetime64[ns]", "datetime64[ns, UTC]"]) @pytest.mark.parametrize( "other", ["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, CET]"] ) def test_astype_copies(self, dtype, other): # https://github.com/pandas-dev/pandas/pull/32490 ser = pd.Series([1, 2], dtype=dtype) orig = ser.copy() err = False if (dtype == "datetime64[ns]") ^ (other == "datetime64[ns]"): # deprecated in favor of tz_localize err = True if err: if dtype == "datetime64[ns]": msg = "Use obj.tz_localize instead or series.dt.tz_localize instead" else: msg = "from timezone-aware dtype to timezone-naive dtype" with pytest.raises(TypeError, match=msg): ser.astype(other) else: t = ser.astype(other) t[:] = pd.NaT tm.assert_series_equal(ser, orig) @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"]) def test_astype_int(self, dtype): arr = DatetimeArray._from_sequence( [pd.Timestamp("2000"), pd.Timestamp("2001")], dtype="M8[ns]" ) if np.dtype(dtype) != np.int64: with pytest.raises(TypeError, match=r"Do obj.astype\('int64'\)"): arr.astype(dtype) return result = arr.astype(dtype) expected = arr._ndarray.view("i8") tm.assert_numpy_array_equal(result, expected) def test_astype_to_sparse_dt64(self): # GH#50082 dti = pd.date_range("2016-01-01", periods=4) dta = dti._data result = dta.astype("Sparse[datetime64[ns]]") assert result.dtype == "Sparse[datetime64[ns]]" assert (result == dta).all() def test_tz_setter_raises(self): arr = DatetimeArray._from_sequence( ["2000"], dtype=DatetimeTZDtype(tz="US/Central") ) with pytest.raises(AttributeError, match="tz_localize"): arr.tz = "UTC" def test_setitem_str_impute_tz(self, tz_naive_fixture): # Like for getitem, if we are passed a naive-like string, we impute # our own timezone. tz = tz_naive_fixture data = np.array([1, 2, 3], dtype="M8[ns]") dtype = data.dtype if tz is None else DatetimeTZDtype(tz=tz) arr = DatetimeArray._from_sequence(data, dtype=dtype) expected = arr.copy() ts = pd.Timestamp("2020-09-08 16:50").tz_localize(tz) setter = str(ts.tz_localize(None)) # Setting a scalar tznaive string expected[0] = ts arr[0] = setter tm.assert_equal(arr, expected) # Setting a listlike of tznaive strings expected[1] = ts arr[:2] = [setter, setter] tm.assert_equal(arr, expected) def test_setitem_different_tz_raises(self): # pre-2.0 we required exact tz match, in 2.0 we require only # tzawareness-match data = np.array([1, 2, 3], dtype="M8[ns]") arr = DatetimeArray._from_sequence( data, copy=False, dtype=DatetimeTZDtype(tz="US/Central") ) with pytest.raises(TypeError, match="Cannot compare tz-naive and tz-aware"): arr[0] = pd.Timestamp("2000") ts = pd.Timestamp("2000", tz="US/Eastern") arr[0] = ts assert arr[0] == ts.tz_convert("US/Central") def test_setitem_clears_freq(self): a = pd.date_range("2000", periods=2, freq="D", tz="US/Central")._data a[0] = pd.Timestamp("2000", tz="US/Central") assert a.freq is None @pytest.mark.parametrize( "obj", [ pd.Timestamp("2021-01-01"), pd.Timestamp("2021-01-01").to_datetime64(), pd.Timestamp("2021-01-01").to_pydatetime(), ], ) def test_setitem_objects(self, obj): # make sure we accept datetime64 and datetime in addition to Timestamp dti = pd.date_range("2000", periods=2, freq="D") arr = dti._data arr[0] = obj assert arr[0] == obj def test_repeat_preserves_tz(self): dti = pd.date_range("2000", periods=2, freq="D", tz="US/Central") arr = dti._data repeated = arr.repeat([1, 1]) # preserves tz and values, but not freq expected = DatetimeArray._from_sequence(arr.asi8, dtype=arr.dtype) tm.assert_equal(repeated, expected) def test_value_counts_preserves_tz(self): dti = pd.date_range("2000", periods=2, freq="D", tz="US/Central") arr = dti._data.repeat([4, 3]) result = arr.value_counts() # Note: not tm.assert_index_equal, since `freq`s do not match assert result.index.equals(dti) arr[-2] = pd.NaT result = arr.value_counts(dropna=False) expected = pd.Series([4, 2, 1], index=[dti[0], dti[1], pd.NaT], name="count") tm.assert_series_equal(result, expected) @pytest.mark.parametrize("method", ["pad", "backfill"]) def test_fillna_preserves_tz(self, method): dti = pd.date_range( "2000-01-01", periods=5, freq="D", tz="US/Central", unit="ns" ) arr = DatetimeArray._from_sequence(dti, dtype=dti.dtype, copy=True) arr[2] = pd.NaT fill_val = dti[1] if method == "pad" else dti[3] expected = DatetimeArray._from_sequence( [dti[0], dti[1], fill_val, dti[3], dti[4]], dtype=DatetimeTZDtype(tz="US/Central"), ) result = arr._pad_or_backfill(method=method) tm.assert_extension_array_equal(result, expected) # assert that arr and dti were not modified in-place assert arr[2] is pd.NaT assert dti[2] == pd.Timestamp("2000-01-03", tz="US/Central") def test_fillna_2d(self): dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific") dta = dti._data.reshape(3, 2).copy() dta[0, 1] = pd.NaT dta[1, 0] = pd.NaT res1 = dta._pad_or_backfill(method="pad") expected1 = dta.copy() expected1[1, 0] = dta[0, 0] tm.assert_extension_array_equal(res1, expected1) res2 = dta._pad_or_backfill(method="backfill") expected2 = dta.copy() expected2 = dta.copy() expected2[1, 0] = dta[2, 0] expected2[0, 1] = dta[1, 1] tm.assert_extension_array_equal(res2, expected2) # with different ordering for underlying ndarray; behavior should # be unchanged dta2 = dta._from_backing_data(dta._ndarray.copy(order="F")) assert dta2._ndarray.flags["F_CONTIGUOUS"] assert not dta2._ndarray.flags["C_CONTIGUOUS"] tm.assert_extension_array_equal(dta, dta2) res3 = dta2._pad_or_backfill(method="pad") tm.assert_extension_array_equal(res3, expected1) res4 = dta2._pad_or_backfill(method="backfill") tm.assert_extension_array_equal(res4, expected2) # test the DataFrame method while we're here df = pd.DataFrame(dta) res = df.ffill() expected = pd.DataFrame(expected1) tm.assert_frame_equal(res, expected) res = df.bfill() expected = pd.DataFrame(expected2) tm.assert_frame_equal(res, expected) def test_array_interface_tz(self): tz = "US/Central" data = pd.date_range("2017", periods=2, tz=tz, unit="ns")._data result = np.asarray(data) expected = np.array( [ pd.Timestamp("2017-01-01T00:00:00", tz=tz), pd.Timestamp("2017-01-02T00:00:00", tz=tz), ], dtype=object, ) tm.assert_numpy_array_equal(result, expected) result = np.asarray(data, dtype=object) tm.assert_numpy_array_equal(result, expected) result = np.asarray(data, dtype="M8[ns]") expected = np.array( ["2017-01-01T06:00:00", "2017-01-02T06:00:00"], dtype="M8[ns]" ) tm.assert_numpy_array_equal(result, expected) def test_array_interface(self): data = pd.date_range("2017", periods=2, unit="ns")._data expected = np.array( ["2017-01-01T00:00:00", "2017-01-02T00:00:00"], dtype="datetime64[ns]" ) result = np.asarray(data) tm.assert_numpy_array_equal(result, expected) result = np.asarray(data, dtype=object) expected = np.array( [pd.Timestamp("2017-01-01T00:00:00"), pd.Timestamp("2017-01-02T00:00:00")], dtype=object, ) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize("index", [True, False]) def test_searchsorted_different_tz(self, index): data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9 arr = pd.DatetimeIndex(data, freq="D")._data.tz_localize("Asia/Tokyo") if index: arr = pd.Index(arr) expected = arr.searchsorted(arr[2]) result = arr.searchsorted(arr[2].tz_convert("UTC")) assert result == expected expected = arr.searchsorted(arr[2:6]) result = arr.searchsorted(arr[2:6].tz_convert("UTC")) tm.assert_equal(result, expected) @pytest.mark.parametrize("index", [True, False]) def test_searchsorted_tzawareness_compat(self, index): data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9 arr = pd.DatetimeIndex(data, freq="D")._data if index: arr = pd.Index(arr) mismatch = arr.tz_localize("Asia/Tokyo") msg = "Cannot compare tz-naive and tz-aware datetime-like objects" with pytest.raises(TypeError, match=msg): arr.searchsorted(mismatch[0]) with pytest.raises(TypeError, match=msg): arr.searchsorted(mismatch) with pytest.raises(TypeError, match=msg): mismatch.searchsorted(arr[0]) with pytest.raises(TypeError, match=msg): mismatch.searchsorted(arr) @pytest.mark.parametrize( "other", [ 1, np.int64(1), 1.0, np.timedelta64("NaT"), pd.Timedelta(days=2), "invalid", np.arange(10, dtype="i8") * 24 * 3600 * 10**9, np.arange(10).view("timedelta64[ns]") * 24 * 3600 * 10**9, pd.Timestamp("2021-01-01").to_period("D"), ], ) @pytest.mark.parametrize("index", [True, False]) def test_searchsorted_invalid_types(self, other, index): data = np.arange(10, dtype="i8") * 24 * 3600 * 10**9 arr = pd.DatetimeIndex(data, freq="D")._data if index: arr = pd.Index(arr) msg = "|".join( [ "searchsorted requires compatible dtype or scalar", "value should be a 'Timestamp', 'NaT', or array of those. Got", ] ) with pytest.raises(TypeError, match=msg): arr.searchsorted(other) def test_shift_fill_value(self): dti = pd.date_range("2016-01-01", periods=3) dta = dti._data expected = DatetimeArray._from_sequence( np.roll(dta._ndarray, 1), dtype=dti.dtype ) fv = dta[-1] for fill_value in [fv, fv.to_pydatetime(), fv.to_datetime64()]: result = dta.shift(1, fill_value=fill_value) tm.assert_datetime_array_equal(result, expected) dta = dta.tz_localize("UTC") expected = expected.tz_localize("UTC") fv = dta[-1] for fill_value in [fv, fv.to_pydatetime()]: result = dta.shift(1, fill_value=fill_value) tm.assert_datetime_array_equal(result, expected) def test_shift_value_tzawareness_mismatch(self): dti = pd.date_range("2016-01-01", periods=3) dta = dti._data fv = dta[-1].tz_localize("UTC") for invalid in [fv, fv.to_pydatetime()]: with pytest.raises(TypeError, match="Cannot compare"): dta.shift(1, fill_value=invalid) dta = dta.tz_localize("UTC") fv = dta[-1].tz_localize(None) for invalid in [fv, fv.to_pydatetime(), fv.to_datetime64()]: with pytest.raises(TypeError, match="Cannot compare"): dta.shift(1, fill_value=invalid) def test_shift_requires_tzmatch(self): # pre-2.0 we required exact tz match, in 2.0 we require just # matching tzawareness dti = pd.date_range("2016-01-01", periods=3, tz="UTC") dta = dti._data fill_value = pd.Timestamp("2020-10-18 18:44", tz="US/Pacific") result = dta.shift(1, fill_value=fill_value) expected = dta.shift(1, fill_value=fill_value.tz_convert("UTC")) tm.assert_equal(result, expected) def test_tz_localize_t2d(self): dti = pd.date_range("1994-05-12", periods=12, tz="US/Pacific") dta = dti._data.reshape(3, 4) result = dta.tz_localize(None) expected = dta.ravel().tz_localize(None).reshape(dta.shape) tm.assert_datetime_array_equal(result, expected) roundtrip = expected.tz_localize("US/Pacific") tm.assert_datetime_array_equal(roundtrip, dta) @pytest.mark.parametrize( "tz", ["US/Eastern", "dateutil/US/Eastern", "pytz/US/Eastern"] ) def test_iter_zoneinfo_fold(self, tz): # GH#49684 if tz.startswith("pytz/"): pytz = pytest.importorskip("pytz") tz = pytz.timezone(tz.removeprefix("pytz/")) utc_vals = np.array( [1320552000, 1320555600, 1320559200, 1320562800], dtype=np.int64 ) utc_vals *= 1_000_000_000 dta = ( DatetimeArray._from_sequence(utc_vals, dtype=np.dtype("M8[ns]")) .tz_localize("UTC") .tz_convert(tz) ) left = dta[2] right = list(dta)[2] assert str(left) == str(right) # previously there was a bug where with non-pytz right would be # Timestamp('2011-11-06 01:00:00-0400', tz='US/Eastern') # while left would be # Timestamp('2011-11-06 01:00:00-0500', tz='US/Eastern') # The .value's would match (so they would compare as equal), # but the folds would not assert left.utcoffset() == right.utcoffset() # The same bug in ints_to_pydatetime affected .astype, so we test # that here. right2 = dta.astype(object)[2] assert str(left) == str(right2) assert left.utcoffset() == right2.utcoffset() @pytest.mark.parametrize( "freq", ["2M", "2SM", "2sm", "2Q", "2Q-SEP", "1Y", "2Y-MAR", "2m", "2q-sep", "2y"], ) def test_date_range_frequency_M_Q_Y_raises(self, freq): msg = f"Invalid frequency: {freq}" with pytest.raises(ValueError, match=msg): pd.date_range("1/1/2000", periods=4, freq=freq) @pytest.mark.parametrize("freq_depr", ["2MIN", "2nS", "2Us"]) def test_date_range_uppercase_frequency_deprecated(self, freq_depr): # GH#9586, GH#54939 depr_msg = ( f"'{freq_depr[1:]}' is deprecated and will be removed in a " f"future version, please use '{freq_depr.lower()[1:]}' instead." ) expected = pd.date_range("1/1/2000", periods=4, freq=freq_depr.lower()) with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): result = pd.date_range("1/1/2000", periods=4, freq=freq_depr) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "freq", [ "2ye-mar", "2ys", "2qe", "2qs-feb", "2bqs", "2sms", "2bms", "2cbme", "2me", ], ) def test_date_range_lowercase_frequency_raises(self, freq): msg = f"Invalid frequency: {freq}" with pytest.raises(ValueError, match=msg): pd.date_range("1/1/2000", periods=4, freq=freq) def test_date_range_lowercase_frequency_deprecated(self): # GH#9586, GH#54939 depr_msg = "'w' is deprecated and will be removed in a future version" expected = pd.date_range("1/1/2000", periods=4, freq="2W") with tm.assert_produces_warning(Pandas4Warning, match=depr_msg): result = pd.date_range("1/1/2000", periods=4, freq="2w") tm.assert_index_equal(result, expected) @pytest.mark.parametrize("freq", ["1A", "2A-MAR", "2a-mar"]) def test_date_range_frequency_A_raises(self, freq): msg = f"Invalid frequency: {freq}" with pytest.raises(ValueError, match=msg): pd.date_range("1/1/2000", periods=4, freq=freq) @pytest.mark.parametrize("freq", ["2H", "2CBH", "2S"]) def test_date_range_uppercase_frequency_raises(self, freq): msg = f"Invalid frequency: {freq}" with pytest.raises(ValueError, match=msg): pd.date_range("1/1/2000", periods=4, freq=freq) def test_factorize_sort_without_freq(): dta = DatetimeArray._from_sequence([0, 2, 1], dtype="M8[ns]") msg = r"call pd.factorize\(obj, sort=True\) instead" with pytest.raises(NotImplementedError, match=msg): dta.factorize(sort=True) # Do TimedeltaArray while we're here tda = dta - dta[0] with pytest.raises(NotImplementedError, match=msg): tda.factorize(sort=True)
TestDatetimeArray
python
numpy__numpy
numpy/_utils/_pep440.py
{ "start": 2335, "end": 3411 }
class ____: def __repr__(self): return "-Infinity" def __hash__(self): return hash(repr(self)) def __lt__(self, other): return True def __le__(self, other): return True def __eq__(self, other): return isinstance(other, self.__class__) def __ne__(self, other): return not isinstance(other, self.__class__) def __gt__(self, other): return False def __ge__(self, other): return False def __neg__(self): return Infinity # BEGIN packaging/version.py NegativeInfinity = NegativeInfinity() _Version = collections.namedtuple( "_Version", ["epoch", "release", "dev", "pre", "post", "local"], ) def parse(version): """ Parse the given version string and return either a :class:`Version` object or a :class:`LegacyVersion` object depending on if the given version is a valid PEP 440 version or a legacy version. """ try: return Version(version) except InvalidVersion: return LegacyVersion(version)
NegativeInfinity
python
doocs__leetcode
solution/0700-0799/0738.Monotone Increasing Digits/Solution.py
{ "start": 0, "end": 443 }
class ____: def monotoneIncreasingDigits(self, n: int) -> int: s = list(str(n)) i = 1 while i < len(s) and s[i - 1] <= s[i]: i += 1 if i < len(s): while i and s[i - 1] > s[i]: s[i - 1] = str(int(s[i - 1]) - 1) i -= 1 i += 1 while i < len(s): s[i] = '9' i += 1 return int(''.join(s))
Solution
python
django-haystack__django-haystack
test_haystack/test_fields.py
{ "start": 8339, "end": 9994 }
class ____(TestCase): def test_init(self): try: foo = EdgeNgramField(model_attr="foo") except: self.fail() self.assertRaises(SearchFieldError, EdgeNgramField, faceted=True) def test_prepare(self): mock = MockModel() mock.user = "daniel" author = EdgeNgramField(model_attr="user") self.assertEqual(author.prepare(mock), "daniel") # Do a lookup through the relation. mock_tag = MockTag.objects.create(name="primary") mock = MockModel() mock.tag = mock_tag tag_name = EdgeNgramField(model_attr="tag__name") self.assertEqual(tag_name.prepare(mock), "primary") # Use the default. mock = MockModel() author = EdgeNgramField(model_attr="author", default="") self.assertEqual(author.prepare(mock), "") # Simulate failed lookups. mock_tag = MockTag.objects.create(name="primary") mock = MockModel() mock.tag = mock_tag tag_slug = EdgeNgramField(model_attr="tag__slug") self.assertRaises(SearchFieldError, tag_slug.prepare, mock) # Simulate default='foo'. mock = MockModel() default = EdgeNgramField(default="foo") self.assertEqual(default.prepare(mock), "foo") # Simulate null=True. mock = MockModel() empty = EdgeNgramField(null=True) self.assertEqual(empty.prepare(mock), None) mock = MockModel() mock.user = None author = EdgeNgramField(model_attr="user", null=True) self.assertEqual(author.prepare(mock), None)
EdgeNgramFieldTestCase
python
getsentry__sentry
src/sentry/api/serializers/release_details_types.py
{ "start": 1711, "end": 1870 }
class ____(ProjectOptional): id: int slug: str name: str platform: str | None platforms: list[str] | None hasHealthData: bool
BaseProject
python
pytorch__pytorch
torch/_inductor/compile_fx_ext.py
{ "start": 3544, "end": 4268 }
class ____: """ This handles the data for serializing lowering.lowering """ # A full implementation would make sure that all lowerings are copied over # (or at least detected and raise a bypass when a non-standard lowering is # used). For now we just handle tests by looking for lowerings that were # overridden with a forced fallback. fallbacks: OrderedSet[str] def __init__(self) -> None: from . import lowering self.fallbacks = OrderedSet( str(k) for k, v in lowering.lowerings.items() if _is_fallback_handler(v) ) def patch(self) -> _LoweringSerializerContextManager: return _LoweringSerializerContextManager(self)
_LoweringSerializer
python
getsentry__sentry
src/sentry/api/serializers/models/rule.py
{ "start": 2557, "end": 12172 }
class ____(Serializer): def __init__( self, expand: list[str] | None = None, prepare_component_fields: bool = False, project_slug: str | None = None, ): super().__init__() self.expand = expand or [] self.prepare_component_fields = prepare_component_fields self.project_slug = project_slug def get_attrs(self, item_list, user, **kwargs): from sentry.sentry_apps.services.app import app_service prefetch_related_objects(item_list, "project") environments = Environment.objects.in_bulk( [_f for _f in [i.environment_id for i in item_list] if _f] ) result: dict[Rule, dict[str, Any]] result = {i: {"environment": environments.get(i.environment_id)} for i in item_list} ras = list( RuleActivity.objects.filter( rule__in=item_list, type=RuleActivityType.CREATED.value ).select_related("rule") ) users = { u.id: u for u in user_service.get_many_by_id( ids=[ra.user_id for ra in ras if ra.user_id is not None] ) } for rule_activity in ras: if rule_activity.user_id is None: creator = None else: u = users.get(rule_activity.user_id) if u: creator = { "id": u.id, "name": u.get_display_name(), "email": u.email, } else: creator = None result[rule_activity.rule].update({"created_by": creator}) rules = {item.id: item for item in item_list} sentry_app_installations_by_uuid: Mapping[str, RpcSentryAppComponentContext] = {} if self.prepare_component_fields: sentry_app_uuids = [ sentry_app_uuid for sentry_app_uuid in ( action.get("sentryAppInstallationUuid") for rule in rules.values() for action in rule.data.get("actions", []) ) if sentry_app_uuid is not None ] install_contexts = app_service.get_component_contexts( filter={"uuids": sentry_app_uuids}, component_type="alert-rule-action" ) sentry_app_installations_by_uuid = { install_context.installation.uuid: install_context for install_context in install_contexts } for rule in rules.values(): actor = rule.owner if actor: result[rule]["owner"] = actor.identifier errors = [] for action in rule.data.get("actions", []): install_context = sentry_app_installations_by_uuid.get( str(action.get("sentryAppInstallationUuid")) ) if install_context: rpc_install = install_context.installation rpc_component = install_context.component rpc_app = rpc_install.sentry_app component = ( prepare_ui_component( rpc_install, rpc_component, self.project_slug, action.get("settings"), ) if rpc_component else None ) if component is None: errors.append({"detail": f"Could not fetch details from {rpc_app.name}"}) action["disabled"] = True continue action["formFields"] = component.app_schema.get("settings", {}) if len(errors): result[rule]["errors"] = errors if "lastTriggered" in self.expand: last_triggered_lookup = { rfh["rule_id"]: rfh["date_added"] for rfh in RuleFireHistory.objects.filter(rule__in=item_list) .values("rule_id") .annotate(date_added=Max("date_added")) } # Update lastTriggered with WorkflowFireHistory if available if item_list: rule_ids = [rule.id for rule in item_list] workflow_rule_lookup = dict( AlertRuleWorkflow.objects.filter(rule_id__in=rule_ids).values_list( "workflow_id", "rule_id" ) ) workflow_fire_results = ( WorkflowFireHistory.objects.filter(workflow_id__in=workflow_rule_lookup.keys()) .values("workflow_id") .annotate(date_added=Max("date_added")) ) for wfh in workflow_fire_results: rule_id = workflow_rule_lookup.get(wfh["workflow_id"]) if rule_id: # Take the maximum date between RuleFireHistory and WorkflowFireHistory existing_date = last_triggered_lookup.get(rule_id) new_date = wfh["date_added"] if (existing_date and new_date > existing_date) or not existing_date: last_triggered_lookup[rule_id] = new_date # Set the results for rule in item_list: result[rule]["last_triggered"] = last_triggered_lookup.get(rule.id, None) neglected_rule_lookup = { nr["rule_id"]: nr["disable_date"] for nr in NeglectedRule.objects.filter( rule__in=item_list, opted_out=False, sent_initial_email_date__isnull=False, ).values("rule_id", "disable_date") } for rule in item_list: disable_date = neglected_rule_lookup.get(rule.id, None) if disable_date: result[rule]["disable_date"] = disable_date rule_snooze_lookup = { snooze["rule_id"]: {"user_id": snooze["user_id"], "owner_id": snooze["owner_id"]} for snooze in RuleSnooze.objects.filter( Q(user_id=user.id) | Q(user_id=None), rule__in=[item.id for item in item_list], ).values("rule_id", "user_id", "owner_id") } for rule in item_list: snooze = rule_snooze_lookup.get(rule.id, None) if snooze: result[rule]["snooze"] = snooze return result def serialize(self, obj, attrs, user, **kwargs) -> RuleSerializerResponse: environment = attrs["environment"] all_conditions = [ dict(list(o.items()) + [("name", generate_rule_label(obj.project, obj, o))]) for o in obj.data.get("conditions", []) ] actions = [] for action in obj.data.get("actions", []): try: actions.append( dict( list(action.items()) + [("name", generate_rule_label(obj.project, obj, action))] ) ) except serializers.ValidationError: # Integrations can be deleted and we don't want to fail to load the rule pass d: RuleSerializerResponse = { # XXX(dcramer): we currently serialize unsaved rule objects # as part of the rule editor "id": str(obj.id) if obj.id else None, # conditions pertain to criteria that can trigger an alert "conditions": list(filter(lambda condition: not _is_filter(condition), all_conditions)), # filters are not new conditions but are the subset of conditions that pertain to event attributes "filters": list(filter(lambda condition: _is_filter(condition), all_conditions)), "actions": actions, "actionMatch": obj.data.get("action_match") or Rule.DEFAULT_CONDITION_MATCH, "filterMatch": obj.data.get("filter_match") or Rule.DEFAULT_FILTER_MATCH, "frequency": obj.data.get("frequency") or Rule.DEFAULT_FREQUENCY, "name": obj.label, "dateCreated": obj.date_added, "owner": attrs.get("owner", None), "createdBy": attrs.get("created_by", None), "environment": environment.name if environment is not None else None, "projects": [obj.project.slug], "status": "active" if obj.status == ObjectStatus.ACTIVE else "disabled", "snooze": "snooze" in attrs, } if "last_triggered" in attrs: d["lastTriggered"] = attrs["last_triggered"] if "errors" in attrs: d["errors"] = attrs["errors"] if "snooze" in attrs: snooze = attrs["snooze"] created_by = None if user.id == snooze.get("owner_id"): created_by = "You" elif owner_id := snooze.get("owner_id"): creator = user_service.get_user(owner_id) if creator: created_by = creator.get_display_name() if created_by is not None: d["snoozeCreatedBy"] = created_by d["snoozeForEveryone"] = snooze.get("user_id") is None if "disable_date" in attrs: d["disableReason"] = "noisy" d["disableDate"] = attrs["disable_date"] return d
RuleSerializer
python
django__django
tests/admin_views/test_autocomplete_view.py
{ "start": 14744, "end": 23706 }
class ____(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) self.admin_login( username="super", password="secret", login_url=reverse("autocomplete_admin:index"), ) @contextmanager def select2_ajax_wait(self, timeout=10): from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec yield with self.disable_implicit_wait(): try: loading_element = self.selenium.find_element( By.CSS_SELECTOR, "li.select2-results__option.loading-results" ) except NoSuchElementException: pass else: self.wait_until(ec.staleness_of(loading_element), timeout=timeout) def test_select(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select self.selenium.get( self.live_server_url + reverse("autocomplete_admin:admin_views_answer_add") ) elem = self.selenium.find_element(By.CSS_SELECTOR, ".select2-selection") with self.select2_ajax_wait(): elem.click() # Open the autocomplete dropdown. results = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") self.assertTrue(results.is_displayed()) option = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results__option") self.assertEqual(option.text, "No results found") with self.select2_ajax_wait(): elem.click() # Close the autocomplete dropdown. q1 = Question.objects.create(question="Who am I?") Question.objects.bulk_create( Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10) ) with self.select2_ajax_wait(): elem.click() # Reopen the dropdown now that some objects exist. result_container = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results" ) self.assertTrue(result_container.is_displayed()) # PAGINATOR_SIZE results and "Loading more results". self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 1, root_element=result_container, ) search = self.selenium.find_element(By.CSS_SELECTOR, ".select2-search__field") # Load next page of results by scrolling to the bottom of the list. for _ in range(PAGINATOR_SIZE + 1): with self.select2_ajax_wait(): search.send_keys(Keys.ARROW_DOWN) # All objects are now loaded. self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 11, root_element=result_container, ) # Limit the results with the search field. with self.select2_ajax_wait(): search.send_keys("Who") # Ajax request is delayed. self.assertTrue(result_container.is_displayed()) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 12, root_element=result_container, ) self.assertTrue(result_container.is_displayed()) self.assertCountSeleniumElements( ".select2-results__option", 1, root_element=result_container ) # Select the result. with self.select2_ajax_wait(): search.send_keys(Keys.RETURN) select = Select(self.selenium.find_element(By.ID, "id_question")) self.assertEqual( select.first_selected_option.get_attribute("value"), str(q1.pk) ) def test_select_multiple(self): from selenium.common import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select self.selenium.get( self.live_server_url + reverse("autocomplete_admin:admin_views_question_add") ) elem = self.selenium.find_element(By.CSS_SELECTOR, ".select2-selection") with self.select2_ajax_wait(): elem.click() # Open the autocomplete dropdown. results = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") self.assertTrue(results.is_displayed()) option = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results__option") self.assertEqual(option.text, "No results found") with self.select2_ajax_wait(): elem.click() # Close the autocomplete dropdown. Question.objects.create(question="Who am I?") Question.objects.bulk_create( Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10) ) with self.select2_ajax_wait(): elem.click() # Reopen the dropdown now that some objects exist. result_container = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results" ) self.assertIs(result_container.is_displayed(), True) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 1, root_element=result_container, ) search = self.selenium.find_element(By.CSS_SELECTOR, ".select2-search__field") # Load next page of results by scrolling to the bottom of the list. for _ in range(PAGINATOR_SIZE + 1): with self.select2_ajax_wait(): search.send_keys(Keys.ARROW_DOWN) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 11, root_element=result_container, ) # Limit the results with the search field. with self.select2_ajax_wait(): search.send_keys("Who") # Ajax request is delayed. self.assertIs(result_container.is_displayed(), True) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 12, root_element=result_container, ) self.assertIs(result_container.is_displayed(), True) self.assertCountSeleniumElements( ".select2-results__option", 1, root_element=result_container ) with self.select2_ajax_wait(): # Select the result. search.send_keys(Keys.RETURN) with self.disable_implicit_wait(): with self.assertRaises(NoSuchElementException): self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") with self.select2_ajax_wait(): # Reopen the dropdown. elem.click() result_container = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results" ) self.assertIs(result_container.is_displayed(), True) with self.select2_ajax_wait(): # Add the first result to the selection. search.send_keys(Keys.ARROW_DOWN) search.send_keys(Keys.RETURN) select = Select(self.selenium.find_element(By.ID, "id_related_questions")) self.assertEqual(len(select.all_selected_options), 2) def test_inline_add_another_widgets(self): from selenium.webdriver.common.by import By def assertNoResults(row): elem = row.find_element(By.CSS_SELECTOR, ".select2-selection") with self.select2_ajax_wait(): elem.click() # Open the autocomplete dropdown. results = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") self.assertTrue(results.is_displayed()) option = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results__option" ) self.assertEqual(option.text, "No results found") # Autocomplete works in rows present when the page loads. self.selenium.get( self.live_server_url + reverse("autocomplete_admin:admin_views_book_add") ) rows = self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-authorship_set") self.assertEqual(len(rows), 3) assertNoResults(rows[0]) # Autocomplete works in rows added using the "Add another" button. self.selenium.find_element(By.LINK_TEXT, "Add another Authorship").click() rows = self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-authorship_set") self.assertEqual(len(rows), 4) assertNoResults(rows[-1])
SeleniumTests
python
run-llama__llama_index
llama-index-core/llama_index/core/callbacks/llama_debug.py
{ "start": 383, "end": 7768 }
class ____(PythonicallyPrintingBaseHandler): """ Callback handler that keeps track of debug info. NOTE: this is a beta feature. The usage within our codebase, and the interface may change. This handler simply keeps track of event starts/ends, separated by event types. You can use this callback handler to keep track of and debug events. Args: event_starts_to_ignore (Optional[List[CBEventType]]): list of event types to ignore when tracking event starts. event_ends_to_ignore (Optional[List[CBEventType]]): list of event types to ignore when tracking event ends. """ def __init__( self, event_starts_to_ignore: Optional[List[CBEventType]] = None, event_ends_to_ignore: Optional[List[CBEventType]] = None, print_trace_on_end: bool = True, logger: Optional[logging.Logger] = None, ) -> None: """Initialize the llama debug handler.""" self._event_pairs_by_type: Dict[CBEventType, List[CBEvent]] = defaultdict(list) self._event_pairs_by_id: Dict[str, List[CBEvent]] = defaultdict(list) self._sequential_events: List[CBEvent] = [] self._cur_trace_id: Optional[str] = None self._trace_map: Dict[str, List[str]] = defaultdict(list) self.print_trace_on_end = print_trace_on_end event_starts_to_ignore = ( event_starts_to_ignore if event_starts_to_ignore else [] ) event_ends_to_ignore = event_ends_to_ignore if event_ends_to_ignore else [] super().__init__( event_starts_to_ignore=event_starts_to_ignore, event_ends_to_ignore=event_ends_to_ignore, logger=logger, ) def on_event_start( self, event_type: CBEventType, payload: Optional[Dict[str, Any]] = None, event_id: str = "", parent_id: str = "", **kwargs: Any, ) -> str: """ Store event start data by event type. Args: event_type (CBEventType): event type to store. payload (Optional[Dict[str, Any]]): payload to store. event_id (str): event id to store. parent_id (str): parent event id. """ event = CBEvent(event_type, payload=payload, id_=event_id) self._event_pairs_by_type[event.event_type].append(event) self._event_pairs_by_id[event.id_].append(event) self._sequential_events.append(event) return event.id_ def on_event_end( self, event_type: CBEventType, payload: Optional[Dict[str, Any]] = None, event_id: str = "", **kwargs: Any, ) -> None: """ Store event end data by event type. Args: event_type (CBEventType): event type to store. payload (Optional[Dict[str, Any]]): payload to store. event_id (str): event id to store. """ event = CBEvent(event_type, payload=payload, id_=event_id) self._event_pairs_by_type[event.event_type].append(event) self._event_pairs_by_id[event.id_].append(event) self._sequential_events.append(event) self._trace_map = defaultdict(list) def get_events(self, event_type: Optional[CBEventType] = None) -> List[CBEvent]: """Get all events for a specific event type.""" if event_type is not None: return self._event_pairs_by_type[event_type] return self._sequential_events def _get_event_pairs(self, events: List[CBEvent]) -> List[List[CBEvent]]: """Helper function to pair events according to their ID.""" event_pairs: Dict[str, List[CBEvent]] = defaultdict(list) for event in events: event_pairs[event.id_].append(event) return sorted( event_pairs.values(), key=lambda x: datetime.strptime(x[0].time, TIMESTAMP_FORMAT), ) def _get_time_stats_from_event_pairs( self, event_pairs: List[List[CBEvent]] ) -> EventStats: """Calculate time-based stats for a set of event pairs.""" total_secs = 0.0 for event_pair in event_pairs: start_time = datetime.strptime(event_pair[0].time, TIMESTAMP_FORMAT) end_time = datetime.strptime(event_pair[-1].time, TIMESTAMP_FORMAT) total_secs += (end_time - start_time).total_seconds() return EventStats( total_secs=total_secs, average_secs=total_secs / len(event_pairs), total_count=len(event_pairs), ) def get_event_pairs( self, event_type: Optional[CBEventType] = None ) -> List[List[CBEvent]]: """Pair events by ID, either all events or a specific type.""" if event_type is not None: return self._get_event_pairs(self._event_pairs_by_type[event_type]) return self._get_event_pairs(self._sequential_events) def get_llm_inputs_outputs(self) -> List[List[CBEvent]]: """Get the exact LLM inputs and outputs.""" return self._get_event_pairs(self._event_pairs_by_type[CBEventType.LLM]) def get_event_time_info( self, event_type: Optional[CBEventType] = None ) -> EventStats: event_pairs = self.get_event_pairs(event_type) return self._get_time_stats_from_event_pairs(event_pairs) def flush_event_logs(self) -> None: """Clear all events from memory.""" self._event_pairs_by_type = defaultdict(list) self._event_pairs_by_id = defaultdict(list) self._sequential_events = [] def start_trace(self, trace_id: Optional[str] = None) -> None: """Launch a trace.""" self._trace_map = defaultdict(list) self._cur_trace_id = trace_id def end_trace( self, trace_id: Optional[str] = None, trace_map: Optional[Dict[str, List[str]]] = None, ) -> None: """Shutdown the current trace.""" self._trace_map = trace_map or defaultdict(list) if self.print_trace_on_end: self.print_trace_map() def _print_trace_map(self, cur_event_id: str, level: int = 0) -> None: """Recursively print trace map to terminal for debugging.""" event_pair = self._event_pairs_by_id[cur_event_id] if event_pair: time_stats = self._get_time_stats_from_event_pairs([event_pair]) indent = " " * level * 2 self._print( f"{indent}|_{event_pair[0].event_type} -> {time_stats.total_secs} seconds", ) child_event_ids = self._trace_map[cur_event_id] for child_event_id in child_event_ids: self._print_trace_map(child_event_id, level=level + 1) def print_trace_map(self) -> None: """Print simple trace map to terminal for debugging of the most recent trace.""" self._print("*" * 10) self._print(f"Trace: {self._cur_trace_id}") self._print_trace_map(BASE_TRACE_EVENT, level=1) self._print("*" * 10) @property def event_pairs_by_type(self) -> Dict[CBEventType, List[CBEvent]]: return self._event_pairs_by_type @property def events_pairs_by_id(self) -> Dict[str, List[CBEvent]]: return self._event_pairs_by_id @property def sequential_events(self) -> List[CBEvent]: return self._sequential_events
LlamaDebugHandler
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query_parameters_where.py
{ "start": 1300, "end": 1780 }
class ____: def test5_alarm1(self, x: List[str]): pass def test5_alarm2(self, x: List[int]): pass def test5_alarm3(self, x: C): pass def test5_alarm4(self, x: str): pass def test5_noalarm1(self, x: int): pass def test6_alarm1(a, b, c, d): _test_sink(a) def test6_noalarm1(a, b, c, d): _test_sink(b) def test6_alarm2(a, b, c, d): _test_sink(c) def test6_noalarm2(a, b, c, d): _test_sink(d)
Test5
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/ColorBarItem.py
{ "start": 195, "end": 3349 }
class ____(QtWidgets.QMainWindow): """ example application main window """ def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) gr_wid = pg.GraphicsLayoutWidget(show=True) self.setCentralWidget(gr_wid) self.setWindowTitle('pyqtgraph example: Interactive color bar') self.resize(800,700) self.show() ## Create image items data = np.fromfunction(lambda i, j: (1+0.3*np.sin(i)) * (i)**2 + (j)**2, (100, 100)) noisy_data = data * (1 + 0.2 * np.random.random(data.shape) ) noisy_transposed = noisy_data.transpose() #--- add non-interactive image with integrated color ------------------ p1 = gr_wid.addPlot(title="non-interactive") # Basic steps to create a false color image with color bar: i1 = pg.ImageItem(image=data) p1.addItem( i1 ) p1.addColorBar( i1, colorMap='CET-L9', values=(0, 30_000)) # , interactive=False) # p1.setMouseEnabled( x=False, y=False) p1.disableAutoRange() p1.hideButtons() p1.setRange(xRange=(0,100), yRange=(0,100), padding=0) p1.showAxes(True, showValues=(True,False,False,True) ) #--- add interactive image with integrated horizontal color bar ------- i2 = pg.ImageItem(image=noisy_data) p2 = gr_wid.addPlot(1,0, 1,1, title="interactive") p2.addItem( i2, title='' ) # inserted color bar also works with labels on the right. p2.showAxis('right') p2.getAxis('left').setStyle( showValues=False ) p2.getAxis('bottom').setLabel('bottom axis label') p2.getAxis('right').setLabel('right axis label') bar = pg.ColorBarItem( values = (0, 30_000), colorMap='CET-L4', label='horizontal color bar', limits = (0, None), rounding=1000, orientation = 'h', pen='#8888FF', hoverPen='#EEEEFF', hoverBrush='#EEEEFF80' ) bar.setImageItem( i2, insert_in=p2 ) #--- multiple images adjusted by a separate color bar ------------------------ i3 = pg.ImageItem(image=noisy_data) p3 = gr_wid.addPlot(0,1, 1,1, title="shared 1") p3.addItem( i3 ) i4 = pg.ImageItem(image=noisy_transposed) p4 = gr_wid.addPlot(1,1, 1,1, title="shared 2") p4.addItem( i4 ) cmap = pg.colormap.get('CET-L8') bar = pg.ColorBarItem( # values = (-15_000, 15_000), limits = (-30_000, 30_000), # start with full range... rounding=1000, width = 10, colorMap=cmap ) bar.setImageItem( [i3, i4] ) bar.setLevels( low=-5_000, high=15_000) # ... then adjust to retro sunset. # manually adjust reserved space at top and bottom to align with plot bar.getAxis('bottom').setHeight(21) bar.getAxis('top').setHeight(31) gr_wid.addItem(bar, 0,2, 2,1) # large bar spanning both rows mkQApp("ColorBarItem Example") main_window = MainWindow() ## Start Qt event loop if __name__ == '__main__': pg.exec()
MainWindow
python
astropy__astropy
astropy/modeling/tests/test_parameters.py
{ "start": 5480, "end": 26638 }
class ____: def setup_class(self): """ Unit tests for parameters Read an iraf database file created by onedspec.identify. Use the information to create a 1D Chebyshev model and perform the same fit. Create also a gaussian model. """ test_file = get_pkg_data_filename("data/idcompspec.fits") f = open(test_file) lines = f.read() reclist = lines.split("begin") f.close() record = irafutil.IdentifyRecord(reclist[1]) self.icoeff = record.coeff order = int(record.fields["order"]) self.model = models.Chebyshev1D(order - 1) self.gmodel = models.Gaussian1D(2, mean=3, stddev=4) self.linear_fitter = fitting.LinearLSQFitter() self.x = record.x self.y = record.z self.yy = np.array([record.z, record.z]) def test_set_parameters_as_list(self): """Tests updating parameters using a list.""" self.model.parameters = [30, 40, 50, 60, 70] assert (self.model.parameters == [30.0, 40.0, 50.0, 60, 70]).all() def test_set_parameters_as_array(self): """Tests updating parameters using an array.""" self.model.parameters = np.array([3, 4, 5, 6, 7]) assert (self.model.parameters == [3.0, 4.0, 5.0, 6.0, 7.0]).all() def test_set_as_tuple(self): """Tests updating parameters using a tuple.""" self.model.parameters = (1, 2, 3, 4, 5) assert (self.model.parameters == [1, 2, 3, 4, 5]).all() def test_set_model_attr_seq(self): """ Tests updating the parameters attribute when a model's parameter (in this case coeff) is updated. """ self.model.parameters = [0, 0.0, 0.0, 0, 0] self.model.c0 = 7 assert (self.model.parameters == [7, 0.0, 0.0, 0, 0]).all() def test_set_model_attr_num(self): """Update the parameter list when a model's parameter is updated.""" self.gmodel.amplitude = 7 assert (self.gmodel.parameters == [7, 3, 4]).all() def test_set_item(self): """Update the parameters using indexing.""" self.model.parameters = [1, 2, 3, 4, 5] tpar = self.model.parameters tpar[0] = 10.0 self.model.parameters = tpar assert (self.model.parameters == [10, 2, 3, 4, 5]).all() assert self.model.c0 == 10 def test_wrong_size1(self): """ Tests raising an error when attempting to reset the parameters using a list of a different size. """ MESSAGE = ( r"Input parameter values not compatible with the model parameters array: .*" ) with pytest.raises(InputParameterError, match=MESSAGE): self.model.parameters = [1, 2, 3] def test_wrong_size2(self): """ Tests raising an exception when attempting to update a model's parameter (in this case coeff) with a sequence of the wrong size. """ MESSAGE = ( r"Value for parameter c0 does not match shape or size\nexpected by model .*" r" vs .*" ) with pytest.raises(InputParameterError, match=MESSAGE): self.model.c0 = [1, 2, 3] def test_wrong_shape(self): """ Tests raising an exception when attempting to update a model's parameter and the new value has the wrong shape. """ MESSAGE = ( r"Value for parameter amplitude does not match shape or size\nexpected by" r" model .* vs .*" ) with pytest.raises(InputParameterError, match=MESSAGE): self.gmodel.amplitude = [1, 2] def test_par_against_iraf(self): """ Test the fitter modifies model.parameters. Uses an iraf example. """ new_model = self.linear_fitter(self.model, self.x, self.y) np.testing.assert_allclose( new_model.parameters, np.array( [ 4826.1066602783685, 952.8943813407858, 12.641236013982386, -1.7910672553339604, 0.90252884366711317, ] ), rtol=10 ** (-2), ) def testPolynomial1D(self): d = {"c0": 11, "c1": 12, "c2": 13, "c3": 14} p1 = models.Polynomial1D(3, **d) np.testing.assert_equal(p1.parameters, [11, 12, 13, 14]) def test_poly1d_multiple_sets(self): p1 = models.Polynomial1D(3, n_models=3) np.testing.assert_equal( p1.parameters, [0.0, 0.0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) np.testing.assert_array_equal(p1.c0, [0, 0, 0]) p1.c0 = [10, 10, 10] np.testing.assert_equal( p1.parameters, [10.0, 10.0, 10.0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) def test_par_slicing(self): """ Test assigning to a parameter slice """ p1 = models.Polynomial1D(3, n_models=3) p1.c0[:2] = [10, 10] np.testing.assert_equal( p1.parameters, [10.0, 10.0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) def test_poly2d(self): p2 = models.Polynomial2D(degree=3) p2.c0_0 = 5 np.testing.assert_equal(p2.parameters, [5, 0, 0, 0, 0, 0, 0, 0, 0, 0]) def test_poly2d_multiple_sets(self): kw = { "c0_0": [2, 3], "c1_0": [1, 2], "c2_0": [4, 5], "c0_1": [1, 1], "c0_2": [2, 2], "c1_1": [5, 5], } p2 = models.Polynomial2D(2, **kw) np.testing.assert_equal(p2.parameters, [2, 3, 1, 2, 4, 5, 1, 1, 2, 2, 5, 5]) def test_shift_model_parameters1d(self): sh1 = models.Shift(2) sh1.offset = 3 assert sh1.offset == 3 assert sh1.offset.value == 3 def test_scale_model_parametersnd(self): sc1 = models.Scale([2, 2]) sc1.factor = [3, 3] assert np.all(sc1.factor == [3, 3]) np.testing.assert_array_equal(sc1.factor.value, [3, 3]) def test_bounds(self): # Valid __init__ param = Parameter(bounds=(1, 2)) assert param.bounds == (1, 2) param = Parameter(min=1, max=2) assert param.bounds == (1, 2) # Errors __init__ MESSAGE = r"bounds may not be specified simultaneously with min or max .*" with pytest.raises(ValueError, match=MESSAGE): Parameter(bounds=(1, 2), min=1, name="test") with pytest.raises(ValueError, match=MESSAGE): Parameter(bounds=(1, 2), max=2, name="test") with pytest.raises(ValueError, match=MESSAGE): Parameter(bounds=(1, 2), min=1, max=2, name="test") # Setters param = Parameter(name="test", default=[1, 2, 3, 4]) assert param.bounds == (None, None) == param._bounds # Set errors MESSAGE = "{} value must be a number or a Quantity" with pytest.raises(TypeError, match=MESSAGE.format("Min")): param.bounds = ("test", None) with pytest.raises(TypeError, match=MESSAGE.format("Max")): param.bounds = (None, "test") # Set number param.bounds = (1, 2) assert param.bounds == (1, 2) == param._bounds # Set Quantity param.bounds = (1 * u.m, 2 * u.m) assert param.bounds == (1, 2) == param._bounds def test_modify_value(self): param = Parameter(name="test", default=[1, 2, 3]) assert (param.value == [1, 2, 3]).all() # Errors MESSAGE = r"Slice assignment outside the parameter dimensions for 'test'" with pytest.raises(InputParameterError, match=MESSAGE): param[slice(0, 0)] = 2 MESSAGE = r"Input dimension 3 invalid for 'test' parameter with dimension 1" with pytest.raises(InputParameterError, match=MESSAGE): param[3] = np.array([5]) # assignment of a slice param[slice(0, 2)] = [4, 5] assert (param.value == [4, 5, 3]).all() # assignment of a value param[2] = 6 assert (param.value == [4, 5, 6]).all() def test__set_unit(self): param = Parameter(name="test", default=[1, 2, 3]) assert param.unit is None # No force Error (no existing unit) MESSAGE = r"Cannot attach units to parameters that were .*" with pytest.raises(ValueError, match=MESSAGE): param._set_unit(u.m) # Force param._set_unit(u.m, True) assert param.unit == u.m # Force magnitude unit (mag=False) MESSAGE = r"This parameter does not support the magnitude units such as .*" with pytest.raises(ValueError, match=MESSAGE): param._set_unit(u.ABmag, True) # Force magnitude unit (mag=True) param._mag = True param._set_unit(u.ABmag, True) assert param._unit == u.ABmag # No force Error (existing unit) MESSAGE = r"Cannot change the unit attribute directly, instead change the .*" with pytest.raises(ValueError, match=MESSAGE): param._set_unit(u.K) def test_quantity(self): param = Parameter(name="test", default=[1, 2, 3]) assert param.unit is None assert param.quantity is None param = Parameter(name="test", default=[1, 2, 3], unit=u.m) assert param.unit == u.m assert (param.quantity == np.array([1, 2, 3]) * u.m).all() def test_shape(self): # Array like param = Parameter(name="test", default=[1, 2, 3, 4]) assert param.shape == (4,) # Reshape error MESSAGE = r"cannot reshape array of size 4 into shape .*" with pytest.raises(ValueError, match=MESSAGE): param.shape = (5,) # Reshape success param.shape = (2, 2) assert param.shape == (2, 2) assert (param.value == [[1, 2], [3, 4]]).all() # Scalar param = Parameter(name="test", default=1) assert param.shape == () # Reshape error MESSAGE = r"Cannot assign this shape to a scalar quantity" with pytest.raises(ValueError, match=MESSAGE): param.shape = (5,) param.shape = (1,) # single value param = Parameter(name="test", default=np.array([1])) assert param.shape == (1,) # Reshape error with pytest.raises(ValueError, match=MESSAGE): param.shape = (5,) param.shape = () def test_size(self): param = Parameter(name="test", default=[1, 2, 3, 4]) assert param.size == 4 param = Parameter(name="test", default=[1]) assert param.size == 1 param = Parameter(name="test", default=1) assert param.size == 1 def test_std(self): param = Parameter(name="test", default=[1, 2, 3, 4]) assert param.std is None assert param._std is None param.std = 5 assert param.std == 5 == param._std def test_fixed(self): param = Parameter(name="test", default=[1, 2, 3, 4]) assert param.fixed is False assert param._fixed is False # Set error MESSAGE = r"Value must be boolean" with pytest.raises(ValueError, match=MESSAGE): param.fixed = 3 # Set param.fixed = True assert param.fixed is True assert param._fixed is True def test_tied(self): param = Parameter(name="test", default=[1, 2, 3, 4]) assert param.tied is False assert param._tied is False # Set error MESSAGE = r"Tied must be a callable or set to False or None" with pytest.raises(TypeError, match=MESSAGE): param.tied = mk.NonCallableMagicMock() # Set None param.tied = None assert param.tied is None assert param._tied is None # Set False param.tied = False assert param.tied is False assert param._tied is False # Set other tied = mk.MagicMock() param.tied = tied assert param.tied == tied == param._tied def test_validator(self): param = Parameter(name="test", default=[1, 2, 3, 4]) assert param._validator is None valid = mk.MagicMock() param.validator(valid) assert param._validator == valid MESSAGE = r"This decorator method expects a callable.*" with pytest.raises(ValueError, match=MESSAGE): param.validator(mk.NonCallableMagicMock()) def test_validate(self): param = Parameter(name="test", default=[1, 2, 3, 4]) assert param._validator is None assert param.model is None # Run without validator param.validate(mk.MagicMock()) # Run with validator but no Model validator = mk.MagicMock() param.validator(validator) assert param._validator == validator param.validate(mk.MagicMock()) assert validator.call_args_list == [] # Full validate param._model = mk.MagicMock() value = mk.MagicMock() param.validate(value) assert validator.call_args_list == [mk.call(param._model, value)] def test_copy(self): param = Parameter(name="test", default=[1, 2, 3, 4]) copy_param = param.copy() assert (param == copy_param).all() assert id(param) != id(copy_param) def test_model(self): param = Parameter(name="test", default=[1, 2, 3, 4]) assert param.model is None assert param._model is None assert param._model_required is False assert (param._value == [1, 2, 3, 4]).all() setter = mk.MagicMock() getter = mk.MagicMock() param._setter = setter param._getter = getter # No Model Required param._value = [5, 6, 7, 8] model0 = mk.MagicMock() setter0 = mk.MagicMock() getter0 = mk.MagicMock() with mk.patch.object( Parameter, "_create_value_wrapper", side_effect=[setter0, getter0] ) as mkCreate: param.model = model0 assert param.model == model0 == param._model assert param._setter == setter0 assert param._getter == getter0 assert mkCreate.call_args_list == [ mk.call(setter, model0), mk.call(getter, model0), ] assert param._value == [5, 6, 7, 8] param._setter = setter param._getter = getter # Model required param._model_required = True model1 = mk.MagicMock() setter1 = mk.MagicMock() getter1 = mk.MagicMock() setter1.return_value = np.array([9, 10, 11, 12]) getter1.return_value = np.array([9, 10, 11, 12]) with mk.patch.object( Parameter, "_create_value_wrapper", side_effect=[setter1, getter1] ) as mkCreate: param.model = model1 assert param.model == model1 == param._model assert param._setter == setter1 assert param._getter == getter1 assert mkCreate.call_args_list == [ mk.call(setter, model1), mk.call(getter, model1), ] assert (param.value == [9, 10, 11, 12]).all() param._setter = setter param._getter = getter param._default = None with mk.patch.object( Parameter, "_create_value_wrapper", side_effect=[setter1, getter1] ) as mkCreate: param.model = model1 assert param.model == model1 == param._model assert param._setter == setter1 assert param._getter == getter1 assert mkCreate.call_args_list == [ mk.call(setter, model1), mk.call(getter, model1), ] assert param._value is None def test_value(self): param = Parameter(name="test", default=1) assert not isinstance(param.value, np.ndarray) assert param.value == 1 param = Parameter(name="test", default=[1]) assert not isinstance(param.value, np.ndarray) assert param.value == 1 param = Parameter(name="test", default=[[1]]) assert not isinstance(param.value, np.ndarray) assert param.value == 1 param = Parameter(name="test", default=np.array([1])) assert not isinstance(param.value, np.ndarray) assert param.value == 1 param = Parameter(name="test", default=[1, 2, 3]) assert isinstance(param.value, np.ndarray) assert (param.value == [1, 2, 3]).all() param = Parameter(name="test", default=[1], setter=setter1, getter=getter1) assert not isinstance(param.value, np.ndarray) assert param.value == 1 param = Parameter(name="test", default=[[1]], setter=setter1, getter=getter1) assert not isinstance(param.value, np.ndarray) assert param.value == 1 param = Parameter( name="test", default=np.array([1]), setter=setter1, getter=getter1 ) assert not isinstance(param.value, np.ndarray) assert param.value == 1 def test_raw_value(self): param = Parameter(name="test", default=[1, 2, 3, 4]) # Normal case assert (param._raw_value == param.value).all() # Bad setter param._setter = True param._internal_value = 4 assert param._raw_value == 4 def test__create_value_wrapper(self): param = Parameter(name="test", default=[1, 2, 3, 4]) # Bad ufunc MESSAGE = r"A numpy.ufunc used for Parameter getter/setter .*" with pytest.raises(TypeError, match=MESSAGE): param._create_value_wrapper(np.add, mk.MagicMock()) # Good ufunc with mk.patch( "astropy.modeling.parameters._wrap_ufunc", autospec=True ) as mkWrap: assert ( param._create_value_wrapper(np.negative, mk.MagicMock()) == mkWrap.return_value ) assert mkWrap.call_args_list == [mk.call(np.negative)] # None assert param._create_value_wrapper(None, mk.MagicMock()) is None # wrapper with one argument def wrapper1(a): pass assert param._create_value_wrapper(wrapper1, mk.MagicMock()) == wrapper1 # wrapper with two argument2 def wrapper2(a, b): pass # model is None assert param._model_required is False assert param._create_value_wrapper(wrapper2, None) == wrapper2 assert param._model_required is True # model is not None param._model_required = False model = mk.MagicMock() partial_wrapper = param._create_value_wrapper(wrapper2, model) assert isinstance(partial_wrapper, functools.partial) assert partial_wrapper.func is wrapper2 assert partial_wrapper.args == () assert list(partial_wrapper.keywords.keys()) == ["b"] assert partial_wrapper.keywords["b"] is model # wrapper with more than 2 arguments def wrapper3(a, b, c): pass MESSAGE = r"Parameter getter/setter must be a function .*" with pytest.raises(TypeError, match=MESSAGE): param._create_value_wrapper(wrapper3, mk.MagicMock()) def test_bool(self): # single value is true param = Parameter(name="test", default=1) assert param.value == 1 assert np.all(param) assert param # single value is false param = Parameter(name="test", default=0) assert param.value == 0 assert not np.all(param) assert not param # vector value all true param = Parameter(name="test", default=[1, 2, 3, 4]) assert np.all(param.value == [1, 2, 3, 4]) assert np.all(param) assert param # vector value at least one false param = Parameter(name="test", default=[1, 2, 0, 3, 4]) assert np.all(param.value == [1, 2, 0, 3, 4]) assert not np.all(param) assert not param def test_param_repr_oneline(self): # Single value no units param = Parameter(name="test", default=1) assert param_repr_oneline(param) == "1." # Vector value no units param = Parameter(name="test", default=[1, 2, 3, 4]) assert param_repr_oneline(param) == "[1., 2., 3., 4.]" # Single value units param = Parameter(name="test", default=1 * u.m) assert param_repr_oneline(param) == "1. m" # Vector value units param = Parameter(name="test", default=[1, 2, 3, 4] * u.m) assert param_repr_oneline(param) == "[1., 2., 3., 4.] m" def test_getter_setter(self): msg = "setter and getter must both be input" with pytest.raises(ValueError, match=msg): Parameter(name="test", default=1, getter=getter1) with pytest.raises(ValueError, match=msg): Parameter(name="test", default=1, setter=setter1)
TestParameters
python
getsentry__sentry
src/sentry/notifications/notification_action/action_validation.py
{ "start": 4611, "end": 4840 }
class ____(TicketingActionValidatorHandler): provider = Action.Type.JIRA_SERVER notify_action_form = JiraServerNotifyServiceForm @action_validator_registry.register(Action.Type.AZURE_DEVOPS)
JiraServerActionValidatorHandler
python
PrefectHQ__prefect
src/prefect/task_runners.py
{ "start": 31629, "end": 34524 }
class ____(TaskRunner[PrefectDistributedFuture[R]]): def __init__(self): super().__init__() def duplicate(self) -> "PrefectTaskRunner[R]": return type(self)() @overload def submit( self, task: "Task[P, CoroutineType[Any, Any, R]]", parameters: dict[str, Any], wait_for: Iterable[PrefectFuture[Any]] | None = None, dependencies: dict[str, set[RunInput]] | None = None, ) -> PrefectDistributedFuture[R]: ... @overload def submit( self, task: "Task[Any, R]", parameters: dict[str, Any], wait_for: Iterable[PrefectFuture[Any]] | None = None, dependencies: dict[str, set[RunInput]] | None = None, ) -> PrefectDistributedFuture[R]: ... def submit( self, task: "Task[P, R | CoroutineType[Any, Any, R]]", parameters: dict[str, Any], wait_for: Iterable[PrefectFuture[Any]] | None = None, dependencies: dict[str, set[RunInput]] | None = None, ) -> PrefectDistributedFuture[R]: """ Submit a task to the task run engine running in a separate thread. Args: task: The task to submit. parameters: The parameters to use when running the task. wait_for: A list of futures that the task depends on. Returns: A future object that can be used to wait for the task to complete and retrieve the result. """ if not self._started: raise RuntimeError("Task runner is not started") from prefect.context import FlowRunContext flow_run_ctx = FlowRunContext.get() if flow_run_ctx: get_run_logger(flow_run_ctx).info( f"Submitting task {task.name} to for execution by a Prefect task worker..." ) else: self.logger.info( f"Submitting task {task.name} to for execution by a Prefect task worker..." ) return task.apply_async( kwargs=parameters, wait_for=wait_for, dependencies=dependencies ) @overload def map( self, task: "Task[P, CoroutineType[Any, Any, R]]", parameters: dict[str, Any], wait_for: Iterable[PrefectFuture[Any]] | None = None, ) -> PrefectFutureList[PrefectDistributedFuture[R]]: ... @overload def map( self, task: "Task[Any, R]", parameters: dict[str, Any], wait_for: Iterable[PrefectFuture[Any]] | None = None, ) -> PrefectFutureList[PrefectDistributedFuture[R]]: ... def map( self, task: "Task[P, R | CoroutineType[Any, Any, R]]", parameters: dict[str, Any], wait_for: Iterable[PrefectFuture[Any]] | None = None, ) -> PrefectFutureList[PrefectDistributedFuture[R]]: return super().map(task, parameters, wait_for)
PrefectTaskRunner
python
keras-team__keras
keras/src/ops/operation_test.py
{ "start": 571, "end": 850 }
class ____(operation.Operation): def call(self, x): return (x, x + 1) def compute_output_spec(self, x): return ( keras_tensor.KerasTensor(x.shape, x.dtype), keras_tensor.KerasTensor(x.shape, x.dtype), )
OpWithMultipleOutputs
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarTuple12.py
{ "start": 449, "end": 793 }
class ____(Protocol[*Ts, T]): def __call__(self, *args: *Ts, keyed: T) -> tuple[Unpack[Ts], T]: ... def example(a: int, b: str, *, keyed: bool) -> tuple[int, str, bool]: return (a, b, keyed) a: CallbackA[int, str, bool] = example reveal_type( a, expected_text="(a: int, b: str, *, keyed: bool) -> tuple[int, str, bool]" )
CallbackA
python
altair-viz__altair
altair/utils/data.py
{ "start": 2906, "end": 3387 }
class ____(PluginRegistry[DataTransformerType, R]): _global_settings = {"consolidate_datasets": True} @property def consolidate_datasets(self) -> bool: return self._global_settings["consolidate_datasets"] @consolidate_datasets.setter def consolidate_datasets(self, value: bool) -> None: self._global_settings["consolidate_datasets"] = value # ==============================================================================
DataTransformerRegistry
python
huggingface__transformers
src/transformers/models/maskformer/modeling_maskformer_swin.py
{ "start": 10456, "end": 12841 }
class ____(nn.Module): """ Patch Merging Layer. Args: input_resolution (`tuple[int]`): Resolution of input feature. dim (`int`): Number of input channels. norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`): Normalization layer class. """ def __init__(self, input_resolution: tuple[int], dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None: super().__init__() self.input_resolution = input_resolution self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim) def maybe_pad(self, input_feature, height, width): should_pad = (height % 2 == 1) or (width % 2 == 1) if should_pad: pad_values = (0, 0, 0, width % 2, 0, height % 2) input_feature = nn.functional.pad(input_feature, pad_values) return input_feature def forward(self, input_feature: torch.Tensor, input_dimensions: tuple[int, int]) -> torch.Tensor: height, width = input_dimensions # `dim` is height * width batch_size, dim, num_channels = input_feature.shape input_feature = input_feature.view(batch_size, height, width, num_channels) # pad input to be divisible by width and height, if needed input_feature = self.maybe_pad(input_feature, height, width) # [batch_size, height/2, width/2, num_channels] input_feature_0 = input_feature[:, 0::2, 0::2, :] # [batch_size, height/2, width/2, num_channels] input_feature_1 = input_feature[:, 1::2, 0::2, :] # [batch_size, height/2, width/2, num_channels] input_feature_2 = input_feature[:, 0::2, 1::2, :] # [batch_size, height/2, width/2, num_channels] input_feature_3 = input_feature[:, 1::2, 1::2, :] # batch_size height/2 width/2 4*num_channels input_feature = torch.cat([input_feature_0, input_feature_1, input_feature_2, input_feature_3], -1) input_feature = input_feature.view(batch_size, -1, 4 * num_channels) # batch_size height/2*width/2 4*C input_feature = self.norm(input_feature) input_feature = self.reduction(input_feature) return input_feature # Copied from transformers.models.swin.modeling_swin.SwinDropPath with Swin->MaskFormerSwin
MaskFormerSwinPatchMerging
python
pallets__quart
src/quart/wrappers/request.py
{ "start": 933, "end": 3955 }
class ____: """A request body container. The request body can either be iterated over and consumed in parts (without building up memory usage) or awaited. .. code-block:: python async for data in body: ... # or simply complete = await body Note: It is not possible to iterate over the data and then await it. """ def __init__( self, expected_content_length: int | None, max_content_length: int | None ) -> None: self._data = bytearray() self._complete: asyncio.Event = asyncio.Event() self._has_data: asyncio.Event = asyncio.Event() self._max_content_length = max_content_length # Exceptions must be raised within application (not ASGI) # calls, this is achieved by having the ASGI methods set this # to an exception on error. self._must_raise: Exception | None = None if ( expected_content_length is not None and max_content_length is not None and expected_content_length > max_content_length ): self._must_raise = RequestEntityTooLarge() def __aiter__(self) -> Body: return self async def __anext__(self) -> bytes: if self._must_raise is not None: raise self._must_raise # if we got all of the data in the first shot, then self._complete is # set and self._has_data will not get set again, so skip the await # if we already have completed everything if not self._complete.is_set(): await self._has_data.wait() if self._complete.is_set() and len(self._data) == 0: raise StopAsyncIteration() data = bytes(self._data) self._data.clear() self._has_data.clear() return data def __await__(self) -> Generator[Any, None, Any]: # Must check the _must_raise before and after waiting on the # completion event as it may change whilst waiting and the # event may not be set if there is already an issue. if self._must_raise is not None: raise self._must_raise yield from self._complete.wait().__await__() if self._must_raise is not None: raise self._must_raise return bytes(self._data) def append(self, data: bytes) -> None: if data == b"" or self._must_raise is not None: return self._data.extend(data) self._has_data.set() if ( self._max_content_length is not None and len(self._data) > self._max_content_length ): self._must_raise = RequestEntityTooLarge() self.set_complete() def set_complete(self) -> None: self._complete.set() self._has_data.set() def set_result(self, data: bytes) -> None: """Convenience method, mainly for testing.""" self.append(data) self.set_complete() def clear(self) -> None: self._data.clear()
Body
python
numpy__numpy
numpy/random/tests/test_randomstate.py
{ "start": 19526, "end": 57838 }
class ____: # Make sure the random distribution returns the correct value for a # given seed seed = 1234567890 def test_rand(self): rng = random.RandomState(self.seed) actual = rng.rand(3, 2) desired = np.array([[0.61879477158567997, 0.59162362775974664], [0.88868358904449662, 0.89165480011560816], [0.4575674820298663, 0.7781880808593471]]) assert_array_almost_equal(actual, desired, decimal=15) def test_rand_singleton(self): rng = random.RandomState(self.seed) actual = rng.rand() desired = 0.61879477158567997 assert_array_almost_equal(actual, desired, decimal=15) def test_randn(self): rng = random.RandomState(self.seed) actual = rng.randn(3, 2) desired = np.array([[1.34016345771863121, 1.73759122771936081], [1.498988344300628, -0.2286433324536169], [2.031033998682787, 2.17032494605655257]]) assert_array_almost_equal(actual, desired, decimal=15) rng = random.RandomState(self.seed) actual = rng.randn() assert_array_almost_equal(actual, desired[0, 0], decimal=15) def test_randint(self): rng = random.RandomState(self.seed) actual = rng.randint(-99, 99, size=(3, 2)) desired = np.array([[31, 3], [-52, 41], [-48, -66]]) assert_array_equal(actual, desired) def test_random_integers(self): rng = random.RandomState(self.seed) with pytest.warns(DeprecationWarning): actual = rng.random_integers(-99, 99, size=(3, 2)) desired = np.array([[31, 3], [-52, 41], [-48, -66]]) assert_array_equal(actual, desired) rng = random.RandomState(self.seed) with pytest.warns(DeprecationWarning): actual = rng.random_integers(198, size=(3, 2)) assert_array_equal(actual, desired + 100) def test_tomaxint(self): rs = random.RandomState(self.seed) actual = rs.tomaxint(size=(3, 2)) if np.iinfo(np.long).max == 2147483647: desired = np.array([[1328851649, 731237375], [1270502067, 320041495], [1908433478, 499156889]], dtype=np.int64) else: desired = np.array([[5707374374421908479, 5456764827585442327], [8196659375100692377, 8224063923314595285], [4220315081820346526, 7177518203184491332]], dtype=np.int64) assert_equal(actual, desired) rs.seed(self.seed) actual = rs.tomaxint() assert_equal(actual, desired[0, 0]) def test_random_integers_max_int(self): # Tests whether random_integers can generate the # maximum allowed Python int that can be converted # into a C long. Previous implementations of this # method have thrown an OverflowError when attempting # to generate this integer. with pytest.warns(DeprecationWarning): actual = random.random_integers(np.iinfo('l').max, np.iinfo('l').max) desired = np.iinfo('l').max assert_equal(actual, desired) with pytest.warns(DeprecationWarning): typer = np.dtype('l').type actual = random.random_integers(typer(np.iinfo('l').max), typer(np.iinfo('l').max)) assert_equal(actual, desired) def test_random_integers_deprecated(self): with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) # DeprecationWarning raised with high == None assert_raises(DeprecationWarning, random.random_integers, np.iinfo('l').max) # DeprecationWarning raised with high != None assert_raises(DeprecationWarning, random.random_integers, np.iinfo('l').max, np.iinfo('l').max) def test_random_sample(self): rng = random.RandomState(self.seed) actual = rng.random_sample((3, 2)) desired = np.array([[0.61879477158567997, 0.59162362775974664], [0.88868358904449662, 0.89165480011560816], [0.4575674820298663, 0.7781880808593471]]) assert_array_almost_equal(actual, desired, decimal=15) rng = random.RandomState(self.seed) actual = rng.random_sample() assert_array_almost_equal(actual, desired[0, 0], decimal=15) def test_choice_uniform_replace(self): rng = random.RandomState(self.seed) actual = rng.choice(4, 4) desired = np.array([2, 3, 2, 3]) assert_array_equal(actual, desired) def test_choice_nonuniform_replace(self): rng = random.RandomState(self.seed) actual = rng.choice(4, 4, p=[0.4, 0.4, 0.1, 0.1]) desired = np.array([1, 1, 2, 2]) assert_array_equal(actual, desired) def test_choice_uniform_noreplace(self): rng = random.RandomState(self.seed) actual = rng.choice(4, 3, replace=False) desired = np.array([0, 1, 3]) assert_array_equal(actual, desired) def test_choice_nonuniform_noreplace(self): rng = random.RandomState(self.seed) actual = rng.choice(4, 3, replace=False, p=[0.1, 0.3, 0.5, 0.1]) desired = np.array([2, 3, 1]) assert_array_equal(actual, desired) def test_choice_noninteger(self): rng = random.RandomState(self.seed) actual = rng.choice(['a', 'b', 'c', 'd'], 4) desired = np.array(['c', 'd', 'c', 'd']) assert_array_equal(actual, desired) def test_choice_exceptions(self): sample = random.choice assert_raises(ValueError, sample, -1, 3) assert_raises(ValueError, sample, 3., 3) assert_raises(ValueError, sample, [[1, 2], [3, 4]], 3) assert_raises(ValueError, sample, [], 3) assert_raises(ValueError, sample, [1, 2, 3, 4], 3, p=[[0.25, 0.25], [0.25, 0.25]]) assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4, 0.2]) assert_raises(ValueError, sample, [1, 2], 3, p=[1.1, -0.1]) assert_raises(ValueError, sample, [1, 2], 3, p=[0.4, 0.4]) assert_raises(ValueError, sample, [1, 2, 3], 4, replace=False) # gh-13087 assert_raises(ValueError, sample, [1, 2, 3], -2, replace=False) assert_raises(ValueError, sample, [1, 2, 3], (-1,), replace=False) assert_raises(ValueError, sample, [1, 2, 3], (-1, 1), replace=False) assert_raises(ValueError, sample, [1, 2, 3], 2, replace=False, p=[1, 0, 0]) def test_choice_return_shape(self): p = [0.1, 0.9] # Check scalar assert_(np.isscalar(random.choice(2, replace=True))) assert_(np.isscalar(random.choice(2, replace=False))) assert_(np.isscalar(random.choice(2, replace=True, p=p))) assert_(np.isscalar(random.choice(2, replace=False, p=p))) assert_(np.isscalar(random.choice([1, 2], replace=True))) assert_(random.choice([None], replace=True) is None) a = np.array([1, 2]) arr = np.empty(1, dtype=object) arr[0] = a assert_(random.choice(arr, replace=True) is a) # Check 0-d array s = () assert_(not np.isscalar(random.choice(2, s, replace=True))) assert_(not np.isscalar(random.choice(2, s, replace=False))) assert_(not np.isscalar(random.choice(2, s, replace=True, p=p))) assert_(not np.isscalar(random.choice(2, s, replace=False, p=p))) assert_(not np.isscalar(random.choice([1, 2], s, replace=True))) assert_(random.choice([None], s, replace=True).ndim == 0) a = np.array([1, 2]) arr = np.empty(1, dtype=object) arr[0] = a assert_(random.choice(arr, s, replace=True).item() is a) # Check multi dimensional array s = (2, 3) p = [0.1, 0.1, 0.1, 0.1, 0.4, 0.2] assert_equal(random.choice(6, s, replace=True).shape, s) assert_equal(random.choice(6, s, replace=False).shape, s) assert_equal(random.choice(6, s, replace=True, p=p).shape, s) assert_equal(random.choice(6, s, replace=False, p=p).shape, s) assert_equal(random.choice(np.arange(6), s, replace=True).shape, s) # Check zero-size assert_equal(random.randint(0, 0, size=(3, 0, 4)).shape, (3, 0, 4)) assert_equal(random.randint(0, -10, size=0).shape, (0,)) assert_equal(random.randint(10, 10, size=0).shape, (0,)) assert_equal(random.choice(0, size=0).shape, (0,)) assert_equal(random.choice([], size=(0,)).shape, (0,)) assert_equal(random.choice(['a', 'b'], size=(3, 0, 4)).shape, (3, 0, 4)) assert_raises(ValueError, random.choice, [], 10) def test_choice_nan_probabilities(self): a = np.array([42, 1, 2]) p = [None, None, None] assert_raises(ValueError, random.choice, a, p=p) def test_choice_p_non_contiguous(self): p = np.ones(10) / 5 p[1::2] = 3.0 rng = random.RandomState(self.seed) non_contig = rng.choice(5, 3, p=p[::2]) rng = random.RandomState(self.seed) contig = rng.choice(5, 3, p=np.ascontiguousarray(p[::2])) assert_array_equal(non_contig, contig) def test_bytes(self): rng = random.RandomState(self.seed) actual = rng.bytes(10) desired = b'\x82Ui\x9e\xff\x97+Wf\xa5' assert_equal(actual, desired) def test_shuffle(self): # Test lists, arrays (of various dtypes), and multidimensional versions # of both, c-contiguous or not: for conv in [lambda x: np.array([]), lambda x: x, lambda x: np.asarray(x).astype(np.int8), lambda x: np.asarray(x).astype(np.float32), lambda x: np.asarray(x).astype(np.complex64), lambda x: np.asarray(x).astype(object), lambda x: [(i, i) for i in x], lambda x: np.asarray([[i, i] for i in x]), lambda x: np.vstack([x, x]).T, # gh-11442 lambda x: (np.asarray([(i, i) for i in x], [("a", int), ("b", int)]) .view(np.recarray)), # gh-4270 lambda x: np.asarray([(i, i) for i in x], [("a", object, (1,)), ("b", np.int32, (1,))])]: rng = random.RandomState(self.seed) alist = conv([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) rng.shuffle(alist) actual = alist desired = conv([0, 1, 9, 6, 2, 4, 5, 8, 7, 3]) assert_array_equal(actual, desired) def test_shuffle_masked(self): # gh-3263 a = np.ma.masked_values(np.reshape(range(20), (5, 4)) % 3 - 1, -1) b = np.ma.masked_values(np.arange(20) % 3 - 1, -1) a_orig = a.copy() b_orig = b.copy() for i in range(50): random.shuffle(a) assert_equal( sorted(a.data[~a.mask]), sorted(a_orig.data[~a_orig.mask])) random.shuffle(b) assert_equal( sorted(b.data[~b.mask]), sorted(b_orig.data[~b_orig.mask])) def test_shuffle_invalid_objects(self): x = np.array(3) assert_raises(TypeError, random.shuffle, x) def test_permutation(self): rng = random.RandomState(self.seed) alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] actual = rng.permutation(alist) desired = [0, 1, 9, 6, 2, 4, 5, 8, 7, 3] assert_array_equal(actual, desired) rng = random.RandomState(self.seed) arr_2d = np.atleast_2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).T actual = rng.permutation(arr_2d) assert_array_equal(actual, np.atleast_2d(desired).T) rng = random.RandomState(self.seed) bad_x_str = "abcd" assert_raises(IndexError, random.permutation, bad_x_str) rng = random.RandomState(self.seed) bad_x_float = 1.2 assert_raises(IndexError, random.permutation, bad_x_float) integer_val = 10 desired = [9, 0, 8, 5, 1, 3, 4, 7, 6, 2] rng = random.RandomState(self.seed) actual = rng.permutation(integer_val) assert_array_equal(actual, desired) def test_beta(self): rng = random.RandomState(self.seed) actual = rng.beta(.1, .9, size=(3, 2)) desired = np.array( [[1.45341850513746058e-02, 5.31297615662868145e-04], [1.85366619058432324e-06, 4.19214516800110563e-03], [1.58405155108498093e-04, 1.26252891949397652e-04]]) assert_array_almost_equal(actual, desired, decimal=15) def test_binomial(self): rng = random.RandomState(self.seed) actual = rng.binomial(100.123, .456, size=(3, 2)) desired = np.array([[37, 43], [42, 48], [46, 45]]) assert_array_equal(actual, desired) rng = random.RandomState(self.seed) actual = rng.binomial(100.123, .456) desired = 37 assert_array_equal(actual, desired) def test_chisquare(self): rng = random.RandomState(self.seed) actual = rng.chisquare(50, size=(3, 2)) desired = np.array([[63.87858175501090585, 68.68407748911370447], [65.77116116901505904, 47.09686762438974483], [72.3828403199695174, 74.18408615260374006]]) assert_array_almost_equal(actual, desired, decimal=13) def test_dirichlet(self): rng = random.RandomState(self.seed) alpha = np.array([51.72840233779265162, 39.74494232180943953]) actual = rng.dirichlet(alpha, size=(3, 2)) desired = np.array([[[0.54539444573611562, 0.45460555426388438], [0.62345816822039413, 0.37654183177960598]], [[0.55206000085785778, 0.44793999914214233], [0.58964023305154301, 0.41035976694845688]], [[0.59266909280647828, 0.40733090719352177], [0.56974431743975207, 0.43025568256024799]]]) assert_array_almost_equal(actual, desired, decimal=15) bad_alpha = np.array([5.4e-01, -1.0e-16]) assert_raises(ValueError, random.dirichlet, bad_alpha) rng = random.RandomState(self.seed) alpha = np.array([51.72840233779265162, 39.74494232180943953]) actual = rng.dirichlet(alpha) assert_array_almost_equal(actual, desired[0, 0], decimal=15) def test_dirichlet_size(self): # gh-3173 p = np.array([51.72840233779265162, 39.74494232180943953]) assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2)) assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2)) assert_equal(random.dirichlet(p, np.uint32(1)).shape, (1, 2)) assert_equal(random.dirichlet(p, [2, 2]).shape, (2, 2, 2)) assert_equal(random.dirichlet(p, (2, 2)).shape, (2, 2, 2)) assert_equal(random.dirichlet(p, np.array((2, 2))).shape, (2, 2, 2)) assert_raises(TypeError, random.dirichlet, p, float(1)) def test_dirichlet_bad_alpha(self): # gh-2089 alpha = np.array([5.4e-01, -1.0e-16]) assert_raises(ValueError, random.dirichlet, alpha) def test_dirichlet_alpha_non_contiguous(self): a = np.array([51.72840233779265162, -1.0, 39.74494232180943953]) alpha = a[::2] rng = random.RandomState(self.seed) non_contig = rng.dirichlet(alpha, size=(3, 2)) rng = random.RandomState(self.seed) contig = rng.dirichlet(np.ascontiguousarray(alpha), size=(3, 2)) assert_array_almost_equal(non_contig, contig) def test_exponential(self): rng = random.RandomState(self.seed) actual = rng.exponential(1.1234, size=(3, 2)) desired = np.array([[1.08342649775011624, 1.00607889924557314], [2.46628830085216721, 2.49668106809923884], [0.68717433461363442, 1.69175666993575979]]) assert_array_almost_equal(actual, desired, decimal=15) def test_exponential_0(self): assert_equal(random.exponential(scale=0), 0) assert_raises(ValueError, random.exponential, scale=-0.) def test_f(self): rng = random.RandomState(self.seed) actual = rng.f(12, 77, size=(3, 2)) desired = np.array([[1.21975394418575878, 1.75135759791559775], [1.44803115017146489, 1.22108959480396262], [1.02176975757740629, 1.34431827623300415]]) assert_array_almost_equal(actual, desired, decimal=15) def test_gamma(self): rng = random.RandomState(self.seed) actual = rng.gamma(5, 3, size=(3, 2)) desired = np.array([[24.60509188649287182, 28.54993563207210627], [26.13476110204064184, 12.56988482927716078], [31.71863275789960568, 33.30143302795922011]]) assert_array_almost_equal(actual, desired, decimal=14) def test_gamma_0(self): assert_equal(random.gamma(shape=0, scale=0), 0) assert_raises(ValueError, random.gamma, shape=-0., scale=-0.) def test_geometric(self): rng = random.RandomState(self.seed) actual = rng.geometric(.123456789, size=(3, 2)) desired = np.array([[8, 7], [17, 17], [5, 12]]) assert_array_equal(actual, desired) def test_geometric_exceptions(self): assert_raises(ValueError, random.geometric, 1.1) assert_raises(ValueError, random.geometric, [1.1] * 10) assert_raises(ValueError, random.geometric, -0.1) assert_raises(ValueError, random.geometric, [-0.1] * 10) with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) assert_raises(ValueError, random.geometric, np.nan) assert_raises(ValueError, random.geometric, [np.nan] * 10) def test_gumbel(self): rng = random.RandomState(self.seed) actual = rng.gumbel(loc=.123456789, scale=2.0, size=(3, 2)) desired = np.array([[0.19591898743416816, 0.34405539668096674], [-1.4492522252274278, -1.47374816298446865], [1.10651090478803416, -0.69535848626236174]]) assert_array_almost_equal(actual, desired, decimal=15) def test_gumbel_0(self): assert_equal(random.gumbel(scale=0), 0) assert_raises(ValueError, random.gumbel, scale=-0.) def test_hypergeometric(self): rng = random.RandomState(self.seed) actual = rng.hypergeometric(10.1, 5.5, 14, size=(3, 2)) desired = np.array([[10, 10], [10, 10], [9, 9]]) assert_array_equal(actual, desired) # Test nbad = 0 actual = rng.hypergeometric(5, 0, 3, size=4) desired = np.array([3, 3, 3, 3]) assert_array_equal(actual, desired) actual = rng.hypergeometric(15, 0, 12, size=4) desired = np.array([12, 12, 12, 12]) assert_array_equal(actual, desired) # Test ngood = 0 actual = rng.hypergeometric(0, 5, 3, size=4) desired = np.array([0, 0, 0, 0]) assert_array_equal(actual, desired) actual = rng.hypergeometric(0, 15, 12, size=4) desired = np.array([0, 0, 0, 0]) assert_array_equal(actual, desired) def test_laplace(self): rng = random.RandomState(self.seed) actual = rng.laplace(loc=.123456789, scale=2.0, size=(3, 2)) desired = np.array([[0.66599721112760157, 0.52829452552221945], [3.12791959514407125, 3.18202813572992005], [-0.05391065675859356, 1.74901336242837324]]) assert_array_almost_equal(actual, desired, decimal=15) def test_laplace_0(self): assert_equal(random.laplace(scale=0), 0) assert_raises(ValueError, random.laplace, scale=-0.) def test_logistic(self): rng = random.RandomState(self.seed) actual = rng.logistic(loc=.123456789, scale=2.0, size=(3, 2)) desired = np.array([[1.09232835305011444, 0.8648196662399954], [4.27818590694950185, 4.33897006346929714], [-0.21682183359214885, 2.63373365386060332]]) assert_array_almost_equal(actual, desired, decimal=15) def test_lognormal(self): rng = random.RandomState(self.seed) actual = rng.lognormal(mean=.123456789, sigma=2.0, size=(3, 2)) desired = np.array([[16.50698631688883822, 36.54846706092654784], [22.67886599981281748, 0.71617561058995771], [65.72798501792723869, 86.84341601437161273]]) assert_array_almost_equal(actual, desired, decimal=13) def test_lognormal_0(self): assert_equal(random.lognormal(sigma=0), 1) assert_raises(ValueError, random.lognormal, sigma=-0.) def test_logseries(self): rng = random.RandomState(self.seed) actual = rng.logseries(p=.923456789, size=(3, 2)) desired = np.array([[2, 2], [6, 17], [3, 6]]) assert_array_equal(actual, desired) def test_logseries_zero(self): assert random.logseries(0) == 1 @pytest.mark.parametrize("value", [np.nextafter(0., -1), 1., np.nan, 5.]) def test_logseries_exceptions(self, value): with np.errstate(invalid="ignore"): with pytest.raises(ValueError): random.logseries(value) with pytest.raises(ValueError): # contiguous path: random.logseries(np.array([value] * 10)) with pytest.raises(ValueError): # non-contiguous path: random.logseries(np.array([value] * 10)[::2]) def test_multinomial(self): rng = random.RandomState(self.seed) actual = rng.multinomial(20, [1 / 6.] * 6, size=(3, 2)) desired = np.array([[[4, 3, 5, 4, 2, 2], [5, 2, 8, 2, 2, 1]], [[3, 4, 3, 6, 0, 4], [2, 1, 4, 3, 6, 4]], [[4, 4, 2, 5, 2, 3], [4, 3, 4, 2, 3, 4]]]) assert_array_equal(actual, desired) def test_multivariate_normal(self): rng = random.RandomState(self.seed) mean = (.123456789, 10) cov = [[1, 0], [0, 1]] size = (3, 2) actual = rng.multivariate_normal(mean, cov, size) desired = np.array([[[1.463620246718631, 11.73759122771936], [1.622445133300628, 9.771356667546383]], [[2.154490787682787, 12.170324946056553], [1.719909438201865, 9.230548443648306]], [[0.689515026297799, 9.880729819607714], [-0.023054015651998, 9.201096623542879]]]) assert_array_almost_equal(actual, desired, decimal=15) # Check for default size, was raising deprecation warning actual = rng.multivariate_normal(mean, cov) desired = np.array([0.895289569463708, 9.17180864067987]) assert_array_almost_equal(actual, desired, decimal=15) # Check that non positive-semidefinite covariance warns with # RuntimeWarning mean = [0, 0] cov = [[1, 2], [2, 1]] pytest.warns(RuntimeWarning, rng.multivariate_normal, mean, cov) # and that it doesn't warn with RuntimeWarning check_valid='ignore' assert_no_warnings(rng.multivariate_normal, mean, cov, check_valid='ignore') # and that it raises with RuntimeWarning check_valid='raises' assert_raises(ValueError, rng.multivariate_normal, mean, cov, check_valid='raise') cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32) with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) rng.multivariate_normal(mean, cov) mu = np.zeros(2) cov = np.eye(2) assert_raises(ValueError, rng.multivariate_normal, mean, cov, check_valid='other') assert_raises(ValueError, rng.multivariate_normal, np.zeros((2, 1, 1)), cov) assert_raises(ValueError, rng.multivariate_normal, mu, np.empty((3, 2))) assert_raises(ValueError, rng.multivariate_normal, mu, np.eye(3)) def test_negative_binomial(self): rng = random.RandomState(self.seed) actual = rng.negative_binomial(n=100, p=.12345, size=(3, 2)) desired = np.array([[848, 841], [892, 611], [779, 647]]) assert_array_equal(actual, desired) def test_negative_binomial_exceptions(self): with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) assert_raises(ValueError, random.negative_binomial, 100, np.nan) assert_raises(ValueError, random.negative_binomial, 100, [np.nan] * 10) def test_noncentral_chisquare(self): rng = random.RandomState(self.seed) actual = rng.noncentral_chisquare(df=5, nonc=5, size=(3, 2)) desired = np.array([[23.91905354498517511, 13.35324692733826346], [31.22452661329736401, 16.60047399466177254], [5.03461598262724586, 17.94973089023519464]]) assert_array_almost_equal(actual, desired, decimal=14) actual = rng.noncentral_chisquare(df=.5, nonc=.2, size=(3, 2)) desired = np.array([[1.47145377828516666, 0.15052899268012659], [0.00943803056963588, 1.02647251615666169], [0.332334982684171, 0.15451287602753125]]) assert_array_almost_equal(actual, desired, decimal=14) rng = random.RandomState(self.seed) actual = rng.noncentral_chisquare(df=5, nonc=0, size=(3, 2)) desired = np.array([[9.597154162763948, 11.725484450296079], [10.413711048138335, 3.694475922923986], [13.484222138963087, 14.377255424602957]]) assert_array_almost_equal(actual, desired, decimal=14) def test_noncentral_f(self): rng = random.RandomState(self.seed) actual = rng.noncentral_f(dfnum=5, dfden=2, nonc=1, size=(3, 2)) desired = np.array([[1.40598099674926669, 0.34207973179285761], [3.57715069265772545, 7.92632662577829805], [0.43741599463544162, 1.1774208752428319]]) assert_array_almost_equal(actual, desired, decimal=14) def test_noncentral_f_nan(self): random.seed(self.seed) actual = random.noncentral_f(dfnum=5, dfden=2, nonc=np.nan) assert np.isnan(actual) def test_normal(self): rng = random.RandomState(self.seed) actual = rng.normal(loc=.123456789, scale=2.0, size=(3, 2)) desired = np.array([[2.80378370443726244, 3.59863924443872163], [3.121433477601256, -0.33382987590723379], [4.18552478636557357, 4.46410668111310471]]) assert_array_almost_equal(actual, desired, decimal=15) def test_normal_0(self): assert_equal(random.normal(scale=0), 0) assert_raises(ValueError, random.normal, scale=-0.) def test_pareto(self): rng = random.RandomState(self.seed) actual = rng.pareto(a=.123456789, size=(3, 2)) desired = np.array( [[2.46852460439034849e+03, 1.41286880810518346e+03], [5.28287797029485181e+07, 6.57720981047328785e+07], [1.40840323350391515e+02, 1.98390255135251704e+05]]) # For some reason on 32-bit x86 Ubuntu 12.10 the [1, 0] entry in this # matrix differs by 24 nulps. Discussion: # https://mail.python.org/pipermail/numpy-discussion/2012-September/063801.html # Consensus is that this is probably some gcc quirk that affects # rounding but not in any important way, so we just use a looser # tolerance on this test: np.testing.assert_array_almost_equal_nulp(actual, desired, nulp=30) def test_poisson(self): rng = random.RandomState(self.seed) actual = rng.poisson(lam=.123456789, size=(3, 2)) desired = np.array([[0, 0], [1, 0], [0, 0]]) assert_array_equal(actual, desired) def test_poisson_exceptions(self): lambig = np.iinfo('l').max lamneg = -1 assert_raises(ValueError, random.poisson, lamneg) assert_raises(ValueError, random.poisson, [lamneg] * 10) assert_raises(ValueError, random.poisson, lambig) assert_raises(ValueError, random.poisson, [lambig] * 10) with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) assert_raises(ValueError, random.poisson, np.nan) assert_raises(ValueError, random.poisson, [np.nan] * 10) def test_power(self): rng = random.RandomState(self.seed) actual = rng.power(a=.123456789, size=(3, 2)) desired = np.array([[0.02048932883240791, 0.01424192241128213], [0.38446073748535298, 0.39499689943484395], [0.00177699707563439, 0.13115505880863756]]) assert_array_almost_equal(actual, desired, decimal=15) def test_rayleigh(self): rng = random.RandomState(self.seed) actual = rng.rayleigh(scale=10, size=(3, 2)) desired = np.array([[13.8882496494248393, 13.383318339044731], [20.95413364294492098, 21.08285015800712614], [11.06066537006854311, 17.35468505778271009]]) assert_array_almost_equal(actual, desired, decimal=14) def test_rayleigh_0(self): assert_equal(random.rayleigh(scale=0), 0) assert_raises(ValueError, random.rayleigh, scale=-0.) def test_standard_cauchy(self): rng = random.RandomState(self.seed) actual = rng.standard_cauchy(size=(3, 2)) desired = np.array([[0.77127660196445336, -6.55601161955910605], [0.93582023391158309, -2.07479293013759447], [-4.74601644297011926, 0.18338989290760804]]) assert_array_almost_equal(actual, desired, decimal=15) def test_standard_exponential(self): rng = random.RandomState(self.seed) actual = rng.standard_exponential(size=(3, 2)) desired = np.array([[0.96441739162374596, 0.89556604882105506], [2.1953785836319808, 2.22243285392490542], [0.6116915921431676, 1.50592546727413201]]) assert_array_almost_equal(actual, desired, decimal=15) def test_standard_gamma(self): rng = random.RandomState(self.seed) actual = rng.standard_gamma(shape=3, size=(3, 2)) desired = np.array([[5.50841531318455058, 6.62953470301903103], [5.93988484943779227, 2.31044849402133989], [7.54838614231317084, 8.012756093271868]]) assert_array_almost_equal(actual, desired, decimal=14) def test_standard_gamma_0(self): assert_equal(random.standard_gamma(shape=0), 0) assert_raises(ValueError, random.standard_gamma, shape=-0.) def test_standard_normal(self): rng = random.RandomState(self.seed) actual = rng.standard_normal(size=(3, 2)) desired = np.array([[1.34016345771863121, 1.73759122771936081], [1.498988344300628, -0.2286433324536169], [2.031033998682787, 2.17032494605655257]]) assert_array_almost_equal(actual, desired, decimal=15) def test_randn_singleton(self): rng = random.RandomState(self.seed) actual = rng.randn() desired = np.array(1.34016345771863121) assert_array_almost_equal(actual, desired, decimal=15) def test_standard_t(self): rng = random.RandomState(self.seed) actual = rng.standard_t(df=10, size=(3, 2)) desired = np.array([[0.97140611862659965, -0.08830486548450577], [1.36311143689505321, -0.55317463909867071], [-0.18473749069684214, 0.61181537341755321]]) assert_array_almost_equal(actual, desired, decimal=15) def test_triangular(self): rng = random.RandomState(self.seed) actual = rng.triangular(left=5.12, mode=10.23, right=20.34, size=(3, 2)) desired = np.array([[12.68117178949215784, 12.4129206149193152], [16.20131377335158263, 16.25692138747600524], [11.20400690911820263, 14.4978144835829923]]) assert_array_almost_equal(actual, desired, decimal=14) def test_uniform(self): rng = random.RandomState(self.seed) actual = rng.uniform(low=1.23, high=10.54, size=(3, 2)) desired = np.array([[6.99097932346268003, 6.73801597444323974], [9.50364421400426274, 9.53130618907631089], [5.48995325769805476, 8.47493103280052118]]) assert_array_almost_equal(actual, desired, decimal=15) def test_uniform_range_bounds(self): fmin = np.finfo('float').min fmax = np.finfo('float').max func = random.uniform assert_raises(OverflowError, func, -np.inf, 0) assert_raises(OverflowError, func, 0, np.inf) assert_raises(OverflowError, func, fmin, fmax) assert_raises(OverflowError, func, [-np.inf], [0]) assert_raises(OverflowError, func, [0], [np.inf]) # (fmax / 1e17) - fmin is within range, so this should not throw # account for i386 extended precision DBL_MAX / 1e17 + DBL_MAX > # DBL_MAX by increasing fmin a bit random.uniform(low=np.nextafter(fmin, 1), high=fmax / 1e17) def test_scalar_exception_propagation(self): # Tests that exceptions are correctly propagated in distributions # when called with objects that throw exceptions when converted to # scalars. # # Regression test for gh: 8865 class ThrowingFloat(np.ndarray): def __float__(self): raise TypeError throwing_float = np.array(1.0).view(ThrowingFloat) assert_raises(TypeError, random.uniform, throwing_float, throwing_float) class ThrowingInteger(np.ndarray): def __int__(self): raise TypeError throwing_int = np.array(1).view(ThrowingInteger) assert_raises(TypeError, random.hypergeometric, throwing_int, 1, 1) def test_vonmises(self): rng = random.RandomState(self.seed) actual = rng.vonmises(mu=1.23, kappa=1.54, size=(3, 2)) desired = np.array([[2.28567572673902042, 2.89163838442285037], [0.38198375564286025, 2.57638023113890746], [1.19153771588353052, 1.83509849681825354]]) assert_array_almost_equal(actual, desired, decimal=15) def test_vonmises_small(self): # check infinite loop, gh-4720 random.seed(self.seed) r = random.vonmises(mu=0., kappa=1.1e-8, size=10**6) assert_(np.isfinite(r).all()) def test_vonmises_large(self): # guard against changes in RandomState when Generator is fixed rng = random.RandomState(self.seed) actual = rng.vonmises(mu=0., kappa=1e7, size=3) desired = np.array([4.634253748521111e-04, 3.558873596114509e-04, -2.337119622577433e-04]) assert_array_almost_equal(actual, desired, decimal=8) def test_vonmises_nan(self): random.seed(self.seed) r = random.vonmises(mu=0., kappa=np.nan) assert_(np.isnan(r)) def test_wald(self): rng = random.RandomState(self.seed) actual = rng.wald(mean=1.23, scale=1.54, size=(3, 2)) desired = np.array([[3.82935265715889983, 5.13125249184285526], [0.35045403618358717, 1.50832396872003538], [0.24124319895843183, 0.22031101461955038]]) assert_array_almost_equal(actual, desired, decimal=14) def test_weibull(self): rng = random.RandomState(self.seed) actual = rng.weibull(a=1.23, size=(3, 2)) desired = np.array([[0.97097342648766727, 0.91422896443565516], [1.89517770034962929, 1.91414357960479564], [0.67057783752390987, 1.39494046635066793]]) assert_array_almost_equal(actual, desired, decimal=15) def test_weibull_0(self): random.seed(self.seed) assert_equal(random.weibull(a=0, size=12), np.zeros(12)) assert_raises(ValueError, random.weibull, a=-0.) def test_zipf(self): rng = random.RandomState(self.seed) actual = rng.zipf(a=1.23, size=(3, 2)) desired = np.array([[66, 29], [1, 1], [3, 13]]) assert_array_equal(actual, desired)
TestRandomDist
python
huggingface__transformers
src/transformers/models/upernet/modeling_upernet.py
{ "start": 9701, "end": 10004 }
class ____(PreTrainedModel): config: UperNetConfig main_input_name = "pixel_values" input_modalities = ("image",) _no_split_modules = [] @auto_docstring( custom_intro=""" UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes. """ )
UperNetPreTrainedModel
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_basic.py
{ "start": 21948, "end": 23178 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "a", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column( "b_id", Integer, ForeignKey("b.id", use_alter=True, name="b_fk"), ), ) Table( "b", metadata, Column("id", Integer, ForeignKey("a.id"), primary_key=True), ) @classmethod def setup_classes(cls): Base = declarative_base() class A(Base): __tablename__ = "a" id = Column( Integer, primary_key=True, test_needs_autoincrement=True ) b_id = Column(Integer, ForeignKey("b.id")) class B(A): __tablename__ = "b" id = Column(Integer, ForeignKey("a.id"), primary_key=True) __mapper_args__ = {"inherit_condition": id == A.id} cls.classes.A = A cls.classes.B = B def test_flush(self): s = fixture_session() s.add(self.classes.B()) s.flush()
SortOnlyOnImportantFKsTest
python
ansible__ansible
lib/ansible/_internal/_templating/_engine.py
{ "start": 1944, "end": 2261 }
class ____(enum.Enum): # DTFIX-FUTURE: this enum ideally wouldn't exist - revisit/rename before making public DEFAULT = enum.auto() STOP_ON_TEMPLATE = enum.auto() STOP_ON_CONTAINER = enum.auto() ALWAYS_FINALIZE = enum.auto() @dataclasses.dataclass(kw_only=True, slots=True, frozen=True)
TemplateMode
python
tartley__colorama
colorama/tests/utils.py
{ "start": 160, "end": 230 }
class ____(StringIO): def isatty(self): return True
StreamTTY
python
lepture__authlib
authlib/oauth2/rfc6749/hooks.py
{ "start": 38, "end": 1004 }
class ____: _hooks = None def __init__(self): self._hooks = defaultdict(set) def register_hook(self, hook_type, hook): self._hooks[hook_type].add(hook) def execute_hook(self, hook_type, *args, **kwargs): for hook in self._hooks[hook_type]: hook(self, *args, **kwargs) def hooked(func=None, before=None, after=None): """Execute hooks before and after the decorated method.""" def decorator(func): before_name = before or f"before_{func.__name__}" after_name = after or f"after_{func.__name__}" def wrapper(self, *args, **kwargs): self.execute_hook(before_name, *args, **kwargs) result = func(self, *args, **kwargs) self.execute_hook(after_name, result) return result return wrapper # The decorator has been called without parenthesis if callable(func): return decorator(func) return decorator
Hookable
python
run-llama__llama_index
llama-index-core/llama_index/core/retrievers/transform_retriever.py
{ "start": 365, "end": 1586 }
class ____(BaseRetriever): """ Transform Retriever. Takes in an existing retriever and a query transform and runs the query transform before running the retriever. """ def __init__( self, retriever: BaseRetriever, query_transform: BaseQueryTransform, transform_metadata: Optional[dict] = None, callback_manager: Optional[CallbackManager] = None, object_map: Optional[dict] = None, verbose: bool = False, ) -> None: self._retriever = retriever self._query_transform = query_transform self._transform_metadata = transform_metadata super().__init__( callback_manager=callback_manager, object_map=object_map, verbose=verbose ) def _get_prompt_modules(self) -> PromptMixinType: """Get prompt sub-modules.""" # NOTE: don't include tools for now return {"query_transform": self._query_transform} def _retrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]: query_bundle = self._query_transform.run( query_bundle, metadata=self._transform_metadata ) return self._retriever.retrieve(query_bundle)
TransformRetriever
python
scipy__scipy
scipy/interpolate/_fitpack2.py
{ "start": 52329, "end": 56420 }
class ____(BivariateSpline): """ Weighted least-squares bivariate spline approximation. Parameters ---------- x, y, z : array_like 1-D sequences of data points (order is not important). tx, ty : array_like Strictly ordered 1-D sequences of knots coordinates. w : array_like, optional Positive 1-D array of weights, of the same length as `x`, `y` and `z`. bbox : (4,) array_like, optional Sequence of length 4 specifying the boundary of the rectangular approximation domain. By default, ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``. kx, ky : ints, optional Degrees of the bivariate spline. Default is 3. eps : float, optional A threshold for determining the effective rank of an over-determined linear system of equations. `eps` should have a value within the open interval ``(0, 1)``, the default is 1e-16. See Also -------- BivariateSpline : a base class for bivariate splines. UnivariateSpline : a smooth univariate spline to fit a given set of data points. SmoothBivariateSpline : a smoothing bivariate spline through the given points RectSphereBivariateSpline : a bivariate spline over a rectangular mesh on a sphere SmoothSphereBivariateSpline : a smoothing bivariate spline in spherical coordinates LSQSphereBivariateSpline : a bivariate spline in spherical coordinates using weighted least-squares fitting RectBivariateSpline : a bivariate spline over a rectangular mesh. bisplrep : a function to find a bivariate B-spline representation of a surface bisplev : a function to evaluate a bivariate B-spline and its derivatives Notes ----- The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``. If the input data is such that input dimensions have incommensurate units and differ by many orders of magnitude, the interpolant may have numerical artifacts. Consider rescaling the data before interpolating. """ def __init__(self, x, y, z, tx, ty, w=None, bbox=[None]*4, kx=3, ky=3, eps=None): x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps) bbox = ravel(bbox) if not bbox.shape == (4,): raise ValueError('bbox shape should be (4,)') nx = 2*kx+2+len(tx) ny = 2*ky+2+len(ty) # The Fortran subroutine "surfit" (called as dfitpack.surfit_lsq) # requires that the knot arrays passed as input should be "real # array(s) of dimension nmax" where "nmax" refers to the greater of nx # and ny. We pad the tx1/ty1 arrays here so that this is satisfied, and # slice them to the desired sizes upon return. nmax = max(nx, ny) tx1 = zeros((nmax,), float) ty1 = zeros((nmax,), float) tx1[kx+1:nx-kx-1] = tx ty1[ky+1:ny-ky-1] = ty xb, xe, yb, ye = bbox with FITPACK_LOCK: tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, nx, tx1, ny, ty1, w, xb, xe, yb, ye, kx, ky, eps, lwrk2=1) if ier > 10: tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, nx, tx1, ny, ty1, w, xb, xe, yb, ye, kx, ky, eps, lwrk2=ier) if ier in [0, -1, -2]: # normal return pass else: if ier < -2: deficiency = (nx-kx-1)*(ny-ky-1)+ier message = _surfit_messages.get(-3) % (deficiency) else: message = _surfit_messages.get(ier, f'ier={ier}') warnings.warn(message, stacklevel=2) self.fp = fp self.tck = tx1[:nx], ty1[:ny], c self.degrees = kx, ky @xp_capabilities(out_of_scope=True)
LSQBivariateSpline
python
skorch-dev__skorch
skorch/callbacks/logging.py
{ "start": 18792, "end": 24094 }
class ____(Callback): """Display a progress bar for each epoch. The progress bar includes elapsed and estimated remaining time for the current epoch, the number of batches processed, and other user-defined metrics. The progress bar is erased once the epoch is completed. ``ProgressBar`` needs to know the total number of batches per epoch in order to display a meaningful progress bar. By default, this number is determined automatically using the dataset length and the batch size. If this heuristic does not work for some reason, you may either specify the number of batches explicitly or let the ``ProgressBar`` count the actual number of batches in the previous epoch. For jupyter notebooks a non-ASCII progress bar can be printed instead. To use this feature, you need to have `ipywidgets <https://ipywidgets.readthedocs.io/en/stable/user_install.html>`_ installed. Parameters ---------- batches_per_epoch : int, str (default='auto') Either a concrete number or a string specifying the method used to determine the number of batches per epoch automatically. ``'auto'`` means that the number is computed from the length of the dataset and the batch size. ``'count'`` means that the number is determined by counting the batches in the previous epoch. Note that this will leave you without a progress bar at the first epoch. detect_notebook : bool (default=True) If enabled, the progress bar determines if its current environment is a jupyter notebook and switches to a non-ASCII progress bar. postfix_keys : list of str (default=['train_loss', 'valid_loss']) You can use this list to specify additional info displayed in the progress bar such as metrics and losses. A prerequisite to this is that these values are residing in the history on batch level already, i.e. they must be accessible via >>> net.history[-1, 'batches', -1, key] """ def __init__( self, batches_per_epoch='auto', detect_notebook=True, postfix_keys=None ): self.batches_per_epoch = batches_per_epoch self.detect_notebook = detect_notebook self.postfix_keys = postfix_keys or ['train_loss', 'valid_loss'] def in_ipynb(self): try: return get_ipython().__class__.__name__ == 'ZMQInteractiveShell' except NameError: return False def _use_notebook(self): return self.in_ipynb() if self.detect_notebook else False def _get_batch_size(self, net, training): name = 'iterator_train' if training else 'iterator_valid' net_params = net.get_params() return net_params.get(name + '__batch_size', net_params['batch_size']) def _get_batches_per_epoch_phase(self, net, dataset, training): if dataset is None: return 0 batch_size = self._get_batch_size(net, training) return int(np.ceil(get_len(dataset) / batch_size)) def _get_batches_per_epoch(self, net, dataset_train, dataset_valid): return (self._get_batches_per_epoch_phase(net, dataset_train, True) + self._get_batches_per_epoch_phase(net, dataset_valid, False)) def _get_postfix_dict(self, net): postfix = {} for key in self.postfix_keys: try: postfix[key] = net.history[-1, 'batches', -1, key] except KeyError: pass return postfix # pylint: disable=attribute-defined-outside-init def on_batch_end(self, net, **kwargs): self.pbar_.set_postfix(self._get_postfix_dict(net), refresh=False) self.pbar_.update() # pylint: disable=attribute-defined-outside-init, arguments-differ def on_epoch_begin(self, net, dataset_train=None, dataset_valid=None, **kwargs): # Assume it is a number until proven otherwise. batches_per_epoch = self.batches_per_epoch if self.batches_per_epoch == 'auto': batches_per_epoch = self._get_batches_per_epoch( net, dataset_train, dataset_valid ) elif self.batches_per_epoch == 'count': if len(net.history) <= 1: # No limit is known until the end of the first epoch. batches_per_epoch = None else: batches_per_epoch = len(net.history[-2, 'batches']) if self._use_notebook(): self.pbar_ = tqdm.tqdm_notebook(total=batches_per_epoch, leave=False) else: self.pbar_ = tqdm.tqdm(total=batches_per_epoch, leave=False) def on_epoch_end(self, net, **kwargs): self.pbar_.close() def __getstate__(self): # don't save away the temporary pbar_ object which gets created on # epoch begin anew anyway. This avoids pickling errors with tqdm. state = self.__dict__.copy() state.pop('pbar_', None) return state def rename_tensorboard_key(key): """Rename keys from history to keys in TensorBoard Specifically, prefixes all names with "Loss/" if they seem to be losses. """ if key.startswith('train') or key.startswith('valid'): key = 'Loss/' + key return key
ProgressBar
python
huggingface__transformers
tests/models/bark/test_modeling_bark.py
{ "start": 22716, "end": 26296 }
class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): all_model_classes = (BarkCoarseModel,) if is_torch_available() else () # `BarkCoarseModel` inherits from `BarkCausalModel`, but requires an advanced generation config. # `BarkCausalModel` does not, so we run generation tests there. all_generative_model_classes = (BarkCausalModel,) if is_torch_available() else () is_encoder_decoder = False test_missing_keys = False test_resize_embeddings = True def setUp(self): self.model_tester = BarkCoarseModelTester(self) self.config_tester = ConfigTester(self, config_class=BarkCoarseConfig, n_embd=37) def test_config(self): self.config_tester.run_common_tests() def test_save_load_strict(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: model = model_class(config) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) self.assertEqual(info["missing_keys"], set()) def test_decoder_model_past_with_large_inputs(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) def test_inputs_embeds(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) input_ids = inputs["input_ids"] del inputs["input_ids"] wte = model.get_input_embeddings() inputs["input_embeds"] = wte(input_ids) with torch.no_grad(): model(**inputs)[0] # override as the input arg is called "input_embeds", not "inputs_embeds" def test_inputs_embeds_matches_input_ids(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) model.to(torch_device) model.eval() inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) with torch.no_grad(): out_ids = model(**inputs)[0] input_ids = inputs["input_ids"] del inputs["input_ids"] wte = model.get_input_embeddings() inputs["input_embeds"] = wte(input_ids) with torch.no_grad(): out_embeds = model(**inputs)[0] torch.testing.assert_close(out_embeds, out_ids) @require_torch_fp16 def test_generate_fp16(self): config, input_dict = self.model_tester.prepare_config_and_inputs() input_ids = input_dict["input_ids"] attention_mask = input_ids.ne(1).to(torch_device) model = self.all_generative_model_classes[0](config).eval().to(torch_device) model.half() model.generate(input_ids, attention_mask=attention_mask) model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3) @unittest.skip("Bark has no base model due to special archiecture") def test_model_base_model_prefix(self): pass @require_torch
BarkCoarseModelTest
python
celery__celery
t/unit/backends/test_redis.py
{ "start": 5228, "end": 5270 }
class ____: Sentinel = Sentinel
sentinel
python
mamba-org__mamba
micromamba/tests/test_proxy.py
{ "start": 506, "end": 3793 }
class ____: def __init__(self, exe: Path, conf: Path, dump: Path): self.exe = Path(exe).resolve() self.conf = Path(conf).resolve() self.dump = Path(dump).resolve() self.process = None def start_proxy(self, port, options=[]): assert self.process is None self.process = subprocess.Popen( [ self.exe, "--listen-port", str(port), "--scripts", str(__this_dir__ / "dump_proxy_connections.py"), "--set", f"outfile={self.dump}", "--set", f"confdir={self.conf}", *options, ] ) # Wait until mitmproxy has generated its certificate or some tests might fail while not (Path(self.conf) / "mitmproxy-ca-cert.pem").exists(): time.sleep(1) def stop_proxy(self): self.process.terminate() try: self.process.wait(3) except subprocess.TimeoutExpired: self.process.kill() self.process = None @pytest.mark.parametrize("auth", [None, "foo:bar", "user%40example.com:pass"]) @pytest.mark.parametrize("ssl_verify", (True, False)) def test_proxy_install( mitmdump_exe, tmp_home, tmp_prefix, tmp_path, unused_tcp_port, auth, ssl_verify ): """ This test makes sure micromamba follows the proxy settings in .condarc It starts mitmproxy with the `dump_proxy_connections.py` script, which dumps all requested urls in a text file. After that micromamba is used to install a package, while pointing it to that mitmproxy instance. Once micromamba finished the proxy server is stopped and the urls micromamba requested are compared to the urls mitmproxy intercepted, making sure that all the requests went through the proxy. """ if auth is not None: proxy_options = ["--proxyauth", urllib.parse.unquote(auth)] proxy_url = f"http://{auth}@localhost:{unused_tcp_port}" else: proxy_options = [] proxy_url = f"http://localhost:{unused_tcp_port}" proxy = MitmProxy( exe=mitmdump_exe, conf=(tmp_path / "mitmproxy-conf"), dump=(tmp_path / "mitmproxy-dump"), ) proxy.start_proxy(unused_tcp_port, proxy_options) rc_file = tmp_prefix / "rc.yaml" verify_string = proxy.conf / "mitmproxy-ca-cert.pem" if ssl_verify else "false" file_content = [ "proxy_servers:", f" http: {proxy_url}", f" https: {proxy_url}", f"ssl_verify: {verify_string}", ] with open(rc_file, "w") as f: f.write("\n".join(file_content)) cmd = ["xtensor", "--rc-file", rc_file] if os.name == "nt": # The certificates generated by mitmproxy don't support revocation. # The schannel backend curl uses on Windows fails revocation check if revocation isn't supported. Other # backends succeed revocation check in that case. cmd += ["--ssl-no-revoke"] res = helpers.install(*cmd, "--json", no_rc=False) proxy.stop_proxy() with open(proxy.dump) as f: proxied_requests = f.read().splitlines() for fetch in res["actions"]["FETCH"]: assert fetch["url"] in proxied_requests
MitmProxy
python
cython__cython
tests/run/cpdef_optargs_pure.py
{ "start": 105, "end": 910 }
class ____(object): a = 99 def pymethod(self, x, y=1, z=PyClass): """ >>> obj = PyClass99() >>> obj.pymethod(0) (0, 1, 2) """ return x, y, z.a def func(x, y=1, z=PyClass): """ >>> func(0) (0, 1, 2) >>> func(0, 3) (0, 3, 2) >>> func(0, 3, PyClass) (0, 3, 2) >>> func(0, 3, 5) Traceback (most recent call last): AttributeError: 'int' object has no attribute 'a' """ return x, y, z.a @cython.ccall def pyfunc(x, y=1, z=PyClass): """ >>> pyfunc(0) (0, 1, 2) >>> pyfunc(0, 3) (0, 3, 2) >>> pyfunc(0, 3, PyClass) (0, 3, 2) >>> pyfunc(0, 3, 5) Traceback (most recent call last): AttributeError: 'int' object has no attribute 'a' """ return x, y, z.a
PyClass99
python
TheAlgorithms__Python
strings/autocomplete_using_trie.py
{ "start": 48, "end": 1489 }
class ____: def __init__(self) -> None: self._trie: dict = {} def insert_word(self, text: str) -> None: trie = self._trie for char in text: if char not in trie: trie[char] = {} trie = trie[char] trie[END] = True def find_word(self, prefix: str) -> tuple | list: trie = self._trie for char in prefix: if char in trie: trie = trie[char] else: return [] return self._elements(trie) def _elements(self, d: dict) -> tuple: result = [] for c, v in d.items(): sub_result = [" "] if c == END else [(c + s) for s in self._elements(v)] result.extend(sub_result) return tuple(result) trie = Trie() words = ("depart", "detergent", "daring", "dog", "deer", "deal") for word in words: trie.insert_word(word) def autocomplete_using_trie(string: str) -> tuple: """ >>> trie = Trie() >>> for word in words: ... trie.insert_word(word) ... >>> matches = autocomplete_using_trie("de") >>> "detergent " in matches True >>> "dog " in matches False """ suffixes = trie.find_word(string) return tuple(string + word for word in suffixes) def main() -> None: print(autocomplete_using_trie("de")) if __name__ == "__main__": import doctest doctest.testmod() main()
Trie
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_with.py
{ "start": 13605, "end": 21277 }
class ____(ContextmanagerAssertionMixin, __TestCase): def testSingleResource(self): cm = mock_contextmanager_generator() def shouldThrow(): with cm as self.resource: self.assertInWithManagerInvariants(cm) self.assertInWithGeneratorInvariants(self.resource) self.raiseTestException() self.assertRaises(RuntimeError, shouldThrow) self.assertAfterWithManagerInvariantsWithError(cm) self.assertAfterWithGeneratorInvariantsWithError(self.resource) def testExceptionNormalized(self): cm = mock_contextmanager_generator() def shouldThrow(): with cm as self.resource: # Note this relies on the fact that 1 // 0 produces an exception # that is not normalized immediately. 1 // 0 self.assertRaises(ZeroDivisionError, shouldThrow) self.assertAfterWithManagerInvariantsWithError(cm, ZeroDivisionError) def testNestedSingleStatements(self): mock_a = mock_contextmanager_generator() mock_b = mock_contextmanager_generator() def shouldThrow(): with mock_a as self.foo: with mock_b as self.bar: self.assertInWithManagerInvariants(mock_a) self.assertInWithManagerInvariants(mock_b) self.assertInWithGeneratorInvariants(self.foo) self.assertInWithGeneratorInvariants(self.bar) self.raiseTestException() self.assertRaises(RuntimeError, shouldThrow) self.assertAfterWithManagerInvariantsWithError(mock_a) self.assertAfterWithManagerInvariantsWithError(mock_b) self.assertAfterWithGeneratorInvariantsWithError(self.foo) self.assertAfterWithGeneratorInvariantsWithError(self.bar) def testMultipleResourcesInSingleStatement(self): cm_a = mock_contextmanager_generator() cm_b = mock_contextmanager_generator() mock_nested = MockNested(cm_a, cm_b) def shouldThrow(): with mock_nested as (self.resource_a, self.resource_b): self.assertInWithManagerInvariants(cm_a) self.assertInWithManagerInvariants(cm_b) self.assertInWithManagerInvariants(mock_nested) self.assertInWithGeneratorInvariants(self.resource_a) self.assertInWithGeneratorInvariants(self.resource_b) self.raiseTestException() self.assertRaises(RuntimeError, shouldThrow) self.assertAfterWithManagerInvariantsWithError(cm_a) self.assertAfterWithManagerInvariantsWithError(cm_b) self.assertAfterWithManagerInvariantsWithError(mock_nested) self.assertAfterWithGeneratorInvariantsWithError(self.resource_a) self.assertAfterWithGeneratorInvariantsWithError(self.resource_b) def testNestedExceptionBeforeInnerStatement(self): mock_a = mock_contextmanager_generator() mock_b = mock_contextmanager_generator() self.bar = None def shouldThrow(): with mock_a as self.foo: self.assertInWithManagerInvariants(mock_a) self.assertInWithGeneratorInvariants(self.foo) self.raiseTestException() with mock_b as self.bar: pass self.assertRaises(RuntimeError, shouldThrow) self.assertAfterWithManagerInvariantsWithError(mock_a) self.assertAfterWithGeneratorInvariantsWithError(self.foo) # The inner statement stuff should never have been touched self.assertEqual(self.bar, None) self.assertFalse(mock_b.enter_called) self.assertFalse(mock_b.exit_called) self.assertEqual(mock_b.exit_args, None) def testNestedExceptionAfterInnerStatement(self): mock_a = mock_contextmanager_generator() mock_b = mock_contextmanager_generator() def shouldThrow(): with mock_a as self.foo: with mock_b as self.bar: self.assertInWithManagerInvariants(mock_a) self.assertInWithManagerInvariants(mock_b) self.assertInWithGeneratorInvariants(self.foo) self.assertInWithGeneratorInvariants(self.bar) self.raiseTestException() self.assertRaises(RuntimeError, shouldThrow) self.assertAfterWithManagerInvariantsWithError(mock_a) self.assertAfterWithManagerInvariantsNoError(mock_b) self.assertAfterWithGeneratorInvariantsWithError(self.foo) self.assertAfterWithGeneratorInvariantsNoError(self.bar) def testRaisedStopIteration1(self): # From bug 1462485 @contextmanager def cm(): yield def shouldThrow(): with cm(): raise StopIteration("from with") with self.assertRaisesRegex(StopIteration, 'from with'): shouldThrow() def testRaisedStopIteration2(self): # From bug 1462485 with torch._dynamo.error_on_graph_break(False): class cm(object): def __enter__(self): pass def __exit__(self, type, value, traceback): pass def shouldThrow(): with cm(): raise StopIteration("from with") with self.assertRaisesRegex(StopIteration, 'from with'): shouldThrow() def testRaisedStopIteration3(self): # Another variant where the exception hasn't been instantiated # From bug 1705170 @contextmanager def cm(): yield def shouldThrow(): with cm(): raise next(iter([])) with self.assertRaises(StopIteration): shouldThrow() def testRaisedGeneratorExit1(self): # From bug 1462485 @contextmanager def cm(): yield def shouldThrow(): with cm(): raise GeneratorExit("from with") self.assertRaises(GeneratorExit, shouldThrow) def testRaisedGeneratorExit2(self): # From bug 1462485 with torch._dynamo.error_on_graph_break(False): class cm (object): def __enter__(self): pass def __exit__(self, type, value, traceback): pass def shouldThrow(): with cm(): raise GeneratorExit("from with") self.assertRaises(GeneratorExit, shouldThrow) def testErrorsInBool(self): # issue4589: __exit__ return code may raise an exception # when looking at its truth value. with torch._dynamo.error_on_graph_break(False): class cm(object): def __init__(self, bool_conversion): class Bool: def __bool__(self): return bool_conversion() self.exit_result = Bool() def __enter__(self): return 3 def __exit__(self, a, b, c): return self.exit_result def trueAsBool(): with cm(lambda: True): self.fail("Should NOT see this") trueAsBool() def falseAsBool(): with cm(lambda: False): self.fail("Should raise") self.assertRaises(AssertionError, falseAsBool) def failAsBool(): with cm(lambda: 1//0): self.fail("Should NOT see this") self.assertRaises(ZeroDivisionError, failAsBool)
ExceptionalTestCase
python
pytorch__pytorch
torch/nn/modules/activation.py
{ "start": 57601, "end": 59400 }
class ____(Module): r"""Applies the Softmax function to an n-dimensional input Tensor. Rescales them so that the elements of the n-dimensional output Tensor lie in the range [0,1] and sum to 1. Softmax is defined as: .. math:: \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)} When the input Tensor is a sparse tensor then the unspecified values are treated as ``-inf``. Shape: - Input: :math:`(*)` where `*` means, any number of additional dimensions - Output: :math:`(*)`, same shape as the input Returns: a Tensor of the same dimension and shape as the input with values in the range [0, 1] Args: dim (int): A dimension along which Softmax will be computed (so every slice along dim will sum to 1). .. note:: This module doesn't work directly with NLLLoss, which expects the Log to be computed between the Softmax and itself. Use `LogSoftmax` instead (it's faster and has better numerical properties). Examples:: >>> m = nn.Softmax(dim=1) >>> input = torch.randn(2, 3) >>> output = m(input) """ __constants__ = ["dim"] dim: Optional[int] def __init__(self, dim: Optional[int] = None) -> None: super().__init__() self.dim = dim def __setstate__(self, state): super().__setstate__(state) if not hasattr(self, "dim"): self.dim = None def forward(self, input: Tensor) -> Tensor: """ Runs the forward pass. """ return F.softmax(input, self.dim, _stacklevel=5) def extra_repr(self) -> str: """ Return the extra representation of the module. """ return f"dim={self.dim}"
Softmax
python
django-mptt__django-mptt
tests/myapp/tests.py
{ "start": 76513, "end": 77937 }
class ____(TreeTestCase): """ Regression tests for #176 and #424 """ def setUp(self): OrderedInsertion.objects.create(name="a") def test_deferred_order_insertion_by(self): qs = OrderedInsertion.objects.defer("name") with self.assertNumQueries(1): nodes = list(qs) with self.assertNumQueries(0): self.assertTreeEqual( nodes, """ 1 - 1 0 1 2 """, ) def test_deferred_cached_field_undeferred(self): obj = OrderedInsertion.objects.defer("name").get() self.assertEqual(obj._mptt_cached_fields["name"], DeferredAttribute) with self.assertNumQueries(1): obj.name with self.assertNumQueries(3): # does a node move, since the order_insertion_by field changed obj.save() self.assertEqual(obj._mptt_cached_fields["name"], "a") def test_deferred_cached_field_change(self): obj = OrderedInsertion.objects.defer("name").get() self.assertEqual(obj._mptt_cached_fields["name"], DeferredAttribute) with self.assertNumQueries(0): obj.name = "b" with self.assertNumQueries(3): # does a node move, since the order_insertion_by field changed obj.save() self.assertEqual(obj._mptt_cached_fields["name"], "b")
DeferredAttributeTests
python
vyperlang__vyper
vyper/compiler/input_bundle.py
{ "start": 524, "end": 1196 }
class ____: # an input to the compiler, basically an abstraction for file contents source_id: int path: PathLike # the path that was asked for # resolved_path is the real path that was resolved to. # mainly handy for debugging at this point resolved_path: PathLike contents: str @cached_property def sha256sum(self): return sha256sum(self.contents) @property def from_builtin(self): return self.source_id == BUILTIN # fast hash which doesn't require looking at the contents def __hash__(self): return hash((self.source_id, self.path, self.resolved_path)) @dataclass(frozen=True)
CompilerInput
python
huggingface__transformers
src/transformers/models/pegasus/modeling_pegasus.py
{ "start": 55800, "end": 61834 }
class ____(PegasusPreTrainedModel, GenerationMixin): _tied_weights_keys = { "lm_head.weight": "model.decoder.embed_tokens.weight", } def __init__(self, config): config = copy.deepcopy(config) config.is_decoder = True config.is_encoder_decoder = False super().__init__(config) self.model = PegasusDecoderWrapper(config) self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.decoder.embed_tokens def set_input_embeddings(self, value): self.model.decoder.embed_tokens = value def get_position_embeddings(self) -> nn.Embedding: """ Returns the position embeddings matrix """ return self.model.decoder.get_position_embeddings() def resize_position_embeddings(self, new_num_position_embeddings: int): """ Resizes position embeddings matrix of the model if `new_num_position_embeddings != config.max_position_embeddings`. Arguments: new_num_position_embeddings (`int`): The number of new position embeddings. If position embeddings are learned, increasing the size will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will add correct vectors at the end following the position encoding algorithm, whereas reducing the size will remove vectors from the end. """ self.config.max_position_embeddings = new_num_position_embeddings self.model.decoder.resize_position_embeddings(new_num_position_embeddings) @auto_docstring # Copied from transformers.models.bart.modeling_bart.BartForCausalLM.forward with Bart->Pegasus, facebook/bart-base->google/pegasus-large def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, ) -> Union[tuple, CausalLMOutputWithCrossAttentions]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Example: ```python >>> from transformers import AutoTokenizer, PegasusForCausalLM >>> tokenizer = AutoTokenizer.from_pretrained("google/pegasus-large") >>> model = PegasusForCausalLM.from_pretrained("google/pegasus-large", add_cross_attention=False) >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder." >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") >>> outputs = model(**inputs) >>> logits = outputs.logits >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size] >>> list(logits.shape) == expected_shape True ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model.decoder( input_ids=input_ids, attention_mask=attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) hidden_states = outputs[0] # Only compute necessary logits slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: labels = labels.to(logits.device) loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return CausalLMOutputWithCrossAttentions( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions, ) __all__ = ["PegasusForCausalLM", "PegasusForConditionalGeneration", "PegasusModel", "PegasusPreTrainedModel"]
PegasusForCausalLM
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_for_serving_test.py
{ "start": 1267, "end": 16972 }
class ____(test.TestCase): def setUp(self): super(TPUEmbeddingForServingTest, self).setUp() self.embedding_values = np.array(list(range(32)), dtype=np.float64) self.initializer = init_ops_v2.Constant(self.embedding_values) # Embedding for video initialized to # 0 1 2 3 # 4 5 6 7 # ... self.table_video = tpu_embedding_v2_utils.TableConfig( vocabulary_size=8, dim=4, initializer=self.initializer, combiner='sum', name='video') # Embedding for user initialized to # 0 1 # 2 3 # 4 5 # 6 7 # ... self.table_user = tpu_embedding_v2_utils.TableConfig( vocabulary_size=16, dim=2, initializer=self.initializer, combiner='mean', name='user') self.feature_config = ( tpu_embedding_v2_utils.FeatureConfig( table=self.table_video, name='watched'), tpu_embedding_v2_utils.FeatureConfig( table=self.table_video, name='favorited'), tpu_embedding_v2_utils.FeatureConfig( table=self.table_user, name='friends')) self.batch_size = 2 self.data_batch_size = 4 # One (global) batch of inputs # sparse tensor for watched: # row 0: 0 # row 1: 0, 1 # row 2: 0, 1 # row 3: 1 self.feature_watched_indices = [[0, 0], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0]] self.feature_watched_values = [0, 0, 1, 0, 1, 1] self.feature_watched_row_lengths = [1, 2, 2, 1] # sparse tensor for favorited: # row 0: 0, 1 # row 1: 1 # row 2: 0 # row 3: 0, 1 self.feature_favorited_indices = [[0, 0], [0, 1], [1, 0], [2, 0], [3, 0], [3, 1]] self.feature_favorited_values = [0, 1, 1, 0, 0, 1] self.feature_favorited_row_lengths = [2, 1, 1, 2] # sparse tensor for friends: # row 0: 3 # row 1: 0, 1, 2 # row 2: 3 # row 3: 0, 1, 2 self.feature_friends_indices = [[0, 0], [1, 0], [1, 1], [1, 2], [2, 0], [3, 0], [3, 1], [3, 2]] self.feature_friends_values = [3, 0, 1, 2, 3, 0, 1, 2] self.feature_friends_row_lengths = [1, 3, 1, 3] def _create_mid_level(self): optimizer = tpu_embedding_v2_utils.SGD(learning_rate=0.1) return tpu_embedding_for_serving.TPUEmbeddingForServing( feature_config=self.feature_config, optimizer=optimizer) def _get_dense_tensors(self, dtype=dtypes.int32): feature0 = constant_op.constant(self.feature_watched_values, dtype=dtype) feature1 = constant_op.constant(self.feature_favorited_values, dtype=dtype) feature2 = constant_op.constant(self.feature_friends_values, dtype=dtype) return (feature0, feature1, feature2) def test_cpu_dense_lookup(self): mid_level = self._create_mid_level() features = self._get_dense_tensors() results = mid_level(features, weights=None) all_lookups = [] for feature, config in zip(nest.flatten(features), self.feature_config): table = mid_level.embedding_tables[config.table].numpy() all_lookups.append(table[feature.numpy()]) self.assertAllClose(results, nest.pack_sequence_as(results, all_lookups)) def test_cpu_dense_lookup_with_weights(self): mid_level = self._create_mid_level() features = self._get_dense_tensors() weights = self._get_dense_tensors(dtype=dtypes.float32) with self.assertRaisesRegex( ValueError, 'Weight specified for .*, but input is dense.'): mid_level(features, weights=weights) def _get_sparse_tensors(self, dtype=dtypes.int32): feature0 = sparse_tensor.SparseTensor( indices=self.feature_watched_indices, values=constant_op.constant(self.feature_watched_values, dtype=dtype), dense_shape=[self.data_batch_size, 2]) feature1 = sparse_tensor.SparseTensor( indices=self.feature_favorited_indices, values=constant_op.constant(self.feature_favorited_values, dtype=dtype), dense_shape=[self.data_batch_size, 2]) feature2 = sparse_tensor.SparseTensor( indices=self.feature_friends_indices, values=constant_op.constant(self.feature_friends_values, dtype=dtype), dense_shape=[self.data_batch_size, 3]) return (feature0, feature1, feature2) def test_cpu_sparse_lookup(self): mid_level = self._create_mid_level() features = self._get_sparse_tensors() results = mid_level(features, weights=None) reduced = [] for feature, config in zip(nest.flatten(features), self.feature_config): table = mid_level.embedding_tables[config.table].numpy() all_lookups = table[feature.values.numpy()] # With row starts we can use reduceat in numpy. Get row starts from the # ragged tensor API. ragged = ragged_tensor.RaggedTensor.from_sparse(feature) row_starts = ragged.row_starts().numpy() reduced.append(np.add.reduceat(all_lookups, row_starts)) if config.table.combiner == 'mean': # for mean, divide by the row lengths. reduced[-1] /= np.expand_dims(ragged.row_lengths().numpy(), axis=1) self.assertAllClose(results, nest.pack_sequence_as(results, reduced)) def test_cpu_sparse_lookup_with_weights(self): mid_level = self._create_mid_level() features = self._get_sparse_tensors() weights = self._get_sparse_tensors(dtype=dtypes.float32) results = mid_level(features, weights=weights) weighted_sum = [] for feature, weight, config in zip(nest.flatten(features), nest.flatten(weights), self.feature_config): table = mid_level.embedding_tables[config.table].numpy() # Expand dims here needed to broadcast this multiplication properly. weight = np.expand_dims(weight.values.numpy(), axis=1) all_lookups = table[feature.values.numpy()] * weight # With row starts we can use reduceat in numpy. Get row starts from the # ragged tensor API. row_starts = ragged_tensor.RaggedTensor.from_sparse(feature).row_starts() row_starts = row_starts.numpy() weighted_sum.append(np.add.reduceat(all_lookups, row_starts)) if config.table.combiner == 'mean': weighted_sum[-1] /= np.add.reduceat(weight, row_starts) self.assertAllClose(results, nest.pack_sequence_as(results, weighted_sum)) def test_cpu_sparse_lookup_with_non_sparse_weights(self): mid_level = self._create_mid_level() features = self._get_sparse_tensors() weights = self._get_dense_tensors(dtype=dtypes.float32) with self.assertRaisesRegex( ValueError, 'but it does not match type of the input which is'): mid_level(features, weights=weights) def _get_ragged_tensors(self, dtype=dtypes.int32): feature0 = ragged_tensor.RaggedTensor.from_row_lengths( values=constant_op.constant(self.feature_watched_values, dtype=dtype), row_lengths=self.feature_watched_row_lengths) feature1 = ragged_tensor.RaggedTensor.from_row_lengths( values=constant_op.constant(self.feature_favorited_values, dtype=dtype), row_lengths=self.feature_favorited_row_lengths) feature2 = ragged_tensor.RaggedTensor.from_row_lengths( values=constant_op.constant(self.feature_friends_values, dtype=dtype), row_lengths=self.feature_friends_row_lengths) return (feature0, feature1, feature2) def test_cpu_ragged_lookup_with_weights(self): mid_level = self._create_mid_level() features = self._get_ragged_tensors() weights = self._get_ragged_tensors(dtype=dtypes.float32) results = mid_level(features, weights=weights) weighted_sum = [] for feature, weight, config in zip(nest.flatten(features), nest.flatten(weights), self.feature_config): table = mid_level.embedding_tables[config.table].numpy() # Expand dims here needed to broadcast this multiplication properly. weight = np.expand_dims(weight.values.numpy(), axis=1) all_lookups = table[feature.values.numpy()] * weight row_starts = feature.row_starts().numpy() weighted_sum.append(np.add.reduceat(all_lookups, row_starts)) if config.table.combiner == 'mean': weighted_sum[-1] /= np.add.reduceat(weight, row_starts) self.assertAllClose(results, nest.pack_sequence_as(results, weighted_sum)) def test_cpu_partial_structure_for_features(self): mid_level = self._create_mid_level() # Remove one element of the tuple, the inputs are a subset of # feature_config and will be able to excute. features = tuple(self._get_sparse_tensors()[:2]) results = mid_level(features, weights=None) reduced = [] for i, feature in enumerate(nest.flatten(features)): config = self.feature_config[i] table = mid_level.embedding_tables[config.table].numpy() all_lookups = table[feature.values.numpy()] # With row starts we can use reduceat in numpy. Get row starts from the # ragged tensor API. ragged = ragged_tensor.RaggedTensor.from_sparse(feature) row_starts = ragged.row_starts().numpy() reduced.append(np.add.reduceat(all_lookups, row_starts)) if config.table.combiner == 'mean': # for mean, divide by the row lengths. reduced[-1] /= np.expand_dims(ragged.row_lengths().numpy(), axis=1) self.assertAllClose(results, nest.pack_sequence_as(results, reduced)) def test_cpu_invalid_structure_for_features(self): mid_level = self._create_mid_level() # Add one element of the tuple, self.feature_config has 3 so we need to # pass no more than 3 elements or None. features = self._get_sparse_tensors() + (self._get_sparse_tensors()[0],) with self.assertRaises(ValueError): mid_level(features, weights=None) def test_cpu_invalid_structure_for_weights(self): mid_level = self._create_mid_level() features = self._get_sparse_tensors() # Remove one element of the tuple, inputs has 3 so we need to pass 3 (or # None). weights = tuple(self._get_dense_tensors(dtype=dtypes.float32)[:2]) with self.assertRaises(ValueError): mid_level(features, weights=weights) def _numpy_sequence_lookup(self, table, indices, values, batch_size, max_sequence_length, dim): # First we truncate to max_sequence_length. valid_entries = np.nonzero(indices[:, 1] < max_sequence_length)[0] indices = indices[valid_entries] values = values[valid_entries] # Then we gather the values lookup = table[values] # Then we scatter them into the result array. scatter_result = np.zeros([batch_size, max_sequence_length, dim]) for i, index in enumerate(indices): scatter_result[index[0], index[1], :] = lookup[i] return scatter_result def test_cpu_sequence_lookup_sparse(self): feature_config = ( tpu_embedding_v2_utils.FeatureConfig( table=self.table_user, name='friends', max_sequence_length=2),) optimizer = tpu_embedding_v2_utils.SGD(learning_rate=0.1) mid_level = tpu_embedding_for_serving.TPUEmbeddingForServing( feature_config=feature_config, optimizer=optimizer) features = self._get_sparse_tensors()[2:3] result = mid_level(features, weights=None) golden = self._numpy_sequence_lookup( mid_level.embedding_tables[self.table_user].numpy(), features[0].indices.numpy(), features[0].values.numpy(), self.data_batch_size, feature_config[0].max_sequence_length, self.table_user.dim) self.assertAllClose(result[0], golden) def test_cpu_sequence_lookup_ragged(self): feature_config = ( tpu_embedding_v2_utils.FeatureConfig( table=self.table_user, name='friends', max_sequence_length=2),) optimizer = tpu_embedding_v2_utils.SGD(learning_rate=0.1) mid_level = tpu_embedding_for_serving.TPUEmbeddingForServing( feature_config=feature_config, optimizer=optimizer) features = self._get_ragged_tensors()[2:3] result = mid_level(features, weights=None) sparse_ver = features[0].to_sparse() golden = self._numpy_sequence_lookup( mid_level.embedding_tables[self.table_user].numpy(), sparse_ver.indices.numpy(), sparse_ver.values.numpy(), self.data_batch_size, feature_config[0].max_sequence_length, self.table_user.dim) self.assertAllClose(result[0], golden) def test_cpu_high_dimensional_lookup_ragged(self): feature_config = (tpu_embedding_v2_utils.FeatureConfig( table=self.table_user, name='friends', output_shape=[2, 2]),) optimizer = tpu_embedding_v2_utils.SGD(learning_rate=0.1) mid_level = tpu_embedding_for_serving.TPUEmbeddingForServing( feature_config=feature_config, optimizer=optimizer) features = self._get_ragged_tensors()[2:3] result = mid_level(features, weights=None) self.assertAllClose(result[0].shape, (2, 2, 2)) def test_cpu_high_dimensional_sequence_lookup_ragged(self): # Prod of output shape is a factor of the data batch size. # The divide result will be the sequence length. feature_config = (tpu_embedding_v2_utils.FeatureConfig( table=self.table_user, name='friends', output_shape=[2, 4]),) optimizer = tpu_embedding_v2_utils.SGD(learning_rate=0.1) mid_level = tpu_embedding_for_serving.TPUEmbeddingForServing( feature_config=feature_config, optimizer=optimizer) features = self._get_ragged_tensors()[2:3] result = mid_level(features, weights=None) self.assertAllClose(result[0].shape, (2, 4, 2)) def test_cpu_high_dimensional_invalid_lookup_ragged(self): # Prod of output shape is not a factor of the data batch size. # An error will be raised in this case. feature_config = (tpu_embedding_v2_utils.FeatureConfig( table=self.table_user, name='friends', output_shape=[3]),) optimizer = tpu_embedding_v2_utils.SGD(learning_rate=0.1) mid_level = tpu_embedding_for_serving.TPUEmbeddingForServing( feature_config=feature_config, optimizer=optimizer) features = self._get_ragged_tensors()[2:3] with self.assertRaisesRegex( ValueError, 'Output shape set in the FeatureConfig should be the factor'): mid_level(features, weights=None) def test_cpu_no_optimizer(self): feature_config = ( tpu_embedding_v2_utils.FeatureConfig( table=self.table_video, name='watched', max_sequence_length=2),) mid_level = tpu_embedding_for_serving.TPUEmbeddingForServing( feature_config=feature_config, optimizer=None) # Build the layer manually to create the variables. Normally calling enqueue # would do this. mid_level.build() self.assertEqual( list(mid_level._variables[self.table_video.name].keys()), ['parameters']) def test_cpu_multiple_creation(self): feature_config = (tpu_embedding_v2_utils.FeatureConfig( table=self.table_user, name='friends', max_sequence_length=2),) optimizer = tpu_embedding_v2_utils.SGD(learning_rate=0.1) embedding_one = tpu_embedding_for_serving.TPUEmbeddingForServing( feature_config=feature_config, optimizer=optimizer) embedding_two = tpu_embedding_for_serving.TPUEmbeddingForServing( feature_config=feature_config, optimizer=optimizer) # Both of the tpu embedding tables should be able to build on cpu. embedding_one.build() embedding_two.build() if __name__ == '__main__': v2_compat.enable_v2_behavior() test.main()
TPUEmbeddingForServingTest
python
kamyu104__LeetCode-Solutions
Python/lowest-common-ancestor-of-a-binary-tree.py
{ "start": 29, "end": 729 }
class ____(object): # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): if root in (None, p, q): return root left, right = [self.lowestCommonAncestor(child, p, q) \ for child in (root.left, root.right)] # 1. If the current subtree contains both p and q, # return their LCA. # 2. If only one of them is in that subtree, # return that one of them. # 3. If neither of them is in that subtree, # return the node of that subtree. return root if left and right else left or right
Solution
python
getsentry__sentry
src/sentry/integrations/mixins/issues.py
{ "start": 1748, "end": 2528 }
class ____(enum.Enum): """ When an issue's state changes, we may have to sync the state based on the "done" states we get from the API. This enum encapsulates the three options we have: "resolve", "unresolve", or "do nothing". """ NOOP = 0 RESOLVE = 1 UNRESOLVE = 2 @classmethod def from_resolve_unresolve( cls, should_resolve: bool, should_unresolve: bool ) -> ResolveSyncAction: if should_resolve and should_unresolve: logger.warning("sync-config-conflict") return ResolveSyncAction.NOOP if should_resolve: return ResolveSyncAction.RESOLVE if should_unresolve: return ResolveSyncAction.UNRESOLVE return ResolveSyncAction.NOOP
ResolveSyncAction
python
huggingface__transformers
tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py
{ "start": 4958, "end": 8067 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as MobileNetV1 does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (MobileNetV1Model, MobileNetV1ForImageClassification) if is_torch_available() else () pipeline_model_mapping = ( {"image-feature-extraction": MobileNetV1Model, "image-classification": MobileNetV1ForImageClassification} if is_torch_available() else {} ) test_resize_embeddings = False has_attentions = False test_torch_exportable = True def setUp(self): self.model_tester = MobileNetV1ModelTester(self) self.config_tester = MobileNetV1ConfigTester(self, config_class=MobileNetV1Config, has_text_modality=False) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="MobileNetV1 does not output attentions") def test_attention_outputs(self): pass def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_stages = 26 self.assertEqual(len(hidden_states), expected_num_stages) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) def test_for_image_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "google/mobilenet_v1_1.0_224" model = MobileNetV1Model.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_vision
MobileNetV1ModelTest
python
getsentry__sentry
tests/sentry/tasks/test_activity.py
{ "start": 229, "end": 411 }
class ____(NotificationPlugin): def notify_about_activity(self, activity): pass def is_enabled(self, project=None) -> bool: return True
BasicPreprocessorPlugin
python
django__django
django/db/models/functions/text.py
{ "start": 11465, "end": 11538 }
class ____(Transform): function = "UPPER" lookup_name = "upper"
Upper
python
google__pytype
pytype/tests/test_match2.py
{ "start": 15488, "end": 20454 }
class ____(test_base.BaseTest): """Tests for non-iterable string behavior.""" def test_add_string(self): ty = self.Infer(""" a = [] a += list("foo") a += "bar" """) self.assertTypesMatchPytd( ty, """ from typing import List a = ... # type: List[str] """, ) def test_str_against_plain_iterable(self): self.Check(""" from typing import Iterable def f (itr: Iterable): return f("abcdef") f(["abc", "def", "ghi"]) f(("abc", "def", "ghi")) """) def test_str_against_iterable(self): self.CheckWithErrors(""" from typing import Iterable def f(x: Iterable[str]): return x f("abcdef") # wrong-arg-types f(["abc", "def", "ghi"]) f(("abc", "def", "ghi")) """) def test_str_against_plain_sequence(self): self.Check(""" from typing import Sequence def f (itr: Sequence): return f("abcdef") f(["abc", "def", "ghi"]) """) def test_str_against_sequence(self): self.CheckWithErrors(""" from typing import Sequence def f(x: Sequence[str]): return x f("abcdef") # wrong-arg-types f(["abc", "def", "ghi"]) f(("abc", "def", "ghi")) """) def test_intended_iterable_str_against_sequence(self): self.Check(""" from typing import Union, Sequence def f(x: Union[str, Sequence[str]]): return x f("abcdef") f(["abc", "def", "ghi"]) f(("abc", "def", "ghi")) """) def test_intended_iterable_str_against_iterable(self): self.Check(""" from typing import Union, Iterable def f(x: Union[str, Iterable[str]]): return x f("abcdef") f(["abc", "def", "ghi"]) f(("abc", "def", "ghi")) """) def test_str_against_union_sequence_str(self): self.Check(""" from typing import Union, Sequence def f(x: Union[Sequence[str], str]): return x f("abcdef") f(["abc", "def", "ghi"]) f(("abc", "def", "ghi")) """) def test_str_against_union_iterable_str(self): self.Check(""" from typing import Union, Iterable def f(x: Union[Iterable[str], str]): return x f("abcdef") f(["abc", "def", "ghi"]) f(("abc", "def", "ghi")) """) def test_optional_str_against_iterable(self): self.CheckWithErrors(""" from typing import Iterable, Optional def foo(x: Iterable[str]): ... def bar(s: str): foo(s) # wrong-arg-types def baz(os: Optional[str]): foo(os) # wrong-arg-types """) def test_optional_str_against_plain_iterable(self): self.Check(""" from typing import Iterable, Optional def foo(x: Iterable): ... def bar(s: str): foo(s) def baz(os: Optional[str]): foo(os) # TODO(b/63407497): should be wrong-arg-types """) def test_str_against_plain_collection(self): self.Check(""" from typing import Collection def f(itr: Collection): return f("abcdef") f(["abc", "def", "ghi"]) """) def test_str_against_plain_container(self): self.Check(""" from typing import Container def f(itr: Container): return f("abcdef") f(["abc", "def", "ghi"]) """) def test_str_against_plain_mapping(self): self.CheckWithErrors(""" from typing import Mapping def f(itr: Mapping): return f("abcdef") # wrong-arg-types """) def test_str_against_collection(self): self.CheckWithErrors(""" from typing import Collection def f(x: Collection[str]): return f("abcdef") # wrong-arg-types """) def test_str_against_container(self): self.CheckWithErrors(""" from typing import Container def f(x: Container[str]): return f("abcdef") # wrong-arg-types """) def test_str_against_mapping(self): self.CheckWithErrors(""" from typing import Mapping def f(x: Mapping[int, str]): return f("abcdef") # wrong-arg-types """) def test_star_unpacking_strings(self): self.Check(""" *a, b = "hello world" """) def test_from_keys(self): self.Check(""" d = dict.fromkeys(u"x") """) def test_filter(self): self.Check(""" x = filter(None, "") """) def test_reduce(self): self.Check(""" x = reduce(lambda x, y: 42, "abcdef") """) def test_sorted(self): self.Check(""" x = sorted(u"hello") """) def test_iter(self): self.Check(""" x = iter("hello") """) def test_zip(self): self.Check(""" x = zip("abc", "def") """) def test_tuple_init(self): self.Check(""" x = tuple("abcdef") """) def test_frozenset_init(self): self.Check(""" x = frozenset("abcdef") """) if __name__ == "__main__": test_base.main()
NonIterableStringsTest
python
scikit-learn__scikit-learn
sklearn/linear_model/_coordinate_descent.py
{ "start": 53226, "end": 69338 }
class ____(MultiOutputMixin, LinearModel, ABC): """Base class for iterative model fitting along a regularization path.""" _parameter_constraints: dict = { "eps": [Interval(Real, 0, None, closed="neither")], "n_alphas": [ Interval(Integral, 1, None, closed="left"), Hidden(StrOptions({"deprecated"})), ], # TODO(1.9): remove "warn" and None options. "alphas": [ Interval(Integral, 1, None, closed="left"), "array-like", None, Hidden(StrOptions({"warn"})), ], "fit_intercept": ["boolean"], "precompute": [StrOptions({"auto"}), "array-like", "boolean"], "max_iter": [Interval(Integral, 1, None, closed="left")], "tol": [Interval(Real, 0, None, closed="left")], "copy_X": ["boolean"], "cv": ["cv_object"], "verbose": ["verbose"], "n_jobs": [Integral, None], "positive": ["boolean"], "random_state": ["random_state"], "selection": [StrOptions({"cyclic", "random"})], } @abstractmethod def __init__( self, eps=1e-3, n_alphas="deprecated", alphas="warn", fit_intercept=True, precompute="auto", max_iter=1000, tol=1e-4, copy_X=True, cv=None, verbose=False, n_jobs=None, positive=False, random_state=None, selection="cyclic", ): self.eps = eps self.n_alphas = n_alphas self.alphas = alphas self.fit_intercept = fit_intercept self.precompute = precompute self.max_iter = max_iter self.tol = tol self.copy_X = copy_X self.cv = cv self.verbose = verbose self.n_jobs = n_jobs self.positive = positive self.random_state = random_state self.selection = selection @abstractmethod def _get_estimator(self): """Model to be fitted after the best alpha has been determined.""" @abstractmethod def _is_multitask(self): """Bool indicating if class is meant for multidimensional target.""" @staticmethod @abstractmethod def path(X, y, **kwargs): """Compute path with coordinate descent.""" @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y, sample_weight=None, **params): """Fit linear model with coordinate descent. Fit is on grid of alphas and best alpha estimated by cross-validation. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output, X can be sparse. Note that large sparse matrices and arrays requiring `int64` indices are not accepted. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. sample_weight : float or array-like of shape (n_samples,), \ default=None Sample weights used for fitting and evaluation of the weighted mean squared error of each cv-fold. Note that the cross validated MSE that is finally used to find the best model is the unweighted mean over the (weighted) MSEs of each test fold. **params : dict, default=None Parameters to be passed to the CV splitter. .. versionadded:: 1.4 Only available if `enable_metadata_routing=True`, which can be set by using ``sklearn.set_config(enable_metadata_routing=True)``. See :ref:`Metadata Routing User Guide <metadata_routing>` for more details. Returns ------- self : object Returns an instance of fitted model. """ _raise_for_params(params, self, "fit") # TODO(1.9): remove n_alphas and alphas={"warn", None}; set alphas=100 by # default. Remove these deprecations messages and use self.alphas directly # instead of self._alphas. if self.n_alphas == "deprecated": self._alphas = 100 else: warnings.warn( "'n_alphas' was deprecated in 1.7 and will be removed in 1.9. " "'alphas' now accepts an integer value which removes the need to pass " "'n_alphas'. The default value of 'alphas' will change from None to " "100 in 1.9. Pass an explicit value to 'alphas' and leave 'n_alphas' " "to its default value to silence this warning.", FutureWarning, ) self._alphas = self.n_alphas if isinstance(self.alphas, str) and self.alphas == "warn": # - If self.n_alphas == "deprecated", both are left to their default values # so we don't warn since the future default behavior will be the same as # the current default behavior. # - If self.n_alphas != "deprecated", then we already warned about it # and the warning message mentions the future self.alphas default, so # no need to warn a second time. pass elif self.alphas is None: warnings.warn( "'alphas=None' is deprecated and will be removed in 1.9, at which " "point the default value will be set to 100. Set 'alphas=100' " "to silence this warning.", FutureWarning, ) else: self._alphas = self.alphas # This makes sure that there is no duplication in memory. # Dealing right with copy_X is important in the following: # Multiple functions touch X and subsamples of X and can induce a # lot of duplication of memory. # There is no need copy X if the model is fit without an intercept. copy_X = self.copy_X and self.fit_intercept # TODO: Sample_weights? check_y_params = dict( copy=False, dtype=[np.float64, np.float32], ensure_2d=False ) if isinstance(X, np.ndarray) or sparse.issparse(X): # Keep a reference to X reference_to_old_X = X # Let us not impose Fortran-contiguity so far: In the cross-validation # loop, rows of X will be subsampled and produce non-F-contiguous X_fold # anyway. _path_residual will take care about it. # Need to validate separately here. # We can't pass multi_output=True because that would allow y to be # csr. We also want to allow y to be 64 or 32 but check_X_y only # allows to convert for 64. check_X_params = dict( accept_sparse="csc", dtype=[np.float64, np.float32], force_writeable=True, copy=False, accept_large_sparse=False, ) X, y = validate_data( self, X, y, validate_separately=(check_X_params, check_y_params) ) if sparse.issparse(X): if hasattr(reference_to_old_X, "data") and not np.may_share_memory( reference_to_old_X.data, X.data ): # X is a sparse matrix and has been copied. No need to copy again. copy_X = False elif not np.may_share_memory(reference_to_old_X, X): # X has been copied. No need to copy again. copy_X = False del reference_to_old_X else: # Need to validate separately here. # We can't pass multi_output=True because that would allow y to be # csr. We also want to allow y to be 64 or 32 but check_X_y only # allows to convert for 64. check_X_params = dict( accept_sparse="csc", dtype=[np.float64, np.float32], order="F", force_writeable=True, copy=copy_X, ) X, y = validate_data( self, X, y, validate_separately=(check_X_params, check_y_params) ) copy_X = False check_consistent_length(X, y) if not self._is_multitask(): if y.ndim > 1 and y.shape[1] > 1: raise ValueError( "For multi-task outputs, use MultiTask%s" % self.__class__.__name__ ) y = column_or_1d(y, warn=True) else: if sparse.issparse(X): raise TypeError("X should be dense but a sparse matrix was passed.") elif y.ndim == 1: raise ValueError( "For mono-task outputs, use %sCV" % self.__class__.__name__[9:] ) if isinstance(sample_weight, numbers.Number): sample_weight = None if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) model = self._get_estimator() # All LinearModelCV parameters except 'cv' are acceptable path_params = self.get_params() # fit_intercept is not a parameter of the path function path_params.pop("fit_intercept", None) if "l1_ratio" in path_params: l1_ratios = np.atleast_1d(path_params["l1_ratio"]) # For the first path, we need to set l1_ratio path_params["l1_ratio"] = l1_ratios[0] else: l1_ratios = [ 1, ] path_params.pop("cv", None) path_params.pop("n_jobs", None) n_l1_ratio = len(l1_ratios) check_scalar_alpha = partial( check_scalar, target_type=Real, min_val=0.0, include_boundaries="left", ) if isinstance(self._alphas, Integral): alphas = [ _alpha_grid( X, y, l1_ratio=l1_ratio, fit_intercept=self.fit_intercept, eps=self.eps, n_alphas=self._alphas, sample_weight=sample_weight, ) for l1_ratio in l1_ratios ] else: # Making sure alphas entries are scalars. for index, alpha in enumerate(self._alphas): check_scalar_alpha(alpha, f"alphas[{index}]") # Making sure alphas is properly ordered. alphas = np.tile(np.sort(self._alphas)[::-1], (n_l1_ratio, 1)) # We want n_alphas to be the number of alphas used for each l1_ratio. n_alphas = len(alphas[0]) path_params.update({"n_alphas": n_alphas}) path_params["copy_X"] = copy_X # We are not computing in parallel, we can modify X # inplace in the folds if effective_n_jobs(self.n_jobs) > 1: path_params["copy_X"] = False # init cross-validation generator cv = check_cv(self.cv) if _routing_enabled(): splitter_supports_sample_weight = get_routing_for_object(cv).consumes( method="split", params=["sample_weight"] ) if ( sample_weight is not None and not splitter_supports_sample_weight and not has_fit_parameter(self, "sample_weight") ): raise ValueError( "The CV splitter and underlying estimator do not support" " sample weights." ) if splitter_supports_sample_weight: params["sample_weight"] = sample_weight routed_params = process_routing(self, "fit", **params) if sample_weight is not None and not has_fit_parameter( self, "sample_weight" ): # MultiTaskElasticNetCV does not (yet) support sample_weight sample_weight = None else: routed_params = Bunch() routed_params.splitter = Bunch(split=Bunch()) # Compute path for all folds and compute MSE to get the best alpha folds = list(cv.split(X, y, **routed_params.splitter.split)) best_mse = np.inf # We do a double for loop folded in one, in order to be able to # iterate in parallel on l1_ratio and folds jobs = ( delayed(_path_residuals)( X, y, sample_weight, train, test, self.fit_intercept, self.path, path_params, alphas=this_alphas, l1_ratio=this_l1_ratio, X_order="F", dtype=X.dtype.type, ) for this_l1_ratio, this_alphas in zip(l1_ratios, alphas) for train, test in folds ) mse_paths = Parallel( n_jobs=self.n_jobs, verbose=self.verbose, prefer="threads", )(jobs) mse_paths = np.reshape(mse_paths, (n_l1_ratio, len(folds), -1)) # The mean is computed over folds. mean_mse = np.mean(mse_paths, axis=1) self.mse_path_ = np.squeeze(np.moveaxis(mse_paths, 2, 1)) for l1_ratio, l1_alphas, mse_alphas in zip(l1_ratios, alphas, mean_mse): i_best_alpha = np.argmin(mse_alphas) this_best_mse = mse_alphas[i_best_alpha] if this_best_mse < best_mse: best_alpha = l1_alphas[i_best_alpha] best_l1_ratio = l1_ratio best_mse = this_best_mse self.l1_ratio_ = best_l1_ratio self.alpha_ = best_alpha if isinstance(self._alphas, Integral): self.alphas_ = np.asarray(alphas) if n_l1_ratio == 1: self.alphas_ = self.alphas_[0] # Remove duplicate alphas in case alphas is provided. else: self.alphas_ = np.asarray(alphas[0]) # Refit the model with the parameters selected common_params = { name: value for name, value in self.get_params().items() if name in model.get_params() } model.set_params(**common_params) model.alpha = best_alpha model.l1_ratio = best_l1_ratio model.copy_X = copy_X precompute = getattr(self, "precompute", None) if isinstance(precompute, str) and precompute == "auto": model.precompute = False if sample_weight is None: # MultiTaskElasticNetCV does not (yet) support sample_weight, even # not sample_weight=None. model.fit(X, y) else: model.fit(X, y, sample_weight=sample_weight) if not hasattr(self, "l1_ratio"): del self.l1_ratio_ self.coef_ = model.coef_ self.intercept_ = model.intercept_ self.dual_gap_ = model.dual_gap_ self.n_iter_ = model.n_iter_ return self def get_metadata_routing(self): """Get metadata routing of this object. Please check :ref:`User Guide <metadata_routing>` on how the routing mechanism works. .. versionadded:: 1.4 Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating routing information. """ router = ( MetadataRouter(owner=self) .add_self_request(self) .add( splitter=check_cv(self.cv), method_mapping=MethodMapping().add(caller="fit", callee="split"), ) ) return router def __sklearn_tags__(self): tags = super().__sklearn_tags__() multitask = self._is_multitask() tags.input_tags.sparse = not multitask tags.target_tags.multi_output = multitask return tags
LinearModelCV
python
walkccc__LeetCode
solutions/3378. Count Connected Components in LCM Graph/3378.py
{ "start": 0, "end": 554 }
class ____: def __init__(self): self.id = {} self.rank = collections.Counter() def unionByRank(self, u: int, v: int) -> None: i = self.find(u) j = self.find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 def find(self, u: int) -> int: if u not in self.id: self.id[u] = u if self.id[u] != u: self.id[u] = self.find(self.id[u]) return self.id[u]
UnionFind
python
huggingface__transformers
src/transformers/models/deepseek_vl/image_processing_deepseek_vl.py
{ "start": 2232, "end": 21447 }
class ____(BaseImageProcessor): r""" Constructs a DEEPSEEK_VL image processor. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the `do_resize` parameter in the `preprocess` method. size (`dict`, *optional*, defaults to `{"height": 384, "width": 384}`): Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess` method. min_size (`int`, *optional*, defaults to 14): The minimum allowed size for the resized image. Ensures that neither the height nor width falls below this value after resizing. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`): Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be overridden by the `resample` parameter in the `preprocess` method. do_rescale (`bool`, *optional*, defaults to `True`): Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale` parameter in the `preprocess` method. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`): Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be overridden by the `rescale_factor` parameter in the `preprocess` method. do_normalize (`bool`, *optional*, defaults to `True`): Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess` method. Can be overridden by the `do_normalize` parameter in the `preprocess` method. image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`): Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be overridden by the `image_mean` parameter in the `preprocess` method. image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`): Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method. Can be overridden by the `image_std` parameter in the `preprocess` method. do_convert_rgb (`bool`, *optional*, defaults to `True`): Whether to convert the image to RGB. do_pad (`bool`, *optional*, defaults to `True`): Whether to pad the image to square or not. """ model_input_names = ["pixel_values"] valid_kwargs = DeepseekVLImageProcessorKwargs def __init__( self, do_resize: bool = True, size: Optional[dict[str, int]] = None, min_size: int = 14, resample: PILImageResampling = PILImageResampling.BICUBIC, do_rescale: bool = True, rescale_factor: Union[int, float] = 1 / 255, do_normalize: bool = True, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, do_convert_rgb: Optional[bool] = None, do_pad: Optional[bool] = True, **kwargs, ) -> None: super().__init__(**kwargs) size = size if size is not None else {"height": 384, "width": 384} size = get_size_dict(size, default_to_square=True) self.do_resize = do_resize self.size = size self.resample = resample self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.do_normalize = do_normalize self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD self.do_convert_rgb = do_convert_rgb self.do_pad = do_pad self.min_size = min_size if image_mean is None: self.background_color = (127, 127, 127) else: self.background_color = tuple(int(x * 255) for x in image_mean) def resize( self, image: np.ndarray, size: Union[dict[str, int], int], resample: PILImageResampling = PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Resize an image to dynamically calculated size. Args: image (`np.ndarray`): Image to resize. size (`dict[str, int]` or `int`): The size to resize the image to. If a dictionary, it should have the keys `"height"` and `"width"`. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`. data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the output image. If unset, the channel dimension format of the input image is used. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - `None`: will be inferred from input input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. Returns: `np.ndarray`: The resized image. """ if input_data_format is None: input_data_format = infer_channel_dimension_format(image) height, width = get_image_size(image, input_data_format) max_size = max(height, width) size = get_size_dict(size, default_to_square=True) if size["height"] != size["width"]: raise ValueError( f"Output height and width must be the same. Got height={size['height']} and width={size['width']}" ) size = size["height"] delta = size / max_size # Largest side becomes `size` and the other side is scaled according to the aspect ratio. output_size_nonpadded = [ max(int(height * delta), self.min_size), max(int(width * delta), self.min_size), ] image = resize( image, size=output_size_nonpadded, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs, ) return image @filter_out_non_signature_kwargs() def preprocess( self, images: ImageInput, do_resize: Optional[bool] = None, size: Optional[dict[str, int]] = None, resample: Optional[PILImageResampling] = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, return_tensors: Optional[Union[str, TensorType]] = None, do_convert_rgb: Optional[bool] = None, background_color: Optional[Union[int, tuple[int, int, int]]] = None, do_pad: Optional[bool] = None, data_format: ChannelDimension = ChannelDimension.FIRST, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> PIL.Image.Image: """ Preprocess an image or batch of images. Args: images (`ImageInput`): Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`. do_resize (`bool`, *optional*, defaults to `self.do_resize`): Whether to resize the image. size (`dict[str, int]`, *optional*, defaults to `self.size`): Controls the size of the image after `resize`. The shortest edge of the image is resized to `size["shortest_edge"]` whilst preserving the aspect ratio. If the longest edge of this resized image is > `int(size["shortest_edge"] * (1333 / 800))`, then the image is resized again to make the longest edge equal to `int(size["shortest_edge"] * (1333 / 800))`. resample (`PILImageResampling`, *optional*, defaults to `self.resample`): Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the image values between [0 - 1]. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): Rescale factor to rescale the image by if `do_rescale` is set to `True`. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): Whether to normalize the image. image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`): Image mean to normalize the image by if `do_normalize` is set to `True`. image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`): Image standard deviation to normalize the image by if `do_normalize` is set to `True`. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`): Whether to convert the image to RGB. background_color (`tuple[int, int, int]`): The background color to use for the padding. do_pad (`bool`, *optional*, defaults to `self.do_pad`): Whether to pad the image to square or not. return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return. Can be one of: - Unset: Return a list of `np.ndarray`. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - Unset: Use the channel dimension format of the input image. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. """ do_resize = do_resize if do_resize is not None else self.do_resize resample = resample if resample is not None else self.resample do_rescale = do_rescale if do_rescale is not None else self.do_rescale rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor do_normalize = do_normalize if do_normalize is not None else self.do_normalize image_mean = image_mean if image_mean is not None else self.image_mean image_std = image_std if image_std is not None else self.image_std do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb do_pad = do_pad if do_pad is not None else self.do_pad background_color = background_color if background_color is not None else self.background_color size = size if size is not None else self.size size = get_size_dict(size, default_to_square=False) images = self.fetch_images(images) images = make_flat_list_of_images(images) if not valid_images(images): raise ValueError("Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor") validate_preprocess_arguments( do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_resize=do_resize, size=size, resample=resample, ) # PIL RGBA images are converted to RGB if do_convert_rgb: images = [convert_to_rgb(image) for image in images] # All transformations expect numpy arrays. images = [to_numpy_array(image) for image in images] if do_rescale and is_scaled_image(images[0]): logger.warning_once( "It looks like you are trying to rescale already rescaled images. If the input" " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again." ) if input_data_format is None: # We assume that all images have the same channel dimension format. input_data_format = infer_channel_dimension_format(images[0]) if do_resize: images = [ self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format) for image in images ] if do_pad: # Expand and pad the images to obtain a square image of dimensions `size x size` images = [ self.pad_to_square( image=image, background_color=background_color, input_data_format=input_data_format, ) for image in images ] if do_rescale: images = [ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format) for image in images ] if do_normalize: images = [ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format) for image in images ] images = [ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images ] encoded_outputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors) return encoded_outputs def pad_to_square( self, image: np.ndarray, background_color: Union[int, tuple[int, int, int]] = 0, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Pads an image to a square based on the longest edge. Args: image (`np.ndarray`): The image to pad. background_color (`int` or `tuple[int, int, int]`, *optional*, defaults to 0): The color to use for the padding. Can be an integer for single channel or a tuple of integers representing for multi-channel images. If passed as integer in multi-channel mode, it will default to `0` in subsequent channels. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use same as the input image. input_data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. Returns: `np.ndarray`: The padded image. """ height, width = get_image_size(image, input_data_format) num_channels = image.shape[0] if input_data_format == ChannelDimension.FIRST else image.shape[-1] if height == width: image = ( to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image ) return image max_dim = max(height, width) # Ensure background_color is the correct shape if isinstance(background_color, int): background_color = [background_color] elif len(background_color) != num_channels: raise ValueError( f"background_color must have no more than {num_channels} elements to match the number of channels" ) if input_data_format == ChannelDimension.FIRST: result = np.zeros((num_channels, max_dim, max_dim), dtype=image.dtype) for i, color in enumerate(background_color): result[i, :, :] = color if width > height: start = (max_dim - height) // 2 result[:, start : start + height, :] = image else: start = (max_dim - width) // 2 result[:, :, start : start + width] = image else: result = np.zeros((max_dim, max_dim, num_channels), dtype=image.dtype) for i, color in enumerate(background_color): result[:, :, i] = color if width > height: start = (max_dim - height) // 2 result[start : start + height, :, :] = image else: start = (max_dim - width) // 2 result[:, start : start + width, :] = image return result __all__ = ["DeepseekVLImageProcessor"]
DeepseekVLImageProcessor
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 73170, "end": 74198 }
class ____(test.TestCase): # Checks that executing the same rng_func multiple times rarely produces the # same result. def _testSingleSessionNotConstant( self, rng_func, num, dtype, min_or_mean, max_or_stddev, use_gpu, op_seed=None, graph_seed=None, ): with self.session(use_gpu=use_gpu, graph=ops.Graph()) as _: if graph_seed is not None: random_seed.set_random_seed(graph_seed) x = rng_func([num], min_or_mean, max_or_stddev, dtype=dtype, seed=op_seed) y = self.evaluate(x) z = self.evaluate(x) w = self.evaluate(x) # We use exact equality here. If the random-number generator is producing # the same output, all three outputs will be bitwise identical. self.assertTrue( (not np.array_equal(y, z)) or (not np.array_equal(z, w)) or (not np.array_equal(y, w)) ) @test_util.for_all_test_methods( test_util.disable_xla, "This never passed on XLA" )
RandomOpTestCommon
python
lepture__mistune
src/mistune/directives/toc.py
{ "start": 646, "end": 3916 }
class ____(DirectivePlugin): def __init__(self, min_level: int = 1, max_level: int = 3) -> None: self.min_level = min_level self.max_level = max_level def generate_heading_id(self, token: Dict[str, Any], index: int) -> str: return "toc_" + str(index + 1) def parse(self, block: "BlockParser", m: Match[str], state: "BlockState") -> Dict[str, Any]: title = self.parse_title(m) options = self.parse_options(m) if options: d_options = dict(options) collapse = "collapse" in d_options min_level = _normalize_level(d_options, "min-level", self.min_level) max_level = _normalize_level(d_options, "max-level", self.max_level) if min_level < self.min_level: raise ValueError(f'"min-level" option MUST be >= {self.min_level}') if max_level > self.max_level: raise ValueError(f'"max-level" option MUST be <= {self.max_level}') if min_level > max_level: raise ValueError('"min-level" option MUST be less than "max-level" option') else: collapse = False min_level = self.min_level max_level = self.max_level attrs = { "min_level": min_level, "max_level": max_level, "collapse": collapse, } return {"type": "toc", "text": title or "", "attrs": attrs} def toc_hook(self, md: "Markdown", state: "BlockState") -> None: sections = [] headings = [] for tok in state.tokens: if tok["type"] == "toc": sections.append(tok) elif tok["type"] == "heading": headings.append(tok) if sections: toc_items = [] # adding ID for each heading for i, tok in enumerate(headings): tok["attrs"]["id"] = self.generate_heading_id(tok, i) toc_items.append(normalize_toc_item(md, tok)) for sec in sections: _min = sec["attrs"]["min_level"] _max = sec["attrs"]["max_level"] toc = [item for item in toc_items if _min <= item[0] <= _max] sec["attrs"]["toc"] = toc def __call__(self, directive: BaseDirective, md: "Markdown") -> None: if md.renderer and md.renderer.NAME == "html": # only works with HTML renderer directive.register("toc", self.parse) md.before_render_hooks.append(self.toc_hook) md.renderer.register("toc", render_html_toc) def render_html_toc(renderer: "BaseRenderer", title: str, collapse: bool = False, **attrs: Any) -> str: if not title: title = "Table of Contents" content = render_toc_ul(attrs["toc"]) html = '<details class="toc"' if not collapse: html += " open" html += ">\n<summary>" + title + "</summary>\n" return html + content + "</details>\n" def _normalize_level(options: Dict[str, Any], name: str, default: Any) -> Any: level = options.get(name) if not level: return default try: return int(level) except (ValueError, TypeError): raise ValueError(f'"{name}" option MUST be integer')
TableOfContents
python
astropy__astropy
astropy/io/fits/hdu/base.py
{ "start": 27274, "end": 28436 }
class ____(_BaseHDU): """ A Corrupted HDU class. This class is used when one or more mandatory `Card`s are corrupted (unparsable), such as the ``BITPIX``, ``NAXIS``, or ``END`` cards. A corrupted HDU usually means that the data size cannot be calculated or the ``END`` card is not found. In the case of a missing ``END`` card, the `Header` may also contain the binary data .. note:: In future, it may be possible to decipher where the last block of the `Header` ends, but this task may be difficult when the extension is a `TableHDU` containing ASCII data. """ @property def size(self): """ Returns the size (in bytes) of the HDU's data part. """ # Note: On compressed files this might report a negative size; but the # file is corrupt anyways so I'm not too worried about it. if self._buffer is not None: return len(self._buffer) - self._data_offset return self._file.size - self._data_offset def _summary(self): return (self.name, self.ver, "CorruptedHDU") def verify(self): pass
_CorruptedHDU
python
gevent__gevent
examples/webpy.py
{ "start": 450, "end": 1182 }
class ____(object): # Since gevent's WSGIServer executes each incoming connection in a separate greenlet # long running requests such as this one don't block one another; # and thanks to "monkey.patch_all()" statement at the top, thread-local storage used by web.ctx # becomes greenlet-local storage thus making requests isolated as they should be. def GET(self): print('GET /long') time.sleep(10) # possible to block the request indefinitely, without harming others return 'Hello, 10 seconds later' if __name__ == "__main__": application = web.application(urls, globals()).wsgifunc() print('Serving on 8088...') WSGIServer(('', 8088), application).serve_forever()
long_polling
python
pandas-dev__pandas
asv_bench/benchmarks/tslibs/period.py
{ "start": 1999, "end": 2593 }
class ____: params = [["D"], [True, False]] param_names = ["freq", "is_offset"] def setup(self, freq, is_offset): if is_offset: self.freq = to_offset(freq) else: self.freq = freq def time_period_constructor(self, freq, is_offset): Period("2012-06-01", freq=freq) _freq_ints = [ 1000, 1011, # Annual - November End 2000, 2011, # Quarterly - November End 3000, 4000, 4006, # Weekly - Saturday End 5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000, ]
PeriodConstructor
python
sympy__sympy
sympy/physics/optics/gaussopt.py
{ "start": 5126, "end": 5768 }
class ____(RayTransferMatrix): """ Ray Transfer Matrix for refraction. Parameters ========== n1 : Refractive index of one medium. n2 : Refractive index of other medium. See Also ======== RayTransferMatrix Examples ======== >>> from sympy.physics.optics import FlatRefraction >>> from sympy import symbols >>> n1, n2 = symbols('n1 n2') >>> FlatRefraction(n1, n2) Matrix([ [1, 0], [0, n1/n2]]) """ def __new__(cls, n1, n2): n1, n2 = map(sympify, (n1, n2)) return RayTransferMatrix.__new__(cls, 1, 0, 0, n1/n2)
FlatRefraction
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 340850, "end": 341498 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("ExternalIdentityEdge"), graphql_name="edges" ) nodes = sgqlc.types.Field( sgqlc.types.list_of("ExternalIdentity"), graphql_name="nodes" ) page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
ExternalIdentityConnection
python
pytorch__pytorch
torch/_inductor/codegen/common.py
{ "start": 4247, "end": 4556 }
class ____(ABC): """ An IR object possibly corresponding to a variable in the wrapper code. """ @abstractmethod def get_name(self) -> str: pass @abstractmethod def get_example(self) -> Union[torch.Tensor, sympy.Symbol]: pass @ir_dataclass(frozen=True)
CodegenSymbol
python
mahmoud__boltons
boltons/urlutils.py
{ "start": 55909, "end": 57489 }
class ____(OrderedMultiDict): """A subclass of :class:`~dictutils.OrderedMultiDict` specialized for representing query string values. Everything is fully unquoted on load and all parsed keys and values are strings by default. As the name suggests, multiple values are supported and insertion order is preserved. >>> qp = QueryParamDict.from_text(u'key=val1&key=val2&utm_source=rtd') >>> qp.getlist('key') [u'val1', u'val2'] >>> qp['key'] u'val2' >>> qp.add('key', 'val3') >>> qp.to_text() 'key=val1&key=val2&utm_source=rtd&key=val3' See :class:`~dictutils.OrderedMultiDict` for more API features. """ @classmethod def from_text(cls, query_string): """ Parse *query_string* and return a new :class:`QueryParamDict`. """ pairs = parse_qsl(query_string, keep_blank_values=True) return cls(pairs) def to_text(self, full_quote=False): """ Render and return a query string. Args: full_quote (bool): Whether or not to percent-quote special characters or leave them decoded for readability. """ ret_list = [] for k, v in self.iteritems(multi=True): key = quote_query_part(to_unicode(k), full_quote=full_quote) if v is None: ret_list.append(key) else: val = quote_query_part(to_unicode(v), full_quote=full_quote) ret_list.append('='.join((key, val))) return '&'.join(ret_list) # end urlutils.py
QueryParamDict
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image03.py
{ "start": 315, "end": 841 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image03.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_image("E9", self.image_dir + "red.jpg") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/filter_test.py
{ "start": 9264, "end": 10285 }
class ____( test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.default_test_combinations()) def testShuffleFilter(self): dataset = dataset_ops.Dataset.range(100) dataset = global_shuffle_op._global_shuffle(dataset) dataset = dataset.filter(lambda x: math_ops.equal(x % 2, 0)) self.assertDatasetProduces( dataset, list(range(0, 100, 2)), requires_initialization=True, assert_items_equal=True) @combinations.generate(test_base.default_test_combinations()) def testFilterShuffle(self): dataset = dataset_ops.Dataset.range(100) dataset = dataset.filter(lambda x: math_ops.equal(x % 2, 0)) with self.assertRaisesRegex( errors.FailedPreconditionError, "`global_shuffle` requires all upstream transformations be compatible " "with random access."): dataset = global_shuffle_op._global_shuffle(dataset) self.getDatasetOutput(dataset, requires_initialization=True)
FilterGlobalShuffleTest
python
pytorch__pytorch
torch/_inductor/index_propagation.py
{ "start": 6386, "end": 13345 }
class ____(DefaultHandler): """Ops wrapper that tries to propagate constant and index_expr values through the computation. This aims to maximize the compile time simplification possible, and convert indirect indexing from arange into normal static indexing. """ def __init__( self, inner: Any, iter_ranges: dict[sympy.Symbol, sympy.Expr], indirect_var_ranges: dict[sympy.Symbol, sympy.Expr], ) -> None: self._inner = inner self.shape_env = V.graph.sizevars.shape_env var_to_range = { k: ValueRanges(0, upper_bound(v) - 1) for k, v in iter_ranges.items() } self.var_to_range = tuple( itertools.chain(self.shape_env.var_to_range.items(), var_to_range.items()) ) # NOTE: this is intentionally kept as a reference so the caller can # update it in-place self.indirect_var_ranges = indirect_var_ranges axioms = [] for x, s in iter_ranges.items(): axioms.append(0 <= x) axioms.append(x < s) self.axioms = tuple(axioms) + self.shape_env.get_axioms() def materialize_expr(self, expr: sympy.Expr, dtype: torch.dtype) -> Any: # Construct a new constant/index_expr from the SymPy expression if _is_constant(expr): val = dtype_to_type(dtype)(expr) return self._inner.constant(val, dtype) return self._inner.index_expr(expr, dtype) def unwrap(self, a: Union[Any, IndexPropVar]) -> Any: if isinstance(a, (list, tuple)): return tuple(self.unwrap(v) for v in a) if not isinstance(a, IndexPropVar): return a # Prefer the sympy representation if possible if a.is_symbolic: return self.materialize_expr(a.value.expr, a.value.dtype) return a.value def wrap(self, a) -> IndexPropResult: if isinstance(a, (list, tuple)): return tuple(self.wrap(v) for v in a) return IndexPropVar(a) @overload def fallback( self, name: Literal["indirect_indexing"], args: Sequence[Any], kwargs: dict[str, Any], ) -> IndexPropVar: ... @overload def fallback( self, name: str, args: Sequence[Any], kwargs: dict[str, Any] ) -> IndexPropResult: ... def fallback( self, name: str, args: Sequence[Any], kwargs: dict[str, Any] ) -> IndexPropResult: # Fallback to the wrapped handler new_args = [self.unwrap(a) for a in args] new_kwargs = {k: self.unwrap(v) for k, v in kwargs.items()} return self.wrap(getattr(self._inner, name)(*new_args, **new_kwargs)) def propagate_sympy( self, name: str, args: Sequence[Any], kwargs: dict[str, Any] ) -> IndexPropResult: # Build a new SymPy expression from this ops call def unwrap(a: Union[Any, IndexPropVar]) -> Any: if not isinstance(a, IndexPropVar): return a return a.value new_args = [unwrap(a) for a in args] new_kwargs = {k: unwrap(v) for k, v in kwargs.items()} new_expr = getattr(SymPyOps, name)(*new_args, **new_kwargs) is_valid_expr = new_expr is not NotImplemented and ( # Inductor doesn't expect floating point in sympy expressions, but # allow floating point constants to be propagated new_expr.is_constant() or new_expr.expr.is_integer ) if not is_valid_expr: return self.fallback(name, args, kwargs) return IndexPropVar.new_symbolic(new_expr) def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: if not hasattr(SymPyOps, name): return self.fallback(name, args, kwargs) var_arguments = [ a for a in itertools.chain(args, kwargs.values()) if isinstance(a, IndexPropVar) ] if not all(v.is_symbolic for v in var_arguments): return self.fallback(name, args, kwargs) return self.propagate_sympy(name, args, kwargs) def statically_true(self, e): """ Given some iter_ranges, return a function that given an expression, returns whether it is true or false using value ranges, guard knowledge and runtime_asserts. FIXME I think this may not be entirely right, as we may not be able to use all runtime_asserts If this is an issue, just use guards in `self.axioms`. The proper way of handling this would be to have a global shape_env that adds runtime_asserts as they happen in the code. Then, it should be used in SimplifyIndexing to perform wrap_expr and in CSEProxy.check_bounds to elide upper / lower bounds also for indirect_indexing """ var_to_range = ( *self.var_to_range, *( (k, ValueRanges(0, upper_bound(v) - 1)) for k, v in self.indirect_var_ranges.items() ), ) # pyrefly: ignore [bad-argument-type] return statically_known_true(self.shape_env, e, self.axioms, var_to_range) def indirect_indexing( self, index: Union[Any, IndexPropVar], size: Any, check: bool = True, wrap_neg=True, ) -> Any: if isinstance(index, IndexPropVar) and index.is_symbolic: # If we find something we can convert into a direct indexing we do so # We still need to (perhaps) wrap the expression and add bound checks # We want to do this "constant folding", as we don't allow to fuse # kernels into indirect indexing expr = sympy.sympify(index.value.expr) # TODO Perhaps move this logic to the simplify indexing pass def wrap_expr(expr): # Positive, negative, mixed if self.statically_true(0 <= expr): return expr elif self.statically_true(expr < 0): return expr + size else: return Where(expr < 0, expr + size, expr) # Sometimes it's easier to prove 0 <= expr than the weaker -size <= expr can_prove_lower = self.statically_true(0 <= expr) or self.statically_true( -size <= expr ) can_prove_upper = self.statically_true(expr < size) if wrap_neg: expr = wrap_expr(expr) if generate_assert(check): self.fallback( "check_bounds", (expr, size), dict(lower=not can_prove_lower, upper=not can_prove_upper), ) return expr indirect_var = self.fallback( "indirect_indexing", (index, size, check, wrap_neg), {} ).value return indirect_var
IndexPropagation
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/quantization_test.py
{ "start": 9530, "end": 12038 }
class ____(op_bench.TorchBenchmarkBase): r"""Benchmarks 3 different fake quantize per channel operators.""" def init(self, N, C, H, W, zero_point_dtype, nbits, device, op_func): self.quant_min = 0 self.quant_max = 2**nbits - 1 self.quant_range = 2**nbits # Axis is chosen with respect to the number of channels: C. self.axis = 1 self.input = nn.Parameter( torch.rand( N, C, H, W, dtype=torch.float, device=device, requires_grad=self.auto_set(), ) ) if op_func.__name__ == "fakeQuantizePerChannelOriginalKernel": self.scale = torch.ones( C, device=device, dtype=torch.float32, requires_grad=False ) self.zero_point = torch.zeros( C, device=device, dtype=zero_point_dtype, requires_grad=False ) else: self.scale = nn.Parameter( torch.ones(C, device=device, dtype=torch.float32), requires_grad=self.auto_set(), ) self.zero_point = nn.Parameter( torch.zeros(C, device=device, dtype=torch.float32), requires_grad=self.auto_set(), ) self.inputs = { "input": self.input, "scale": self.scale, "zero_point": self.zero_point, "axis": self.axis, "quant_min": self.quant_min, "quant_max": self.quant_max, } self.op_func = op_func def forward( self, input, scale, zero_point, axis: int, quant_min: int, quant_max: int ): return self.op_func(input, scale, zero_point, axis, quant_min, quant_max) op_bench.generate_pt_tests_from_op_list( fake_quantize_per_channel_ops, fake_quantize_operator_configs_short + fake_quantize_operator_configs_long, FakeQuantizePerChannelOpBenchmark, ) op_bench.generate_pt_tests_from_op_list( fake_quantize_per_channel_float_zero_point_ops, fake_quantize_operator_configs_long_float_zero_point, FakeQuantizePerChannelOpBenchmark, ) op_bench.generate_pt_gradient_tests_from_op_list( fake_quantize_per_channel_ops, fake_quantize_operator_configs_short + fake_quantize_operator_configs_long, FakeQuantizePerChannelOpBenchmark, ) if __name__ == "__main__": op_bench.benchmark_runner.main()
FakeQuantizePerChannelOpBenchmark
python
pytorch__pytorch
torch/testing/_internal/common_distributed.py
{ "start": 58522, "end": 59359 }
class ____(DistributedTestBase): """ Use this for tests that actually run on multiple GPUs. Decorate tests with @skip_if_lt_x_gpu(ngpu) Note: MultiProcTestCase spawns processes per test and is slow. Prefer MultiThreadedTestCase for most tests. Perhaps use this one sparingly for integration tests. """ @property def world_size(self) -> int: return torch.accelerator.device_count() @classmethod def _run( cls, rank: int, test_name: str, file_name: str, parent_pipe, **kwargs ) -> None: trace_log.addHandler(logging.NullHandler()) # The rest is copypasta from MultiProcessTestCase._run self = cls(test_name) self.rank = rank self.file_name = file_name self.run_test(test_name, parent_pipe)
DynamoDistributedMultiProcTestCase
python
django__django
django/db/models/fields/related_lookups.py
{ "start": 5740, "end": 5804 }
class ____(RelatedLookupMixin, LessThan): pass
RelatedLessThan
python
pytorch__pytorch
test/test_cuda.py
{ "start": 159240, "end": 195708 }
class ____(TestCase): @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) def test_memory_snapshot(self): try: torch.cuda.memory.empty_cache() torch.cuda.memory._record_memory_history("state", stacks="python") # make x the second block in a segment torch.rand(2 * 311, 411, device="cuda") unused = torch.rand(310, 410, device="cuda") x = torch.rand(311, 411, device="cuda") # create a bunch of tensors that all will tile into the # same segment to exercise the history merging code # 512B is the minimum block size, # so we allocate all the tensors to this size to make sure # they tile evenly tensors = [torch.rand(128, device="cuda") for _ in range(1000)] while tensors: del tensors[randint(0, len(tensors) - 1)] # exercise the history trimming code torch.rand(128 * 5, device="cuda") ss = torch.cuda.memory._snapshot() found_it = False for seg in ss["segments"]: self.assertTrue("frames" in seg) for b in seg["blocks"]: if b["requested_size"] == 311 * 411 * 4: self.assertTrue("test_cuda" in b["frames"][0]["filename"]) found_it = True self.assertEqual(x.untyped_storage().data_ptr(), b["address"]) self.assertTrue(found_it) if not IS_WINDOWS: with tempfile.NamedTemporaryFile() as f: torch.cuda.memory._save_segment_usage(f.name) with open(f.name) as f2: self.assertTrue("test_cuda.py" in f2.read()) del unused del x torch.cuda.empty_cache() ss = torch.cuda.memory._snapshot() self.assertTrue( ss["device_traces"][0][-1]["action"] in ("segment_free", "segment_unmap") ) finally: torch.cuda.memory._record_memory_history(None) @unittest.skipUnless(IS_X86 and IS_LINUX, "x86 linux only cpp unwinding") def test_direct_traceback(self): from torch._C._profiler import gather_traceback, symbolize_tracebacks # @manual c = gather_traceback(True, True, True) (r,) = symbolize_tracebacks([c]) r = str(r) self.assertTrue("test_cuda.py" in r) self.assertTrue("unwind" in r) @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) @requiresCppContext def test_memory_snapshot_with_cpp(self): try: torch.cuda.memory.empty_cache() torch.cuda.memory._record_memory_history("state", stacks="all") x = torch.rand(311, 411, device="cuda") # noqa: F841 ss = torch.cuda.memory._snapshot()["segments"] found_it = False for seg in ss: for b in seg["blocks"]: if b["requested_size"] == 311 * 411 * 4: self.assertTrue("::rand" in str(b["frames"])) found_it = True self.assertTrue(found_it) finally: torch.cuda.memory._record_memory_history(None) @skipIfRocm def test_memory_profiler_viz(self): with torch.profiler.profile( with_stack=True, profile_memory=True, record_shapes=True ) as prof: x = torch.rand(128, 128, device="cuda") x * x + x * x plot = profile_plot(prof) plot = json.dumps(_profile_to_snapshot(prof)) self.assertTrue("test_cuda.py" in plot) self.assertTrue("test_memory_profiler_viz" in plot) self.assertTrue("category" in plot) @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) @requiresCppContext def test_cycles(self): fired = False def observer(html): nonlocal fired fired = True self.assertTrue("torch.Tensor" in html) self.assertTrue("test_cuda" in html) self.assertTrue("cell_contents" in html) disarm = observe_tensor_cycles(observer) def noop(): pass try: def create(): x = torch.empty(3, 4, device="cuda") def foo(p): if p: return foo(not p) else: return x return foo create() gc.collect() # the callback has to run outside of the collect # call so it doesn't actual fire until the next # method call after a gc.collect noop() self.assertTrue(fired) finally: disarm() @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) @requiresCppContext def test_memory_plots(self): for context, stacks in ( ("all", "all" if IS_LINUX else "python"), ("all", "python"), (None, "python"), ): try: torch.cuda.memory.empty_cache() torch.cuda.memory._record_memory_history( "all", context=context, stacks=stacks ) def run(): x = torch.rand(128, 128, device="cuda") x * x + x * x run() cpp = stacks == "all" record_context = context is not None ss = torch.cuda.memory._snapshot() trace_plot(ss) trace_plot(ss, filter_freed=True) segment_plot(ss) text = json.dumps(ss) self.assertTrue(record_context == ("test_memory_plots" in text)) self.assertTrue(cpp == ("::rand" in text)) self.assertTrue(str(128 * 128 * 4) in text) finally: torch.cuda.memory._record_memory_history(None) @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) @requiresCppContext def test_memory_plots_free_stack(self): for context in ["alloc", "all", "state"]: try: torch.cuda.memory.empty_cache() torch.cuda.memory._record_memory_history(context=context) x = None def thealloc(): nonlocal x x = torch.rand(3, 4, device="cuda") def thefree(): nonlocal x del x thealloc() thefree() ss = json.dumps(torch.cuda.memory._snapshot()) self.assertEqual(("thefree" in ss), (context == "all")) self.assertEqual(("thealloc" in ss), (context != "state")) finally: torch.cuda.memory._record_memory_history(None) @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) @unittest.skipIf(not has_triton(), "test needs triton") @requiresCppContext @serialTest() def test_memory_compile_regions(self): expected_allocation_sequence = [ "Torch-Compiled Region: 0/0", "Torch-Compiled Region: 1/0", "Torch-Compiled Region: 0/0", ] class MyModel(nn.Module): def __init__(self): super().__init__() self.linear1 = nn.Linear(10, 10) self.linear2 = nn.Linear(10, 10) def forward(self, x): x = self.linear1(x) if x.sum() > 0: x = x + 1 else: x = x - 1 x = self.linear2(x) return x try: torch.cuda.memory.empty_cache() input_tensor = torch.randn(1, 10, device="cuda") # Create an instance of the model model = MyModel() model.to("cuda") # Compile the model using torch.compile compiled_model = torch.compile(model) # Create a sample input tensor torch.cuda.memory._record_memory_history( context="all", compile_context=True ) compiled_model(input_tensor) ss = torch.cuda.memory._snapshot()["device_traces"] device_idx = 0 allocation_sequence = [] while len(ss[device_idx]) == 0: device_idx = device_idx + 1 for s in ss[device_idx]: context = s["compile_context"] if context == "N/A": continue if len(allocation_sequence) > 0 and allocation_sequence[-1] == context: continue allocation_sequence.append(context) self.assertTrue(allocation_sequence == expected_allocation_sequence) except RuntimeError as e: pass finally: torch.cuda.memory._record_memory_history(None) @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) @requiresCppContext def test_memory_plots_history_context(self): try: torch.cuda.memory.empty_cache() x = None def should_capture1(): nonlocal x x = torch.rand(4, 4, device="cuda") def should_not_capture(): nonlocal x x = torch.rand(3, 4, device="cuda") def should_capture2(): nonlocal x x = torch.rand(4, 4, device="cuda") # Recording with context and python call stacks should capture the call stack. torch.cuda.memory._record_memory_history(context="all", stacks="python") should_capture1() # Recording with context=None should not capture the call stack. torch.cuda.memory._record_memory_history(context=None) should_not_capture() # Recording with context and python call stacks should capture the call stack. torch.cuda.memory._record_memory_history(context="all", stacks="python") should_capture2() ss = json.dumps(torch.cuda.memory._snapshot()) self.assertTrue("should_capture1" in ss) self.assertTrue("should_not_capture" not in ss) self.assertTrue("should_capture2" in ss) finally: torch.cuda.memory._record_memory_history(None) @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) @requiresCppContext def test_memory_plots_free_segment_stack(self): for context in ["alloc", "all", "state"]: try: torch._C._cuda_clearCublasWorkspaces() torch.cuda.memory.empty_cache() torch.cuda.memory._record_memory_history(context=context) x = torch.rand(3, 4, device="cuda") del x torch.cuda.memory.empty_cache() ss = json.dumps(torch.cuda.memory._snapshot()) self.assertEqual(("empty_cache" in ss), (context == "all")) finally: torch.cuda.memory._record_memory_history(None) @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) @requiresCppContext def test_memory_plots_metadata(self): for context in ["alloc", "all", "state"]: try: torch._C._cuda_clearCublasWorkspaces() torch.cuda.memory.empty_cache() torch.cuda.memory._set_memory_metadata("metadata test") torch.cuda.memory._record_memory_history(context=context) x = torch.rand(3, 4, device="cuda") del x torch.cuda.memory.empty_cache() torch.cuda.memory._set_memory_metadata("") ss = torch.cuda.memory._snapshot() for event in ss["device_traces"][0]: self.assertTrue(event["user_metadata"] == "metadata test") finally: torch.cuda.memory._record_memory_history(None) @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) def test_memory_snapshot_script(self): try: torch._C._cuda_clearCublasWorkspaces() torch.cuda.memory.empty_cache() torch.cuda.memory._record_memory_history("state", stacks="python") @torch.jit.script def foo(): return torch.rand(311, 411, device="cuda") x = foo() # noqa: F841 ss = torch.cuda.memory._snapshot()["segments"] found_it = False for seg in ss: for b in seg["blocks"]: if b["requested_size"] == 311 * 411 * 4: self.assertEqual(b["frames"][0]["name"], "foo") found_it = True self.assertTrue(found_it) finally: torch.cuda.memory._record_memory_history(None) @serialTest() def test_max_split_expandable(self): try: orig = torch.cuda.get_per_process_memory_fraction() torch.cuda.memory.empty_cache() mb = 1024 * 1024 _, all_memory = torch.cuda.memory.mem_get_info() pre_reserved = torch.cuda.memory_reserved() total_allowed = 120 * mb + pre_reserved fraction_allowed = total_allowed / all_memory self.assertEqual(int(round(fraction_allowed * all_memory)), total_allowed) torch.cuda.memory.set_per_process_memory_fraction(fraction_allowed) def alloc(n): return torch.ones(n * mb, dtype=torch.int8, device="cuda") torch.cuda.memory._set_allocator_settings( "expandable_segments:False,max_split_size_mb:40" ) a = alloc(40) torch.cuda.memory._set_allocator_settings( "expandable_segments:True,max_split_size_mb:40" ) b = alloc(40) torch.cuda.memory._set_allocator_settings( "expandable_segments:False,max_split_size_mb:40" ) c = alloc(40) with self.assertRaises(torch.OutOfMemoryError): alloc(40) del a, b, c # force release_cached_blocks to run with some expandable segments in the free list alloc(120) finally: torch.cuda.memory.set_per_process_memory_fraction(orig) @serialTest() def test_garbage_collect_expandable(self): try: orig = torch.cuda.get_per_process_memory_fraction(0) torch.cuda.memory.empty_cache() mb = 1024 * 1024 _, all_memory = torch.cuda.memory.mem_get_info() pre_reserved = torch.cuda.memory_reserved() total_allowed = 120 * mb + pre_reserved fraction_allowed = total_allowed / all_memory self.assertEqual((fraction_allowed * all_memory), total_allowed) torch.cuda.memory.set_per_process_memory_fraction(fraction_allowed) def alloc(n): return torch.ones(n * mb, dtype=torch.int8, device="cuda") torch.cuda.memory._set_allocator_settings( "expandable_segments:False,garbage_collection_threshold:0.5" ) a = alloc(40) torch.cuda.memory._set_allocator_settings( "expandable_segments:True,garbage_collection_threshold:0.5" ) b = alloc(40) del a, b # causes GC to run. The expandable segment block will be split # so GC would not attempt to free it anyway, but this at least makes sure # expandable_segment blocks can be in the free list when this is called. alloc(80) finally: torch.cuda.memory.set_per_process_memory_fraction(orig) def test_allocator_settings(self): def power2_div(size, div_factor): pow2 = 1 while pow2 < size: pow2 = pow2 * 2 if pow2 == size: return pow2 step = pow2 / 2 / div_factor ret = pow2 / 2 while ret < size: ret = ret + step return ret torch.cuda.memory.empty_cache() key_allocated = ( "active_bytes.all.allocated" if not TEST_CUDAMALLOCASYNC else "allocated_bytes.all.current" ) key_requested = "requested_bytes.all.allocated" nelems = 21 * 1024 * 1024 nbytes = 4 * nelems # floats are 4 bytes nelems_big = 100 * 1024 * 1024 nbytes_big = 4 * nelems_big # floats are 4 bytes start_mem = torch.cuda.memory_stats()[key_allocated] torch.cuda.memory._set_allocator_settings("") x = torch.rand(nelems, device="cuda") # test roundup_power2_divisions single value syntax reg_mem = torch.cuda.memory_stats()[key_allocated] start_requested = torch.cuda.memory_stats()[key_requested] torch.cuda.memory._set_allocator_settings("roundup_power2_divisions:4") y = torch.rand(nelems, device="cuda") pow2_div4_mem = torch.cuda.memory_stats()[key_allocated] current_requested = torch.cuda.memory_stats()[key_requested] self.assertEqual(reg_mem - start_mem, nbytes) if not TEST_CUDAMALLOCASYNC: # not supported with the cudaMallocAsync backend self.assertEqual(pow2_div4_mem - reg_mem, power2_div(nbytes, 4)) self.assertEqual(current_requested - start_requested, nbytes) torch.cuda.memory._set_allocator_settings("garbage_collection_threshold:0.5") torch.cuda.memory._set_allocator_settings( "garbage_collection_threshold:0.5,max_split_size_mb:40" ) # should have reset the power2 divisions now torch.cuda.memory.empty_cache() start_mem = torch.cuda.memory_stats()[key_allocated] z = torch.rand(nelems, device="cuda") reg_mem = torch.cuda.memory_stats()[key_allocated] self.assertEqual(reg_mem - start_mem, nbytes) # roundup_power2_divisions knob array syntax torch.cuda.memory.empty_cache() torch.cuda.memory._set_allocator_settings( "garbage_collection_threshold:0.5,roundup_power2_divisions:[64:8,128:2,256:2,512:2,1024:1,>:1]" ) start_mem = torch.cuda.memory_stats()[key_allocated] w = torch.rand(nelems, device="cuda") pow2_div8_mem = torch.cuda.memory_stats()[key_allocated] if not TEST_CUDAMALLOCASYNC: # not supported with the cudaMallocAsync backend self.assertEqual(pow2_div8_mem - start_mem, power2_div(nbytes, 8)) torch.cuda.memory.empty_cache() start_mem = torch.cuda.memory_stats()[key_allocated] v = torch.rand(nelems_big, device="cuda") pow2_div2_mem = torch.cuda.memory_stats()[key_allocated] if not TEST_CUDAMALLOCASYNC: # not supported with the cudaMallocAsync backend self.assertEqual(pow2_div2_mem - start_mem, power2_div(nbytes_big, 2)) torch.cuda.memory.empty_cache() torch.cuda.memory._set_allocator_settings("release_lock_on_cudamalloc:True") start_mem = torch.cuda.memory_stats()[key_allocated] w = torch.rand(nelems, device="cuda") reg_mem = torch.cuda.memory_stats()[key_allocated] self.assertEqual(reg_mem - start_mem, nbytes) with self.assertRaises(ValueError): torch._C._accelerator_setAllocatorSettings("foo:1,bar:2") with self.assertRaises(ValueError): torch._C._accelerator_setAllocatorSettings( "garbage_collection_threshold:1.2" ) with self.assertRaises(ValueError): torch._C._accelerator_setAllocatorSettings("max_split_size_mb:2") with self.assertRaises(ValueError): torch._C._accelerator_setAllocatorSettings( "release_lock_on_cudamalloc:none" ) with self.assertRaises(ValueError): torch._C._accelerator_setAllocatorSettings( "pinned_use_cuda_host_register:none" ) with self.assertRaises(ValueError): torch._C._accelerator_setAllocatorSettings( "pinned_num_register_threads:none" ) with self.assertRaises(ValueError): torch._C._accelerator_setAllocatorSettings( "pinned_num_register_threads:1024" ) def test_allocator_backend(self): def check_output(script: str) -> str: return ( subprocess.check_output([sys.executable, "-c", script]) .decode("ascii") .strip() ) test_script = """\ import os os.environ["PYTORCH_ALLOC_CONF"] = "max_split_size_mb:20,backend:cudaMallocAsync,release_lock_on_cudamalloc:none" import torch torch.cuda.init() print(torch.cuda.get_allocator_backend()) """ rc = check_output(test_script) self.assertEqual(rc, "cudaMallocAsync") def test_allocator_memory_fraction_setting(self): def make_env(fraction): env = os.environ.copy() var = "PYTORCH_CUDA_ALLOC_CONF" key = "per_process_memory_fraction" value = [ x for x in env.get(var, "").split(",") if len(x) > 0 and not x.startswith(f"{key}:") ] value.append(f"{key}:{fraction}") env[var] = ",".join(value) return env def run_test(value): test_script = """\ import os import torch device = torch._C._cuda_getDevice() value = torch.cuda.memory.get_per_process_memory_fraction(device) print(value, end="") """ return subprocess.run( [sys.executable, "-c", test_script], env=make_env(value), text=True, check=True, capture_output=True, ) self.assertEqual(run_test(0.0).stdout, "0.0") self.assertEqual(run_test(0.5).stdout, "0.5") self.assertEqual(run_test(1.0).stdout, "1.0") with self.assertRaises(subprocess.CalledProcessError) as e: run_test(-0.1) assert "per_process_memory_fraction is invalid" in e.exception.stderr, ( e.exception.stderr ) with self.assertRaises(subprocess.CalledProcessError) as e: run_test(1.1) assert "per_process_memory_fraction is invalid" in e.exception.stderr, ( e.exception.stderr ) def test_cachingAllocator_raw_alloc(self): # Test that raw_alloc respects the setting that # activates/deactivates the caching allocator # Helper function that calls raw_alloc and returns # relevant field in data structure def requested_bytes_alloc_stats(raw_alloc_size, stream): start = torch.cuda.memory_stats()["requested_bytes.all.allocated"] mem_ptr = torch._C._cuda_cudaCachingAllocator_raw_alloc( raw_alloc_size, stream ) finish = torch.cuda.memory_stats()["requested_bytes.all.allocated"] torch._C._cuda_cudaCachingAllocator_raw_delete(mem_ptr) return finish - start torch.cuda.empty_cache() device = torch._C._cuda_getDevice() stream = torch._C._cuda_getCurrentRawStream(device) torch._C._cuda_resetAccumulatedMemoryStats(device) # size of allocation raw_alloc_size = 1024 * 1024 # 1 MB try: # Deactivate the caching allocator torch.cuda.caching_allocator_enable(False) # For a deactivated caching allocator, result is zero cuda_alloc_size = requested_bytes_alloc_stats(raw_alloc_size, stream) self.assertEqual(cuda_alloc_size, 0) finally: # Make sure we get back to the default state that is # an activated caching allocator torch.cuda.caching_allocator_enable(True) # For an active caching allocator, result matches raw_alloc_size cuda_alloc_size = requested_bytes_alloc_stats(raw_alloc_size, stream) self.assertEqual(cuda_alloc_size, raw_alloc_size) @unittest.skipIf( IS_JETSON, "oom reporting has issues on jetson igx due to partial nvml support" ) @parametrize("max_split_size_mb_setting", [False, True]) def test_raises_oom(self, max_split_size_mb_setting): if max_split_size_mb_setting: # CudaCachingAllocator does early return when searching available blocks # if max_split_size_mb is not set # Setting this triggers more parts of the code torch.cuda.memory._set_allocator_settings("max_split_size_mb:1024") torch.cuda.memory.empty_cache() with self.assertRaises(torch.cuda.OutOfMemoryError): torch.empty(1024 * 1024 * 1024 * 1024, device="cuda") @unittest.skipIf( not (IS_LINUX and os.uname().machine == "x86_64"), "cpp traces only on linux" ) @unittest.skipIf( TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync" ) def test_cpp_memory_snapshot_pickle(self): from torch.utils.cpp_extension import load_inline source = """ #include <torch/csrc/cuda/memory_snapshot.h> py::object do_snapshot() { std::string data = torch::cuda::_memory_snapshot_pickled(); return py::bytes(data); } void record(bool e, bool ctx) { torch::cuda::_record_memory_history(e, ctx, 10, ctx, ctx); } """ m = load_inline( name="snapshot", cpp_sources=[source], functions=["do_snapshot", "record"] ) for ctx in (False, True): try: m.record(True, ctx) @torch.jit.script def the_script_fn(): return torch.rand(311, 411, device="cuda") def run(): t = the_script_fn() return pickle.loads(m.do_snapshot()) mem = run() found = False for s in mem["segments"]: for b in s["blocks"]: if b["state"] == "active_allocated": if b["requested_size"] == 311 * 411 * 4: if ctx: frame_text = str(b["frames"]) # C++ frame self.assertTrue("::rand" in frame_text) # script frame self.assertTrue("the_script_fn" in frame_text) # python frame self.assertTrue("case.py" in frame_text) found = True last_action = mem["device_traces"][0][-1] self.assertEqual(last_action["action"], "alloc") self.assertEqual(last_action["size"], 311 * 411 * 4) self.assertTrue(found) finally: m.record(False, False) @unittest.skipIf(TEST_CUDAMALLOCASYNC, "temporarily disabled") @unittest.skipIf( IS_JETSON, "oom reporting has issues on jetson igx due to partial nvml support" ) def test_notifies_oom(self): x = False def cb(device, alloc, device_alloc, device_free): nonlocal x x = True torch._C._cuda_attach_out_of_memory_observer(cb) with self.assertRaises(torch.cuda.OutOfMemoryError): torch.empty(1024 * 1024 * 1024 * 1024, device="cuda") self.assertTrue(x) def test_allocator_fuzz(self): # fuzz state = random.getstate() random.seed(123) N = 10000 try: mem = [] total = 0 c = 0 def alloc(): nonlocal total, c b = random.randrange(2 * 1024 * 1024 // 4, 20 * 1024 * 1024 // 4) mem.append((c, torch.full((b,), c, dtype=torch.int32, device="cuda"))) c += 1 total += b def free(): nonlocal total idx = random.randrange(0, len(mem)) v, x = mem.pop(idx) self.assertTrue(torch.all(v == x)) total -= x.numel() choices = [alloc, free, torch.cuda.memory.empty_cache] for _ in range(N): while total >= 1024 * 1024 * 1024 / (4 * 10): free() (action,) = random.choices(choices, weights=[1, 1 if mem else 0, 0.1]) action() finally: random.setstate(state) @unittest.skipIf(not TEST_PYNVML, "pynvml/amdsmi is not available") def test_nvml_get_handler(self): if not torch.version.hip: self.assertTrue(torch.cuda._get_pynvml_handler() is not None) else: self.assertTrue(torch.cuda._get_amdsmi_handler() is not None) @unittest.skipIf(not TEST_PYNVML, "pynvml/amdsmi is not available") def test_temperature(self): self.assertTrue(0 <= torch.cuda.temperature() <= 150) @unittest.skipIf(TEST_WITH_ROCM, "flaky for AMD gpu") @unittest.skipIf(not TEST_PYNVML, "pynvml/amdsmi is not available") def test_device_memory_used(self): """ Verify used device memory in bytes """ torch.cuda.synchronize() gc.collect() torch.cuda.empty_cache() a = torch.cuda.device_memory_used() num_bytes = 512 * 1024**2 _ = torch.empty(num_bytes, dtype=torch.int8, device="cuda") torch.cuda.synchronize() torch.cuda.empty_cache() b = torch.cuda.device_memory_used() mem_bytes = b - a # test the order of magnitude self.assertTrue(num_bytes // 32 <= mem_bytes <= num_bytes * 32) @unittest.skipIf(not TEST_PYNVML, "pynvml/amdsmi is not available") def test_power_draw(self): self.assertTrue(torch.cuda.power_draw() >= 0) @unittest.skipIf(not TEST_PYNVML, "pynvml/amdsmi is not available") @skipIfRocmArch(MI300_ARCH) def test_clock_speed(self): self.assertTrue(torch.cuda.clock_rate() >= 0) @unittest.skipIf(not TEST_PYNVML, "pynvml/amdsmi is not available") @unittest.skipIf(not TEST_WITH_ROCM, "amdsmi specific test") def test_raw_amdsmi_device_count(self): """ This unit test will verify if the number of GPUs shown in `amd-smi list` is equivalent to the count returned by `_raw_device_count_amdsmi`. This should be unaffected by visible device settings. """ raw_device_cnt = int( subprocess.check_output( "amd-smi list | grep 'GPU' | wc -l", shell=True ).strip() ) self.assertEqual(torch.cuda._raw_device_count_amdsmi(), raw_device_cnt) @unittest.skipIf(not TEST_PYNVML, "pynvml/amdsmi is not available") @unittest.skipIf(not TEST_WITH_ROCM, "amdsmi specific test") def test_raw_amdsmi_device_uuids(self): """ This unit test will extract a list of UUIDs for each GPU using rocminfo information, and check whether each UUID is present in the output from `_raw_device_uuid_amdsmi` this allows us to test that the pytorch call is returning a correct list of UUIDs. """ cmd = "rocminfo | grep -o 'Uuid:.*GPU-.*' | sed 's/Uuid:.*GPU-//'" uuids = subprocess.check_output(cmd, shell=True, text=True).strip().split("\n") uuids = [s.strip() for s in uuids] raw_uuids = torch.cuda._raw_device_uuid_amdsmi() for uuid in uuids: matching = True if not any(uuid in raw_id for raw_id in raw_uuids): matching = False self.assertEqual(True, matching) @unittest.skipIf(not TEST_PYNVML, "pynvml/amdsmi is not available") @unittest.skipIf(not TEST_WITH_ROCM, "amdsmi specific test") def test_uuid_visible_devices(self): """ This unit test will simulate an environment where a UUID is passed via CUDA/HIP_VISIBLE_DEVICES and ensure that the correct device count is returned. This allows us to test that the visible device functionality is operating as expected. """ test_script = """\ import torch import os print(f"{torch.cuda.device_count()}") """ cmd = "rocminfo | grep -o 'Uuid:.*GPU-.*' | sed 's/Uuid://'" uuids = subprocess.check_output(cmd, shell=True, text=True).strip().split("\n") uuids = [s.strip() for s in uuids] custom_envs = [] for uuid in uuids: custom_envs.append( {"CUDA_VISIBLE_DEVICES": f"{uuid}", "HIP_VISIBLE_DEVICES": None} ) custom_envs.append( {"HIP_VISIBLE_DEVICES": f"{uuid}", "CUDA_VISIBLE_DEVICES": None} ) for env_config in custom_envs: env = os.environ.copy() for key, value in env_config.items(): if value is None: env.pop(key, None) else: env[key] = value r = ( subprocess.check_output([sys.executable, "-c", test_script], env=env) .decode("ascii") .strip() ) self.assertEqual("1", r) MIN_BLOCK_SIZE = 512 SMALL_SIZE = 1048576 SMALL_BUFFER = 2097152 LARGE_BUFFER = 20971520 def get_cudagraph_segments(pool_id): segments = torch.cuda.memory_snapshot() return [segment for segment in segments if segment["segment_pool_id"] == pool_id] def get_all_cudagraph_segments(): segments = torch.cuda.memory_snapshot() return [segment for segment in segments if segment["segment_pool_id"] != (0, 0)] def cudagraphify(fn, inputs, pool=None): if not TEST_CUDA_GRAPH: raise unittest.SkipTest("cuda graph test is skipped") torch.cuda.synchronize() stream = torch.cuda.Stream() stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(stream): fn(*inputs) stream.synchronize() torch.cuda.current_stream().wait_stream(stream) torch.cuda.synchronize() graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph, stream=stream, pool=pool): static_outputs = fn(*inputs) return graph, static_outputs def int8_cuda(size): return torch.ones([size], device="cuda", dtype=torch.uint8) def live_blocks(pool_id): blocks = 0 seg = get_cudagraph_segments(pool_id) for segment in get_cudagraph_segments(pool_id): for block in segment["blocks"]: blocks += block["state"] == "active_allocated" return blocks def tensor_metadata(x): return { "nbytes": x.untyped_storage().nbytes(), "data_ptr": x.untyped_storage().data_ptr(), "size": x.shape, "stride": x.stride(), "dtype": x.dtype, "device": x.device, "storage_offset": x.storage_offset(), } def reconstruct_from_tensor_metadata(metadata): s = torch._C._construct_storage_from_data_pointer( metadata["data_ptr"], metadata["device"], metadata["nbytes"] ) t = torch.empty([0], device=metadata["device"], dtype=metadata["dtype"]) t.set_( source=s, storage_offset=metadata["storage_offset"], size=metadata["size"], stride=metadata["stride"], ) return t @unittest.skipIf(not TEST_CUDA or TEST_CUDAMALLOCASYNC or TEST_WITH_ROCM, "NYI") @torch.testing._internal.common_utils.markDynamoStrictTest
TestCudaMallocAsync
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 7009, "end": 7158 }
class ____(models.Model): relations = models.ManyToManyField("self") history = HistoricalRecords(m2m_fields=[relations])
PollWithSelfManyToMany