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
getsentry__sentry
tests/sentry/issues/escalating/test_issue_velocity.py
{ "start": 626, "end": 14040 }
class ____(TestCase, SnubaTestCase): def setUp(self) -> None: self.now = timezone.now() self.utcnow = datetime.utcnow() super().setUp() def test_calculation_simple(self) -> None: """ Tests threshold calculation for a single issue with the minimum number of events in the past week. """ self.store_event( project_id=self.project.id, data={ "fingerprint": ["group-1"], "timestamp": (self.now - timedelta(days=8)).isoformat(), "user": {"id": self.user.id, "email": self.user.email}, }, ) for _ in range(2): self.store_event( project_id=self.project.id, data={ "fingerprint": ["group-1"], "timestamp": (self.now - timedelta(days=1)).isoformat(), "user": {"id": self.user.id, "email": self.user.email}, }, ) threshold = calculate_threshold(self.project) assert threshold == 2 / WEEK_IN_HOURS def test_calculation_multiple_issues(self) -> None: """ Tests that we receive the approximate 90th percentile for multiple issues older than a week with multiple events in the past week. """ for i in range(5): # ensure the velocity for each issue is calculated using the whole week self.store_event( project_id=self.project.id, data={ "fingerprint": [f"group-{i}"], "timestamp": (self.now - timedelta(days=8)).isoformat(), "user": {"id": self.user.id, "email": self.user.email}, }, ) for _ in range(i + 2): # fill with events that happened in the previous week self.store_event( project_id=self.project.id, data={ "fingerprint": [f"group-{i}"], "timestamp": (self.now - timedelta(days=1)).isoformat(), "user": {"id": self.user.id, "email": self.user.email}, }, ) # approximate calculation of 95th percentile for small sample expected_threshold = 6 * 0.95 / WEEK_IN_HOURS actual_threshold = calculate_threshold(self.project) # clickhouse's quantile function is approximate # https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantile assert actual_threshold is not None assert math.isclose(expected_threshold, actual_threshold, abs_tol=10**-3) def test_calculation_for_issues_first_seen_recently(self) -> None: """ Tests that issues first seen within the past week use the difference in hours between now and when they were first seen to calculate frequency instead of the full week in hours. """ for _ in range(2): self.store_event( project_id=self.project.id, data={ "fingerprint": ["group-1"], "timestamp": (self.now - timedelta(days=1)).isoformat(), "user": {"id": self.user.id, "email": self.user.email}, }, ) threshold = calculate_threshold(self.project) assert threshold == 2 / 24 def test_calculation_excludes_issues_with_only_one_event_in_past_week(self) -> None: """ Tests that issues with only one event in the past week are excluded from the calculation. """ self.store_event( project_id=self.project.id, data={ "fingerprint": ["group-1"], "timestamp": (self.now - timedelta(days=8)).isoformat(), "user": {"id": self.user.id, "email": self.user.email}, }, ) self.store_event( project_id=self.project.id, data={ "fingerprint": ["group-1"], "timestamp": (self.now - timedelta(days=1)).isoformat(), "user": {"id": self.user.id, "email": self.user.email}, }, ) threshold = calculate_threshold(self.project) assert threshold is not None assert math.isnan(threshold) def test_calculation_excludes_issues_newer_than_an_hour(self) -> None: """ Tests that issues that were first seen within the past hour are excluded from the calculation. """ self.store_event( project_id=self.project.id, data={ "fingerprint": ["group-1"], "timestamp": (self.now - timedelta(minutes=1)).isoformat(), "user": {"id": self.user.id, "email": self.user.email}, }, ) self.store_event( project_id=self.project.id, data={ "fingerprint": ["group-1"], "timestamp": (self.now - timedelta(minutes=1)).isoformat(), "user": {"id": self.user.id, "email": self.user.email}, }, ) threshold = calculate_threshold(self.project) assert threshold is not None assert math.isnan(threshold) @patch("sentry.issues.escalating.issue_velocity.update_threshold") def test_get_latest_threshold_simple(self, mock_update: MagicMock) -> None: """ Tests that we get the last threshold stored when the stale date has not passed yet. """ redis_client = get_redis_client() redis_client.set(THRESHOLD_KEY.format(project_id=self.project.id), 0.1) redis_client.set(STALE_DATE_KEY.format(project_id=self.project.id), str(self.utcnow)) threshold = get_latest_threshold(self.project) mock_update.assert_not_called() assert threshold == 0.1 @patch("sentry.issues.escalating.issue_velocity.update_threshold") def test_get_latest_threshold_outdated(self, mock_update: MagicMock) -> None: """ Tests that we update the threshold when the stale date has passed. """ redis_client = get_redis_client() redis_client.set(THRESHOLD_KEY.format(project_id=self.project.id), 1.2) redis_client.set( STALE_DATE_KEY.format(project_id=self.project.id), str(self.utcnow - timedelta(days=1, seconds=1)), ) mock_update.return_value = 1.5 assert get_latest_threshold(self.project) == 1.5 @patch("sentry.issues.escalating.issue_velocity.update_threshold") def test_get_latest_threshold_when_none_saved(self, mock_update: MagicMock) -> None: """ Tests that we update the threshold when it is non-existent. """ mock_update.return_value = 10.7 assert get_latest_threshold(self.project) == 10.7 @patch("sentry.issues.escalating.issue_velocity.update_threshold") def test_get_latest_threshold_locked(self, mock_update: MagicMock) -> None: """ Tests that we return the stale threshold when another process has the lock. """ redis_client = get_redis_client() redis_client.set(THRESHOLD_KEY.format(project_id=self.project.id), 0.7) redis_client.set( STALE_DATE_KEY.format(project_id=self.project.id), str(self.utcnow - timedelta(days=1)), ) lock = locks.get( f"calculate_project_thresholds:{self.project.id}", duration=10, name="calculate_project_thresholds", ) with lock.acquire(): threshold = get_latest_threshold(self.project) mock_update.assert_not_called() assert threshold == 0.7 @patch("sentry.issues.escalating.issue_velocity.update_threshold") def test_get_latest_threshold_locked_no_stale(self, mock_update: MagicMock) -> None: """ Tests that we return 0 when another process has the lock and there is no stale value. """ lock = locks.get( f"calculate_project_thresholds:{self.project.id}", duration=10, name="calculate_project_thresholds", ) with lock.acquire(): threshold = get_latest_threshold(self.project) mock_update.assert_not_called() assert threshold == 0 @patch("sentry.issues.escalating.issue_velocity.calculate_threshold") def test_update_threshold_simple(self, mock_calculation: MagicMock) -> None: """ Tests that we save the newly calculated threshold at the default TTL and return it. """ mock_calculation.return_value = 5 threshold = update_threshold(self.project.id, "threshold-key", "date-key") assert threshold == 5 redis_client = get_redis_client() assert redis_client.get("threshold-key") == "5" stored_date = redis_client.get("date-key") assert isinstance(stored_date, str) assert datetime.fromisoformat(stored_date) == self.utcnow assert redis_client.ttl("threshold-key") == DEFAULT_TTL assert redis_client.ttl("date-key") == DEFAULT_TTL @patch("sentry.issues.escalating.issue_velocity.calculate_threshold") def test_update_threshold_with_stale(self, mock_calculation: MagicMock) -> None: """ Tests that we return the stale threshold if the calculation method returns None. """ mock_calculation.return_value = None redis_client = get_redis_client() redis_client.set("threshold-key", 0.5, ex=86400) assert update_threshold(self.project, "threshold-key", "date-key", 0.5) == 0.5 @patch("sentry.issues.escalating.issue_velocity.calculate_threshold") def test_update_threshold_none(self, mock_calculation: MagicMock) -> None: """ Tests that we return 0 if the calculation method returns None and we don't have a stale threshold. """ mock_calculation.return_value = None assert update_threshold(self.project, "threshold-key", "date-key") == 0 @patch("sentry.issues.escalating.issue_velocity.calculate_threshold") def test_update_threshold_nan(self, mock_calculation: MagicMock) -> None: """ Tests that we return 0 and save a threshold for the default TTL if the calculation returned NaN. """ mock_calculation.return_value = float("nan") assert update_threshold(self.project, "threshold-key", "date-key") == 0 redis_client = get_redis_client() assert redis_client.get("threshold-key") == "0" stored_date = redis_client.get("date-key") assert isinstance(stored_date, str) assert datetime.fromisoformat(stored_date) == self.utcnow assert redis_client.ttl("threshold-key") == DEFAULT_TTL def test_fallback_to_stale(self) -> None: """ Tests that we return the stale threshold and maintain its TTL, and update the stale date to make the threshold usable for the next ten minutes as a fallback. """ redis_client = get_redis_client() redis_client.set("threshold-key", 0.5, ex=86400) assert fallback_to_stale_or_zero("threshold-key", "date-key", 0.5) == 0.5 assert redis_client.get("threshold-key") == "0.5" stored_date = redis_client.get("date-key") assert isinstance(stored_date, str) assert datetime.fromisoformat(stored_date) == ( self.utcnow - timedelta(seconds=TIME_TO_USE_EXISTING_THRESHOLD) + timedelta(seconds=FALLBACK_TTL) ) assert redis_client.ttl("threshold-key") == 86400 assert redis_client.ttl("date-key") == 86400 def test_fallback_to_zero(self) -> None: """ Tests that we return 0 and store it in Redis for the next ten minutes as a fallback if we do not have a stale threshold. """ assert fallback_to_stale_or_zero("threshold-key", "date-key", None) == 0 redis_client = get_redis_client() assert redis_client.get("threshold-key") == "0" stored_date = redis_client.get("date-key") assert isinstance(stored_date, str) assert datetime.fromisoformat(stored_date) == ( self.utcnow - timedelta(seconds=TIME_TO_USE_EXISTING_THRESHOLD) + timedelta(seconds=FALLBACK_TTL) ) assert redis_client.ttl("threshold-key") == FALLBACK_TTL assert redis_client.ttl("date-key") == FALLBACK_TTL def test_fallback_to_stale_zero_ttl(self) -> None: """ Tests that we return 0 and store it in Redis for the next ten minutes as a fallback if our stale threshold has a TTL <= 0. """ redis_client = get_redis_client() assert fallback_to_stale_or_zero("threshold-key", "date-key", 0.5) == 0 assert redis_client.get("threshold-key") == "0" stored_date = redis_client.get("date-key") assert isinstance(stored_date, str) assert datetime.fromisoformat(stored_date) == ( self.utcnow - timedelta(seconds=TIME_TO_USE_EXISTING_THRESHOLD) + timedelta(seconds=FALLBACK_TTL) ) assert redis_client.ttl("threshold-key") == FALLBACK_TTL assert redis_client.ttl("date-key") == FALLBACK_TTL
IssueVelocityTests
python
wandb__wandb
wandb/sdk/lib/disabled.py
{ "start": 420, "end": 963 }
class ____: """Compatibility class for integrations that explicitly check for wandb.RunDisabled.""" def __getattr__(self, name: str) -> Any: from wandb.proto.wandb_telemetry_pb2 import Deprecated from wandb.sdk.lib.deprecation import warn_and_record_deprecation warn_and_record_deprecation( feature=Deprecated(run_disabled=True), message="RunDisabled is deprecated and is a no-op. " '`wandb.init(mode="disabled")` now returns an instance of `wandb.Run`.', )
RunDisabled
python
bokeh__bokeh
src/bokeh/models/ui/floating.py
{ "start": 1527, "end": 3052 }
class ____(Pane): """ A floating panel attachable to an edge of the viewport or a component. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) location = Required(Enum(Location))(help=""" The attachment edge of the viewport or a component. To attach a ``Drawer`` to the viewport, add it as a document root. Otherwise add it to another UI component's ``elements`` property. """) open = Bool(default=False, help=""" Initial or actual state of the component. """) size = Either(Float, CSSLength)(default=300, help=""" The initial or actual size (width or height) of the component. This can either be a CSS length value (``20px``, ``1.5em``, ``30vw``, etc.) or a number of pixels (equivalent to CSS ``px`` units). """) resizable = Bool(default=False, help=""" Whether the component is resizable by dragging its interactive edge. """) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
Drawer
python
modin-project__modin
modin/config/envvars.py
{ "start": 31840, "end": 32741 }
class ____(EnvironmentVariable, type=int): """Max size of logs (in MBs) to store per Modin job.""" varname = "MODIN_LOG_FILE_SIZE" default = 10 @classmethod def put(cls, value: int) -> None: """ Set ``LogFileSize`` with extra checks. Parameters ---------- value : int Config value to set. """ if value <= 0: raise ValueError(f"Log file size should be > 0 MB, passed value {value}") super().put(value) @classmethod def get(cls) -> int: """ Get ``LogFileSize`` with extra checks. Returns ------- int """ log_file_size = super().get() if log_file_size <= 0: raise ValueError( f"`LogFileSize` should be > 0; current value: {log_file_size}" ) return log_file_size
LogFileSize
python
langchain-ai__langchain
libs/core/tests/unit_tests/vectorstores/test_vectorstore.py
{ "start": 2061, "end": 10388 }
class ____(VectorStore): """A VectorStore that only implements add documents.""" def __init__(self) -> None: self.store: dict[str, Document] = {} @override def add_documents( self, documents: list[Document], *, ids: list[str] | None = None, **kwargs: Any, ) -> list[str]: ids_ = [] ids_iter = iter(ids or []) for document in documents: id_ = next(ids_iter) if ids else document.id or str(uuid.uuid4()) self.store[id_] = Document( id=id_, page_content=document.page_content, metadata=document.metadata ) ids_.append(id_) return ids_ def get_by_ids(self, ids: Sequence[str], /) -> list[Document]: return [self.store[id_] for id_ in ids if id_ in self.store] @classmethod @override def from_texts( cls, texts: list[str], embedding: Embeddings, metadatas: list[dict] | None = None, **kwargs: Any, ) -> CustomAddDocumentsVectorstore: vectorstore = CustomAddDocumentsVectorstore() vectorstore.add_texts(texts, metadatas=metadatas, **kwargs) return vectorstore def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> list[Document]: raise NotImplementedError @pytest.mark.parametrize( "vs_class", [CustomAddTextsVectorstore, CustomAddDocumentsVectorstore] ) def test_default_add_documents(vs_class: type[VectorStore]) -> None: """Test default implementation of add_documents. Test that we can implement the upsert method of the CustomVectorStore class without violating the Liskov Substitution Principle. """ store = vs_class() # Check upsert with id assert store.add_documents([Document(id="1", page_content="hello")]) == ["1"] assert store.get_by_ids(["1"]) == [Document(id="1", page_content="hello")] # Check upsert without id ids = store.add_documents([Document(page_content="world")]) assert len(ids) == 1 assert store.get_by_ids(ids) == [Document(id=ids[0], page_content="world")] # Check that add_documents works assert store.add_documents([Document(id="5", page_content="baz")]) == ["5"] # Test add documents with id specified in both document and ids original_document = Document(id="7", page_content="baz") assert store.add_documents([original_document], ids=["6"]) == ["6"] assert original_document.id == "7" # original document should not be modified assert store.get_by_ids(["6"]) == [Document(id="6", page_content="baz")] @pytest.mark.parametrize( "vs_class", [CustomAddTextsVectorstore, CustomAddDocumentsVectorstore] ) def test_default_add_texts(vs_class: type[VectorStore]) -> None: store = vs_class() # Check that default implementation of add_texts works assert store.add_texts(["hello", "world"], ids=["3", "4"]) == ["3", "4"] assert store.get_by_ids(["3", "4"]) == [ Document(id="3", page_content="hello"), Document(id="4", page_content="world"), ] # Add texts without ids ids_ = store.add_texts(["foo", "bar"]) assert len(ids_) == 2 assert store.get_by_ids(ids_) == [ Document(id=ids_[0], page_content="foo"), Document(id=ids_[1], page_content="bar"), ] # Add texts with metadatas ids_2 = store.add_texts(["foo", "bar"], metadatas=[{"foo": "bar"}] * 2) assert len(ids_2) == 2 assert store.get_by_ids(ids_2) == [ Document(id=ids_2[0], page_content="foo", metadata={"foo": "bar"}), Document(id=ids_2[1], page_content="bar", metadata={"foo": "bar"}), ] @pytest.mark.parametrize( "vs_class", [CustomAddTextsVectorstore, CustomAddDocumentsVectorstore] ) async def test_default_aadd_documents(vs_class: type[VectorStore]) -> None: """Test delegation to the synchronous method.""" store = vs_class() # Check upsert with id assert await store.aadd_documents([Document(id="1", page_content="hello")]) == ["1"] assert await store.aget_by_ids(["1"]) == [Document(id="1", page_content="hello")] # Check upsert without id ids = await store.aadd_documents([Document(page_content="world")]) assert len(ids) == 1 assert await store.aget_by_ids(ids) == [Document(id=ids[0], page_content="world")] # Check that add_documents works assert await store.aadd_documents([Document(id="5", page_content="baz")]) == ["5"] # Test add documents with id specified in both document and ids original_document = Document(id="7", page_content="baz") assert await store.aadd_documents([original_document], ids=["6"]) == ["6"] assert original_document.id == "7" # original document should not be modified assert await store.aget_by_ids(["6"]) == [Document(id="6", page_content="baz")] @pytest.mark.parametrize( "vs_class", [CustomAddTextsVectorstore, CustomAddDocumentsVectorstore] ) async def test_default_aadd_texts(vs_class: type[VectorStore]) -> None: """Test delegation to the synchronous method.""" store = vs_class() # Check that default implementation of aadd_texts works assert await store.aadd_texts(["hello", "world"], ids=["3", "4"]) == ["3", "4"] assert await store.aget_by_ids(["3", "4"]) == [ Document(id="3", page_content="hello"), Document(id="4", page_content="world"), ] # Add texts without ids ids_ = await store.aadd_texts(["foo", "bar"]) assert len(ids_) == 2 assert await store.aget_by_ids(ids_) == [ Document(id=ids_[0], page_content="foo"), Document(id=ids_[1], page_content="bar"), ] # Add texts with metadatas ids_2 = await store.aadd_texts(["foo", "bar"], metadatas=[{"foo": "bar"}] * 2) assert len(ids_2) == 2 assert await store.aget_by_ids(ids_2) == [ Document(id=ids_2[0], page_content="foo", metadata={"foo": "bar"}), Document(id=ids_2[1], page_content="bar", metadata={"foo": "bar"}), ] @pytest.mark.parametrize( "vs_class", [CustomAddTextsVectorstore, CustomAddDocumentsVectorstore] ) def test_default_from_documents(vs_class: type[VectorStore]) -> None: embeddings = FakeEmbeddings(size=1) store = vs_class.from_documents( [Document(id="1", page_content="hello", metadata={"foo": "bar"})], embeddings ) assert store.get_by_ids(["1"]) == [ Document(id="1", page_content="hello", metadata={"foo": "bar"}) ] # from_documents with IDs in args store = vs_class.from_documents( [Document(page_content="hello", metadata={"foo": "bar"})], embeddings, ids=["1"] ) assert store.get_by_ids(["1"]) == [ Document(id="1", page_content="hello", metadata={"foo": "bar"}) ] # Test from_documents with id specified in both document and ids original_document = Document(id="7", page_content="baz") store = vs_class.from_documents([original_document], embeddings, ids=["6"]) assert original_document.id == "7" # original document should not be modified assert store.get_by_ids(["6"]) == [Document(id="6", page_content="baz")] @pytest.mark.parametrize( "vs_class", [CustomAddTextsVectorstore, CustomAddDocumentsVectorstore] ) async def test_default_afrom_documents(vs_class: type[VectorStore]) -> None: embeddings = FakeEmbeddings(size=1) store = await vs_class.afrom_documents( [Document(id="1", page_content="hello", metadata={"foo": "bar"})], embeddings ) assert await store.aget_by_ids(["1"]) == [ Document(id="1", page_content="hello", metadata={"foo": "bar"}) ] # from_documents with IDs in args store = await vs_class.afrom_documents( [Document(page_content="hello", metadata={"foo": "bar"})], embeddings, ids=["1"] ) assert await store.aget_by_ids(["1"]) == [ Document(id="1", page_content="hello", metadata={"foo": "bar"}) ] # Test afrom_documents with id specified in both document and IDs original_document = Document(id="7", page_content="baz") store = await vs_class.afrom_documents([original_document], embeddings, ids=["6"]) assert original_document.id == "7" # original document should not be modified assert await store.aget_by_ids(["6"]) == [Document(id="6", page_content="baz")]
CustomAddDocumentsVectorstore
python
ray-project__ray
python/ray/serve/tests/test_config_files/test_dag/conditional_dag.py
{ "start": 308, "end": 1175 }
class ____: def __init__(self, multiplier: DeploymentHandle, adder: DeploymentHandle): self.adder = adder self.multiplier = multiplier async def route(self, op: Operation, input: int) -> int: if op == Operation.ADDITION: amount = await self.adder.add.remote(input) elif op == Operation.MULTIPLICATION: amount = await self.multiplier.multiply.remote(input) return f"{amount} pizzas please!" async def __call__(self, request: starlette.requests.Request) -> str: op, input = await request.json() return await self.route(op, input) @serve.deployment( user_config={ "factor": 3, }, ray_actor_options={ "num_cpus": 0.1, "runtime_env": { "env_vars": { "override_factor": "-2", } }, }, )
Router
python
hynek__structlog
src/structlog/_generic.py
{ "start": 417, "end": 1636 }
class ____(BoundLoggerBase): """ A generic BoundLogger that can wrap anything. Every unknown method will be passed to the wrapped *logger*. If that's too much magic for you, try `structlog.stdlib.BoundLogger` or `structlog.twisted.BoundLogger` which also take advantage of knowing the wrapped class which generally results in better performance. Not intended to be instantiated by yourself. See :func:`~structlog.wrap_logger` and :func:`~structlog.get_logger`. """ def __getattr__(self, method_name: str) -> Any: """ If not done so yet, wrap the desired logger method & cache the result. """ if method_name == "__deepcopy__": return None wrapped = partial(self._proxy_to_logger, method_name) setattr(self, method_name, wrapped) return wrapped def __getstate__(self) -> dict[str, Any]: """ Our __getattr__ magic makes this necessary. """ return self.__dict__ def __setstate__(self, state: dict[str, Any]) -> None: """ Our __getattr__ magic makes this necessary. """ for k, v in state.items(): setattr(self, k, v)
BoundLogger
python
joblib__joblib
joblib/externals/loky/process_executor.py
{ "start": 10190, "end": 19599 }
class ____(Queue): """Safe Queue set exception to the future object linked to a job""" def __init__( self, max_size=0, ctx=None, pending_work_items=None, running_work_items=None, thread_wakeup=None, shutdown_lock=None, reducers=None, ): self.thread_wakeup = thread_wakeup self.shutdown_lock = shutdown_lock self.pending_work_items = pending_work_items self.running_work_items = running_work_items super().__init__(max_size, reducers=reducers, ctx=ctx) def _on_queue_feeder_error(self, e, obj): if isinstance(obj, _CallItem): # format traceback only works on python3 if isinstance(e, struct.error): raised_error = RuntimeError( "The task could not be sent to the workers as it is too " "large for `send_bytes`." ) else: raised_error = PicklingError( "Could not pickle the task to send it to the workers." ) tb = traceback.format_exception( type(e), e, getattr(e, "__traceback__", None) ) raised_error.__cause__ = _RemoteTraceback("".join(tb)) work_item = self.pending_work_items.pop(obj.work_id, None) self.running_work_items.remove(obj.work_id) # work_item can be None if another process terminated. In this # case, the executor_manager_thread fails all work_items with # BrokenProcessPool if work_item is not None: work_item.future.set_exception(raised_error) del work_item with self.shutdown_lock: self.thread_wakeup.wakeup() else: super()._on_queue_feeder_error(e, obj) def _get_chunks(chunksize, *iterables): """Iterates over zip()ed iterables in chunks.""" it = zip(*iterables) while True: chunk = tuple(itertools.islice(it, chunksize)) if not chunk: return yield chunk def _process_chunk(fn, chunk): """Processes a chunk of an iterable passed to map. Runs the function passed to map() on a chunk of the iterable passed to map. This function is run in a separate process. """ return [fn(*args) for args in chunk] def _sendback_result(result_queue, work_id, result=None, exception=None): """Safely send back the given result or exception""" try: result_queue.put( _ResultItem(work_id, result=result, exception=exception) ) except BaseException as e: exc = _ExceptionWithTraceback(e) result_queue.put(_ResultItem(work_id, exception=exc)) def _enable_faulthandler_if_needed(): if "PYTHONFAULTHANDLER" in os.environ: # Respect the environment variable to configure faulthandler. This # makes it possible to never enable faulthandler in the loky workers by # setting PYTHONFAULTHANDLER=0 explicitly in the environment. mp.util.debug( f"faulthandler explicitly configured by environment variable: " f"PYTHONFAULTHANDLER={os.environ['PYTHONFAULTHANDLER']}." ) else: if faulthandler.is_enabled(): # Fault handler is already enabled, possibly via a custom # initializer to customize the behavior. mp.util.debug("faulthandler already enabled.") else: # Enable faulthandler by default with default paramaters otherwise. mp.util.debug( "Enabling faulthandler to report tracebacks on worker crashes." ) faulthandler.enable() def _process_worker( call_queue, result_queue, initializer, initargs, processes_management_lock, timeout, worker_exit_lock, current_depth, ): """Evaluates calls from call_queue and places the results in result_queue. This worker is run in a separate process. Args: call_queue: A ctx.Queue of _CallItems that will be read and evaluated by the worker. result_queue: A ctx.Queue of _ResultItems that will written to by the worker. initializer: A callable initializer, or None initargs: A tuple of args for the initializer processes_management_lock: A ctx.Lock avoiding worker timeout while some workers are being spawned. timeout: maximum time to wait for a new item in the call_queue. If that time is expired, the worker will shutdown. worker_exit_lock: Lock to avoid flagging the executor as broken on workers timeout. current_depth: Nested parallelism level, to avoid infinite spawning. """ if initializer is not None: try: initializer(*initargs) except BaseException: LOGGER.critical("Exception in initializer:", exc_info=True) # The parent will notice that the process stopped and # mark the pool broken return # set the global _CURRENT_DEPTH mechanism to limit recursive call global _CURRENT_DEPTH _CURRENT_DEPTH = current_depth _process_reference_size = None _last_memory_leak_check = None pid = os.getpid() mp.util.debug(f"Worker started with timeout={timeout}") _enable_faulthandler_if_needed() while True: try: call_item = call_queue.get(block=True, timeout=timeout) if call_item is None: mp.util.info("Shutting down worker on sentinel") except queue.Empty: mp.util.info(f"Shutting down worker after timeout {timeout:0.3f}s") if processes_management_lock.acquire(block=False): processes_management_lock.release() call_item = None else: mp.util.info("Could not acquire processes_management_lock") continue except BaseException: previous_tb = traceback.format_exc() try: result_queue.put(_RemoteTraceback(previous_tb)) except BaseException: # If we cannot format correctly the exception, at least print # the traceback. print(previous_tb) mp.util.debug("Exiting with code 1") sys.exit(1) if call_item is None: # Notify queue management thread about worker shutdown result_queue.put(pid) is_clean = worker_exit_lock.acquire(True, timeout=30) # Early notify any loky executor running in this worker process # (nested parallelism) that this process is about to shutdown to # avoid a deadlock waiting undifinitely for the worker to finish. _python_exit() if is_clean: mp.util.debug("Exited cleanly") else: mp.util.info("Main process did not release worker_exit") return try: r = call_item() except BaseException as e: exc = _ExceptionWithTraceback(e) result_queue.put(_ResultItem(call_item.work_id, exception=exc)) else: _sendback_result(result_queue, call_item.work_id, result=r) del r # Free the resource as soon as possible, to avoid holding onto # open files or shared memory that is not needed anymore del call_item if _USE_PSUTIL: if _process_reference_size is None: # Make reference measurement after the first call _process_reference_size = _get_memory_usage(pid, force_gc=True) _last_memory_leak_check = time() continue if time() - _last_memory_leak_check > _MEMORY_LEAK_CHECK_DELAY: mem_usage = _get_memory_usage(pid) _last_memory_leak_check = time() if mem_usage - _process_reference_size < _MAX_MEMORY_LEAK_SIZE: # Memory usage stays within bounds: everything is fine. continue # Check again memory usage; this time take the measurement # after a forced garbage collection to break any reference # cycles. mem_usage = _get_memory_usage(pid, force_gc=True) _last_memory_leak_check = time() if mem_usage - _process_reference_size < _MAX_MEMORY_LEAK_SIZE: # The GC managed to free the memory: everything is fine. continue # The process is leaking memory: let the master process # know that we need to start a new worker. mp.util.info("Memory leak detected: shutting down worker") result_queue.put(pid) with worker_exit_lock: mp.util.debug("Exit due to memory leak") return else: # if psutil is not installed, trigger gc.collect events # regularly to limit potential memory leaks due to reference cycles if _last_memory_leak_check is None or ( time() - _last_memory_leak_check > _MEMORY_LEAK_CHECK_DELAY ): gc.collect() _last_memory_leak_check = time()
_SafeQueue
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_textbox37.py
{ "start": 315, "end": 945 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("textbox37.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_textbox( "E9", "This is some text", {"url": "https://github.com/jmcnamara", "tip": "GitHub"}, ) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
ray-project__ray
python/ray/tune/experiment/trial.py
{ "start": 2457, "end": 3253 }
class ____: """Describes the format to import/export the trial Trainable. This may correspond to different file formats based on the Trainable implementation. """ CHECKPOINT = "checkpoint" MODEL = "model" ONNX = "onnx" H5 = "h5" @staticmethod def validate(formats): """Validates formats. Raises: ValueError: if the format is unknown. """ for i in range(len(formats)): formats[i] = formats[i].strip().lower() if formats[i] not in [ ExportFormat.CHECKPOINT, ExportFormat.MODEL, ExportFormat.ONNX, ExportFormat.H5, ]: raise TuneError("Unsupported import/export format: " + formats[i])
ExportFormat
python
facebook__pyre-check
client/configuration/extension.py
{ "start": 744, "end": 2062 }
class ____: suffix: str include_suffix_in_module_qualifier: bool = False def command_line_argument(self) -> str: options = "" if self.include_suffix_in_module_qualifier: options = "$" + "include_suffix_in_module_qualifier" return self.suffix + options @staticmethod def from_json(json: object) -> "Element": if isinstance(json, str): return Element(suffix=json, include_suffix_in_module_qualifier=False) elif isinstance(json, dict): suffix = json.get("suffix", None) include_suffix_in_module_qualifier = json.get( "include_suffix_in_module_qualifier", None ) if isinstance(suffix, str) and isinstance( include_suffix_in_module_qualifier, bool ): return Element( suffix=suffix, include_suffix_in_module_qualifier=include_suffix_in_module_qualifier, ) raise exceptions.InvalidConfiguration(f"Invalid extension element: {json}") def to_json(self) -> str: return json.dumps( { "suffix": self.suffix, "include_suffix_in_module_qualifier": self.include_suffix_in_module_qualifier, } )
Element
python
django__django
tests/utils_tests/test_autoreload.py
{ "start": 15048, "end": 16600 }
class ____(SimpleTestCase): @mock.patch("django.utils.autoreload.ensure_echo_on") def test_echo_on_called(self, mocked_echo): fake_reloader = mock.MagicMock() autoreload.start_django(fake_reloader, lambda: None) self.assertEqual(mocked_echo.call_count, 1) @mock.patch("django.utils.autoreload.check_errors") def test_check_errors_called(self, mocked_check_errors): fake_method = mock.MagicMock(return_value=None) fake_reloader = mock.MagicMock() autoreload.start_django(fake_reloader, fake_method) self.assertCountEqual(mocked_check_errors.call_args[0], [fake_method]) @mock.patch("threading.Thread") @mock.patch("django.utils.autoreload.check_errors") def test_starts_thread_with_args(self, mocked_check_errors, mocked_thread): fake_reloader = mock.MagicMock() fake_main_func = mock.MagicMock() fake_thread = mock.MagicMock() mocked_check_errors.return_value = fake_main_func mocked_thread.return_value = fake_thread autoreload.start_django(fake_reloader, fake_main_func, 123, abc=123) self.assertEqual(mocked_thread.call_count, 1) self.assertEqual( mocked_thread.call_args[1], { "target": fake_main_func, "args": (123,), "kwargs": {"abc": 123}, "name": "django-main-thread", }, ) self.assertIs(fake_thread.daemon, True) self.assertTrue(fake_thread.start.called)
StartDjangoTests
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pep8_naming/ignore_names/N805.py
{ "start": 835, "end": 994 }
class ____: def badAllowed(this, blah, /, self, something: str): pass def stillBad(this, blah, /, self, something: str): pass
PosOnlyClass
python
pypa__pip
src/pip/_internal/vcs/versioncontrol.py
{ "start": 2840, "end": 4261 }
class ____: """ Encapsulates a VCS-specific revision to install, along with any VCS install options. Args: vc_class: a VersionControl subclass. rev: the name of the revision to install. extra_args: a list of extra options. """ vc_class: type[VersionControl] rev: str | None = None extra_args: CommandArgs = field(default_factory=list) branch_name: str | None = None def __repr__(self) -> str: return f"<RevOptions {self.vc_class.name}: rev={self.rev!r}>" @property def arg_rev(self) -> str | None: if self.rev is None: return self.vc_class.default_arg_rev return self.rev def to_args(self) -> CommandArgs: """ Return the VCS-specific command arguments. """ args: CommandArgs = [] rev = self.arg_rev if rev is not None: args += self.vc_class.get_base_rev_args(rev) args += self.extra_args return args def to_display(self) -> str: if not self.rev: return "" return f" (to revision {self.rev})" def make_new(self, rev: str) -> RevOptions: """ Make a copy of the current instance, but with a new rev. Args: rev: the name of the revision for the new object. """ return self.vc_class.make_rev_options(rev, extra_args=self.extra_args)
RevOptions
python
ethereum__web3.py
web3/exceptions.py
{ "start": 1070, "end": 1247 }
class ____(Web3Exception, AttributeError): """ A web3.py exception wrapper for `AttributeError`, for better control over exception handling. """
Web3AttributeError
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_tridiag_test.py
{ "start": 5511, "end": 7107 }
class ____( _LinearOperatorTriDiagBase, linear_operator_test_util.SquareLinearOperatorDerivedClassTest): """Most tests done in the base class LinearOperatorDerivedClassTest.""" def tearDown(self): config.enable_tensor_float_32_execution(self.tf32_keep_) def setUp(self): self.tf32_keep_ = config.tensor_float_32_execution_enabled() config.enable_tensor_float_32_execution(False) def operator_and_matrix( self, build_info, dtype, use_placeholder, ensure_self_adjoint_and_pd=False): return self.build_operator_and_matrix( build_info, dtype, use_placeholder, ensure_self_adjoint_and_pd=ensure_self_adjoint_and_pd, diagonals_format='sequence') @test_util.disable_xla('Current implementation does not yet support pivoting') def test_tape_safe(self): diagonals = [ variables_module.Variable([3., 6., 2.]), variables_module.Variable([2., 4., 2.]), variables_module.Variable([5., 1., 2.])] operator = linalg_lib.LinearOperatorTridiag( diagonals, diagonals_format='sequence') # Skip the diagonal part and trace since this only dependent on the # middle variable. We test this below. self.check_tape_safe(operator, skip_options=['diag_part', 'trace']) diagonals = [ [3., 6., 2.], variables_module.Variable([2., 4., 2.]), [5., 1., 2.] ] operator = linalg_lib.LinearOperatorTridiag( diagonals, diagonals_format='sequence') @test_util.with_eager_op_as_function @test_util.run_all_in_graph_and_eager_modes
LinearOperatorTriDiagSequenceTest
python
walkccc__LeetCode
solutions/3274. Check if Two Chessboard Squares Have the Same Color/3274.py
{ "start": 0, "end": 349 }
class ____: def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool: # Same as 1812. Determine Color of a Chessboard Square def squareIsWhite(coordinate: str) -> bool: letter, digit = coordinate return ord(letter) % 2 != int(digit) % 2 return squareIsWhite(coordinate1) == squareIsWhite(coordinate2)
Solution
python
kamyu104__LeetCode-Solutions
Python/find-weighted-median-node-in-tree.py
{ "start": 1022, "end": 5092 }
class ____(object): def findMedian(self, n, edges, queries): """ :type n: int :type edges: List[List[int]] :type queries: List[List[int]] :rtype: List[int] """ def iter_dfs(): lookup = [False]*len(adj) lookup2 = [[] for _ in xrange(len(adj))] for i, q in enumerate(queries): for x in q: lookup2[x].append(i) uf = UnionFind(len(adj)) ancestor = range(len(adj)) depth = [0]*len(adj) dist = [0]*len(adj) lca = [0]*len(queries) result = [0]*len(queries) stk = [(1, (0,))] while stk: step, args = stk.pop() if step == 1: u = args[0] for i in lookup2[u]: if queries[i][0] == queries[i][1]: lca[i] = u continue result[i] += dist[u] for x in queries[i]: if lookup[x]: lca[i] = ancestor[uf.find_set(x)] result[i] -= 2*dist[lca[i]] lookup[u] = True stk.append((2, (u, 0))) elif step == 2: u, i = args if i == len(adj[u]): continue v, w = adj[u][i] stk.append((2, (u, i+1))) if lookup[v]: continue dist[v] = dist[u]+w depth[v] = depth[u]+1 stk.append((3, (v, u))) stk.append((1, (v, u))) elif step == 3: v, u = args uf.union_set(v, u) ancestor[uf.find_set(u)] = u return result, lca, dist, depth def iter_dfs2(): lookup3 = [[] for _ in xrange(len(adj))] for i, (u, v) in enumerate(queries): if 2*(dist[u]-dist[lca[i]]) >= result[i]: lookup3[u].append((i, 0)) else: lookup3[v].append((i, 1)) result2 = [0]*len(queries) path = [] stk = [(1, (0,))] while stk: step, args = stk.pop() if step == 1: u = args[0] path.append(u) for i, t in lookup3[u]: d = depth[u]-depth[lca[i]] if t == 0: j = binary_search(0, d, lambda x: 2*(dist[u]-dist[path[-(x+1)]]) >= result[i]) result2[i] = path[-(j+1)] else: l = dist[queries[i][0]]-dist[lca[i]] j = binary_search(0, d-1, lambda x: 2*(l+(dist[path[-((d-1)+1)+x]]-dist[lca[i]])) >= result[i]) result2[i] = path[-((d-1)+1)+j] stk.append((3, None)) stk.append((2, (u, 0))) elif step == 2: u, i = args if i == len(adj[u]): continue v, w = adj[u][i] stk.append((2, (u, i+1))) if len(path) >= 2 and path[-2] == v: continue dist[v] = dist[u]+w depth[v] = depth[u]+1 stk.append((1, (v, u))) elif step == 3: path.pop() return result2 adj = [[] for _ in xrange(len(edges)+1)] for u, v, w in edges: adj[u].append((v, w)) adj[v].append((u, w)) result, lca, dist, depth = iter_dfs() return iter_dfs2() # Time: O(n + qlogh) # Space: O(n + q) # dfs, Tarjan's Offline LCA Algorithm, binary search, prefix sum
Solution
python
wandb__wandb
wandb/sdk/artifacts/_generated/registry_versions.py
{ "start": 283, "end": 377 }
class ____(GQLResult): organization: Optional[RegistryVersionsOrganization]
RegistryVersions
python
apache__airflow
providers/fab/src/airflow/providers/fab/auth_manager/models/__init__.py
{ "start": 4106, "end": 4784 }
class ____(Model): """Represents permission object such as `User` or `Dag`.""" __tablename__ = "ab_view_menu" id: Mapped[int] = mapped_column( Integer, Sequence("ab_view_menu_id_seq", start=1, increment=1, minvalue=1, cycle=False), primary_key=True, ) name: Mapped[str] = mapped_column(String(250), unique=True, nullable=False) def __eq__(self, other): return (isinstance(other, self.__class__)) and (self.name == other.name) def __hash__(self): return hash((self.id, self.name)) def __neq__(self, other): return self.name != other.name def __repr__(self): return self.name
Resource
python
prabhupant__python-ds
data_structures/binary_trees/evaluate_expresssion_tree.py
{ "start": 120, "end": 800 }
class ____: def __init__(self, val): self.val = val self.right = None self.left = None def evaluate(root): if root is None: return 0 # Check for leaf node if root.left is None and root.right is None: return int(root.data) # Evaluate left tree left_sum = evaluate(root.left) # Evaluate right tree right_sum = evaluate(root.right) # Check which operator to apply if root.data == '+': return left_sum + right_sum elif root.data == '-': return left_sum - right_sum elif root.data == '*': return left_sum * right_sum else: return left_sum / right_sum
Node
python
pennersr__django-allauth
allauth/socialaccount/providers/bitbucket_oauth2/provider.py
{ "start": 241, "end": 522 }
class ____(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get("links", {}).get("html", {}).get("href") def get_avatar_url(self): return self.account.extra_data.get("links", {}).get("avatar", {}).get("href")
BitbucketOAuth2Account
python
python__mypy
mypy/typestate.py
{ "start": 1073, "end": 15958 }
class ____: """This class provides subtype caching to improve performance of subtype checks. It also holds protocol fine grained dependencies. Note: to avoid leaking global state, 'reset_all_subtype_caches()' should be called after a build has finished and after a daemon shutdown. This subtype cache only exists for performance reasons, resetting subtype caches for a class has no semantic effect. The protocol dependencies however are only stored here, and shouldn't be deleted unless not needed any more (e.g. during daemon shutdown). """ # '_subtype_caches' keeps track of (subtype, supertype) pairs where supertypes are # instances of the given TypeInfo. The cache also keeps track of whether the check # was done in strict optional mode and of the specific *kind* of subtyping relationship, # which we represent as an arbitrary hashable tuple. # We need the caches, since subtype checks for structural types are very slow. _subtype_caches: Final[SubtypeCache] # Same as above but for negative subtyping results. _negative_subtype_caches: Final[SubtypeCache] # This contains protocol dependencies generated after running a full build, # or after an update. These dependencies are special because: # * They are a global property of the program; i.e. some dependencies for imported # classes can be generated in the importing modules. # * Because of the above, they are serialized separately, after a full run, # or a full update. # `proto_deps` can be None if after deserialization it turns out that they are # inconsistent with the other cache files (or an error occurred during deserialization). # A blocking error will be generated in this case, since we can't proceed safely. # For the description of kinds of protocol dependencies and corresponding examples, # see _snapshot_protocol_deps. proto_deps: dict[str, set[str]] | None # Protocols (full names) a given class attempted to implement. # Used to calculate fine grained protocol dependencies and optimize protocol # subtype cache invalidation in fine grained mode. For example, if we pass a value # of type a.A to a function expecting something compatible with protocol p.P, # we'd have 'a.A' -> {'p.P', ...} in the map. This map is flushed after every incremental # update. _attempted_protocols: Final[dict[str, set[str]]] # We also snapshot protocol members of the above protocols. For example, if we pass # a value of type a.A to a function expecting something compatible with Iterable, we'd have # 'a.A' -> {'__iter__', ...} in the map. This map is also flushed after every incremental # update. This map is needed to only generate dependencies like <a.A.__iter__> -> <a.A> # instead of a wildcard to avoid unnecessarily invalidating classes. _checked_against_members: Final[dict[str, set[str]]] # TypeInfos that appeared as a left type (subtype) in a subtype check since latest # dependency snapshot update. This is an optimisation for fine grained mode; during a full # run we only take a dependency snapshot at the very end, so this set will contain all # subtype-checked TypeInfos. After a fine grained update however, we can gather only new # dependencies generated from (typically) few TypeInfos that were subtype-checked # (i.e. appeared as r.h.s. in an assignment or an argument in a function call in # a re-checked target) during the update. _rechecked_types: Final[set[TypeInfo]] # The two attributes below are assumption stacks for subtyping relationships between # recursive type aliases. Normally, one would pass type assumptions as an additional # arguments to is_subtype(), but this would mean updating dozens of related functions # threading this through all callsites (see also comment for TypeInfo.assuming). _assuming: Final[list[tuple[Type, Type]]] _assuming_proper: Final[list[tuple[Type, Type]]] # Ditto for inference of generic constraints against recursive type aliases. inferring: Final[list[tuple[Type, Type]]] # Whether to use joins or unions when solving constraints, see checkexpr.py for details. infer_unions: bool # Whether to use new type inference algorithm that can infer polymorphic types. # This is temporary and will be removed soon when new algorithm is more polished. infer_polymorphic: bool # N.B: We do all of the accesses to these properties through # TypeState, instead of making these classmethods and accessing # via the cls parameter, since mypyc can optimize accesses to # Final attributes of a directly referenced type. def __init__(self) -> None: self._subtype_caches = {} self._negative_subtype_caches = {} self.proto_deps = {} self._attempted_protocols = {} self._checked_against_members = {} self._rechecked_types = set() self._assuming = [] self._assuming_proper = [] self.inferring = [] self.infer_unions = False self.infer_polymorphic = False def is_assumed_subtype(self, left: Type, right: Type) -> bool: for l, r in reversed(self._assuming): if get_proper_type(l) == get_proper_type(left) and get_proper_type( r ) == get_proper_type(right): return True return False def is_assumed_proper_subtype(self, left: Type, right: Type) -> bool: for l, r in reversed(self._assuming_proper): if get_proper_type(l) == get_proper_type(left) and get_proper_type( r ) == get_proper_type(right): return True return False def get_assumptions(self, is_proper: bool) -> list[tuple[Type, Type]]: if is_proper: return self._assuming_proper return self._assuming def reset_all_subtype_caches(self) -> None: """Completely reset all known subtype caches.""" self._subtype_caches.clear() self._negative_subtype_caches.clear() def reset_subtype_caches_for(self, info: TypeInfo) -> None: """Reset subtype caches (if any) for a given supertype TypeInfo.""" if info in self._subtype_caches: self._subtype_caches[info].clear() if info in self._negative_subtype_caches: self._negative_subtype_caches[info].clear() def reset_all_subtype_caches_for(self, info: TypeInfo) -> None: """Reset subtype caches (if any) for a given supertype TypeInfo and its MRO.""" for item in info.mro: self.reset_subtype_caches_for(item) def is_cached_subtype_check(self, kind: SubtypeKind, left: Instance, right: Instance) -> bool: if left.last_known_value is not None or right.last_known_value is not None: # If there is a literal last known value, give up. There # will be an unbounded number of potential types to cache, # making caching less effective. return False info = right.type cache = self._subtype_caches.get(info) if cache is None: return False subcache = cache.get(kind) if subcache is None: return False return (left, right) in subcache def is_cached_negative_subtype_check( self, kind: SubtypeKind, left: Instance, right: Instance ) -> bool: if left.last_known_value is not None or right.last_known_value is not None: # If there is a literal last known value, give up. There # will be an unbounded number of potential types to cache, # making caching less effective. return False info = right.type cache = self._negative_subtype_caches.get(info) if cache is None: return False subcache = cache.get(kind) if subcache is None: return False return (left, right) in subcache def record_subtype_cache_entry( self, kind: SubtypeKind, left: Instance, right: Instance ) -> None: if left.last_known_value is not None or right.last_known_value is not None: # These are unlikely to match, due to the large space of # possible values. Avoid uselessly increasing cache sizes. return if any( (isinstance(tv, TypeVarType) and tv.variance == VARIANCE_NOT_READY) for tv in right.type.defn.type_vars ): # Variance indeterminate -- don't know the result return cache = self._subtype_caches.setdefault(right.type, {}) cache.setdefault(kind, set()).add((left, right)) def record_negative_subtype_cache_entry( self, kind: SubtypeKind, left: Instance, right: Instance ) -> None: if left.last_known_value is not None or right.last_known_value is not None: # These are unlikely to match, due to the large space of # possible values. Avoid uselessly increasing cache sizes. return if len(self._negative_subtype_caches) > MAX_NEGATIVE_CACHE_TYPES: self._negative_subtype_caches.clear() cache = self._negative_subtype_caches.setdefault(right.type, {}) subcache = cache.setdefault(kind, set()) if len(subcache) > MAX_NEGATIVE_CACHE_ENTRIES: subcache.clear() cache.setdefault(kind, set()).add((left, right)) def reset_protocol_deps(self) -> None: """Reset dependencies after a full run or before a daemon shutdown.""" self.proto_deps = {} self._attempted_protocols.clear() self._checked_against_members.clear() self._rechecked_types.clear() def record_protocol_subtype_check(self, left_type: TypeInfo, right_type: TypeInfo) -> None: assert right_type.is_protocol self._rechecked_types.add(left_type) self._attempted_protocols.setdefault(left_type.fullname, set()).add(right_type.fullname) self._checked_against_members.setdefault(left_type.fullname, set()).update( right_type.protocol_members ) def _snapshot_protocol_deps(self) -> dict[str, set[str]]: """Collect protocol attribute dependencies found so far from registered subtype checks. There are three kinds of protocol dependencies. For example, after a subtype check: x: Proto = C() the following dependencies will be generated: 1. ..., <SuperProto[wildcard]>, <Proto[wildcard]> -> <Proto> 2. ..., <B.attr>, <C.attr> -> <C> [for every attr in Proto members] 3. <C> -> Proto # this one to invalidate the subtype cache The first kind is generated immediately per-module in deps.py (see also an example there for motivation why it is needed). While two other kinds are generated here after all modules are type checked and we have recorded all the subtype checks. To understand these two kinds, consider a simple example: class A: def __iter__(self) -> Iterator[int]: ... it: Iterable[int] = A() We add <a.A.__iter__> -> <a.A> to invalidate the assignment (module target in this case), whenever the signature of a.A.__iter__ changes. We also add <a.A> -> typing.Iterable, to invalidate the subtype caches of the latter. (Note that the same logic applies to proper subtype checks, and calculating meets and joins, if this involves calling 'subtypes.is_protocol_implementation'). """ deps: dict[str, set[str]] = {} for info in self._rechecked_types: for attr in self._checked_against_members[info.fullname]: # The need for full MRO here is subtle, during an update, base classes of # a concrete class may not be reprocessed, so not all <B.x> -> <C.x> deps # are added. for base_info in info.mro[:-1]: trigger = make_trigger(f"{base_info.fullname}.{attr}") if "typing" in trigger or "builtins" in trigger: # TODO: avoid everything from typeshed continue deps.setdefault(trigger, set()).add(make_trigger(info.fullname)) for proto in self._attempted_protocols[info.fullname]: trigger = make_trigger(info.fullname) if "typing" in trigger or "builtins" in trigger: continue # If any class that was checked against a protocol changes, # we need to reset the subtype cache for the protocol. # # Note: strictly speaking, the protocol doesn't need to be # re-checked, we only need to reset the cache, and its uses # elsewhere are still valid (unless invalidated by other deps). deps.setdefault(trigger, set()).add(proto) return deps def update_protocol_deps(self, second_map: dict[str, set[str]] | None = None) -> None: """Update global protocol dependency map. We update the global map incrementally, using a snapshot only from recently type checked types. If second_map is given, update it as well. This is currently used by FineGrainedBuildManager that maintains normal (non-protocol) dependencies. """ assert self.proto_deps is not None, "This should not be called after failed cache load" new_deps = self._snapshot_protocol_deps() for trigger, targets in new_deps.items(): self.proto_deps.setdefault(trigger, set()).update(targets) if second_map is not None: for trigger, targets in new_deps.items(): second_map.setdefault(trigger, set()).update(targets) self._rechecked_types.clear() self._attempted_protocols.clear() self._checked_against_members.clear() def add_all_protocol_deps(self, deps: dict[str, set[str]]) -> None: """Add all known protocol dependencies to deps. This is used by tests and debug output, and also when collecting all collected or loaded dependencies as part of build. """ self.update_protocol_deps() # just in case if self.proto_deps is not None: for trigger, targets in self.proto_deps.items(): deps.setdefault(trigger, set()).update(targets) type_state: Final = TypeState() def reset_global_state() -> None: """Reset most existing global state. Currently most of it is in this module. Few exceptions are strict optional status and functools.lru_cache. """ type_state.reset_all_subtype_caches() type_state.reset_protocol_deps() TypeVarId.next_raw_id = 1
TypeState
python
numba__numba
numba/core/datamodel/models.py
{ "start": 25697, "end": 26456 }
class ____(StructModel): def __init__(self, dmm, fe_type): entry_type = types.SetEntry(fe_type.container) members = [ # Number of active + deleted entries ('fill', types.intp), # Number of active entries ('used', types.intp), # Allocated size - 1 (size being a power of 2) ('mask', types.intp), # Search finger ('finger', types.intp), # This member is only used only for reflected sets ('dirty', types.boolean), # Actually an inlined var-sized array ('entries', entry_type), ] super(SetPayloadModel, self).__init__(dmm, fe_type, members) @register_default(types.Set)
SetPayloadModel
python
ZoranPandovski__al-go-rithms
games/ant_colony.py
{ "start": 30, "end": 17258 }
class ____: class ant(Thread): def __init__(self, init_location, possible_locations, pheromone_map, distance_callback, alpha, beta, first_pass=False): """ initialized an ant, to traverse the map init_location -> marks where in the map that the ant starts possible_locations -> a list of possible nodes the ant can go to when used internally, gives a list of possible locations the ant can traverse to _minus those nodes already visited_ pheromone_map -> map of pheromone values for each traversal between each node distance_callback -> is a function to calculate the distance between two nodes alpha -> a parameter from the ACO algorithm to control the influence of the amount of pheromone when making a choice in _pick_path() beta -> a parameters from ACO that controls the influence of the distance to the next node in _pick_path() first_pass -> if this is a first pass on a map, then do some steps differently, noted in methods below route -> a list that is updated with the labels of the nodes that the ant has traversed pheromone_trail -> a list of pheromone amounts deposited along the ants trail, maps to each traversal in route distance_traveled -> total distance tranveled along the steps in route location -> marks where the ant currently is tour_complete -> flag to indicate the ant has completed its traversal used by get_route() and get_distance_traveled() """ Thread.__init__(self) self.init_location = init_location self.possible_locations = possible_locations self.route = [] self.distance_traveled = 0.0 self.location = init_location self.pheromone_map = pheromone_map self.distance_callback = distance_callback self.alpha = alpha self.beta = beta self.first_pass = first_pass #append start location to route, before doing random walk self._update_route(init_location) self.tour_complete = False def run(self): """ until self.possible_locations is empty (the ant has visited all nodes) _pick_path() to find a next node to traverse to _traverse() to: _update_route() (to show latest traversal) _update_distance_traveled() (after traversal) return the ants route and its distance, for use in ant_colony: do pheromone updates check for new possible optimal solution with this ants latest tour """ while self.possible_locations: next = self._pick_path() self._traverse(self.location, next) self.tour_complete = True def _pick_path(self): """ source: https://en.wikipedia.org/wiki/Ant_colony_optimization_algorithms#Edge_selection implements the path selection algorithm of ACO calculate the attractiveness of each possible transition from the current location then randomly choose a next path, based on its attractiveness """ #on the first pass (no pheromones), then we can just choice() to find the next one if self.first_pass: import random return random.choice(self.possible_locations) attractiveness = dict() sum_total = 0.0 #for each possible location, find its attractiveness (it's (pheromone amount)*1/distance [tau*eta, from the algortihm]) #sum all attrativeness amounts for calculating probability of each route in the next step for possible_next_location in self.possible_locations: #NOTE: do all calculations as float, otherwise we get integer division at times for really hard to track down bugs pheromone_amount = float(self.pheromone_map[self.location][possible_next_location]) distance = float(self.distance_callback(self.location, possible_next_location)) #tau^alpha * eta^beta attractiveness[possible_next_location] = pow(pheromone_amount, self.alpha)*pow(1/distance, self.beta) sum_total += attractiveness[possible_next_location] #it is possible to have small values for pheromone amount / distance, such that with rounding errors this is equal to zero #rare, but handle when it happens if sum_total == 0.0: #increment all zero's, such that they are the smallest non-zero values supported by the system #source: http://stackoverflow.com/a/10426033/5343977 def next_up(x): import math import struct # NaNs and positive infinity map to themselves. if math.isnan(x) or (math.isinf(x) and x > 0): return x # 0.0 and -0.0 both map to the smallest +ve float. if x == 0.0: x = 0.0 n = struct.unpack('<q', struct.pack('<d', x))[0] if n >= 0: n += 1 else: n -= 1 return struct.unpack('<d', struct.pack('<q', n))[0] for key in attractiveness: attractiveness[key] = next_up(attractiveness[key]) sum_total = next_up(sum_total) #cumulative probability behavior, inspired by: http://stackoverflow.com/a/3679747/5343977 #randomly choose the next path import random toss = random.random() cummulative = 0 for possible_next_location in attractiveness: weight = (attractiveness[possible_next_location] / sum_total) if toss <= weight + cummulative: return possible_next_location cummulative += weight def _traverse(self, start, end): """ _update_route() to show new traversal _update_distance_traveled() to record new distance traveled self.location update to new location called from run() """ self._update_route(end) self._update_distance_traveled(start, end) self.location = end def _update_route(self, new): """ add new node to self.route remove new node form self.possible_location called from _traverse() & __init__() """ self.route.append(new) self.possible_locations.remove(new) def _update_distance_traveled(self, start, end): """ use self.distance_callback to update self.distance_traveled """ self.distance_traveled += float(self.distance_callback(start, end)) def get_route(self): if self.tour_complete: return self.route return None def get_distance_traveled(self): if self.tour_complete: return self.distance_traveled return None def __init__(self, nodes, distance_callback, start=None, ant_count=50, alpha=.5, beta=1.2, pheromone_evaporation_coefficient=.40, pheromone_constant=1000.0, iterations=80): """ initializes an ant colony (houses a number of worker ants that will traverse a map to find an optimal route as per ACO [Ant Colony Optimization]) source: https://en.wikipedia.org/wiki/Ant_colony_optimization_algorithms nodes -> is assumed to be a dict() mapping node ids to values that are understandable by distance_callback distance_callback -> is assumed to take a pair of coordinates and return the distance between them populated into distance_matrix on each call to get_distance() start -> if set, then is assumed to be the node where all ants start their traversal if unset, then assumed to be the first key of nodes when sorted() distance_matrix -> holds values of distances calculated between nodes populated on demand by _get_distance() pheromone_map -> holds final values of pheromones used by ants to determine traversals pheromone dissipation happens to these values first, before adding pheromone values from the ants during their traversal (in ant_updated_pheromone_map) ant_updated_pheromone_map -> a matrix to hold the pheromone values that the ants lay down not used to dissipate, values from here are added to pheromone_map after dissipation step (reset for each traversal) alpha -> a parameter from the ACO algorithm to control the influence of the amount of pheromone when an ant makes a choice beta -> a parameters from ACO that controls the influence of the distance to the next node in ant choice making pheromone_constant -> a parameter used in depositing pheromones on the map (Q in ACO algorithm) used by _update_pheromone_map() pheromone_evaporation_coefficient -> a parameter used in removing pheromone values from the pheromone_map (rho in ACO algorithm) used by _update_pheromone_map() ants -> holds worker ants they traverse the map as per ACO notable properties: total distance traveled route first_pass -> flags a first pass for the ants, which triggers unique behavior iterations -> how many iterations to let the ants traverse the map shortest_distance -> the shortest distance seen from an ant traversal shortets_path_seen -> the shortest path seen from a traversal (shortest_distance is the distance along this path) """ #nodes if type(nodes) is not dict: raise TypeError("nodes must be dict") if len(nodes) < 1: raise ValueError("there must be at least one node in dict nodes") #create internal mapping and mapping for return to caller self.id_to_key, self.nodes = self._init_nodes(nodes) #create matrix to hold distance calculations between nodes self.distance_matrix = self._init_matrix(len(nodes)) #create matrix for master pheromone map, that records pheromone amounts along routes self.pheromone_map = self._init_matrix(len(nodes)) #create a matrix for ants to add their pheromones to, before adding those to pheromone_map during the update_pheromone_map step self.ant_updated_pheromone_map = self._init_matrix(len(nodes)) #distance_callback if not callable(distance_callback): raise TypeError("distance_callback is not callable, should be method") self.distance_callback = distance_callback #start if start is None: self.start = 0 else: self.start = None #init start to internal id of node id passed for key, value in self.id_to_key.items(): if value == start: self.start = key #if we didn't find a key in the nodes passed in, then raise if self.start is None: raise KeyError("Key: " + str(start) + " not found in the nodes dict passed.") #ant_count if type(ant_count) is not int: raise TypeError("ant_count must be int") if ant_count < 1: raise ValueError("ant_count must be >= 1") self.ant_count = ant_count #alpha if (type(alpha) is not int) and type(alpha) is not float: raise TypeError("alpha must be int or float") if alpha < 0: raise ValueError("alpha must be >= 0") self.alpha = float(alpha) #beta if (type(beta) is not int) and type(beta) is not float: raise TypeError("beta must be int or float") if beta < 1: raise ValueError("beta must be >= 1") self.beta = float(beta) #pheromone_evaporation_coefficient if (type(pheromone_evaporation_coefficient) is not int) and type(pheromone_evaporation_coefficient) is not float: raise TypeError("pheromone_evaporation_coefficient must be int or float") self.pheromone_evaporation_coefficient = float(pheromone_evaporation_coefficient) #pheromone_constant if (type(pheromone_constant) is not int) and type(pheromone_constant) is not float: raise TypeError("pheromone_constant must be int or float") self.pheromone_constant = float(pheromone_constant) #iterations if (type(iterations) is not int): raise TypeError("iterations must be int") if iterations < 0: raise ValueError("iterations must be >= 0") self.iterations = iterations #other internal variable init self.first_pass = True self.ants = self._init_ants(self.start) self.shortest_distance = None self.shortest_path_seen = None def _get_distance(self, start, end): """ uses the distance_callback to return the distance between nodes if a distance has not been calculated before, then it is populated in distance_matrix and returned if a distance has been called before, then its value is returned from distance_matrix """ if not self.distance_matrix[start][end]: distance = self.distance_callback(self.nodes[start], self.nodes[end]) if (type(distance) is not int) and (type(distance) is not float): raise TypeError("distance_callback should return either int or float, saw: "+ str(type(distance))) self.distance_matrix[start][end] = float(distance) return distance return self.distance_matrix[start][end] def _init_nodes(self, nodes): """ create a mapping of internal id numbers (0 .. n) to the keys in the nodes passed create a mapping of the id's to the values of nodes we use id_to_key to return the route in the node names the caller expects in mainloop() """ id_to_key = dict() id_to_values = dict() id = 0 for key in sorted(nodes.keys()): id_to_key[id] = key id_to_values[id] = nodes[key] id += 1 return id_to_key, id_to_values def _init_matrix(self, size, value=0.0): """ setup a matrix NxN (where n = size) used in both self.distance_matrix and self.pheromone_map as they require identical matrixes besides which value to initialize to """ ret = [] for row in range(size): ret.append([float(value) for x in range(size)]) return ret def _init_ants(self, start): """ on first pass: create a number of ant objects on subsequent passes, just call __init__ on each to reset them by default, all ants start at the first node, 0 as per problem description: https://www.codeeval.com/open_challenges/90/ """ #allocate new ants on the first pass if self.first_pass: return [self.ant(start, self.nodes.keys(), self.pheromone_map, self._get_distance, self.alpha, self.beta, first_pass=True) for x in range(self.ant_count)] #else, just reset them to use on another pass for ant in self.ants: ant.__init__(start, self.nodes.keys(), self.pheromone_map, self._get_distance, self.alpha, self.beta) def _update_pheromone_map(self): """ 1) Update self.pheromone_map by decaying values contained therein via the ACO algorithm 2) Add pheromone_values from all ants from ant_updated_pheromone_map called by: mainloop() (after all ants have traveresed) """ #always a square matrix for start in range(len(self.pheromone_map)): for end in range(len(self.pheromone_map)): #decay the pheromone value at this location #tau_xy <- (1-rho)*tau_xy (ACO) self.pheromone_map[start][end] = (1-self.pheromone_evaporation_coefficient)*self.pheromone_map[start][end] #then add all contributions to this location for each ant that travered it #(ACO) #tau_xy <- tau_xy + delta tau_xy_k # delta tau_xy_k = Q / L_k self.pheromone_map[start][end] += self.ant_updated_pheromone_map[start][end] def _populate_ant_updated_pheromone_map(self, ant): """ given an ant, populate ant_updated_pheromone_map with pheromone values according to ACO along the ant's route called from: mainloop() ( before _update_pheromone_map() ) """ route = ant.get_route() for i in range(len(route)-1): #find the pheromone over the route the ant traversed current_pheromone_value = float(self.ant_updated_pheromone_map[route[i]][route[i+1]]) #update the pheromone along that section of the route #(ACO) # delta tau_xy_k = Q / L_k new_pheromone_value = self.pheromone_constant/ant.get_distance_traveled() self.ant_updated_pheromone_map[route[i]][route[i+1]] = current_pheromone_value + new_pheromone_value self.ant_updated_pheromone_map[route[i+1]][route[i]] = current_pheromone_value + new_pheromone_value def mainloop(self): """ Runs the worker ants, collects their returns and updates the pheromone map with pheromone values from workers calls: _update_pheromones() ant.run() runs the simulation self.iterations times """ for _ in range(self.iterations): #start the multi-threaded ants, calls ant.run() in a new thread for ant in self.ants: ant.start() #source: http://stackoverflow.com/a/11968818/5343977 #wait until the ants are finished, before moving on to modifying shared resources for ant in self.ants: ant.join() for ant in self.ants: #update ant_updated_pheromone_map with this ant's constribution of pheromones along its route self._populate_ant_updated_pheromone_map(ant) #if we haven't seen any paths yet, then populate for comparisons later if not self.shortest_distance: self.shortest_distance = ant.get_distance_traveled() if not self.shortest_path_seen: self.shortest_path_seen = ant.get_route() #if we see a shorter path, then save for return if ant.get_distance_traveled() < self.shortest_distance: self.shortest_distance = ant.get_distance_traveled() self.shortest_path_seen = ant.get_route() #decay current pheromone values and add all pheromone values we saw during traversal (from ant_updated_pheromone_map) self._update_pheromone_map() #flag that we finished the first pass of the ants traversal if self.first_pass: self.first_pass = False #reset all ants to default for the next iteration self._init_ants(self.start) #reset ant_updated_pheromone_map to record pheromones for ants on next pass self.ant_updated_pheromone_map = self._init_matrix(len(self.nodes), value=0) #translate shortest path back into callers node id's ret = [] for id in self.shortest_path_seen: ret.append(self.id_to_key[id]) return ret
ant_colony
python
pyqtgraph__pyqtgraph
benchmarks/renderImageItem.py
{ "start": 696, "end": 923 }
class ____(typing.NamedTuple): sizes: list[tuple[int, int]] acceleration: list[str] uses_levels: list[bool] dtypes: list[npt.DTypeLike] channels: list[int] lut_lengths: list[npt.DTypeLike | None]
Parameters
python
doocs__leetcode
solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.py
{ "start": 0, "end": 335 }
class ____: def finalPrices(self, prices: List[int]) -> List[int]: stk = [] for i in reversed(range(len(prices))): x = prices[i] while stk and x < stk[-1]: stk.pop() if stk: prices[i] -= stk[-1] stk.append(x) return prices
Solution
python
python-excel__xlrd
xlrd/formatting.py
{ "start": 42884, "end": 43593 }
class ____(BaseObject, EqNeAttrs): """ A collection of the protection-related attributes of an ``XF`` record. Items correspond to those in the Excel UI's Format -> Cells -> Protection tab. Note the OOo docs include the "cell or style" bit in this bundle of attributes. This is incorrect; the bit is used in determining which bundles to use. .. versionadded:: 0.6.1 """ #: 1 = Cell is prevented from being changed, moved, resized, or deleted #: (only if the sheet is protected). cell_locked = 0 #: 1 = Hide formula so that it doesn't appear in the formula bar when #: the cell is selected (only if the sheet is protected). formula_hidden = 0
XFProtection
python
openai__openai-python
src/openai/resources/realtime/realtime.py
{ "start": 8525, "end": 11483 }
class ____: """Represents a live websocket connection to the Realtime API""" session: AsyncRealtimeSessionResource response: AsyncRealtimeResponseResource input_audio_buffer: AsyncRealtimeInputAudioBufferResource conversation: AsyncRealtimeConversationResource output_audio_buffer: AsyncRealtimeOutputAudioBufferResource _connection: AsyncWebsocketConnection def __init__(self, connection: AsyncWebsocketConnection) -> None: self._connection = connection self.session = AsyncRealtimeSessionResource(self) self.response = AsyncRealtimeResponseResource(self) self.input_audio_buffer = AsyncRealtimeInputAudioBufferResource(self) self.conversation = AsyncRealtimeConversationResource(self) self.output_audio_buffer = AsyncRealtimeOutputAudioBufferResource(self) async def __aiter__(self) -> AsyncIterator[RealtimeServerEvent]: """ An infinite-iterator that will continue to yield events until the connection is closed. """ from websockets.exceptions import ConnectionClosedOK try: while True: yield await self.recv() except ConnectionClosedOK: return async def recv(self) -> RealtimeServerEvent: """ Receive the next message from the connection and parses it into a `RealtimeServerEvent` object. Canceling this method is safe. There's no risk of losing data. """ return self.parse_event(await self.recv_bytes()) async def recv_bytes(self) -> bytes: """Receive the next message from the connection as raw bytes. Canceling this method is safe. There's no risk of losing data. If you want to parse the message into a `RealtimeServerEvent` object like `.recv()` does, then you can call `.parse_event(data)`. """ message = await self._connection.recv(decode=False) log.debug(f"Received websocket message: %s", message) return message async def send(self, event: RealtimeClientEvent | RealtimeClientEventParam) -> None: data = ( event.to_json(use_api_names=True, exclude_defaults=True, exclude_unset=True) if isinstance(event, BaseModel) else json.dumps(await async_maybe_transform(event, RealtimeClientEventParam)) ) await self._connection.send(data) async def close(self, *, code: int = 1000, reason: str = "") -> None: await self._connection.close(code=code, reason=reason) def parse_event(self, data: str | bytes) -> RealtimeServerEvent: """ Converts a raw `str` or `bytes` message into a `RealtimeServerEvent` object. This is helpful if you're using `.recv_bytes()`. """ return cast( RealtimeServerEvent, construct_type_unchecked(value=json.loads(data), type_=cast(Any, RealtimeServerEvent)) )
AsyncRealtimeConnection
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI059.py
{ "start": 688, "end": 1147 }
class ____( # comment about the bracket # Part 1 of multiline comment 1 # Part 2 of multiline comment 1 Generic[T] # comment about Generic[T] # PYI059 # another comment? , # comment about the comma? # part 1 of multiline comment 2 # part 2 of multiline comment 2 int, # comment about int # yet another comment? ): # and another one for good measure ... # in case of multiple Generic[] inheritance, don't fix it.
Foo
python
scipy__scipy
scipy/sparse/linalg/tests/test_expm_multiply.py
{ "start": 6597, "end": 15000 }
class ____: @pytest.mark.fail_slow(20) def test_sparse_expm_multiply_interval(self): rng = np.random.default_rng(1234) start = 0.1 stop = 3.2 n = 40 k = 3 endpoint = True for num in (14, 13, 2): A = scipy.sparse.random_array((n, n), density=0.05, rng=rng) B = rng.standard_normal((n, k)) v = rng.standard_normal((n,)) for target in (B, v): X = expm_multiply(A, target, start=start, stop=stop, num=num, endpoint=endpoint) samples = np.linspace(start=start, stop=stop, num=num, endpoint=endpoint) with warnings.catch_warnings(): warnings.filterwarnings( "ignore", "splu converted its input to CSC format", SparseEfficiencyWarning, ) warnings.filterwarnings( "ignore", "spsolve is more efficient when sparse b is in" " the CSC matrix format", SparseEfficiencyWarning, ) for solution, t in zip(X, samples): assert_allclose(solution, sp_expm(t*A).dot(target)) @pytest.mark.fail_slow(20) def test_expm_multiply_interval_vector(self): rng = np.random.default_rng(1234) interval = {'start': 0.1, 'stop': 3.2, 'endpoint': True} for num, n in product([14, 13, 2], [1, 2, 5, 20, 40]): A = scipy.linalg.inv(rng.standard_normal((n, n))) v = rng.standard_normal(n) samples = np.linspace(num=num, **interval) X = expm_multiply(A, v, num=num, **interval) for solution, t in zip(X, samples): assert_allclose(solution, sp_expm(t*A).dot(v)) # test for linear operator with unknown trace -> estimate trace with estimated_warns(): Xguess = expm_multiply(aslinearoperator(A), v, num=num, **interval) # test for linear operator with given trace Xgiven = expm_multiply(aslinearoperator(A), v, num=num, **interval, traceA=np.trace(A)) # test robustness for linear operator with wrong trace Xwrong = expm_multiply(aslinearoperator(A), v, num=num, **interval, traceA=np.trace(A)*5) for sol_guess, sol_given, sol_wrong, t in zip(Xguess, Xgiven, Xwrong, samples): correct = sp_expm(t*A).dot(v) assert_allclose(sol_guess, correct) assert_allclose(sol_given, correct) assert_allclose(sol_wrong, correct) @pytest.mark.fail_slow(20) def test_expm_multiply_interval_matrix(self): rng = np.random.default_rng(1234) interval = {'start': 0.1, 'stop': 3.2, 'endpoint': True} for num, n, k in product([14, 13, 2], [1, 2, 5, 20, 40], [1, 2]): A = scipy.linalg.inv(rng.standard_normal((n, n))) B = rng.standard_normal((n, k)) samples = np.linspace(num=num, **interval) X = expm_multiply(A, B, num=num, **interval) for solution, t in zip(X, samples): assert_allclose(solution, sp_expm(t*A).dot(B)) with estimated_warns(): X = expm_multiply(aslinearoperator(A), B, num=num, **interval) for solution, t in zip(X, samples): assert_allclose(solution, sp_expm(t*A).dot(B)) def test_sparse_expm_multiply_interval_dtypes(self): # Test A & B int A = scipy.sparse.diags_array(np.arange(5),format='csr', dtype=int) B = np.ones(5, dtype=int) Aexpm = scipy.sparse.diags_array(np.exp(np.arange(5)),format='csr') BI = np.identity(5, dtype=int) BI_sparse = scipy.sparse.csr_array(BI) assert_allclose(expm_multiply(A,B,0,1)[-1], Aexpm.dot(B)) assert_allclose(np.diag(expm_multiply(A, BI_sparse, 0, 1)[-1]), Aexpm.dot(B)) # Test A complex, B int A = scipy.sparse.diags_array(-1j*np.arange(5),format='csr', dtype=complex) B = np.ones(5, dtype=int) Aexpm = scipy.sparse.diags_array(np.exp(-1j*np.arange(5)),format='csr') assert_allclose(expm_multiply(A,B,0,1)[-1], Aexpm.dot(B)) assert_allclose(np.diag(expm_multiply(A, BI_sparse, 0, 1)[-1]), Aexpm.dot(B)) # Test A int, B complex A = scipy.sparse.diags_array(np.arange(5),format='csr', dtype=int) B = np.full(5, 1j, dtype=complex) Aexpm = scipy.sparse.diags_array(np.exp(np.arange(5)),format='csr') assert_allclose(expm_multiply(A,B,0,1)[-1], Aexpm.dot(B)) BI = np.identity(5, dtype=complex)*1j assert_allclose( np.diag(expm_multiply(A, scipy.sparse.csr_array(BI), 0, 1)[-1]), Aexpm.dot(B) ) def test_expm_multiply_interval_status_0(self): self._help_test_specific_expm_interval_status(0) def test_expm_multiply_interval_status_1(self): self._help_test_specific_expm_interval_status(1) def test_expm_multiply_interval_status_2(self): self._help_test_specific_expm_interval_status(2) def _help_test_specific_expm_interval_status(self, target_status): rng = np.random.RandomState(1234) start = 0.1 stop = 3.2 num = 13 endpoint = True n = 5 k = 2 nrepeats = 10 nsuccesses = 0 for num in [14, 13, 2] * nrepeats: A = rng.randn(n, n) B = rng.randn(n, k) status = _expm_multiply_interval(A, B, start=start, stop=stop, num=num, endpoint=endpoint, status_only=True) if status == target_status: X, status = _expm_multiply_interval(A, B, start=start, stop=stop, num=num, endpoint=endpoint, status_only=False) assert_equal(X.shape, (num, n, k)) samples = np.linspace(start=start, stop=stop, num=num, endpoint=endpoint) for solution, t in zip(X, samples): assert_allclose(solution, sp_expm(t*A).dot(B)) nsuccesses += 1 if not nsuccesses: msg = 'failed to find a status-' + str(target_status) + ' interval' raise Exception(msg) @pytest.mark.parametrize("dtype_a", DTYPES) @pytest.mark.parametrize("dtype_b", DTYPES) @pytest.mark.parametrize("b_is_matrix", [False, True]) def test_expm_multiply_dtype(dtype_a, dtype_b, b_is_matrix): """Make sure `expm_multiply` handles all numerical dtypes correctly.""" assert_allclose_ = (partial(assert_allclose, rtol=1.8e-3, atol=1e-5) if {dtype_a, dtype_b} & IMPRECISE else assert_allclose) rng = np.random.default_rng(1234) # test data n = 7 b_shape = (n, 3) if b_is_matrix else (n, ) if dtype_a in REAL_DTYPES: A = scipy.linalg.inv(rng.random([n, n])).astype(dtype_a) else: A = scipy.linalg.inv( rng.random([n, n]) + 1j*rng.random([n, n]) ).astype(dtype_a) if dtype_b in REAL_DTYPES: B = (2*rng.random(b_shape)).astype(dtype_b) else: B = (rng.random(b_shape) + 1j*rng.random(b_shape)).astype(dtype_b) # single application sol_mat = expm_multiply(A, B) with estimated_warns(): sol_op = expm_multiply(aslinearoperator(A), B) direct_sol = np.dot(sp_expm(A), B) assert_allclose_(sol_mat, direct_sol) assert_allclose_(sol_op, direct_sol) sol_op = expm_multiply(aslinearoperator(A), B, traceA=np.trace(A)) assert_allclose_(sol_op, direct_sol) # for time points interval = {'start': 0.1, 'stop': 3.2, 'num': 13, 'endpoint': True} samples = np.linspace(**interval) X_mat = expm_multiply(A, B, **interval) with estimated_warns(): X_op = expm_multiply(aslinearoperator(A), B, **interval) for sol_mat, sol_op, t in zip(X_mat, X_op, samples): direct_sol = sp_expm(t*A).dot(B) assert_allclose_(sol_mat, direct_sol) assert_allclose_(sol_op, direct_sol)
TestExpmActionInterval
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/map_test.py
{ "start": 4967, "end": 5330 }
class ____: value1: tensor.Tensor value2: tensor.Tensor def __tf_flatten__(self): metadata = tuple() components = (self.value1, self.value2) return metadata, components @classmethod def __tf_unflatten__(cls, metadata, components): del metadata return cls(value1=components[0], value2=components[1]) @dataclasses.dataclass
MyDataclass
python
celery__celery
t/unit/worker/test_state.py
{ "start": 4346, "end": 4486 }
class ____: def __init__(self, name): self.id = uuid() self.name = name @pytest.mark.usefixtures('reset_state')
SimpleReq
python
pallets__flask
src/flask/json/provider.py
{ "start": 3966, "end": 7644 }
class ____(JSONProvider): """Provide JSON operations using Python's built-in :mod:`json` library. Serializes the following additional data types: - :class:`datetime.datetime` and :class:`datetime.date` are serialized to :rfc:`822` strings. This is the same as the HTTP date format. - :class:`uuid.UUID` is serialized to a string. - :class:`dataclasses.dataclass` is passed to :func:`dataclasses.asdict`. - :class:`~markupsafe.Markup` (or any object with a ``__html__`` method) will call the ``__html__`` method to get a string. """ default: t.Callable[[t.Any], t.Any] = staticmethod(_default) """Apply this function to any object that :meth:`json.dumps` does not know how to serialize. It should return a valid JSON type or raise a ``TypeError``. """ ensure_ascii = True """Replace non-ASCII characters with escape sequences. This may be more compatible with some clients, but can be disabled for better performance and size. """ sort_keys = True """Sort the keys in any serialized dicts. This may be useful for some caching situations, but can be disabled for better performance. When enabled, keys must all be strings, they are not converted before sorting. """ compact: bool | None = None """If ``True``, or ``None`` out of debug mode, the :meth:`response` output will not add indentation, newlines, or spaces. If ``False``, or ``None`` in debug mode, it will use a non-compact representation. """ mimetype = "application/json" """The mimetype set in :meth:`response`.""" def dumps(self, obj: t.Any, **kwargs: t.Any) -> str: """Serialize data as JSON to a string. Keyword arguments are passed to :func:`json.dumps`. Sets some parameter defaults from the :attr:`default`, :attr:`ensure_ascii`, and :attr:`sort_keys` attributes. :param obj: The data to serialize. :param kwargs: Passed to :func:`json.dumps`. """ kwargs.setdefault("default", self.default) kwargs.setdefault("ensure_ascii", self.ensure_ascii) kwargs.setdefault("sort_keys", self.sort_keys) return json.dumps(obj, **kwargs) def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any: """Deserialize data as JSON from a string or bytes. :param s: Text or UTF-8 bytes. :param kwargs: Passed to :func:`json.loads`. """ return json.loads(s, **kwargs) def response(self, *args: t.Any, **kwargs: t.Any) -> Response: """Serialize the given arguments as JSON, and return a :class:`~flask.Response` object with it. The response mimetype will be "application/json" and can be changed with :attr:`mimetype`. If :attr:`compact` is ``False`` or debug mode is enabled, the output will be formatted to be easier to read. Either positional or keyword arguments can be given, not both. If no arguments are given, ``None`` is serialized. :param args: A single value to serialize, or multiple values to treat as a list to serialize. :param kwargs: Treat as a dict to serialize. """ obj = self._prepare_response_obj(args, kwargs) dump_args: dict[str, t.Any] = {} if (self.compact is None and self._app.debug) or self.compact is False: dump_args.setdefault("indent", 2) else: dump_args.setdefault("separators", (",", ":")) return self._app.response_class( f"{self.dumps(obj, **dump_args)}\n", mimetype=self.mimetype )
DefaultJSONProvider
python
langchain-ai__langchain
libs/langchain/langchain_classic/chat_models/base.py
{ "start": 23049, "end": 38094 }
class ____(Runnable[LanguageModelInput, Any]): def __init__( self, *, default_config: dict | None = None, configurable_fields: Literal["any"] | list[str] | tuple[str, ...] = "any", config_prefix: str = "", queued_declarative_operations: Sequence[tuple[str, tuple, dict]] = (), ) -> None: self._default_config: dict = default_config or {} self._configurable_fields: Literal["any"] | list[str] = ( configurable_fields if configurable_fields == "any" else list(configurable_fields) ) self._config_prefix = ( config_prefix + "_" if config_prefix and not config_prefix.endswith("_") else config_prefix ) self._queued_declarative_operations: list[tuple[str, tuple, dict]] = list( queued_declarative_operations, ) def __getattr__(self, name: str) -> Any: if name in _DECLARATIVE_METHODS: # Declarative operations that cannot be applied until after an actual model # object is instantiated. So instead of returning the actual operation, # we record the operation and its arguments in a queue. This queue is # then applied in order whenever we actually instantiate the model (in # self._model()). def queue(*args: Any, **kwargs: Any) -> _ConfigurableModel: queued_declarative_operations = list( self._queued_declarative_operations, ) queued_declarative_operations.append((name, args, kwargs)) return _ConfigurableModel( default_config=dict(self._default_config), configurable_fields=list(self._configurable_fields) if isinstance(self._configurable_fields, list) else self._configurable_fields, config_prefix=self._config_prefix, queued_declarative_operations=queued_declarative_operations, ) return queue if self._default_config and (model := self._model()) and hasattr(model, name): return getattr(model, name) msg = f"{name} is not a BaseChatModel attribute" if self._default_config: msg += " and is not implemented on the default model" msg += "." raise AttributeError(msg) def _model(self, config: RunnableConfig | None = None) -> Runnable: params = {**self._default_config, **self._model_params(config)} model = _init_chat_model_helper(**params) for name, args, kwargs in self._queued_declarative_operations: model = getattr(model, name)(*args, **kwargs) return model def _model_params(self, config: RunnableConfig | None) -> dict: config = ensure_config(config) model_params = { k.removeprefix(self._config_prefix): v for k, v in config.get("configurable", {}).items() if k.startswith(self._config_prefix) } if self._configurable_fields != "any": model_params = { k: v for k, v in model_params.items() if k in self._configurable_fields } return model_params def with_config( self, config: RunnableConfig | None = None, **kwargs: Any, ) -> _ConfigurableModel: """Bind config to a `Runnable`, returning a new `Runnable`.""" config = RunnableConfig(**(config or {}), **cast("RunnableConfig", kwargs)) model_params = self._model_params(config) remaining_config = {k: v for k, v in config.items() if k != "configurable"} remaining_config["configurable"] = { k: v for k, v in config.get("configurable", {}).items() if k.removeprefix(self._config_prefix) not in model_params } queued_declarative_operations = list(self._queued_declarative_operations) if remaining_config: queued_declarative_operations.append( ( "with_config", (), {"config": remaining_config}, ), ) return _ConfigurableModel( default_config={**self._default_config, **model_params}, configurable_fields=list(self._configurable_fields) if isinstance(self._configurable_fields, list) else self._configurable_fields, config_prefix=self._config_prefix, queued_declarative_operations=queued_declarative_operations, ) @property @override def InputType(self) -> TypeAlias: """Get the input type for this `Runnable`.""" from langchain_core.prompt_values import ( ChatPromptValueConcrete, StringPromptValue, ) # This is a version of LanguageModelInput which replaces the abstract # base class BaseMessage with a union of its subclasses, which makes # for a much better schema. return str | StringPromptValue | ChatPromptValueConcrete | list[AnyMessage] @override def invoke( self, input: LanguageModelInput, config: RunnableConfig | None = None, **kwargs: Any, ) -> Any: return self._model(config).invoke(input, config=config, **kwargs) @override async def ainvoke( self, input: LanguageModelInput, config: RunnableConfig | None = None, **kwargs: Any, ) -> Any: return await self._model(config).ainvoke(input, config=config, **kwargs) @override def stream( self, input: LanguageModelInput, config: RunnableConfig | None = None, **kwargs: Any | None, ) -> Iterator[Any]: yield from self._model(config).stream(input, config=config, **kwargs) @override async def astream( self, input: LanguageModelInput, config: RunnableConfig | None = None, **kwargs: Any | None, ) -> AsyncIterator[Any]: async for x in self._model(config).astream(input, config=config, **kwargs): yield x def batch( self, inputs: list[LanguageModelInput], config: RunnableConfig | list[RunnableConfig] | None = None, *, return_exceptions: bool = False, **kwargs: Any | None, ) -> list[Any]: config = config or None # If <= 1 config use the underlying models batch implementation. if config is None or isinstance(config, dict) or len(config) <= 1: if isinstance(config, list): config = config[0] return self._model(config).batch( inputs, config=config, return_exceptions=return_exceptions, **kwargs, ) # If multiple configs default to Runnable.batch which uses executor to invoke # in parallel. return super().batch( inputs, config=config, return_exceptions=return_exceptions, **kwargs, ) async def abatch( self, inputs: list[LanguageModelInput], config: RunnableConfig | list[RunnableConfig] | None = None, *, return_exceptions: bool = False, **kwargs: Any | None, ) -> list[Any]: config = config or None # If <= 1 config use the underlying models batch implementation. if config is None or isinstance(config, dict) or len(config) <= 1: if isinstance(config, list): config = config[0] return await self._model(config).abatch( inputs, config=config, return_exceptions=return_exceptions, **kwargs, ) # If multiple configs default to Runnable.batch which uses executor to invoke # in parallel. return await super().abatch( inputs, config=config, return_exceptions=return_exceptions, **kwargs, ) def batch_as_completed( self, inputs: Sequence[LanguageModelInput], config: RunnableConfig | Sequence[RunnableConfig] | None = None, *, return_exceptions: bool = False, **kwargs: Any, ) -> Iterator[tuple[int, Any | Exception]]: config = config or None # If <= 1 config use the underlying models batch implementation. if config is None or isinstance(config, dict) or len(config) <= 1: if isinstance(config, list): config = config[0] yield from self._model(cast("RunnableConfig", config)).batch_as_completed( # type: ignore[call-overload] inputs, config=config, return_exceptions=return_exceptions, **kwargs, ) # If multiple configs default to Runnable.batch which uses executor to invoke # in parallel. else: yield from super().batch_as_completed( # type: ignore[call-overload] inputs, config=config, return_exceptions=return_exceptions, **kwargs, ) async def abatch_as_completed( self, inputs: Sequence[LanguageModelInput], config: RunnableConfig | Sequence[RunnableConfig] | None = None, *, return_exceptions: bool = False, **kwargs: Any, ) -> AsyncIterator[tuple[int, Any]]: config = config or None # If <= 1 config use the underlying models batch implementation. if config is None or isinstance(config, dict) or len(config) <= 1: if isinstance(config, list): config = config[0] async for x in self._model( cast("RunnableConfig", config), ).abatch_as_completed( # type: ignore[call-overload] inputs, config=config, return_exceptions=return_exceptions, **kwargs, ): yield x # If multiple configs default to Runnable.batch which uses executor to invoke # in parallel. else: async for x in super().abatch_as_completed( # type: ignore[call-overload] inputs, config=config, return_exceptions=return_exceptions, **kwargs, ): yield x @override def transform( self, input: Iterator[LanguageModelInput], config: RunnableConfig | None = None, **kwargs: Any | None, ) -> Iterator[Any]: yield from self._model(config).transform(input, config=config, **kwargs) @override async def atransform( self, input: AsyncIterator[LanguageModelInput], config: RunnableConfig | None = None, **kwargs: Any | None, ) -> AsyncIterator[Any]: async for x in self._model(config).atransform(input, config=config, **kwargs): yield x @overload def astream_log( self, input: Any, config: RunnableConfig | None = None, *, diff: Literal[True] = True, with_streamed_output_list: bool = True, include_names: Sequence[str] | None = None, include_types: Sequence[str] | None = None, include_tags: Sequence[str] | None = None, exclude_names: Sequence[str] | None = None, exclude_types: Sequence[str] | None = None, exclude_tags: Sequence[str] | None = None, **kwargs: Any, ) -> AsyncIterator[RunLogPatch]: ... @overload def astream_log( self, input: Any, config: RunnableConfig | None = None, *, diff: Literal[False], with_streamed_output_list: bool = True, include_names: Sequence[str] | None = None, include_types: Sequence[str] | None = None, include_tags: Sequence[str] | None = None, exclude_names: Sequence[str] | None = None, exclude_types: Sequence[str] | None = None, exclude_tags: Sequence[str] | None = None, **kwargs: Any, ) -> AsyncIterator[RunLog]: ... @override async def astream_log( self, input: Any, config: RunnableConfig | None = None, *, diff: bool = True, with_streamed_output_list: bool = True, include_names: Sequence[str] | None = None, include_types: Sequence[str] | None = None, include_tags: Sequence[str] | None = None, exclude_names: Sequence[str] | None = None, exclude_types: Sequence[str] | None = None, exclude_tags: Sequence[str] | None = None, **kwargs: Any, ) -> AsyncIterator[RunLogPatch] | AsyncIterator[RunLog]: async for x in self._model(config).astream_log( # type: ignore[call-overload, misc] input, config=config, diff=diff, with_streamed_output_list=with_streamed_output_list, include_names=include_names, include_types=include_types, include_tags=include_tags, exclude_tags=exclude_tags, exclude_types=exclude_types, exclude_names=exclude_names, **kwargs, ): yield x @override async def astream_events( self, input: Any, config: RunnableConfig | None = None, *, version: Literal["v1", "v2"] = "v2", include_names: Sequence[str] | None = None, include_types: Sequence[str] | None = None, include_tags: Sequence[str] | None = None, exclude_names: Sequence[str] | None = None, exclude_types: Sequence[str] | None = None, exclude_tags: Sequence[str] | None = None, **kwargs: Any, ) -> AsyncIterator[StreamEvent]: async for x in self._model(config).astream_events( input, config=config, version=version, include_names=include_names, include_types=include_types, include_tags=include_tags, exclude_tags=exclude_tags, exclude_types=exclude_types, exclude_names=exclude_names, **kwargs, ): yield x # Explicitly added to satisfy downstream linters. def bind_tools( self, tools: Sequence[dict[str, Any] | type[BaseModel] | Callable | BaseTool], **kwargs: Any, ) -> Runnable[LanguageModelInput, AIMessage]: return self.__getattr__("bind_tools")(tools, **kwargs) # Explicitly added to satisfy downstream linters. def with_structured_output( self, schema: dict | type[BaseModel], **kwargs: Any, ) -> Runnable[LanguageModelInput, dict | BaseModel]: return self.__getattr__("with_structured_output")(schema, **kwargs)
_ConfigurableModel
python
pytorch__pytorch
torch/_inductor/exc.py
{ "start": 1293, "end": 1890 }
class ____(OperatorIssue): def __init__(self, target: Any, args: list[Any], kwargs: dict[str, Any]) -> None: _record_missing_op(target) super().__init__( f"missing decomposition\n{self.operator_str(target, args, kwargs)}" + textwrap.dedent( f""" There is a decomposition available for {target} in torch._decomp.get_decompositions(). Please add this operator to the `decompositions` list in torch._inductor.decomposition """ ) )
MissingOperatorWithDecomp
python
django__django
tests/gis_tests/layermap/models.py
{ "start": 43, "end": 210 }
class ____(models.Model): name = models.CharField(max_length=25) class Meta: abstract = True def __str__(self): return self.name
NamedModel
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/commands/ci/state.py
{ "start": 2007, "end": 2424 }
class ____(metaclass=ABCMeta): @abstractmethod def load(self, location_name: str) -> LocationState: ... @abstractmethod def save(self, location_state: LocationState): ... @abstractmethod def list_locations(self) -> list[LocationState]: ... def list_selected_locations(self) -> list[LocationState]: return [location for location in self.list_locations() if location.selected]
Store
python
lxml__lxml
src/lxml/tests/test_elementpath.py
{ "start": 457, "end": 15107 }
class ____(HelperTestCase): etree = etree from lxml import _elementpath _empty_namespaces = None def test_cache(self): self._elementpath._cache.clear() el = self.etree.XML(b'<a><b><c/><c/></b></a>') self.assertFalse(self._elementpath._cache) self.assertTrue(el.findall('b/c')) self.assertEqual(1, len(self._elementpath._cache)) self.assertTrue(el.findall('b/c')) self.assertEqual(1, len(self._elementpath._cache)) self.assertFalse(el.findall('xxx')) self.assertEqual(2, len(self._elementpath._cache)) self.assertFalse(el.findall('xxx')) self.assertEqual(2, len(self._elementpath._cache)) self.assertTrue(el.findall('b/c')) self.assertEqual(2, len(self._elementpath._cache)) def _assert_tokens(self, tokens, path, namespaces=None): if namespaces is None: namespaces = self._empty_namespaces self.assertEqual(tokens, list(self._elementpath.xpath_tokenizer(path, namespaces))) def test_tokenizer(self): assert_tokens = self._assert_tokens assert_tokens( [('/', '')], '/', ) assert_tokens( [('.', ''), ('/', ''), ('', 'a'), ('/', ''), ('', 'b'), ('/', ''), ('', 'c')], './a/b/c', ) assert_tokens( [('/', ''), ('', 'a'), ('/', ''), ('', 'b'), ('/', ''), ('', 'c')], '/a/b/c', ) assert_tokens( [('/', ''), ('', '{nsx}a'), ('/', ''), ('', '{nsy}b'), ('/', ''), ('', 'c')], '/x:a/y:b/c', {'x': 'nsx', 'y': 'nsy'}, ) assert_tokens( [('/', ''), ('', '{nsx}a'), ('/', ''), ('', '{nsy}b'), ('/', ''), ('', '{nsnone}c')], '/x:a/y:b/c', {'x': 'nsx', 'y': 'nsy', None: 'nsnone'}, ) def test_tokenizer_predicates(self): assert_tokens = self._assert_tokens assert_tokens( [('', 'a'), ('[', ''), ('', 'b'), (']', '')], 'a[b]', ) assert_tokens( [('', 'a'), ('[', ''), ('', 'b'), ('=', ''), ('"abc"', ''), (']', '')], 'a[b="abc"]', ) assert_tokens( [('', 'a'), ('[', ''), ('.', ''), ('', ''), ('=', ''), ('', ''), ('"abc"', ''), (']', '')], 'a[. = "abc"]', ) def test_tokenizer_index(self): assert_tokens = self._assert_tokens assert_tokens( [('/', ''), ('', 'a'), ('/', ''), ('', 'b'), ('/', ''), ('', 'c'), ('[', ''), ('', '1'), (']', '')], '/a/b/c[1]', ) assert_tokens( [('/', ''), ('', '{nsnone}a'), ('/', ''), ('', '{nsnone}b'), ('/', ''), ('', '{nsnone}c'), ('[', ''), ('', '1'), (']', '')], '/a/b/c[1]', namespaces={None:'nsnone'}, ) assert_tokens( [('/', ''), ('', '{nsnone}a'), ('/', ''), ('', '{nsnone}b'), ('[', ''), ('', '2'), (']', ''), ('/', ''), ('', '{nsnone}c'), ('[', ''), ('', '1'), (']', '')], '/a/b[2]/c[1]', namespaces={None:'nsnone'}, ) assert_tokens( [('/', ''), ('', '{nsnone}a'), ('/', ''), ('', '{nsnone}b'), ('[', ''), ('', '100'), (']', '')], '/a/b[100]', namespaces={None:'nsnone'} ) def test_xpath_tokenizer(self): # Test the XPath tokenizer. Copied from CPython's "test_xml_etree.py" ElementPath = self._elementpath def check(p, expected, namespaces=self._empty_namespaces): self.assertEqual([op or tag for op, tag in ElementPath.xpath_tokenizer(p, namespaces)], expected) # tests from the xml specification check("*", ['*']) check("text()", ['text', '()']) check("@name", ['@', 'name']) check("@*", ['@', '*']) check("para[1]", ['para', '[', '1', ']']) check("para[last()]", ['para', '[', 'last', '()', ']']) check("*/para", ['*', '/', 'para']) check("/doc/chapter[5]/section[2]", ['/', 'doc', '/', 'chapter', '[', '5', ']', '/', 'section', '[', '2', ']']) check("chapter//para", ['chapter', '//', 'para']) check("//para", ['//', 'para']) check("//olist/item", ['//', 'olist', '/', 'item']) check(".", ['.']) check(".//para", ['.', '//', 'para']) check("..", ['..']) check("../@lang", ['..', '/', '@', 'lang']) check("chapter[title]", ['chapter', '[', 'title', ']']) check("employee[@secretary and @assistant]", ['employee', '[', '@', 'secretary', '', 'and', '', '@', 'assistant', ']']) # additional tests check("@{ns}attr", ['@', '{ns}attr']) check("{http://spam}egg", ['{http://spam}egg']) check("./spam.egg", ['.', '/', 'spam.egg']) check(".//{http://spam}egg", ['.', '//', '{http://spam}egg']) # wildcard tags check("{ns}*", ['{ns}*']) check("{}*", ['{}*']) check("{*}tag", ['{*}tag']) check("{*}*", ['{*}*']) check(".//{*}tag", ['.', '//', '{*}tag']) # namespace prefix resolution check("./xsd:type", ['.', '/', '{http://www.w3.org/2001/XMLSchema}type'], {'xsd': 'http://www.w3.org/2001/XMLSchema'}) check("type", ['{http://www.w3.org/2001/XMLSchema}type'], {'': 'http://www.w3.org/2001/XMLSchema'}) check("@xsd:type", ['@', '{http://www.w3.org/2001/XMLSchema}type'], {'xsd': 'http://www.w3.org/2001/XMLSchema'}) check("@type", ['@', 'type'], {'': 'http://www.w3.org/2001/XMLSchema'}) check("@{*}type", ['@', '{*}type'], {'': 'http://www.w3.org/2001/XMLSchema'}) check("@{ns}attr", ['@', '{ns}attr'], {'': 'http://www.w3.org/2001/XMLSchema', 'ns': 'http://www.w3.org/2001/XMLSchema'}) if self.etree is etree: check("/doc/section[2]", ['/', '{http://www.w3.org/2001/XMLSchema}doc', '/', '{http://www.w3.org/2001/XMLSchema}section', '[', '2', ']'], {"":"http://www.w3.org/2001/XMLSchema"} ) check("/doc/section[2]", ['/', '{http://www.w3.org/2001/XMLSchema}doc', '/', '{http://www.w3.org/2001/XMLSchema}section', '[', '2', ']'], {None:"http://www.w3.org/2001/XMLSchema"} ) check("/ns:doc/ns:section[2]", ['/', '{http://www.w3.org/2001/XMLSchema}doc', '/', '{http://www.w3.org/2001/XMLSchema}section', '[', '2', ']'], {"ns":"http://www.w3.org/2001/XMLSchema"} ) def test_find(self): """ Test find methods (including xpath syntax). Originally copied from 'selftest.py'. """ elem = etree.XML(""" <body> <tag class='a'>text</tag> <tag class='b' /> <section> <tag class='b' id='inner'>subtext</tag> </section> </body> """) self.assertEqual(elem.find("tag").tag, 'tag') self.assertEqual(etree.ElementTree(elem).find("tag").tag, 'tag') self.assertEqual(elem.find("section/tag").tag, 'tag') self.assertEqual(etree.ElementTree(elem).find("section/tag").tag, 'tag') self.assertEqual(elem.findtext("tag"), 'text') self.assertEqual(elem.findtext("tog"), None) self.assertEqual(elem.findtext("tog", "default"), 'default') self.assertEqual(etree.ElementTree(elem).findtext("tag"), 'text') self.assertEqual(elem.findtext("section/tag"), 'subtext') self.assertEqual(etree.ElementTree(elem).findtext("section/tag"), 'subtext') self.assertEqual(summarize_list(elem.findall("tag")), ['tag', 'tag']) self.assertEqual(summarize_list(elem.findall("*")), ['tag', 'tag', 'section']) self.assertEqual(summarize_list(elem.findall(".//tag")), ['tag', 'tag', 'tag']) self.assertEqual(summarize_list(elem.findall("section/tag")), ['tag']) self.assertEqual(summarize_list(elem.findall("section//tag")), ['tag']) self.assertEqual(summarize_list(elem.findall("section/*")), ['tag']) self.assertEqual(summarize_list(elem.findall("section//*")), ['tag']) self.assertEqual(summarize_list(elem.findall("section/.//*")), ['tag']) self.assertEqual(summarize_list(elem.findall("*/*")), ['tag']) self.assertEqual(summarize_list(elem.findall("*//*")), ['tag']) self.assertEqual(summarize_list(elem.findall("*/tag")), ['tag']) self.assertEqual(summarize_list(elem.findall("*/./tag")), ['tag']) self.assertEqual(summarize_list(elem.findall("./tag")), ['tag', 'tag']) self.assertEqual(summarize_list(elem.findall(".//tag")), ['tag', 'tag', 'tag']) self.assertEqual(summarize_list(elem.findall("././tag")), ['tag', 'tag']) self.assertEqual(summarize_list(elem.findall(".//tag[@class]")), ['tag', 'tag', 'tag']) self.assertEqual(summarize_list(elem.findall(".//tag[ @class]")), ['tag', 'tag', 'tag']) self.assertEqual(summarize_list(elem.findall(".//tag[@class ]")), ['tag', 'tag', 'tag']) self.assertEqual(summarize_list(elem.findall(".//tag[ @class ]")), ['tag', 'tag', 'tag']) self.assertEqual(summarize_list(elem.findall(".//tag[@class='a']")), ['tag']) self.assertEqual(summarize_list(elem.findall('.//tag[@class="a"]')), ['tag']) self.assertEqual(summarize_list(elem.findall(".//tag[@class='b']")), ['tag', 'tag']) self.assertEqual(summarize_list(elem.findall('.//tag[@class="b"]')), ['tag', 'tag']) self.assertEqual(summarize_list(elem.findall('.//tag[@class = "b"]')), ['tag', 'tag']) self.assertEqual(summarize_list(elem.findall(".//tag[@id]")), ['tag']) self.assertEqual(summarize_list(elem.findall(".//tag[@class][@id]")), ['tag']) self.assertEqual(summarize_list(elem.findall(".//section[tag]")), ['section']) self.assertEqual(summarize_list(elem.findall(".//section[element]")), []) self.assertEqual(summarize_list(elem.findall(".//section[tag='subtext']")), ['section']) self.assertEqual(summarize_list(elem.findall(".//section[tag ='subtext']")), ['section']) self.assertEqual(summarize_list(elem.findall(".//section[tag= 'subtext']")), ['section']) self.assertEqual(summarize_list(elem.findall(".//section[tag = 'subtext']")), ['section']) self.assertEqual(summarize_list(elem.findall(".//section[ tag = 'subtext' ]")), ['section']) self.assertEqual(summarize_list(elem.findall(".//tag[.='subtext']")), ['tag']) self.assertEqual(summarize_list(elem.findall(".//tag[. ='subtext']")), ['tag']) self.assertEqual(summarize_list(elem.findall('.//tag[.= "subtext"]')), ['tag']) self.assertEqual(summarize_list(elem.findall(".//tag[. = 'subtext']")), ['tag']) self.assertEqual(summarize_list(elem.findall(".//tag[. = 'subtext ']")), []) self.assertEqual(summarize_list(elem.findall(".//tag[.= ' subtext']")), []) self.assertEqual(summarize_list(elem.findall("../tag")), []) self.assertEqual(summarize_list(elem.findall("section/../tag")), ['tag', 'tag']) self.assertEqual(summarize_list(etree.ElementTree(elem).findall("./tag")), ['tag', 'tag']) self.assertEqual(summarize_list(etree.ElementTree(elem).findall("/tag")), ['tag', 'tag']) # This would be correct: if False: self.assertEqual(summarize_list(etree.ElementTree(elem).findall("/body")), ['body']) # duplicate section => 2x tag matches elem[1] = deepcopy(elem[2]) self.assertEqual(summarize_list(elem.findall(".//section[tag = 'subtext']")), ['section', 'section']) self.assertEqual(summarize_list(elem.findall(".//tag[. = 'subtext']")), ['tag', 'tag']) self.assertEqual(summarize_list(elem.findall(".//tag[@class][@id]")), ['tag', 'tag']) def test_find_warning(self): etree = self.etree elem = etree.XML(""" <body> <tag class='a'>text</tag> <tag class='b' /> <section> <tag class='b' id='inner'>subtext</tag> </section> </body> """) # FIXME: ET's Path module handles this case incorrectly; this gives # a warning in 1.3, and the behaviour will be modified in the future. self.assertWarnsRegex( FutureWarning, ".*If you rely on the current behaviour, change it to './tag'", etree.ElementTree(elem).findall, "/tag") self.assertWarnsRegex( FutureWarning, ".*If you rely on the current behaviour, change it to './tag'", etree.ElementTree(elem).findtext, "/tag") self.assertWarnsRegex( FutureWarning, ".*If you rely on the current behaviour, change it to './tag'", etree.ElementTree(elem).find, "/tag") self.assertWarnsRegex( FutureWarning, ".*If you rely on the current behaviour, change it to './tag'", etree.ElementTree(elem).iterfind, "/tag")
EtreeElementPathTestCase
python
Pylons__pyramid
docs/tutorials/wiki2/src/authorization/tutorial/routes.py
{ "start": 1545, "end": 1817 }
class ____: def __init__(self, page): self.page = page def __acl__(self): return [ (Allow, Everyone, 'view'), (Allow, 'role:editor', 'edit'), (Allow, 'u:' + str(self.page.creator_id), 'edit'), ]
PageResource
python
sphinx-doc__sphinx
sphinx/search/hu.py
{ "start": 197, "end": 610 }
class ____(SearchLanguage): lang = 'hu' language_name = 'Hungarian' js_stemmer_rawcode = 'hungarian-stemmer.js' stopwords = HUNGARIAN_STOPWORDS def __init__(self, options: dict[str, str]) -> None: super().__init__(options) self.stemmer = snowballstemmer.stemmer('hungarian') def stem(self, word: str) -> str: return self.stemmer.stemWord(word.lower())
SearchHungarian
python
great-expectations__great_expectations
tests/expectations/test_condition_validators.py
{ "start": 463, "end": 1834 }
class ____: """Tests for AndCondition validator when passed to Expectation.""" def test_flatten_nested_and_conditions(self): """Test that nested AndConditions are flattened when passed to Expectation.""" column_1 = Column("column_1") column_2 = Column("column_2") column_3 = Column("column_3") row_condition = (column_1 < 8) & ((column_2 > 8) & (column_3 == 8)) # Pass to an Expectation - should flatten expectation = ExpectColumnValuesToBeInSet( column="test_column", value_set=["a", "b"], row_condition=row_condition ) # Verify flattening occurred - should have 3 conditions instead of nested structure assert len(expectation.row_condition.conditions) == 3 def test_error_on_or_within_and(self): """Test that OrConditions nested within AndConditions raise error in Expectation.""" column_1 = Column("column_1") column_2 = Column("column_2") column_3 = Column("column_3") # OR within AND row_condition = (column_1 < 8) & ((column_2 > 8) | (column_3 == 8)) with pytest.raises(ValueError, match="AND groups cannot contain OR conditions"): ExpectColumnValuesToBeInSet( column="test_column", value_set=["a", "b"], row_condition=row_condition )
TestAndConditionValidator
python
python__mypy
mypyc/ir/ops.py
{ "start": 39695, "end": 40517 }
class ____(RegisterOp): """result = truncate src from src_type to dst_type Truncate a value from type with more bits to type with less bits. dst_type and src_type can be native integer types, bools or tagged integers. Tagged integers should have the tag bit unset. """ error_kind = ERR_NEVER def __init__(self, src: Value, dst_type: RType, line: int = -1) -> None: super().__init__(line) self.src = src self.type = dst_type self.src_type = src.type def sources(self) -> list[Value]: return [self.src] def set_sources(self, new: list[Value]) -> None: (self.src,) = new def stolen(self) -> list[Value]: return [] def accept(self, visitor: OpVisitor[T]) -> T: return visitor.visit_truncate(self) @final
Truncate
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F811_18.py
{ "start": 151, "end": 306 }
class ____(unittest.TestCase): def test_get_transport(self): transport = 'transport' self.assertIsNotNone(transport)
GetTransportTestCase
python
pytorch__pytorch
torch/_dynamo/utils.py
{ "start": 5042, "end": 5140 }
class ____(enum.Enum): AUTO_FUNC_V1 = 1 AUTO_FUNC_V2 = 2 TRITON_OPS = 3
ReInplaceTrigger
python
pypa__pip
docs/pip_sphinxext.py
{ "start": 6849, "end": 7886 }
class ____(PipOptions): def determine_opt_prefix(self, opt_name: str) -> str: for command in commands_dict: cmd = create_command(command) if cmd.cmd_opts.has_option(opt_name): return command raise KeyError(f"Could not identify prefix of opt {opt_name}") def process_options(self) -> None: for option in SUPPORTED_OPTIONS: if getattr(option, "deprecated", False): continue opt = option() opt_name = opt._long_opts[0] if opt._short_opts: short_opt_name = f"{opt._short_opts[0]}, " else: short_opt_name = "" if option in cmdoptions.general_group["options"]: prefix = "" else: prefix = f"{self.determine_opt_prefix(opt_name)}_" self.view_list.append( f"* :ref:`{short_opt_name}{opt_name}<{prefix}{opt_name}>`", "\n", )
PipReqFileOptionsReference
python
openai__openai-python
src/openai/types/responses/response_file_search_call_completed_event.py
{ "start": 213, "end": 671 }
class ____(BaseModel): item_id: str """The ID of the output item that the file search call is initiated.""" output_index: int """The index of the output item that the file search call is initiated.""" sequence_number: int """The sequence number of this event.""" type: Literal["response.file_search_call.completed"] """The type of the event. Always `response.file_search_call.completed`."""
ResponseFileSearchCallCompletedEvent
python
wandb__wandb
wandb/sdk/launch/wandb_reference.py
{ "start": 756, "end": 4253 }
class ____: # TODO: This will include port, should we separate that out? host: Optional[str] = None entity: Optional[str] = None project: Optional[str] = None # Set when we don't know how to parse yet path: Optional[str] = None # Reference type will determine what other fields are set ref_type: Optional[ReferenceType] = None run_id: Optional[str] = None job_name: Optional[str] = None job_alias: str = "latest" # In addition to an alias can be a version specifier def is_bare(self) -> bool: return self.host is None def is_job(self) -> bool: return self.ref_type == ReferenceType.JOB def is_run(self) -> bool: return self.ref_type == ReferenceType.RUN def is_job_or_run(self) -> bool: return self.is_job() or self.is_run() def job_reference(self) -> str: assert self.is_job() return f"{self.job_name}:{self.job_alias}" def job_reference_scoped(self) -> str: assert self.entity assert self.project unscoped = self.job_reference() return f"{self.entity}/{self.project}/{unscoped}" def url_host(self) -> str: return f"{PREFIX_HTTPS}{self.host}" if self.host else "" def url_entity(self) -> str: assert self.entity return f"{self.url_host()}/{self.entity}" def url_project(self) -> str: assert self.project return f"{self.url_entity()}/{self.project}" @staticmethod def parse(uri: str) -> Optional["WandbReference"]: """Attempt to parse a string as a W&B URL.""" # TODO: Error if HTTP and host is not localhost? if ( not uri.startswith("/") and not uri.startswith(PREFIX_HTTP) and not uri.startswith(PREFIX_HTTPS) ): return None ref = WandbReference() # This takes care of things like query and fragment parsed = urlparse(uri) if parsed.netloc: ref.host = parsed.netloc if not parsed.path.startswith("/"): return ref ref.path = parsed.path[1:] parts = ref.path.split("/") if len(parts) > 0: if parts[0] not in RESERVED_NON_ENTITIES: ref.path = None ref.entity = parts[0] if len(parts) > 1: if parts[1] not in RESERVED_NON_PROJECTS: ref.project = parts[1] if len(parts) > 3 and parts[2] == "runs": ref.ref_type = ReferenceType.RUN ref.run_id = parts[3] elif ( len(parts) > 4 and parts[2] == "artifacts" and parts[3] == "job" ): ref.ref_type = ReferenceType.JOB ref.job_name = parts[4] if len(parts) > 5 and parts[5] not in RESERVED_JOB_PATHS: ref.job_alias = parts[5] # TODO: Right now we are not tracking selection as part of URL state in the Jobs tab. # If that changes we'll want to update this. return ref @staticmethod def is_uri_job_or_run(uri: str) -> bool: ref = WandbReference.parse(uri) if ref and ref.is_job_or_run(): return True return False
WandbReference
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format29.py
{ "start": 315, "end": 2028 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format29.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "line"}) chart.axis_ids = [108652416, 108655744] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$B$1:$B$5", "trendline": { "type": "polynomial", "name": "My trend name", "order": 2, "forward": 0.5, "backward": 0.5, "display_equation": True, "display_r_squared": True, "line": { "color": "red", "width": 1, "dash_type": "long_dash", }, }, } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
keras-team__keras
keras/src/layers/pooling/base_global_pooling.py
{ "start": 123, "end": 1491 }
class ____(Layer): """Base global pooling layer.""" def __init__( self, pool_dimensions, data_format=None, keepdims=False, **kwargs ): super().__init__(**kwargs) self.data_format = backend.standardize_data_format(data_format) self.keepdims = keepdims self.input_spec = InputSpec(ndim=pool_dimensions + 2) self._build_at_init() def call(self, inputs): raise NotImplementedError def compute_output_shape(self, input_shape): num_spatial_dims = len(input_shape) - 2 if self.data_format == "channels_last": if self.keepdims: return ( (input_shape[0],) + (1,) * num_spatial_dims + (input_shape[-1],) ) else: return (input_shape[0],) + (input_shape[-1],) else: if self.keepdims: return (input_shape[0], input_shape[1]) + ( 1, ) * num_spatial_dims else: return (input_shape[0], input_shape[1]) def get_config(self): config = super().get_config() config.update( { "data_format": self.data_format, "keepdims": self.keepdims, } ) return config
BaseGlobalPooling
python
getsentry__sentry
tests/sentry/api/serializers/test_team.py
{ "start": 465, "end": 9750 }
class ____(TestCase): def test_simple(self) -> None: user = self.create_user(username="foo") organization = self.create_organization() team = self.create_team(organization=organization) result = serialize(team, user) result.pop("dateCreated") assert result == { "id": str(team.id), "slug": team.slug, "name": team.name, "access": TEAM_CONTRIBUTOR["scopes"], "hasAccess": True, "isPending": False, "isMember": False, "teamRole": None, "flags": {"idp:provisioned": False}, "avatar": {"avatarType": "letter_avatar", "avatarUuid": None}, "memberCount": 0, } def test_member_count(self) -> None: user = self.create_user(username="foo") other_user = self.create_user(username="bar") third_user = self.create_user(username="baz") # Inactive users are not included in the member count inactive_user = self.create_user(username="qux", is_active=False) organization = self.create_organization(owner=user) team = self.create_team( organization=organization, members=[user, other_user, third_user, inactive_user], ) result = serialize(team, user) assert result["memberCount"] == 3 def test_member_count_does_not_include_invite_requests(self) -> None: org = self.create_organization(owner=self.user) team = self.create_team(organization=org) self.create_member(user=self.create_user(), organization=org, teams=[team]) # member self.create_member(email="1@example.com", organization=org, teams=[team]) # pending invite result = serialize(team, self.user) assert result["memberCount"] == 2 # invite requests self.create_member( email="2@example.com", organization=org, invite_status=InviteStatus.REQUESTED_TO_BE_INVITED.value, teams=[team], ) self.create_member( email="3@gmail.com", organization=org, invite_status=InviteStatus.REQUESTED_TO_JOIN.value, teams=[team], ) result = serialize(team, self.user) assert result["memberCount"] == 2 def test_member(self) -> None: user = self.create_user(username="foo") organization = self.create_organization() team = self.create_team(organization=organization) self.create_member(user=user, organization=organization) result = serialize(team, user) assert result["access"] == TEAM_CONTRIBUTOR["scopes"] assert result["hasAccess"] is True assert result["isMember"] is False assert result["teamRole"] is None organization.flags.allow_joinleave = False organization.save() result = serialize(team, user) # after changing to allow_joinleave=False assert result["access"] == set() assert result["hasAccess"] is False assert result["isMember"] is False assert result["teamRole"] is None self.create_team_membership(user=user, team=team) result = serialize(team, user) # after giving them access to team assert result["access"] == TEAM_CONTRIBUTOR["scopes"] assert result["hasAccess"] is True assert result["isMember"] is True assert result["teamRole"] == TEAM_CONTRIBUTOR["id"] def test_member_with_team_role(self) -> None: user = self.create_user(username="foo") organization = self.create_organization() team = self.create_team(organization=organization) self.create_member(user=user, organization=organization) result = serialize(team, user) assert result["access"] == TEAM_CONTRIBUTOR["scopes"] assert result["hasAccess"] is True assert result["isMember"] is False assert result["teamRole"] is None organization.flags.allow_joinleave = False organization.save() result = serialize(team, user) # after changing to allow_joinleave=False assert result["access"] == set() assert result["hasAccess"] is False assert result["isMember"] is False assert result["teamRole"] is None self.create_team_membership(user=user, team=team, role="admin") result = serialize(team, user) # after giving them access to team assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is True assert result["teamRole"] == TEAM_ADMIN["id"] def test_admin(self) -> None: user = self.create_user(username="foo") organization = self.create_organization() team = self.create_team(organization=organization) self.create_member(user=user, organization=organization, role="admin") result = serialize(team, user) assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is False assert result["teamRole"] is None organization.flags.allow_joinleave = False organization.save() result = serialize(team, user) # after changing to allow_joinleave=False assert result["access"] == set() assert result["hasAccess"] is False assert result["isMember"] is False assert result["teamRole"] is None self.create_team_membership(user=user, team=team, role=None) result = serialize(team, user) # after giving them access to team assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is True assert result["teamRole"] == TEAM_ADMIN["id"] def test_manager(self) -> None: user = self.create_user(username="foo") organization = self.create_organization() self.create_member(user=user, organization=organization, role="manager") team = self.create_team(organization=organization) result = serialize(team, user) assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is False assert result["teamRole"] is None organization.flags.allow_joinleave = False organization.save() result = serialize(team, user) # after changing to allow_joinleave=False assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is False assert result["teamRole"] is None self.create_team_membership(user=user, team=team, role=None) result = serialize(team, user) # after giving them access to team assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is True assert result["teamRole"] == TEAM_ADMIN["id"] def test_owner(self) -> None: user = self.create_user(username="foo") organization = self.create_organization() self.create_member(user=user, organization=organization, role="owner") team = self.create_team(organization=organization) result = serialize(team, user) assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is False assert result["teamRole"] is None organization.flags.allow_joinleave = False organization.save() result = serialize(team, user) # after changing to allow_joinleave=False assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is False assert result["teamRole"] is None self.create_team_membership(user=user, team=team, role=None) result = serialize(team, user) # after giving them access to team assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is True assert result["teamRole"] == TEAM_ADMIN["id"] def test_superuser(self) -> None: user = self.create_user(username="foo", is_superuser=True) organization = self.create_organization() team = self.create_team(organization=organization) req = self.make_request() req.user = user req.superuser.set_logged_in(req.user) with env.active_request(req): result = serialize(team, user) assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is False assert result["teamRole"] is None organization.flags.allow_joinleave = False organization.save() result = serialize(team, user) # after changing to allow_joinleave=False assert result["access"] == TEAM_ADMIN["scopes"] assert result["hasAccess"] is True assert result["isMember"] is False assert result["teamRole"] is None
TeamSerializerTest
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-robots-within-budget.py
{ "start": 923, "end": 1723 }
class ____(object): def maximumRobots(self, chargeTimes, runningCosts, budget): """ :type chargeTimes: List[int] :type runningCosts: List[int] :type budget: int :rtype: int """ result = left = curr = 0 dq = collections.deque() for right in xrange(len(chargeTimes)): while dq and chargeTimes[dq[-1]] <= chargeTimes[right]: dq.pop() dq.append(right) curr += runningCosts[right] while dq and chargeTimes[dq[0]]+(right-left+1)*curr > budget: if dq[0] == left: dq.popleft() curr -= runningCosts[left] left += 1 result = max(result, right-left+1) return result
Solution2
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py
{ "start": 32965, "end": 46635 }
class ____: @pytest.mark.usefixtures("configure_git_connection_for_dag_bundle") def test_list_dag_runs_return_200(self, test_client, session): with assert_queries_count(5): response = test_client.post("/dags/~/dagRuns/list", json={}) assert response.status_code == 200 body = response.json() assert body["total_entries"] == 4 for each in body["dag_runs"]: run = session.query(DagRun).where(DagRun.run_id == each["dag_run_id"]).one() expected = get_dag_run_dict(run) assert each == expected def test_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.post("/dags/~/dagRuns/list", json={}) assert response.status_code == 401 def test_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.post("/dags/~/dagRuns/list", json={}) assert response.status_code == 403 def test_list_dag_runs_with_invalid_dag_id(self, test_client): response = test_client.post("/dags/invalid/dagRuns/list", json={}) assert response.status_code == 422 body = response.json() assert body["detail"] == [ { "type": "literal_error", "loc": ["path", "dag_id"], "msg": "Input should be '~'", "input": "invalid", "ctx": {"expected": "'~'"}, } ] @pytest.mark.parametrize( ("dag_ids", "status_code", "expected_dag_id_list"), [ ([], 200, DAG_RUNS_LIST), ([DAG1_ID], 200, [DAG1_RUN1_ID, DAG1_RUN2_ID]), [["invalid"], 200, []], ], ) @pytest.mark.usefixtures("configure_git_connection_for_dag_bundle") def test_list_dag_runs_with_dag_ids_filter(self, test_client, dag_ids, status_code, expected_dag_id_list): with assert_queries_count(5): response = test_client.post("/dags/~/dagRuns/list", json={"dag_ids": dag_ids}) assert response.status_code == status_code assert set([each["dag_run_id"] for each in response.json()["dag_runs"]]) == set(expected_dag_id_list) def test_invalid_order_by_raises_400(self, test_client): response = test_client.post("/dags/~/dagRuns/list", json={"order_by": "invalid"}) assert response.status_code == 400 body = response.json() assert ( body["detail"] == "Ordering with 'invalid' is disallowed or the attribute does not exist on the model" ) @pytest.mark.parametrize( ("order_by", "expected_order"), [ pytest.param("id", DAG_RUNS_LIST, id="order_by_id"), pytest.param( "state", [DAG1_RUN2_ID, DAG1_RUN1_ID, DAG2_RUN1_ID, DAG2_RUN2_ID], id="order_by_state" ), pytest.param("dag_id", DAG_RUNS_LIST, id="order_by_dag_id"), pytest.param("run_after", DAG_RUNS_LIST, id="order_by_run_after"), pytest.param("logical_date", DAG_RUNS_LIST, id="order_by_logical_date"), pytest.param("dag_run_id", DAG_RUNS_LIST, id="order_by_dag_run_id"), pytest.param("start_date", DAG_RUNS_LIST, id="order_by_start_date"), pytest.param("end_date", DAG_RUNS_LIST, id="order_by_end_date"), pytest.param("updated_at", DAG_RUNS_LIST, id="order_by_updated_at"), pytest.param("conf", DAG_RUNS_LIST, id="order_by_conf"), ], ) @pytest.mark.usefixtures("configure_git_connection_for_dag_bundle") def test_dag_runs_ordering(self, test_client, order_by, expected_order): # Test ascending order response = test_client.post("/dags/~/dagRuns/list", json={"order_by": order_by}) assert response.status_code == 200 body = response.json() assert body["total_entries"] == 4 assert [run["dag_run_id"] for run in body["dag_runs"]] == expected_order # Test descending order response = test_client.post("/dags/~/dagRuns/list", json={"order_by": f"-{order_by}"}) assert response.status_code == 200 body = response.json() assert body["total_entries"] == 4 assert [run["dag_run_id"] for run in body["dag_runs"]] == expected_order[::-1] @pytest.mark.parametrize( ("post_body", "expected_dag_id_order"), [ ({}, DAG_RUNS_LIST), ({"page_limit": 1}, DAG_RUNS_LIST[:1]), ({"page_limit": 3}, DAG_RUNS_LIST[:3]), ({"page_offset": 1}, DAG_RUNS_LIST[1:]), ({"page_offset": 5}, []), ({"page_limit": 1, "page_offset": 1}, DAG_RUNS_LIST[1:2]), ({"page_limit": 1, "page_offset": 2}, DAG_RUNS_LIST[2:3]), ], ) @pytest.mark.usefixtures("configure_git_connection_for_dag_bundle") def test_limit_and_offset(self, test_client, post_body, expected_dag_id_order): response = test_client.post("/dags/~/dagRuns/list", json=post_body) assert response.status_code == 200 body = response.json() assert body["total_entries"] == 4 assert [each["dag_run_id"] for each in body["dag_runs"]] == expected_dag_id_order @pytest.mark.parametrize( ("post_body", "expected_detail"), [ ( {"page_limit": 1, "page_offset": -1}, [ { "type": "greater_than_equal", "loc": ["body", "page_offset"], "msg": "Input should be greater than or equal to 0", "input": -1, "ctx": {"ge": 0}, } ], ), ( {"page_limit": -1, "page_offset": 1}, [ { "type": "greater_than_equal", "loc": ["body", "page_limit"], "msg": "Input should be greater than or equal to 0", "input": -1, "ctx": {"ge": 0}, } ], ), ( {"page_limit": -1, "page_offset": -1}, [ { "type": "greater_than_equal", "loc": ["body", "page_offset"], "msg": "Input should be greater than or equal to 0", "input": -1, "ctx": {"ge": 0}, }, { "type": "greater_than_equal", "loc": ["body", "page_limit"], "msg": "Input should be greater than or equal to 0", "input": -1, "ctx": {"ge": 0}, }, ], ), ], ) def test_bad_limit_and_offset(self, test_client, post_body, expected_detail): response = test_client.post("/dags/~/dagRuns/list", json=post_body) assert response.status_code == 422 assert response.json()["detail"] == expected_detail @pytest.mark.parametrize( ("post_body", "expected_dag_id_list"), [ ( {"logical_date_gte": LOGICAL_DATE1.isoformat()}, DAG_RUNS_LIST, ), ({"logical_date_lte": LOGICAL_DATE3.isoformat()}, DAG_RUNS_LIST[:3]), ( { "start_date_gte": START_DATE1.isoformat(), "start_date_lte": (START_DATE2 - timedelta(days=1)).isoformat(), }, [DAG1_RUN1_ID, DAG1_RUN2_ID], ), ( { "end_date_gte": START_DATE2.isoformat(), # 2024-04-15 "end_date_lte": (datetime.now(tz=timezone.utc) + timedelta(days=1)).isoformat(), }, # Only DAG2 runs match: their start_date is 2024-04-15, so end_date >= 2024-04-15 # DAG1 runs have start_date 2024-01-15, so end_date < 2024-04-15 [DAG2_RUN1_ID, DAG2_RUN2_ID], ), ( { "logical_date_gte": LOGICAL_DATE1.isoformat(), "logical_date_lte": LOGICAL_DATE2.isoformat(), }, [DAG1_RUN1_ID, DAG1_RUN2_ID], ), ( { "start_date_gte": START_DATE2.isoformat(), "end_date_lte": (datetime.now(tz=timezone.utc) + timedelta(days=1)).isoformat(), }, [DAG2_RUN1_ID, DAG2_RUN2_ID], ), ( {"states": [DagRunState.SUCCESS.value]}, [DAG1_RUN1_ID, DAG2_RUN1_ID, DAG2_RUN2_ID], ), ({"states": [DagRunState.FAILED.value]}, [DAG1_RUN2_ID]), ( { "states": [DagRunState.SUCCESS.value], "logical_date_gte": LOGICAL_DATE2.isoformat(), }, DAG_RUNS_LIST[2:], ), ( { "states": [DagRunState.FAILED.value], "start_date_gte": START_DATE1.isoformat(), }, [DAG1_RUN2_ID], ), ], ) @pytest.mark.usefixtures("configure_git_connection_for_dag_bundle") def test_filters(self, test_client, post_body, expected_dag_id_list): response = test_client.post("/dags/~/dagRuns/list", json=post_body) assert response.status_code == 200 body = response.json() assert [each["dag_run_id"] for each in body["dag_runs"]] == expected_dag_id_list def test_bad_filters(self, test_client): post_body = { "logical_date_gte": "invalid", "start_date_gte": "invalid", "end_date_gte": "invalid", "logical_date_lte": "invalid", "start_date_lte": "invalid", "end_date_lte": "invalid", "dag_ids": "invalid", } expected_detail = [ { "input": "invalid", "loc": ["body", "dag_ids"], "msg": "Input should be a valid list", "type": "list_type", }, { "type": "datetime_from_date_parsing", "loc": ["body", "logical_date_gte"], "msg": "Input should be a valid datetime or date, input is too short", "input": "invalid", "ctx": {"error": "input is too short"}, }, { "type": "datetime_from_date_parsing", "loc": ["body", "logical_date_lte"], "msg": "Input should be a valid datetime or date, input is too short", "input": "invalid", "ctx": {"error": "input is too short"}, }, { "type": "datetime_from_date_parsing", "loc": ["body", "start_date_gte"], "msg": "Input should be a valid datetime or date, input is too short", "input": "invalid", "ctx": {"error": "input is too short"}, }, { "type": "datetime_from_date_parsing", "loc": ["body", "start_date_lte"], "msg": "Input should be a valid datetime or date, input is too short", "input": "invalid", "ctx": {"error": "input is too short"}, }, { "type": "datetime_from_date_parsing", "loc": ["body", "end_date_gte"], "msg": "Input should be a valid datetime or date, input is too short", "input": "invalid", "ctx": {"error": "input is too short"}, }, { "type": "datetime_from_date_parsing", "loc": ["body", "end_date_lte"], "msg": "Input should be a valid datetime or date, input is too short", "input": "invalid", "ctx": {"error": "input is too short"}, }, ] response = test_client.post("/dags/~/dagRuns/list", json=post_body) assert response.status_code == 422 body = response.json() assert body["detail"] == expected_detail @pytest.mark.parametrize( ("post_body", "expected_response"), [ ( {"states": ["invalid"]}, [ { "type": "enum", "loc": ["body", "states", 0], "msg": "Input should be 'queued', 'running', 'success' or 'failed'", "input": "invalid", "ctx": {"expected": "'queued', 'running', 'success' or 'failed'"}, } ], ), ( {"states": "invalid"}, [ { "type": "list_type", "loc": ["body", "states"], "msg": "Input should be a valid list", "input": "invalid", } ], ), ], ) def test_invalid_state(self, test_client, post_body, expected_response): response = test_client.post("/dags/~/dagRuns/list", json=post_body) assert response.status_code == 422 assert response.json()["detail"] == expected_response
TestListDagRunsBatch
python
doocs__leetcode
solution/2500-2599/2529.Maximum Count of Positive Integer and Negative Integer/Solution.py
{ "start": 0, "end": 167 }
class ____: def maximumCount(self, nums: List[int]) -> int: a = sum(x > 0 for x in nums) b = sum(x < 0 for x in nums) return max(a, b)
Solution
python
scipy__scipy
scipy/linalg/tests/test_lapack.py
{ "start": 17206, "end": 17813 }
class ____: # 'lower' argument of dportf/dpotri @pytest.mark.parametrize("lower", [True, False]) @pytest.mark.parametrize("clean", [True, False]) def test_gh_2691(self, lower, clean): rng = np.random.default_rng(42) x = rng.normal(size=(3, 3)) a = x.dot(x.T) dpotrf, dpotri = get_lapack_funcs(("potrf", "potri"), (a, )) c, _ = dpotrf(a, lower, clean=clean) dpt = dpotri(c, lower)[0] if lower: assert_allclose(np.tril(dpt), np.tril(inv(a))) else: assert_allclose(np.triu(dpt), np.triu(inv(a)))
TestDpotr
python
huggingface__transformers
tests/models/unispeech_sat/test_modeling_unispeech_sat.py
{ "start": 28353, "end": 33898 }
class ____(unittest.TestCase): def _load_datasamples(self, num_samples): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") # automatic decoding with librispeech speech_samples = ds.sort("id").filter( lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def _load_superb(self, task, num_samples): ds = load_dataset("anton-l/superb_dummy", task, split="test") return ds[:num_samples] def test_inference_encoder_base(self): model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-base-plus") model.to(torch_device) feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "facebook/wav2vec2-base", return_attention_mask=True ) input_speech = self._load_datasamples(2) inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) with torch.no_grad(): outputs = model( inputs_dict.input_values.to(torch_device), attention_mask=inputs_dict.attention_mask.to(torch_device), ) # fmt: off expected_hidden_states_slice = torch.tensor( [[[-0.0743, 0.1384], [-0.0845, 0.1704]], [[-0.0954, 0.1936], [-0.1123, 0.2095]]], device=torch_device, ) # fmt: on torch.testing.assert_close( outputs.last_hidden_state[:, :2, -2:], expected_hidden_states_slice, rtol=1e-3, atol=1e-3 ) def test_inference_encoder_large(self): model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-large") model.to(torch_device) feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("facebook/wav2vec2-large-xlsr-53") input_speech = self._load_datasamples(2) inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) with torch.no_grad(): outputs = model( inputs_dict.input_values.to(torch_device), attention_mask=inputs_dict.attention_mask.to(torch_device), ) # fmt: off expected_hidden_states_slice = torch.tensor( [[[-0.1172, -0.0797], [-0.0012, 0.0213]], [[-0.1225, -0.1277], [-0.0668, -0.0585]]], device=torch_device, ) # fmt: on torch.testing.assert_close( outputs.last_hidden_state[:, :2, -2:], expected_hidden_states_slice, rtol=1e-3, atol=1e-3 ) def test_inference_diarization(self): model = UniSpeechSatForAudioFrameClassification.from_pretrained("microsoft/unispeech-sat-base-plus-sd").to( torch_device ) processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/unispeech-sat-base-plus-sd") input_data = self._load_superb("sd", 4) inputs = processor(input_data["speech"], return_tensors="pt", padding=True, sampling_rate=16_000) input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): outputs = model(input_values, attention_mask=attention_mask) # labels is a one-hot array of shape (num_frames, num_speakers) labels = (outputs.logits > 0).long() # s3prl logits for the same batch expected_logits = torch.tensor( [ [[-5.6119, -5.5845], [-3.7772, -5.4824], [-3.6914, -5.1619], [-4.7560, -5.0496]], [[-6.3785, -4.8365], [-5.5863, -5.4149], [-5.5639, -4.8469], [-6.1511, -4.0052]], [[-6.0355, -3.7414], [-5.5968, -4.8061], [-5.4620, -4.7310], [-5.5864, -4.6078]], [[-5.9493, -4.8963], [-4.4050, -5.4476], [-4.1755, -5.1395], [-4.0272, -4.3705]], ], device=torch_device, ) self.assertEqual(labels[0, :, 0].sum(), 270) self.assertEqual(labels[0, :, 1].sum(), 647) torch.testing.assert_close(outputs.logits[:, :4], expected_logits, rtol=1e-2, atol=1e-2) def test_inference_speaker_verification(self): model = UniSpeechSatForXVector.from_pretrained("microsoft/unispeech-sat-base-plus-sv").to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/unispeech-sat-base-plus-sv") input_data = self._load_superb("si", 4) inputs = processor(input_data["speech"], return_tensors="pt", padding=True) labels = torch.tensor([5, 1, 1, 3], device=torch_device).T with torch.no_grad(): input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) outputs = model(input_values, attention_mask=attention_mask, labels=labels) embeddings = torch.nn.functional.normalize(outputs.embeddings, dim=-1) cosine_sim = torch.nn.CosineSimilarity(dim=-1) # id10002 vs id10002 self.assertAlmostEqual(cosine_sim(embeddings[1], embeddings[2]).item(), 0.9671, 3) # id10006 vs id10002 self.assertAlmostEqual(cosine_sim(embeddings[0], embeddings[1]).item(), 0.4941, 3) # id10002 vs id10004 self.assertAlmostEqual(cosine_sim(embeddings[2], embeddings[3]).item(), 0.5616, 3) self.assertAlmostEqual(outputs.loss.item(), 18.5925, 2)
UniSpeechSatModelIntegrationTest
python
walkccc__LeetCode
solutions/128. Longest Consecutive Sequence/128.py
{ "start": 0, "end": 336 }
class ____: def longestConsecutive(self, nums: list[int]) -> int: ans = 0 seen = set(nums) for num in seen: # `num` is the start of a sequence. if num - 1 in seen: continue length = 0 while num in seen: num += 1 length += 1 ans = max(ans, length) return ans
Solution
python
openai__openai-python
src/openai/types/realtime/conversation_item_truncate_event.py
{ "start": 234, "end": 944 }
class ____(BaseModel): audio_end_ms: int """Inclusive duration up to which audio is truncated, in milliseconds. If the audio_end_ms is greater than the actual audio duration, the server will respond with an error. """ content_index: int """The index of the content part to truncate. Set this to `0`.""" item_id: str """The ID of the assistant message item to truncate. Only assistant message items can be truncated. """ type: Literal["conversation.item.truncate"] """The event type, must be `conversation.item.truncate`.""" event_id: Optional[str] = None """Optional client-generated ID used to identify this event."""
ConversationItemTruncateEvent
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 30290, "end": 32502 }
class ____(TestFrozenSet): thetype = FrozenSetSubclass basetype = frozenset def test_keywords_in_subclass(self): with torch._dynamo.error_on_graph_break(False): class subclass(frozenset): pass u = subclass([1, 2]) self.assertIs(type(u), subclass) self.assertEqual(set(u), {1, 2}) with self.assertRaises(TypeError): subclass(sequence=()) with torch._dynamo.error_on_graph_break(False): class subclass_with_init(frozenset): def __init__(self, arg, newarg=None): self.newarg = newarg u = subclass_with_init([1, 2], newarg=3) self.assertIs(type(u), subclass_with_init) self.assertEqual(set(u), {1, 2}) self.assertEqual(u.newarg, 3) with torch._dynamo.error_on_graph_break(False): class subclass_with_new(frozenset): def __new__(cls, arg, newarg=None): self = super().__new__(cls, arg) self.newarg = newarg return self u = subclass_with_new([1, 2], newarg=3) self.assertIs(type(u), subclass_with_new) self.assertEqual(set(u), {1, 2}) self.assertEqual(u.newarg, 3) def test_constructor_identity(self): s = self.thetype(range(3)) t = self.thetype(s) self.assertNotEqual(id(s), id(t)) def test_copy(self): dup = self.s.copy() self.assertNotEqual(id(self.s), id(dup)) def test_nested_empty_constructor(self): s = self.thetype() t = self.thetype(s) self.assertEqual(s, t) def test_singleton_empty_frozenset(self): Frozenset = self.thetype f = frozenset() F = Frozenset() efs = [Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''), Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''), Frozenset(range(0)), Frozenset(Frozenset()), Frozenset(frozenset()), f, F, Frozenset(f), Frozenset(F)] # All empty frozenset subclass instances should have different ids self.assertEqual(len(set(map(id, efs))), len(efs))
TestFrozenSetSubclass
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_quote_name06.py
{ "start": 314, "end": 1509 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("quote_name06.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) sheet_name = "Sheet-1" worksheet = workbook.add_worksheet(sheet_name) chart = workbook.add_chart({"type": "column"}) chart.axis_ids = [62284544, 83429248] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) worksheet.repeat_rows(0, 1) worksheet.set_portrait() worksheet.vertical_dpi = 200 chart.add_series({"values": [sheet_name, 0, 0, 4, 0]}) chart.add_series({"values": [sheet_name, 0, 1, 4, 1]}) chart.add_series({"values": [sheet_name, 0, 2, 4, 2]}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0087_relink_crons_to_compatible_issue_workflows.py
{ "start": 978, "end": 1338 }
class ____: """Represents a condition with its type, comparison, and result.""" type: str comparison: dict[str, Any] result: bool def to_dict(self) -> dict[str, Any]: return { "type": self.type, "comparison": self.comparison, "result": self.result, } @dataclass(frozen=True)
ConditionData
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 40998, "end": 44364 }
class ____(nn.Module): def __init__(self, config: Qwen3OmniMoeVisionEncoderConfig) -> None: super().__init__() self.dim = config.hidden_size self.num_heads = config.num_heads self.head_dim = self.dim // self.num_heads self.num_key_value_groups = 1 # needed for eager attention self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True) self.proj = nn.Linear(self.dim, self.dim) self.scaling = self.head_dim**-0.5 self.config = config self.attention_dropout = 0.0 self.is_causal = False def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, rotary_pos_emb: Optional[torch.Tensor] = None, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, **kwargs, ) -> torch.Tensor: seq_length = hidden_states.shape[0] query_states, key_states, value_states = ( self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0) ) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin) query_states = query_states.transpose(0, 1).unsqueeze(0) key_states = key_states.transpose(0, 1).unsqueeze(0) value_states = value_states.transpose(0, 1).unsqueeze(0) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] if self.config._attn_implementation == "flash_attention_2": # Flash Attention 2: Use cu_seqlens for variable length attention max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max() attn_output, _ = attention_interface( self, query_states, key_states, value_states, attention_mask=None, scaling=self.scaling, dropout=0.0 if not self.training else self.attention_dropout, cu_seq_lens_q=cu_seqlens, cu_seq_lens_k=cu_seqlens, max_length_q=max_seqlen, max_length_k=max_seqlen, is_causal=False, **kwargs, ) else: # Other implementations: Process each chunk separately lengths = cu_seqlens[1:] - cu_seqlens[:-1] splits = [ torch.split(tensor, lengths.tolist(), dim=2) for tensor in (query_states, key_states, value_states) ] attn_outputs = [ attention_interface( self, q, k, v, attention_mask=None, scaling=self.scaling, dropout=0.0 if not self.training else self.attention_dropout, is_causal=False, **kwargs, )[0] for q, k, v in zip(*splits) ] attn_output = torch.cat(attn_outputs, dim=1) attn_output = attn_output.reshape(seq_length, -1).contiguous() attn_output = self.proj(attn_output) return attn_output
Qwen3OmniMoeVisionAttention
python
pypa__pip
tests/unit/test_utils.py
{ "start": 11452, "end": 12527 }
class ____: on_unix = pytest.mark.skipif("sys.platform == 'win32'") on_win32 = pytest.mark.skipif("sys.platform != 'win32'") @pytest.mark.parametrize( "path, fake_cwd, expected", [ pytest.param( *("/home/name/project", Path("/home/name"), "./project"), marks=on_unix, ), pytest.param( *("/home", Path("/home/name"), "/home"), marks=on_unix, id="not-go-up", ), pytest.param( *("C:\\Name\\Project", Path("C:\\Name"), ".\\Project"), marks=on_win32, ), pytest.param( *("D:\\Data", Path("C:\\Name"), "D:\\Data"), marks=on_win32, ), ], ) def test_display(self, path: str, fake_cwd: Path, expected: str) -> None: with patch("pathlib.Path.cwd") as cwd_func: cwd_func.return_value = fake_cwd got = display_path(path) assert got == expected
Test_display_path
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/streams.py
{ "start": 26005, "end": 26463 }
class ____(SemiIncrementalMixin, GithubStream): """ API docs: https://docs.github.com/en/rest/issues/milestones?apiVersion=2022-11-28#list-milestones """ is_sorted = "desc" stream_base_params = { "state": "all", "sort": "updated", "direction": "desc", } def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str: return f"repos/{stream_slice['repository']}/milestones"
IssueMilestones
python
cython__cython
Cython/Compiler/Symtab.py
{ "start": 1710, "end": 1965 }
class ____: writable_needed = False def __init__(self, buflocal_nd_var, rcbuf_var): self.buflocal_nd_var = buflocal_nd_var self.rcbuf_var = rcbuf_var def __repr__(self): return "<BufferAux %r>" % self.__dict__
BufferAux
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0087_relink_crons_to_compatible_issue_workflows.py
{ "start": 13585, "end": 14993 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = True dependencies = [ ("workflow_engine", "0086_fix_cron_to_cron_workflow_links"), ("monitors", "0009_backfill_monitor_detectors"), ] operations = [ migrations.RunPython( link_crons_to_compatible_issue_workflows, migrations.RunPython.noop, hints={"tables": ["workflow_engine_detectorworkflow"]}, ), ]
Migration
python
huggingface__transformers
src/transformers/data/processors/glue.py
{ "start": 7778, "end": 8444 }
class ____(MnliProcessor): """Processor for the MultiNLI Mismatched data set (GLUE version).""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning) def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev_mismatched.tsv")), "dev_mismatched") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples(self._read_tsv(os.path.join(data_dir, "test_mismatched.tsv")), "test_mismatched")
MnliMismatchedProcessor
python
astropy__astropy
astropy/units/core.py
{ "start": 85166, "end": 94703 }
class ____(NamedTuple): """Prefix for representing multiples or sub-multiples of units. Parameters ---------- symbols : tuple of str The symbols of the prefix, to be combined with symbols of units. If multiple are specified then they will be treated as aliases. names : tuple of str The names of the prefix, to be combined with names of units. If multiple are specified then they will be treated as aliases. factor : `~astropy.units.typing.UnitScale` The multiplicative factor represented by the prefix. Examples -------- >>> UnitPrefix(("k",), ("kilo",), 1e3) # Simple prefix UnitPrefix(symbols=('k',), names=('kilo',), factor=1000.0) >>> UnitPrefix(("da",), ("deca", "deka"), 1e1) # Multiple names UnitPrefix(symbols=('da',), names=('deca', 'deka'), factor=10.0) >>> UnitPrefix(("u", "\N{MICRO SIGN}"), ("micro",), 1e-6) # Multiple symbols UnitPrefix(symbols=('u', 'µ'), names=('micro',), factor=1e-06) """ symbols: tuple[str, ...] "The symbols of the prefix, to be combined with symbols of units." names: tuple[str, ...] "The names of the prefix, to be combined with names of units." factor: UnitScale "The multiplicative factor represented by the prefix." si_prefixes: Final = tuple( UnitPrefix(symbols, names, factor) for symbols, names, factor in ( (("Q",), ("quetta",), 1e30), (("R",), ("ronna",), 1e27), (("Y",), ("yotta",), 1e24), (("Z",), ("zetta",), 1e21), (("E",), ("exa",), 1e18), (("P",), ("peta",), 1e15), (("T",), ("tera",), 1e12), (("G",), ("giga",), 1e9), (("M",), ("mega",), 1e6), (("k",), ("kilo",), 1e3), (("h",), ("hecto",), 1e2), (("da",), ("deka", "deca"), 1e1), (("d",), ("deci",), 1e-1), (("c",), ("centi",), 1e-2), (("m",), ("milli",), 1e-3), (("u", "\N{MICRO SIGN}", "\N{GREEK SMALL LETTER MU}"), ("micro",), 1e-6), (("n",), ("nano",), 1e-9), (("p",), ("pico",), 1e-12), (("f",), ("femto",), 1e-15), (("a",), ("atto",), 1e-18), (("z",), ("zepto",), 1e-21), (("y",), ("yocto",), 1e-24), (("r",), ("ronto",), 1e-27), (("q",), ("quecto",), 1e-30), ) ) binary_prefixes: Final = tuple( UnitPrefix(symbols, names, factor) for symbols, names, factor in ( (("Ki",), ("kibi",), 2**10), (("Mi",), ("mebi",), 2**20), (("Gi",), ("gibi",), 2**30), (("Ti",), ("tebi",), 2**40), (("Pi",), ("pebi",), 2**50), (("Ei",), ("exbi",), 2**60), (("Zi",), ("zebi",), 2**70), (("Yi",), ("yobi",), 2**80), ) ) def _add_prefixes( u: NamedUnit, excludes: Collection[str] = (), namespace: MutableMapping[str, object] | None = None, prefixes: bool | Iterable[UnitPrefix] = False, ) -> None: """ Set up all of the standard metric prefixes for a unit. This function should not be used directly, but instead use the `prefixes` kwarg on `def_unit` See the documentation of that function for the description of the parameters. """ if prefixes is True: prefixes = si_prefixes elif prefixes is False: prefixes = [] for short, full, factor in prefixes: names = [] format = {} for prefix in short: if prefix in excludes: continue for alias in u.short_names: names.append(prefix + alias) # This is a hack to use Greek mu as a prefix # for some formatters. if prefix == "u": format["latex"] = r"\mu " + u._get_format_name("latex") format["unicode"] = "\N{MICRO SIGN}" + u._get_format_name("unicode") for key, val in u._format.items(): format.setdefault(key, prefix + val) for prefix in full: if prefix in excludes: continue for alias in u.long_names: names.append(prefix + alias) if names: PrefixUnit( names, CompositeUnit(factor, [u], [1], _error_check=False), namespace=namespace, format=format, ) @overload def def_unit( s: str | list[str], represents: UnitLike, doc: str | None = None, format: Mapping[str, str] | None = None, prefixes: bool | Iterable[UnitPrefix] = False, exclude_prefixes: Collection[str] = (), namespace: MutableMapping[str, object] | None = None, ) -> Unit: ... @overload def def_unit( s: str | list[str], represents: None = None, doc: str | None = None, format: Mapping[str, str] | None = None, prefixes: bool | Iterable[UnitPrefix] = False, exclude_prefixes: Collection[str] = (), namespace: MutableMapping[str, object] | None = None, ) -> IrreducibleUnit: ... def def_unit( s: str | list[str], represents: UnitLike | None = None, doc: str | None = None, format: Mapping[str, str] | None = None, prefixes: bool | Iterable[UnitPrefix] = False, exclude_prefixes: Collection[str] = (), namespace: MutableMapping[str, object] | None = None, ) -> NamedUnit: """Define a new unit. This function differs from creating units directly with `Unit` or `IrreducibleUnit` because it can also automatically generate prefixed units in the given namespace. Parameters ---------- s : str or list of str The name of the unit. If a list, the first element is the canonical (short) name, and the rest of the elements are aliases. represents : unit-like, optional The unit that this named unit represents. If not provided, a new `IrreducibleUnit` is created. doc : str, optional A docstring describing the unit. format : dict, optional A mapping to format-specific representations of this unit. For example, for the ``Ohm`` unit, it might be nice to have it displayed as ``\\Omega`` by the ``latex`` formatter. In that case, `format` argument should be set to:: {'latex': r'\\Omega'} prefixes : bool or iterable of UnitPrefix, optional When `True`, generate all of the SI prefixed versions of the unit as well. For example, for a given unit ``m``, will generate ``mm``, ``cm``, ``km``, etc. If only a few prefixed versions should be created then an iterable of `UnitPrefix` instances can be specified instead. Default is `False`, which means no prefixed versions will be generated. This function always returns the base unit object, even if multiple scaled versions of the unit were created. exclude_prefixes : `~collections.abc.Collection` of str, optional If any of the SI prefixes need to be excluded, they may be listed here. For example, when defining the prefixes for ``a``, ``exclude_prefixes`` should be set to ``["P"]`` so that ``Pa`` would still refer to the pascal. If a bare `str` is used then the prefixes that will be excluded are the substrings of the `str`, not just its individual characters. namespace : dict, optional When provided, inject the unit (and all of its aliases and prefixes), into the given namespace dictionary. Returns ------- unit : `~astropy.units.NamedUnit` The newly-defined unit, or a matching unit that was already defined. Raises ------ ValueError If ``represents`` cannot be parsed as a unit, e.g., because it is a malformed string or a |Quantity| that is not a scalar. """ if represents is not None: result = Unit(s, represents, namespace=namespace, doc=doc, format=format) else: result = IrreducibleUnit(s, namespace=namespace, doc=doc, format=format) if prefixes: _add_prefixes( result, excludes=exclude_prefixes, namespace=namespace, prefixes=prefixes ) return result KNOWN_GOOD = np.ndarray | float | int | complex def _condition_arg(value): """Validate value is acceptable for conversion purposes. Will convert into an array if not a scalar or array-like, where scalars and arrays can be python and numpy types, anything that defines ``__array_namespace__`` or anything that has a ``.dtype`` attribute. Parameters ---------- value : scalar or array-like Returns ------- Scalar value or array Raises ------ ValueError If value is not as expected """ if ( isinstance(value, KNOWN_GOOD) or hasattr(value, "dtype") or hasattr(value, "__array_namespace__") ): return value value = np.array(value) if value.dtype.kind not in "ifc": raise ValueError( "Value not scalar compatible or convertible to " "an int, float, or complex array" ) return value def unit_scale_converter(val): """Function that just multiplies the value by unity. This is a separate function so it can be recognized and discarded in unit conversion. """ return 1.0 * _condition_arg(val) dimensionless_unscaled: Final[CompositeUnit] = CompositeUnit( 1, [], [], _error_check=False ) # Abbreviation of the above, see #1980 one: Final[CompositeUnit] = dimensionless_unscaled
UnitPrefix
python
django__django
tests/fixtures/models.py
{ "start": 564, "end": 775 }
class ____(models.Model): title = models.CharField(max_length=100) description = models.TextField() class Meta: ordering = ("title",) def __str__(self): return self.title
Category
python
fsspec__filesystem_spec
fsspec/conftest.py
{ "start": 499, "end": 3446 }
class ____: """ Helper class to inspect instance caches of filesystem classes in tests. """ def clear(self) -> None: """ Clear instance caches of all currently imported filesystem classes. """ classes = deque([fsspec.spec.AbstractFileSystem]) while classes: cls = classes.popleft() cls.clear_instance_cache() classes.extend(cls.__subclasses__()) def gather_counts(self, *, omit_zero: bool = True) -> dict[str, int]: """ Gather counts of filesystem instances in the instance caches of all currently imported filesystem classes. Parameters ---------- omit_zero: Whether to omit instance types with no cached instances. """ out: dict[str, int] = {} classes = deque([fsspec.spec.AbstractFileSystem]) while classes: cls = classes.popleft() count = len(cls._cache) # there is no public interface for the cache # note: skip intermediate AbstractFileSystem subclasses # if they proxy the protocol attribute via a property. if isinstance(cls.protocol, (Sequence, str)): key = cls.protocol if isinstance(cls.protocol, str) else cls.protocol[0] if count or not omit_zero: out[key] = count classes.extend(cls.__subclasses__()) return out @pytest.fixture(scope="function", autouse=True) def instance_caches() -> Generator[InstanceCacheInspector, None, None]: """ Fixture to ensure empty filesystem instance caches before and after a test. Used by default for all tests. Clears caches of all imported filesystem classes. Can be used to write test assertions about instance caches. Usage: def test_something(instance_caches): # Test code here fsspec.open("file://abc") fsspec.open("memory://foo/bar") # Test assertion assert instance_caches.gather_counts() == {"file": 1, "memory": 1} Returns ------- instance_caches: An instance cache inspector for clearing and inspecting caches. """ ic = InstanceCacheInspector() ic.clear() try: yield ic finally: ic.clear() @pytest.fixture(scope="function") def ftp_writable(tmpdir): """ Fixture providing a writable FTP filesystem. """ pytest.importorskip("pyftpdlib") d = str(tmpdir) with open(os.path.join(d, "out"), "wb") as f: f.write(b"hello" * 10000) P = subprocess.Popen( [sys.executable, "-m", "pyftpdlib", "-d", d, "-u", "user", "-P", "pass", "-w"] ) try: time.sleep(1) yield "localhost", 2121, "user", "pass" finally: P.terminate() P.wait() try: shutil.rmtree(tmpdir) except Exception: pass
InstanceCacheInspector
python
wandb__wandb
landfill/functional_tests/artifacts/link-model-outside-run.py
{ "start": 176, "end": 1102 }
class ____(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = F.max_pool2d(x, 2) x = self.dropout1(x) x = torch.flatten(x, 1) x = self.fc1(x) x = F.relu(x) x = self.dropout2(x) x = self.fc2(x) output = F.log_softmax(x, dim=1) return output def main(): my_model = Net() sm = _SavedModel.init(my_model) art = wandb.Artifact("my-model", "model") art.add(sm, "index") link_model(sm, "project/test_portfolio") if __name__ == "__main__": main()
Net
python
plotly__plotly.py
plotly/graph_objs/indicator/delta/_decreasing.py
{ "start": 233, "end": 3044 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "indicator.delta" _path_str = "indicator.delta.decreasing" _valid_props = {"color", "symbol"} @property def color(self): """ Sets the color for increasing value. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def symbol(self): """ Sets the symbol to display for increasing value The 'symbol' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["symbol"] @symbol.setter def symbol(self, val): self["symbol"] = val @property def _prop_descriptions(self): return """\ color Sets the color for increasing value. symbol Sets the symbol to display for increasing value """ def __init__(self, arg=None, color=None, symbol=None, **kwargs): """ Construct a new Decreasing object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.indicator.delta.Decreasing` color Sets the color for increasing value. symbol Sets the symbol to display for increasing value Returns ------- Decreasing """ super().__init__("decreasing") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.indicator.delta.Decreasing constructor must be a dict or an instance of :class:`plotly.graph_objs.indicator.delta.Decreasing`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("symbol", arg, symbol) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Decreasing
python
pydantic__pydantic
pydantic/_internal/_signature.py
{ "start": 372, "end": 6779 }
class ____: def __repr__(self): return '<factory>' _HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS() def _field_name_for_signature(field_name: str, field_info: FieldInfo) -> str: """Extract the correct name to use for the field when generating a signature. Assuming the field has a valid alias, this will return the alias. Otherwise, it will return the field name. First priority is given to the alias, then the validation_alias, then the field name. Args: field_name: The name of the field field_info: The corresponding FieldInfo object. Returns: The correct name to use when generating a signature. """ if isinstance(field_info.alias, str) and is_valid_identifier(field_info.alias): return field_info.alias if isinstance(field_info.validation_alias, str) and is_valid_identifier(field_info.validation_alias): return field_info.validation_alias return field_name def _process_param_defaults(param: Parameter) -> Parameter: """Modify the signature for a parameter in a dataclass where the default value is a FieldInfo instance. Args: param (Parameter): The parameter Returns: Parameter: The custom processed parameter """ from ..fields import FieldInfo param_default = param.default if isinstance(param_default, FieldInfo): annotation = param.annotation # Replace the annotation if appropriate # inspect does "clever" things to show annotations as strings because we have # `from __future__ import annotations` in main, we don't want that if annotation == 'Any': annotation = Any # Replace the field default default = param_default.default if default is PydanticUndefined: if param_default.default_factory is PydanticUndefined: default = Signature.empty else: # this is used by dataclasses to indicate a factory exists: default = dataclasses._HAS_DEFAULT_FACTORY # type: ignore return param.replace( annotation=annotation, name=_field_name_for_signature(param.name, param_default), default=default ) return param def _generate_signature_parameters( # noqa: C901 (ignore complexity, could use a refactor) init: Callable[..., None], fields: dict[str, FieldInfo], validate_by_name: bool, extra: ExtraValues | None, ) -> dict[str, Parameter]: """Generate a mapping of parameter names to Parameter objects for a pydantic BaseModel or dataclass.""" from itertools import islice present_params = signature(init).parameters.values() merged_params: dict[str, Parameter] = {} var_kw = None use_var_kw = False for param in islice(present_params, 1, None): # skip self arg # inspect does "clever" things to show annotations as strings because we have # `from __future__ import annotations` in main, we don't want that if fields.get(param.name): # exclude params with init=False if getattr(fields[param.name], 'init', True) is False: continue param = param.replace(name=_field_name_for_signature(param.name, fields[param.name])) if param.annotation == 'Any': param = param.replace(annotation=Any) if param.kind is param.VAR_KEYWORD: var_kw = param continue merged_params[param.name] = param if var_kw: # if custom init has no var_kw, fields which are not declared in it cannot be passed through allow_names = validate_by_name for field_name, field in fields.items(): # when alias is a str it should be used for signature generation param_name = _field_name_for_signature(field_name, field) if field_name in merged_params or param_name in merged_params: continue if not is_valid_identifier(param_name): if allow_names: param_name = field_name else: use_var_kw = True continue if field.is_required(): default = Parameter.empty elif field.default_factory is not None: # Mimics stdlib dataclasses: default = _HAS_DEFAULT_FACTORY else: default = field.default merged_params[param_name] = Parameter( param_name, Parameter.KEYWORD_ONLY, annotation=field.rebuild_annotation(), default=default, ) if extra == 'allow': use_var_kw = True if var_kw and use_var_kw: # Make sure the parameter for extra kwargs # does not have the same name as a field default_model_signature = [ ('self', Parameter.POSITIONAL_ONLY), ('data', Parameter.VAR_KEYWORD), ] if [(p.name, p.kind) for p in present_params] == default_model_signature: # if this is the standard model signature, use extra_data as the extra args name var_kw_name = 'extra_data' else: # else start from var_kw var_kw_name = var_kw.name # generate a name that's definitely unique while var_kw_name in fields: var_kw_name += '_' merged_params[var_kw_name] = var_kw.replace(name=var_kw_name) return merged_params def generate_pydantic_signature( init: Callable[..., None], fields: dict[str, FieldInfo], validate_by_name: bool, extra: ExtraValues | None, is_dataclass: bool = False, ) -> Signature: """Generate signature for a pydantic BaseModel or dataclass. Args: init: The class init. fields: The model fields. validate_by_name: The `validate_by_name` value of the config. extra: The `extra` value of the config. is_dataclass: Whether the model is a dataclass. Returns: The dataclass/BaseModel subclass signature. """ merged_params = _generate_signature_parameters(init, fields, validate_by_name, extra) if is_dataclass: merged_params = {k: _process_param_defaults(v) for k, v in merged_params.items()} return Signature(parameters=list(merged_params.values()), return_annotation=None)
_HAS_DEFAULT_FACTORY_CLASS
python
huggingface__transformers
src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py
{ "start": 28868, "end": 34642 }
class ____(GPTBigCodePreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.transformer = GPTBigCodeModel(config) self.score = nn.Linear(config.n_embd, self.num_labels, bias=False) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, **kwargs, ) -> Union[tuple, SequenceClassifierOutputWithPast]: r""" input_ids (`torch.Tensor` of shape `(batch_size, input_ids_length)`): `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()` (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) labels (`torch.Tensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict transformer_outputs = self.transformer( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, **kwargs, ) hidden_states = transformer_outputs[0] logits = self.score(hidden_states) if input_ids is not None: batch_size, sequence_length = input_ids.shape[:2] else: batch_size, sequence_length = inputs_embeds.shape[:2] if self.config.pad_token_id is None and batch_size != 1: raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") if self.config.pad_token_id is None: last_non_pad_token = -1 elif input_ids is not None: # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32) token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32) last_non_pad_token = (token_indices * non_pad_mask).argmax(-1) else: last_non_pad_token = -1 logger.warning_once( f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " "unexpected if using padding tokens in conjunction with `inputs_embeds.`" ) pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token] loss = None if labels is not None: labels = labels.to(logits.device) if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) else: loss = loss_fct(pooled_logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(pooled_logits, labels) if not return_dict: output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) @auto_docstring
GPTBigCodeForSequenceClassification
python
astropy__astropy
astropy/io/fits/diff.py
{ "start": 15791, "end": 23570 }
class ____(_BaseDiff): """ Diff two HDU objects, including their headers and their data (but only if both HDUs contain the same type of data (image, table, or unknown). `HDUDiff` objects have the following diff attributes: - ``diff_extnames``: If the two HDUs have different EXTNAME values, this contains a 2-tuple of the different extension names. - ``diff_extvers``: If the two HDUS have different EXTVER values, this contains a 2-tuple of the different extension versions. - ``diff_extlevels``: If the two HDUs have different EXTLEVEL values, this contains a 2-tuple of the different extension levels. - ``diff_extension_types``: If the two HDUs have different XTENSION values, this contains a 2-tuple of the different extension types. - ``diff_headers``: Contains a `HeaderDiff` object for the headers of the two HDUs. This will always contain an object--it may be determined whether the headers are different through ``diff_headers.identical``. - ``diff_data``: Contains either a `ImageDataDiff`, `TableDataDiff`, or `RawDataDiff` as appropriate for the data in the HDUs, and only if the two HDUs have non-empty data of the same type (`RawDataDiff` is used for HDUs containing non-empty data of an indeterminate type). """ def __init__( self, a, b, ignore_keywords=[], ignore_comments=[], ignore_fields=[], numdiffs=10, rtol=0.0, atol=0.0, ignore_blanks=True, ignore_blank_cards=True, ): """ Parameters ---------- a : BaseHDU An HDU object. b : BaseHDU An HDU object to compare to the first HDU object. ignore_keywords : sequence, optional Header keywords to ignore when comparing two headers; the presence of these keywords and their values are ignored. Wildcard strings may also be included in the list. ignore_comments : sequence, optional A list of header keywords whose comments should be ignored in the comparison. May contain wildcard strings as with ignore_keywords. ignore_fields : sequence, optional The (case-insensitive) names of any table columns to ignore if any table data is to be compared. numdiffs : int, optional The number of pixel/table values to output when reporting HDU data differences. Though the count of differences is the same either way, this allows controlling the number of different values that are kept in memory or output. If a negative value is given, then numdiffs is treated as unlimited (default: 10). rtol : float, optional The relative difference to allow when comparing two float values either in header values, image arrays, or table columns (default: 0.0). Values which satisfy the expression .. math:: \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right| are considered to be different. The underlying function used for comparison is `numpy.allclose`. .. versionadded:: 2.0 atol : float, optional The allowed absolute difference. See also ``rtol`` parameter. .. versionadded:: 2.0 ignore_blanks : bool, optional Ignore extra whitespace at the end of string values either in headers or data. Extra leading whitespace is not ignored (default: True). ignore_blank_cards : bool, optional Ignore all cards that are blank, i.e. they only contain whitespace (default: True). """ self.ignore_keywords = {k.upper() for k in ignore_keywords} self.ignore_comments = {k.upper() for k in ignore_comments} self.ignore_fields = {k.upper() for k in ignore_fields} self.rtol = rtol self.atol = atol self.numdiffs = numdiffs self.ignore_blanks = ignore_blanks self.ignore_blank_cards = ignore_blank_cards self.diff_extnames = () self.diff_extvers = () self.diff_extlevels = () self.diff_extension_types = () self.diff_headers = None self.diff_data = None super().__init__(a, b) def _diff(self): if self.a.name != self.b.name: self.diff_extnames = (self.a.name, self.b.name) if self.a.ver != self.b.ver: self.diff_extvers = (self.a.ver, self.b.ver) if self.a.level != self.b.level: self.diff_extlevels = (self.a.level, self.b.level) if self.a.header.get("XTENSION") != self.b.header.get("XTENSION"): self.diff_extension_types = ( self.a.header.get("XTENSION"), self.b.header.get("XTENSION"), ) self.diff_headers = HeaderDiff.fromdiff( self, self.a.header.copy(), self.b.header.copy() ) if self.a.data is None or self.b.data is None: # TODO: Perhaps have some means of marking this case pass elif self.a.is_image and self.b.is_image: self.diff_data = ImageDataDiff.fromdiff(self, self.a.data, self.b.data) # Clean up references to (possibly) memmapped arrays so they can # be closed by .close() self.diff_data.a = None self.diff_data.b = None elif isinstance(self.a, _TableLikeHDU) and isinstance(self.b, _TableLikeHDU): # TODO: Replace this if/when _BaseHDU grows a .is_table property self.diff_data = TableDataDiff.fromdiff(self, self.a.data, self.b.data) # Clean up references to (possibly) memmapped arrays so they can # be closed by .close() self.diff_data.a = None self.diff_data.b = None elif not self.diff_extension_types: # Don't diff the data for unequal extension types that are not # recognized image or table types self.diff_data = RawDataDiff.fromdiff(self, self.a.data, self.b.data) # Clean up references to (possibly) memmapped arrays so they can # be closed by .close() self.diff_data.a = None self.diff_data.b = None def _report(self): if self.identical: self._writeln(" No differences found.") if self.diff_extension_types: self._writeln( " Extension types differ:\n a: {}\n b: {}".format( *self.diff_extension_types ) ) if self.diff_extnames: self._writeln( " Extension names differ:\n a: {}\n b: {}".format(*self.diff_extnames) ) if self.diff_extvers: self._writeln( " Extension versions differ:\n a: {}\n b: {}".format( *self.diff_extvers ) ) if self.diff_extlevels: self._writeln( " Extension levels differ:\n a: {}\n b: {}".format( *self.diff_extlevels ) ) if not self.diff_headers.identical: self._fileobj.write("\n") self._writeln(" Headers contain differences:") self.diff_headers.report(self._fileobj, indent=self._indent + 1) if self.diff_data is not None and not self.diff_data.identical: self._fileobj.write("\n") self._writeln(" Data contains differences:") self.diff_data.report(self._fileobj, indent=self._indent + 1)
HDUDiff
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vector_index.py
{ "start": 7377, "end": 7589 }
class ____(_QuantizerConfigCreate): cache: Optional[bool] rescoreLimit: Optional[int] trainingLimit: Optional[int] @staticmethod def quantizer_name() -> str: return "sq"
_SQConfigCreate
python
kamyu104__LeetCode-Solutions
Python/unique-binary-search-trees.py
{ "start": 29, "end": 531 }
class ____(object): def numTrees(self, n): """ :type n: int :rtype: int """ if n == 0: return 1 def combination(n, k): count = 1 # C(n, k) = (n) / 1 * (n - 1) / 2 ... * (n - k + 1) / k for i in xrange(1, k + 1): count = count * (n - i + 1) / i return count return combination(2 * n, n) - combination(2 * n, n - 1) # Time: O(n^2) # Space: O(n) # DP solution.
Solution
python
apache__avro
lang/py/avro/errors.py
{ "start": 3540, "end": 3666 }
class ____(AvroException): """Raised when an error message is sent by an Avro requestor or responder."""
AvroRemoteException
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 128511, "end": 129342 }
class ____(Operation): def call(self, x1, x2): return backend.numpy.less_equal(x1, x2) def compute_output_spec(self, x1, x2): x1_shape = getattr(x1, "shape", []) x2_shape = getattr(x2, "shape", []) output_shape = broadcast_shapes(x1_shape, x2_shape) return KerasTensor(output_shape, dtype="bool") @keras_export( [ "keras.ops.less_equal", "keras.ops.numpy.less_equal", ] ) def less_equal(x1, x2): """Return the truth value of `x1 <= x2` element-wise. Args: x1: First input tensor. x2: Second input tensor. Returns: Output tensor, element-wise comparison of `x1` and `x2`. """ if any_symbolic_tensors((x1, x2)): return LessEqual().symbolic_call(x1, x2) return backend.numpy.less_equal(x1, x2)
LessEqual
python
apache__airflow
dev/breeze/src/airflow_breeze/utils/release_validator.py
{ "start": 1230, "end": 1395 }
class ____: check_type: CheckType passed: bool message: str details: list[str] | None = None duration_seconds: float | None = None
ValidationResult
python
mwaskom__seaborn
seaborn/_marks/bar.py
{ "start": 6258, "end": 9137 }
class ____(BarBase): """ A faster bar mark with defaults more suitable for histograms. See also -------- Bar : A bar mark drawn between baseline and data values. Examples -------- .. include:: ../docstrings/objects.Bars.rst """ color: MappableColor = Mappable("C0", grouping=False) alpha: MappableFloat = Mappable(.7, grouping=False) fill: MappableBool = Mappable(True, grouping=False) edgecolor: MappableColor = Mappable(rc="patch.edgecolor", grouping=False) edgealpha: MappableFloat = Mappable(1, grouping=False) edgewidth: MappableFloat = Mappable(auto=True, grouping=False) edgestyle: MappableStyle = Mappable("-", grouping=False) # pattern: MappableString = Mappable(None) # TODO no Property yet width: MappableFloat = Mappable(1, grouping=False) baseline: MappableFloat = Mappable(0, grouping=False) # TODO *is* this mappable? def _plot(self, split_gen, scales, orient): ori_idx = ["x", "y"].index(orient) val_idx = ["y", "x"].index(orient) patches = defaultdict(list) for _, data, ax in split_gen(): bars, _ = self._make_patches(data, scales, orient) patches[ax].extend(bars) collections = {} for ax, ax_patches in patches.items(): col = mpl.collections.PatchCollection(ax_patches, match_original=True) col.sticky_edges[val_idx][:] = (0, np.inf) ax.add_collection(col, autolim=False) collections[ax] = col # Workaround for matplotlib autoscaling bug # https://github.com/matplotlib/matplotlib/issues/11898 # https://github.com/matplotlib/matplotlib/issues/23129 xys = np.vstack([path.vertices for path in col.get_paths()]) ax.update_datalim(xys) if "edgewidth" not in scales and isinstance(self.edgewidth, Mappable): for ax in collections: ax.autoscale_view() def get_dimensions(collection): edges, widths = [], [] for verts in (path.vertices for path in collection.get_paths()): edges.append(min(verts[:, ori_idx])) widths.append(np.ptp(verts[:, ori_idx])) return np.array(edges), np.array(widths) min_width = np.inf for ax, col in collections.items(): edges, widths = get_dimensions(col) points = 72 / ax.figure.dpi * abs( ax.transData.transform([edges + widths] * 2) - ax.transData.transform([edges] * 2) ) min_width = min(min_width, min(points[:, ori_idx])) linewidth = min(.1 * min_width, mpl.rcParams["patch.linewidth"]) for _, col in collections.items(): col.set_linewidth(linewidth)
Bars
python
huggingface__transformers
src/transformers/models/yolos/modeling_yolos.py
{ "start": 13961, "end": 14462 }
class ____(nn.Module): def __init__(self, config: YolosConfig): super().__init__() self.attention = YolosSelfAttention(config) self.output = YolosSelfOutput(config) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: self_attn_output, _ = self.attention(hidden_states) output = self.output(self_attn_output, hidden_states) return output # Copied from transformers.models.vit.modeling_vit.ViTIntermediate with ViT->Yolos
YolosAttention
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_permissions.py
{ "start": 2501, "end": 2679 }
class ____: @check_permission(Permissions.LAUNCH_PARTITION_BACKFILL) def mutate(self, graphene_info: ResolveInfo, **_kwargs): pass
FakeMissingEnumPermissionMutation
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 29894, "end": 31029 }
class ____(Interface): def __call__(environ, router): """ This callable triggers the router to process a raw WSGI environ dict into a response and controls the :app:`Pyramid` request pipeline. The ``environ`` is the raw WSGI environ. The ``router`` is an :class:`pyramid.interfaces.IRouter` object which should be used to create a request object and send it into the processing pipeline. The return value should be a :class:`pyramid.interfaces.IResponse` object or an exception that will be handled by WSGI middleware. The default execution policy simply creates a request and sends it through the pipeline, attempting to render any exception that escapes: .. code-block:: python def simple_execution_policy(environ, router): with router.request_context(environ) as request: try: return router.invoke_request(request) except Exception: return request.invoke_exception_view(reraise=True) """
IExecutionPolicy
python
coleifer__peewee
tests/models.py
{ "start": 58562, "end": 59708 }
class ____(ModelTestCase): database = get_in_memory_db() requires = [User] def test_raw(self): with self.database.atomic(): for username in ('charlie', 'chuck', 'huey', 'zaizee'): User.create(username=username) query = (User .raw('SELECT username, SUBSTR(username, 1, 1) AS first ' 'FROM users ' 'WHERE SUBSTR(username, 1, 1) = ? ' 'ORDER BY username DESC', 'c')) self.assertEqual([(row.username, row.first) for row in query], [('chuck', 'c'), ('charlie', 'c')]) def test_raw_iterator(self): (User .insert_many([('charlie',), ('huey',)], fields=[User.username]) .execute()) with self.assertQueryCount(1): query = User.raw('SELECT * FROM users ORDER BY id') results = [user.username for user in query.iterator()] self.assertEqual(results, ['charlie', 'huey']) # Since we used iterator(), the results were not cached. self.assertEqual([u.username for u in query], [])
TestRaw
python
kamyu104__LeetCode-Solutions
Python/find-pivot-index.py
{ "start": 29, "end": 367 }
class ____(object): def pivotIndex(self, nums): """ :type nums: List[int] :rtype: int """ total = sum(nums) left_sum = 0 for i, num in enumerate(nums): if left_sum == (total-left_sum-num): return i left_sum += num return -1
Solution
python
doocs__leetcode
lcof2/剑指 Offer II 021. 删除链表的倒数第 n 个结点/Solution.py
{ "start": 151, "end": 505 }
class ____: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: dummy = ListNode(next=head) slow, fast = dummy, dummy for _ in range(n): fast = fast.next while fast.next: slow = slow.next fast = fast.next slow.next = slow.next.next return dummy.next
Solution
python
wandb__wandb
wandb/vendor/pygments/lexers/elm.py
{ "start": 407, "end": 2996 }
class ____(RegexLexer): """ For `Elm <http://elm-lang.org/>`_ source code. .. versionadded:: 2.1 """ name = 'Elm' aliases = ['elm'] filenames = ['*.elm'] mimetypes = ['text/x-elm'] validName = r'[a-z_][a-zA-Z_\']*' specialName = r'^main ' builtinOps = ( '~', '||', '|>', '|', '`', '^', '\\', '\'', '>>', '>=', '>', '==', '=', '<~', '<|', '<=', '<<', '<-', '<', '::', ':', '/=', '//', '/', '..', '.', '->', '-', '++', '+', '*', '&&', '%', ) reservedWords = words(( 'alias', 'as', 'case', 'else', 'if', 'import', 'in', 'let', 'module', 'of', 'port', 'then', 'type', 'where', ), suffix=r'\b') tokens = { 'root': [ # Comments (r'\{-', Comment.Multiline, 'comment'), (r'--.*', Comment.Single), # Whitespace (r'\s+', Text), # Strings (r'"', String, 'doublequote'), # Modules (r'^\s*module\s*', Keyword.Namespace, 'imports'), # Imports (r'^\s*import\s*', Keyword.Namespace, 'imports'), # Shaders (r'\[glsl\|.*', Name.Entity, 'shader'), # Keywords (reservedWords, Keyword.Reserved), # Types (r'[A-Z]\w*', Keyword.Type), # Main (specialName, Keyword.Reserved), # Prefix Operators (words((builtinOps), prefix=r'\(', suffix=r'\)'), Name.Function), # Infix Operators (words((builtinOps)), Name.Function), # Numbers include('numbers'), # Variable Names (validName, Name.Variable), # Parens (r'[,()\[\]{}]', Punctuation), ], 'comment': [ (r'-(?!\})', Comment.Multiline), (r'\{-', Comment.Multiline, 'comment'), (r'[^-}]', Comment.Multiline), (r'-\}', Comment.Multiline, '#pop'), ], 'doublequote': [ (r'\\u[0-9a-fA-F]{4}', String.Escape), (r'\\[nrfvb\\"]', String.Escape), (r'[^"]', String), (r'"', String, '#pop'), ], 'imports': [ (r'\w+(\.\w+)*', Name.Class, '#pop'), ], 'numbers': [ (r'_?\d+\.(?=\d+)', Number.Float), (r'_?\d+', Number.Integer), ], 'shader': [ (r'\|(?!\])', Name.Entity), (r'\|\]', Name.Entity, '#pop'), (r'.*\n', Name.Entity), ], }
ElmLexer
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_version_querysets.py
{ "start": 4506, "end": 5859 }
class ____(TestVersionQuerySetBase): def setUp(self): super().setUp() self.external_version_public = get( Version, project=self.project, active=True, type=EXTERNAL, privacy_level=PUBLIC, ) self.external_version_private = get( Version, project=self.project, active=True, type=EXTERNAL, privacy_level=PRIVATE, ) self.another_external_version_public = get( Version, project=self.another_project, active=True, type=EXTERNAL, privacy_level=PUBLIC, ) self.another_external_version_private = get( Version, project=self.another_project, active=True, type=EXTERNAL, privacy_level=PRIVATE, ) self.shared_external_version_public = get( Version, project=self.shared_project, active=True, type=EXTERNAL, privacy_level=PUBLIC, ) self.shared_external_version_private = get( Version, project=self.shared_project, active=True, type=EXTERNAL, privacy_level=PRIVATE, )
TestVersionQuerySetWithManagerBase
python
ethereum__web3.py
web3/exceptions.py
{ "start": 2692, "end": 3465 }
class ____(Web3Exception): """ Raised by the stalecheck_middleware when the latest block is too old. """ def __init__(self, block: BlockData, allowable_delay: int) -> None: last_block_date = datetime.datetime.fromtimestamp(block["timestamp"]).strftime( "%c" ) message = ( f"The latest block, #{block['number']}, is " f"{time.time() - block['timestamp']} seconds old, but is only " f"allowed to be {allowable_delay} s old. " f"The date of the most recent block is {last_block_date}. Continue " "syncing and try again..." ) super().__init__(message, block, allowable_delay) def __str__(self) -> str: return self.args[0]
StaleBlockchain
python
getsentry__sentry
src/sentry/api/endpoints/api_token_details.py
{ "start": 849, "end": 998 }
class ____(serializers.Serializer): name = CharField(max_length=255, allow_blank=True, required=True) @control_silo_endpoint
ApiTokenNameSerializer
python
scipy__scipy
scipy/signal/tests/test_filter_design.py
{ "start": 1998, "end": 4408 }
class ____: def test_trivial_input(self): assert _cplxpair([]).size == 0 assert _cplxpair(1) == 1 def test_output_order(self): xp_assert_close(_cplxpair([1+1j, 1-1j]), [1-1j, 1+1j]) a = [1+1j, 1+1j, 1, 1-1j, 1-1j, 2] b = [1-1j, 1+1j, 1-1j, 1+1j, 1, 2] xp_assert_close(_cplxpair(a), b) # points spaced around the unit circle z = np.exp(2j*pi*array([4, 3, 5, 2, 6, 1, 0])/7) z1 = np.copy(z) np.random.shuffle(z) xp_assert_close(_cplxpair(z), z1) np.random.shuffle(z) xp_assert_close(_cplxpair(z), z1) np.random.shuffle(z) xp_assert_close(_cplxpair(z), z1) # Should be able to pair up all the conjugates x = np.random.rand(10000) + 1j * np.random.rand(10000) y = x.conj() z = np.random.rand(10000) x = np.concatenate((x, y, z)) np.random.shuffle(x) c = _cplxpair(x) # Every other element of head should be conjugates: xp_assert_close(c[0:20000:2], np.conj(c[1:20000:2])) # Real parts of head should be in sorted order: xp_assert_close(c[0:20000:2].real, np.sort(c[0:20000:2].real)) # Tail should be sorted real numbers: xp_assert_close(c[20000:], np.sort(c[20000:])) def test_real_integer_input(self): xp_assert_equal(_cplxpair([2, 0, 1]), [0, 1, 2]) def test_tolerances(self): eps = spacing(1) xp_assert_close(_cplxpair([1j, -1j, 1+1j*eps], tol=2*eps), [-1j, 1j, 1+1j*eps]) # sorting close to 0 xp_assert_close(_cplxpair([-eps+1j, +eps-1j]), [-1j, +1j]) xp_assert_close(_cplxpair([+eps+1j, -eps-1j]), [-1j, +1j]) xp_assert_close(_cplxpair([+1j, -1j]), [-1j, +1j]) def test_unmatched_conjugates(self): # 1+2j is unmatched assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+2j]) # 1+2j and 1-3j are unmatched assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+2j, 1-3j]) # 1+3j is unmatched assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+3j]) # Not conjugates assert_raises(ValueError, _cplxpair, [4+5j, 4+5j]) assert_raises(ValueError, _cplxpair, [1-7j, 1-7j]) # No pairs assert_raises(ValueError, _cplxpair, [1+3j]) assert_raises(ValueError, _cplxpair, [1-3j])
TestCplxPair
python
tensorflow__tensorflow
third_party/xla/build_tools/configure/configure.py
{ "start": 7184, "end": 10026 }
class ____: """Paths to various tools and libraries needed to build XLA. This class is where all 'stateful' activity should happen, like trying to read environment variables or looking for things in the $PATH. An instance that has all fields set should not try to do any of these things though, so that this file can remain unit testable. """ clang_path: Optional[str] = None clang_major_version: Optional[int] = None gcc_path: Optional[str] = None gcc_major_version: Optional[int] = None lld_path: Optional[str] = None ld_library_path: Optional[str] = None # CUDA specific cuda_version: Optional[str] = None cuda_compute_capabilities: Optional[list[str]] = None cudnn_version: Optional[str] = None local_cuda_path: Optional[str] = None local_cudnn_path: Optional[str] = None local_nccl_path: Optional[str] = None def get_relevant_paths_and_versions(self, config: "XLAConfigOptions"): """Gets paths and versions as needed by the config. Args: config: XLAConfigOptions instance that determines what paths and versions to try to autoconfigure. """ if self.ld_library_path is None: self.ld_library_path = os.environ.get("LD_LIBRARY_PATH", None) if config.host_compiler == HostCompiler.CLANG: if self.clang_path or not is_hermetic_build(config.backend, config.os): self.clang_path = _find_executable_or_die("clang", self.clang_path) self.clang_major_version = ( self.clang_major_version or _get_clang_major_version(self.clang_path) ) # Notably, we don't use `_find_executable_or_die` for lld, as it changes # which commands it accepts based on its name! ld.lld is symlinked to a # different executable just called lld, which should not be invoked # directly. self.lld_path = self.lld_path or shutil.which("ld.lld") else: # TODO: b/443091874 - set the version of Clang when it will be # available outside of rules_ml_toolchain. Current hermetic Clang # version is 18 self.clang_major_version = 18 # Hermetic toolchain elif config.host_compiler == HostCompiler.GCC: self.gcc_path = _find_executable_or_die("gcc", self.gcc_path) self.gcc_major_version = self.gcc_major_version or _get_gcc_major_version( self.gcc_path ) if config.backend == Backend.CUDA: if config.cuda_compiler == CudaCompiler.CLANG and ( self.clang_path or not is_hermetic_build(config.backend, config.os) ): self.clang_path = _find_executable_or_die("clang", self.clang_path) if not self.cuda_compute_capabilities: self.cuda_compute_capabilities = _get_cuda_compute_capabilities_or_die() @dataclasses.dataclass(frozen=True, **_KW_ONLY_IF_PYTHON310)
DiscoverablePathsAndVersions
python
apache__airflow
providers/facebook/src/airflow/providers/facebook/ads/hooks/ads.py
{ "start": 1360, "end": 1588 }
class ____(Enum): """Available options for facebook async task status.""" COMPLETED = "Job Completed" STARTED = "Job Started" RUNNING = "Job Running" FAILED = "Job Failed" SKIPPED = "Job Skipped"
JobStatus
python
jazzband__pip-tools
tests/test_cli_compile.py
{ "start": 1481, "end": 130345 }
class ____: """ A small data-builder for setting up files in a tmp dir. Contains a name for use as the ID in parametrized tests and contents. 'contents' maps from subpaths in the tmp dir to file content or callables which produce file content given the tmp dir. """ # the name for the collection of files name: str = "<unnamed test file collection>" # static or computed contents contents: dict[str, str | _t.Callable[[pathlib.Path], str]] = dataclasses.field( default_factory=dict ) def __str__(self) -> str: return self.name def populate(self, tmp_path: pathlib.Path) -> None: """Populate the tmp dir with file contents.""" for path_str, content in self.contents.items(): path = tmp_path / path_str path.parent.mkdir(exist_ok=True, parents=True) if isinstance(content, str): path.write_text(content) else: path.write_text(content(tmp_path)) def get_path_to(self, filename: str) -> str: """Given a filename, find the (first) path to that filename in the contents.""" return next( stub_file_path for stub_file_path in self.contents if (stub_file_path == filename) or stub_file_path.endswith(f"/{filename}") ) @pytest.fixture( autouse=True, params=[ pytest.param("legacy", id="legacy resolver"), pytest.param("backtracking", id="backtracking resolver"), ], ) def current_resolver(request, monkeypatch): # Hide --resolver option from pip-compile header, so that we don't have to # inject it every time to tests outputs. exclude_options = COMPILE_EXCLUDE_OPTIONS | {"--resolver"} monkeypatch.setattr("piptools.utils.COMPILE_EXCLUDE_OPTIONS", exclude_options) # Setup given resolver name resolver_name = request.param monkeypatch.setenv("PIP_TOOLS_RESOLVER", resolver_name) return resolver_name @pytest.fixture(autouse=True) def _temp_dep_cache(tmpdir, monkeypatch): monkeypatch.setenv("PIP_TOOLS_CACHE_DIR", str(tmpdir / "cache")) def test_default_pip_conf_read(pip_with_index_conf, runner): # preconditions with open("requirements.in", "w"): pass out = runner.invoke(cli, ["-v"]) # check that we have our index-url as specified in pip.conf assert "Using indexes:\n http://example.com" in out.stderr assert "--index-url http://example.com" in out.stderr def test_command_line_overrides_pip_conf(pip_with_index_conf, runner): # preconditions with open("requirements.in", "w"): pass out = runner.invoke(cli, ["-v", "-i", "http://override.com"]) # check that we have our index-url as specified in pip.conf assert "Using indexes:\n http://override.com" in out.stderr @pytest.mark.network @pytest.mark.parametrize( ("install_requires", "expected_output"), ( pytest.param("small-fake-a==0.1", "small-fake-a==0.1", id="regular"), pytest.param( "pip-tools @ https://github.com/jazzband/pip-tools/archive/7d86c8d3.zip", "pip-tools @ https://github.com/jazzband/pip-tools/archive/7d86c8d3.zip", id="zip URL", ), pytest.param( "pip-tools @ git+https://github.com/jazzband/pip-tools@7d86c8d3", "pip-tools @ git+https://github.com/jazzband/pip-tools@7d86c8d3", id="scm URL", ), pytest.param( "pip-tools @ https://files.pythonhosted.org/packages/06/96/" "89872db07ae70770fba97205b0737c17ef013d0d1c790" "899c16bb8bac419/pip_tools-3.6.1-py2.py3-none-any.whl", "pip-tools @ https://files.pythonhosted.org/packages/06/96/" "89872db07ae70770fba97205b0737c17ef013d0d1c790" "899c16bb8bac419/pip_tools-3.6.1-py2.py3-none-any.whl", id="wheel URL", ), ), ) def test_command_line_setuptools_read( runner, make_package, minimal_wheels_path, install_requires, expected_output ): package_dir = make_package( name="fake-setuptools-a", install_requires=(install_requires,), ) out = runner.invoke( cli, ( str(package_dir / "setup.py"), "--find-links", minimal_wheels_path.as_posix(), "--no-build-isolation", ), ) assert out.exit_code == 0 # check that pip-compile generated a configuration file output_file = package_dir / "requirements.txt" assert output_file.exists() # The package version must NOT be updated in the output file assert expected_output in output_file.read_text().splitlines() @pytest.mark.network @pytest.mark.parametrize( ("options", "expected_output_file"), ( # For the `pip-compile` output file should be "requirements.txt" ([], "requirements.txt"), # For the `pip-compile --output-file=output.txt` # output file should be "output.txt" (["--output-file", "output.txt"], "output.txt"), # For the `pip-compile setup.py` output file should be "requirements.txt" (["setup.py"], "requirements.txt"), # For the `pip-compile setup.py --output-file=output.txt` # output file should be "output.txt" (["setup.py", "--output-file", "output.txt"], "output.txt"), ), ) def test_command_line_setuptools_output_file(runner, options, expected_output_file): """ Test the output files for setup.py as a requirement file. """ with open("setup.py", "w") as package: package.write( dedent( """\ from setuptools import setup setup(install_requires=[]) """ ) ) out = runner.invoke(cli, ["--no-build-isolation"] + options) assert out.exit_code == 0 assert os.path.exists(expected_output_file) @pytest.mark.network def test_command_line_setuptools_nested_output_file(tmpdir, runner): """ Test the output file for setup.py in nested folder as a requirement file. """ proj_dir = tmpdir.mkdir("proj") with open(str(proj_dir / "setup.py"), "w") as package: package.write( dedent( """\ from setuptools import setup setup(install_requires=[]) """ ) ) out = runner.invoke(cli, [str(proj_dir / "setup.py"), "--no-build-isolation"]) assert out.exit_code == 0 assert (proj_dir / "requirements.txt").exists() @pytest.mark.network def test_setuptools_preserves_environment_markers( runner, make_package, make_wheel, make_pip_conf, tmpdir ): make_pip_conf( dedent( """\ [global] disable-pip-version-check = True """ ) ) dists_dir = tmpdir / "dists" foo_dir = make_package(name="foo", version="1.0") make_wheel(foo_dir, dists_dir) bar_dir = make_package( name="bar", version="2.0", install_requires=['foo ; python_version >= "1"'] ) out = runner.invoke( cli, [ str(bar_dir / "setup.py"), "--output-file", "-", "--no-header", "--no-annotate", "--no-emit-find-links", "--no-build-isolation", "--find-links", str(dists_dir), ], ) assert out.exit_code == 0, out.stderr assert out.stdout == 'foo==1.0 ; python_version >= "1"\n' def test_no_index_option(runner, tmp_path): req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke(cli, [req_in.as_posix(), "--no-index", "--verbose"]) assert out.exit_code == 0 assert "Ignoring indexes." in out.stderr def test_find_links_option(runner): with open("requirements.in", "w") as req_in: req_in.write("-f ./libs3") out = runner.invoke(cli, ["-v", "-f", "./libs1", "-f", "./libs2"]) # Check that find-links has been passed to pip assert "Using links:\n ./libs1\n ./libs2\n ./libs3\n" in out.stderr # Check that find-links has been written to a requirements.txt with open("requirements.txt") as req_txt: assert ( "--find-links ./libs1\n--find-links ./libs2\n--find-links ./libs3\n" in req_txt.read() ) def test_find_links_envvar(monkeypatch, runner): with open("requirements.in", "w") as req_in: req_in.write("-f ./libs3") monkeypatch.setenv("PIP_FIND_LINKS", "./libs1 ./libs2") out = runner.invoke(cli, ["-v"]) # Check that find-links has been passed to pip assert "Using links:\n ./libs1\n ./libs2\n ./libs3\n" in out.stderr # Check that find-links has been written to a requirements.txt with open("requirements.txt") as req_txt: assert ( "--find-links ./libs1\n--find-links ./libs2\n--find-links ./libs3\n" in req_txt.read() ) def test_extra_index_option(pip_with_index_conf, runner): with open("requirements.in", "w"): pass out = runner.invoke( cli, [ "-v", "--extra-index-url", "http://extraindex1.com", "--extra-index-url", "http://extraindex2.com", ], ) assert ( "Using indexes:\n" " http://example.com\n" " http://extraindex1.com\n" " http://extraindex2.com" in out.stderr ) assert ( "--index-url http://example.com\n" "--extra-index-url http://extraindex1.com\n" "--extra-index-url http://extraindex2.com" in out.stderr ) def test_extra_index_envvar(monkeypatch, runner): with open("requirements.in", "w"): pass monkeypatch.setenv("PIP_INDEX_URL", "http://example.com") monkeypatch.setenv( "PIP_EXTRA_INDEX_URL", "http://extraindex1.com http://extraindex2.com" ) out = runner.invoke(cli, ["-v"]) assert ( "Using indexes:\n" " http://example.com\n" " http://extraindex1.com\n" " http://extraindex2.com" in out.stderr ) assert ( "--index-url http://example.com\n" "--extra-index-url http://extraindex1.com\n" "--extra-index-url http://extraindex2.com" in out.stderr ) @pytest.mark.parametrize("option", ("--extra-index-url", "--find-links")) def test_redacted_urls_in_verbose_output(runner, option): """ Test that URLs with sensitive data don't leak to the output. """ with open("requirements.in", "w"): pass out = runner.invoke( cli, [ "--no-header", "--no-emit-index-url", "--no-emit-find-links", "--verbose", option, "http://username:password@example.com", ], ) assert "http://username:****@example.com" in out.stderr assert "password" not in out.stderr def test_trusted_host_option(pip_conf, runner): with open("requirements.in", "w"): pass out = runner.invoke( cli, ["-v", "--trusted-host", "example.com", "--trusted-host", "example2.com"] ) assert "--trusted-host example.com\n--trusted-host example2.com\n" in out.stderr def test_trusted_host_envvar(monkeypatch, pip_conf, runner): with open("requirements.in", "w"): pass monkeypatch.setenv("PIP_TRUSTED_HOST", "example.com example2.com") out = runner.invoke(cli, ["-v"]) assert "--trusted-host example.com\n--trusted-host example2.com\n" in out.stderr @pytest.mark.parametrize( "options", ( pytest.param( ["--trusted-host", "example.com", "--no-emit-trusted-host"], id="trusted host", ), pytest.param( ["--find-links", "wheels", "--no-emit-find-links"], id="find links" ), pytest.param( ["--index-url", "https://index-url", "--no-emit-index-url"], id="index url" ), ), ) def test_all_no_emit_options(runner, options): with open("requirements.in", "w"): pass out = runner.invoke( cli, ["--output-file", "-", "--no-header", "--strip-extras", *options] ) assert out.stdout.strip().splitlines() == [] @pytest.mark.parametrize( ("option", "expected_output"), ( pytest.param( "--emit-index-url", ["--index-url https://index-url"], id="index url" ), pytest.param("--no-emit-index-url", [], id="no index"), ), ) def test_emit_index_url_option(runner, option, expected_output): with open("requirements.in", "w"): pass out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--index-url", "https://index-url", option, ], ) assert out.stdout.strip().splitlines() == expected_output @pytest.mark.network def test_realistic_complex_sub_dependencies(runner, tmp_path): wheels_dir = tmp_path / "wheels" wheels_dir.mkdir() # make a temporary wheel of a fake package subprocess.run( [ "pip", "wheel", "--no-deps", "-w", wheels_dir, os.path.join(PACKAGES_PATH, "fake_with_deps", "."), ], check=True, ) with open("requirements.in", "w") as req_in: req_in.write("fake_with_deps") # require fake package out = runner.invoke(cli, ["-n", "--rebuild", "-f", wheels_dir.as_posix()]) assert out.exit_code == 0 def test_run_as_module_compile(): """piptools can be run as ``python -m piptools ...``.""" result = subprocess.run( [sys.executable, "-m", "piptools", "compile", "--help"], stdout=subprocess.PIPE, check=True, ) # Should have run pip-compile successfully. assert result.stdout.startswith(b"Usage:") assert b"Compile requirements.txt from source files" in result.stdout def test_editable_package(pip_conf, runner): """piptools can compile an editable""" fake_package_dir = os.path.join(PACKAGES_PATH, "small_fake_with_deps") fake_package_dir = path_to_url(fake_package_dir) with open("requirements.in", "w") as req_in: req_in.write("-e " + fake_package_dir) # require editable fake package out = runner.invoke(cli, ["-n"]) assert out.exit_code == 0 assert fake_package_dir in out.stderr assert "small-fake-a==0.1" in out.stderr def test_editable_package_without_non_editable_duplicate(pip_conf, runner): """ piptools keeps editable requirement, without also adding a duplicate "non-editable" requirement variation """ fake_package_dir = os.path.join(PACKAGES_PATH, "small_fake_a") fake_package_dir = path_to_url(fake_package_dir) with open("requirements.in", "w") as req_in: # small_fake_with_unpinned_deps also requires small_fake_a req_in.write( "-e " + fake_package_dir + "\nsmall_fake_with_unpinned_deps" # require editable fake package ) out = runner.invoke(cli, ["-n"]) assert out.exit_code == 0 assert fake_package_dir in out.stderr # Shouldn't include a non-editable small-fake-a==<version>. assert "small-fake-a==" not in out.stderr @legacy_resolver_only def test_editable_package_constraint_without_non_editable_duplicate(pip_conf, runner): """ piptools keeps editable constraint, without also adding a duplicate "non-editable" requirement variation """ fake_package_dir = os.path.join(PACKAGES_PATH, "small_fake_a") fake_package_dir = path_to_url(fake_package_dir) with open("constraints.txt", "w") as constraints: constraints.write("-e " + fake_package_dir) # require editable fake package with open("requirements.in", "w") as req_in: req_in.write( "-c constraints.txt" # require editable fake package "\nsmall_fake_with_unpinned_deps" # This one also requires small_fake_a ) out = runner.invoke(cli, ["--output-file", "-", "--quiet"]) assert out.exit_code == 0 assert fake_package_dir in out.stdout # Shouldn't include a non-editable small-fake-a==<version>. assert "small-fake-a==" not in out.stdout @legacy_resolver_only @pytest.mark.parametrize("req_editable", ((True,), (False,))) def test_editable_package_in_constraints(pip_conf, runner, req_editable): """ piptools can compile an editable that appears in both primary requirements and constraints """ fake_package_dir = os.path.join(PACKAGES_PATH, "small_fake_with_deps") fake_package_dir = path_to_url(fake_package_dir) with open("constraints.txt", "w") as constraints_in: constraints_in.write("-e " + fake_package_dir) with open("requirements.in", "w") as req_in: prefix = "-e " if req_editable else "" req_in.write(prefix + fake_package_dir + "\n-c constraints.txt") out = runner.invoke(cli, ["-n"]) assert out.exit_code == 0 assert fake_package_dir in out.stderr assert "small-fake-a==0.1" in out.stderr @pytest.mark.network def test_editable_package_vcs(runner): vcs_package = ( "git+https://github.com/jazzband/pip-tools@" "f97e62ecb0d9b70965c8eff952c001d8e2722e94" "#egg=pip-tools" ) with open("requirements.in", "w") as req_in: req_in.write("-e " + vcs_package) out = runner.invoke(cli, ["-n", "--rebuild"]) assert out.exit_code == 0 assert vcs_package in out.stderr assert "click" in out.stderr # dependency of pip-tools @pytest.mark.network def test_compile_cached_vcs_package(runner, venv): """ Test pip-compile doesn't write local paths for cached wheels of VCS packages. Regression test for issue GH-1647. """ vcs_package = ( "typing-extensions @ git+https://github.com/python/typing_extensions@" "9c0759a260fe126210a1e2026720000a3c40a919" ) vcs_wheel_prefix = "typing_extensions-4.3.0-py3" # Install and cache VCS package. subprocess.run( [os.fspath(venv / "python"), "-m" "pip", "install", vcs_package], check=True, ) assert ( vcs_wheel_prefix in subprocess.run( [ sys.executable, "-m" "pip", "cache", "list", "--format=abspath", vcs_wheel_prefix, ], check=True, capture_output=True, text=True, ).stdout ) with open("requirements.in", "w") as req_in: req_in.write(vcs_package) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "--no-annotate", "--no-build-isolation", ], ) assert out.exit_code == 0, out assert vcs_package == out.stdout.strip() @legacy_resolver_only def test_locally_available_editable_package_is_not_archived_in_cache_dir( pip_conf, tmpdir, runner ): """ piptools will not create an archive for a locally available editable requirement """ cache_dir = tmpdir.mkdir("cache_dir") fake_package_dir = os.path.join(PACKAGES_PATH, "small_fake_with_deps") fake_package_dir = path_to_url(fake_package_dir) with open("requirements.in", "w") as req_in: req_in.write("-e " + fake_package_dir) # require editable fake package out = runner.invoke(cli, ["-n", "--rebuild", "--cache-dir", str(cache_dir)]) assert out.exit_code == 0 assert fake_package_dir in out.stderr assert "small-fake-a==0.1" in out.stderr # we should not find any archived file in {cache_dir}/pkgs assert not os.listdir(os.path.join(str(cache_dir), "pkgs")) @pytest.mark.parametrize( ("line", "dependency"), ( # use pip-tools version prior to its use of setuptools_scm, # which is incompatible with https: install pytest.param( "https://github.com/jazzband/pip-tools/archive/" "7d86c8d3ecd1faa6be11c7ddc6b29a30ffd1dae3.zip", "\nclick==", id="Zip URL", ), pytest.param( "git+https://github.com/jazzband/pip-tools@" "7d86c8d3ecd1faa6be11c7ddc6b29a30ffd1dae3", "\nclick==", id="VCS URL", ), pytest.param( "https://files.pythonhosted.org/packages/06/96/" "89872db07ae70770fba97205b0737c17ef013d0d1c790" "899c16bb8bac419/pip_tools-3.6.1-py2.py3-none-any.whl", "\nclick==", id="Wheel URL", ), pytest.param( "pytest-django @ git+https://github.com/pytest-dev/pytest-django" "@21492afc88a19d4ca01cd0ac392a5325b14f95c7" "#egg=pytest-django", "pytest-django @ git+https://github.com/pytest-dev/pytest-django" "@21492afc88a19d4ca01cd0ac392a5325b14f95c7", id="VCS with direct reference and egg", ), ), ) @pytest.mark.parametrize("generate_hashes", ((True,), (False,))) @pytest.mark.network def test_url_package(runner, line, dependency, generate_hashes): with open("requirements.in", "w") as req_in: req_in.write(line) out = runner.invoke( cli, ["-n", "--rebuild", "--no-build-isolation"] + (["--generate-hashes"] if generate_hashes else []), ) assert out.exit_code == 0 assert dependency in out.stderr @pytest.mark.parametrize( ("line", "dependency", "rewritten_line"), ( pytest.param( path_to_url( os.path.join( MINIMAL_WHEELS_PATH, "small_fake_with_deps-0.1-py2.py3-none-any.whl" ) ), "\nsmall-fake-a==0.1", None, id="Wheel URI", ), pytest.param( path_to_url(os.path.join(PACKAGES_PATH, "small_fake_with_deps")), "\nsmall-fake-a==0.1", None, id="Local project URI", ), pytest.param( os.path.join( MINIMAL_WHEELS_PATH, "small_fake_with_deps-0.1-py2.py3-none-any.whl" ), "\nsmall-fake-a==0.1", path_to_url( os.path.join( MINIMAL_WHEELS_PATH, "small_fake_with_deps-0.1-py2.py3-none-any.whl" ) ), id="Bare path to file URI", ), pytest.param( os.path.join( MINIMAL_WHEELS_PATH, "small_fake_with_deps-0.1-py2.py3-none-any.whl" ), "\nsmall-fake-with-deps @ " + path_to_url( os.path.join( MINIMAL_WHEELS_PATH, "small_fake_with_deps-0.1-py2.py3-none-any.whl" ) ), "\nsmall-fake-with-deps @ " + path_to_url( os.path.join( MINIMAL_WHEELS_PATH, "small_fake_with_deps-0.1-py2.py3-none-any.whl" ) ), id="Local project with absolute URI", ), pytest.param( path_to_url(os.path.join(PACKAGES_PATH, "small_fake_with_subdir")) + "#subdirectory=subdir&egg=small-fake-a", "small-fake-a @ " + path_to_url(os.path.join(PACKAGES_PATH, "small_fake_with_subdir")) + "#subdirectory=subdir", "small-fake-a @ " + path_to_url(os.path.join(PACKAGES_PATH, "small_fake_with_subdir")) + "#subdirectory=subdir", id="Local project with subdirectory", ), ), ) @pytest.mark.parametrize("generate_hashes", ((True,), (False,))) def test_local_file_uri_package( pip_conf, runner, line, dependency, rewritten_line, generate_hashes ): if rewritten_line is None: rewritten_line = line with open("requirements.in", "w") as req_in: req_in.write(line) out = runner.invoke( cli, ["-n", "--rebuild"] + (["--generate-hashes"] if generate_hashes else []) ) assert out.exit_code == 0 assert rewritten_line in out.stderr assert dependency in out.stderr def test_relative_file_uri_package(pip_conf, runner): # Copy wheel into temp dir shutil.copy( os.path.join( MINIMAL_WHEELS_PATH, "small_fake_with_deps-0.1-py2.py3-none-any.whl" ), ".", ) with open("requirements.in", "w") as req_in: req_in.write("file:small_fake_with_deps-0.1-py2.py3-none-any.whl") out = runner.invoke(cli, ["-n", "--rebuild"]) assert out.exit_code == 0 assert "file:small_fake_with_deps-0.1-py2.py3-none-any.whl" in out.stderr def test_direct_reference_with_extras(runner): with open("requirements.in", "w") as req_in: req_in.write( "pip-tools[testing,coverage] @ git+https://github.com/jazzband/pip-tools@6.2.0" ) out = runner.invoke(cli, ["-n", "--rebuild", "--no-build-isolation"]) assert out.exit_code == 0 assert ( "pip-tools[coverage,testing] @ git+https://github.com/jazzband/pip-tools@6.2.0" in out.stderr ) assert "pytest==" in out.stderr assert "pytest-cov==" in out.stderr def test_input_file_without_extension(pip_conf, runner): """ piptools can compile a file without an extension, and add .txt as the default output file extension. """ with open("requirements", "w") as req_in: req_in.write("small-fake-a==0.1") out = runner.invoke(cli, ["requirements"]) assert out.exit_code == 0 assert "small-fake-a==0.1" in out.stderr assert os.path.exists("requirements.txt") def test_ignore_incompatible_existing_pins(pip_conf, runner): """ Successfully compile when existing output pins conflict with input. """ with open("requirements.txt", "w") as req_txt: req_txt.write("small-fake-a==0.2\nsmall-fake-b==0.2") with open("requirements.in", "w") as req_in: req_in.write("small-fake-with-deps\nsmall-fake-b<0.2") out = runner.invoke(cli, []) assert out.exit_code == 0 def test_upgrade_packages_option(pip_conf, runner): """ piptools respects --upgrade-package/-P inline list. """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a\nsmall-fake-b") with open("requirements.txt", "w") as req_in: req_in.write("small-fake-a==0.1\nsmall-fake-b==0.1") out = runner.invoke(cli, ["--no-annotate", "-P", "small-fake-b"]) assert out.exit_code == 0 assert "small-fake-a==0.1" in out.stderr.splitlines() assert "small-fake-b==0.3" in out.stderr.splitlines() def test_upgrade_packages_option_irrelevant(pip_conf, runner): """ piptools ignores --upgrade-package/-P items not already constrained. """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a") with open("requirements.txt", "w") as req_in: req_in.write("small-fake-a==0.1") out = runner.invoke(cli, ["--no-annotate", "--upgrade-package", "small-fake-b"]) assert out.exit_code == 0 assert "small-fake-a==0.1" in out.stderr.splitlines() assert "small-fake-b==0.3" not in out.stderr.splitlines() def test_upgrade_packages_option_no_existing_file(pip_conf, runner): """ piptools respects --upgrade-package/-P inline list when the output file doesn't exist. """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a\nsmall-fake-b") out = runner.invoke(cli, ["--no-annotate", "-P", "small-fake-b"]) assert out.exit_code == 0 assert "small-fake-a==0.2" in out.stderr.splitlines() assert "small-fake-b==0.3" in out.stderr.splitlines() assert ( "WARNING: the output file requirements.txt exists but is empty" not in out.stderr ) def test_upgrade_packages_empty_target_file_warning(pip_conf, runner): """ piptools warns the user if --upgrade-package/-P is specified and the output file exists, but is empty. """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a==0.2") with open("requirements.txt", "w") as req_txt: req_txt.write("") out = runner.invoke(cli, ["--no-annotate", "-P", "small-fake-a"]) assert out.exit_code == 0 assert "small-fake-a==0.2" in out.stderr.splitlines() assert "WARNING: the output file requirements.txt exists but is empty" in out.stderr @pytest.mark.parametrize( ("current_package", "upgraded_package"), ( pytest.param("small-fake-b==0.1", "small-fake-b==0.3", id="upgrade"), pytest.param("small-fake-b==0.3", "small-fake-b==0.1", id="downgrade"), ), ) def test_upgrade_packages_version_option( pip_conf, runner, current_package, upgraded_package ): """ piptools respects --upgrade-package/-P inline list with specified versions. """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a\nsmall-fake-b") with open("requirements.txt", "w") as req_in: req_in.write("small-fake-a==0.1\n" + current_package) out = runner.invoke(cli, ["--no-annotate", "--upgrade-package", upgraded_package]) assert out.exit_code == 0 stderr_lines = out.stderr.splitlines() assert "small-fake-a==0.1" in stderr_lines assert upgraded_package in stderr_lines def test_upgrade_packages_version_option_no_existing_file(pip_conf, runner): """ piptools respects --upgrade-package/-P inline list with specified versions. """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a\nsmall-fake-b") out = runner.invoke(cli, ["-P", "small-fake-b==0.2"]) assert out.exit_code == 0 assert "small-fake-a==0.2" in out.stderr assert "small-fake-b==0.2" in out.stderr @pytest.mark.parametrize( "reqs_in", ( pytest.param("small-fake-a\nsmall-fake-b", id="direct reqs"), pytest.param("small-fake-with-unpinned-deps", id="parent req"), ), ) def test_upgrade_packages_version_option_and_upgrade(pip_conf, runner, reqs_in): """ piptools respects --upgrade-package/-P inline list with specified versions whilst also doing --upgrade. """ with open("requirements.in", "w") as req_in: req_in.write(reqs_in) with open("requirements.txt", "w") as req_in: req_in.write("small-fake-a==0.1\nsmall-fake-b==0.1") out = runner.invoke(cli, ["--upgrade", "-P", "small-fake-b==0.1"]) assert out.exit_code == 0 assert "small-fake-a==0.2" in out.stderr assert "small-fake-b==0.1" in out.stderr def test_upgrade_packages_version_option_and_upgrade_no_existing_file(pip_conf, runner): """ piptools respects --upgrade-package/-P inline list with specified versions whilst also doing --upgrade and the output file doesn't exist. """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a\nsmall-fake-b") out = runner.invoke(cli, ["--upgrade", "-P", "small-fake-b==0.1"]) assert out.exit_code == 0 assert "small-fake-a==0.2" in out.stderr assert "small-fake-b==0.1" in out.stderr def test_upgrade_package_with_extra(runner, make_package, make_sdist, tmpdir): """ piptools ignores extras on --upgrade-package/-P items if already constrained. """ test_package_1 = make_package( "test_package_1", version="0.1", extras_require={"more": "test_package_2"} ) test_package_2 = make_package( "test_package_2", version="0.1", ) dists_dir = tmpdir / "dists" for pkg in (test_package_1, test_package_2): make_sdist(pkg, dists_dir) # Constrain our requirement with an extra with open("requirements.in", "w") as req_in: req_in.write("test-package-1[more]") # Run update on test-package-1[more] -- this should be equivalent # to running an update on test-package-1 out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--find-links", str(dists_dir), "--no-annotate", "--no-header", "--no-emit-options", "--no-build-isolation", "--upgrade-package", "test-package-1[more]", ], ) assert out.exit_code == 0, out assert ( dedent( """\ test-package-1[more]==0.1 test-package-2==0.1 """ ) == out.stdout ) def test_quiet_option(pip_conf, runner): with open("requirements.in", "w") as req_in: req_in.write("small-fake-a") out = runner.invoke(cli, ["--quiet"]) # Pinned requirements result has not been written to stderr: assert b"small-fake-a" not in out.stderr_bytes def test_dry_run_noisy_option(runner): with open("requirements.in", "w"): pass out = runner.invoke(cli, ["--dry-run"]) # Dry-run message has been written to output assert "Dry-run, so nothing updated." in out.stderr.splitlines() def test_dry_run_quiet_option(runner): with open("requirements.in", "w"): pass out = runner.invoke(cli, ["--output-file", "-", "--dry-run", "--quiet"]) # Neither dry-run message nor pinned requirements written to output: assert not out.stdout_bytes # Dry-run message has not been written to stderr: assert "dry-run" not in out.stderr.lower() # Pinned requirements (just the header in this case) *are* written to stderr: assert "# " in out.stderr def test_generate_hashes_with_editable(pip_conf, runner): small_fake_package_dir = os.path.join(PACKAGES_PATH, "small_fake_with_deps") small_fake_package_url = path_to_url(small_fake_package_dir) with open("requirements.in", "w") as fp: fp.write(f"-e {small_fake_package_url}\n") out = runner.invoke(cli, ["--no-annotate", "--generate-hashes"]) expected = ( "-e {}\n" "small-fake-a==0.1 \\\n" " --hash=sha256:5e6071ee6e4c59e0d0408d366f" "e9b66781d2cf01be9a6e19a2433bb3c5336330\n" "small-fake-b==0.1 \\\n" " --hash=sha256:acdba8f8b8a816213c30d5310c" "3fe296c0107b16ed452062f7f994a5672e3b3f\n" ).format(small_fake_package_url) assert out.exit_code == 0 assert expected in out.stderr @pytest.mark.network def test_generate_hashes_with_url(runner): with open("requirements.in", "w") as fp: fp.write( "https://github.com/jazzband/pip-tools/archive/" "7d86c8d3ecd1faa6be11c7ddc6b29a30ffd1dae3.zip#egg=pip-tools\n" ) out = runner.invoke(cli, ["--no-annotate", "--generate-hashes"]) expected = ( "pip-tools @ https://github.com/jazzband/pip-tools/archive/" "7d86c8d3ecd1faa6be11c7ddc6b29a30ffd1dae3.zip \\\n" " --hash=sha256:d24de92e18ad5bf291f25cfcdcf" "0171be6fa70d01d0bef9eeda356b8549715e7\n" ) assert out.exit_code == 0 assert expected in out.stderr def test_generate_hashes_verbose(pip_conf, runner): """ The hashes generation process should show a progress. """ with open("requirements.in", "w") as fp: fp.write("small-fake-a==0.1") out = runner.invoke(cli, ["--generate-hashes", "-v"]) expected_verbose_text = "Generating hashes:\n small-fake-a\n" assert expected_verbose_text in out.stderr @pytest.mark.network def test_generate_hashes_with_annotations(runner): with open("requirements.in", "w") as fp: fp.write("six==1.15.0") out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--generate-hashes", ], ) assert out.stdout == dedent( """\ six==1.15.0 \\ --hash=sha256:30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259 \\ --hash=sha256:8b74bedcbbbaca38ff6d7491d76f2b06b3592611af620f8426e82dddb04a5ced # via -r requirements.in """ ) @pytest.mark.network @pytest.mark.parametrize("gen_hashes", (True, False)) @pytest.mark.parametrize( "annotate_options", ( ("--no-annotate",), ("--annotation-style", "line"), ("--annotation-style", "split"), ), ) @pytest.mark.parametrize( ("nl_options", "must_include", "must_exclude"), ( pytest.param(("--newline", "lf"), b"\n", b"\r\n", id="LF"), pytest.param(("--newline", "crlf"), b"\r\n", b"\n", id="CRLF"), pytest.param( ("--newline", "native"), os.linesep.encode(), {"\n": b"\r\n", "\r\n": b"\n"}[os.linesep], id="native", ), ), ) def test_override_newline( pip_conf, runner, gen_hashes, annotate_options, nl_options, must_include, must_exclude, tmp_path, ): opts = annotate_options + nl_options if gen_hashes: opts += ("--generate-hashes",) example_dir = tmp_path / "example_dir" example_dir.mkdir() in_path = example_dir / "requirements.in" out_path = example_dir / "requirements.txt" in_path.write_bytes(b"small-fake-a==0.1\nsmall-fake-b\n") runner.invoke( cli, [*opts, f"--output-file={os.fsdecode(out_path)}", os.fsdecode(in_path)] ) txt = out_path.read_bytes() assert must_include in txt if must_exclude in must_include: txt = txt.replace(must_include, b"") assert must_exclude not in txt # Do it again, with --newline=preserve: opts = annotate_options + ("--newline", "preserve") if gen_hashes: opts += ("--generate-hashes",) runner.invoke( cli, [*opts, f"--output-file={os.fsdecode(out_path)}", os.fsdecode(in_path)] ) txt = out_path.read_bytes() assert must_include in txt if must_exclude in must_include: txt = txt.replace(must_include, b"") assert must_exclude not in txt @pytest.mark.network @pytest.mark.parametrize( ("linesep", "must_exclude"), (pytest.param("\n", "\r\n", id="LF"), pytest.param("\r\n", "\n", id="CRLF")), ) def test_preserve_newline_from_input(runner, linesep, must_exclude): with open("requirements.in", "wb") as req_in: req_in.write(f"six{linesep}".encode()) runner.invoke(cli, ["--newline=preserve", "requirements.in"]) with open("requirements.txt", "rb") as req_txt: txt = req_txt.read().decode() assert linesep in txt if must_exclude in linesep: txt = txt.replace(linesep, "") assert must_exclude not in txt def test_generate_hashes_with_split_style_annotations(pip_conf, runner, tmpdir_cwd): reqs_in = tmpdir_cwd / "requirements.in" reqs_in.write_text( dedent( """\ small_fake_with_deps small-fake-a """ ) ) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "--generate-hashes", "--annotation-style", "split", ], ) assert out.stdout == dedent( """\ small-fake-a==0.1 \\ --hash=sha256:5e6071ee6e4c59e0d0408d366fe9b66781d2cf01be9a6e19a2433bb3c5336330 # via # -r requirements.in # small-fake-with-deps small-fake-with-deps==0.1 \\ --hash=sha256:71403033c0545516cc5066c9196d9490affae65a865af3198438be6923e4762e # via -r requirements.in """ ) def test_generate_hashes_with_line_style_annotations(pip_conf, runner, tmpdir_cwd): reqs_in = tmpdir_cwd / "requirements.in" reqs_in.write_text( dedent( """\ small_fake_with_deps small-fake-a """ ) ) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "--generate-hashes", "--annotation-style", "line", ], ) assert out.stdout == dedent( """\ small-fake-a==0.1 \\ --hash=sha256:5e6071ee6e4c59e0d0408d366fe9b66781d2cf01be9a6e19a2433bb3c5336330 # via -r requirements.in, small-fake-with-deps small-fake-with-deps==0.1 \\ --hash=sha256:71403033c0545516cc5066c9196d9490affae65a865af3198438be6923e4762e # via -r requirements.in """ ) @pytest.mark.network def test_generate_hashes_with_mixed_sources( runner, make_package, make_wheel, make_sdist, tmp_path ): """ Test that pip-compile generate hashes for every file from all given sources: PyPI and/or --find-links. """ wheels_dir = tmp_path / "wheels" wheels_dir.mkdir() dummy_six_pkg = make_package(name="six", version="1.16.0") make_wheel(dummy_six_pkg, wheels_dir, "--build-number", "123") fav_hasher = hashlib.new(FAVORITE_HASH) fav_hasher.update((wheels_dir / "six-1.16.0-123-py3-none-any.whl").read_bytes()) dummy_six_wheel_digest = fav_hasher.hexdigest() with open("requirements.in", "w") as fp: fp.write("six==1.16.0\n") out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--generate-hashes", "--no-emit-options", "--no-annotate", "--find-links", wheels_dir.as_uri(), ], ) expected_digests = sorted( ( # sdist hash for six-1.16.0.tar.gz from PyPI "1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926", # wheel hash for six-1.16.0-py2.py3-none-any.whl from PyPI "8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254", # wheel hash for local six-1.16.0-123-py3-none-any.whl file dummy_six_wheel_digest, ) ) expected_output = dedent( f"""\ six==1.16.0 \\ --hash=sha256:{expected_digests[0]} \\ --hash=sha256:{expected_digests[1]} \\ --hash=sha256:{expected_digests[2]} """ ) assert out.stdout == expected_output def test_filter_pip_markers(pip_conf, runner): """ Check that pip-compile works with pip environment markers (PEP496) """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a==0.1\nunknown_package==0.1; python_version == '1'") out = runner.invoke(cli, ["--output-file", "-", "--quiet"]) assert out.exit_code == 0 assert "small-fake-a==0.1" in out.stdout assert "unknown_package" not in out.stdout def test_bad_setup_file(runner): with open("setup.py", "w") as package: package.write("BAD SYNTAX") out = runner.invoke(cli, ["--no-build-isolation"]) assert out.exit_code == 2 assert f"Failed to parse {os.path.abspath('setup.py')}" in out.stderr @legacy_resolver_only def test_no_candidates(pip_conf, runner): with open("requirements", "w") as req_in: req_in.write("small-fake-a>0.3b1,<0.3b2") out = runner.invoke(cli, ["-n", "requirements"]) assert out.exit_code == 2 assert "Skipped pre-versions:" in out.stderr @legacy_resolver_only def test_no_candidates_pre(pip_conf, runner): with open("requirements", "w") as req_in: req_in.write("small-fake-a>0.3b1,<0.3b1") out = runner.invoke(cli, ["-n", "requirements", "--pre"]) assert out.exit_code == 2 assert "Tried pre-versions:" in out.stderr @pytest.mark.parametrize( ("url", "expected_url"), ( pytest.param("https://example.com", b"https://example.com", id="regular url"), pytest.param( "https://username:password@example.com", b"https://username:****@example.com", id="url with credentials", ), ), ) def test_default_index_url(make_pip_conf, url, expected_url): """ Test help's output with default index URL. """ make_pip_conf( dedent( f"""\ [global] index-url = {url} """ ) ) result = subprocess.run( [sys.executable, "-m", "piptools", "compile", "--help"], stdout=subprocess.PIPE, check=True, ) assert expected_url in result.stdout def test_stdin_without_output_file(runner): """ The --output-file option is required for STDIN. """ out = runner.invoke(cli, ["-n", "-"]) assert out.exit_code == 2 assert "--output-file is required if input is from stdin" in out.stderr def test_stdin(pip_conf, runner): """ Test compile requirements from STDIN. """ out = runner.invoke( cli, ["-", "--output-file", "-", "--quiet", "--no-emit-options", "--no-header"], input="small-fake-a==0.1", ) assert out.stdout == dedent( """\ small-fake-a==0.1 # via -r - """ ) def test_multiple_input_files_without_output_file(runner): """ The --output-file option is required for multiple requirement input files. """ with open("src_file1.in", "w") as req_in: req_in.write("six==1.10.0") with open("src_file2.in", "w") as req_in: req_in.write("django==2.1") out = runner.invoke(cli, ["src_file1.in", "src_file2.in"]) assert ( "--output-file is required if two or more input files are given" in out.stderr ) assert out.exit_code == 2 @pytest.mark.parametrize( ("options", "expected"), ( pytest.param( ("--annotate",), """\ small-fake-a==0.1 # via # -c constraints.txt # small-fake-with-deps small-fake-with-deps==0.1 # via -r requirements.in """, id="annotate", ), pytest.param( ("--annotate", "--annotation-style", "line"), """\ small-fake-a==0.1 # via -c constraints.txt, small-fake-with-deps small-fake-with-deps==0.1 # via -r requirements.in """, id="annotate line style", ), pytest.param( ("--no-annotate",), """\ small-fake-a==0.1 small-fake-with-deps==0.1 """, id="no annotate", ), ), ) def test_annotate_option(pip_conf, runner, options, expected): """ The output lines have annotations if the option is turned on. """ with open("constraints.txt", "w") as constraints_in: constraints_in.write("small-fake-a==0.1") with open("requirements.in", "w") as req_in: req_in.write("-c constraints.txt\n") req_in.write("small_fake_with_deps") out = runner.invoke( cli, [*options, "--output-file", "-", "--quiet", "--no-emit-options", "--no-header"], ) assert out.exit_code == 0, out assert out.stdout == dedent(expected) @pytest.mark.parametrize( ("option", "expected"), ( pytest.param( "--allow-unsafe", dedent( """\ small-fake-a==0.1 small-fake-b==0.3 # The following packages are considered to be unsafe in a requirements file: small-fake-with-deps==0.1 """ ), id="allow all packages", ), pytest.param( "--no-allow-unsafe", dedent( """\ small-fake-a==0.1 small-fake-b==0.3 # The following packages are considered to be unsafe in a requirements file: # small-fake-with-deps """ ), id="comment out small-fake-with-deps and its dependencies", ), pytest.param( None, dedent( """\ small-fake-a==0.1 small-fake-b==0.3 # The following packages are considered to be unsafe in a requirements file: # small-fake-with-deps """ ), id="allow unsafe is default option", ), ), ) def test_allow_unsafe_option(pip_conf, monkeypatch, runner, option, expected): """ Unsafe packages are printed as expected with and without --allow-unsafe. """ monkeypatch.setattr("piptools.resolver.UNSAFE_PACKAGES", {"small-fake-with-deps"}) with open("requirements.in", "w") as req_in: req_in.write("small-fake-b\n") req_in.write("small-fake-with-deps") out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "--no-annotate", *([option] if option else []), ], ) assert out.exit_code == 0, out assert out.stdout == expected @pytest.mark.parametrize( ("unsafe_package", "expected"), ( ( "small-fake-with-deps", dedent( """\ small-fake-a==0.1 small-fake-b==0.3 # The following packages are considered to be unsafe in a requirements file: # small-fake-with-deps """ ), ), ( "small-fake-a", dedent( """\ small-fake-b==0.3 small-fake-with-deps==0.1 # The following packages are considered to be unsafe in a requirements file: # small-fake-a """ ), ), ), ) def test_unsafe_package_option(pip_conf, monkeypatch, runner, unsafe_package, expected): monkeypatch.setattr("piptools.resolver.UNSAFE_PACKAGES", {"small-fake-with-deps"}) with open("requirements.in", "w") as req_in: req_in.write("small-fake-b\n") req_in.write("small-fake-with-deps") out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "--no-annotate", "--unsafe-package", unsafe_package, ], ) assert out.exit_code == 0, out assert out.stdout == expected @pytest.mark.parametrize( "unsafe_package", ( pytest.param("small-fake-with-deps", id="kebab-case"), pytest.param("small_fake_with_deps", id="snake_case"), pytest.param("Small_Fake_With_Deps", id="mixed-case"), ), ) def test_unsafe_package_option_normalizes(pip_conf, runner, unsafe_package): """ The --unsafe-package option should normalize package names. """ pathlib.Path("requirements.in").write_text( dedent( """\ small_fake_b small-fake-with-deps """ ), encoding="utf-8", ) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "--no-annotate", "--no-allow-unsafe", "--unsafe-package", unsafe_package, ], ) assert out.exit_code == 0, out assert out.stdout == dedent( """\ small-fake-a==0.1 small-fake-b==0.3 # The following packages are considered to be unsafe in a requirements file: # small-fake-with-deps """ ) @pytest.mark.parametrize( ("option", "attr", "expected"), (("--cert", "cert", "foo.crt"), ("--client-cert", "client_cert", "bar.pem")), ) @mock.patch("piptools.scripts.compile.parse_requirements") def test_cert_option(parse_requirements, runner, option, attr, expected): """ The options --cert and --client-cert have to be passed to the PyPIRepository. """ with open("requirements.in", "w"): pass runner.invoke(cli, [option, expected]) # Ensure the options in parse_requirements has the expected option args, kwargs = parse_requirements.call_args assert getattr(kwargs["options"], attr) == expected @pytest.mark.parametrize( ("option", "expected"), (("--build-isolation", True), ("--no-build-isolation", False)), ) @mock.patch("piptools.scripts.compile.parse_requirements") def test_parse_requirements_build_isolation_option( parse_requirements, runner, option, expected ): """ A value of the --build-isolation/--no-build-isolation flag must be passed to parse_requirements(). """ with open("requirements.in", "w"): pass runner.invoke(cli, [option]) # Ensure the options in parse_requirements has the expected build_isolation option args, kwargs = parse_requirements.call_args assert kwargs["options"].build_isolation is expected @pytest.mark.parametrize( ("option", "expected"), (("--build-isolation", True), ("--no-build-isolation", False)), ) @mock.patch("piptools.scripts.compile.build_project_metadata") def test_build_project_metadata_isolation_option( build_project_metadata, runner, option, expected ): """ A value of the --build-isolation/--no-build-isolation flag must be passed to build_project_metadata(). """ with open("setup.py", "w") as package: package.write( dedent( """\ from setuptools import setup setup(install_requires=[]) """ ) ) runner.invoke(cli, [option]) # Ensure the options in build_project_metadata has the isolated kwarg _, kwargs = build_project_metadata.call_args assert kwargs["isolated"] is expected @mock.patch("piptools.scripts.compile.PyPIRepository") def test_forwarded_args(PyPIRepository, runner): """ Test the forwarded cli args (--pip-args 'arg...') are passed to the pip command. """ with open("requirements.in", "w"): pass cli_args = ("--no-annotate", "--generate-hashes") pip_args = ("--no-color", "--isolated", "--disable-pip-version-check") runner.invoke(cli, [*cli_args, "--pip-args", " ".join(pip_args)]) args, kwargs = PyPIRepository.call_args assert set(pip_args).issubset(set(args[0])) @pytest.mark.parametrize( "pip_args", ( pytest.param( ("--use-pep517", "--global-option=build_ext"), id="use-pep517 and global-option", ), pytest.param( ("--no-use-pep517", "--build-option=build_ext"), id="no-use-pep517 and build-option", ), ), ) @mock.patch("piptools.scripts.compile.PyPIRepository") def test_forwarded_args_filter_deprecated(PyPIRepository, runner, pip_args): """ Test the cli args (``--pip-args 'arg...'``) are filtered out if pip no longer supports them. """ pathlib.Path("requirements.in").write_text("", encoding="utf-8") cli_args = ("--no-annotate", "--generate-hashes") runner.invoke(cli, [*cli_args, "--pip-args", shlex.join(pip_args)]) pip_option_keys = {pip_arg.split("=")[0] for pip_arg in pip_args} (first_posarg, *_tail_args), _kwargs = PyPIRepository.call_args pip_current_version = get_pip_version_for_python_executable(sys.executable) pip_breaking_version = Version("25.3") if pip_current_version >= pip_breaking_version: # pragma: >=3.9 cover assert set(first_posarg) ^ pip_option_keys else: assert set(first_posarg) & pip_option_keys @pytest.mark.parametrize( ("cli_option", "infile_option", "expected_package"), ( # no --pre pip-compile should resolve to the last stable version (False, False, "small-fake-a==0.2"), # pip-compile --pre should resolve to the last pre-released version (True, False, "small-fake-a==0.3b1"), (False, True, "small-fake-a==0.3b1"), (True, True, "small-fake-a==0.3b1"), ), ) def test_pre_option(pip_conf, runner, cli_option, infile_option, expected_package): """ Tests pip-compile respects --pre option. """ with open("requirements.in", "w") as req_in: if infile_option: req_in.write("--pre\n") req_in.write("small-fake-a\n") out = runner.invoke(cli, ["--no-annotate", "-n"] + (["-p"] if cli_option else [])) assert out.exit_code == 0, out.stderr assert expected_package in out.stderr.splitlines(), out.stderr @pytest.mark.parametrize( "add_options", ( [], ["--output-file", "requirements.txt"], ["--upgrade"], ["--upgrade", "--output-file", "requirements.txt"], ["--upgrade-package", "small-fake-a"], ["--upgrade-package", "small-fake-a", "--output-file", "requirements.txt"], ), ) def test_dry_run_option(pip_conf, runner, add_options): """ Tests pip-compile doesn't create requirements.txt file on dry-run. """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a\n") out = runner.invoke(cli, ["--no-annotate", "--dry-run", *add_options]) assert out.exit_code == 0, out.stderr assert "small-fake-a==0.2" in out.stderr.splitlines() assert not os.path.exists("requirements.txt") @pytest.mark.parametrize( ("add_options", "expected_cli_output_package"), ( ([], "small-fake-a==0.1"), (["--output-file", "requirements.txt"], "small-fake-a==0.1"), (["--upgrade"], "small-fake-a==0.2"), (["--upgrade", "--output-file", "requirements.txt"], "small-fake-a==0.2"), (["--upgrade-package", "small-fake-a"], "small-fake-a==0.2"), ( ["--upgrade-package", "small-fake-a", "--output-file", "requirements.txt"], "small-fake-a==0.2", ), ), ) def test_dry_run_doesnt_touch_output_file( pip_conf, runner, add_options, expected_cli_output_package ): """ Tests pip-compile doesn't touch requirements.txt file on dry-run. """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-a\n") with open("requirements.txt", "w") as req_txt: req_txt.write("small-fake-a==0.1\n") before_compile_mtime = os.stat("requirements.txt").st_mtime out = runner.invoke(cli, ["--no-annotate", "--dry-run", *add_options]) assert out.exit_code == 0, out.stderr assert expected_cli_output_package in out.stderr.splitlines() # The package version must NOT be updated in the output file with open("requirements.txt") as req_txt: assert "small-fake-a==0.1" in req_txt.read().splitlines() # The output file must not be touched after_compile_mtime = os.stat("requirements.txt").st_mtime assert after_compile_mtime == before_compile_mtime @pytest.mark.parametrize( ("empty_input_pkg", "prior_output_pkg"), ( ("", ""), ("", "small-fake-a==0.1\n"), ("# Nothing to see here", ""), ("# Nothing to see here", "small-fake-a==0.1\n"), ), ) def test_empty_input_file_no_header(runner, empty_input_pkg, prior_output_pkg): """ Tests pip-compile creates an empty requirements.txt file, given --no-header and empty requirements.in """ with open("requirements.in", "w") as req_in: req_in.write(empty_input_pkg) # empty input file with open("requirements.txt", "w") as req_txt: req_txt.write(prior_output_pkg) runner.invoke(cli, ["--no-header", "requirements.in"]) with open("requirements.txt") as req_txt: assert req_txt.read().strip() == "" def test_upgrade_package_doesnt_remove_annotation(pip_conf, runner): """ Tests pip-compile --upgrade-package shouldn't remove "via" annotation. See: GH-929 """ with open("requirements.in", "w") as req_in: req_in.write("small-fake-with-deps\n") runner.invoke(cli) # Downgrade small-fake-a to 0.1 with open("requirements.txt", "w") as req_txt: req_txt.write( "small-fake-with-deps==0.1\n" "small-fake-a==0.1 # via small-fake-with-deps\n" ) runner.invoke(cli, ["-P", "small-fake-a", "--no-emit-options", "--no-header"]) with open("requirements.txt") as req_txt: assert req_txt.read() == dedent( """\ small-fake-a==0.1 # via small-fake-with-deps small-fake-with-deps==0.1 # via -r requirements.in """ ) @pytest.mark.parametrize(("num_inputs"), (2, 3, 10)) def test_many_inputs_includes_all_annotations(pip_conf, runner, tmp_path, num_inputs): """ Tests that an entry required by multiple input files is attributed to all of them in the annotation. See: https://github.com/jazzband/pip-tools/issues/1853 """ req_ins = [tmp_path / f"requirements{n:02d}.in" for n in range(num_inputs)] for req_in in req_ins: req_in.write_text("small-fake-a==0.1\n") out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-find-links", ] + [str(r) for r in req_ins], ) assert out.exit_code == 0, out.stderr assert ( out.stdout == "\n".join( [ "small-fake-a==0.1", " # via", ] + [f" # -r {req_in.as_posix()}" for req_in in req_ins] ) + "\n" ) @pytest.mark.parametrize( "options", ( "--index-url https://example.com", "--extra-index-url https://example.com", "--find-links ./libs1", "--trusted-host example.com", "--no-binary :all:", "--only-binary :all:", ), ) def test_options_in_requirements_file(runner, options): """ Test the options from requirements.in is copied to requirements.txt. """ with open("requirements.in", "w") as reqs_in: reqs_in.write(options) out = runner.invoke(cli) assert out.exit_code == 0, out with open("requirements.txt") as reqs_txt: assert options in reqs_txt.read().splitlines() @pytest.mark.parametrize( ("cli_options", "expected_message"), ( pytest.param( ["--index-url", "scheme://foo"], "Was scheme://foo reachable?", id="single index url", ), pytest.param( ["--index-url", "scheme://foo", "--extra-index-url", "scheme://bar"], "Were scheme://foo or scheme://bar reachable?", id="multiple index urls", ), pytest.param( ["--index-url", "scheme://username:password@host"], "Was scheme://username:****@host reachable?", id="index url with credentials", ), ), ) @legacy_resolver_only def test_unreachable_index_urls(runner, cli_options, expected_message): """ Test pip-compile raises an error if index URLs are not reachable. """ with open("requirements.in", "w") as reqs_in: reqs_in.write("some-package") out = runner.invoke(cli, cli_options) assert out.exit_code == 2, out stderr_lines = out.stderr.splitlines() assert "No versions found" in stderr_lines assert expected_message in stderr_lines @pytest.mark.parametrize("subdep_already_pinned", (True, False)) @pytest.mark.parametrize( ("current_package", "upgraded_package"), ( pytest.param("small-fake-b==0.1", "small-fake-b==0.2", id="upgrade"), pytest.param("small-fake-b==0.2", "small-fake-b==0.1", id="downgrade"), ), ) def test_upgrade_packages_option_subdependency( pip_conf, runner, current_package, upgraded_package, subdep_already_pinned ): """ Test that pip-compile --upgrade-package/-P upgrades/downgrades subdependencies. """ with open("requirements.in", "w") as reqs: reqs.write("small-fake-with-unpinned-deps\n") with open("requirements.txt", "w") as reqs: reqs.write("small-fake-a==0.1\n") if subdep_already_pinned: reqs.write(current_package + "\n") reqs.write("small-fake-with-unpinned-deps==0.1\n") out = runner.invoke( cli, ["--no-annotate", "--dry-run", "--upgrade-package", upgraded_package] ) stderr_lines = out.stderr.splitlines() assert "small-fake-a==0.1" in stderr_lines, "small-fake-a must keep its version" assert ( upgraded_package in stderr_lines ), f"{current_package} must be upgraded/downgraded to {upgraded_package}" @pytest.mark.parametrize( ("input_opts", "output_opts"), ( # Test that input options overwrite output options pytest.param( "--index-url https://index-url", "--index-url https://another-index-url", id="index url", ), pytest.param( "--extra-index-url https://extra-index-url", "--extra-index-url https://another-extra-index-url", id="extra index url", ), pytest.param("--find-links dir", "--find-links another-dir", id="find links"), pytest.param( "--trusted-host hostname", "--trusted-host another-hostname", id="trusted host", ), pytest.param( "--no-binary :package:", "--no-binary :another-package:", id="no binary" ), pytest.param( "--only-binary :package:", "--only-binary :another-package:", id="only binary", ), # Test misc corner cases pytest.param("", "--index-url https://index-url", id="empty input options"), pytest.param( "--index-url https://index-url", ( "--index-url https://index-url\n" "--extra-index-url https://another-extra-index-url" ), id="partially matched options", ), ), ) def test_remove_outdated_options(runner, input_opts, output_opts): """ Test that the options from the current requirements.txt wouldn't stay after compile if they were removed from requirements.in file. """ with open("requirements.in", "w") as req_in: req_in.write(input_opts) with open("requirements.txt", "w") as req_txt: req_txt.write(output_opts) out = runner.invoke(cli, ["--output-file", "-", "--quiet", "--no-header"]) assert out.exit_code == 0, out assert out.stdout.strip() == input_opts def test_sub_dependencies_with_constraints(pip_conf, runner): # Write constraints file with open("constraints.txt", "w") as constraints_in: constraints_in.write("small-fake-a==0.1\n") constraints_in.write("small-fake-b==0.2\n") constraints_in.write("small-fake-with-unpinned-deps==0.1") with open("requirements.in", "w") as req_in: req_in.write("-c constraints.txt\n") req_in.write("small_fake_with_deps_and_sub_deps") # require fake package out = runner.invoke(cli, ["--no-annotate"]) assert out.exit_code == 0 req_out_lines = set(out.stderr.splitlines()) assert { "small-fake-a==0.1", "small-fake-b==0.2", "small-fake-with-deps-and-sub-deps==0.1", "small-fake-with-unpinned-deps==0.1", }.issubset(req_out_lines) def test_preserve_compiled_prerelease_version(pip_conf, runner): with open("requirements.in", "w") as req_in: req_in.write("small-fake-a") with open("requirements.txt", "w") as req_txt: req_txt.write("small-fake-a==0.3b1") out = runner.invoke(cli, ["--no-annotate", "--no-header"]) assert out.exit_code == 0, out assert "small-fake-a==0.3b1" in out.stderr.splitlines() @backtracking_resolver_only def test_ignore_compiled_unavailable_version(pip_conf, runner, current_resolver): with open("requirements.in", "w") as req_in: req_in.write("small-fake-a") with open("requirements.txt", "w") as req_txt: req_txt.write("small-fake-a==9999") out = runner.invoke(cli, ["--no-annotate", "--no-header"]) assert out.exit_code == 0, out assert "small-fake-a==" in out.stderr assert "small-fake-a==9999" not in out.stderr.splitlines() assert ( "Discarding small-fake-a==9999 " "(from -r requirements.txt (line 1)) " "to proceed the resolution" ) in out.stderr def test_prefer_binary_dist( pip_conf, make_package, make_sdist, make_wheel, tmpdir, runner ): """ Test pip-compile chooses a correct version of a package with a binary distribution when PIP_PREFER_BINARY environment variable is on. """ dists_dir = tmpdir / "dists" # Make first-package==1.0 and wheels first_package_v1 = make_package(name="first-package", version="1.0") make_wheel(first_package_v1, dists_dir) # Make first-package==2.0 and sdists first_package_v2 = make_package(name="first-package", version="2.0") make_sdist(first_package_v2, dists_dir) # Make second-package==1.0 which depends on first-package, and wheels second_package_v1 = make_package( name="second-package", version="1.0", install_requires=["first-package"] ) make_wheel(second_package_v1, dists_dir) with open("requirements.in", "w") as req_in: req_in.write("second-package") out = runner.invoke( cli, ["--no-annotate", "--find-links", str(dists_dir)], env={"PIP_PREFER_BINARY": "1"}, ) assert out.exit_code == 0, out assert "first-package==1.0" in out.stderr.splitlines(), out.stderr assert "second-package==1.0" in out.stderr.splitlines(), out.stderr @pytest.mark.parametrize("prefer_binary", (True, False)) def test_prefer_binary_dist_even_there_is_source_dists( pip_conf, make_package, make_sdist, make_wheel, tmpdir, runner, prefer_binary ): """ Test pip-compile chooses a correct version of a package with a binary distribution (despite a source dist existing) when PIP_PREFER_BINARY environment variable is on or off. Regression test for issue GH-1118. """ dists_dir = tmpdir / "dists" # Make first version of package with only wheels package_v1 = make_package(name="test-package", version="1.0") make_wheel(package_v1, dists_dir) # Make seconds version with wheels and sdists package_v2 = make_package(name="test-package", version="2.0") make_wheel(package_v2, dists_dir) make_sdist(package_v2, dists_dir) with open("requirements.in", "w") as req_in: req_in.write("test-package") out = runner.invoke( cli, ["--no-annotate", "--find-links", str(dists_dir)], env={"PIP_PREFER_BINARY": str(int(prefer_binary))}, ) assert out.exit_code == 0, out assert "test-package==2.0" in out.stderr.splitlines(), out.stderr @pytest.mark.parametrize("output_content", ("test-package-1==0.1", "")) def test_duplicate_reqs_combined( pip_conf, make_package, make_sdist, tmpdir, runner, output_content ): """ Test pip-compile tracks dependencies properly when install requirements are combined, especially when an output file already exists. Regression test for issue GH-1154. """ test_package_1 = make_package("test_package_1", version="0.1") test_package_2 = make_package( "test_package_2", version="0.1", install_requires=["test-package-1"] ) dists_dir = tmpdir / "dists" for pkg in (test_package_1, test_package_2): make_sdist(pkg, dists_dir) with open("requirements.in", "w") as reqs_in: reqs_in.write(f"file:{test_package_2}\n") reqs_in.write(f"file:{test_package_2}#egg=test-package-2\n") if output_content: with open("requirements.txt", "w") as reqs_out: reqs_out.write(output_content) out = runner.invoke(cli, ["--find-links", str(dists_dir)]) assert out.exit_code == 0, out assert str(test_package_2) in out.stderr assert "test-package-1==0.1" in out.stderr def test_local_duplicate_subdependency_combined(runner, make_package): """ Test pip-compile tracks subdependencies properly when install requirements are combined, especially when local paths are passed as urls, and those reqs are combined after getting dependencies. Regression test for issue GH-1505. """ package_a = make_package("project-a", install_requires=["pip-tools==6.3.0"]) package_b = make_package("project-b", install_requires=["project-a"]) with open("requirements.in", "w") as req_in: req_in.writelines( [ f"file://{package_a}#egg=project-a\n", f"file://{package_b}#egg=project-b", ] ) out = runner.invoke(cli, ["-n"]) assert out.exit_code == 0 assert "project-b" in out.stderr assert "project-a" in out.stderr assert "pip-tools==6.3.0" in out.stderr assert "click" in out.stderr # dependency of pip-tools def test_combine_extras(pip_conf, runner, make_package): """ Ensure that multiple declarations of a dependency that specify different extras produces a requirement for that package with the union of the extras """ package_with_extras = make_package( "package_with_extras", extras_require={ "extra1": ["small-fake-a==0.1"], "extra2": ["small-fake-b==0.1"], }, ) with open("requirements.in", "w") as req_in: req_in.writelines( [ "-r ./requirements-second.in\n", f"{package_with_extras}[extra1]", ] ) with open("requirements-second.in", "w") as req_sec_in: req_sec_in.write(f"{package_with_extras}[extra2]") out = runner.invoke(cli, ["-n"]) assert out.exit_code == 0 assert "package-with-extras" in out.stderr assert "small-fake-a==" in out.stderr assert "small-fake-b==" in out.stderr def test_combine_different_extras_of_the_same_package( pip_conf, runner, tmpdir, make_package, make_wheel ): """ Loosely based on the example from https://github.com/jazzband/pip-tools/issues/1511. """ pkgs = [ make_package( "fake-colorful", version="0.3", ), make_package( "fake-tensorboardX", version="0.5", ), make_package( "fake-ray", version="0.1", extras_require={ "default": ["fake-colorful==0.3"], "tune": ["fake-tensorboardX==0.5"], }, ), make_package( "fake-tune-sklearn", version="0.7", install_requires=[ "fake-ray[tune]==0.1", ], ), ] dists_dir = tmpdir / "dists" for pkg in pkgs: make_wheel(pkg, dists_dir) with open("requirements.in", "w") as req_in: req_in.writelines( [ "fake-ray[default]==0.1\n", "fake-tune-sklearn==0.7\n", ] ) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--find-links", str(dists_dir), "--no-header", "--no-emit-options", ], ) assert out.exit_code == 0 assert ( dedent( """\ fake-colorful==0.3 # via fake-ray fake-ray[default,tune]==0.1 # via # -r requirements.in # fake-tune-sklearn fake-tensorboardx==0.5 # via fake-ray fake-tune-sklearn==0.7 # via -r requirements.in """ ) == out.stdout ) def test_canonicalize_extras(pip_conf, runner, tmp_path, make_package, make_wheel): """ Ensure extras are written in a consistent format. """ pkgs = [ make_package( "fake-sqlalchemy", version="0.1", extras_require={"fake-postgresql_psycoPG2BINARY": ["fake-greenlet"]}, ), make_package( "fake-greenlet", version="0.2", ), ] dists_dir = tmp_path / "dists" for pkg in pkgs: make_wheel(pkg, dists_dir) with open("requirements.in", "w") as req_in: req_in.write("fake-sqlalchemy[FAKE_postgresql-psycopg2binary]\n") out = runner.invoke( cli, [ "--output-file", "-", "--find-links", str(dists_dir), "--no-header", "--no-emit-options", "--no-annotate", "--no-strip-extras", ], ) assert out.exit_code == 0 assert ( "fake-sqlalchemy[fake-postgresql-psycopg2binary]==0.1" in out.stdout.splitlines() ) @pytest.mark.parametrize( ("pkg2_install_requires", "req_in_content", "out_expected_content"), ( pytest.param( "", ["test-package-1===0.1.0\n"], ["test-package-1===0.1.0"], id="pin package with ===", ), pytest.param( "", ["test-package-1==0.1.0\n"], ["test-package-1==0.1.0"], id="pin package with ==", ), pytest.param( "test-package-1==0.1.0", ["test-package-1===0.1.0\n", "test-package-2==0.1.0\n"], ["test-package-1===0.1.0", "test-package-2==0.1.0"], id="dep === pin preferred over == pin, main package == pin", ), pytest.param( "test-package-1==0.1.0", ["test-package-1===0.1.0\n", "test-package-2===0.1.0\n"], ["test-package-1===0.1.0", "test-package-2===0.1.0"], id="dep === pin preferred over == pin, main package === pin", ), pytest.param( "test-package-1==0.1.0", ["test-package-2===0.1.0\n"], ["test-package-1==0.1.0", "test-package-2===0.1.0"], id="dep == pin conserved, main package === pin", ), ), ) def test_triple_equal_pinned_dependency_is_used( runner, make_package, make_wheel, tmpdir, pkg2_install_requires, req_in_content, out_expected_content, ): """ Test that pip-compile properly emits the pinned requirement with === torchvision 0.8.2 requires torch==1.7.1 which can resolve to versions with patches (e.g. torch 1.7.1+cu110), we want torch===1.7.1 without patches """ dists_dir = tmpdir / "dists" test_package_1 = make_package("test_package_1", version="0.1.0") make_wheel(test_package_1, dists_dir) test_package_2 = make_package( "test_package_2", version="0.1.0", install_requires=[pkg2_install_requires] ) make_wheel(test_package_2, dists_dir) with open("requirements.in", "w") as reqs_in: for line in req_in_content: reqs_in.write(line) out = runner.invoke(cli, ["--find-links", str(dists_dir)]) assert out.exit_code == 0, out for line in out_expected_content: assert line in out.stderr METADATA_TEST_CASES = ( pytest.param( "setup.cfg", """ [metadata] name = sample_lib author = Vincent Driessen author_email = me@nvie.com [options] packages = find: install_requires = small-fake-a==0.1 [options.extras_require] dev = small-fake-b==0.2 test = small-fake-c==0.3 """, id="setup.cfg", ), pytest.param( "setup.py", """ from setuptools import setup, find_packages setup( name="sample_lib", version=0.1, install_requires=["small-fake-a==0.1"], packages=find_packages(), extras_require={ "dev": ["small-fake-b==0.2"], "test": ["small-fake-c==0.3"], }, ) """, id="setup.py", ), pytest.param( "pyproject.toml", """ [build-system] requires = ["flit_core >=2,<4"] build-backend = "flit_core.buildapi" [tool.flit.metadata] module = "sample_lib" author = "Vincent Driessen" author-email = "me@nvie.com" requires = ["small-fake-a==0.1"] [tool.flit.metadata.requires-extra] dev = ["small-fake-b==0.2"] test = ["small-fake-c==0.3"] """, id="flit", ), pytest.param( "pyproject.toml", """ [build-system] requires = ["poetry_core>=1.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry] name = "sample_lib" version = "0.1.0" description = "" authors = ["Vincent Driessen <me@nvie.com>"] [tool.poetry.dependencies] python = "*" small-fake-a = "0.1" small-fake-b = "0.2" small-fake-c = "0.3" [tool.poetry.extras] dev = ["small-fake-b"] test = ["small-fake-c"] """, id="poetry", ), ) @pytest.mark.network @pytest.mark.parametrize(("fname", "content"), METADATA_TEST_CASES) def test_not_specified_input_file( fake_dists, runner, make_module, fname, content, monkeypatch ): """ Test that a default-named file is parsed if present. """ meta_path = make_module(fname=fname, content=content) monkeypatch.chdir(os.path.dirname(meta_path)) out = runner.invoke( cli, [ "--output-file", "-", "--no-header", "--no-emit-options", "--no-annotate", "--no-build-isolation", "--find-links", fake_dists, ], ) monkeypatch.undo() assert out.exit_code == 0, out.stderr assert "small-fake-a==0.1\n" == out.stdout def test_not_specified_input_file_without_allowed_files(runner): """ It should raise an error if there are no input files or default input files such as "setup.py" or "requirements.in". """ out = runner.invoke(cli) assert out.exit_code == 2 expected_error = ( "Error: Invalid value: If you do not specify an input file, the default " "is one of: requirements.in, setup.py, pyproject.toml, setup.cfg" ) assert expected_error in out.stderr.splitlines() @pytest.mark.network @pytest.mark.parametrize(("fname", "content"), METADATA_TEST_CASES) def test_input_formats(fake_dists, runner, make_module, fname, content): """ Test different dependency formats as input file. """ meta_path = make_module(fname=fname, content=content) out = runner.invoke( cli, ["-n", "--no-build-isolation", "--find-links", fake_dists, meta_path] ) assert out.exit_code == 0, out.stderr assert "small-fake-a==0.1" in out.stderr assert "small-fake-b" not in out.stderr assert "small-fake-c" not in out.stderr assert "extra ==" not in out.stderr @pytest.mark.parametrize("verbose_option", (True, False)) def test_error_in_pyproject_toml( fake_dists, runner, make_module, capfd, verbose_option ): """ Test that an error in pyproject.toml is reported. """ fname = "pyproject.toml" invalid_content = dedent( """\ [project] invalid = "metadata" """ ) meta_path = make_module(fname=fname, content=invalid_content) options = [] if verbose_option: options = ["--verbose"] options.extend( ["-n", "--no-build-isolation", "--find-links", fake_dists, meta_path] ) out = runner.invoke(cli, options) assert out.exit_code == 2, out.stderr captured = capfd.readouterr() assert ( bool(re.search(r"`project` must contain \['[^']+'\] properties", captured.err)) ) is verbose_option @pytest.mark.network @pytest.mark.parametrize(("fname", "content"), METADATA_TEST_CASES) def test_one_extra(fake_dists, runner, make_module, fname, content): """ Test one ``--extra`` (dev) passed, other extras (test) must be ignored. """ meta_path = make_module(fname=fname, content=content) out = runner.invoke( cli, [ "-n", "--extra", "dev", "--no-build-isolation", "--find-links", fake_dists, meta_path, ], ) assert out.exit_code == 0, out.stderr assert "small-fake-a==0.1" in out.stderr assert "small-fake-b==0.2" in out.stderr assert "extra ==" not in out.stderr @pytest.mark.network @pytest.mark.parametrize( "extra_opts", ( pytest.param(("--extra", "dev", "--extra", "test"), id="singular"), pytest.param(("--extra", "dev,test"), id="comma-separated"), ), ) @pytest.mark.parametrize(("fname", "content"), METADATA_TEST_CASES) def test_multiple_extras(fake_dists, runner, make_module, fname, content, extra_opts): """ Test passing multiple ``--extra`` params. """ meta_path = make_module(fname=fname, content=content) out = runner.invoke( cli, [ "-n", *extra_opts, "--no-build-isolation", "--find-links", fake_dists, meta_path, ], ) assert out.exit_code == 0, out.stderr assert "small-fake-a==0.1" in out.stderr assert "small-fake-b==0.2" in out.stderr assert "extra ==" not in out.stderr @pytest.mark.network @pytest.mark.parametrize(("fname", "content"), METADATA_TEST_CASES) def test_all_extras(fake_dists, runner, make_module, fname, content): """ Test passing ``--all-extras`` includes all applicable extras. """ meta_path = make_module(fname=fname, content=content) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--all-extras", "--find-links", fake_dists, "--no-annotate", "--no-emit-options", "--no-header", "--no-build-isolation", meta_path, ], ) assert out.exit_code == 0, out assert ( dedent( """\ small-fake-a==0.1 small-fake-b==0.2 small-fake-c==0.3 """ ) == out.stdout ) # This should not depend on the metadata format so testing all cases is wasteful @pytest.mark.parametrize(("fname", "content"), METADATA_TEST_CASES[:1]) def test_all_extras_fail_with_extra(fake_dists, runner, make_module, fname, content): """ Test that passing ``--all-extras`` and ``--extra`` fails. """ meta_path = make_module(fname=fname, content=content) out = runner.invoke( cli, [ "-n", "--all-extras", "--extra", "dev", "--find-links", fake_dists, "--no-annotate", "--no-emit-options", "--no-header", "--no-build-isolation", meta_path, ], ) assert out.exit_code == 2 exp = "--extra has no effect when used with --all-extras" assert exp in out.stderr def _mock_resolver_cls(monkeypatch: pytest.MonkeyPatch) -> MagicMock: obj = MagicMock() obj.resolve = MagicMock(return_value=set()) obj.resolve_hashes = MagicMock(return_value=dict()) cls = MagicMock(return_value=obj) monkeypatch.setattr("piptools.scripts.compile.BacktrackingResolver", cls) monkeypatch.setattr("piptools.scripts.compile.LegacyResolver", cls) return cls def _mock_build_project_metadata(monkeypatch: pytest.MonkeyPatch) -> MagicMock: func = MagicMock( return_value=ProjectMetadata( extras=("e",), requirements=( install_req_from_line("rdep0"), install_req_from_line("rdep1; extra=='e'"), ), build_requirements=(install_req_from_line("bdep0"),), ) ) monkeypatch.setattr("piptools.scripts.compile.build_project_metadata", func) return func @backtracking_resolver_only @pytest.mark.network def test_all_extras_and_all_build_deps( fake_dists_with_build_deps, runner, tmp_path, monkeypatch, current_resolver, ): """ Test that trying to lock all dependencies gives the expected output. """ src_pkg_path = pathlib.Path(PACKAGES_PATH) / "small_fake_with_build_deps" # When used as argument to the runner it is not passed to pip monkeypatch.setenv("PIP_FIND_LINKS", fake_dists_with_build_deps) with runner.isolated_filesystem(tmp_path) as tmp_pkg_path: shutil.copytree(src_pkg_path, tmp_pkg_path, dirs_exist_ok=True) out = runner.invoke( cli, [ "--allow-unsafe", "--output-file", "-", "--quiet", "--no-emit-options", "--no-header", "--all-extras", "--all-build-deps", ], ) assert out.exit_code == 0 # Note that the build dependencies of our build dependencies are not resolved. # This means that if our build dependencies are not available as wheels then we will not get # reproducible results. assert "fake_transient_build_dep" not in out.stdout assert out.stdout == dedent( """\ fake-direct-extra-runtime-dep==0.2 # via small-fake-with-build-deps (setup.py) fake-direct-runtime-dep==0.1 # via small-fake-with-build-deps (setup.py) fake-dynamic-build-dep-for-all==0.2 # via # small-fake-with-build-deps (pyproject.toml::build-system.backend::editable) # small-fake-with-build-deps (pyproject.toml::build-system.backend::sdist) # small-fake-with-build-deps (pyproject.toml::build-system.backend::wheel) fake-dynamic-build-dep-for-editable==0.5 # via small-fake-with-build-deps (pyproject.toml::build-system.backend::editable) fake-dynamic-build-dep-for-sdist==0.3 # via small-fake-with-build-deps (pyproject.toml::build-system.backend::sdist) fake-dynamic-build-dep-for-wheel==0.4 # via small-fake-with-build-deps (pyproject.toml::build-system.backend::wheel) fake-static-build-dep==0.1 # via small-fake-with-build-deps (pyproject.toml::build-system.requires) fake-transient-run-dep==0.3 # via fake-static-build-dep wheel==0.41.1 # via # small-fake-with-build-deps (pyproject.toml::build-system.backend::wheel) # small-fake-with-build-deps (pyproject.toml::build-system.requires) # The following packages are considered to be unsafe in a requirements file: setuptools==68.1.2 # via small-fake-with-build-deps (pyproject.toml::build-system.requires) """ ) @backtracking_resolver_only def test_all_build_deps(runner, tmp_path, monkeypatch): """ Test that ``--all-build-deps`` is equivalent to specifying every ``--build-deps-for``. """ func = _mock_build_project_metadata(monkeypatch) _mock_resolver_cls(monkeypatch) src_file = tmp_path / "pyproject.toml" src_file.touch() out = runner.invoke( cli, [ "--all-build-deps", os.fspath(src_file), ], ) assert out.exit_code == 0 assert func.call_args.kwargs["build_targets"] == ( "editable", "sdist", "wheel", ) @backtracking_resolver_only def test_only_build_deps(runner, tmp_path, monkeypatch): """ Test that ``--only-build-deps`` excludes dependencies other than build dependencies. """ _mock_build_project_metadata(monkeypatch) cls = _mock_resolver_cls(monkeypatch) src_file = tmp_path / "pyproject.toml" src_file.touch() out = runner.invoke( cli, [ "--all-build-deps", "--only-build-deps", os.fspath(src_file), ], ) assert out.exit_code == 0 assert [c.name for c in cls.call_args.kwargs["constraints"]] == ["bdep0"] @backtracking_resolver_only def test_all_build_deps_fail_with_build_target(runner): """ Test that passing ``--all-build-deps`` and ``--build-deps-for`` fails. """ out = runner.invoke( cli, [ "--all-build-deps", "--build-deps-for", "sdist", ], ) exp = "--build-deps-for has no effect when used with --all-build-deps" assert out.exit_code == 2 assert exp in out.stderr @backtracking_resolver_only def test_only_build_deps_fails_without_any_build_deps(runner): """ Test that passing ``--only-build-deps`` fails when it is not specified how build deps should be gathered. """ out = runner.invoke( cli, ["--only-build-deps"], ) exp = "--only-build-deps requires either --build-deps-for or --all-build-deps" assert out.exit_code == 2 assert exp in out.stderr @backtracking_resolver_only @pytest.mark.parametrize("option", ("--all-extras", "--extra=foo")) def test_only_build_deps_fails_with_conflicting_options(runner, option): """ Test that passing ``--all-build-deps`` and conflicting option fails. """ out = runner.invoke( cli, [ "--all-build-deps", "--only-build-deps", option, ], ) exp = "--only-build-deps cannot be used with any of --extra, --all-extras" assert out.exit_code == 2 assert exp in out.stderr @backtracking_resolver_only @pytest.mark.parametrize("option", ("--all-build-deps", "--build-deps-for=wheel")) def test_build_deps_fail_without_setup_file(runner, tmpdir, option): """ Test that passing ``--build-deps-for`` or ``--all-build-deps`` fails when used with a requirements file as opposed to a setup file. """ path = pathlib.Path(tmpdir) / "requirements.in" path.write_text("\n") out = runner.invoke(cli, ["-n", option, os.fspath(path)]) exp = ( "--build-deps-for and --all-build-deps can be used only with the " "setup.py, setup.cfg and pyproject.toml specs." ) assert out.exit_code == 2 assert exp in out.stderr def test_extras_fail_with_requirements_in(runner, tmpdir): """ Test that passing ``--extra`` with ``requirements.in`` input file fails. """ path = pathlib.Path(tmpdir) / "requirements.in" path.write_text("\n") out = runner.invoke(cli, ["-n", "--extra", "something", os.fspath(path)]) assert out.exit_code == 2 exp = "--extra has effect only with setup.py and PEP-517 input formats" assert exp in out.stderr def test_cli_compile_strip_extras(runner, make_package, make_sdist, tmpdir): """ Assures that ``--strip-extras`` removes mention of extras from output. """ test_package_1 = make_package( "test_package_1", version="0.1", extras_require={"more": "test_package_2"} ) test_package_2 = make_package( "test_package_2", version="0.1", ) dists_dir = tmpdir / "dists" for pkg in (test_package_1, test_package_2): make_sdist(pkg, dists_dir) with open("requirements.in", "w") as reqs_out: reqs_out.write("test_package_1[more]") out = runner.invoke(cli, ["--strip-extras", "--find-links", str(dists_dir)]) assert out.exit_code == 0, out assert "test-package-2==0.1" in out.stderr assert "[more]" not in out.stderr def test_cli_compile_all_extras_with_multiple_packages( runner, make_package, make_sdist, tmpdir ): """ Assures that ``--all-extras`` works when multiple sources are specified. """ test_package_1 = make_package( "test_package_1", version="0.1", extras_require={"more": []}, ) test_package_2 = make_package( "test_package_2", version="0.1", extras_require={"more": []}, ) out = runner.invoke( cli, [ "--all-extras", "--output-file", "requirements.txt", str(test_package_1 / "setup.py"), str(test_package_2 / "setup.py"), ], ) assert out.exit_code == 0, out assert "--all-extras" in out.stderr assert f"test_package_1{os.path.sep}0.1{os.path.sep}setup.py" in out.stderr assert f"test_package_2{os.path.sep}0.1{os.path.sep}setup.py" in out.stderr @pytest.mark.parametrize( ("package_specs", "constraints", "existing_reqs", "expected_reqs"), ( ( [ { "name": "test_package_1", "version": "1.1", "install_requires": ["test_package_2 ~= 1.1"], }, { "name": "test_package_2", "version": "1.1", "extras_require": {"more": "test_package_3"}, }, ], """ test_package_1 == 1.1 """, """ test_package_1 == 1.0 test_package_2 == 1.0 """, """ test-package-1==1.1 test-package-2==1.1 """, ), ( [ { "name": "test_package_1", "version": "1.1", "install_requires": ["test_package_2[more] ~= 1.1"], }, { "name": "test_package_2", "version": "1.1", "extras_require": {"more": "test_package_3"}, }, { "name": "test_package_3", "version": "0.1", }, ], """ test_package_1 == 1.1 """, """ test_package_1 == 1.0 test_package_2 == 1.0 test_package_3 == 0.1 """, """ test-package-1==1.1 test-package-2==1.1 test-package-3==0.1 """, ), ( [ { "name": "test_package_1", "version": "1.1", "install_requires": ["test_package_2[more] ~= 1.1"], }, { "name": "test_package_2", "version": "1.1", "extras_require": {"more": "test_package_3"}, }, { "name": "test_package_3", "version": "0.1", }, ], """ test_package_1 == 1.1 """, """ test_package_1 == 1.0 test_package_2[more] == 1.0 test_package_3 == 0.1 """, """ test-package-1==1.1 test-package-2==1.1 test-package-3==0.1 """, ), ), ids=("no-extra", "extra-stripped-from-existing", "with-extra-in-existing"), ) def test_resolver_drops_existing_conflicting_constraint( runner, make_package, make_sdist, tmpdir, package_specs, constraints, existing_reqs, expected_reqs, ) -> None: """ Test that the resolver will find a solution even if some of the existing (indirect) requirements are incompatible with the new constraints. This must succeed even if the conflicting requirement includes some extra, no matter whether the extra is mentioned in the existing requirements or not (cf. `issue #1977 <https://github.com/jazzband/pip-tools/issues/1977>`_). """ expected_requirements = {line.strip() for line in expected_reqs.splitlines()} dists_dir = tmpdir / "dists" packages = [make_package(**spec) for spec in package_specs] for pkg in packages: make_sdist(pkg, dists_dir) with open("requirements.txt", "w") as existing_reqs_out: existing_reqs_out.write(dedent(existing_reqs)) with open("requirements.in", "w") as constraints_out: constraints_out.write(dedent(constraints)) out = runner.invoke(cli, ["--strip-extras", "--find-links", str(dists_dir)]) assert out.exit_code == 0, out with open("requirements.txt") as req_txt: req_txt_content = req_txt.read() assert expected_requirements.issubset(req_txt_content.splitlines()) def test_resolution_failure(runner): """Test resolution impossible for unknown package.""" with open("requirements.in", "w") as reqs_out: reqs_out.write("unknown-package") out = runner.invoke(cli) assert out.exit_code != 0, out def test_resolver_reaches_max_rounds(runner): """Test resolver reched max rounds and raises error.""" with open("requirements.in", "w") as reqs_out: reqs_out.write("six") out = runner.invoke(cli, ["--max-rounds", 0]) assert out.exit_code != 0, out def test_preserve_via_requirements_constrained_dependencies_when_run_twice( pip_conf, runner ): """ Test that 2 consecutive runs of pip-compile (first with a non-existing requirements.txt file, second with an existing file) produce the same output. """ with open("constraints.txt", "w") as constraints_in: constraints_in.write("small-fake-a==0.1") with open("requirements.in", "w") as req_in: req_in.write("-c constraints.txt\nsmall_fake_with_deps") cli_arguments = ["--no-emit-options", "--no-header"] # First run of the command will generate `requirements.txt`, which doesn't yet exist. first_out = runner.invoke(cli, cli_arguments) assert first_out.exit_code == 0, first_out with open("requirements.txt") as req_txt: first_output = req_txt.read() # Second run of the command will update `requirements.txt`. second_out = runner.invoke(cli, cli_arguments) assert second_out.exit_code == 0, second_out with open("requirements.txt") as req_txt: second_output = req_txt.read() expected_output = dedent( """\ small-fake-a==0.1 # via # -c constraints.txt # small-fake-with-deps small-fake-with-deps==0.1 # via -r requirements.in """ ) assert first_output == expected_output assert second_output == expected_output def test_failure_of_legacy_resolver_prompts_for_backtracking( pip_conf, runner, tmpdir, make_package, make_wheel, current_resolver ): """Test that pip-compile prompts to use the backtracking resolver""" pkgs = [ make_package("a", version="0.1", install_requires=["b==0.1"]), make_package("a", version="0.2", install_requires=["b==0.2"]), make_package("b", version="0.1"), make_package("b", version="0.2"), make_package("c", version="1", install_requires=["b==0.1", "a"]), ] dists_dir = tmpdir / "dists" for pkg in pkgs: make_wheel(pkg, dists_dir) with open("requirements.in", "w") as req_in: req_in.writelines(["c"]) out = runner.invoke( cli, ["--resolver", current_resolver, "--find-links", str(dists_dir)], ) if current_resolver == "legacy": assert out.exit_code == 2, out assert "Consider using backtracking resolver with" in out.stderr elif current_resolver == "backtracking": assert out.exit_code == 0, out else: raise AssertionError("unreachable") def test_print_deprecation_warning_if_using_legacy_resolver(runner, current_resolver): with open("requirements.in", "w"): pass out = runner.invoke(cli) assert out.exit_code == 0, out expected_warning = "WARNING: the legacy dependency resolver is deprecated" if current_resolver == "legacy": assert expected_warning in out.stderr else: assert expected_warning not in out.stderr @pytest.mark.parametrize( "input_filenames", ( pytest.param(("requirements.txt",), id="one file"), pytest.param(("requirements.txt", "dev-requirements.in"), id="multiple files"), ), ) def test_raise_error_when_input_and_output_filenames_are_matched( runner, tmp_path, input_filenames ): req_in_paths = [] for input_filename in input_filenames: req_in = tmp_path / input_filename req_in.touch() req_in_paths.append(req_in.as_posix()) req_out = tmp_path / "requirements.txt" req_out_path = req_out.as_posix() out = runner.invoke(cli, req_in_paths + ["--output-file", req_out_path]) assert out.exit_code == 2 expected_error = ( f"Error: input and output filenames must not be matched: {req_out_path}" ) assert expected_error in out.stderr.splitlines() @pytest.mark.network @backtracking_resolver_only def test_pass_pip_cache_to_pip_args(tmpdir, runner, current_resolver): cache_dir = tmpdir.mkdir("cache_dir") with open("requirements.in", "w") as fp: fp.write("six==1.15.0") out = runner.invoke( cli, ["--cache-dir", str(cache_dir), "--resolver", current_resolver] ) assert out.exit_code == 0 # TODO: Remove hack once testing only on v23.3+ pip_current_version = get_pip_version_for_python_executable(sys.executable) pip_breaking_version = Version("23.3.dev0") if pip_current_version >= pip_breaking_version: pip_http_cache_dir = "http-v2" else: pip_http_cache_dir = "http" assert os.listdir(os.path.join(str(cache_dir), pip_http_cache_dir)) @backtracking_resolver_only def test_compile_recursive_extras_static( runner, tmp_path, minimal_wheels_path, current_resolver, ): (tmp_path / "pyproject.toml").write_text( dedent( """ [project] name = "foo" version = "0.0.1" dependencies = ["small-fake-a"] [project.optional-dependencies] footest = ["small-fake-b"] dev = ["foo[footest]"] """ ) ) out = runner.invoke( cli, [ "--no-build-isolation", "--no-header", "--no-annotate", "--no-emit-options", "--extra", "dev", "--find-links", minimal_wheels_path.as_posix(), os.fspath(tmp_path / "pyproject.toml"), "--output-file", "-", ], ) expected = rf"""foo[footest] @ {tmp_path.as_uri()} small-fake-a==0.2 small-fake-b==0.3 """ try: assert out.exit_code == 0 assert expected == out.stdout except Exception: # pragma: no cover print(out.stdout) print(out.stderr) raise @backtracking_resolver_only def test_compile_recursive_extras_build_targets( runner, tmp_path, minimal_wheels_path, current_resolver ): (tmp_path / "pyproject.toml").write_text( dedent( """ [project] name = "foo" version = "0.0.1" dependencies = ["small-fake-a"] [project.optional-dependencies] footest = ["small-fake-b"] dev = ["foo[footest]"] """ ) ) out = runner.invoke( cli, [ "--no-build-isolation", "--no-header", "--no-annotate", "--no-emit-options", "--extra", "dev", "--build-deps-for", "wheel", "--find-links", minimal_wheels_path.as_posix(), os.fspath(tmp_path / "pyproject.toml"), "--output-file", "-", ], ) expected = rf"""foo[footest] @ {tmp_path.as_uri()} small-fake-a==0.2 small-fake-b==0.3 # The following packages are considered to be unsafe in a requirements file: # setuptools """ try: assert out.exit_code == 0 assert expected == out.stdout except Exception: # pragma: no cover print(out.stdout) print(out.stderr) raise @backtracking_resolver_only def test_compile_build_targets_setuptools_no_wheel_dep( runner, tmp_path, minimal_wheels_path, current_resolver, ): """Check that user requests apply to build dependencies. This verifies that build deps compilation would not use the latest version of an unconstrained build requirements list, when the user requested restricting them. It is implemented against `setuptools < 70.1.0` which is known to inject a dependency on `wheel` (newer `setuptools` vendor it). The idea is that `pyproject.toml` does not have an upper bound for `setuptools` but the CLI arg does. And when this works correctly, the `wheel` entry will be included into the resolved output. This is a regression test for https://github.com/jazzband/pip-tools/pull/1681#issuecomment-2212541289. """ (tmp_path / "pyproject.toml").write_text( dedent( """ [project] name = "foo" version = "0.0.1" dependencies = ["small-fake-a"] """ ) ) (tmp_path / "constraints.txt").write_text("wheel<0.43") out = runner.invoke( cli, [ "--build-isolation", "--no-header", "--no-annotate", "--no-emit-options", "--extra", "dev", "--build-deps-for", "wheel", "--find-links", minimal_wheels_path.as_posix(), os.fspath(tmp_path / "pyproject.toml"), "--constraint", os.fspath(tmp_path / "constraints.txt"), "--upgrade-package", "setuptools < 70.1.0", # setuptools>=70.1.0 doesn't require wheel any more "--output-file", "-", ], catch_exceptions=True, ) expected = r"""small-fake-a==0.2 wheel==0.42.0 # The following packages are considered to be unsafe in a requirements file: # setuptools """ try: assert out.exit_code == 0 assert expected == out.stdout except Exception: # pragma: no cover print(out.stdout) print(out.stderr) raise def test_config_option(pip_conf, runner, tmp_path, make_config_file): config_file = make_config_file("dry-run", True) req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke(cli, [req_in.as_posix(), "--config", config_file.as_posix()]) assert out.exit_code == 0 assert "Dry-run, so nothing updated" in out.stderr def test_default_config_option(pip_conf, runner, make_config_file, tmpdir_cwd): make_config_file("dry-run", True) req_in = tmpdir_cwd / "requirements.in" req_in.touch() out = runner.invoke(cli) assert out.exit_code == 0 assert "Dry-run, so nothing updated" in out.stderr def test_no_config_option_overrides_config_with_defaults( pip_conf, runner, tmp_path, make_config_file ): config_file = make_config_file("dry-run", True) req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke( cli, [req_in.as_posix(), "--no-config", "--config", config_file.as_posix()] ) assert out.exit_code == 0 assert "Dry-run, so nothing updated" not in out.stderr def test_raise_error_on_unknown_config_option( pip_conf, runner, tmp_path, make_config_file ): config_file = make_config_file("unknown-option", True) req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke(cli, [req_in.as_posix(), "--config", config_file.as_posix()]) assert out.exit_code == 2 assert "No such config key 'unknown_option'" in out.stderr def test_raise_error_on_invalid_config_option( pip_conf, runner, tmp_path, make_config_file ): config_file = make_config_file("dry-run", ["invalid", "value"]) req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke(cli, [req_in.as_posix(), "--config", config_file.as_posix()]) assert out.exit_code == 2 assert "Invalid value for config key 'dry_run': ['invalid', 'value']" in out.stderr @pytest.mark.parametrize("option", ("-c", "--constraint")) def test_constraint_option(pip_conf, runner, tmpdir_cwd, make_config_file, option): req_in = tmpdir_cwd / "requirements.in" req_in.write_text("small-fake-a") constraints_txt = tmpdir_cwd / "constraints.txt" constraints_txt.write_text("small-fake-a==0.1") out = runner.invoke( cli, [ req_in.name, option, constraints_txt.name, "--output-file", "-", "--no-header", "--no-emit-options", ], ) assert out.exit_code == 0 assert out.stdout == dedent( """\ small-fake-a==0.1 # via # -c constraints.txt # -r requirements.in """ ) def test_allow_in_config_pip_sync_option(pip_conf, runner, tmp_path, make_config_file): config_file = make_config_file("--ask", True) # pip-sync's option req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke( cli, [req_in.as_posix(), "--verbose", "--config", config_file.as_posix()] ) assert out.exit_code == 0 assert "Using pip-tools configuration defaults found" in out.stderr def test_use_src_files_from_config_if_option_is_not_specified_from_cli( pip_conf, runner, tmp_path, make_config_file ): foo_in = tmp_path / "foo.in" req_in = tmp_path / "requirements.in" config_file = make_config_file("src-files", [foo_in.as_posix()]) req_in.write_text("small-fake-a==0.1", encoding="utf-8") foo_in.write_text("small-fake-b==0.1", encoding="utf-8") out = runner.invoke(cli, ["--config", config_file.as_posix()]) assert out.exit_code == 0, out assert "small-fake-b" in out.stderr assert "small-fake-a" not in out.stderr def test_use_src_files_from_cli_if_option_is_specified_in_both_config_and_cli( pip_conf, runner, tmp_path, make_config_file ): foo_in = tmp_path / "foo.in" req_in = tmp_path / "requirements.in" config_file = make_config_file("src-files", [foo_in.as_posix()]) req_in.write_text("small-fake-a==0.1", encoding="utf-8") foo_in.write_text("small-fake-b==0.1", encoding="utf-8") out = runner.invoke(cli, [req_in.as_posix(), "--config", config_file.as_posix()]) assert out.exit_code == 0, out assert "small-fake-a" in out.stderr assert "small-fake-b" not in out.stderr def test_cli_boolean_flag_config_option_has_valid_context( pip_conf, runner, tmp_path, make_config_file ): config_file = make_config_file("no-annotate", True) req_in = tmp_path / "requirements.in" req_in.write_text("small-fake-a==0.1") out = runner.invoke( cli, [ req_in.as_posix(), "--config", config_file.as_posix(), "--no-emit-options", "--no-header", "--output-file", "-", ], ) assert out.exit_code == 0 assert out.stdout == "small-fake-a==0.1\n" def test_invalid_cli_boolean_flag_config_option_captured( pip_conf, runner, tmp_path, make_config_file ): config_file = make_config_file("no-annnotate", True) req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke(cli, [req_in.as_posix(), "--config", config_file.as_posix()]) assert out.exit_code == 2 assert "No such config key 'annnotate'." in out.stderr strip_extras_warning = ( "WARNING: --strip-extras is becoming the default in version 8.0.0." ) def test_show_warning_on_default_strip_extras_option( runner, make_package, make_sdist, tmp_path ): req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke(cli, req_in.as_posix()) assert out.exit_code == 0 assert strip_extras_warning in out.stderr @pytest.mark.parametrize("option", ("--strip-extras", "--no-strip-extras")) def test_do_not_show_warning_on_explicit_strip_extras_option( runner, make_package, make_sdist, tmp_path, option ): req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke(cli, [option, req_in.as_posix()]) assert out.exit_code == 0 assert strip_extras_warning not in out.stderr def test_origin_of_extra_requirement_not_written_to_annotations( pip_conf, runner, make_package, make_wheel, tmp_path, tmpdir ): req_in = tmp_path / "requirements.in" package_with_extras = make_package( "package_with_extras", version="0.1", extras_require={ "extra1": ["small-fake-a==0.1"], "extra2": ["small-fake-b==0.1"], }, ) dists_dir = tmpdir / "dists" make_wheel(package_with_extras, dists_dir) with open(req_in, "w") as req_out: req_out.write("package-with-extras[extra1,extra2]") out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--find-links", str(dists_dir), "--no-emit-options", "--no-build-isolation", req_in.as_posix(), ], ) assert out.exit_code == 0, out assert ( dedent( f"""\ package-with-extras[extra1,extra2]==0.1 # via -r {req_in.as_posix()} small-fake-a==0.1 # via package-with-extras small-fake-b==0.1 # via package-with-extras """ ) == out.stdout ) def test_tool_specific_config_option(pip_conf, runner, tmp_path, make_config_file): config_file = make_config_file( "dry-run", True, section="pip-tools", subsection="compile" ) req_in = tmp_path / "requirements.in" req_in.touch() out = runner.invoke(cli, [req_in.as_posix(), "--config", config_file.as_posix()]) assert out.exit_code == 0 assert "Dry-run, so nothing updated" in out.stderr @pytest.mark.xfail(reason="https://github.com/jazzband/pip-tools/issues/2012") @mock.patch("piptools.scripts.compile.parse_requirements") def test_stdout_should_not_be_read_when_stdin_is_not_a_plain_file( parse_req, runner, tmp_path, ): parse_req.side_effect = lambda fname, finder, options, session: pytest.fail( "Must not be called when output is a fifo" ) req_in = tmp_path / "requirements.txt" req_in.touch() fifo = tmp_path / "fifo" os.mkfifo(fifo) out = runner.invoke(cli, [req_in.as_posix(), "--output-file", fifo.as_posix()]) assert out.exit_code == 0, out @pytest.mark.parametrize( "input_path_absolute", (True, False), ids=("absolute-input", "relative-input") ) @pytest.mark.parametrize( "test_files_collection", ( TestFilesCollection( "relative_include", { "requirements2.in": "small-fake-a\n", "requirements.in": "-r requirements2.in\n", }, ), TestFilesCollection( "absolute_include", { "requirements2.in": "small-fake-a\n", "requirements.in": lambda tmpdir: f"-r {(tmpdir / 'requirements2.in').as_posix()}", }, ), ), ids=str, ) def test_second_order_requirements_path_handling( pip_conf, runner, tmp_path, monkeypatch, pip_produces_absolute_paths, input_path_absolute, test_files_collection, ): """ Test normalization of ``-r`` includes in output. Given nested requirements files, the internal requirements file path will be written in the output, and it will be absolute or relative depending only on whether or not the initial path was absolute or relative. """ test_files_collection.populate(tmp_path) # the input path is given on the CLI as absolute or relative # and this determines the expected output path as well input_dir_path = tmp_path if input_path_absolute else pathlib.Path(".") input_path = (input_dir_path / "requirements.in").as_posix() output_path = (input_dir_path / "requirements2.in").as_posix() with monkeypatch.context() as revertable_ctx: revertable_ctx.chdir(tmp_path) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "-r", input_path, ], ) assert out.exit_code == 0 assert out.stdout == dedent( f"""\ small-fake-a==0.2 # via -r {output_path} """ ) @pytest.mark.parametrize( "test_files_collection", ( TestFilesCollection( "parent_dir", { "requirements2.in": "small-fake-a\n", "subdir/requirements.in": "-r ../requirements2.in\n", }, ), TestFilesCollection( "subdir", { "requirements.in": "-r ./subdir/requirements2.in", "subdir/requirements2.in": "small-fake-a\n", }, ), TestFilesCollection( "sibling_dir", { "subdir1/requirements.in": "-r ../subdir2/requirements2.in", "subdir2/requirements2.in": "small-fake-a\n", }, ), ), ids=str, ) def test_second_order_requirements_relative_path_in_separate_dir( pip_conf, runner, tmp_path, monkeypatch, test_files_collection, pip_produces_absolute_paths, ): """ Test normalization of ``-r`` includes when the requirements files are in distinct directories. Confirm that the output path will be relative to the current working directory. """ test_files_collection.populate(tmp_path) # the input is the path to 'requirements.in' relative to the starting dir input_path = test_files_collection.get_path_to("requirements.in") # the output should also be relative to the starting dir, the path to 'requirements2.in' output_path = test_files_collection.get_path_to("requirements2.in") # for older pip versions, recompute the output path to be relative to the input path if not pip_produces_absolute_paths: # traverse upwards to the root tmp dir, and append the output path to that # similar to pathlib.Path.relative_to(..., walk_up=True) relative_segments = len(pathlib.Path(input_path).parents) - 1 output_path = ( pathlib.Path(input_path).parent / ("../" * relative_segments) / output_path ).as_posix() with monkeypatch.context() as revertable_ctx: revertable_ctx.chdir(tmp_path) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "-r", input_path, ], ) assert out.exit_code == 0 assert out.stdout == dedent( f"""\ small-fake-a==0.2 # via -r {output_path} """ ) def test_second_order_requirements_can_be_in_parent_of_cwd( pip_conf, runner, tmp_path, monkeypatch, pip_produces_absolute_paths, ): """ Test handling of ``-r`` includes when the included requirements file is in the parent of the current working directory. """ test_files_collection = TestFilesCollection( contents={ "subdir1/requirements.in": "-r ../requirements2.in\n", "requirements2.in": "small-fake-a\n", } ) test_files_collection.populate(tmp_path) with monkeypatch.context() as revertable_ctx: # cd into the subdir where the initial requirements are revertable_ctx.chdir(tmp_path / "subdir1") out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "-r", "requirements.in", ], ) assert out.exit_code == 0 assert out.stdout == dedent( """\ small-fake-a==0.2 # via -r ../requirements2.in """ ) @pytest.mark.parametrize( "input_path_absolute", (True, False), ids=("absolute-input", "relative-input") ) def test_url_constraints_are_not_treated_as_file_paths( pip_conf, make_package, runner, tmp_path, monkeypatch, input_path_absolute, ): """ Test normalization of ``-c`` constraints when the constraints are HTTPS URLs. The constraints should be preserved verbatim. This is a regression test for https://github.com/jazzband/pip-tools/issues/2223 """ constraints_url = "https://example.com/files/common_constraints.txt" reqs_in = tmp_path / "requirements.in" reqs_in.write_text( f""" small-fake-a -c {constraints_url} """ ) input_dir_path = tmp_path if input_path_absolute else pathlib.Path(".") input_path = (input_dir_path / "requirements.in").as_posix() # TODO: find a better way of mocking the callout to get the constraints # file (use `responses`?) # # we need a mock response for `GET https://...` as fetched by pip # although this is fragile, it can be adapted if pip changes def fake_url_get(url): response = mock.Mock() response.reason = "Ok" response.status_code = 200 response.url = url response.text = "small-fake-a==0.2" return response mock_get = mock.Mock(side_effect=fake_url_get) with monkeypatch.context() as revertable_ctx: revertable_ctx.chdir(tmp_path) revertable_ctx.setattr(PipSession, "get", mock_get) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", "-r", input_path, ], ) # sanity check, pip should have tried to fetch the constraints mock_get.assert_called_once_with(constraints_url) assert out.exit_code == 0 assert out.stdout == dedent( f"""\ small-fake-a==0.2 # via # -c {constraints_url} # -r {input_path} """ ) @pytest.mark.parametrize( "pyproject_path_is_absolute", (True, False), ids=("absolute-input", "relative-input"), ) def test_that_self_referential_pyproject_toml_extra_can_be_compiled( pip_conf, runner, tmp_path, monkeypatch, pyproject_path_is_absolute ): """ Test that a :file:`pyproject.toml` source file can use self-referential extras which point back to the original package name. This is a regression test for: https://github.com/jazzband/pip-tools/issues/2215 """ src_file = tmp_path / "pyproject.toml" src_file.write_text( dedent( """ [project] name = "foo" version = "0.1.0" [project.optional-dependencies] ext1 = ["small-fake-a"] ext2 = ["foo[ext1]"] """ ) ) if pyproject_path_is_absolute: input_path = src_file.as_posix() else: input_path = src_file.relative_to(tmp_path).as_posix() with monkeypatch.context() as revertable_ctx: revertable_ctx.chdir(tmp_path) out = runner.invoke( cli, [ "--output-file", "-", "--quiet", "--no-header", "--no-emit-options", # use in-process setuptools "--no-build-isolation", # importantly, request the extra which uses the self-reference "--extra", "ext2", input_path, ], ) assert out.exit_code == 0 assert out.stdout == dedent( f"""\ foo[ext1] @ {src_file.parent.absolute().as_uri()} # via foo ({input_path}) small-fake-a==0.2 # via foo """ )
TestFilesCollection
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_v2_test.py
{ "start": 4219, "end": 8654 }
class ____(test.TestCase): def test_transformations_called_once(self): class TransformCounter(BaseFeatureColumnForTests): def __init__(self): super(TransformCounter, self).__init__() self.num_transform = 0 @property def _is_v2_column(self): return True @property def name(self): return 'TransformCounter' def transform_feature(self, transformation_cache, state_manager): self.num_transform += 1 # Count transform calls. return transformation_cache.get('a', state_manager) @property def parse_example_spec(self): pass transformation_cache = fc.FeatureTransformationCache( features={'a': [[2], [3.]]}) column = TransformCounter() self.assertEqual(0, column.num_transform) transformation_cache.get(column, None) self.assertEqual(1, column.num_transform) transformation_cache.get(column, None) self.assertEqual(1, column.num_transform) def test_returns_transform_output(self): class Transformer(BaseFeatureColumnForTests): @property def _is_v2_column(self): return True @property def name(self): return 'Transformer' def transform_feature(self, transformation_cache, state_manager): return 'Output' @property def parse_example_spec(self): pass transformation_cache = fc.FeatureTransformationCache( features={'a': [[2], [3.]]}) column = Transformer() self.assertEqual('Output', transformation_cache.get(column, None)) self.assertEqual('Output', transformation_cache.get(column, None)) def test_does_not_pollute_given_features_dict(self): class Transformer(BaseFeatureColumnForTests): @property def _is_v2_column(self): return True @property def name(self): return 'Transformer' def transform_feature(self, transformation_cache, state_manager): return 'Output' @property def parse_example_spec(self): pass features = {'a': [[2], [3.]]} transformation_cache = fc.FeatureTransformationCache(features=features) transformation_cache.get(Transformer(), None) self.assertEqual(['a'], list(features.keys())) def test_error_if_feature_is_not_found(self): transformation_cache = fc.FeatureTransformationCache( features={'a': [[2], [3.]]}) with self.assertRaisesRegex(ValueError, 'bbb is not in features dictionary'): transformation_cache.get('bbb', None) with self.assertRaisesRegex(ValueError, 'bbb is not in features dictionary'): transformation_cache.get(u'bbb', None) def test_not_supported_feature_column(self): class NotAProperColumn(BaseFeatureColumnForTests): @property def _is_v2_column(self): return True @property def name(self): return 'NotAProperColumn' def transform_feature(self, transformation_cache, state_manager): # It should return not None. pass @property def parse_example_spec(self): pass transformation_cache = fc.FeatureTransformationCache( features={'a': [[2], [3.]]}) with self.assertRaisesRegex(ValueError, 'NotAProperColumn is not supported'): transformation_cache.get(NotAProperColumn(), None) def test_key_should_be_string_or_feature_colum(self): class NotAFeatureColumn(object): pass transformation_cache = fc.FeatureTransformationCache( features={'a': [[2], [3.]]}) with self.assertRaisesRegex( TypeError, '"key" must be either a "str" or "FeatureColumn".'): transformation_cache.get(NotAFeatureColumn(), None) def test_expand_dim_rank_1_sparse_tensor_empty_batch(self): # empty 1-D sparse tensor: transformation_cache = fc.FeatureTransformationCache( features={ 'a': sparse_tensor.SparseTensor( indices=np.reshape(np.array([], dtype=np.int64), (0, 1)), dense_shape=[0], values=np.array([])) }) spv = self.evaluate(transformation_cache.get('a', None)) self.assertAllEqual(np.array([0, 1], dtype=np.int64), spv.dense_shape) self.assertAllEqual( np.reshape(np.array([], dtype=np.int64), (0, 2)), spv.indices)
LazyColumnTest
python
google__jax
tests/multiprocess/colocated_python_test.py
{ "start": 922, "end": 2703 }
class ____(jt_multiprocess.MultiProcessTest): def setUp(self): super().setUp() if not HAS_CLOUDPICKLE: self.skipTest( "ColocatedPythonTestMultiHost depends on cloudpickle library" ) jtu.request_cpu_devices(jax.local_device_count()) def test_colocated_cpu_devices(self): if jax.device_count() % 2 == 0: mesh_shape = (2, jax.device_count() // 2) else: mesh_shape = (1, jax.device_count()) mesh = jax.make_mesh(mesh_shape, ("x", "y"), axis_types=(jax.sharding.AxisType.Explicit,) * 2) cpu_mesh1 = colocated_python.colocated_cpu_devices(mesh) cpu_devices = colocated_python.colocated_cpu_devices(mesh.devices.flat) cpu_mesh2 = jax.make_mesh(mesh_shape, ("x", "y"), axis_types=(jax.sharding.AxisType.Explicit,) * 2, devices=cpu_devices) self.assertEqual(cpu_mesh1, cpu_mesh2) def test_simple_function(self): @colocated_python.colocated_python def add_one(x): return jax.make_array_from_single_device_arrays( x.shape, x.sharding, [s.data + 1 for s in x.addressable_shards]) mesh = jax.make_mesh((jax.device_count(),), ("x",), axis_types=(jax.sharding.AxisType.Explicit,)) cpu_mesh = colocated_python.colocated_cpu_devices(mesh) cpu_sharding = jax.NamedSharding(cpu_mesh, jax.P("x")) x = np.arange(cpu_mesh.size) x = jax.device_put(x, cpu_sharding) out = add_one(x) out = jax.jit(lambda x: x, out_shardings=jax.NamedSharding(cpu_mesh, jax.P()))(out) out = jax.device_get(out) np.testing.assert_equal(out, np.arange(cpu_mesh.size) + 1) if __name__ == "__main__": jt_multiprocess.main()
ColocatedPythonTestMultiHost
python
pydata__xarray
xarray/tests/test_variable.py
{ "start": 38942, "end": 89884 }
class ____(VariableSubclassobjects): def cls(self, *args, **kwargs) -> Variable: return Variable(*args, **kwargs) @pytest.fixture(autouse=True) def setup(self): self.d = np.random.random((10, 3)).astype(np.float64) def test_values(self): v = Variable(["time", "x"], self.d) assert_array_equal(v.values, self.d) assert source_ndarray(v.values) is self.d with pytest.raises(ValueError): # wrong size v.values = np.random.random(5) d2 = np.random.random((10, 3)) v.values = d2 assert source_ndarray(v.values) is d2 def test_numpy_same_methods(self): v = Variable([], np.float32(0.0)) assert v.item() == 0 # type: ignore[attr-defined] assert type(v.item()) is float # type: ignore[attr-defined] v = IndexVariable("x", np.arange(5)) assert 2 == v.searchsorted(2) # type: ignore[attr-defined] @pytest.mark.parametrize( "values, unit", [ (np.datetime64("2000-01-01"), "s"), ( pd.Timestamp("2000-01-01T00").as_unit("s"), "s" if has_pandas_3 else "ns", ), ( datetime(2000, 1, 1), "us" if has_pandas_3 else "ns", ), (np.datetime64("2000-01-01T00:00:00.1234567891"), "ns"), ], ) def test_datetime64_conversion_scalar(self, values, unit): v = Variable([], values) assert v.dtype == np.dtype(f"datetime64[{unit}]") assert np.issubdtype(v.values, "datetime64") assert v.values.dtype == np.dtype(f"datetime64[{unit}]") @pytest.mark.parametrize( "values, unit", [ (np.timedelta64(1, "m"), "s"), (np.timedelta64(1, "D"), "s"), (np.timedelta64(1001, "ps"), "ns"), (pd.Timedelta("1 day"), "ns"), (timedelta(days=1), "ns"), ], ) def test_timedelta64_conversion_scalar(self, values, unit): v = Variable([], values) assert v.dtype == np.dtype(f"timedelta64[{unit}]") assert np.issubdtype(v.values, "timedelta64") assert v.values.dtype == np.dtype(f"timedelta64[{unit}]") def test_0d_str(self): v = Variable([], "foo") assert v.dtype == np.dtype("U3") assert v.values == "foo" v = Variable([], np.bytes_("foo")) assert v.dtype == np.dtype("S3") assert v.values == "foo".encode("ascii") def test_0d_datetime(self): v = Variable([], pd.Timestamp("2000-01-01").as_unit("s")) expected_unit = "s" if has_pandas_3 else "ns" assert v.dtype == np.dtype(f"datetime64[{expected_unit}]") assert v.values == np.datetime64("2000-01-01", expected_unit) # type: ignore[call-overload] @pytest.mark.parametrize( "values, unit", [(pd.to_timedelta("1s"), "ns"), (np.timedelta64(1, "s"), "s")] ) def test_0d_timedelta(self, values, unit): # todo: check, if this test is OK v = Variable([], values) assert v.dtype == np.dtype(f"timedelta64[{unit}]") assert v.values == np.timedelta64(10**9, "ns") def test_equals_and_identical(self): d = np.random.rand(10, 3) d[0, 0] = np.nan v1 = Variable(("dim1", "dim2"), data=d, attrs={"att1": 3, "att2": [1, 2, 3]}) v2 = Variable(("dim1", "dim2"), data=d, attrs={"att1": 3, "att2": [1, 2, 3]}) assert v1.equals(v2) assert v1.identical(v2) v3 = Variable(("dim1", "dim3"), data=d) assert not v1.equals(v3) v4 = Variable(("dim1", "dim2"), data=d) assert v1.equals(v4) assert not v1.identical(v4) v5 = deepcopy(v1) v5.values[:] = np.random.rand(10, 3) assert not v1.equals(v5) assert not v1.equals(None) assert not v1.equals(d) assert not v1.identical(None) assert not v1.identical(d) def test_broadcast_equals(self): v1 = Variable((), np.nan) v2 = Variable(("x"), [np.nan, np.nan]) assert v1.broadcast_equals(v2) assert not v1.equals(v2) assert not v1.identical(v2) v3 = Variable(("x"), [np.nan]) assert v1.broadcast_equals(v3) assert not v1.equals(v3) assert not v1.identical(v3) assert not v1.broadcast_equals(None) v4 = Variable(("x"), [np.nan] * 3) assert not v2.broadcast_equals(v4) def test_no_conflicts(self): v1 = Variable(("x"), [1, 2, np.nan, np.nan]) v2 = Variable(("x"), [np.nan, 2, 3, np.nan]) assert v1.no_conflicts(v2) assert not v1.equals(v2) assert not v1.broadcast_equals(v2) assert not v1.identical(v2) assert not v1.no_conflicts(None) v3 = Variable(("y"), [np.nan, 2, 3, np.nan]) assert not v3.no_conflicts(v1) d = np.array([1, 2, np.nan, np.nan]) assert not v1.no_conflicts(d) assert not v2.no_conflicts(d) v4 = Variable(("w", "x"), [d]) assert v1.no_conflicts(v4) def test_as_variable(self): data = np.arange(10) expected = Variable("x", data) expected_extra = Variable( "x", data, attrs={"myattr": "val"}, encoding={"scale_factor": 1} ) assert_identical(expected, as_variable(expected)) ds = Dataset({"x": expected}) var = as_variable(ds["x"]).to_base_variable() assert_identical(expected, var) assert not isinstance(ds["x"], Variable) assert isinstance(as_variable(ds["x"]), Variable) xarray_tuple = ( expected_extra.dims, expected_extra.values, expected_extra.attrs, expected_extra.encoding, ) assert_identical(expected_extra, as_variable(xarray_tuple)) with pytest.raises(TypeError, match=r"tuple of form"): as_variable(tuple(data)) with pytest.raises(ValueError, match=r"tuple of form"): # GH1016 as_variable(("five", "six", "seven")) with pytest.raises(TypeError, match=r"without an explicit list of dimensions"): as_variable(data) with pytest.warns(FutureWarning, match="IndexVariable"): actual = as_variable(data, name="x") assert_identical(expected.to_index_variable(), actual) actual = as_variable(0) expected = Variable([], 0) assert_identical(expected, actual) data2: np.ndarray[tuple[int, int], np.dtype[np.signedinteger[Any]]] = np.arange( 9 ).reshape((3, 3)) expected = Variable(("x", "y"), data2) with pytest.raises(ValueError, match=r"without explicit dimension names"): as_variable(data2, name="x") # name of nD variable matches dimension name actual = as_variable(expected, name="x") assert_identical(expected, actual) # test datetime, timedelta conversion dt = np.array([datetime(1999, 1, 1) + timedelta(days=x) for x in range(10)]) with pytest.warns(FutureWarning, match="IndexVariable"): assert as_variable(dt, "time").dtype.kind == "M" td = np.array([timedelta(days=x) for x in range(10)]) with pytest.warns(FutureWarning, match="IndexVariable"): assert as_variable(td, "time").dtype.kind == "m" with pytest.raises(TypeError): as_variable(("x", DataArray([]))) def test_repr(self): v = Variable(["time", "x"], [[1, 2, 3], [4, 5, 6]], {"foo": "bar"}) v = v.astype(np.uint64) expected = dedent( """ <xarray.Variable (time: 2, x: 3)> Size: 48B array([[1, 2, 3], [4, 5, 6]], dtype=uint64) Attributes: foo: bar """ ).strip() assert expected == repr(v) def test_repr_lazy_data(self): v = Variable("x", LazilyIndexedArray(np.arange(2e5))) assert "200000 values with dtype" in repr(v) assert isinstance(v._data, LazilyIndexedArray) def test_detect_indexer_type(self): """Tests indexer type was correctly detected.""" data = np.random.random((10, 11)) v = Variable(["x", "y"], data) _, ind, _ = v._broadcast_indexes((0, 1)) assert type(ind) is indexing.BasicIndexer _, ind, _ = v._broadcast_indexes((0, slice(0, 8, 2))) assert type(ind) is indexing.BasicIndexer _, ind, _ = v._broadcast_indexes((0, [0, 1])) assert type(ind) is indexing.OuterIndexer _, ind, _ = v._broadcast_indexes(([0, 1], 1)) assert type(ind) is indexing.OuterIndexer _, ind, _ = v._broadcast_indexes(([0, 1], [1, 2])) assert type(ind) is indexing.OuterIndexer _, ind, _ = v._broadcast_indexes(([0, 1], slice(0, 8, 2))) assert type(ind) is indexing.OuterIndexer vind = Variable(("a",), [0, 1]) _, ind, _ = v._broadcast_indexes((vind, slice(0, 8, 2))) assert type(ind) is indexing.OuterIndexer vind = Variable(("y",), [0, 1]) _, ind, _ = v._broadcast_indexes((vind, 3)) assert type(ind) is indexing.OuterIndexer vind = Variable(("a",), [0, 1]) _, ind, _ = v._broadcast_indexes((vind, vind)) assert type(ind) is indexing.VectorizedIndexer vind = Variable(("a", "b"), [[0, 2], [1, 3]]) _, ind, _ = v._broadcast_indexes((vind, 3)) assert type(ind) is indexing.VectorizedIndexer def test_indexer_type(self): # GH:issue:1688. Wrong indexer type induces NotImplementedError data = np.random.random((10, 11)) v = Variable(["x", "y"], data) def assert_indexer_type(key, object_type): _dims, index_tuple, _new_order = v._broadcast_indexes(key) assert isinstance(index_tuple, object_type) # should return BasicIndexer assert_indexer_type((0, 1), BasicIndexer) assert_indexer_type((0, slice(None, None)), BasicIndexer) assert_indexer_type((Variable([], 3), slice(None, None)), BasicIndexer) assert_indexer_type((Variable([], 3), (Variable([], 6))), BasicIndexer) # should return OuterIndexer assert_indexer_type(([0, 1], 1), OuterIndexer) assert_indexer_type(([0, 1], [1, 2]), OuterIndexer) assert_indexer_type((Variable(("x"), [0, 1]), 1), OuterIndexer) assert_indexer_type((Variable(("x"), [0, 1]), slice(None, None)), OuterIndexer) assert_indexer_type( (Variable(("x"), [0, 1]), Variable(("y"), [0, 1])), OuterIndexer ) # should return VectorizedIndexer assert_indexer_type((Variable(("y"), [0, 1]), [0, 1]), VectorizedIndexer) assert_indexer_type( (Variable(("z"), [0, 1]), Variable(("z"), [0, 1])), VectorizedIndexer ) assert_indexer_type( ( Variable(("a", "b"), [[0, 1], [1, 2]]), Variable(("a", "b"), [[0, 1], [1, 2]]), ), VectorizedIndexer, ) def test_items(self): data = np.random.random((10, 11)) v = Variable(["x", "y"], data) # test slicing assert_identical(v, v[:]) assert_identical(v, v[...]) assert_identical(Variable(["y"], data[0]), v[0]) assert_identical(Variable(["x"], data[:, 0]), v[:, 0]) assert_identical(Variable(["x", "y"], data[:3, :2]), v[:3, :2]) # test array indexing x = Variable(["x"], np.arange(10)) y = Variable(["y"], np.arange(11)) assert_identical(v, v[x.values]) assert_identical(v, v[x]) assert_identical(v[:3], v[x < 3]) assert_identical(v[:, 3:], v[:, y >= 3]) assert_identical(v[:3, 3:], v[x < 3, y >= 3]) assert_identical(v[:3, :2], v[x[:3], y[:2]]) assert_identical(v[:3, :2], v[range(3), range(2)]) # test iteration for n, item in enumerate(v): assert_identical(Variable(["y"], data[n]), item) with pytest.raises(TypeError, match=r"iteration over a 0-d"): iter(Variable([], 0)) # test setting v.values[:] = 0 assert np.all(v.values == 0) # test orthogonal setting v[range(10), range(11)] = 1 assert_array_equal(v.values, np.ones((10, 11))) def test_getitem_basic(self): v = self.cls(["x", "y"], [[0, 1, 2], [3, 4, 5]]) # int argument v_new = v[0] assert v_new.dims == ("y",) assert_array_equal(v_new, v._data[0]) # slice argument v_new = v[:2] assert v_new.dims == ("x", "y") assert_array_equal(v_new, v._data[:2]) # list arguments v_new = v[[0]] assert v_new.dims == ("x", "y") assert_array_equal(v_new, v._data[[0]]) # type: ignore[call-overload] v_new = v[[]] assert v_new.dims == ("x", "y") assert_array_equal(v_new, v._data[[]]) # type: ignore[call-overload] # dict arguments v_new = v[dict(x=0)] assert v_new.dims == ("y",) assert_array_equal(v_new, v._data[0]) v_new = v[dict(x=0, y=slice(None))] assert v_new.dims == ("y",) assert_array_equal(v_new, v._data[0]) v_new = v[dict(x=0, y=1)] assert v_new.dims == () assert_array_equal(v_new, v._data[0, 1]) v_new = v[dict(y=1)] assert v_new.dims == ("x",) assert_array_equal(v_new, v._data[:, 1]) # tuple argument v_new = v[(slice(None), 1)] assert v_new.dims == ("x",) assert_array_equal(v_new, v._data[:, 1]) # test that we obtain a modifiable view when taking a 0d slice v_new = v[0, 0] v_new[...] += 99 assert_array_equal(v_new, v._data[0, 0]) def test_getitem_with_mask_2d_input(self): v = Variable(("x", "y"), [[0, 1, 2], [3, 4, 5]]) assert_identical( v._getitem_with_mask(([-1, 0], [1, -1])), Variable(("x", "y"), [[np.nan, np.nan], [1, np.nan]]), ) assert_identical(v._getitem_with_mask((slice(2), [0, 1, 2])), v) def test_isel(self): v = Variable(["time", "x"], self.d) assert_identical(v.isel(time=slice(None)), v) assert_identical(v.isel(time=0), v[0]) assert_identical(v.isel(time=slice(0, 3)), v[:3]) assert_identical(v.isel(x=0), v[:, 0]) assert_identical(v.isel(x=[0, 2]), v[:, [0, 2]]) assert_identical(v.isel(time=[]), v[[]]) with pytest.raises( ValueError, match=r"Dimensions {'not_a_dim'} do not exist. Expected one or more of " r"\('time', 'x'\)", ): v.isel(not_a_dim=0) with pytest.warns( UserWarning, match=r"Dimensions {'not_a_dim'} do not exist. Expected one or more of " r"\('time', 'x'\)", ): v.isel(not_a_dim=0, missing_dims="warn") assert_identical(v, v.isel(not_a_dim=0, missing_dims="ignore")) def test_index_0d_numpy_string(self): # regression test to verify our work around for indexing 0d strings v = Variable([], np.bytes_("asdf")) assert_identical(v[()], v) v = Variable([], np.str_("asdf")) assert_identical(v[()], v) def test_indexing_0d_unicode(self): # regression test for GH568 actual = Variable(("x"), ["tmax"])[0][()] expected = Variable((), "tmax") assert_identical(actual, expected) @pytest.mark.parametrize("fill_value", [dtypes.NA, 2, 2.0]) def test_shift(self, fill_value): v = Variable("x", [1, 2, 3, 4, 5]) assert_identical(v, v.shift(x=0)) assert v is not v.shift(x=0) expected = Variable("x", [np.nan, np.nan, 1, 2, 3]) assert_identical(expected, v.shift(x=2)) if fill_value == dtypes.NA: # if we supply the default, we expect the missing value for a # float array fill_value_exp = np.nan else: fill_value_exp = fill_value expected = Variable("x", [fill_value_exp, 1, 2, 3, 4]) assert_identical(expected, v.shift(x=1, fill_value=fill_value)) expected = Variable("x", [2, 3, 4, 5, fill_value_exp]) assert_identical(expected, v.shift(x=-1, fill_value=fill_value)) expected = Variable("x", [fill_value_exp] * 5) assert_identical(expected, v.shift(x=5, fill_value=fill_value)) assert_identical(expected, v.shift(x=6, fill_value=fill_value)) with pytest.raises(ValueError, match=r"dimension"): v.shift(z=0) v = Variable("x", [1, 2, 3, 4, 5], {"foo": "bar"}) assert_identical(v, v.shift(x=0)) expected = Variable("x", [fill_value_exp, 1, 2, 3, 4], {"foo": "bar"}) assert_identical(expected, v.shift(x=1, fill_value=fill_value)) def test_shift2d(self): v = Variable(("x", "y"), [[1, 2], [3, 4]]) expected = Variable(("x", "y"), [[np.nan, np.nan], [np.nan, 1]]) assert_identical(expected, v.shift(x=1, y=1)) def test_roll(self): v = Variable("x", [1, 2, 3, 4, 5]) assert_identical(v, v.roll(x=0)) assert v is not v.roll(x=0) expected = Variable("x", [5, 1, 2, 3, 4]) assert_identical(expected, v.roll(x=1)) assert_identical(expected, v.roll(x=-4)) assert_identical(expected, v.roll(x=6)) expected = Variable("x", [4, 5, 1, 2, 3]) assert_identical(expected, v.roll(x=2)) assert_identical(expected, v.roll(x=-3)) with pytest.raises(ValueError, match=r"dimension"): v.roll(z=0) def test_roll_consistency(self): v = Variable(("x", "y"), np.random.randn(5, 6)) for axis, dim in [(0, "x"), (1, "y")]: for shift in [-3, 0, 1, 7, 11]: expected = np.roll(v.values, shift, axis=axis) actual = v.roll(**{dim: shift}).values assert_array_equal(expected, actual) def test_transpose(self): v = Variable(["time", "x"], self.d) v2 = Variable(["x", "time"], self.d.T) assert_identical(v, v2.transpose()) assert_identical(v.transpose(), v.T) x = np.random.randn(2, 3, 4, 5) w = Variable(["a", "b", "c", "d"], x) w2 = Variable(["d", "b", "c", "a"], np.einsum("abcd->dbca", x)) assert w2.shape == (5, 3, 4, 2) assert_identical(w2, w.transpose("d", "b", "c", "a")) assert_identical(w2, w.transpose("d", ..., "a")) assert_identical(w2, w.transpose("d", "b", "c", ...)) assert_identical(w2, w.transpose(..., "b", "c", "a")) assert_identical(w, w2.transpose("a", "b", "c", "d")) w3 = Variable(["b", "c", "d", "a"], np.einsum("abcd->bcda", x)) assert_identical(w, w3.transpose("a", "b", "c", "d")) # test missing dimension, raise error with pytest.raises(ValueError): v.transpose(..., "not_a_dim") # test missing dimension, ignore error actual = v.transpose(..., "not_a_dim", missing_dims="ignore") expected_ell = v.transpose(...) assert_identical(expected_ell, actual) # test missing dimension, raise warning with pytest.warns(UserWarning): v.transpose(..., "not_a_dim", missing_dims="warn") assert_identical(expected_ell, actual) def test_transpose_0d(self): for value in [ 3.5, ("a", 1), np.datetime64("2000-01-01"), np.timedelta64(1, "h"), None, object(), ]: variable = Variable([], value) actual = variable.transpose() assert_identical(actual, variable) def test_pandas_categorical_dtype(self): data = pd.Categorical(np.arange(10, dtype="int64")) v = self.cls("x", data) print(v) # should not error assert isinstance(v.dtype, pd.CategoricalDtype) def test_squeeze(self): v = Variable(["x", "y"], [[1]]) assert_identical(Variable([], 1), v.squeeze()) assert_identical(Variable(["y"], [1]), v.squeeze("x")) assert_identical(Variable(["y"], [1]), v.squeeze(["x"])) assert_identical(Variable(["x"], [1]), v.squeeze("y")) assert_identical(Variable([], 1), v.squeeze(["x", "y"])) v = Variable(["x", "y"], [[1, 2]]) assert_identical(Variable(["y"], [1, 2]), v.squeeze()) assert_identical(Variable(["y"], [1, 2]), v.squeeze("x")) with pytest.raises(ValueError, match=r"cannot select a dimension"): v.squeeze("y") def test_get_axis_num(self) -> None: v = Variable(["x", "y", "z"], np.random.randn(2, 3, 4)) assert v.get_axis_num("x") == 0 assert v.get_axis_num(["x"]) == (0,) assert v.get_axis_num(["x", "y"]) == (0, 1) assert v.get_axis_num(["z", "y", "x"]) == (2, 1, 0) with pytest.raises(ValueError, match=r"not found in array dim"): v.get_axis_num("foobar") # Test the type annotations: mypy will complain if the inferred # type is wrong v.get_axis_num("x") + 0 v.get_axis_num(["x"]) + () v.get_axis_num(("x", "y")) + () def test_set_dims(self): v = Variable(["x"], [0, 1]) actual = v.set_dims(["x", "y"]) expected = Variable(["x", "y"], [[0], [1]]) assert_identical(actual, expected) actual = v.set_dims(["y", "x"]) assert_identical(actual, expected.T) actual = v.set_dims({"x": 2, "y": 2}) expected = Variable(["x", "y"], [[0, 0], [1, 1]]) assert_identical(actual, expected) v = Variable(["foo"], [0, 1]) actual = v.set_dims("foo") expected = v assert_identical(actual, expected) with pytest.raises(ValueError, match=r"must be a superset"): v.set_dims(["z"]) def test_set_dims_object_dtype(self): v = Variable([], ("a", 1)) actual = v.set_dims(("x",), (3,)) exp_values = np.empty((3,), dtype=object) for i in range(3): exp_values[i] = ("a", 1) expected = Variable(["x"], exp_values) assert_identical(actual, expected) def test_set_dims_without_broadcast(self): class ArrayWithoutBroadcastTo(NDArrayMixin, indexing.ExplicitlyIndexed): def __init__(self, array): self.array = array # Broadcasting with __getitem__ is "easier" to implement # especially for dims of 1 def __getitem__(self, key): return self.array[key] def __array_function__(self, *args, **kwargs): raise NotImplementedError( "Not we don't want to use broadcast_to here " "https://github.com/pydata/xarray/issues/9462" ) arr = ArrayWithoutBroadcastTo(np.zeros((3, 4))) # We should be able to add a new axis without broadcasting assert arr[np.newaxis, :, :].shape == (1, 3, 4) with pytest.raises(NotImplementedError): np.broadcast_to(arr, (1, 3, 4)) v = Variable(["x", "y"], arr) v_expanded = v.set_dims(["z", "x", "y"]) assert v_expanded.dims == ("z", "x", "y") assert v_expanded.shape == (1, 3, 4) v_expanded = v.set_dims(["x", "z", "y"]) assert v_expanded.dims == ("x", "z", "y") assert v_expanded.shape == (3, 1, 4) v_expanded = v.set_dims(["x", "y", "z"]) assert v_expanded.dims == ("x", "y", "z") assert v_expanded.shape == (3, 4, 1) # Explicitly asking for a shape of 1 triggers a different # codepath in set_dims # https://github.com/pydata/xarray/issues/9462 v_expanded = v.set_dims(["z", "x", "y"], shape=(1, 3, 4)) assert v_expanded.dims == ("z", "x", "y") assert v_expanded.shape == (1, 3, 4) v_expanded = v.set_dims(["x", "z", "y"], shape=(3, 1, 4)) assert v_expanded.dims == ("x", "z", "y") assert v_expanded.shape == (3, 1, 4) v_expanded = v.set_dims(["x", "y", "z"], shape=(3, 4, 1)) assert v_expanded.dims == ("x", "y", "z") assert v_expanded.shape == (3, 4, 1) v_expanded = v.set_dims({"z": 1, "x": 3, "y": 4}) assert v_expanded.dims == ("z", "x", "y") assert v_expanded.shape == (1, 3, 4) v_expanded = v.set_dims({"x": 3, "z": 1, "y": 4}) assert v_expanded.dims == ("x", "z", "y") assert v_expanded.shape == (3, 1, 4) v_expanded = v.set_dims({"x": 3, "y": 4, "z": 1}) assert v_expanded.dims == ("x", "y", "z") assert v_expanded.shape == (3, 4, 1) with pytest.raises(NotImplementedError): v.set_dims({"z": 2, "x": 3, "y": 4}) with pytest.raises(NotImplementedError): v.set_dims(["z", "x", "y"], shape=(2, 3, 4)) def test_stack(self): v = Variable(["x", "y"], [[0, 1], [2, 3]], {"foo": "bar"}) actual = v.stack(z=("x", "y")) expected = Variable("z", [0, 1, 2, 3], v.attrs) assert_identical(actual, expected) actual = v.stack(z=("x",)) expected = Variable(("y", "z"), v.data.T, v.attrs) assert_identical(actual, expected) actual = v.stack(z=()) assert_identical(actual, v) actual = v.stack(X=("x",), Y=("y",)).transpose("X", "Y") expected = Variable(("X", "Y"), v.data, v.attrs) assert_identical(actual, expected) def test_stack_errors(self): v = Variable(["x", "y"], [[0, 1], [2, 3]], {"foo": "bar"}) with pytest.raises(ValueError, match=r"invalid existing dim"): v.stack(z=("x1",)) with pytest.raises(ValueError, match=r"cannot create a new dim"): v.stack(x=("x",)) def test_unstack(self): v = Variable("z", [0, 1, 2, 3], {"foo": "bar"}) actual = v.unstack(z={"x": 2, "y": 2}) expected = Variable(("x", "y"), [[0, 1], [2, 3]], v.attrs) assert_identical(actual, expected) actual = v.unstack(z={"x": 4, "y": 1}) expected = Variable(("x", "y"), [[0], [1], [2], [3]], v.attrs) assert_identical(actual, expected) actual = v.unstack(z={"x": 4}) expected = Variable("x", [0, 1, 2, 3], v.attrs) assert_identical(actual, expected) def test_unstack_errors(self): v = Variable("z", [0, 1, 2, 3]) with pytest.raises(ValueError, match=r"invalid existing dim"): v.unstack(foo={"x": 4}) with pytest.raises(ValueError, match=r"cannot create a new dim"): v.stack(z=("z",)) with pytest.raises(ValueError, match=r"the product of the new dim"): v.unstack(z={"x": 5}) def test_unstack_2d(self): v = Variable(["x", "y"], [[0, 1], [2, 3]]) actual = v.unstack(y={"z": 2}) expected = Variable(["x", "z"], v.data) assert_identical(actual, expected) actual = v.unstack(x={"z": 2}) expected = Variable(["y", "z"], v.data.T) assert_identical(actual, expected) def test_stack_unstack_consistency(self): v = Variable(["x", "y"], [[0, 1], [2, 3]]) actual = v.stack(z=("x", "y")).unstack(z={"x": 2, "y": 2}) assert_identical(actual, v) @pytest.mark.filterwarnings("error::RuntimeWarning") def test_unstack_without_missing(self): v = Variable(["z"], [0, 1, 2, 3]) expected = Variable(["x", "y"], [[0, 1], [2, 3]]) actual = v.unstack(z={"x": 2, "y": 2}) assert_identical(actual, expected) def test_broadcasting_math(self): x = np.random.randn(2, 3) v = Variable(["a", "b"], x) # 1d to 2d broadcasting assert_identical(v * v, Variable(["a", "b"], np.einsum("ab,ab->ab", x, x))) assert_identical(v * v[0], Variable(["a", "b"], np.einsum("ab,b->ab", x, x[0]))) assert_identical(v[0] * v, Variable(["b", "a"], np.einsum("b,ab->ba", x[0], x))) assert_identical( v[0] * v[:, 0], Variable(["b", "a"], np.einsum("b,a->ba", x[0], x[:, 0])) ) # higher dim broadcasting y = np.random.randn(3, 4, 5) w = Variable(["b", "c", "d"], y) assert_identical( v * w, Variable(["a", "b", "c", "d"], np.einsum("ab,bcd->abcd", x, y)) ) assert_identical( w * v, Variable(["b", "c", "d", "a"], np.einsum("bcd,ab->bcda", y, x)) ) assert_identical( v * w[0], Variable(["a", "b", "c", "d"], np.einsum("ab,cd->abcd", x, y[0])) ) @pytest.mark.filterwarnings("ignore:Duplicate dimension names") def test_broadcasting_failures(self): a = Variable(["x"], np.arange(10)) b = Variable(["x"], np.arange(5)) c = Variable(["x", "x"], np.arange(100).reshape(10, 10)) with pytest.raises(ValueError, match=r"mismatched lengths"): a + b with pytest.raises(ValueError, match=r"duplicate dimensions"): a + c def test_inplace_math(self): x = np.arange(5) v = Variable(["x"], x) v2 = v v2 += 1 assert v is v2 # since we provided an ndarray for data, it is also modified in-place assert source_ndarray(v.values) is x assert_array_equal(v.values, np.arange(5) + 1) with pytest.raises(ValueError, match=r"dimensions cannot change"): v += Variable("y", np.arange(5)) def test_inplace_math_error(self): x = np.arange(5) v = IndexVariable(["x"], x) with pytest.raises( TypeError, match=r"Values of an IndexVariable are immutable" ): v += 1 def test_reduce(self): v = Variable(["x", "y"], self.d, {"ignored": "attributes"}) # Reduce keeps attrs by default expected = Variable(["y"], self.d.std(axis=0), {"ignored": "attributes"}) assert_identical(v.reduce(np.std, "x"), expected) assert_identical(v.reduce(np.std, axis=0), v.reduce(np.std, dim="x")) assert_identical( v.reduce(np.std, ["y", "x"]), Variable([], self.d.std(axis=(0, 1)), {"ignored": "attributes"}), ) assert_identical( v.reduce(np.std), Variable([], self.d.std(), {"ignored": "attributes"}) ) # Chained reductions both keep attrs expected_chained = Variable( [], self.d.mean(axis=0).std(), {"ignored": "attributes"} ) assert_identical( v.reduce(np.mean, "x").reduce(np.std, "y"), expected_chained, ) assert_allclose(v.mean("x"), v.reduce(np.mean, "x")) with pytest.raises(ValueError, match=r"cannot supply both"): v.mean(dim="x", axis=0) @requires_bottleneck @pytest.mark.parametrize("compute_backend", ["bottleneck"], indirect=True) def test_reduce_use_bottleneck(self, monkeypatch, compute_backend): def raise_if_called(*args, **kwargs): raise RuntimeError("should not have been called") import bottleneck as bn monkeypatch.setattr(bn, "nanmin", raise_if_called) v = Variable("x", [0.0, np.nan, 1.0]) with pytest.raises(RuntimeError, match="should not have been called"): with set_options(use_bottleneck=True): v.min() with set_options(use_bottleneck=False): v.min() @pytest.mark.parametrize("skipna", [True, False, None]) @pytest.mark.parametrize("q", [0.25, [0.50], [0.25, 0.75]]) @pytest.mark.parametrize( "axis, dim", zip([None, 0, [0], [0, 1]], [None, "x", ["x"], ["x", "y"]], strict=True), ) def test_quantile(self, q, axis, dim, skipna): d = self.d.copy() d[0, 0] = np.nan v = Variable(["x", "y"], d) actual = v.quantile(q, dim=dim, skipna=skipna) _percentile_func = np.nanpercentile if skipna in (True, None) else np.percentile expected = _percentile_func(d, np.array(q) * 100, axis=axis) np.testing.assert_allclose(actual.values, expected) @requires_dask @pytest.mark.parametrize("q", [0.25, [0.50], [0.25, 0.75]]) @pytest.mark.parametrize("axis, dim", [[1, "y"], [[1], ["y"]]]) def test_quantile_dask(self, q, axis, dim): v = Variable(["x", "y"], self.d).chunk({"x": 2}) actual = v.quantile(q, dim=dim) assert isinstance(actual.data, dask_array_type) expected = np.nanpercentile(self.d, np.array(q) * 100, axis=axis) np.testing.assert_allclose(actual.values, expected) @pytest.mark.parametrize("method", ["midpoint", "lower"]) @pytest.mark.parametrize( "use_dask", [pytest.param(True, marks=requires_dask), False] ) def test_quantile_method(self, method, use_dask) -> None: v = Variable(["x", "y"], self.d) if use_dask: v = v.chunk({"x": 2}) q = np.array([0.25, 0.5, 0.75]) actual = v.quantile(q, dim="y", method=method) expected = np.nanquantile(self.d, q, axis=1, method=method) if use_dask: assert isinstance(actual.data, dask_array_type) np.testing.assert_allclose(actual.values, expected) @pytest.mark.filterwarnings( "default:The `interpolation` argument to quantile was renamed to `method`:FutureWarning" ) @pytest.mark.parametrize("method", ["midpoint", "lower"]) def test_quantile_interpolation_deprecation(self, method) -> None: v = Variable(["x", "y"], self.d) q = np.array([0.25, 0.5, 0.75]) with pytest.warns( FutureWarning, match="`interpolation` argument to quantile was renamed to `method`", ): actual = v.quantile(q, dim="y", interpolation=method) expected = v.quantile(q, dim="y", method=method) np.testing.assert_allclose(actual.values, expected.values) with warnings.catch_warnings(record=True): with pytest.raises(TypeError, match="interpolation and method keywords"): v.quantile(q, dim="y", interpolation=method, method=method) @requires_dask def test_quantile_chunked_dim_error(self): v = Variable(["x", "y"], self.d).chunk({"x": 2}) if has_dask_ge_2024_11_0: # Dask rechunks np.testing.assert_allclose( v.compute().quantile(0.5, dim="x"), v.quantile(0.5, dim="x") ) else: # this checks for ValueError in dask.array.apply_gufunc with pytest.raises(ValueError, match=r"consists of multiple chunks"): v.quantile(0.5, dim="x") @pytest.mark.parametrize("compute_backend", ["numbagg", None], indirect=True) @pytest.mark.parametrize("q", [-0.1, 1.1, [2], [0.25, 2]]) def test_quantile_out_of_bounds(self, q, compute_backend): v = Variable(["x", "y"], self.d) # escape special characters with pytest.raises( ValueError, match=r"(Q|q)uantiles must be in the range \[0, 1\]", ): v.quantile(q, dim="x") @requires_dask @requires_bottleneck def test_rank_dask(self): # Instead of a single test here, we could parameterize the other tests for both # arrays. But this is sufficient. v = Variable( ["x", "y"], [[30.0, 1.0, np.nan, 20.0, 4.0], [30.0, 1.0, np.nan, 20.0, 4.0]] ).chunk(x=1) expected = Variable( ["x", "y"], [[4.0, 1.0, np.nan, 3.0, 2.0], [4.0, 1.0, np.nan, 3.0, 2.0]] ) assert_equal(v.rank("y").compute(), expected) with pytest.raises( ValueError, match=r" with dask='parallelized' consists of multiple chunks" ): v.rank("x") def test_rank_use_bottleneck(self): v = Variable(["x"], [3.0, 1.0, np.nan, 2.0, 4.0]) with set_options(use_bottleneck=False): with pytest.raises(RuntimeError): v.rank("x") @requires_bottleneck def test_rank(self): import bottleneck as bn # floats v = Variable(["x", "y"], [[3, 4, np.nan, 1]]) expect_0 = bn.nanrankdata(v.data, axis=0) expect_1 = bn.nanrankdata(v.data, axis=1) np.testing.assert_allclose(v.rank("x").values, expect_0) np.testing.assert_allclose(v.rank("y").values, expect_1) # int v = Variable(["x"], [3, 2, 1]) expect = bn.rankdata(v.data, axis=0) np.testing.assert_allclose(v.rank("x").values, expect) # str v = Variable(["x"], ["c", "b", "a"]) expect = bn.rankdata(v.data, axis=0) np.testing.assert_allclose(v.rank("x").values, expect) # pct v = Variable(["x"], [3.0, 1.0, np.nan, 2.0, 4.0]) v_expect = Variable(["x"], [0.75, 0.25, np.nan, 0.5, 1.0]) assert_equal(v.rank("x", pct=True), v_expect) # invalid dim with pytest.raises(ValueError): # apply_ufunc error message isn't great here — `ValueError: tuple.index(x): x not in tuple` v.rank("y") def test_big_endian_reduce(self): # regression test for GH489 data = np.ones(5, dtype=">f4") v = Variable(["x"], data) expected = Variable([], 5) assert_identical(expected, v.sum()) def test_reduce_funcs(self): v = Variable("x", np.array([1, np.nan, 2, 3])) assert_identical(v.mean(), Variable([], 2)) assert_identical(v.mean(skipna=True), Variable([], 2)) assert_identical(v.mean(skipna=False), Variable([], np.nan)) assert_identical(np.mean(v), Variable([], 2)) assert_identical(v.prod(), Variable([], 6)) assert_identical(v.cumsum(axis=0), Variable("x", np.array([1, 1, 3, 6]))) assert_identical(v.cumprod(axis=0), Variable("x", np.array([1, 1, 2, 6]))) assert_identical(v.var(), Variable([], 2.0 / 3)) assert_identical(v.median(), Variable([], 2)) v = Variable("x", [True, False, False]) assert_identical(v.any(), Variable([], True)) assert_identical(v.all(dim="x"), Variable([], False)) v = Variable("t", pd.date_range("2000-01-01", periods=3)) assert v.argmax(skipna=True, dim="t") == 2 assert_identical(v.max(), Variable([], pd.Timestamp("2000-01-03"))) def test_reduce_keepdims(self): v = Variable(["x", "y"], self.d) with set_options(use_numbagg=False): assert_identical( v.mean(keepdims=True), Variable(v.dims, np.mean(self.d, keepdims=True)) ) assert_identical( v.mean(dim="x", keepdims=True), Variable(v.dims, np.mean(self.d, axis=0, keepdims=True)), ) assert_identical( v.mean(dim="y", keepdims=True), Variable(v.dims, np.mean(self.d, axis=1, keepdims=True)), ) assert_identical( v.mean(dim=["y", "x"], keepdims=True), Variable(v.dims, np.mean(self.d, axis=(1, 0), keepdims=True)), ) v = Variable([], 1.0) assert_identical( v.mean(keepdims=True), Variable([], np.mean(v.data, keepdims=True)) ) @requires_dask def test_reduce_keepdims_dask(self): import dask.array v = Variable(["x", "y"], self.d).chunk() actual = v.mean(keepdims=True) assert isinstance(actual.data, dask.array.Array) expected = Variable(v.dims, np.mean(self.d, keepdims=True)) assert_identical(actual, expected) actual = v.mean(dim="y", keepdims=True) assert isinstance(actual.data, dask.array.Array) expected = Variable(v.dims, np.mean(self.d, axis=1, keepdims=True)) assert_identical(actual, expected) def test_reduce_keep_attrs(self): _attrs = {"units": "test", "long_name": "testing"} v = Variable(["x", "y"], self.d, _attrs) # Test default behavior (keeps attrs for reduction operations) vm = v.mean() assert len(vm.attrs) == len(_attrs) assert vm.attrs == _attrs # Test explicitly keeping attrs vm = v.mean(keep_attrs=True) assert len(vm.attrs) == len(_attrs) assert vm.attrs == _attrs # Test explicitly dropping attrs vm = v.mean(keep_attrs=False) assert len(vm.attrs) == 0 assert vm.attrs == {} def test_binary_ops_keep_attrs(self): _attrs = {"units": "test", "long_name": "testing"} a = Variable(["x", "y"], np.random.randn(3, 3), _attrs) b = Variable(["x", "y"], np.random.randn(3, 3), _attrs) # Test kept attrs (now default) d = a - b # just one operation assert d.attrs == _attrs # Test dropped attrs with set_options(keep_attrs=False): d = a - b assert d.attrs == {} def test_binary_ops_attrs_drop_conflicts(self): # Test that binary operations combine attrs with drop_conflicts behavior attrs_a = {"units": "meters", "long_name": "distance", "source": "sensor_a"} attrs_b = {"units": "feet", "resolution": "high", "source": "sensor_b"} a = Variable(["x"], [1, 2, 3], attrs_a) b = Variable(["x"], [4, 5, 6], attrs_b) # With keep_attrs=True (default), should combine attrs dropping conflicts result = a + b # "units" and "source" conflict, so they're dropped # "long_name" only in a, "resolution" only in b, so they're kept assert result.attrs == {"long_name": "distance", "resolution": "high"} # Test with identical values for some attrs attrs_c = {"units": "meters", "type": "data", "source": "sensor_c"} c = Variable(["x"], [7, 8, 9], attrs_c) result2 = a + c # "units" has same value, so kept; "source" conflicts, so dropped # "long_name" from a, "type" from c assert result2.attrs == { "units": "meters", "long_name": "distance", "type": "data", } # With keep_attrs=False, attrs should be empty with set_options(keep_attrs=False): result3 = a + b assert result3.attrs == {} def test_count(self): expected = Variable([], 3) actual = Variable(["x"], [1, 2, 3, np.nan]).count() assert_identical(expected, actual) v = Variable(["x"], np.array(["1", "2", "3", np.nan], dtype=object)) actual = v.count() assert_identical(expected, actual) actual = Variable(["x"], [True, False, True]).count() assert_identical(expected, actual) assert actual.dtype == int expected = Variable(["x"], [2, 3]) actual = Variable(["x", "y"], [[1, 0, np.nan], [1, 1, 1]]).count("y") assert_identical(expected, actual) def test_setitem(self): v = Variable(["x", "y"], [[0, 3, 2], [3, 4, 5]]) v[0, 1] = 1 assert v[0, 1] == 1 v = Variable(["x", "y"], [[0, 3, 2], [3, 4, 5]]) v[dict(x=[0, 1])] = 1 assert_array_equal(v[[0, 1]], np.ones_like(v[[0, 1]])) # boolean indexing v = Variable(["x", "y"], [[0, 3, 2], [3, 4, 5]]) v[dict(x=[True, False])] = 1 assert_array_equal(v[0], np.ones_like(v[0])) v = Variable(["x", "y"], [[0, 3, 2], [3, 4, 5]]) v[dict(x=[True, False], y=[False, True, False])] = 1 assert v[0, 1] == 1 def test_setitem_fancy(self): # assignment which should work as np.ndarray does def assert_assigned_2d(array, key_x, key_y, values): expected = array.copy() expected[key_x, key_y] = values v = Variable(["x", "y"], array) v[dict(x=key_x, y=key_y)] = values assert_array_equal(expected, v) # 1d vectorized indexing assert_assigned_2d( np.random.randn(4, 3), key_x=Variable(["a"], [0, 1]), key_y=Variable(["a"], [0, 1]), values=0, ) assert_assigned_2d( np.random.randn(4, 3), key_x=Variable(["a"], [0, 1]), key_y=Variable(["a"], [0, 1]), values=Variable((), 0), ) assert_assigned_2d( np.random.randn(4, 3), key_x=Variable(["a"], [0, 1]), key_y=Variable(["a"], [0, 1]), values=Variable(("a"), [3, 2]), ) assert_assigned_2d( np.random.randn(4, 3), key_x=slice(None), key_y=Variable(["a"], [0, 1]), values=Variable(("a"), [3, 2]), ) # 2d-vectorized indexing assert_assigned_2d( np.random.randn(4, 3), key_x=Variable(["a", "b"], [[0, 1]]), key_y=Variable(["a", "b"], [[1, 0]]), values=0, ) assert_assigned_2d( np.random.randn(4, 3), key_x=Variable(["a", "b"], [[0, 1]]), key_y=Variable(["a", "b"], [[1, 0]]), values=[0], ) assert_assigned_2d( np.random.randn(5, 4), key_x=Variable(["a", "b"], [[0, 1], [2, 3]]), key_y=Variable(["a", "b"], [[1, 0], [3, 3]]), values=[2, 3], ) # vindex with slice v = Variable(["x", "y", "z"], np.ones((4, 3, 2))) ind = Variable(["a"], [0, 1]) v[dict(x=ind, z=ind)] = 0 expected = Variable(["x", "y", "z"], np.ones((4, 3, 2))) expected[0, :, 0] = 0 expected[1, :, 1] = 0 assert_identical(expected, v) # dimension broadcast v = Variable(["x", "y"], np.ones((3, 2))) ind = Variable(["a", "b"], [[0, 1]]) v[ind, :] = 0 expected = Variable(["x", "y"], [[0, 0], [0, 0], [1, 1]]) assert_identical(expected, v) with pytest.raises(ValueError, match=r"shape mismatch"): v[ind, ind] = np.zeros((1, 2, 1)) v = Variable(["x", "y"], [[0, 3, 2], [3, 4, 5]]) ind = Variable(["a"], [0, 1]) v[dict(x=ind)] = Variable(["a", "y"], np.ones((2, 3), dtype=int) * 10) assert_array_equal(v[0], np.ones_like(v[0]) * 10) assert_array_equal(v[1], np.ones_like(v[1]) * 10) assert v.dims == ("x", "y") # dimension should not change # increment v = Variable(["x", "y"], np.arange(6).reshape(3, 2)) ind = Variable(["a"], [0, 1]) v[dict(x=ind)] += 1 expected = Variable(["x", "y"], [[1, 2], [3, 4], [4, 5]]) assert_identical(v, expected) ind = Variable(["a"], [0, 0]) v[dict(x=ind)] += 1 expected = Variable(["x", "y"], [[2, 3], [3, 4], [4, 5]]) assert_identical(v, expected) def test_coarsen(self): v = self.cls(["x"], [0, 1, 2, 3, 4]) actual = v.coarsen({"x": 2}, boundary="pad", func="mean") expected = self.cls(["x"], [0.5, 2.5, 4]) assert_identical(actual, expected) actual = v.coarsen({"x": 2}, func="mean", boundary="pad", side="right") expected = self.cls(["x"], [0, 1.5, 3.5]) assert_identical(actual, expected) actual = v.coarsen({"x": 2}, func=np.mean, side="right", boundary="trim") expected = self.cls(["x"], [1.5, 3.5]) assert_identical(actual, expected) # working test v = self.cls(["x", "y", "z"], np.arange(40 * 30 * 2).reshape(40, 30, 2)) for windows, func, side, boundary in [ ({"x": 2}, np.mean, "left", "trim"), ({"x": 2}, np.median, {"x": "left"}, "pad"), ({"x": 2, "y": 3}, np.max, "left", {"x": "pad", "y": "trim"}), ]: v.coarsen(windows, func, boundary, side) def test_coarsen_2d(self): # 2d-mean should be the same with the successive 1d-mean v = self.cls(["x", "y"], np.arange(6 * 12).reshape(6, 12)) actual = v.coarsen({"x": 3, "y": 4}, func="mean") expected = v.coarsen({"x": 3}, func="mean").coarsen({"y": 4}, func="mean") assert_equal(actual, expected) v = self.cls(["x", "y"], np.arange(7 * 12).reshape(7, 12)) actual = v.coarsen({"x": 3, "y": 4}, func="mean", boundary="trim") expected = v.coarsen({"x": 3}, func="mean", boundary="trim").coarsen( {"y": 4}, func="mean", boundary="trim" ) assert_equal(actual, expected) # if there is nan, the two should be different v = self.cls(["x", "y"], 1.0 * np.arange(6 * 12).reshape(6, 12)) v[2, 4] = np.nan v[3, 5] = np.nan actual = v.coarsen({"x": 3, "y": 4}, func="mean", boundary="trim") expected = ( v.coarsen({"x": 3}, func="sum", boundary="trim").coarsen( {"y": 4}, func="sum", boundary="trim" ) / 12 ) assert not actual.equals(expected) # adjusting the nan count expected[0, 1] *= 12 / 11 expected[1, 1] *= 12 / 11 assert_allclose(actual, expected) v = self.cls(("x", "y"), np.arange(4 * 4, dtype=np.float32).reshape(4, 4)) actual = v.coarsen(dict(x=2, y=2), func="count", boundary="exact") expected = self.cls(("x", "y"), 4 * np.ones((2, 2))) assert_equal(actual, expected) v[0, 0] = np.nan v[-1, -1] = np.nan expected[0, 0] = 3 expected[-1, -1] = 3 actual = v.coarsen(dict(x=2, y=2), func="count", boundary="exact") assert_equal(actual, expected) actual = v.coarsen(dict(x=2, y=2), func="sum", boundary="exact", skipna=False) expected = self.cls(("x", "y"), [[np.nan, 18], [42, np.nan]]) assert_equal(actual, expected) actual = v.coarsen(dict(x=2, y=2), func="sum", boundary="exact", skipna=True) expected = self.cls(("x", "y"), [[10, 18], [42, 35]]) assert_equal(actual, expected) # perhaps @pytest.mark.parametrize("operation", [f for f in duck_array_ops]) def test_coarsen_keep_attrs(self, operation="mean"): _attrs = {"units": "test", "long_name": "testing"} test_func = getattr(duck_array_ops, operation, None) # Test dropped attrs with set_options(keep_attrs=False): new = Variable(["coord"], np.linspace(1, 10, 100), attrs=_attrs).coarsen( windows={"coord": 1}, func=test_func, boundary="exact", side="left" ) assert new.attrs == {} # Test kept attrs with set_options(keep_attrs=True): new = Variable(["coord"], np.linspace(1, 10, 100), attrs=_attrs).coarsen( windows={"coord": 1}, func=test_func, boundary="exact", side="left", ) assert new.attrs == _attrs @requires_dask
TestVariable
python
great-expectations__great_expectations
tests/integration/data_sources_and_expectations/test_expectation_conditions.py
{ "start": 14279, "end": 17990 }
class ____: """Simple tests to ensure that Spark properly utilizes row condition from each type of expectation (ColumnMapExpectation, ColumnPairMapExpectation, etc) """ @parameterize_batch_for_data_sources( data_source_configs=[spark_filesystem_csv_datasource_test_config], data=DATA, ) def test_column_aggregate_expectation_with_condition_row_condition( self, batch_for_datasource: Batch ) -> None: """Test ColumnAggregateExpectation with Condition row_condition.""" row_condition = (Column("quantity") > 0) & (Column("quantity") < 3) expectation = gxe.ExpectColumnMinToBeBetween( column="amount", min_value=0.5, max_value=1.5, row_condition=row_condition, condition_parser="spark", ) result = batch_for_datasource.validate(expectation) assert result.success @parameterize_batch_for_data_sources( data_source_configs=[spark_filesystem_csv_datasource_test_config], data=DATA, ) def test_column_map_expectation_with_condition_row_condition( self, batch_for_datasource: Batch ) -> None: """Test ColumnMapExpectation with Condition row_condition.""" row_condition = Column("name") == "albert" expectation = gxe.ExpectColumnValuesToBeBetween( column="quantity", min_value=0.5, max_value=1.5, row_condition=row_condition, condition_parser="spark", ) result = batch_for_datasource.validate(expectation) assert result.success @parameterize_batch_for_data_sources( data_source_configs=[spark_filesystem_csv_datasource_test_config], data=DATA, ) def test_column_pair_map_expectation_with_condition_row_condition( self, batch_for_datasource: Batch ) -> None: """Test ColumnPairMapExpectation with Condition row_condition.""" row_condition = Column("quantity") < 3 expectation = gxe.ExpectColumnPairValuesToBeEqual( column_A="quantity", column_B="quantity", row_condition=row_condition, condition_parser="spark", ) result = batch_for_datasource.validate(expectation) assert result.success @parameterize_batch_for_data_sources( data_source_configs=[spark_filesystem_csv_datasource_test_config], data=DATA, ) def test_multicolumn_map_expectation_with_condition_row_condition( self, batch_for_datasource: Batch ) -> None: """Test MulticolumnMapExpectation with Condition row_condition.""" row_condition = Column("quantity") < 3 expectation = gxe.ExpectCompoundColumnsToBeUnique( column_list=["quantity", "name"], row_condition=row_condition, condition_parser="spark", ) result = batch_for_datasource.validate(expectation) assert result.success @parameterize_batch_for_data_sources( data_source_configs=[spark_filesystem_csv_datasource_test_config], data=DATA, ) def test_batch_expectation_with_condition_row_condition( self, batch_for_datasource: Batch ) -> None: """Test BatchExpectation with Condition row_condition.""" row_condition = Column("name") == "albert" expectation = gxe.ExpectTableRowCountToBeBetween( min_value=1, max_value=1, row_condition=row_condition, condition_parser="spark", ) result = batch_for_datasource.validate(expectation) assert result.success
TestSparkConditionClassAcrossExpectationTypes
python
lazyprogrammer__machine_learning_examples
ann_class2/batch_norm_tf.py
{ "start": 460, "end": 1904 }
class ____(object): def __init__(self, M1, M2, f): self.M1 = M1 self.M2 = M2 self.f = f W = init_weight(M1, M2).astype(np.float32) gamma = np.ones(M2).astype(np.float32) beta = np.zeros(M2).astype(np.float32) self.W = tf.Variable(W) self.gamma = tf.Variable(gamma) self.beta = tf.Variable(beta) # for test time self.running_mean = tf.Variable(np.zeros(M2).astype(np.float32), trainable=False) self.running_var = tf.Variable(np.zeros(M2).astype(np.float32), trainable=False) def forward(self, X, is_training, decay=0.9): activation = tf.matmul(X, self.W) if is_training: batch_mean, batch_var = tf.nn.moments(activation, [0]) update_running_mean = tf.assign( self.running_mean, self.running_mean * decay + batch_mean * (1 - decay) ) update_running_var = tf.assign( self.running_var, self.running_var * decay + batch_var * (1 - decay) ) with tf.control_dependencies([update_running_mean, update_running_var]): out = tf.nn.batch_normalization( activation, batch_mean, batch_var, self.beta, self.gamma, 1e-4 ) else: out = tf.nn.batch_normalization( activation, self.running_mean, self.running_var, self.beta, self.gamma, 1e-4 ) return self.f(out)
HiddenLayerBatchNorm