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
Delgan__loguru
tests/test_add_option_serialize.py
{ "start": 62, "end": 4180 }
class ____: def __init__(self): self.message = None self.dict = None self.json = None def write(self, message): self.message = message self.dict = message.record self.json = json.loads(message) def test_serialize(): sink = JsonSink() logger.add(sink, format="{level} {message}", serialize=True) logger.debug("Test") assert sink.json["text"] == "DEBUG Test\n" assert sink.dict["message"] == sink.json["record"]["message"] == "Test" assert set(sink.dict.keys()) == set(sink.json["record"].keys()) def test_serialize_non_ascii_characters(): sink = JsonSink() logger.add(sink, format="{level.icon} {message}", serialize=True) logger.debug("天") assert re.search(r'"message": "([^\"]+)"', sink.message).group(1) == "天" assert re.search(r'"text": "([^\"]+)"', sink.message).group(1) == "🐞 天\\n" assert re.search(r'"icon": "([^\"]+)"', sink.message).group(1) == "🐞" assert sink.json["text"] == "🐞 天\n" assert sink.dict["message"] == sink.json["record"]["message"] == "天" def test_serialize_exception(): sink = JsonSink() logger.add(sink, format="{message}", serialize=True, catch=False) try: 1 / 0 # noqa: B018 except ZeroDivisionError: logger.exception("Error") lines = sink.json["text"].splitlines() assert lines[0] == "Error" assert lines[-1] == "ZeroDivisionError: division by zero" assert sink.json["record"]["exception"] == { "type": "ZeroDivisionError", "value": "division by zero", "traceback": True, } def test_serialize_exception_without_context(): sink = JsonSink() logger.add(sink, format="{message}", serialize=True, catch=False) logger.exception("No Error") lines = sink.json["text"].splitlines() assert lines[0] == "No Error" assert lines[-1] == "NoneType" if sys.version_info < (3, 5, 3) else "NoneType: None" assert sink.json["record"]["exception"] == { "type": None, "value": None, "traceback": False, } def test_serialize_exception_none_tuple(): sink = JsonSink() logger.add(sink, format="{message}", serialize=True, catch=False) logger.opt(exception=(None, None, None)).error("No Error") lines = sink.json["text"].splitlines() assert lines[0] == "No Error" assert lines[-1] == "NoneType" if sys.version_info < (3, 5, 3) else "NoneType: None" assert sink.json["record"]["exception"] == { "type": None, "value": None, "traceback": False, } def test_serialize_exception_instance(): sink = JsonSink() logger.add(sink, format="{message}", serialize=True, catch=False) logger.opt(exception=ZeroDivisionError("Oops")).error("Failure") lines = sink.json["text"].splitlines() assert lines[0] == "Failure" assert lines[-1] == "ZeroDivisionError: Oops" assert sink.json["record"]["exception"] == { "type": "ZeroDivisionError", "value": "Oops", "traceback": False, } def test_serialize_with_catch_decorator(): sink = JsonSink() logger.add(sink, format="{message}", serialize=True, catch=False) @logger.catch def foo(): 1 / 0 # noqa: B018 foo() lines = sink.json["text"].splitlines() assert lines[0].startswith("An error has been caught") assert lines[-1] == "ZeroDivisionError: division by zero" assert bool(sink.json["record"]["exception"]) def test_serialize_with_record_option(): sink = JsonSink() logger.add(sink, format="{message}", serialize=True, catch=False) logger.opt(record=True).info("Test", foo=123) assert sink.json["text"] == "Test\n" assert sink.dict["extra"] == {"foo": 123} def test_serialize_not_serializable(): sink = JsonSink() logger.add(sink, format="{message}", catch=False, serialize=True) not_serializable = object() logger.bind(not_serializable=not_serializable).debug("Test") assert sink.dict["extra"]["not_serializable"] == not_serializable assert bool(sink.json["record"]["extra"]["not_serializable"])
JsonSink
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 627007, "end": 635224 }
class ____( DatumChannelMixin, core.FieldOrDatumDefWithConditionDatumDefGradientstringnull ): """ StrokeDatum schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the beginning of the band if set to ``0``, and at the middle of the band if set to ``0.5``. condition : dict, :class:`ConditionalValueDefGradientstringnullExprRef`, :class:`ConditionalParameterValueDefGradientstringnullExprRef`, :class:`ConditionalPredicateValueDefGradientstringnullExprRef`, Sequence[dict, :class:`ConditionalValueDefGradientstringnullExprRef`, :class:`ConditionalParameterValueDefGradientstringnullExprRef`, :class:`ConditionalPredicateValueDefGradientstringnullExprRef`] One or more value definition(s) with `a parameter or a test predicate <https://vega.github.io/vega-lite/docs/condition.html>`__. **Note:** A field definition's ``condition`` property can only contain `conditional value definitions <https://vega.github.io/vega-lite/docs/condition.html#value>`__ since Vega-Lite only allows at most one encoded field per encoding channel. datum : str, bool, dict, float, :class:`ExprRef`, :class:`DateTime`, :class:`RepeatRef`, :class:`PrimitiveValue`, None A constant value in data domain. title : str, :class:`Text`, Sequence[str], None A title for the field. If ``null``, the title will be removed. **Default value:** derived from the field's name and transformation function (``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function, the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the field is binned or has a time unit applied, the applied function is shown in parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``). Otherwise, the title is simply the field name. **Notes**: 1) You can customize the default field title format by providing the `fieldTitle <https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle function via the compile function's options <https://vega.github.io/vega-lite/usage/compile.html#field-title>`__. 2) If both field definition's ``title`` and axis, header, or legend ``title`` are defined, axis/header/legend title will be used. type : :class:`Type`, Literal['quantitative', 'ordinal', 'temporal', 'nominal', 'geojson'] The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or ``"nominal"``) for the encoded field or constant value (``datum``). It can also be a ``"geojson"`` type for encoding `'geoshape' <https://vega.github.io/vega-lite/docs/geoshape.html>`__. Vega-Lite automatically infers data types in many cases as discussed below. However, type is required for a field if: (1) the field is not nominal and the field encoding has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal scale for a field with ``bin`` or ``timeUnit``. **Default value:** 1) For a data ``field``, ``"nominal"`` is the default data type unless the field encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or ``timeUnit`` that satisfies the following criteria: * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__. * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` or (2) the specified scale type is a time or utc scale * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort order <https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__, (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding channel is ``order``. 2) For a constant value in data domain (``datum``): * ``"quantitative"`` if the datum is a number * ``"nominal"`` if the datum is a string * ``"temporal"`` if the datum is `a date time object <https://vega.github.io/vega-lite/docs/datetime.html>`__ **Note:** * Data ``type`` describes the semantics of the data rather than the primitive data types (number, string, etc.). The same primitive data type can have different types of measurement. For example, numeric data can represent quantitative, ordinal, or nominal data. * Data values for a temporal field can be either a date-time string (e.g., ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a timestamp number (e.g., ``1552199579097``). * When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) or `"ordinal" (for using an ordinal bin scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" (for using an ordinal scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property refers to the post-aggregation data type. For example, we can calculate count ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have ``type`` as they must have exactly the same type as their primary channels (e.g., ``x``, ``y``). **See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__ documentation. """ _class_is_valid_at_instantiation = False _encoding_name = "stroke" @overload def bandPosition(self, _: float, /) -> StrokeDatum: ... @overload def condition( self, *, test: Optional[str | SchemaBase | Map] = Undefined, value: Optional[str | Parameter | SchemaBase | Map | None] = Undefined, ) -> StrokeDatum: ... @overload def condition( self, *, empty: Optional[bool] = Undefined, param: Optional[str | SchemaBase] = Undefined, value: Optional[str | Parameter | SchemaBase | Map | None] = Undefined, ) -> StrokeDatum: ... @overload def condition( self, _: list[core.ConditionalValueDefGradientstringnullExprRef], / ) -> StrokeDatum: ... @overload def title(self, _: str | Sequence[str] | None, /) -> StrokeDatum: ... @overload def type(self, _: Type_T, /) -> StrokeDatum: ... def __init__( self, datum, bandPosition: Optional[float] = Undefined, condition: Optional[SchemaBase | Sequence[SchemaBase | Map] | Map] = Undefined, title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined, type: Optional[SchemaBase | Type_T] = Undefined, **kwds, ): super().__init__( datum=datum, bandPosition=bandPosition, condition=condition, title=title, type=type, **kwds, ) @with_property_setters
StrokeDatum
python
Lightning-AI__lightning
src/lightning/pytorch/utilities/combined_loader.py
{ "start": 7226, "end": 7708 }
class ____(TypedDict): fn: Callable[[list[int]], int] iterator: type[_ModeIterator] _SUPPORTED_MODES = { "min_size": _CombinationMode(fn=min, iterator=_MinSize), "max_size_cycle": _CombinationMode(fn=max, iterator=_MaxSizeCycle), "max_size": _CombinationMode(fn=max, iterator=_MaxSize), "sequential": _CombinationMode(fn=sum, iterator=_Sequential), } _LITERAL_SUPPORTED_MODES = Literal["min_size", "max_size_cycle", "max_size", "sequential"]
_CombinationMode
python
facebook__pyre-check
client/configuration/python_version.py
{ "start": 354, "end": 1306 }
class ____: major: int minor: int = 0 micro: int = 0 @staticmethod def from_string(input: str) -> "PythonVersion": try: splits = input.split(".") if len(splits) == 1: return PythonVersion(major=int(splits[0])) elif len(splits) == 2: return PythonVersion(major=int(splits[0]), minor=int(splits[1])) elif len(splits) == 3: return PythonVersion( major=int(splits[0]), minor=int(splits[1]), micro=int(splits[2]) ) raise exceptions.InvalidPythonVersion( "Version string is expected to have the form of 'X.Y.Z' but got " + f"'{input}'" ) except ValueError as error: raise exceptions.InvalidPythonVersion(input) from error def to_string(self) -> str: return f"{self.major}.{self.minor}.{self.micro}"
PythonVersion
python
tensorflow__tensorflow
tensorflow/compiler/tests/adagrad_da_test.py
{ "start": 1089, "end": 6950 }
class ____(xla_test.XLATestCase): def testAdagradDAWithoutRegularizationBasic1(self): for dtype in self.float_types: with self.session(), self.test_scope(): global_step = resource_variable_ops.ResourceVariable( 0, dtype=dtypes.int64) var0 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype) var1 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) opt = adagrad_da.AdagradDAOptimizer( 3.0, global_step, initial_gradient_squared_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0) update = opt.apply_gradients( zip([grads0, grads1], [var0, var1]), global_step=global_step) self.evaluate(variables.global_variables_initializer()) self.assertAllClose([0.0, 0.0], self.evaluate(var0)) self.assertAllClose([0.0, 0.0], self.evaluate(var1)) # Run a step of AdagradDA update.run() # Let g be the gradient accumulator, gg be the gradient squared # accumulator, T be the global step, lr be the learning rate, # and k the initial gradient squared accumulator value. # w = \dfrac{sign(-g)*lr*|g - l1*T|_{+}}{l2*T*lr + \sqrt{k+gg})} # For -0.1*3.0*(0.1 - 0)/(0 + sqrt(0.1 + 0.1*0.1)) = -0.904534 # similarly for others. self.assertAllCloseAccordingToType( np.array([-0.904534, -1.603567]), self.evaluate(var0)) self.assertAllCloseAccordingToType( np.array([-0.094821, -0.189358]), self.evaluate(var1)) def testAdagradDAwithoutRegularizationBasic2(self): for dtype in self.float_types: with self.session(), self.test_scope(): global_step = resource_variable_ops.ResourceVariable( 0, dtype=dtypes.int64) var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) opt = adagrad_da.AdagradDAOptimizer( 3.0, global_step, initial_gradient_squared_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0) update = opt.apply_gradients( zip([grads0, grads1], [var0, var1]), global_step=global_step) self.evaluate(variables.global_variables_initializer()) self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0)) self.assertAllCloseAccordingToType([4.0, 3.0], self.evaluate(var1)) # Run a step of AdagradDA update.run() self.assertAllCloseAccordingToType( np.array([-0.904534, -1.603567]), self.evaluate(var0)) self.assertAllCloseAccordingToType( np.array([-0.094821, -0.189358]), self.evaluate(var1)) def testAdagradDAWithL1(self): for dtype in self.float_types: with self.session(), self.test_scope(): global_step = resource_variable_ops.ResourceVariable( 0, dtype=dtypes.int64) var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) opt = adagrad_da.AdagradDAOptimizer( 3.0, global_step, initial_gradient_squared_accumulator_value=0.1, l1_regularization_strength=0.001, l2_regularization_strength=0.0) update = opt.apply_gradients( zip([grads0, grads1], [var0, var1]), global_step=global_step) self.evaluate(variables.global_variables_initializer()) self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0)) self.assertAllCloseAccordingToType([4.0, 3.0], self.evaluate(var1)) # Run a step of AdagradDA update.run() self.assertAllCloseAccordingToType( np.array([-0.895489, -1.59555]), self.evaluate(var0)) self.assertAllCloseAccordingToType( np.array([-0.085339, -0.17989]), self.evaluate(var1)) def testAdagradDAWithL1_L2(self): for dtype in self.float_types: with self.session(), self.test_scope(): global_step = resource_variable_ops.ResourceVariable( 0, dtype=dtypes.int64) var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) opt = adagrad_da.AdagradDAOptimizer( 3.0, global_step, initial_gradient_squared_accumulator_value=0.1, l1_regularization_strength=0.001, l2_regularization_strength=2.0) update = opt.apply_gradients( zip([grads0, grads1], [var0, var1]), global_step=global_step) self.evaluate(variables.global_variables_initializer()) self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0)) self.assertAllCloseAccordingToType([4.0, 3.0], self.evaluate(var1)) # Run a step of AdagradDA update.run() self.assertAllCloseAccordingToType( np.array([-0.046907, -0.093659]), self.evaluate(var0)) self.assertAllCloseAccordingToType( np.array([-0.004275, -0.009023]), self.evaluate(var1)) if __name__ == "__main__": test.main()
AdagradDAOptimizerTest
python
ijl__orjson
test/test_roundtrip.py
{ "start": 124, "end": 4018 }
class ____: def _run_roundtrip_json(self, filename): data = read_fixture_str(filename, "roundtrip") assert orjson.dumps(orjson.loads(data)) == data.encode("utf-8") def test_roundtrip001(self): """ roundtrip001.json """ self._run_roundtrip_json("roundtrip01.json") def test_roundtrip002(self): """ roundtrip002.json """ self._run_roundtrip_json("roundtrip02.json") def test_roundtrip003(self): """ roundtrip003.json """ self._run_roundtrip_json("roundtrip03.json") def test_roundtrip004(self): """ roundtrip004.json """ self._run_roundtrip_json("roundtrip04.json") def test_roundtrip005(self): """ roundtrip005.json """ self._run_roundtrip_json("roundtrip05.json") def test_roundtrip006(self): """ roundtrip006.json """ self._run_roundtrip_json("roundtrip06.json") def test_roundtrip007(self): """ roundtrip007.json """ self._run_roundtrip_json("roundtrip07.json") def test_roundtrip008(self): """ roundtrip008.json """ self._run_roundtrip_json("roundtrip08.json") def test_roundtrip009(self): """ roundtrip009.json """ self._run_roundtrip_json("roundtrip09.json") def test_roundtrip010(self): """ roundtrip010.json """ self._run_roundtrip_json("roundtrip10.json") def test_roundtrip011(self): """ roundtrip011.json """ self._run_roundtrip_json("roundtrip11.json") def test_roundtrip012(self): """ roundtrip012.json """ self._run_roundtrip_json("roundtrip12.json") def test_roundtrip013(self): """ roundtrip013.json """ self._run_roundtrip_json("roundtrip13.json") def test_roundtrip014(self): """ roundtrip014.json """ self._run_roundtrip_json("roundtrip14.json") def test_roundtrip015(self): """ roundtrip015.json """ self._run_roundtrip_json("roundtrip15.json") def test_roundtrip016(self): """ roundtrip016.json """ self._run_roundtrip_json("roundtrip16.json") def test_roundtrip017(self): """ roundtrip017.json """ self._run_roundtrip_json("roundtrip17.json") def test_roundtrip018(self): """ roundtrip018.json """ self._run_roundtrip_json("roundtrip18.json") def test_roundtrip019(self): """ roundtrip019.json """ self._run_roundtrip_json("roundtrip19.json") def test_roundtrip020(self): """ roundtrip020.json """ self._run_roundtrip_json("roundtrip20.json") def test_roundtrip021(self): """ roundtrip021.json """ self._run_roundtrip_json("roundtrip21.json") def test_roundtrip022(self): """ roundtrip022.json """ self._run_roundtrip_json("roundtrip22.json") def test_roundtrip023(self): """ roundtrip023.json """ self._run_roundtrip_json("roundtrip23.json") def test_roundtrip024(self): """ roundtrip024.json """ self._run_roundtrip_json("roundtrip24.json") def test_roundtrip025(self): """ roundtrip025.json """ self._run_roundtrip_json("roundtrip25.json") def test_roundtrip026(self): """ roundtrip026.json """ self._run_roundtrip_json("roundtrip26.json") def test_roundtrip027(self): """ roundtrip027.json """ self._run_roundtrip_json("roundtrip27.json")
TestJsonChecker
python
getsentry__sentry
tests/sentry/api/endpoints/test_organization_onboarding_tasks.py
{ "start": 217, "end": 4671 }
class ____(APITestCase): def setUp(self) -> None: self.user = self.create_user() self.member_user = self.create_user() self.org = self.create_organization(owner=self.user) self.create_member(organization=self.org, user=self.member_user) self.login_as(user=self.user) self.path = reverse("sentry-api-0-organization-onboardingtasks", args=[self.org.slug]) def test_mark_complete(self) -> None: response = self.client.post(self.path, {"task": "create_project", "status": "complete"}) assert response.status_code == 204, response.content task = OrganizationOnboardingTask.objects.get( organization=self.org, task=OnboardingTask.FIRST_PROJECT ) assert task.status == OnboardingTaskStatus.COMPLETE assert task.completion_seen is None assert task.user_id == self.user.id def test_mark_completion_seen(self) -> None: response = self.client.post(self.path, {"task": "create_project", "status": "complete"}) assert response.status_code == 204, response.content response = self.client.post(self.path, {"task": "create_project", "completionSeen": True}) assert response.status_code == 204, response.content task = OrganizationOnboardingTask.objects.get( organization=self.org, task=OnboardingTask.FIRST_PROJECT ) assert task.completion_seen is not None def test_mark_completion_seen_as_member(self) -> None: self.login_as(self.member_user) response = self.client.post(self.path, {"task": "create_project", "status": "complete"}) assert response.status_code == 204, response.content response = self.client.post(self.path, {"task": "create_project", "completionSeen": True}) assert response.status_code == 204, response.content task = OrganizationOnboardingTask.objects.get( organization=self.org, task=OnboardingTask.FIRST_PROJECT ) assert task.completion_seen is not None def test_cannot_skip_unskippable(self) -> None: response = self.client.post(self.path, {"task": "create_project", "status": "skipped"}) assert response.status_code == 422, response.content assert not OrganizationOnboardingTask.objects.filter( organization=self.org, task=OnboardingTask.FIRST_PROJECT ).exists() def test_invalid_status_key(self) -> None: response = self.client.post(self.path, {"task": "create_project", "status": "bad_status"}) assert response.status_code == 422, response.content assert response.data["detail"] == "Invalid status key" assert not OrganizationOnboardingTask.objects.filter( organization=self.org, task=OnboardingTask.FIRST_PROJECT ).exists() def test_invalid_task_key(self) -> None: response = self.client.post(self.path, {"task": "bad_key"}) assert response.status_code == 422, response.content assert response.data["detail"] == "Invalid task key" assert not OrganizationOnboardingTask.objects.filter( organization=self.org, task=OnboardingTask.FIRST_PROJECT ).exists() def test_missing_status_or_completion_seen(self) -> None: response = self.client.post(self.path, {"task": "create_project"}) assert response.status_code == 422, response.content assert response.data["detail"] == "completionSeen or status must be provided" assert not OrganizationOnboardingTask.objects.filter( organization=self.org, task=OnboardingTask.FIRST_PROJECT ).exists() def test_get_tasks(self) -> None: # create a task self.client.post(self.path, {"task": "create_project", "status": "complete"}) # get tasks response = self.client.get(self.path) assert response.status_code == 200, response.content # Verify that the response contains the 'onboardingTasks' key assert "onboardingTasks" in response.data tasks = response.data["onboardingTasks"] # Verify that the 'create_project' task is in the list of onboarding tasks create_project_task = next( (task for task in tasks if task["task"] == "create_project"), None ) assert create_project_task is not None assert create_project_task["status"] == "complete"
OrganizationOnboardingTaskEndpointTest
python
PrefectHQ__prefect
src/prefect/server/services/cancellation_cleanup.py
{ "start": 868, "end": 8078 }
class ____(LoopService): """ Cancels tasks and subflows of flow runs that have been cancelled """ @classmethod def service_settings(cls) -> ServicesBaseSetting: return get_current_settings().server.services.cancellation_cleanup def __init__(self, loop_seconds: Optional[float] = None, **kwargs: Any): super().__init__( loop_seconds=loop_seconds or PREFECT_API_SERVICES_CANCELLATION_CLEANUP_LOOP_SECONDS.value(), **kwargs, ) # query for this many runs to mark failed at once self.batch_size = 200 @db_injector async def run_once(self, db: PrefectDBInterface) -> None: """ - cancels active tasks belonging to recently cancelled flow runs - cancels any active subflow that belongs to a cancelled flow """ # cancels active tasks belonging to recently cancelled flow runs await self.clean_up_cancelled_flow_run_task_runs(db) # cancels any active subflow run that belongs to a cancelled flow run await self.clean_up_cancelled_subflow_runs(db) self.logger.info("Finished cleaning up cancelled flow runs.") async def clean_up_cancelled_flow_run_task_runs( self, db: PrefectDBInterface ) -> None: high_water_mark = UUID(int=0) while True: cancelled_flow_query = ( sa.select(db.FlowRun) .where( db.FlowRun.state_type == states.StateType.CANCELLED, db.FlowRun.end_time.is_not(None), db.FlowRun.end_time >= (now("UTC") - datetime.timedelta(days=1)), db.FlowRun.id > high_water_mark, ) .order_by(db.FlowRun.id) .limit(self.batch_size) ) async with db.session_context() as session: flow_run_result = await session.execute(cancelled_flow_query) flow_runs = flow_run_result.scalars().all() for run in flow_runs: await self._cancel_child_runs(db=db, flow_run=run) high_water_mark = run.id # if no relevant flows were found, exit the loop if len(flow_runs) < self.batch_size: break async def clean_up_cancelled_subflow_runs(self, db: PrefectDBInterface) -> None: high_water_mark = UUID(int=0) while True: # Performance optimization: Load only required columns while maintaining ORM functionality # Required columns: # - id: for high water mark tracking # - state_type: for state validation # - parent_task_run_id: for parent task run checks # - deployment_id: for determining cancellation state type subflow_query = ( sa.select(db.FlowRun) .options( sa.orm.load_only( db.FlowRun.id, db.FlowRun.state_type, db.FlowRun.parent_task_run_id, db.FlowRun.deployment_id, ), ) .where( or_( db.FlowRun.state_type == states.StateType.PENDING, db.FlowRun.state_type == states.StateType.SCHEDULED, db.FlowRun.state_type == states.StateType.RUNNING, db.FlowRun.state_type == states.StateType.PAUSED, db.FlowRun.state_type == states.StateType.CANCELLING, ), db.FlowRun.id > high_water_mark, db.FlowRun.parent_task_run_id.is_not(None), ) .order_by(db.FlowRun.id) .limit(self.batch_size) ) async with db.session_context() as session: subflow_run_result = await session.execute(subflow_query) subflow_runs = subflow_run_result.scalars().all() for subflow_run in subflow_runs: await self._cancel_subflow(db=db, flow_run=subflow_run) high_water_mark = max(high_water_mark, subflow_run.id) # if no relevant flows were found, exit the loop if len(subflow_runs) < self.batch_size: break async def _cancel_child_runs( self, db: PrefectDBInterface, flow_run: orm_models.FlowRun ) -> None: async with db.session_context() as session: child_task_runs = await models.task_runs.read_task_runs( session, flow_run_filter=filters.FlowRunFilter( id=filters.FlowRunFilterId(any_=[flow_run.id]) ), task_run_filter=filters.TaskRunFilter( state=filters.TaskRunFilterState( type=filters.TaskRunFilterStateType(any_=NON_TERMINAL_STATES) ) ), limit=100, ) for task_run in child_task_runs: async with db.session_context(begin_transaction=True) as session: await models.task_runs.set_task_run_state( session=session, task_run_id=task_run.id, state=states.Cancelled( message="The parent flow run was cancelled." ), force=True, ) async def _cancel_subflow( self, db: PrefectDBInterface, flow_run: orm_models.FlowRun ) -> Optional[bool]: if not flow_run.parent_task_run_id or not flow_run.state: return False if flow_run.state.type in states.TERMINAL_STATES: return False async with db.session_context() as session: parent_task_run = await models.task_runs.read_task_run( session, task_run_id=flow_run.parent_task_run_id ) if not parent_task_run or not parent_task_run.flow_run_id: # Global orchestration policy will prevent further orchestration return False containing_flow_run = await models.flow_runs.read_flow_run( session, flow_run_id=parent_task_run.flow_run_id ) if ( containing_flow_run and containing_flow_run.state and containing_flow_run.state.type != states.StateType.CANCELLED ): # Nothing to do here; the parent is not cancelled return False if flow_run.deployment_id: state = states.Cancelling(message="The parent flow run was cancelled.") else: state = states.Cancelled(message="The parent flow run was cancelled.") async with db.session_context(begin_transaction=True) as session: await models.flow_runs.set_flow_run_state( session=session, flow_run_id=flow_run.id, state=state, ) if __name__ == "__main__": asyncio.run(CancellationCleanup(handle_signals=True).start())
CancellationCleanup
python
pydata__xarray
xarray/backends/netCDF4_.py
{ "start": 12415, "end": 22099 }
class ____(WritableCFDataStore): """Store for reading and writing data via the Python-NetCDF4 library. This store supports NetCDF3, NetCDF4 and OpenDAP datasets. """ __slots__ = ( "_filename", "_group", "_manager", "_mode", "autoclose", "format", "is_remote", "lock", ) def __init__( self, manager, group=None, mode=None, lock=NETCDF4_PYTHON_LOCK, autoclose=False ): import netCDF4 if isinstance(manager, netCDF4.Dataset): if group is None: root, group = find_root_and_group(manager) else: if type(manager) is not netCDF4.Dataset: raise ValueError( "must supply a root netCDF4.Dataset if the group " "argument is provided" ) root = manager manager = DummyFileManager(root) self._manager = manager self._group = group self._mode = mode self.format = self.ds.data_model self._filename = self.ds.filepath() self.is_remote = is_remote_uri(self._filename) self.lock = ensure_lock(lock) self.autoclose = autoclose def get_child_store(self, group: str) -> Self: if self._group is not None: group = os.path.join(self._group, group) return type(self)( self._manager, group=group, mode=self._mode, lock=self.lock, autoclose=self.autoclose, ) @classmethod def open( cls, filename, mode="r", format="NETCDF4", group=None, clobber=True, diskless=False, persist=False, auto_complex=None, lock=None, lock_maker=None, autoclose=False, ): import netCDF4 if isinstance(filename, os.PathLike): filename = os.fspath(filename) if isinstance(filename, IOBase): raise TypeError( f"file objects are not supported by the netCDF4 backend: {filename}" ) if not isinstance(filename, str | bytes | memoryview | BytesIOProxy): raise TypeError(f"invalid filename for netCDF4 backend: {filename}") if format is None: format = "NETCDF4" if lock is None: if mode == "r": if isinstance(filename, str) and is_remote_uri(filename): lock = NETCDFC_LOCK else: lock = NETCDF4_PYTHON_LOCK else: if format is None or format.startswith("NETCDF4"): lock = NETCDF4_PYTHON_LOCK else: lock = NETCDFC_LOCK if isinstance(filename, str): lock = combine_locks([lock, get_write_lock(filename)]) kwargs = dict( clobber=clobber, diskless=diskless, persist=persist, format=format, ) if auto_complex is not None: kwargs["auto_complex"] = auto_complex if isinstance(filename, BytesIOProxy): assert mode == "w" # Size hint used for creating netCDF3 files. Per the documentation # for nc__create(), the special value NC_SIZEHINT_DEFAULT (which is # the value 0), lets the netcdf library choose a suitable initial # size. memory = 0 kwargs["diskless"] = False nc4_dataset = netCDF4.Dataset( "<xarray-in-memory-write>", mode=mode, memory=memory, **kwargs ) close = _CloseWithCopy(filename, nc4_dataset) manager = DummyFileManager(nc4_dataset, close=close) elif isinstance(filename, bytes | memoryview): assert mode == "r" kwargs["memory"] = filename manager = PickleableFileManager( netCDF4.Dataset, "<xarray-in-memory-read>", mode=mode, kwargs=kwargs ) else: manager = CachingFileManager( netCDF4.Dataset, filename, mode=mode, kwargs=kwargs ) return cls(manager, group=group, mode=mode, lock=lock, autoclose=autoclose) def _acquire(self, needs_lock=True): with self._manager.acquire_context(needs_lock) as root: ds = _nc4_require_group(root, self._group, self._mode) return ds @property def ds(self): return self._acquire() def open_store_variable(self, name: str, var): import netCDF4 dimensions = var.dimensions attributes = {k: var.getncattr(k) for k in var.ncattrs()} data = indexing.LazilyIndexedArray(NetCDF4ArrayWrapper(name, self)) encoding: dict[str, Any] = {} if isinstance(var.datatype, netCDF4.EnumType): encoding["dtype"] = np.dtype( data.dtype, metadata={ "enum": var.datatype.enum_dict, "enum_name": var.datatype.name, }, ) else: encoding["dtype"] = var.dtype _ensure_fill_value_valid(data, attributes) # netCDF4 specific encoding; save _FillValue for later filters = var.filters() if filters is not None: encoding.update(filters) chunking = var.chunking() if chunking is not None: if chunking == "contiguous": encoding["contiguous"] = True encoding["chunksizes"] = None else: encoding["contiguous"] = False encoding["chunksizes"] = tuple(chunking) encoding["preferred_chunks"] = dict( zip(var.dimensions, chunking, strict=True) ) # TODO: figure out how to round-trip "endian-ness" without raising # warnings from netCDF4 # encoding['endian'] = var.endian() pop_to(attributes, encoding, "least_significant_digit") # save source so __repr__ can detect if it's local or not encoding["source"] = self._filename encoding["original_shape"] = data.shape return Variable(dimensions, data, attributes, encoding) def get_variables(self): return FrozenDict( (k, self.open_store_variable(k, v)) for k, v in self.ds.variables.items() ) def get_attrs(self): return FrozenDict((k, self.ds.getncattr(k)) for k in self.ds.ncattrs()) def get_dimensions(self): return FrozenDict((k, len(v)) for k, v in self.ds.dimensions.items()) def get_parent_dimensions(self): return FrozenDict(collect_ancestor_dimensions(self.ds)) def get_encoding(self): return { "unlimited_dims": { k for k, v in self.ds.dimensions.items() if v.isunlimited() } } def set_dimension(self, name, length, is_unlimited=False): _ensure_no_forward_slash_in_name(name) dim_length = length if not is_unlimited else None self.ds.createDimension(name, size=dim_length) def set_attribute(self, key, value): if self.format != "NETCDF4": value = encode_nc3_attr_value(value) if _is_list_of_strings(value): # encode as NC_STRING if attr is list of strings self.ds.setncattr_string(key, value) else: self.ds.setncattr(key, value) def encode_variable(self, variable, name=None): variable = _force_native_endianness(variable) if self.format == "NETCDF4": variable = _encode_nc4_variable(variable, name=name) else: variable = encode_nc3_variable(variable, name=name) return variable def prepare_variable( self, name, variable: Variable, check_encoding=False, unlimited_dims=None ): _ensure_no_forward_slash_in_name(name) attrs = variable.attrs.copy() fill_value = attrs.pop("_FillValue", None) datatype: np.dtype | ncEnumType | h5EnumType datatype = _get_datatype( variable, self.format, raise_on_invalid_encoding=check_encoding ) # check enum metadata and use netCDF4.EnumType if ( (meta := np.dtype(datatype).metadata) and (e_name := meta.get("enum_name")) and (e_dict := meta.get("enum")) ): datatype = _build_and_get_enum(self, name, datatype, e_name, e_dict) encoding = _extract_nc4_variable_encoding( variable, raise_on_invalid=check_encoding, unlimited_dims=unlimited_dims ) if name in self.ds.variables: nc4_var = self.ds.variables[name] else: default_args = dict( varname=name, datatype=datatype, dimensions=variable.dims, zlib=False, complevel=4, shuffle=True, fletcher32=False, contiguous=False, chunksizes=None, endian="native", least_significant_digit=None, fill_value=fill_value, ) default_args.update(encoding) default_args.pop("_FillValue", None) nc4_var = self.ds.createVariable(**default_args) nc4_var.setncatts(attrs) target = NetCDF4ArrayWrapper(name, self) return target, variable.data def sync(self): self.ds.sync() def close(self, **kwargs): self._manager.close(**kwargs)
NetCDF4DataStore
python
Textualize__textual
src/textual/widgets/_header.py
{ "start": 418, "end": 1334 }
class ____(Widget): """Display an 'icon' on the left of the header.""" DEFAULT_CSS = """ HeaderIcon { dock: left; padding: 0 1; width: 8; content-align: left middle; } HeaderIcon:hover { background: $foreground 10%; } """ icon = Reactive("⭘") """The character to use as the icon within the header.""" def on_mount(self) -> None: if self.app.ENABLE_COMMAND_PALETTE: self.tooltip = "Open the command palette" else: self.disabled = True async def on_click(self, event: Click) -> None: """Launch the command palette when icon is clicked.""" event.stop() await self.run_action("app.command_palette") def render(self) -> RenderResult: """Render the header icon. Returns: The rendered icon. """ return self.icon
HeaderIcon
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/base.py
{ "start": 25012, "end": 25406 }
class ____(HasMemoized): """Provide a method-chaining pattern in conjunction with the @_generative decorator that mutates in place.""" __slots__ = () def _generate(self) -> Self: skip = self._memoized_keys # note __dict__ needs to be in __slots__ if this is used for k in skip: self.__dict__.pop(k, None) return self
InPlaceGenerative
python
readthedocs__readthedocs.org
readthedocs/organizations/views/base.py
{ "start": 840, "end": 1353 }
class ____: """ Return 404 if organizations aren't enabled. All organization views should inherit this class. This is mainly for our tests to work, adding the organization urls conditionally on readthedocs/urls.py doesn't work as the file is evaluated only once, not per-test case. """ def dispatch(self, *args, **kwargs): if not settings.RTD_ALLOW_ORGANIZATIONS: raise Http404 return super().dispatch(*args, **kwargs) # Mixins
CheckOrganizationsEnabled
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0068_migrate_anomaly_detection_alerts.py
{ "start": 3950, "end": 4657 }
class ____: """ SentryAppFormConfigDataBlob represents a single form config field for a Sentry App. name is the name of the form field, and value is the value of the form field. """ @classmethod def from_dict(cls, data: dict[str, Any]) -> "SentryAppFormConfigDataBlob": if not isinstance(data.get("name"), str) or not isinstance( data.get("value"), (str, type(None)) ): raise ValueError("Sentry app config must contain name and value keys") return cls(name=data["name"], value=data["value"], label=data.get("label")) name: str = "" value: str = "" label: str | None = None @dataclasses.dataclass
SentryAppFormConfigDataBlob
python
django__django
tests/staticfiles_tests/cases.py
{ "start": 3129, "end": 4553 }
class ____: """ A few standard test cases. """ def test_staticfiles_dirs(self): """ Can find a file in a STATICFILES_DIRS directory. """ self.assertFileContains("test.txt", "Can we find") self.assertFileContains(os.path.join("prefix", "test.txt"), "Prefix") def test_staticfiles_dirs_subdir(self): """ Can find a file in a subdirectory of a STATICFILES_DIRS directory. """ self.assertFileContains("subdir/test.txt", "Can we find") def test_staticfiles_dirs_priority(self): """ File in STATICFILES_DIRS has priority over file in app. """ self.assertFileContains("test/file.txt", "STATICFILES_DIRS") def test_app_files(self): """ Can find a file in an app static/ directory. """ self.assertFileContains("test/file1.txt", "file1 in the app dir") def test_nonascii_filenames(self): """ Can find a file with non-ASCII character in an app static/ directory. """ self.assertFileContains("test/⊗.txt", "⊗ in the app dir") def test_camelcase_filenames(self): """ Can find a file with capital letters. """ self.assertFileContains("test/camelCase.txt", "camelCase") def test_filename_with_percent_sign(self): self.assertFileContains("test/%2F.txt", "%2F content")
TestDefaults
python
google__pytype
pytype/tests/test_methods2.py
{ "start": 94, "end": 3457 }
class ____(test_base.BaseTest): """Tests for class methods.""" def test_function_init(self): ty = self.Infer(""" def __init__(self: int): return self """) self.assertTypesMatchPytd( ty, """ def __init__(self: int) -> int: ... """, ) def test_annotated_self(self): errors = self.CheckWithErrors(""" class Foo: def __init__(x: int): pass # invalid-annotation[e] """) self.assertErrorRegexes(errors, {"e": r"int.*x"}) def test_late_annotated_self(self): errors = self.CheckWithErrors(""" class Foo: def __init__(x: "X"): pass # invalid-annotation[e] class X: pass """) self.assertErrorRegexes(errors, {"e": r"X.*x"}) def test_attribute_with_annotated_self(self): errors = self.CheckWithErrors(""" class Foo: def __init__(self: int): self.x = 3 # invalid-annotation[e] def foo(self): return self.x """) self.assertErrorRegexes(errors, {"e": r"int.*self"}) def test_attribute_with_annotated_self_and_function_init(self): errors = self.CheckWithErrors(""" class Foo: def __init__(self: int): self.x = 3 # invalid-annotation[e] def __init__(self: int): pass """) self.assertErrorRegexes(errors, {"e": r"int.*self"}) def test_use_abstract_classmethod(self): with test_utils.Tempdir() as d: d.create_file( "foo.pyi", """ import abc class Foo(metaclass=abc.ABCMeta): @abc.abstractmethod @classmethod def foo(cls, value) -> int: ... """, ) self.Check( """ import collections import foo class Bar: def __init__(self, **kwargs): for k, v in self.f().items(): v.foo(kwargs[k]) def f(self) -> collections.OrderedDict[str, foo.Foo]: return __any_object__ """, pythonpath=[d.path], ) def test_max_depth(self): # pytype hits max depth in A.cmp() when trying to instantiate `other`, # leading to the FromInt() call in __init__ being skipped and pytype # thinking that other.x is an int. If max depth is raised, pytype correctly # sees that self.x will be a str, and no error is raised. self.CheckWithErrors( """ from typing import Any, Union class A: def __init__(self, x: int): self.x = 1 self.FromInt(x) def cmp(self, other: 'A') -> bool: return self.Upper() < other.Upper() def FromInt(self, x: int) -> None: self.x = 'x' def Upper(self) -> str: return self.x.upper() # attribute-error """, maximum_depth=2, ) def test_call_dispatch(self): self.Check(""" from typing import Union class Foo: def __call__(self): pass class Bar: def __call__(self, x): pass def f(x: Union[Foo, Bar]): if isinstance(x, Foo): return x() """) def test_lookup_on_dynamic_class(self): self.Check(""" class Foo: _HAS_DYNAMIC_ATTRIBUTES = True def f(self) -> str: return '' def g(self): assert_type(self.f(), str) """)
TestMethods
python
jazzband__django-waffle
waffle/models.py
{ "start": 15406, "end": 17509 }
class ____(BaseModel): """A sample of users. A sample is true some percentage of the time, but is not connected to users or requests. """ name = models.CharField( max_length=100, unique=True, help_text=_('The human/computer readable name.'), verbose_name=_('Name'), ) percent = models.DecimalField( max_digits=4, decimal_places=1, help_text=_('A number between 0.0 and 100.0 to indicate a percentage of the time ' 'this sample will be active.'), verbose_name=_('Percent'), ) note = models.TextField( blank=True, help_text=_('Note where this Sample is used.'), verbose_name=_('Note'), ) created = models.DateTimeField( default=timezone.now, db_index=True, help_text=_('Date when this Sample was created.'), verbose_name=_('Created'), ) modified = models.DateTimeField( default=timezone.now, help_text=_('Date when this Sample was last modified.'), verbose_name=_('Modified'), ) objects = managers.SampleManager() SINGLE_CACHE_KEY = 'SAMPLE_CACHE_KEY' ALL_CACHE_KEY = 'ALL_SAMPLES_CACHE_KEY' class Meta: abstract = True verbose_name = _('Sample') verbose_name_plural = _('Samples') def is_active(self) -> bool: if not self.pk: log_level = get_setting('LOG_MISSING_SAMPLES') if log_level: logger.log(log_level, 'Sample %s not found', self.name) if get_setting('CREATE_MISSING_SAMPLES'): default_percent = 100 if get_setting('SAMPLE_DEFAULT') else 0 sample, _created = get_waffle_sample_model().objects.get_or_create( name=self.name, defaults={"percent": default_percent} ) cache = get_cache() cache.set(self._cache_key(self.name), sample) return get_setting('SAMPLE_DEFAULT') return Decimal(str(random.uniform(0, 100))) <= self.percent
AbstractBaseSample
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_simplify/SIM115.py
{ "start": 1178, "end": 5750 }
class ____: def __init__(self, filename: str): self.filename = filename def __enter__(self): self.file = open(self.filename) def __exit__(self, exc_type, exc_val, exc_tb): self.file.close() import tempfile import tarfile from tarfile import TarFile import zipfile import io import codecs import bz2 import gzip import dbm import dbm.gnu import dbm.ndbm import dbm.dumb import lzma import shelve import tokenize import wave import fileinput f = tempfile.NamedTemporaryFile() f = tempfile.TemporaryFile() f = tempfile.SpooledTemporaryFile() f = tarfile.open("foo.tar") f = TarFile("foo.tar").open() f = tarfile.TarFile("foo.tar").open() f = tarfile.TarFile().open() f = zipfile.ZipFile("foo.zip").open("foo.txt") f = io.open("foo.txt") f = io.open_code("foo.txt") f = codecs.open("foo.txt") f = bz2.open("foo.txt") f = gzip.open("foo.txt") f = dbm.open("foo.db") f = dbm.gnu.open("foo.db") f = dbm.ndbm.open("foo.db") f = dbm.dumb.open("foo.db") f = lzma.open("foo.xz") f = lzma.LZMAFile("foo.xz") f = shelve.open("foo.db") f = tokenize.open("foo.py") f = wave.open("foo.wav") f = tarfile.TarFile.taropen("foo.tar") f = fileinput.input("foo.txt") f = fileinput.FileInput("foo.txt") with contextlib.suppress(Exception): # The following line is for example's sake. # For some f's above, this would raise an error (since it'd be f.readline() etc.) data = f.read() f.close() # OK with tempfile.TemporaryFile() as f: data = f.read() # OK with tarfile.open("foo.tar") as f: data = f.add("foo.txt") # OK with tarfile.TarFile("foo.tar") as f: data = f.add("foo.txt") # OK with tarfile.TarFile("foo.tar").open() as f: data = f.add("foo.txt") # OK with zipfile.ZipFile("foo.zip") as f: data = f.read("foo.txt") # OK with zipfile.ZipFile("foo.zip").open("foo.txt") as f: data = f.read() # OK with zipfile.ZipFile("foo.zip") as zf: with zf.open("foo.txt") as f: data = f.read() # OK with io.open("foo.txt") as f: data = f.read() # OK with io.open_code("foo.txt") as f: data = f.read() # OK with codecs.open("foo.txt") as f: data = f.read() # OK with bz2.open("foo.txt") as f: data = f.read() # OK with gzip.open("foo.txt") as f: data = f.read() # OK with dbm.open("foo.db") as f: data = f.get("foo") # OK with dbm.gnu.open("foo.db") as f: data = f.get("foo") # OK with dbm.ndbm.open("foo.db") as f: data = f.get("foo") # OK with dbm.dumb.open("foo.db") as f: data = f.get("foo") # OK with lzma.open("foo.xz") as f: data = f.read() # OK with lzma.LZMAFile("foo.xz") as f: data = f.read() # OK with shelve.open("foo.db") as f: data = f["foo"] # OK with tokenize.open("foo.py") as f: data = f.read() # OK with wave.open("foo.wav") as f: data = f.readframes(1024) # OK with tarfile.TarFile.taropen("foo.tar") as f: data = f.add("foo.txt") # OK with fileinput.input("foo.txt") as f: data = f.readline() # OK with fileinput.FileInput("foo.txt") as f: data = f.readline() # OK (quick one-liner to clear file contents) tempfile.NamedTemporaryFile().close() tempfile.TemporaryFile().close() tempfile.SpooledTemporaryFile().close() tarfile.open("foo.tar").close() tarfile.TarFile("foo.tar").close() tarfile.TarFile("foo.tar").open().close() tarfile.TarFile.open("foo.tar").close() zipfile.ZipFile("foo.zip").close() zipfile.ZipFile("foo.zip").open("foo.txt").close() io.open("foo.txt").close() io.open_code("foo.txt").close() codecs.open("foo.txt").close() bz2.open("foo.txt").close() gzip.open("foo.txt").close() dbm.open("foo.db").close() dbm.gnu.open("foo.db").close() dbm.ndbm.open("foo.db").close() dbm.dumb.open("foo.db").close() lzma.open("foo.xz").close() lzma.LZMAFile("foo.xz").close() shelve.open("foo.db").close() tokenize.open("foo.py").close() wave.open("foo.wav").close() tarfile.TarFile.taropen("foo.tar").close() fileinput.input("foo.txt").close() fileinput.FileInput("foo.txt").close() def aliased(): from shelve import open as open_shelf x = open_shelf("foo.dbm") x.close() from tarfile import TarFile as TF f = TF("foo").open() f.close() import dbm.sqlite3 # OK with dbm.sqlite3.open("foo.db") as f: print(f.keys()) # OK dbm.sqlite3.open("foo.db").close() # SIM115 f = dbm.sqlite3.open("foo.db") f.close() # OK def func(filepath, encoding): return open(filepath, mode="rt", encoding=encoding) # OK def func(filepath, encoding): return f(open(filepath, mode="rt", encoding=encoding)) from unittest import IsolatedAsyncioTestCase, TestCase # OK
MyFile
python
django__django
django/contrib/gis/utils/layermapping.py
{ "start": 1268, "end": 29092 }
class ____: "A class that maps OGR Layers to GeoDjango Models." # Acceptable 'base' types for a multi-geometry type. MULTI_TYPES = { 1: OGRGeomType("MultiPoint"), 2: OGRGeomType("MultiLineString"), 3: OGRGeomType("MultiPolygon"), OGRGeomType("Point25D").num: OGRGeomType("MultiPoint25D"), OGRGeomType("LineString25D").num: OGRGeomType("MultiLineString25D"), OGRGeomType("Polygon25D").num: OGRGeomType("MultiPolygon25D"), } # Acceptable Django field types and corresponding acceptable OGR # counterparts. FIELD_TYPES = { models.AutoField: OFTInteger, models.BigAutoField: OFTInteger64, models.SmallAutoField: OFTInteger, models.BooleanField: (OFTInteger, OFTReal, OFTString), models.IntegerField: (OFTInteger, OFTReal, OFTString), models.FloatField: (OFTInteger, OFTReal), models.DateField: OFTDate, models.DateTimeField: OFTDateTime, models.EmailField: OFTString, models.TimeField: OFTTime, models.DecimalField: (OFTInteger, OFTReal), models.CharField: OFTString, models.SlugField: OFTString, models.TextField: OFTString, models.URLField: OFTString, models.UUIDField: OFTString, models.BigIntegerField: (OFTInteger, OFTReal, OFTString), models.SmallIntegerField: (OFTInteger, OFTReal, OFTString), models.PositiveBigIntegerField: (OFTInteger, OFTReal, OFTString), models.PositiveIntegerField: (OFTInteger, OFTReal, OFTString), models.PositiveSmallIntegerField: (OFTInteger, OFTReal, OFTString), } def __init__( self, model, data, mapping, layer=0, source_srs=None, encoding="utf-8", transaction_mode="commit_on_success", transform=True, unique=None, using=None, ): """ A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage. """ # Getting the DataSource and the associated Layer. if isinstance(data, (str, Path)): self.ds = DataSource(data, encoding=encoding) else: self.ds = data self.layer = self.ds[layer] self.using = using if using is not None else router.db_for_write(model) connection = connections[self.using] self.spatial_backend = connection.ops # Setting the mapping & model attributes. self.mapping = mapping self.model = model # Checking the layer -- initialization of the object will fail if # things don't check out before hand. self.check_layer() # Getting the geometry column associated with the model (an # exception will be raised if there is no geometry column). if connection.features.supports_transform: self.geo_field = self.geometry_field() else: transform = False # Checking the source spatial reference system, and getting # the coordinate transformation object (unless the `transform` # keyword is set to False) if transform: self.source_srs = self.check_srs(source_srs) self.transform = self.coord_transform() else: self.transform = transform # Setting the encoding for OFTString fields, if specified. if encoding: # Making sure the encoding exists, if not a LookupError # exception will be thrown. from codecs import lookup lookup(encoding) self.encoding = encoding else: self.encoding = None if unique: self.check_unique(unique) transaction_mode = "autocommit" # Has to be set to autocommit. self.unique = unique else: self.unique = None # Setting the transaction decorator with the function in the # transaction modes dictionary. self.transaction_mode = transaction_mode if transaction_mode == "autocommit": self.transaction_decorator = None elif transaction_mode == "commit_on_success": self.transaction_decorator = transaction.atomic else: raise LayerMapError("Unrecognized transaction mode: %s" % transaction_mode) # Checking routines used during initialization. def check_fid_range(self, fid_range): "Check the `fid_range` keyword." if fid_range: if isinstance(fid_range, (tuple, list)): return slice(*fid_range) elif isinstance(fid_range, slice): return fid_range else: raise TypeError else: return None def check_layer(self): """ Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer. """ # The geometry field of the model is set here. # TODO: Support more than one geometry field / model. However, this # depends on the GDAL Driver in use. self.geom_field = False self.fields = {} # Getting lists of the field names and the field types available in # the OGR Layer. ogr_fields = self.layer.fields ogr_field_types = self.layer.field_types # Function for determining if the OGR mapping field is in the Layer. def check_ogr_fld(ogr_map_fld): try: idx = ogr_fields.index(ogr_map_fld) except ValueError: raise LayerMapError( 'Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld ) return idx # No need to increment through each feature in the model, simply check # the Layer metadata against what was given in the mapping dictionary. for field_name, ogr_name in self.mapping.items(): # Ensuring that a corresponding field exists in the model # for the given field name in the mapping. try: model_field = self.model._meta.get_field(field_name) except FieldDoesNotExist: raise LayerMapError( 'Given mapping field "%s" not in given Model fields.' % field_name ) # Getting the string name for the Django field class (e.g., # 'PointField'). fld_name = model_field.__class__.__name__ if isinstance(model_field, GeometryField): if self.geom_field: raise LayerMapError( "LayerMapping does not support more than one GeometryField per " "model." ) # Getting the coordinate dimension of the geometry field. coord_dim = model_field.dim try: if coord_dim == 3: gtype = OGRGeomType(ogr_name + "25D") else: gtype = OGRGeomType(ogr_name) except GDALException: raise LayerMapError( 'Invalid mapping for GeometryField "%s".' % field_name ) # Making sure that the OGR Layer's Geometry is compatible. ltype = self.layer.geom_type if not ( ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field) ): raise LayerMapError( "Invalid mapping geometry; model has %s%s, " "layer geometry type is %s." % (fld_name, "(dim=3)" if coord_dim == 3 else "", ltype) ) # Setting the `geom_field` attribute w/the name of the model # field that is a Geometry. Also setting the coordinate # dimension attribute. self.geom_field = field_name self.coord_dim = coord_dim fields_val = model_field elif isinstance(model_field, models.ForeignKey): if isinstance(ogr_name, dict): # Is every given related model mapping field in the Layer? rel_model = model_field.remote_field.model for rel_name, ogr_field in ogr_name.items(): idx = check_ogr_fld(ogr_field) try: rel_model._meta.get_field(rel_name) except FieldDoesNotExist: raise LayerMapError( 'ForeignKey mapping field "%s" not in %s fields.' % (rel_name, rel_model.__class__.__name__) ) fields_val = rel_model else: raise TypeError("ForeignKey mapping must be of dictionary type.") else: # Is the model field type supported by LayerMapping? if model_field.__class__ not in self.FIELD_TYPES: raise LayerMapError( 'Django field type "%s" has no OGR mapping (yet).' % fld_name ) # Is the OGR field in the Layer? idx = check_ogr_fld(ogr_name) ogr_field = ogr_field_types[idx] # Can the OGR field type be mapped to the Django field type? if not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__]): raise LayerMapError( 'OGR field "%s" (of type %s) cannot be mapped to Django %s.' % (ogr_field, ogr_field.__name__, fld_name) ) fields_val = model_field self.fields[field_name] = fields_val def check_srs(self, source_srs): "Check the compatibility of the given spatial reference object." if isinstance(source_srs, SpatialReference): sr = source_srs elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()): sr = source_srs.srs elif isinstance(source_srs, (int, str)): sr = SpatialReference(source_srs) else: # Otherwise just pulling the SpatialReference from the layer sr = self.layer.srs if not sr: raise LayerMapError("No source reference system defined.") else: return sr def check_unique(self, unique): "Check the `unique` keyword parameter -- may be a sequence or string." if isinstance(unique, (list, tuple)): # List of fields to determine uniqueness with for attr in unique: if attr not in self.mapping: raise ValueError elif isinstance(unique, str): # Only a single field passed in. if unique not in self.mapping: raise ValueError else: raise TypeError( "Unique keyword argument must be set with a tuple, list, or string." ) # Keyword argument retrieval routines. def feature_kwargs(self, feat): """ Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model. """ # The keyword arguments for model construction. kwargs = {} # Incrementing through each model field and OGR field in the # dictionary mapping. for field_name, ogr_name in self.mapping.items(): model_field = self.fields[field_name] if isinstance(model_field, GeometryField): # Verify OGR geometry. try: val = self.verify_geom(feat.geom, model_field) except GDALException: raise LayerMapError("Could not retrieve geometry from feature.") elif isinstance(model_field, models.base.ModelBase): # The related _model_, not a field was passed in -- indicating # another mapping for the related Model. val = self.verify_fk(feat, model_field, ogr_name) else: # Otherwise, verify OGR Field type. val = self.verify_ogr_field(feat[ogr_name], model_field) # Setting the keyword arguments for the field name with the # value obtained above. kwargs[field_name] = val return kwargs def unique_kwargs(self, kwargs): """ Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs. """ if isinstance(self.unique, str): return {self.unique: kwargs[self.unique]} else: return {fld: kwargs[fld] for fld in self.unique} # Verification routines used in constructing model keyword arguments. def verify_ogr_field(self, ogr_field, model_field): """ Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception. """ if isinstance(ogr_field, OFTString) and isinstance( model_field, (models.CharField, models.TextField) ): if self.encoding and ogr_field.value is not None: # The encoding for OGR data sources may be specified here # (e.g., 'cp437' for Census Bureau boundary files). val = force_str(ogr_field.value, self.encoding) else: val = ogr_field.value if ( model_field.max_length and val is not None and len(val) > model_field.max_length ): raise InvalidString( "%s model field maximum string length is %s, given %s characters." % (model_field.name, model_field.max_length, len(val)) ) elif isinstance(ogr_field, OFTReal) and isinstance( model_field, models.DecimalField ): try: # Creating an instance of the Decimal value to use. d = Decimal(str(ogr_field.value)) except DecimalInvalidOperation: raise InvalidDecimal( "Could not construct decimal from: %s" % ogr_field.value ) # Getting the decimal value as a tuple. dtup = d.as_tuple() digits = dtup[1] d_idx = dtup[2] # index where the decimal is # Maximum amount of precision, or digits to the left of the # decimal. max_prec = model_field.max_digits - model_field.decimal_places # Getting the digits to the left of the decimal place for the # given decimal. if d_idx < 0: n_prec = len(digits[:d_idx]) else: n_prec = len(digits) + d_idx # If we have more than the maximum digits allowed, then throw an # InvalidDecimal exception. if n_prec > max_prec: raise InvalidDecimal( "A DecimalField with max_digits %d, decimal_places %d must " "round to an absolute value less than 10^%d." % (model_field.max_digits, model_field.decimal_places, max_prec) ) val = d elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance( model_field, models.IntegerField ): # Attempt to convert any OFTReal and OFTString value to an # OFTInteger. try: val = int(ogr_field.value) except ValueError: raise InvalidInteger( "Could not construct integer from: %s" % ogr_field.value ) else: val = ogr_field.value return val def verify_fk(self, feat, rel_model, rel_mapping): """ Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping. """ # TODO: It is expensive to retrieve a model for every record -- # explore if an efficient mechanism exists for caching related # ForeignKey models. # Constructing and verifying the related model keyword arguments. fk_kwargs = {} for field_name, ogr_name in rel_mapping.items(): fk_kwargs[field_name] = self.verify_ogr_field( feat[ogr_name], rel_model._meta.get_field(field_name) ) # Attempting to retrieve and return the related model. try: return rel_model.objects.using(self.using).get(**fk_kwargs) except ObjectDoesNotExist: raise MissingForeignKey( "No ForeignKey %s model found with keyword arguments: %s" % (rel_model.__name__, fk_kwargs) ) def verify_geom(self, geom, model_field): """ Verify the geometry -- construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons). """ # Measured geometries are not yet supported by GeoDjango models. if geom.is_measured: geom.set_measured(False) # Downgrade a 3D geom to a 2D one, if necessary. if self.coord_dim == 2 and geom.is_3d: geom.set_3d(False) if self.make_multi(geom.geom_type, model_field): # Constructing a multi-geometry type to contain the single geometry multi_type = self.MULTI_TYPES[geom.geom_type.num] g = OGRGeometry(multi_type) g.add(geom) else: g = geom # Transforming the geometry with our Coordinate Transformation object, # but only if the class variable `transform` is set w/a CoordTransform # object. if self.transform: g.transform(self.transform) # Returning the WKT of the geometry. return g.wkt # Other model methods. def coord_transform(self): "Return the coordinate transformation object." SpatialRefSys = self.spatial_backend.spatial_ref_sys() try: # Getting the target spatial reference system target_srs = ( SpatialRefSys.objects.using(self.using) .get(srid=self.geo_field.srid) .srs ) # Creating the CoordTransform object return CoordTransform(self.source_srs, target_srs) except Exception as exc: raise LayerMapError( "Could not translate between the data source and model geometry." ) from exc def geometry_field(self): """ Return the GeometryField instance associated with the geographic column. """ # Use `get_field()` on the model's options so that we # get the correct field instance if there's model inheritance. opts = self.model._meta return opts.get_field(self.geom_field) def make_multi(self, geom_type, model_field): """ Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection. """ return ( geom_type.num in self.MULTI_TYPES and model_field.__class__.__name__ == "Multi%s" % geom_type.django ) def save( self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False, ): """ Save the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters: verbose: If set, information will be printed subsequent to each model save executed on the database. fid_range: May be set with a slice or tuple of (begin, end) feature ID's to map from the data source. In other words, this keyword enables the user to selectively import a subset range of features in the geographic data source. step: If set with an integer, transactions will occur at every step interval. For example, if step=1000, a commit would occur after the 1,000th feature, the 2,000th feature etc. progress: When this keyword is set, status information will be printed giving the number of features processed and successfully saved. By default, progress information will pe printed every 1000 features processed, however, this default may be overridden by setting this keyword with an integer for the desired interval. stream: Status information will be written to this file handle. Defaults to using `sys.stdout`, but any object with a `write` method is supported. silent: By default, non-fatal error notifications are printed to stdout, but this keyword may be set to disable these notifications. strict: Execution of the model mapping will cease upon the first error encountered. The default behavior is to attempt to continue. """ # Getting the default Feature ID range. default_range = self.check_fid_range(fid_range) # Setting the progress interval, if requested. if progress: if progress is True or not isinstance(progress, int): progress_interval = 1000 else: progress_interval = progress def _save(feat_range=default_range, num_feat=0, num_saved=0): if feat_range: layer_iter = self.layer[feat_range] else: layer_iter = self.layer for feat in layer_iter: num_feat += 1 # Getting the keyword arguments try: kwargs = self.feature_kwargs(feat) except LayerMapError as msg: # Something borked the validation if strict: raise elif not silent: stream.write( "Ignoring Feature ID %s because: %s\n" % (feat.fid, msg) ) else: # Constructing the model using the keyword args is_update = False if self.unique: # If we want unique models on a particular field, # handle the geometry appropriately. try: # Getting the keyword arguments and retrieving # the unique model. u_kwargs = self.unique_kwargs(kwargs) m = self.model.objects.using(self.using).get(**u_kwargs) is_update = True # Getting the geometry (in OGR form), creating # one from the kwargs WKT, adding in additional # geometries, and update the attribute with the # just-updated geometry WKT. geom_value = getattr(m, self.geom_field) if geom_value is None: geom = OGRGeometry(kwargs[self.geom_field]) else: geom = geom_value.ogr new = OGRGeometry(kwargs[self.geom_field]) for g in new: geom.add(g) setattr(m, self.geom_field, geom.wkt) except ObjectDoesNotExist: # No unique model exists yet, create. m = self.model(**kwargs) else: m = self.model(**kwargs) try: # Attempting to save. m.save(using=self.using) num_saved += 1 if verbose: stream.write( "%s: %s\n" % ("Updated" if is_update else "Saved", m) ) except Exception as msg: if strict: # Bailing out if the `strict` keyword is set. if not silent: stream.write( "Failed to save the feature (id: %s) into the " "model with the keyword arguments:\n" % feat.fid ) stream.write("%s\n" % kwargs) raise elif not silent: stream.write( "Failed to save %s:\n %s\nContinuing\n" % (kwargs, msg) ) # Printing progress information, if requested. if progress and num_feat % progress_interval == 0: stream.write( "Processed %d features, saved %d ...\n" % (num_feat, num_saved) ) # Only used for status output purposes -- incremental saving uses # the values returned here. return num_saved, num_feat if self.transaction_decorator is not None: _save = self.transaction_decorator(_save) nfeat = self.layer.num_feat if step and isinstance(step, int) and step < nfeat: # Incremental saving is requested at the given interval (step) if default_range: raise LayerMapError( "The `step` keyword may not be used in conjunction with the " "`fid_range` keyword." ) beg, num_feat, num_saved = (0, 0, 0) indices = range(step, nfeat, step) n_i = len(indices) for i, end in enumerate(indices): # Constructing the slice to use for this step; the last slice # is special (e.g, [100:] instead of [90:100]). if i + 1 == n_i: step_slice = slice(beg, None) else: step_slice = slice(beg, end) try: num_feat, num_saved = _save(step_slice, num_feat, num_saved) beg = end except Exception: # Deliberately catch everything stream.write( "%s\nFailed to save slice: %s\n" % ("=-" * 20, step_slice) ) raise else: # Otherwise, just calling the previously defined _save() function. _save()
LayerMapping
python
facebook__pyre-check
client/configuration/scheduler_policies.py
{ "start": 5349, "end": 6473 }
class ____: policies: Dict[str, SchedulerPolicy] = dataclasses.field(default_factory=dict) @staticmethod def from_json(value: object) -> "SchedulerPolicies": if not isinstance(value, dict): raise InvalidConfiguration( f"Expected object for scheduler policies, but got `{type(value).__name__}`" ) return SchedulerPolicies( policies={ name: SchedulerPolicy.from_json(policy, name) for name, policy in value.items() } ) @staticmethod def from_path(path: Path) -> "SchedulerPolicies": with open(path, "r") as f: try: return SchedulerPolicies.from_json(json.load(f)) except json.JSONDecodeError as error: raise InvalidConfiguration( f"Error while parsing `{str(path)}`: {error.lineno}:{error.colno}: {error.msg}" ) from error def to_json(self) -> Dict[str, Dict[str, Union[int, str]]]: return {name: policy.to_json() for name, policy in self.policies.items()}
SchedulerPolicies
python
keras-team__keras
keras/src/ops/node.py
{ "start": 4214, "end": 5583 }
class ____( collections.namedtuple( "KerasHistory", ["operation", "node_index", "tensor_index"] ) ): """Tracks the Operation call that created a Tensor. During construction of Keras Functions, this metadata is added to each Tensor produced as the output of an Operation. This allows Keras to track how each Tensor was produced, and this information is later retraced by the `Function` class to reconstruct the Operations graph. Attributes: operation: The Operation instance that produced the Tensor. node_index: The specific call to the Operation that produced this Tensor. Operations can be called multiple times in order to share weights. A new node is created every time an Operation is called. The corresponding node that represents the call event that produced the Tensor can be found at `op._inbound_nodes[node_index]`. tensor_index: The output index for this Tensor. Always zero if the Operation that produced this Tensor only has one output. Nested structures of Tensors are deterministically assigned an index via `nest.flatten`. """ # Added to maintain memory and performance characteristics of `namedtuple` # while subclassing. __slots__ = () def is_keras_tensor(obj): return hasattr(obj, "_keras_history")
KerasHistory
python
openai__openai-python
src/openai/types/realtime/realtime_tools_config_union.py
{ "start": 2481, "end": 4769 }
class ____(BaseModel): server_label: str """A label for this MCP server, used to identify it in tool calls.""" type: Literal["mcp"] """The type of the MCP tool. Always `mcp`.""" allowed_tools: Optional[McpAllowedTools] = None """List of allowed tool names or a filter object.""" authorization: Optional[str] = None """ An OAuth access token that can be used with a remote MCP server, either with a custom MCP server URL or a service connector. Your application must handle the OAuth authorization flow and provide the token here. """ connector_id: Optional[ Literal[ "connector_dropbox", "connector_gmail", "connector_googlecalendar", "connector_googledrive", "connector_microsoftteams", "connector_outlookcalendar", "connector_outlookemail", "connector_sharepoint", ] ] = None """Identifier for service connectors, like those available in ChatGPT. One of `server_url` or `connector_id` must be provided. Learn more about service connectors [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors). Currently supported `connector_id` values are: - Dropbox: `connector_dropbox` - Gmail: `connector_gmail` - Google Calendar: `connector_googlecalendar` - Google Drive: `connector_googledrive` - Microsoft Teams: `connector_microsoftteams` - Outlook Calendar: `connector_outlookcalendar` - Outlook Email: `connector_outlookemail` - SharePoint: `connector_sharepoint` """ headers: Optional[Dict[str, str]] = None """Optional HTTP headers to send to the MCP server. Use for authentication or other purposes. """ require_approval: Optional[McpRequireApproval] = None """Specify which of the MCP server's tools require approval.""" server_description: Optional[str] = None """Optional description of the MCP server, used to provide more context.""" server_url: Optional[str] = None """The URL for the MCP server. One of `server_url` or `connector_id` must be provided. """ RealtimeToolsConfigUnion: TypeAlias = Annotated[Union[RealtimeFunctionTool, Mcp], PropertyInfo(discriminator="type")]
Mcp
python
scikit-image__scikit-image
benchmarks/benchmark_segmentation.py
{ "start": 3696, "end": 4871 }
class ____: param_names = ["seed_count", "connectivity", "compactness"] params = [(5, 500), (1, 2), (0, 0.01)] def setup(self, *args): self.image = filters.sobel(data.coins()) def time_watershed(self, seed_count, connectivity, compactness): watershed(self.image, seed_count, connectivity, compactness=compactness) def peakmem_reference(self, *args): """Provide reference for memory measurement with empty benchmark. Peakmem benchmarks measure the maximum amount of RAM used by a function. However, this maximum also includes the memory used during the setup routine (as of asv 0.2.1; see [1]_). Measuring an empty peakmem function might allow us to disambiguate between the memory used by setup and the memory used by target (see other ``peakmem_`` functions below). References ---------- .. [1]: https://asv.readthedocs.io/en/stable/writing_benchmarks.html#peak-memory """ pass def peakmem_watershed(self, seed_count, connectivity, compactness): watershed(self.image, seed_count, connectivity, compactness=compactness)
Watershed
python
django__django
tests/template_tests/filter_tests/test_center.py
{ "start": 164, "end": 868 }
class ____(SimpleTestCase): @setup( { "center01": ( '{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.' "{% endautoescape %}" ) } ) def test_center01(self): output = self.engine.render_to_string( "center01", {"a": "a&b", "b": mark_safe("a&b")} ) self.assertEqual(output, ". a&b . . a&b .") @setup({"center02": '.{{ a|center:"5" }}. .{{ b|center:"5" }}.'}) def test_center02(self): output = self.engine.render_to_string( "center02", {"a": "a&b", "b": mark_safe("a&b")} ) self.assertEqual(output, ". a&amp;b . . a&b .")
CenterTests
python
pydantic__pydantic
tests/benchmarks/shared.py
{ "start": 1795, "end": 4798 }
class ____: pass StdLibTypes = [ deque, # collections.deque deque[str], # collections.deque deque[int], # collections.deque deque[float], # collections.deque deque[bytes], # collections.deque str, # str int, # int float, # float complex, # complex bool, # bool bytes, # bytes date, # datetime.date datetime, # datetime.datetime time, # datetime.time timedelta, # datetime.timedelta Decimal, # decimal.Decimal Color, # enum ToolEnum, # int enum IPv4Address, # ipaddress.IPv4Address IPv6Address, # ipaddress.IPv6Address IPv4Interface, # ipaddress.IPv4Interface IPv6Interface, # ipaddress.IPv6Interface IPv4Network, # ipaddress.IPv4Network IPv6Network, # ipaddress.IPv6Network Path, # pathlib.Path Pattern, # typing.Pattern UUID, # uuid.UUID uuid4, # uuid.uuid4 uuid5, # uuid.uuid5 Point, # named tuple list, # built-in list list[int], # built-in list list[str], # built-in list list[bytes], # built-in list list[float], # built-in list dict, # built-in dict dict[str, float], # built-in dict dict[str, bytes], # built-in dict dict[str, int], # built-in dict dict[str, str], # built-in dict User, # TypedDict tuple, # tuple tuple[int, str, float], # built-in tuple set, # built-in set set[int], # set set[str], # set frozenset, # built-in frozenset frozenset[int], # built-in frozenset frozenset[str], # built-in frozenset Optional[int], # typing.Optional Optional[str], # typing.Optional Optional[float], # typing.Optional Optional[bytes], # typing.Optional Optional[bool], # typing.Optional Sequence[int], # typing.Sequence Sequence[str], # typing.Sequence Sequence[bytes], # typing.Sequence Sequence[float], # typing.Sequence Iterable[int], # typing.Iterable Iterable[str], # typing.Iterable Iterable[bytes], # typing.Iterable Iterable[float], # typing.Iterable Callable[[int], int], # typing.Callable Callable[[str], str], # typing.Callable Literal['apple', 'pumpkin'], # typing.Literal type[Foo], # typing.Type Any, # typing.Any ] PydanticTypes = [ StrictBool, PositiveInt, PositiveFloat, NegativeInt, NegativeFloat, NonNegativeInt, NonPositiveInt, NonNegativeFloat, NonPositiveFloat, FiniteFloat, UUID1, UUID3, UUID4, UUID5, FilePath, DirectoryPath, NewPath, Base64Bytes, Base64Str, Base64UrlBytes, Base64UrlStr, JsonValue, OnErrorOmit, ImportString, Json[Any], Json[list[int]], Json[list[str]], Json[list[bytes]], Json[list[float]], Json[list[Any]], Secret[bool], Secret[int], Secret[float], Secret[str], Secret[bytes], SecretStr, SecretBytes, ByteSize, PastDate, FutureDate, PastDatetime, ]
Foo
python
getsentry__sentry
src/sentry/uptime/endpoints/serializers.py
{ "start": 1275, "end": 1729 }
class ____(Serializer): @override def serialize(self, obj: UptimeSubscription, attrs, user, **kwargs) -> dict[str, Any]: return { "url": obj.url, "method": obj.method, "body": obj.body, "headers": obj.headers, "intervalSeconds": obj.interval_seconds, "timeoutMs": obj.timeout_ms, "traceSampling": obj.trace_sampling, }
UptimeSubscriptionSerializer
python
readthedocs__readthedocs.org
readthedocs/projects/views/base.py
{ "start": 1401, "end": 2915 }
class ____(SuccessMessageMixin): """ Mixin class that provides project sublevel objects. This mixin uses several class level variables project_url_field The URL kwarg name for the project slug success_message Message when the form is successfully saved, comes from SuccessMessageMixin """ project_url_field = "project_slug" def get_queryset(self): self.project = self.get_project() return self.model.objects.filter(project=self.project) @lru_cache(maxsize=1) def get_project(self): """Return project determined by url kwarg.""" if self.project_url_field not in self.kwargs: return None return get_object_or_404( Project.objects.for_admin_user(user=self.request.user), slug=self.kwargs[self.project_url_field], ) def get_context_data(self, **kwargs): """Add project to context data.""" context = super().get_context_data(**kwargs) project = self.get_project() context["project"] = project context["superproject"] = project and project.superproject return context def get_form_kwargs(self): kwargs = { "project": self.get_project(), } return kwargs def get_form(self, data=None, files=None, **kwargs): """Pass in project to form class instance.""" kwargs.update(self.get_form_kwargs()) return self.form_class(data, files, **kwargs)
ProjectAdminMixin
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 65046, "end": 65332 }
class ____(sgqlc.types.Enum): """The possible states of a project v2. Enumeration Choices: * `CLOSED`: A project v2 that has been closed * `OPEN`: A project v2 that is still open """ __schema__ = github_schema __choices__ = ("CLOSED", "OPEN")
ProjectV2State
python
apache__avro
lang/py/avro/datafile.py
{ "start": 2178, "end": 4814 }
class ____: """ Mixin for meta properties. Files may include arbitrary user-specified metadata. File metadata is written as if defined by the following map schema: `{"type": "map", "values": "bytes"}` All metadata properties that start with "avro." are reserved. The following file metadata properties are currently used: - `avro.schema` contains the schema of objects stored in the file, as JSON data (required). - `avro.codec`, the name of the compression codec used to compress blocks, as a string. Implementations are required to support the following codecs: "null" and "deflate". If codec is absent, it is assumed to be "null". See avro.codecs for implementation details. """ __slots__ = ("_meta",) _meta: MutableMapping[str, bytes] def get_meta(self, key: str) -> Optional[bytes]: """Get the metadata property at `key`.""" return self.meta.get(key) def set_meta(self, key: str, val: bytes) -> None: """Set the metadata property at `key`.""" self.meta[key] = val def del_meta(self, key: str) -> None: """Unset the metadata property at `key`.""" del self.meta[key] @property def meta(self) -> MutableMapping[str, bytes]: """Get the dictionary of metadata for this datafile.""" if not hasattr(self, "_meta"): self._meta = {} return self._meta @property def schema(self) -> str: """Get the schema of objects stored in the file from the file's metadata.""" schema_str = self.get_meta(SCHEMA_KEY) if schema_str: return schema_str.decode() raise avro.errors.DataFileException("Missing required schema metadata.") @schema.setter def schema(self, value: str) -> None: """Set the schema of objects stored in the file's metadata.""" self.set_meta(SCHEMA_KEY, value.encode()) @property def codec(self) -> str: """Get the file's compression codec algorithm from the file's metadata.""" codec = self.get_meta(CODEC_KEY) return "null" if codec is None else codec.decode() @codec.setter def codec(self, value: str) -> None: """Set the file's compression codec algorithm in the file's metadata.""" if value not in VALID_CODECS: raise avro.errors.DataFileException(f"Unknown codec: {value!r}") self.set_meta(CODEC_KEY, value.encode()) @codec.deleter def codec(self) -> None: """Unset the file's compression codec algorithm from the file's metadata.""" self.del_meta(CODEC_KEY)
_DataFileMetadata
python
getsentry__sentry
tests/snuba/sessions/test_sessions.py
{ "start": 9685, "end": 13966 }
class ____(TestCase, ReleaseHealthBaseTestCase): backend = MetricsReleaseHealthBackend() def setUp(self) -> None: super().setUp() self.four_days_ago = timezone.now() - timedelta(days=4) def test_with_and_without_environments(self) -> None: self.bulk_store_sessions(self.create_sessions__v2_crashed()) for environments in [None, ["prod"]]: data = self.backend.get_crash_free_breakdown( project_id=self.project.id, release=release_v1_0_0, start=self.four_days_ago, environments=environments, ) # Last returned date is generated within function, should be close to now: last_date = data[-1]["date"] assert timezone.now() - last_date < timedelta(seconds=1) assert data == [ { "crash_free_sessions": None, "crash_free_users": None, "date": self.four_days_ago + timedelta(days=1), "total_sessions": 0, "total_users": 0, }, { "crash_free_sessions": None, "crash_free_users": None, "date": self.four_days_ago + timedelta(days=2), "total_sessions": 0, "total_users": 0, }, { "crash_free_sessions": 100.0, "crash_free_users": 100.0, "total_sessions": 2, "total_users": 1, "date": mock.ANY, # tested above }, ] def test_all_sessions_crashed(self) -> None: self.bulk_store_sessions(self.create_sessions__v2_crashed()) data = self.backend.get_crash_free_breakdown( project_id=self.project.id, release=release_v2_0_0, start=self.four_days_ago, environments=["prod"], ) # Last returned date is generated within function, should be close to now: last_date = data[-1]["date"] assert timezone.now() - last_date < timedelta(seconds=1) assert data == [ { "crash_free_sessions": None, "crash_free_users": None, "date": self.four_days_ago + timedelta(days=1), "total_sessions": 0, "total_users": 0, }, { "crash_free_sessions": None, "crash_free_users": None, "date": self.four_days_ago + timedelta(days=2), "total_sessions": 0, "total_users": 0, }, { "crash_free_sessions": 0.0, "crash_free_users": 0.0, "total_sessions": 1, "total_users": 1, "date": mock.ANY, }, ] def test_with_non_existing_release(self) -> None: self.bulk_store_sessions(self.create_sessions__v2_crashed()) data = self.backend.get_crash_free_breakdown( project_id=self.project.id, release="non-existing", start=self.four_days_ago, environments=["prod"], ) # Last returned date is generated within function, should be close to now: last_date = data[-1]["date"] assert timezone.now() - last_date < timedelta(seconds=1) assert data == [ { "crash_free_sessions": None, "crash_free_users": None, "date": self.four_days_ago + timedelta(days=1), "total_sessions": 0, "total_users": 0, }, { "crash_free_sessions": None, "crash_free_users": None, "date": self.four_days_ago + timedelta(days=2), "total_sessions": 0, "total_users": 0, }, { "crash_free_sessions": None, "crash_free_users": None, "total_sessions": 0, "total_users": 0, "date": mock.ANY, }, ]
GetCrashFreeBreakdownTestCase
python
Lightning-AI__lightning
src/lightning/fabric/utilities/throughput.py
{ "start": 1283, "end": 12091 }
class ____: """Computes throughput. +------------------------+-------------------------------------------------------------------------------------+ | Key | Value | +========================+=====================================================================================+ | batches_per_sec | Rolling average (over ``window_size`` most recent updates) of the number of batches | | | processed per second | +--------------------------+-----------------------------------------------------------------------------------+ | samples_per_sec | Rolling average (over ``window_size`` most recent updates) of the number of samples | | | processed per second | +--------------------------+-----------------------------------------------------------------------------------+ | items_per_sec | Rolling average (over ``window_size`` most recent updates) of the number of items | | | processed per second | +--------------------------+-----------------------------------------------------------------------------------+ | flpps_per_sec | Rolling average (over ``window_size`` most recent updates) of the number of flops | | | processed per second | +--------------------------+-----------------------------------------------------------------------------------+ | device/batches_per_sec | batches_per_sec divided by world size | +--------------------------+-----------------------------------------------------------------------------------+ | device/samples_per_sec | samples_per_sec divided by world size | +--------------------------+-----------------------------------------------------------------------------------+ | device/items_per_sec | items_per_sec divided by world size. This may include padding depending on the data | +--------------------------+-----------------------------------------------------------------------------------+ | device/flops_per_sec | flops_per_sec divided by world size. | +--------------------------+-----------------------------------------------------------------------------------+ | device/mfu | device/flops_per_sec divided by world size. | +--------------------------+-----------------------------------------------------------------------------------+ | time | Total elapsed time | +--------------------------+-----------------------------------------------------------------------------------+ | batches | Total batches seen | +--------------------------+-----------------------------------------------------------------------------------+ | samples | Total samples seen | +--------------------------+-----------------------------------------------------------------------------------+ | lengths | Total items seen | +--------------------------+-----------------------------------------------------------------------------------+ Example:: throughput = Throughput() t0 = time() for i in range(1000): do_work() if torch.cuda.is_available(): torch.cuda.synchronize() # required or else time() won't be correct throughput.update(time=time() - t0, samples=i) if i % 10 == 0: print(throughput.compute()) Notes: - The implementation assumes that devices FLOPs are all the same as it normalizes by the world size and only takes a single ``available_flops`` value. - items_per_sec, flops_per_sec and MFU do not account for padding if present. We suggest using samples_per_sec or batches_per_sec to measure throughput under this circumstance. Args: available_flops: Number of theoretical flops available for a single device. world_size: Number of devices available across hosts. Global metrics are not included if the world size is 1. window_size: Number of batches to use for a rolling average. separator: Key separator to use when creating per-device and global metrics. """ def __init__( self, available_flops: Optional[float] = None, world_size: int = 1, window_size: int = 100, separator: str = "/" ) -> None: self.available_flops = available_flops self.separator = separator assert world_size > 0 self.world_size = world_size # throughput is computed over a window of values. at least 2 is enforced since it looks at the difference # between the first and last elements assert window_size > 1 # custom class instead of `deque(maxlen=)` because it's easy for users to mess up their timer/counters and log # values that do not increase monotonically. this class will raise an error if that happens. self._time: _MonotonicWindow[float] = _MonotonicWindow(maxlen=window_size) self._batches: _MonotonicWindow[int] = _MonotonicWindow(maxlen=window_size) self._samples: _MonotonicWindow[int] = _MonotonicWindow(maxlen=window_size) self._lengths: _MonotonicWindow[int] = _MonotonicWindow(maxlen=window_size) self._flops: deque[int] = deque(maxlen=window_size) def update( self, *, time: float, batches: int, samples: int, lengths: Optional[int] = None, flops: Optional[int] = None, ) -> None: """Update throughput metrics. Args: time: Total elapsed time in seconds. It should monotonically increase by the iteration time with each call. batches: Total batches seen per device. It should monotonically increase with each call. samples: Total samples seen per device. It should monotonically increase by the batch size with each call. lengths: Total length of the samples seen. It should monotonically increase by the lengths of a batch with each call. flops: Flops elapased per device since last ``update()`` call. You can easily compute this by using :func:`measure_flops` and multiplying it by the number of batches that have been processed. The value might be different in each device if the batch size is not the same. """ self._time.append(time) if samples < batches: raise ValueError(f"Expected samples ({samples}) to be greater or equal than batches ({batches})") self._batches.append(batches) self._samples.append(samples) if lengths is not None: if lengths < samples: raise ValueError(f"Expected lengths ({lengths}) to be greater or equal than samples ({samples})") self._lengths.append(lengths) if len(self._samples) != len(self._lengths): raise RuntimeError( f"If lengths are passed ({len(self._lengths)}), there needs to be the same number of samples" f" ({len(self._samples)})" ) if flops is not None: # sum of flops across ranks self._flops.append(flops * self.world_size) def compute(self) -> _THROUGHPUT_METRICS: """Compute throughput metrics.""" metrics = { "time": self._time[-1], "batches": self._batches[-1], "samples": self._samples[-1], } if self._lengths: metrics["lengths"] = self._lengths[-1] add_global_metrics = self.world_size > 1 # a different but valid design choice would be to still compute all these metrics even if the window of values # has not been filled if len(self._time) == self._time.maxlen: elapsed_time = self._time[-1] - self._time[0] elapsed_batches = self._batches[-1] - self._batches[0] elapsed_samples = self._samples[-1] - self._samples[0] # we are safe from ZeroDivisionError thanks to `_MonotonicWindow` dev_samples_per_sec = elapsed_samples / elapsed_time dev_batches_per_sec = elapsed_batches / elapsed_time metrics.update({ f"device{self.separator}batches_per_sec": elapsed_batches / elapsed_time, f"device{self.separator}samples_per_sec": dev_samples_per_sec, }) if add_global_metrics: samples_per_sec = dev_batches_per_sec * self.world_size metrics.update({ "batches_per_sec": samples_per_sec, "samples_per_sec": dev_samples_per_sec * self.world_size, }) if len(self._lengths) == self._lengths.maxlen: elapsed_lengths = self._lengths[-1] - self._lengths[0] dev_items_per_sec = elapsed_lengths / elapsed_time metrics[f"device{self.separator}items_per_sec"] = dev_items_per_sec if add_global_metrics: items_per_sec = dev_items_per_sec * self.world_size metrics["items_per_sec"] = items_per_sec if len(self._flops) == self._flops.maxlen: elapsed_flops = sum(self._flops) - self._flops[0] elapsed_time = self._time[-1] - self._time[0] flops_per_sec = elapsed_flops / elapsed_time dev_flops_per_sec = flops_per_sec / self.world_size if add_global_metrics: metrics["flops_per_sec"] = flops_per_sec metrics[f"device{self.separator}flops_per_sec"] = dev_flops_per_sec if self.available_flops: metrics[f"device{self.separator}mfu"] = dev_flops_per_sec / self.available_flops return metrics def reset(self) -> None: self._time.clear() self._batches.clear() self._samples.clear() self._lengths.clear() self._flops.clear()
Throughput
python
facebook__pyre-check
documentation/pysa_tutorial/exercise5/generate_models.py
{ "start": 858, "end": 2139 }
class ____: pass def main() -> None: # Here, specify all the generators that you might want to call. generators = { "django_path_params": generate_taint_models.RESTApiSourceGenerator( django_urls=view_generator.DjangoUrls( urls_module="urls", url_pattern_type=UrlPattern, url_resolver_type=Ignore, ) ), # "decorator_extracted_params": generate_taint_models.<GENERATOR_NAME>( # root=".", # annotation_specifications=[ # generate_taint_models.DecoratorAnnotationSpecification( # decorator=<DECORATOR_NAME_INCLUDING_PRECEEDING_@>, # annotations=generator_specifications.default_entrypoint_taint, # ) # ], # ), } # The `run_generators` function will take care of parsing command-line arguments, as # well as executing the generators specified in `default_modes` unless you pass in a # specific set from the command line. generate_taint_models.run_generators( generators, default_modes=[ "django_path_params", # "decorator_extracted_params" ], ) if __name__ == "__main__": main()
Ignore
python
doocs__leetcode
solution/2300-2399/2310.Sum of Numbers With Units Digit K/Solution.py
{ "start": 0, "end": 248 }
class ____: def minimumNumbers(self, num: int, k: int) -> int: if num == 0: return 0 for i in range(1, num + 1): if (t := num - k * i) >= 0 and t % 10 == 0: return i return -1
Solution
python
great-expectations__great_expectations
great_expectations/core/factory/factory.py
{ "start": 102, "end": 583 }
class ____(ABC, Generic[T]): """ Responsible for basic CRUD operations on collections of GX domain objects. """ @abstractmethod def add(self, obj: T) -> T: pass @abstractmethod def delete(self, name: str) -> None: pass @abstractmethod def get(self, name: str) -> T: pass @abstractmethod def all(self) -> Iterable[T]: pass @abstractmethod def add_or_update(self, obj: T) -> T: pass
Factory
python
openai__openai-python
tests/api_resources/realtime/test_calls.py
{ "start": 464, "end": 12686 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize @pytest.mark.respx(base_url=base_url) def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/realtime/calls").mock(return_value=httpx.Response(200, json={"foo": "bar"})) call = client.realtime.calls.create( sdp="sdp", ) assert isinstance(call, _legacy_response.HttpxBinaryResponseContent) assert call.json() == {"foo": "bar"} @parametrize @pytest.mark.respx(base_url=base_url) def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/realtime/calls").mock(return_value=httpx.Response(200, json={"foo": "bar"})) call = client.realtime.calls.create( sdp="sdp", session={ "type": "realtime", "audio": { "input": { "format": { "rate": 24000, "type": "audio/pcm", }, "noise_reduction": {"type": "near_field"}, "transcription": { "language": "language", "model": "whisper-1", "prompt": "prompt", }, "turn_detection": { "type": "server_vad", "create_response": True, "idle_timeout_ms": 5000, "interrupt_response": True, "prefix_padding_ms": 0, "silence_duration_ms": 0, "threshold": 0, }, }, "output": { "format": { "rate": 24000, "type": "audio/pcm", }, "speed": 0.25, "voice": "ash", }, }, "include": ["item.input_audio_transcription.logprobs"], "instructions": "instructions", "max_output_tokens": 0, "model": "string", "output_modalities": ["text"], "prompt": { "id": "id", "variables": {"foo": "string"}, "version": "version", }, "tool_choice": "none", "tools": [ { "description": "description", "name": "name", "parameters": {}, "type": "function", } ], "tracing": "auto", "truncation": "auto", }, ) assert isinstance(call, _legacy_response.HttpxBinaryResponseContent) assert call.json() == {"foo": "bar"} @parametrize @pytest.mark.respx(base_url=base_url) def test_raw_response_create(self, client: OpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/realtime/calls").mock(return_value=httpx.Response(200, json={"foo": "bar"})) response = client.realtime.calls.with_raw_response.create( sdp="sdp", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert_matches_type(_legacy_response.HttpxBinaryResponseContent, call, path=["response"]) @parametrize @pytest.mark.respx(base_url=base_url) def test_streaming_response_create(self, client: OpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/realtime/calls").mock(return_value=httpx.Response(200, json={"foo": "bar"})) with client.realtime.calls.with_streaming_response.create( sdp="sdp", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert_matches_type(bytes, call, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_method_accept(self, client: OpenAI) -> None: call = client.realtime.calls.accept( call_id="call_id", type="realtime", ) assert call is None @parametrize def test_method_accept_with_all_params(self, client: OpenAI) -> None: call = client.realtime.calls.accept( call_id="call_id", type="realtime", audio={ "input": { "format": { "rate": 24000, "type": "audio/pcm", }, "noise_reduction": {"type": "near_field"}, "transcription": { "language": "language", "model": "whisper-1", "prompt": "prompt", }, "turn_detection": { "type": "server_vad", "create_response": True, "idle_timeout_ms": 5000, "interrupt_response": True, "prefix_padding_ms": 0, "silence_duration_ms": 0, "threshold": 0, }, }, "output": { "format": { "rate": 24000, "type": "audio/pcm", }, "speed": 0.25, "voice": "ash", }, }, include=["item.input_audio_transcription.logprobs"], instructions="instructions", max_output_tokens=0, model="string", output_modalities=["text"], prompt={ "id": "id", "variables": {"foo": "string"}, "version": "version", }, tool_choice="none", tools=[ { "description": "description", "name": "name", "parameters": {}, "type": "function", } ], tracing="auto", truncation="auto", ) assert call is None @parametrize def test_raw_response_accept(self, client: OpenAI) -> None: response = client.realtime.calls.with_raw_response.accept( call_id="call_id", type="realtime", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert call is None @parametrize def test_streaming_response_accept(self, client: OpenAI) -> None: with client.realtime.calls.with_streaming_response.accept( call_id="call_id", type="realtime", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert call is None assert cast(Any, response.is_closed) is True @parametrize def test_path_params_accept(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `call_id` but received ''"): client.realtime.calls.with_raw_response.accept( call_id="", type="realtime", ) @parametrize def test_method_hangup(self, client: OpenAI) -> None: call = client.realtime.calls.hangup( "call_id", ) assert call is None @parametrize def test_raw_response_hangup(self, client: OpenAI) -> None: response = client.realtime.calls.with_raw_response.hangup( "call_id", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert call is None @parametrize def test_streaming_response_hangup(self, client: OpenAI) -> None: with client.realtime.calls.with_streaming_response.hangup( "call_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert call is None assert cast(Any, response.is_closed) is True @parametrize def test_path_params_hangup(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `call_id` but received ''"): client.realtime.calls.with_raw_response.hangup( "", ) @parametrize def test_method_refer(self, client: OpenAI) -> None: call = client.realtime.calls.refer( call_id="call_id", target_uri="tel:+14155550123", ) assert call is None @parametrize def test_raw_response_refer(self, client: OpenAI) -> None: response = client.realtime.calls.with_raw_response.refer( call_id="call_id", target_uri="tel:+14155550123", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert call is None @parametrize def test_streaming_response_refer(self, client: OpenAI) -> None: with client.realtime.calls.with_streaming_response.refer( call_id="call_id", target_uri="tel:+14155550123", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert call is None assert cast(Any, response.is_closed) is True @parametrize def test_path_params_refer(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `call_id` but received ''"): client.realtime.calls.with_raw_response.refer( call_id="", target_uri="tel:+14155550123", ) @parametrize def test_method_reject(self, client: OpenAI) -> None: call = client.realtime.calls.reject( call_id="call_id", ) assert call is None @parametrize def test_method_reject_with_all_params(self, client: OpenAI) -> None: call = client.realtime.calls.reject( call_id="call_id", status_code=486, ) assert call is None @parametrize def test_raw_response_reject(self, client: OpenAI) -> None: response = client.realtime.calls.with_raw_response.reject( call_id="call_id", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert call is None @parametrize def test_streaming_response_reject(self, client: OpenAI) -> None: with client.realtime.calls.with_streaming_response.reject( call_id="call_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" call = response.parse() assert call is None assert cast(Any, response.is_closed) is True @parametrize def test_path_params_reject(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `call_id` but received ''"): client.realtime.calls.with_raw_response.reject( call_id="", )
TestCalls
python
tensorflow__tensorflow
third_party/xla/build_tools/lint/check_contents_test.py
{ "start": 820, "end": 3429 }
class ____(absltest.TestCase): @classmethod def setUpClass(cls): super().setUpClass() testdata = test_utils.xla_src_root() / "build_tools" / "lint" / "testdata" with (testdata / "bad_cc.diff").open() as f: cls.bad_cc_hunks = diff_parser.parse_hunks(f.read()) with (testdata / "important_cc.diff").open() as f: cls.important_cc_hunks = diff_parser.parse_hunks(f.read()) def test_check_good_diff(self): locs = check_contents.check_diffs( self.bad_cc_hunks, prohibited_regex="Make_Unique", suppression_regex="OK", ) self.assertEmpty(locs, 0) def test_check_suppressed_diff_without_suppressions(self): locs = check_contents.check_diffs( self.bad_cc_hunks, prohibited_regex="Make_Unique" ) expected_locs = [ check_contents.RegexLocation( path="src/dir/bad.cc", line_number=3, line_contents="using Make_Unique = std::make_unique; // OK", matched_text="Make_Unique", ), check_contents.RegexLocation( path="src/dir/bad.cc", line_number=6, line_contents=" return Make_Unique<int>(a + b); // OK. Fixed now!", matched_text="Make_Unique", ), ] self.assertEqual(locs, expected_locs) def test_check_suppressed_diff_with_path_regexes(self): filtered_hunks = check_contents.filter_hunks_by_path( self.bad_cc_hunks, path_regexes=["src/important\\..*"], path_regex_exclusions=[], ) self.assertLen(filtered_hunks, 1) locs = check_contents.check_diffs( filtered_hunks, prohibited_regex="Make_Unique" ) self.assertEmpty(locs) def test_check_suppressed_diff_with_exclusions(self): filtered_hunks = check_contents.filter_hunks_by_path( self.bad_cc_hunks, path_regexes=[], path_regex_exclusions=["src/dir/.*"], ) self.assertLen(filtered_hunks, 1) locs = check_contents.check_diffs( filtered_hunks, prohibited_regex="Make_Unique" ) self.assertEmpty(locs) def test_check_suppressed_diff_with_suppression(self): filtered_hunks = check_contents.filter_hunks_by_path( self.bad_cc_hunks, path_regexes=[], path_regex_exclusions=[] ) # filtering without path_regex(_exclusions) is a noop self.assertEqual(self.bad_cc_hunks, filtered_hunks) locs = check_contents.check_diffs( filtered_hunks, prohibited_regex="Make_Unique", suppression_regex="OK" ) self.assertEmpty(locs) if __name__ == "__main__": absltest.main()
CheckDiffsTest
python
django__django
tests/db_functions/text/test_right.py
{ "start": 206, "end": 1848 }
class ____(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name="John Smith", alias="smithj") Author.objects.create(name="Rhonda") def test_basic(self): authors = Author.objects.annotate(name_part=Right("name", 5)) self.assertQuerySetEqual( authors.order_by("name"), ["Smith", "honda"], lambda a: a.name_part ) # If alias is null, set it to the first 2 lower characters of the name. Author.objects.filter(alias__isnull=True).update(alias=Lower(Right("name", 2))) self.assertQuerySetEqual( authors.order_by("name"), ["smithj", "da"], lambda a: a.alias ) def test_invalid_length(self): with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"): Author.objects.annotate(raises=Right("name", 0)) def test_zero_length(self): Author.objects.create(name="Tom", alias="tom") authors = Author.objects.annotate( name_part=Right("name", Length("name") - Length("alias")) ) self.assertQuerySetEqual( authors.order_by("name"), [ "mith", "" if connection.features.interprets_empty_strings_as_nulls else None, "", ], lambda a: a.name_part, ) def test_expressions(self): authors = Author.objects.annotate( name_part=Right("name", Value(3, output_field=IntegerField())) ) self.assertQuerySetEqual( authors.order_by("name"), ["ith", "nda"], lambda a: a.name_part )
RightTests
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_errorbars06.py
{ "start": 315, "end": 1571 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_errorbars06.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with error bars.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "column"}) chart.axis_ids = [45472384, 49016832] 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", "y_error_bars": {"type": "standard_error"}, } ) 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
simonw__datasette
datasette/utils/check_callable.py
{ "start": 65, "end": 684 }
class ____(NamedTuple): is_callable: bool is_async_callable: bool def check_callable(obj: Any) -> CallableStatus: if not callable(obj): return CallableStatus(False, False) if isinstance(obj, type): # It's a class return CallableStatus(True, False) if isinstance(obj, types.FunctionType): return CallableStatus(True, inspect.iscoroutinefunction(obj)) if hasattr(obj, "__call__"): return CallableStatus(True, inspect.iscoroutinefunction(obj.__call__)) assert False, "obj {} is somehow callable with no __call__ method".format(repr(obj))
CallableStatus
python
matplotlib__matplotlib
lib/matplotlib/backend_tools.py
{ "start": 30567, "end": 33074 }
class ____(ToolBase): """Tool to copy the figure to the clipboard.""" description = 'Copy the canvas figure to clipboard' default_keymap = property(lambda self: mpl.rcParams['keymap.copy']) def trigger(self, *args, **kwargs): message = "Copy tool is not available" self.toolmanager.message_event(message, self) default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward, 'zoom': ToolZoom, 'pan': ToolPan, 'subplots': ConfigureSubplotsBase, 'save': SaveFigureBase, 'grid': ToolGrid, 'grid_minor': ToolMinorGrid, 'fullscreen': ToolFullScreen, 'quit': ToolQuit, 'quit_all': ToolQuitAll, 'xscale': ToolXScale, 'yscale': ToolYScale, 'position': ToolCursorPosition, _views_positions: ToolViewsPositions, 'cursor': ToolSetCursor, 'rubberband': RubberbandBase, 'help': ToolHelpBase, 'copy': ToolCopyToClipboardBase, } default_toolbar_tools = [['navigation', ['home', 'back', 'forward']], ['zoompan', ['pan', 'zoom', 'subplots']], ['io', ['save', 'help']]] def add_tools_to_manager(toolmanager, tools=default_tools): """ Add multiple tools to a `.ToolManager`. Parameters ---------- toolmanager : `.backend_managers.ToolManager` Manager to which the tools are added. tools : {str: class_like}, optional The tools to add in a {name: tool} dict, see `.backend_managers.ToolManager.add_tool` for more info. """ for name, tool in tools.items(): toolmanager.add_tool(name, tool) def add_tools_to_container(container, tools=default_toolbar_tools): """ Add multiple tools to the container. Parameters ---------- container : Container `.backend_bases.ToolContainerBase` object that will get the tools added. tools : list, optional List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]`` where the tools ``[tool1, tool2, ...]`` will display in group1. See `.backend_bases.ToolContainerBase.add_tool` for details. """ for group, grouptools in tools: for position, tool in enumerate(grouptools): container.add_tool(tool, group, position)
ToolCopyToClipboardBase
python
scipy__scipy
scipy/interpolate/tests/test_interpolate.py
{ "start": 82874, "end": 84421 }
class ____: def test_bp_from_pp(self, xp): x = xp.asarray([0, 1, 3]) c = xp.asarray([[3, 2], [1, 8], [4, 3]]) pp = PPoly(c, x) bp = BPoly.from_power_basis(pp) pp1 = PPoly.from_bernstein_basis(bp) xv = xp.asarray([0.1, 1.4]) xp_assert_close(pp(xv), bp(xv)) xp_assert_close(pp(xv), pp1(xv)) def test_bp_from_pp_random(self): rng = np.random.RandomState(1234) m, k = 5, 8 # number of intervals, order x = np.sort(rng.random(m)) c = rng.random((k, m-1)) pp = PPoly(c, x) bp = BPoly.from_power_basis(pp) pp1 = PPoly.from_bernstein_basis(bp) xv = np.linspace(x[0], x[-1], 21) xp_assert_close(pp(xv), bp(xv)) xp_assert_close(pp(xv), pp1(xv)) def test_pp_from_bp(self, xp): x = xp.asarray([0, 1, 3]) c = xp.asarray([[3, 3], [1, 1], [4, 2]]) bp = BPoly(c, x) pp = PPoly.from_bernstein_basis(bp) bp1 = BPoly.from_power_basis(pp) xv = xp.asarray([0.1, 1.4]) xp_assert_close(bp(xv), pp(xv)) xp_assert_close(bp(xv), bp1(xv)) def test_broken_conversions(self): # regression test for gh-10597: from_power_basis only accepts PPoly etc. x = [0, 1, 3] c = [[3, 3], [1, 1], [4, 2]] pp = PPoly(c, x) with assert_raises(TypeError): PPoly.from_bernstein_basis(pp) bp = BPoly(c, x) with assert_raises(TypeError): BPoly.from_power_basis(bp)
TestPolyConversions
python
vyperlang__vyper
vyper/exceptions.py
{ "start": 9197, "end": 9260 }
class ____(VyperException): """An import cycle"""
ImportCycle
python
PrefectHQ__prefect
src/integrations/prefect-dbt/prefect_dbt/core/runner.py
{ "start": 3264, "end": 44772 }
class ____: """A runner for executing dbt commands with Prefect integration. This class enables the invocation of dbt commands while integrating with Prefect's logging and assets capabilities. Args: manifest: Optional pre-loaded dbt manifest settings: Optional PrefectDbtSettings instance for configuring dbt raise_on_failure: Whether to raise an error if the dbt command encounters a non-exception failure client: Optional Prefect client instance include_compiled_code: Whether to include compiled code in the asset description disable_assets: Global override for disabling asset generation for dbt nodes. If True, assets will not be created for any dbt nodes, even if the node's prefect config has enable_assets set to True. _force_nodes_as_tasks: Whether to force each dbt node execution to have a Prefect task representation when `.invoke()` is called outside of a flow or task run """ def __init__( self, manifest: Optional[Manifest] = None, settings: Optional[PrefectDbtSettings] = None, raise_on_failure: bool = True, client: Optional[PrefectClient] = None, include_compiled_code: bool = False, disable_assets: bool = False, _force_nodes_as_tasks: bool = False, _disable_callbacks: bool = False, ): self._manifest: Optional[Manifest] = manifest self.settings = settings or PrefectDbtSettings() self.raise_on_failure = raise_on_failure self.client = client or get_client() self.include_compiled_code = include_compiled_code self.disable_assets = disable_assets self._force_nodes_as_tasks = _force_nodes_as_tasks self._disable_callbacks = _disable_callbacks self._project_name: Optional[str] = None self._target_path: Optional[Path] = None self._profiles_dir: Optional[Path] = None self._project_dir: Optional[Path] = None self._log_level: Optional[EventLevel] = None self._config: Optional[RuntimeConfig] = None self._graph: Optional[Graph] = None self._skipped_nodes: set[str] = set() self._event_queue: Optional[queue.PriorityQueue] = None self._callback_thread: Optional[threading.Thread] = None self._shutdown_event: Optional[threading.Event] = None self._queue_counter = 0 # Counter for tiebreaking in PriorityQueue self._queue_counter_lock = threading.Lock() # Thread-safe counter increment @property def target_path(self) -> Path: return self._target_path or self.settings.target_path @property def profiles_dir(self) -> Path: return self._profiles_dir or self.settings.profiles_dir @property def project_dir(self) -> Path: return self._project_dir or self.settings.project_dir @property def log_level(self) -> EventLevel: return self._log_level or self.settings.log_level @property def manifest(self) -> Manifest: if self._manifest is None: self._set_manifest_from_project_dir() assert self._manifest is not None # for type checking return self._manifest @property def graph(self) -> Graph: if self._graph is None: self._set_graph_from_manifest() assert self._graph is not None return self._graph @property def project_name(self) -> str: if self._project_name is None: self._set_project_name_from_manifest() assert self._project_name is not None return self._project_name def _set_project_name_from_manifest(self) -> Optional[str]: self._project_name = self.manifest.metadata.project_name def _set_graph_from_manifest(self, add_test_edges: bool = False): linker = Linker() linker.link_graph(self.manifest) if add_test_edges: self.manifest.build_parent_and_child_maps() linker.add_test_edges(self.manifest) self._graph = Graph(linker.graph) def _set_manifest_from_project_dir(self): try: with open( os.path.join(self.project_dir, self.target_path, "manifest.json"), "r" ) as f: self._manifest = Manifest.from_dict(json.load(f)) # type: ignore[reportUnknownMemberType] except FileNotFoundError: raise ValueError( f"Manifest file not found in {os.path.join(self.project_dir, self.target_path, 'manifest.json')}" ) def _get_node_prefect_config( self, manifest_node: Union[ManifestNode, SourceDefinition] ) -> dict[str, dict[str, Any]]: if isinstance(manifest_node, SourceDefinition): return manifest_node.meta.get("prefect", {}) return manifest_node.config.meta.get("prefect", {}) def _get_upstream_manifest_nodes_and_configs( self, manifest_node: ManifestNode, ) -> list[tuple[Union[ManifestNode, SourceDefinition], dict[str, Any]]]: """Get upstream nodes for a given node""" upstream_manifest_nodes: list[ tuple[Union[ManifestNode, SourceDefinition], dict[str, Any]] ] = [] for depends_on_node in manifest_node.depends_on_nodes: # type: ignore[reportUnknownMemberType] depends_manifest_node = self.manifest.nodes.get( depends_on_node # type: ignore[reportUnknownMemberType] ) or self.manifest.sources.get(depends_on_node) # type: ignore[reportUnknownMemberType] if not depends_manifest_node: continue if not depends_manifest_node.relation_name: raise ValueError("Relation name not found in manifest") upstream_manifest_nodes.append( ( depends_manifest_node, self._get_node_prefect_config(depends_manifest_node), ) ) return upstream_manifest_nodes def _get_compiled_code_path(self, manifest_node: ManifestNode) -> Path: """Get the path to compiled code for a manifest node.""" return ( Path(self.project_dir) / self.target_path / "compiled" / self.project_name / manifest_node.original_file_path ) def _get_compiled_code( self, manifest_node: Union[ManifestNode, SourceDefinition] ) -> str: """Get compiled code for a manifest node if it exists and is enabled.""" if not self.include_compiled_code or isinstance( manifest_node, SourceDefinition ): return "" compiled_code_path = self._get_compiled_code_path(manifest_node) if os.path.exists(compiled_code_path): with open(compiled_code_path, "r") as f: code_content = f.read() description = ( f"\n ### Compiled code\n```sql\n{code_content.strip()}\n```" ) if len(description) > MAX_ASSET_DESCRIPTION_LENGTH: warning_msg = ( f"Compiled code for {manifest_node.name} was omitted because it exceeded the " f"maximum asset description length of {MAX_ASSET_DESCRIPTION_LENGTH} characters." ) description = "\n ### Compiled code\n" + warning_msg try: logger = get_run_logger() logger.warning(warning_msg) except MissingContextError: pass return description return "" def _create_asset_from_node( self, manifest_node: Union[ManifestNode, SourceDefinition], adapter_type: str ) -> Asset: """Create an Asset from a manifest node.""" if not manifest_node.relation_name: raise ValueError("Relation name not found in manifest") asset_id = format_resource_id(adapter_type, manifest_node.relation_name) compiled_code = self._get_compiled_code(manifest_node) if isinstance(manifest_node, SourceDefinition): owner = manifest_node.meta.get("owner") else: owner = manifest_node.config.meta.get("owner") if owner and isinstance(owner, str): owners = [owner] else: owners = None return Asset( key=asset_id, properties=AssetProperties( name=manifest_node.name, description=manifest_node.description + compiled_code, owners=owners, ), ) def _create_task_options( self, manifest_node: ManifestNode, upstream_assets: Optional[list[Asset]] = None ) -> TaskOptions: """Create TaskOptions for a manifest node.""" return TaskOptions( task_run_name=f"{manifest_node.resource_type.lower()} {manifest_node.name if manifest_node.name else manifest_node.unique_id}", asset_deps=upstream_assets, # type: ignore[arg-type] cache_policy=NO_CACHE, ) def _get_manifest_node_and_config( self, node_id: str ) -> tuple[Optional[ManifestNode], dict[str, Any]]: """Get manifest node and its prefect config.""" manifest_node = self.manifest.nodes.get(node_id) if manifest_node: prefect_config = manifest_node.config.meta.get("prefect", {}) return manifest_node, prefect_config return None, {} def _call_task( self, task_state: NodeTaskTracker, manifest_node: ManifestNode, context: dict[str, Any], enable_assets: bool, ): """Create and run a task for a node.""" adapter_type = self.manifest.metadata.adapter_type if not adapter_type: raise ValueError("Adapter type not found in manifest") upstream_manifest_nodes = self._get_upstream_manifest_nodes_and_configs( manifest_node ) if manifest_node.resource_type in MATERIALIZATION_NODE_TYPES and enable_assets: asset = self._create_asset_from_node(manifest_node, adapter_type) upstream_assets: list[Asset] = [] for ( upstream_manifest_node, upstream_manifest_node_config, ) in upstream_manifest_nodes: if ( upstream_manifest_node.resource_type in REFERENCE_NODE_TYPES or upstream_manifest_node.resource_type in MATERIALIZATION_NODE_TYPES and upstream_manifest_node_config.get("enable_assets", True) ): upstream_asset = self._create_asset_from_node( upstream_manifest_node, adapter_type ) upstream_assets.append(upstream_asset) task_options = self._create_task_options(manifest_node, upstream_assets) if not manifest_node.relation_name: raise ValueError("Relation name not found in manifest") asset_id = format_resource_id(adapter_type, manifest_node.relation_name) task = MaterializingTask( fn=execute_dbt_node, assets=[asset], materialized_by="dbt", **task_options, ) else: asset_id = None task_options = self._create_task_options(manifest_node) task = Task( fn=execute_dbt_node, **task_options, ) # Start the task in a separate thread task_state.start_task(manifest_node.unique_id, task) task_state.set_node_dependencies( manifest_node.unique_id, [node[0].unique_id for node in upstream_manifest_nodes], ) task_run_id = uuid7() task_state.set_task_run_id(manifest_node.unique_id, task_run_id) task_state.run_task_in_thread( manifest_node.unique_id, task, task_run_id=task_run_id, parameters={ "task_state": task_state, "node_id": manifest_node.unique_id, "asset_id": asset_id, }, context=context, ) @staticmethod def get_dbt_event_msg(event: EventMsg) -> str: return event.info.msg # type: ignore[reportUnknownMemberType] def _get_dbt_event_node_id(self, event: EventMsg) -> str: return event.data.node_info.unique_id # type: ignore[reportUnknownMemberType] def _start_callback_processor(self) -> None: """Start the background thread for processing callbacks.""" if self._event_queue is None: # Use PriorityQueue to ensure NodeStart events are processed first # Priority: 0 = NodeStart (highest), 1 = NodeFinished, 2 = everything else (lowest) self._event_queue = queue.PriorityQueue(maxsize=0) self._shutdown_event = threading.Event() self._callback_thread = threading.Thread( target=self._callback_worker, daemon=True, name="dbt-callback-processor" ) self._callback_thread.start() def _stop_callback_processor(self) -> None: """Stop the background thread and wait for queue to drain.""" if self._shutdown_event: self._shutdown_event.set() if self._event_queue: # Put a sentinel to wake up the worker (with highest priority to ensure it's processed) try: # Use counter -1 to ensure sentinel is processed first among priority 0 items with self._queue_counter_lock: sentinel_counter = self._queue_counter - 1 self._event_queue.put( (0, sentinel_counter, None), timeout=0.1 ) # Priority 0 to process immediately except queue.Full: pass if self._callback_thread and self._callback_thread.is_alive(): self._callback_thread.join(timeout=5.0) def _callback_worker(self) -> None: """Background worker thread that processes queued events.""" while not self._shutdown_event.is_set(): event_data = None item_retrieved = False try: # Get event with timeout to periodically check shutdown # PriorityQueue returns (priority, counter, item) tuples _, _, event_data = self._event_queue.get(timeout=0.1) item_retrieved = True if event_data is None: # Sentinel to shutdown break callback_func, event_msg = event_data callback_func(event_msg) except queue.Empty: continue finally: # Always call task_done() exactly once per successfully retrieved item # This includes the None sentinel used for shutdown if item_retrieved: self._event_queue.task_done() def _get_event_priority(self, event: EventMsg) -> int: """Get priority for an event. Lower number = higher priority. Priority levels: - 0: NodeStart (highest - must create tasks before other events) - 1: NodeFinished (medium - update task status) - 2: Everything else (lowest - logging, etc.) """ event_name = event.info.name if event_name == "NodeStart": return 0 elif event_name == "NodeFinished": return 1 else: return 2 def _queue_callback( self, callback_func: Callable[[EventMsg], None], event: EventMsg, priority: Optional[int] = None, ) -> None: """Helper method to queue a callback for background processing. Args: callback_func: The callback function to execute event: The event message priority: Optional priority override. If None, determined from event name. """ if self._event_queue is None: # Fallback to synchronous if queue not initialized callback_func(event) return # Determine priority if not provided if priority is None: priority = self._get_event_priority(event) # Get a unique counter value for tiebreaking (ensures items with same priority # can be ordered without comparing EventMsg objects) with self._queue_counter_lock: counter = self._queue_counter self._queue_counter += 1 # Queue the callback for background processing (non-blocking) try: self._event_queue.put( (priority, counter, (callback_func, event)), block=False ) except queue.Full: # If queue is full, fall back to synchronous processing # This prevents blocking dbt but may slow it down callback_func(event) def _create_unified_callback( self, task_state: NodeTaskTracker, log_level: EventLevel, context: dict[str, Any], add_test_edges: bool = False, ) -> Callable[[EventMsg], None]: """Creates a single unified callback that efficiently filters and routes dbt events. This approach optimizes performance by: 1. Using a dictionary dispatch table for O(1) routing (faster than if/elif chains) 2. Minimizing attribute access by caching event.info.name once 3. Using set membership checks for the most common case (logging events) 4. Only ONE callback registered with dbtRunner Note: While we cannot avoid the function call overhead entirely (dbt's API limitation), this implementation minimizes the work done per event to the absolute minimum. """ # Start the callback processor if not already started self._start_callback_processor() # Pre-compute event name constants (for use in dispatch table) _NODE_START = "NodeStart" _NODE_FINISHED = "NodeFinished" def _process_logging_sync(event: EventMsg) -> None: """Actual logging logic - runs in background thread.""" event_data = MessageToDict(event.data, preserving_proto_field_name=True) # Handle logging for all events with node_info if event_data.get("node_info"): node_id = self._get_dbt_event_node_id(event) # Skip logging for skipped nodes if node_id not in self._skipped_nodes: flow_run_context: Optional[dict[str, Any]] = context.get( "flow_run_context" ) logger = task_state.get_task_logger( node_id, flow_run_context.get("flow_run") if flow_run_context else None, flow_run_context.get("flow") if flow_run_context else None, ) else: logger = None else: # Get logger for events without node_info try: with hydrated_context(context) as run_context: logger = get_run_logger(run_context) except MissingContextError: logger = None # Log the event if logger is available if logger is not None: logger.setLevel(log_level.value.upper()) if ( event.info.level == EventLevel.DEBUG or event.info.level == EventLevel.TEST ): logger.debug(self.get_dbt_event_msg(event)) elif event.info.level == EventLevel.INFO: logger.info(self.get_dbt_event_msg(event)) elif event.info.level == EventLevel.WARN: logger.warning(self.get_dbt_event_msg(event)) elif event.info.level == EventLevel.ERROR: logger.error(self.get_dbt_event_msg(event)) def _process_node_started_sync(event: EventMsg) -> None: """Actual node started logic - runs in background thread.""" node_id = self._get_dbt_event_node_id(event) if node_id in self._skipped_nodes: return manifest_node, prefect_config = self._get_manifest_node_and_config(node_id) if manifest_node: enable_assets = ( prefect_config.get("enable_assets", True) and not self.disable_assets ) self._call_task(task_state, manifest_node, context, enable_assets) def _process_node_finished_sync(event: EventMsg) -> None: """Actual node finished logic - runs in background thread.""" node_id = self._get_dbt_event_node_id(event) if node_id in self._skipped_nodes: return manifest_node, _ = self._get_manifest_node_and_config(node_id) if manifest_node: event_data = MessageToDict(event.data, preserving_proto_field_name=True) # Store the status before ending the task event_message = self.get_dbt_event_msg(event) task_state.set_node_status(node_id, event_data, event_message) node_info: Optional[dict[str, Any]] = event_data.get("node_info") node_status: Optional[str] = ( node_info.get("node_status") if node_info else None ) if node_status in SKIPPED_STATUSES or node_status in FAILURE_STATUSES: self._set_graph_from_manifest(add_test_edges=add_test_edges) for dep_node_id in self.graph.get_dependent_nodes( # type: ignore[reportUnknownMemberType] UniqueId(node_id) ): # type: ignore[reportUnknownMemberType] self._skipped_nodes.add(dep_node_id) # type: ignore[reportUnknownMemberType] # Create dispatch table for O(1) routing (faster than if/elif for >2 branches) # Using a tuple of (handler, priority) for efficient dispatch # None value means use default logging handler _EVENT_DISPATCH = { _NODE_START: (_process_node_started_sync, 0), _NODE_FINISHED: (_process_node_finished_sync, 1), } # Create a mapping of EventLevel to numeric priority for fast comparison # Higher numbers = higher priority (more important, less verbose) # DEBUG (0) is most verbose, ERROR (4) is most important _EVENT_LEVEL_PRIORITY = { EventLevel.DEBUG: 0, EventLevel.TEST: 1, EventLevel.INFO: 2, EventLevel.WARN: 3, EventLevel.ERROR: 4, } # Get the minimum priority level we should log # If log_level is INFO (2), we log INFO (2), WARN (3), ERROR (4) # If log_level is WARN (3), we log WARN (3), ERROR (4) _min_log_priority = _EVENT_LEVEL_PRIORITY.get(log_level, 2) # Default to INFO def unified_callback(event: EventMsg) -> None: """Ultra-efficient callback that minimizes work per event. Optimization strategy: 1. Route critical events (NodeStart/NodeFinished) immediately 2. For logging events, apply early filtering BEFORE queuing: - Filter by log level (don't queue events below threshold) - Filter out events without messages - This dramatically reduces queue operations for irrelevant events 3. Single attribute access cached in local variable 4. Dictionary lookup for routing (O(1)) This is the most efficient possible implementation given dbt's callback API limitations. We cannot avoid the function call, but we minimize all other work. Performance notes: - Early filtering prevents queuing ~70-90% of events that would never be logged - Dictionary .get() is O(1) and faster than 'in' check + separate lookup - Only events that will actually be logged are queued """ # Single attribute access - cache it to avoid repeated lookups event_name = event.info.name # Single dictionary lookup handles both existence check and routing # Returns None for events not in dispatch table (fast path for logging) dispatch_result = _EVENT_DISPATCH.get(event_name) if dispatch_result is not None: # Critical event (NodeStart/NodeFinished) - always process handler, priority = dispatch_result self._queue_callback(handler, event, priority=priority) else: # Potential logging event - apply early filtering # Check log level first (cheap attribute access) event_level = event.info.level event_priority = _EVENT_LEVEL_PRIORITY.get(event_level, -1) # Skip events below our log level threshold # If log_level is INFO (2), skip DEBUG (0) and TEST (1) # If log_level is WARN (3), skip DEBUG (0), TEST (1), INFO (2) if event_priority < _min_log_priority: return # Don't queue - won't be logged anyway # Check if event has a message (cheap attribute access) # Some events might not have messages, so we skip those try: event_msg = event.info.msg # type: ignore[reportUnknownMemberType] # Skip events without messages or with empty/whitespace-only messages if not event_msg: return # No message - don't queue # Only do string operation if message exists (most events have messages) if isinstance(event_msg, str) and not event_msg.strip(): return # Whitespace-only message - don't queue except (AttributeError, TypeError): return # No message attribute - don't queue # Event passed all filters - queue for logging self._queue_callback(_process_logging_sync, event) return unified_callback def _create_logging_callback( self, task_state: NodeTaskTracker, log_level: EventLevel, context: dict[str, Any], ) -> Callable[[EventMsg], None]: """Creates a callback function for logging dbt events. DEPRECATED: This method is kept for backward compatibility but is no longer used. Use _create_unified_callback instead for better performance. """ # Start the callback processor if not already started self._start_callback_processor() def _process_logging_sync(event: EventMsg) -> None: """Actual logging logic - runs in background thread.""" # Skip logging for NodeStart and NodeFinished events - they have their own callbacks if event.info.name in ("NodeStart", "NodeFinished"): return event_data = MessageToDict(event.data, preserving_proto_field_name=True) # Handle logging for all events with node_info if event_data.get("node_info"): node_id = self._get_dbt_event_node_id(event) # Skip logging for skipped nodes if node_id not in self._skipped_nodes: flow_run_context: Optional[dict[str, Any]] = context.get( "flow_run_context" ) logger = task_state.get_task_logger( node_id, flow_run_context.get("flow_run") if flow_run_context else None, flow_run_context.get("flow") if flow_run_context else None, ) else: logger = None else: # Get logger for events without node_info try: with hydrated_context(context) as run_context: logger = get_run_logger(run_context) except MissingContextError: logger = None # Log the event if logger is available if logger is not None: logger.setLevel(log_level.value.upper()) if ( event.info.level == EventLevel.DEBUG or event.info.level == EventLevel.TEST ): logger.debug(self.get_dbt_event_msg(event)) elif event.info.level == EventLevel.INFO: logger.info(self.get_dbt_event_msg(event)) elif event.info.level == EventLevel.WARN: logger.warning(self.get_dbt_event_msg(event)) elif event.info.level == EventLevel.ERROR: logger.error(self.get_dbt_event_msg(event)) def logging_callback(event: EventMsg) -> None: """Non-blocking callback wrapper that queues logging for background processing.""" # Early filter: Skip NodeStart and NodeFinished events - they have their own callbacks if event.info.name in ("NodeStart", "NodeFinished"): return # Only queue events that will actually be processed self._queue_callback(_process_logging_sync, event) return logging_callback def _create_node_started_callback( self, task_state: NodeTaskTracker, context: dict[str, Any] ) -> Callable[[EventMsg], None]: """Creates a callback function for starting tasks when nodes start. DEPRECATED: This method is kept for backward compatibility but is no longer used. Use _create_unified_callback instead for better performance. """ # Start the callback processor if not already started self._start_callback_processor() def _process_node_started_sync(event: EventMsg) -> None: """Actual node started logic - runs in background thread.""" if event.info.name == "NodeStart": node_id = self._get_dbt_event_node_id(event) if node_id in self._skipped_nodes: return manifest_node, prefect_config = self._get_manifest_node_and_config( node_id ) if manifest_node: enable_assets = ( prefect_config.get("enable_assets", True) and not self.disable_assets ) self._call_task(task_state, manifest_node, context, enable_assets) def node_started_callback(event: EventMsg) -> None: """Non-blocking callback wrapper that queues node started processing. NodeStart events are queued with highest priority (0) to ensure tasks are created before other events for the same node are processed. """ # Early filter: Only process NodeStart events if event.info.name != "NodeStart": return # Queue with highest priority to process before other events self._queue_callback(_process_node_started_sync, event, priority=0) return node_started_callback def _create_node_finished_callback( self, task_state: NodeTaskTracker, context: dict[str, Any], add_test_edges: bool = False, ) -> Callable[[EventMsg], None]: """Creates a callback function for ending tasks when nodes finish. DEPRECATED: This method is kept for backward compatibility but is no longer used. Use _create_unified_callback instead for better performance. """ # Start the callback processor if not already started self._start_callback_processor() def _process_node_finished_sync(event: EventMsg) -> None: """Actual node finished logic - runs in background thread.""" if event.info.name == "NodeFinished": node_id = self._get_dbt_event_node_id(event) if node_id in self._skipped_nodes: return manifest_node, _ = self._get_manifest_node_and_config(node_id) if manifest_node: event_data = MessageToDict( event.data, preserving_proto_field_name=True ) # Store the status before ending the task event_message = self.get_dbt_event_msg(event) task_state.set_node_status(node_id, event_data, event_message) node_info: Optional[dict[str, Any]] = event_data.get("node_info") node_status: Optional[str] = ( node_info.get("node_status") if node_info else None ) if ( node_status in SKIPPED_STATUSES or node_status in FAILURE_STATUSES ): self._set_graph_from_manifest(add_test_edges=add_test_edges) for dep_node_id in self.graph.get_dependent_nodes( # type: ignore[reportUnknownMemberType] UniqueId(node_id) ): # type: ignore[reportUnknownMemberType] self._skipped_nodes.add(dep_node_id) # type: ignore[reportUnknownMemberType] def node_finished_callback(event: EventMsg) -> None: """Non-blocking callback wrapper that queues node finished processing. NodeFinished events are queued with medium priority (1) to ensure they're processed after NodeStart but before regular logging events. """ # Early filter: Only process NodeFinished events if event.info.name != "NodeFinished": return # Queue with medium priority (automatically set by _queue_callback) self._queue_callback(_process_node_finished_sync, event, priority=1) return node_finished_callback def _extract_flag_value( self, args: list[str], flag: str ) -> tuple[list[str], Union[str, None]]: """ Extract a flag value from args and return the modified args and the value. Args: args: List of command line arguments flag: The flag to look for (e.g., "--target-path") Returns: Tuple of (modified_args, flag_value) """ args_copy = args.copy() for i, arg in enumerate(args_copy): if arg == flag and i + 1 < len(args_copy): value = args_copy[i + 1] args_copy.pop(i) # Remove the flag args_copy.pop(i) # Remove the value return args_copy, value return args_copy, None def _update_setting_from_kwargs( self, setting_name: str, kwargs: dict[str, Any], path_converter: Optional[Callable[[Any], Any]] = None, ): """Update a setting from kwargs if present.""" if setting_name in kwargs: value = kwargs.pop(setting_name) if path_converter: value = path_converter(value) setattr(self, f"_{setting_name}", value) def _update_setting_from_cli_flag( self, args: list[str], flag: str, setting_name: str, path_converter: Optional[Callable[[str], Any]] = None, ) -> list[str]: """Update a setting from CLI flag if present.""" args_copy, value = self._extract_flag_value(args, flag) if value and path_converter: setattr(self, f"_{setting_name}", path_converter(value)) return args_copy def invoke(self, args: list[str], **kwargs: Any): """ Invokes a dbt command. Supports the same arguments as `dbtRunner.invoke()`. https://docs.getdbt.com/reference/programmatic-invocations Args: args: List of command line arguments **kwargs: Additional keyword arguments Returns: The result of the dbt command invocation """ # Handle kwargs for each setting for setting_name, _, converter in SETTINGS_CONFIG: self._update_setting_from_kwargs(setting_name, kwargs, converter) # Handle CLI flags for each setting args_copy = args.copy() for setting_name, flag, converter in SETTINGS_CONFIG: args_copy = self._update_setting_from_cli_flag( args_copy, flag, setting_name, converter ) context = serialize_context() in_flow_or_task_run = context.get("flow_run_context") or context.get( "task_run_context" ) task_state = NodeTaskTracker() add_test_edges = True if "build" in args_copy else False if "retry" in args_copy: previous_results = load_result_state( Path(self.project_dir) / self.target_path / "run_results.json" ) if not previous_results: raise ValueError( f"Cannot retry. No previous results found at target path {self.target_path}" ) previous_args = previous_results.args self.previous_command_name = previous_args.get("which") if self.previous_command_name == "build": add_test_edges = True if not self._disable_callbacks: callbacks = ( [ self._create_unified_callback( task_state, self.log_level, context, add_test_edges=add_test_edges, ), ] if in_flow_or_task_run or self._force_nodes_as_tasks else [] ) else: callbacks = [] # Determine which command is being invoked command_name = None for arg in args_copy: if not arg.startswith("-"): command_name = arg break # Build invoke_kwargs with only parameters valid for this command invoke_kwargs = {} # Get valid parameters for the command if we can determine it valid_params = None if command_name: from dbt.cli.main import cli command = cli.commands.get(command_name) if command: valid_params = {p.name for p in command.params} # Add settings to kwargs only if they're valid for the command potential_kwargs = { "profiles_dir": str(self.profiles_dir), "project_dir": str(self.project_dir), "target_path": str(self.target_path), "log_level": "none" if in_flow_or_task_run else str(self.log_level.value), "log_level_file": str(self.log_level.value), } for key, value in potential_kwargs.items(): # If we couldn't determine valid params, include all (backward compat) # Otherwise only include if it's valid for this command if valid_params is None or key in valid_params: invoke_kwargs[key] = value # Add any additional kwargs passed by the user invoke_kwargs.update(kwargs) with self.settings.resolve_profiles_yml() as profiles_dir: invoke_kwargs["profiles_dir"] = profiles_dir res = dbtRunner(callbacks=callbacks).invoke( # type: ignore[reportUnknownMemberType] kwargs_to_args(invoke_kwargs, args_copy) ) # Wait for callback queue to drain after dbt execution completes # Since dbt execution is complete, no new events will be added. # Wait for the background worker to process all remaining items. if self._event_queue is not None: self._event_queue.join() # Stop the callback processor now that all items are processed self._stop_callback_processor() if not res.success and res.exception: raise ValueError( f"Failed to invoke dbt command '{''.join(args_copy)}': {res.exception}" ) elif not res.success and self.raise_on_failure: assert isinstance(res.result, RunExecutionResult), ( "Expected run execution result from failed dbt invoke" ) failure_results = [ FAILURE_MSG.format( resource_type=result.node.resource_type.title(), resource_name=result.node.name, status=result.status, message=result.message, ) for result in res.result.results if result.status in FAILURE_STATUSES ] raise ValueError( f"Failures detected during invocation of dbt command '{' '.join(args_copy)}':\n{os.linesep.join(failure_results)}" ) return res
PrefectDbtRunner
python
kamyu104__LeetCode-Solutions
Python/special-array-with-x-elements-greater-than-or-equal-x.py
{ "start": 54, "end": 516 }
class ____(object): def specialArray(self, nums): """ :type nums: List[int] :rtype: int """ MAX_NUM = 1000 count = [0]*(MAX_NUM+1) for num in nums: count[num] += 1 n = len(nums) for i in xrange(len(count)): if i == n: return i n -= count[i] return -1 # Time: O(n) # Space: O(1) # counting sort + binary search solution
Solution
python
pytorch__pytorch
test/distributed/test_c10d_nccl.py
{ "start": 153658, "end": 158699 }
class ____(MultiProcessTestCase): def setUp(self): super().setUp() nccl_debug_file = tempfile.NamedTemporaryFile() nccl_env = { # TORCH_NCCL_BLOCKING_WAIT overrides TORCH_NCCL_ASYNC_ERROR_HANDLING hence tests # that use TORCH_NCCL_BLOCKING_WAIT will test it as expected. "TORCH_NCCL_ASYNC_ERROR_HANDLING": "1", "NCCL_ALGO": "NVLS", "NCCL_DEBUG": "INFO", "NCCL_DEBUG_SUBSYS": "NVLS", "NCCL_DEBUG_FILE": nccl_debug_file.name, } if torch.cuda.nccl.version() >= (2, 24, 3): nccl_env["NCCL_DEBUG_SUBSYS"] = "REG,TUNING" self.env_patcher = mock.patch.dict(os.environ, nccl_env) self.env_patcher.start() self._spawn_processes() def tearDown(self): self.env_patcher.stop() super().tearDown() try: os.remove(self.file_name) except OSError: pass @requires_nccl() @requires_nccl_version((2, 19), "Need NCCL 2.19 for user buffer registration") @skip_if_lt_x_gpu(4) @requires_multicast_support() def test_nccl_user_buffer_registration(self): store = c10d.FileStore(self.file_name, self.world_size) device = torch.device(f"cuda:{self.rank}") c10d.init_process_group( backend="nccl", rank=self.rank, world_size=self.world_size, store=store, device_id=device, ) torch.cuda.set_device(self.rank) pg = c10d.distributed_c10d._get_default_group() backend = pg._get_backend(torch.device(device)) # Use NCCL memory allocator pool = torch.cuda.MemPool(backend.mem_allocator) # allocate memory with ncclMemAlloc with torch.cuda.use_mem_pool(pool): tensor = torch.arange(1024 * 1024 * 2, device=device) # register buffers to NCCL backend.register_mem_pool(pool) # allreduce now should use NVIDIA Switches pg.allreduce(tensor).wait() torch.cuda.synchronize(device=device) # de-register buffers from NCCL backend.deregister_mem_pool(pool) # clean up memory del tensor, pool with open(os.environ["NCCL_DEBUG_FILE"]) as f: nccl_debug_file_content = f.read() # if buffers were registered and NVLS reduction ran, NCCL_DEBUG # should show successful registration in debug output if torch.cuda.nccl.version() >= (2, 24, 3): self.assertRegex( nccl_debug_file_content, "successfully registered NVLS" ) else: self.assertRegex(nccl_debug_file_content, "local-registered") @requires_nccl() @requires_nccl_version((2, 27), "Need NCCL 2.27 for window registration") @skip_if_lt_x_gpu(4) @requires_multicast_support() def test_nccl_window_registration(self): store = c10d.FileStore(self.file_name, self.world_size) device = torch.device(f"cuda:{self.rank}") with torch.cuda.device(device): # Eager init the nccl comm so that we don't implicitly create one during register_mem_pool c10d.init_process_group( backend="nccl", rank=self.rank, world_size=self.world_size, store=store, device_id=device, ) pg = c10d.distributed_c10d._get_default_group() backend = pg._get_backend(torch.device(device)) # Use NCCL memory allocator # enable symmetric memory usage in NCCL pool = torch.cuda.MemPool(backend.mem_allocator) # allocate memory with ncclMemAlloc # note: symmetric kernels are not available for dtypes like torch.int64 with torch.cuda.use_mem_pool(pool): tensor = torch.arange( 1024 * 1024 * 2, device=device, dtype=torch.float32 ) # register buffers to NCCL backend.register_mem_pool(pool, symm=True) # allreduce now should use NVIDIA Switches pg.allreduce(tensor).wait() # check that further allocations are also registered with torch.cuda.use_mem_pool(pool): tensor = torch.arange( 1024 * 1024 * 2, device=device, dtype=torch.float32 ) pg.allreduce(tensor).wait() torch.cuda.synchronize(device=device) # de-register buffers from NCCL backend.deregister_mem_pool(pool) # clean up memory del tensor, pool with open(os.environ["NCCL_DEBUG_FILE"]) as f: nccl_debug_file_content = f.read() # if buffers were registered and symmetric kernels ran, NCCL_DEBUG # should show successful registration in debug output self.assertRegex(nccl_debug_file_content, "Symmetric")
NcclUserBufferRegistrationTest
python
pydantic__pydantic
tests/mypy/modules/plugin_strict_fields.py
{ "start": 40, "end": 191 }
class ____(BaseModel): a: int b: int = Field(strict=True) c: int = Field(strict=False) # expected error: b Model(a='1', b='2', c='3')
Model
python
walkccc__LeetCode
solutions/2399. Check Distances Between Same Letters/2399.py
{ "start": 0, "end": 336 }
class ____: def checkDistances(self, s: str, distance: list[int]) -> bool: firstSeenIndex = [-1] * 26 for i, c in enumerate(s): j = ord(c) - ord('a') prevIndex = firstSeenIndex[j] if prevIndex != -1 and i - prevIndex - 1 != distance[j]: return False firstSeenIndex[j] = i return True
Solution
python
viewflow__viewflow
tests/test_urls__base.py
{ "start": 608, "end": 1150 }
class ____(Viewset): app_name = "root" index_path = path( "", TemplateView.as_view(template_name="viewflow/base.html"), name="index" ) nested_path = route("test/", NestedViewset()) nested2_path = route("nested2/", NestedViewset(app_name="nested2")) # check here that route_url mounted second time successfully nested3_path = route("inherited/", InheritedViewset(app_name="nested2")) urlconfig = RootViewset() urlpatterns = [path("", urlconfig.urls)] @override_settings(ROOT_URLCONF=__name__)
RootViewset
python
Netflix__metaflow
metaflow/decorators.py
{ "start": 2822, "end": 3268 }
class ____(MetaflowException): headline = "Unknown flow decorator" def __init__(self, deconame): decos = ", ".join(FlowMutatorMeta.all_decorators().keys()) msg = ( "Unknown flow decorator *{deconame}*. The following decorators are " "supported: *{decos}*".format(deconame=deconame, decos=decos) ) super(UnknownFlowDecoratorException, self).__init__(msg)
UnknownFlowDecoratorException
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-confluence/llama_index/readers/confluence/event.py
{ "start": 875, "end": 1122 }
class ____(BaseEvent): """Event emitted when a page is successfully processed.""" page_id: str document: Document @classmethod def class_name(cls) -> str: return "PageDataFetchCompletedEvent"
PageDataFetchCompletedEvent
python
pytorch__pytorch
torch/distributed/_tools/fake_collectives.py
{ "start": 4815, "end": 11810 }
class ____: # Static sets for performance optimization PG_ARG_1 = { c10d.broadcast_.default, c10d.allreduce_.default, c10d.reduce_.default, c10d.send.default, c10d.recv_.default, c10d.recv_any_source_.default, c10d.barrier.default, # c10d.allreduce_coalesced_.default } PG_ARG_2 = { c10d.allgather_.default, c10d._allgather_base_.default, c10d.reduce_scatter_.default, c10d._reduce_scatter_base_.default, c10d.gather_.default, c10d.scatter_.default, c10d.alltoall_.default, c10d.alltoall_base_.default, # c10d.allgather_coalesced_.default, # c10d.allgather_into_tensor_coalesced_.default # c10d.reduce_scatter_tensor_coalesced_.default } PG_ARG_3 = { _c10d_functional.broadcast.default, _c10d_functional.broadcast_.default, _c10d_functional.all_reduce.default, _c10d_functional.all_reduce_.default, _c10d_functional.all_reduce_coalesced.default, _c10d_functional.all_reduce_coalesced_.default, _c10d_functional.all_gather_into_tensor.default, _c10d_functional.all_gather_into_tensor_out.default, _c10d_functional_autograd.all_gather_into_tensor.default, _c10d_functional.all_gather_into_tensor_coalesced.default, } PG_ARG_4 = { _c10d_functional.reduce_scatter_tensor.default, _c10d_functional.reduce_scatter_tensor_coalesced.default, _c10d_functional_autograd.reduce_scatter_tensor.default, _c10d_functional.all_to_all_single.default, _c10d_functional_autograd.all_to_all_single.default, _dtensor.shard_dim_alltoall.default, } WK_ARG_1 = { c10d.broadcast_.default, c10d.allreduce_.default, c10d.allgather_.default, c10d.reduce_scatter_.default, c10d._reduce_scatter_base_.default, c10d._allgather_base_.default, c10d.scatter_.default, c10d.alltoall_.default, } WK = { c10d.send.default, c10d.recv_.default, c10d.recv_any_source_.default, c10d.reduce_.default, c10d.gather_.default, c10d.alltoall_base_.default, c10d.barrier.default, } COMM_TENSOR_ARG_0 = { c10d.allreduce_.default, c10d.send.default, c10d.recv_.default, c10d.recv_any_source_.default, c10d.allgather_.default, c10d.gather_.default, c10d.reduce_.default, c10d.broadcast_.default, _c10d_functional.all_reduce_coalesced.default, _c10d_functional.all_reduce_coalesced_.default, # c10d.allreduce_coalesced_.default # c10d.allgather_coalesced_.default # c10d.allgather_into_tensor_coalesced_.default, } COMM_TENSOR_ARG_1 = { c10d.reduce_scatter_.default, c10d.scatter_.default, # c10d.reduce_scatter_tensor_coalesced_.default, } COMM_TENSOR_ARG_RES = { _c10d_functional.all_gather_into_tensor.default, _c10d_functional_autograd.all_gather_into_tensor.default, } COMM_TENSOR_SINGLE_UNTYPED_STORAGE = { c10d._allgather_base_.default, _c10d_functional.broadcast.default, _c10d_functional.broadcast_.default, _c10d_functional.all_reduce.default, _c10d_functional.all_reduce_.default, _c10d_functional.reduce_scatter_tensor.default, _c10d_functional_autograd.reduce_scatter_tensor.default, } COMM_TENSOR_ARG_0_AND_RES = { _c10d_functional.all_to_all_single.default, _c10d_functional_autograd.all_to_all_single.default, _dtensor.shard_dim_alltoall.default, } COMM_TENSOR_RES_SUM = { _c10d_functional.all_gather_into_tensor_coalesced.default, _c10d_functional.reduce_scatter_tensor_coalesced.default, } @staticmethod def sum_tensors(arg: Any) -> int: """Calculate total memory consumed by the tensors in the argument.""" total_memory = 0 def sum_bytes(t: torch.Tensor) -> None: nonlocal total_memory total_memory += t.untyped_storage().nbytes() tree_map_only(torch.Tensor, sum_bytes, arg) return total_memory @staticmethod def get_process_group(func, args) -> ProcessGroup: # type: ignore[no-untyped-def] """Retrieve the process group for collective operations, except `wait_tensor`.""" if func in CollectiveOp.PG_ARG_1: return ProcessGroup.unbox(args[1]) if func in CollectiveOp.PG_ARG_2: return ProcessGroup.unbox(args[2]) if func in CollectiveOp.PG_ARG_3: return _resolve_process_group(args[2]) if func in CollectiveOp.PG_ARG_4: return _resolve_process_group(args[3]) raise TypeError(f"Func {func} not found in {collective_ops}") @staticmethod def get_comm_tensor_size(func, res, args, kwargs) -> int: # type: ignore[no-untyped-def] """Compute the communication tensor size, except for `wait_tensor`, `barrier`, and `monitored_barrier`.""" if func in CollectiveOp.COMM_TENSOR_ARG_0: return CollectiveOp.sum_tensors(args[0]) if func in CollectiveOp.COMM_TENSOR_ARG_1: return CollectiveOp.sum_tensors(args[1]) if func in CollectiveOp.COMM_TENSOR_ARG_RES: return res.untyped_storage().nbytes() if func in CollectiveOp.COMM_TENSOR_SINGLE_UNTYPED_STORAGE: return args[0].untyped_storage().nbytes() if func is c10d._reduce_scatter_base_.default: return args[1].untyped_storage().nbytes() if func is c10d.alltoall_.default: # TODO(@sanketpurandare) - Confirm size computation return max( CollectiveOp.sum_tensors(args[0]), CollectiveOp.sum_tensors(args[1]) ) if func is c10d.alltoall_base_.default: # TODO(@sanketpurandare) - Confirm size computation return max( args[0].untyped_storage().nbytes(), args[1].untyped_storage().nbytes() ) if func == _c10d_functional.all_gather_into_tensor_out.default: return args[-1].untyped_storage().nbytes() if func in CollectiveOp.COMM_TENSOR_RES_SUM: return CollectiveOp.sum_tensors(res) if func in CollectiveOp.COMM_TENSOR_ARG_0_AND_RES: # TODO(@sanketpurandare) - Confirm size computation return args[0].untyped_storage().nbytes() + res.untyped_storage().nbytes() raise TypeError(f"Unknown function: {func} in {collective_ops}") @staticmethod def get_work(func, res) -> Work: # type: ignore[no-untyped-def] if func in CollectiveOp.WK: return FakeWork.unbox(res) elif func in CollectiveOp.WK_ARG_1: return FakeWork.unbox(res[1]) raise TypeError(f"Func {func} not found in {collective_ops}")
CollectiveOp
python
mwaskom__seaborn
seaborn/matrix.py
{ "start": 25447, "end": 47382 }
class ____(Grid): def __init__(self, data, pivot_kws=None, z_score=None, standard_scale=None, figsize=None, row_colors=None, col_colors=None, mask=None, dendrogram_ratio=None, colors_ratio=None, cbar_pos=None): """Grid object for organizing clustered heatmap input on to axes""" if _no_scipy: raise RuntimeError("ClusterGrid requires scipy to be available") if isinstance(data, pd.DataFrame): self.data = data else: self.data = pd.DataFrame(data) self.data2d = self.format_data(self.data, pivot_kws, z_score, standard_scale) self.mask = _matrix_mask(self.data2d, mask) self._figure = plt.figure(figsize=figsize) self.row_colors, self.row_color_labels = \ self._preprocess_colors(data, row_colors, axis=0) self.col_colors, self.col_color_labels = \ self._preprocess_colors(data, col_colors, axis=1) try: row_dendrogram_ratio, col_dendrogram_ratio = dendrogram_ratio except TypeError: row_dendrogram_ratio = col_dendrogram_ratio = dendrogram_ratio try: row_colors_ratio, col_colors_ratio = colors_ratio except TypeError: row_colors_ratio = col_colors_ratio = colors_ratio width_ratios = self.dim_ratios(self.row_colors, row_dendrogram_ratio, row_colors_ratio) height_ratios = self.dim_ratios(self.col_colors, col_dendrogram_ratio, col_colors_ratio) nrows = 2 if self.col_colors is None else 3 ncols = 2 if self.row_colors is None else 3 self.gs = gridspec.GridSpec(nrows, ncols, width_ratios=width_ratios, height_ratios=height_ratios) self.ax_row_dendrogram = self._figure.add_subplot(self.gs[-1, 0]) self.ax_col_dendrogram = self._figure.add_subplot(self.gs[0, -1]) self.ax_row_dendrogram.set_axis_off() self.ax_col_dendrogram.set_axis_off() self.ax_row_colors = None self.ax_col_colors = None if self.row_colors is not None: self.ax_row_colors = self._figure.add_subplot( self.gs[-1, 1]) if self.col_colors is not None: self.ax_col_colors = self._figure.add_subplot( self.gs[1, -1]) self.ax_heatmap = self._figure.add_subplot(self.gs[-1, -1]) if cbar_pos is None: self.ax_cbar = self.cax = None else: # Initialize the colorbar axes in the gridspec so that tight_layout # works. We will move it where it belongs later. This is a hack. self.ax_cbar = self._figure.add_subplot(self.gs[0, 0]) self.cax = self.ax_cbar # Backwards compatibility self.cbar_pos = cbar_pos self.dendrogram_row = None self.dendrogram_col = None def _preprocess_colors(self, data, colors, axis): """Preprocess {row/col}_colors to extract labels and convert colors.""" labels = None if colors is not None: if isinstance(colors, (pd.DataFrame, pd.Series)): # If data is unindexed, raise if (not hasattr(data, "index") and axis == 0) or ( not hasattr(data, "columns") and axis == 1 ): axis_name = "col" if axis else "row" msg = (f"{axis_name}_colors indices can't be matched with data " f"indices. Provide {axis_name}_colors as a non-indexed " "datatype, e.g. by using `.to_numpy()``") raise TypeError(msg) # Ensure colors match data indices if axis == 0: colors = colors.reindex(data.index) else: colors = colors.reindex(data.columns) # Replace na's with white color # TODO We should set these to transparent instead colors = colors.astype(object).fillna('white') # Extract color values and labels from frame/series if isinstance(colors, pd.DataFrame): labels = list(colors.columns) colors = colors.T.values else: if colors.name is None: labels = [""] else: labels = [colors.name] colors = colors.values colors = _convert_colors(colors) return colors, labels def format_data(self, data, pivot_kws, z_score=None, standard_scale=None): """Extract variables from data or use directly.""" # Either the data is already in 2d matrix format, or need to do a pivot if pivot_kws is not None: data2d = data.pivot(**pivot_kws) else: data2d = data if z_score is not None and standard_scale is not None: raise ValueError( 'Cannot perform both z-scoring and standard-scaling on data') if z_score is not None: data2d = self.z_score(data2d, z_score) if standard_scale is not None: data2d = self.standard_scale(data2d, standard_scale) return data2d @staticmethod def z_score(data2d, axis=1): """Standarize the mean and variance of the data axis Parameters ---------- data2d : pandas.DataFrame Data to normalize axis : int Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. Returns ------- normalized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis. """ if axis == 1: z_scored = data2d else: z_scored = data2d.T z_scored = (z_scored - z_scored.mean()) / z_scored.std() if axis == 1: return z_scored else: return z_scored.T @staticmethod def standard_scale(data2d, axis=1): """Divide the data by the difference between the max and min Parameters ---------- data2d : pandas.DataFrame Data to normalize axis : int Which axis to normalize across. If 0, normalize across rows, if 1, normalize across columns. Returns ------- standardized : pandas.DataFrame Noramlized data with a mean of 0 and variance of 1 across the specified axis. """ # Normalize these values to range from 0 to 1 if axis == 1: standardized = data2d else: standardized = data2d.T subtract = standardized.min() standardized = (standardized - subtract) / ( standardized.max() - standardized.min()) if axis == 1: return standardized else: return standardized.T def dim_ratios(self, colors, dendrogram_ratio, colors_ratio): """Get the proportions of the figure taken up by each axes.""" ratios = [dendrogram_ratio] if colors is not None: # Colors are encoded as rgb, so there is an extra dimension if np.ndim(colors) > 2: n_colors = len(colors) else: n_colors = 1 ratios += [n_colors * colors_ratio] # Add the ratio for the heatmap itself ratios.append(1 - sum(ratios)) return ratios @staticmethod def color_list_to_matrix_and_cmap(colors, ind, axis=0): """Turns a list of colors into a numpy matrix and matplotlib colormap These arguments can now be plotted using heatmap(matrix, cmap) and the provided colors will be plotted. Parameters ---------- colors : list of matplotlib colors Colors to label the rows or columns of a dataframe. ind : list of ints Ordering of the rows or columns, to reorder the original colors by the clustered dendrogram order axis : int Which axis this is labeling Returns ------- matrix : numpy.array A numpy array of integer values, where each indexes into the cmap cmap : matplotlib.colors.ListedColormap """ try: mpl.colors.to_rgb(colors[0]) except ValueError: # We have a 2D color structure m, n = len(colors), len(colors[0]) if not all(len(c) == n for c in colors[1:]): raise ValueError("Multiple side color vectors must have same size") else: # We have one vector of colors m, n = 1, len(colors) colors = [colors] # Map from unique colors to colormap index value unique_colors = {} matrix = np.zeros((m, n), int) for i, inner in enumerate(colors): for j, color in enumerate(inner): idx = unique_colors.setdefault(color, len(unique_colors)) matrix[i, j] = idx # Reorder for clustering and transpose for axis matrix = matrix[:, ind] if axis == 0: matrix = matrix.T cmap = mpl.colors.ListedColormap(list(unique_colors)) return matrix, cmap def plot_dendrograms(self, row_cluster, col_cluster, metric, method, row_linkage, col_linkage, tree_kws): # Plot the row dendrogram if row_cluster: self.dendrogram_row = dendrogram( self.data2d, metric=metric, method=method, label=False, axis=0, ax=self.ax_row_dendrogram, rotate=True, linkage=row_linkage, tree_kws=tree_kws ) else: self.ax_row_dendrogram.set_xticks([]) self.ax_row_dendrogram.set_yticks([]) # PLot the column dendrogram if col_cluster: self.dendrogram_col = dendrogram( self.data2d, metric=metric, method=method, label=False, axis=1, ax=self.ax_col_dendrogram, linkage=col_linkage, tree_kws=tree_kws ) else: self.ax_col_dendrogram.set_xticks([]) self.ax_col_dendrogram.set_yticks([]) despine(ax=self.ax_row_dendrogram, bottom=True, left=True) despine(ax=self.ax_col_dendrogram, bottom=True, left=True) def plot_colors(self, xind, yind, **kws): """Plots color labels between the dendrogram and the heatmap Parameters ---------- heatmap_kws : dict Keyword arguments heatmap """ # Remove any custom colormap and centering # TODO this code has consistently caused problems when we # have missed kwargs that need to be excluded that it might # be better to rewrite *in*clusively. kws = kws.copy() kws.pop('cmap', None) kws.pop('norm', None) kws.pop('center', None) kws.pop('annot', None) kws.pop('vmin', None) kws.pop('vmax', None) kws.pop('robust', None) kws.pop('xticklabels', None) kws.pop('yticklabels', None) # Plot the row colors if self.row_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.row_colors, yind, axis=0) # Get row_color labels if self.row_color_labels is not None: row_color_labels = self.row_color_labels else: row_color_labels = False heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_row_colors, xticklabels=row_color_labels, yticklabels=False, **kws) # Adjust rotation of labels if row_color_labels is not False: plt.setp(self.ax_row_colors.get_xticklabels(), rotation=90) else: despine(self.ax_row_colors, left=True, bottom=True) # Plot the column colors if self.col_colors is not None: matrix, cmap = self.color_list_to_matrix_and_cmap( self.col_colors, xind, axis=1) # Get col_color labels if self.col_color_labels is not None: col_color_labels = self.col_color_labels else: col_color_labels = False heatmap(matrix, cmap=cmap, cbar=False, ax=self.ax_col_colors, xticklabels=False, yticklabels=col_color_labels, **kws) # Adjust rotation of labels, place on right side if col_color_labels is not False: self.ax_col_colors.yaxis.tick_right() plt.setp(self.ax_col_colors.get_yticklabels(), rotation=0) else: despine(self.ax_col_colors, left=True, bottom=True) def plot_matrix(self, colorbar_kws, xind, yind, **kws): self.data2d = self.data2d.iloc[yind, xind] self.mask = self.mask.iloc[yind, xind] # Try to reorganize specified tick labels, if provided xtl = kws.pop("xticklabels", "auto") try: xtl = np.asarray(xtl)[xind] except (TypeError, IndexError): pass ytl = kws.pop("yticklabels", "auto") try: ytl = np.asarray(ytl)[yind] except (TypeError, IndexError): pass # Reorganize the annotations to match the heatmap annot = kws.pop("annot", None) if annot is None or annot is False: pass else: if isinstance(annot, bool): annot_data = self.data2d else: annot_data = np.asarray(annot) if annot_data.shape != self.data2d.shape: err = "`data` and `annot` must have same shape." raise ValueError(err) annot_data = annot_data[yind][:, xind] annot = annot_data # Setting ax_cbar=None in clustermap call implies no colorbar kws.setdefault("cbar", self.ax_cbar is not None) heatmap(self.data2d, ax=self.ax_heatmap, cbar_ax=self.ax_cbar, cbar_kws=colorbar_kws, mask=self.mask, xticklabels=xtl, yticklabels=ytl, annot=annot, **kws) ytl = self.ax_heatmap.get_yticklabels() ytl_rot = None if not ytl else ytl[0].get_rotation() self.ax_heatmap.yaxis.set_ticks_position('right') self.ax_heatmap.yaxis.set_label_position('right') if ytl_rot is not None: ytl = self.ax_heatmap.get_yticklabels() plt.setp(ytl, rotation=ytl_rot) tight_params = dict(h_pad=.02, w_pad=.02) if self.ax_cbar is None: self._figure.tight_layout(**tight_params) else: # Turn the colorbar axes off for tight layout so that its # ticks don't interfere with the rest of the plot layout. # Then move it. self.ax_cbar.set_axis_off() self._figure.tight_layout(**tight_params) self.ax_cbar.set_axis_on() self.ax_cbar.set_position(self.cbar_pos) def plot(self, metric, method, colorbar_kws, row_cluster, col_cluster, row_linkage, col_linkage, tree_kws, **kws): # heatmap square=True sets the aspect ratio on the axes, but that is # not compatible with the multi-axes layout of clustergrid if kws.get("square", False): msg = "``square=True`` ignored in clustermap" warnings.warn(msg) kws.pop("square") colorbar_kws = {} if colorbar_kws is None else colorbar_kws self.plot_dendrograms(row_cluster, col_cluster, metric, method, row_linkage=row_linkage, col_linkage=col_linkage, tree_kws=tree_kws) try: xind = self.dendrogram_col.reordered_ind except AttributeError: xind = np.arange(self.data2d.shape[1]) try: yind = self.dendrogram_row.reordered_ind except AttributeError: yind = np.arange(self.data2d.shape[0]) self.plot_colors(xind, yind, **kws) self.plot_matrix(colorbar_kws, xind, yind, **kws) return self def clustermap( data, *, pivot_kws=None, method='average', metric='euclidean', z_score=None, standard_scale=None, figsize=(10, 10), cbar_kws=None, row_cluster=True, col_cluster=True, row_linkage=None, col_linkage=None, row_colors=None, col_colors=None, mask=None, dendrogram_ratio=.2, colors_ratio=0.03, cbar_pos=(.02, .8, .05, .18), tree_kws=None, **kwargs ): """ Plot a matrix dataset as a hierarchically-clustered heatmap. This function requires scipy to be available. Parameters ---------- data : 2D array-like Rectangular data for clustering. Cannot contain NAs. pivot_kws : dict, optional If `data` is a tidy dataframe, can provide keyword arguments for pivot to create a rectangular dataframe. method : str, optional Linkage method to use for calculating clusters. See :func:`scipy.cluster.hierarchy.linkage` documentation for more information. metric : str, optional Distance metric to use for the data. See :func:`scipy.spatial.distance.pdist` documentation for more options. To use different metrics (or methods) for rows and columns, you may construct each linkage matrix yourself and provide them as `{row,col}_linkage`. z_score : int or None, optional Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores for the rows or the columns. Z scores are: z = (x - mean)/std, so values in each row (column) will get the mean of the row (column) subtracted, then divided by the standard deviation of the row (column). This ensures that each row (column) has mean of 0 and variance of 1. standard_scale : int or None, optional Either 0 (rows) or 1 (columns). Whether or not to standardize that dimension, meaning for each row or column, subtract the minimum and divide each by its maximum. figsize : tuple of (width, height), optional Overall size of the figure. cbar_kws : dict, optional Keyword arguments to pass to `cbar_kws` in :func:`heatmap`, e.g. to add a label to the colorbar. {row,col}_cluster : bool, optional If ``True``, cluster the {rows, columns}. {row,col}_linkage : :class:`numpy.ndarray`, optional Precomputed linkage matrix for the rows or columns. See :func:`scipy.cluster.hierarchy.linkage` for specific formats. {row,col}_colors : list-like or pandas DataFrame/Series, optional List of colors to label for either the rows or columns. Useful to evaluate whether samples within a group are clustered together. Can use nested lists or DataFrame for multiple color levels of labeling. If given as a :class:`pandas.DataFrame` or :class:`pandas.Series`, labels for the colors are extracted from the DataFrames column names or from the name of the Series. DataFrame/Series colors are also matched to the data by their index, ensuring colors are drawn in the correct order. mask : bool array or DataFrame, optional If passed, data will not be shown in cells where `mask` is True. Cells with missing values are automatically masked. Only used for visualizing, not for calculating. {dendrogram,colors}_ratio : float, or pair of floats, optional Proportion of the figure size devoted to the two marginal elements. If a pair is given, they correspond to (row, col) ratios. cbar_pos : tuple of (left, bottom, width, height), optional Position of the colorbar axes in the figure. Setting to ``None`` will disable the colorbar. tree_kws : dict, optional Parameters for the :class:`matplotlib.collections.LineCollection` that is used to plot the lines of the dendrogram tree. kwargs : other keyword arguments All other keyword arguments are passed to :func:`heatmap`. Returns ------- :class:`ClusterGrid` A :class:`ClusterGrid` instance. See Also -------- heatmap : Plot rectangular data as a color-encoded matrix. Notes ----- The returned object has a ``savefig`` method that should be used if you want to save the figure object without clipping the dendrograms. To access the reordered row indices, use: ``clustergrid.dendrogram_row.reordered_ind`` Column indices, use: ``clustergrid.dendrogram_col.reordered_ind`` Examples -------- .. include:: ../docstrings/clustermap.rst """ if _no_scipy: raise RuntimeError("clustermap requires scipy to be available") plotter = ClusterGrid(data, pivot_kws=pivot_kws, figsize=figsize, row_colors=row_colors, col_colors=col_colors, z_score=z_score, standard_scale=standard_scale, mask=mask, dendrogram_ratio=dendrogram_ratio, colors_ratio=colors_ratio, cbar_pos=cbar_pos) return plotter.plot(metric=metric, method=method, colorbar_kws=cbar_kws, row_cluster=row_cluster, col_cluster=col_cluster, row_linkage=row_linkage, col_linkage=col_linkage, tree_kws=tree_kws, **kwargs)
ClusterGrid
python
astropy__astropy
astropy/coordinates/angles/errors.py
{ "start": 2818, "end": 3359 }
class ____(RangeError): """ Raised when an second value (time) is not in the range [0,60]. Parameters ---------- second : int, float Examples -------- .. code-block:: python if not 0 <= sec < 60: raise IllegalSecondError(second) """ def __init__(self, second): self.second = second def __str__(self): return ( f"An invalid value for 'second' was found ('{self.second}'); should be in" " the range [0,60)." )
IllegalSecondError
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 517792, "end": 518238 }
class ____(NumBinopNode): # '-' operator. def compute_c_result_type(self, type1, type2): if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum): return type1 elif (type1.is_ptr or type1.is_array) and (type2.is_ptr or type2.is_array): return PyrexTypes.c_ptrdiff_t_type else: return NumBinopNode.compute_c_result_type( self, type1, type2)
SubNode
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/descriptor1.py
{ "start": 2648, "end": 3645 }
class ____: desc1: Descriptor1 desc2: Descriptor2 desc3: Descriptor3 desc4: Descriptor4 desc5: Descriptor5 desc6: Descriptor6[int | None, int | None] def func4(obj: B) -> Literal[3]: obj.desc1 = None b: None = obj.desc1 obj.desc1 = 3 v1 = obj.desc1 + 1 return obj.desc1 def func5(obj: B) -> Literal[3]: obj.desc2 = 3 # This should generate an error because desc2 isn't # narrowed in this case. b: int = obj.desc2 # This should generate an error because desc2 isn't # narrowed in this case. return obj.desc2 def func6(obj: B) -> Literal[3]: obj.desc3 = 3 b: int = obj.desc3 # This should generate an error because prop2 isn't # narrowed in this case. return obj.desc3 def func7(obj: B): obj.desc4 = 3 reveal_type(obj.desc4, expected_text="str") obj.desc5 = 3 reveal_type(obj.desc5, expected_text="int") obj.desc6 = 1 reveal_type(obj.desc6, expected_text="Literal[1]")
B
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/bulk_persistence.py
{ "start": 21890, "end": 40514 }
class ____(_ORMDMLState): class default_update_options(Options): _dml_strategy: DMLStrategyArgument = "auto" _synchronize_session: SynchronizeSessionArgument = "auto" _can_use_returning: bool = False _is_delete_using: bool = False _is_update_from: bool = False _autoflush: bool = True _subject_mapper: Optional[Mapper[Any]] = None _resolved_values = EMPTY_DICT _eval_condition = None _matched_rows = None _identity_token = None _populate_existing: bool = False @classmethod def can_use_returning( cls, dialect: Dialect, mapper: Mapper[Any], *, is_multitable: bool = False, is_update_from: bool = False, is_delete_using: bool = False, is_executemany: bool = False, ) -> bool: raise NotImplementedError() @classmethod def orm_pre_session_exec( cls, session, statement, params, execution_options, bind_arguments, is_pre_event, ): ( update_options, execution_options, ) = _BulkUDCompileState.default_update_options.from_execution_options( "_sa_orm_update_options", { "synchronize_session", "autoflush", "populate_existing", "identity_token", "is_delete_using", "is_update_from", "dml_strategy", }, execution_options, statement._execution_options, ) bind_arguments["clause"] = statement try: plugin_subject = statement._propagate_attrs["plugin_subject"] except KeyError: assert False, "statement had 'orm' plugin but no plugin_subject" else: if plugin_subject: bind_arguments["mapper"] = plugin_subject.mapper update_options += {"_subject_mapper": plugin_subject.mapper} if "parententity" not in statement.table._annotations: update_options += {"_dml_strategy": "core_only"} elif not isinstance(params, list): if update_options._dml_strategy == "auto": update_options += {"_dml_strategy": "orm"} elif update_options._dml_strategy == "bulk": raise sa_exc.InvalidRequestError( 'Can\'t use "bulk" ORM insert strategy without ' "passing separate parameters" ) else: if update_options._dml_strategy == "auto": update_options += {"_dml_strategy": "bulk"} sync = update_options._synchronize_session if sync is not None: if sync not in ("auto", "evaluate", "fetch", False): raise sa_exc.ArgumentError( "Valid strategies for session synchronization " "are 'auto', 'evaluate', 'fetch', False" ) if update_options._dml_strategy == "bulk" and sync == "fetch": raise sa_exc.InvalidRequestError( "The 'fetch' synchronization strategy is not available " "for 'bulk' ORM updates (i.e. multiple parameter sets)" ) if not is_pre_event: if update_options._autoflush: session._autoflush() if update_options._dml_strategy == "orm": if update_options._synchronize_session == "auto": update_options = cls._do_pre_synchronize_auto( session, statement, params, execution_options, bind_arguments, update_options, ) elif update_options._synchronize_session == "evaluate": update_options = cls._do_pre_synchronize_evaluate( session, statement, params, execution_options, bind_arguments, update_options, ) elif update_options._synchronize_session == "fetch": update_options = cls._do_pre_synchronize_fetch( session, statement, params, execution_options, bind_arguments, update_options, ) elif update_options._dml_strategy == "bulk": if update_options._synchronize_session == "auto": update_options += {"_synchronize_session": "evaluate"} # indicators from the "pre exec" step that are then # added to the DML statement, which will also be part of the cache # key. The compile level create_for_statement() method will then # consume these at compiler time. statement = statement._annotate( { "synchronize_session": update_options._synchronize_session, "is_delete_using": update_options._is_delete_using, "is_update_from": update_options._is_update_from, "dml_strategy": update_options._dml_strategy, "can_use_returning": update_options._can_use_returning, } ) return ( statement, util.immutabledict(execution_options).union( {"_sa_orm_update_options": update_options} ), params, ) @classmethod def orm_setup_cursor_result( cls, session, statement, params, execution_options, bind_arguments, result, ): # this stage of the execution is called after the # do_orm_execute event hook. meaning for an extension like # horizontal sharding, this step happens *within* the horizontal # sharding event handler which calls session.execute() re-entrantly # and will occur for each backend individually. # the sharding extension then returns its own merged result from the # individual ones we return here. update_options = execution_options["_sa_orm_update_options"] if update_options._dml_strategy == "orm": if update_options._synchronize_session == "evaluate": cls._do_post_synchronize_evaluate( session, statement, result, update_options ) elif update_options._synchronize_session == "fetch": cls._do_post_synchronize_fetch( session, statement, result, update_options ) elif update_options._dml_strategy == "bulk": if update_options._synchronize_session == "evaluate": cls._do_post_synchronize_bulk_evaluate( session, params, result, update_options ) return result return cls._return_orm_returning( session, statement, params, execution_options, bind_arguments, result, ) @classmethod def _adjust_for_extra_criteria(cls, global_attributes, ext_info): """Apply extra criteria filtering. For all distinct single-table-inheritance mappers represented in the table being updated or deleted, produce additional WHERE criteria such that only the appropriate subtypes are selected from the total results. Additionally, add WHERE criteria originating from LoaderCriteriaOptions collected from the statement. """ return_crit = () adapter = ext_info._adapter if ext_info.is_aliased_class else None if ( "additional_entity_criteria", ext_info.mapper, ) in global_attributes: return_crit += tuple( ae._resolve_where_criteria(ext_info) for ae in global_attributes[ ("additional_entity_criteria", ext_info.mapper) ] if ae.include_aliases or ae.entity is ext_info ) if ext_info.mapper._single_table_criterion is not None: return_crit += (ext_info.mapper._single_table_criterion,) if adapter: return_crit = tuple(adapter.traverse(crit) for crit in return_crit) return return_crit @classmethod def _interpret_returning_rows(cls, result, mapper, rows): """return rows that indicate PK cols in mapper.primary_key position for RETURNING rows. Prior to 2.0.36, this method seemed to be written for some kind of inheritance scenario but the scenario was unused for actual joined inheritance, and the function instead seemed to perform some kind of partial translation that would remove non-PK cols if the PK cols happened to be first in the row, but not otherwise. The joined inheritance walk feature here seems to have never been used as it was always skipped by the "local_table" check. As of 2.0.36 the function strips away non-PK cols and provides the PK cols for the table in mapper PK order. """ try: if mapper.local_table is not mapper.base_mapper.local_table: # TODO: dive more into how a local table PK is used for fetch # sync, not clear if this is correct as it depends on the # downstream routine to fetch rows using # local_table.primary_key order pk_keys = result._tuple_getter(mapper.local_table.primary_key) else: pk_keys = result._tuple_getter(mapper.primary_key) except KeyError: # can't use these rows, they don't have PK cols in them # this is an unusual case where the user would have used # .return_defaults() return [] return [pk_keys(row) for row in rows] @classmethod def _get_matched_objects_on_criteria(cls, update_options, states): mapper = update_options._subject_mapper eval_condition = update_options._eval_condition raw_data = [ (state.obj(), state, state.dict) for state in states if state.mapper.isa(mapper) and not state.expired ] identity_token = update_options._identity_token if identity_token is not None: raw_data = [ (obj, state, dict_) for obj, state, dict_ in raw_data if state.identity_token == identity_token ] result = [] for obj, state, dict_ in raw_data: evaled_condition = eval_condition(obj) # caution: don't use "in ()" or == here, _EXPIRE_OBJECT # evaluates as True for all comparisons if ( evaled_condition is True or evaled_condition is evaluator._EXPIRED_OBJECT ): result.append( ( obj, state, dict_, evaled_condition is evaluator._EXPIRED_OBJECT, ) ) return result @classmethod def _eval_condition_from_statement(cls, update_options, statement): mapper = update_options._subject_mapper target_cls = mapper.class_ evaluator_compiler = evaluator._EvaluatorCompiler(target_cls) crit = () if statement._where_criteria: crit += statement._where_criteria global_attributes = {} for opt in statement._with_options: if opt._is_criteria_option: opt.get_global_criteria(global_attributes) if global_attributes: crit += cls._adjust_for_extra_criteria(global_attributes, mapper) if crit: eval_condition = evaluator_compiler.process(*crit) else: # workaround for mypy https://github.com/python/mypy/issues/14027 def _eval_condition(obj): return True eval_condition = _eval_condition return eval_condition @classmethod def _do_pre_synchronize_auto( cls, session, statement, params, execution_options, bind_arguments, update_options, ): """setup auto sync strategy "auto" checks if we can use "evaluate" first, then falls back to "fetch" evaluate is vastly more efficient for the common case where session is empty, only has a few objects, and the UPDATE statement can potentially match thousands/millions of rows. OTOH more complex criteria that fails to work with "evaluate" we would hope usually correlates with fewer net rows. """ try: eval_condition = cls._eval_condition_from_statement( update_options, statement ) except evaluator.UnevaluatableError: pass else: return update_options + { "_eval_condition": eval_condition, "_synchronize_session": "evaluate", } update_options += {"_synchronize_session": "fetch"} return cls._do_pre_synchronize_fetch( session, statement, params, execution_options, bind_arguments, update_options, ) @classmethod def _do_pre_synchronize_evaluate( cls, session, statement, params, execution_options, bind_arguments, update_options, ): try: eval_condition = cls._eval_condition_from_statement( update_options, statement ) except evaluator.UnevaluatableError as err: raise sa_exc.InvalidRequestError( 'Could not evaluate current criteria in Python: "%s". ' "Specify 'fetch' or False for the " "synchronize_session execution option." % err ) from err return update_options + { "_eval_condition": eval_condition, } @classmethod def _get_resolved_values(cls, mapper, statement): if statement._multi_values: return [] elif statement._values: return list(statement._values.items()) else: return [] @classmethod def _resolved_keys_as_propnames(cls, mapper, resolved_values): values = [] for k, v in resolved_values: if mapper and isinstance(k, expression.ColumnElement): try: attr = mapper._columntoproperty[k] except orm_exc.UnmappedColumnError: pass else: values.append((attr.key, v)) else: raise sa_exc.InvalidRequestError( "Attribute name not found, can't be " "synchronized back to objects: %r" % k ) return values @classmethod def _do_pre_synchronize_fetch( cls, session, statement, params, execution_options, bind_arguments, update_options, ): mapper = update_options._subject_mapper select_stmt = ( select(*(mapper.primary_key + (mapper.select_identity_token,))) .select_from(mapper) .options(*statement._with_options) ) select_stmt._where_criteria = statement._where_criteria # conditionally run the SELECT statement for pre-fetch, testing the # "bind" for if we can use RETURNING or not using the do_orm_execute # event. If RETURNING is available, the do_orm_execute event # will cancel the SELECT from being actually run. # # The way this is organized seems strange, why don't we just # call can_use_returning() before invoking the statement and get # answer?, why does this go through the whole execute phase using an # event? Answer: because we are integrating with extensions such # as the horizontal sharding extention that "multiplexes" an individual # statement run through multiple engines, and it uses # do_orm_execute() to do that. can_use_returning = None def skip_for_returning(orm_context: ORMExecuteState) -> Any: bind = orm_context.session.get_bind(**orm_context.bind_arguments) nonlocal can_use_returning per_bind_result = cls.can_use_returning( bind.dialect, mapper, is_update_from=update_options._is_update_from, is_delete_using=update_options._is_delete_using, is_executemany=orm_context.is_executemany, ) if can_use_returning is not None: if can_use_returning != per_bind_result: raise sa_exc.InvalidRequestError( "For synchronize_session='fetch', can't mix multiple " "backends where some support RETURNING and others " "don't" ) elif orm_context.is_executemany and not per_bind_result: raise sa_exc.InvalidRequestError( "For synchronize_session='fetch', can't use multiple " "parameter sets in ORM mode, which this backend does not " "support with RETURNING" ) else: can_use_returning = per_bind_result if per_bind_result: return _result.null_result() else: return None result = session.execute( select_stmt, params, execution_options=execution_options, bind_arguments=bind_arguments, _add_event=skip_for_returning, ) matched_rows = result.fetchall() return update_options + { "_matched_rows": matched_rows, "_can_use_returning": can_use_returning, } @CompileState.plugin_for("orm", "insert")
_BulkUDCompileState
python
huggingface__transformers
src/transformers/models/mt5/modeling_mt5.py
{ "start": 44956, "end": 54617 }
class ____(MT5PreTrainedModel, GenerationMixin): r""" Examples: ```python >>> from transformers import MT5ForConditionalGeneration, AutoTokenizer >>> model = MT5ForConditionalGeneration.from_pretrained("google/mt5-small") >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small") >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien." >>> summary = "Weiter Verhandlung in Syrien." >>> inputs = tokenizer(article, text_target=summary, return_tensors="pt") >>> outputs = model(**inputs) >>> loss = outputs.loss ```""" model_type = "mt5" config: MT5Config _keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"] _tied_weights_keys = { "encoder.embed_tokens.weight": "shared.weight", "decoder.embed_tokens.weight": "shared.weight", "lm_head.weight": "shared.weight", } # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.__init__ with T5->MT5 def __init__(self, config: MT5Config): super().__init__(config) self.model_dim = config.d_model self.shared = nn.Embedding(config.vocab_size, config.d_model) encoder_config = copy.deepcopy(config) encoder_config.is_decoder = False encoder_config.use_cache = False encoder_config.tie_encoder_decoder = False self.encoder = MT5Stack(encoder_config) decoder_config = copy.deepcopy(config) decoder_config.is_decoder = True decoder_config.tie_encoder_decoder = False decoder_config.num_layers = config.num_decoder_layers self.decoder = MT5Stack(decoder_config) self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.shared def set_input_embeddings(self, new_embeddings): self.shared = new_embeddings self.encoder.set_input_embeddings(new_embeddings) self.decoder.set_input_embeddings(new_embeddings) @auto_docstring # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.forward with google-t5/->google/, T5->MT5, t5->mt5 def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.BoolTensor] = None, encoder_outputs: Optional[tuple[tuple[torch.Tensor]]] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, decoder_inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, ) -> Union[tuple[torch.FloatTensor], Seq2SeqLMOutput]: r""" input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. MT5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for detail. [What are input IDs?](../glossary#input-ids) To know more on how to prepare `input_ids` for pretraining take a look a [MT5 Training](./mt5#training). decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids) MT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`). To know more on how to prepare `decoder_input_ids` for pretraining take a look at [MT5 Training](./mt5#training). decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ..., config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]` Examples: ```python >>> from transformers import AutoTokenizer, MT5ForConditionalGeneration >>> tokenizer = AutoTokenizer.from_pretrained("google/mt5-small") >>> model = MT5ForConditionalGeneration.from_pretrained("google/mt5-small") >>> # training >>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids >>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids >>> outputs = model(input_ids=input_ids, labels=labels) >>> loss = outputs.loss >>> logits = outputs.logits >>> # inference >>> input_ids = tokenizer( ... "summarize: studies have shown that owning a dog is good for you", return_tensors="pt" ... ).input_ids # Batch size 1 >>> outputs = model.generate(input_ids) >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True)) >>> # studies have shown that owning a dog is good for you. ```""" use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict # Encode if needed (training, first prediction pass) if encoder_outputs is None: # Convert encoder inputs in embeddings if needed encoder_outputs = self.encoder( input_ids=input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) elif return_dict and not isinstance(encoder_outputs, BaseModelOutput): encoder_outputs = BaseModelOutput( last_hidden_state=encoder_outputs[0], hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None, attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None, ) hidden_states = encoder_outputs[0] if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None: # get decoder inputs from shifting lm labels to the right decoder_input_ids = self._shift_right(labels) # Decode decoder_outputs = self.decoder( input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, inputs_embeds=decoder_inputs_embeds, past_key_values=past_key_values, encoder_hidden_states=hidden_states, encoder_attention_mask=attention_mask, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) sequence_output = decoder_outputs[0] if self.config.tie_word_embeddings: sequence_output = sequence_output * (self.model_dim**-0.5) lm_logits = self.lm_head(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss(ignore_index=-100) # move labels to correct device to enable PP labels = labels.to(lm_logits.device) loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1)) if not return_dict: output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs return ((loss,) + output) if loss is not None else output return Seq2SeqLMOutput( loss=loss, logits=lm_logits, past_key_values=decoder_outputs.past_key_values, decoder_hidden_states=decoder_outputs.hidden_states, decoder_attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions, encoder_last_hidden_state=encoder_outputs.last_hidden_state, encoder_hidden_states=encoder_outputs.hidden_states, encoder_attentions=encoder_outputs.attentions, ) # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.prepare_decoder_input_ids_from_labels def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor): return self._shift_right(labels) @auto_docstring
MT5ForConditionalGeneration
python
PrefectHQ__prefect
src/integrations/prefect-email/prefect_email/credentials.py
{ "start": 564, "end": 1848 }
class ____(Enum): """ Server used to send email. """ AOL = "smtp.aol.com" ATT = "smtp.mail.att.net" COMCAST = "smtp.comcast.net" ICLOUD = "smtp.mail.me.com" GMAIL = "smtp.gmail.com" OUTLOOK = "smtp-mail.outlook.com" YAHOO = "smtp.mail.yahoo.com" def _cast_to_enum(obj: Union[str, SMTPType], enum: Enum, restrict: bool = False): """ Casts string to an enum member, if valid; else returns the input obj, or raises a ValueError if restrict. Args: obj: A member's name of the enum. enum: An Enum class. restrict: Whether to only allow passing members from the enum. Returns: A member of the enum. """ if isinstance(obj, enum): # if already an enum member, continue return obj valid_enums = list(enum.__members__) # capitalize and try to match an enum member if obj.upper() not in valid_enums: if restrict: raise ValueError(f"Must be one of {valid_enums}; got {obj!r}") else: # primarily used for SMTPServer so that users # can pass in their custom servers not listed # as one of the SMTPServer Enum values. return obj else: return getattr(enum, obj.upper())
SMTPServer
python
django-debug-toolbar__django-debug-toolbar
tests/test_store.py
{ "start": 738, "end": 1698 }
class ____(TestCase): def test_methods_are_not_implemented(self): # Find all the non-private and dunder class methods methods = [ member for member in vars(store.BaseStore) if not member.startswith("_") ] self.assertEqual(len(methods), 7) with self.assertRaises(NotImplementedError): store.BaseStore.request_ids() with self.assertRaises(NotImplementedError): store.BaseStore.exists("") with self.assertRaises(NotImplementedError): store.BaseStore.set("") with self.assertRaises(NotImplementedError): store.BaseStore.clear() with self.assertRaises(NotImplementedError): store.BaseStore.delete("") with self.assertRaises(NotImplementedError): store.BaseStore.save_panel("", "", None) with self.assertRaises(NotImplementedError): store.BaseStore.panel("", "")
BaseStoreTestCase
python
openai__openai-python
src/openai/types/beta/realtime/response_cancel_event_param.py
{ "start": 224, "end": 630 }
class ____(TypedDict, total=False): type: Required[Literal["response.cancel"]] """The event type, must be `response.cancel`.""" event_id: str """Optional client-generated ID used to identify this event.""" response_id: str """ A specific response ID to cancel - if not provided, will cancel an in-progress response in the default conversation. """
ResponseCancelEventParam
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 8533, "end": 8783 }
class ____(PydanticValueError): code = 'set.min_items' msg_template = 'ensure this value has at least {limit_value} items' def __init__(self, *, limit_value: int) -> None: super().__init__(limit_value=limit_value)
SetMinLengthError
python
HypothesisWorks__hypothesis
hypothesis-python/tests/nocover/test_drypython_returns.py
{ "start": 1041, "end": 1222 }
class ____(Generic[_FirstType], Lawful["MappableN[_FirstType]"]): """Behaves like a functor.""" # End definition: # =============== _ValueType = TypeVar("_ValueType")
MappableN
python
google__jax
jax/_src/state/types.py
{ "start": 2152, "end": 2661 }
class ____(RefEffect): name: str = "Accum" effects.control_flow_allowed_effects.add_type(RefEffect) effects.custom_derivatives_allowed_effects.add_type(RefEffect) effects.custom_derivatives_allowed_effects.add_type(core.InternalMutableArrayEffect) effects.partial_eval_kept_effects.add_type(RefEffect) effects.remat_allowed_effects.add_type(RefEffect) StateEffect = Union[ReadEffect, WriteEffect, AccumEffect] # ## `Ref`s @tree_util.register_pytree_node_class @dataclasses.dataclass(frozen=True)
AccumEffect
python
Textualize__textual
src/textual/drivers/win32.py
{ "start": 1492, "end": 1679 }
class ____(Union): """https://docs.microsoft.com/en-us/windows/console/key-event-record-str""" _fields_ = [ ("AsciiChar", CHAR), ("UnicodeChar", WCHAR), ]
uChar
python
crytic__slither
slither/slithir/operations/new_structure.py
{ "start": 545, "end": 1740 }
class ____(Call, OperationWithLValue): def __init__( self, structure: StructureContract, lvalue: Union[TemporaryVariableSSA, TemporaryVariable], names: Optional[List[str]] = None, ) -> None: """ #### Parameters names - For calls of the form f({argName1 : arg1, ...}), the names of parameters listed in call order. Otherwise, None. """ super().__init__(names=names) assert isinstance(structure, Structure) assert is_valid_lvalue(lvalue) self._structure = structure # todo create analyze to add the contract instance self._lvalue = lvalue @property def read(self) -> List[Union[TemporaryVariableSSA, TemporaryVariable, Constant]]: return self._unroll(self.arguments) @property def structure(self) -> StructureContract: return self._structure @property def structure_name(self): return self.structure.name def __str__(self): args = [str(a) for a in self.arguments] lvalue = self.lvalue return f"{lvalue}({lvalue.type}) = new {self.structure_name}({','.join(args)})"
NewStructure
python
urllib3__urllib3
test/contrib/emscripten/conftest.py
{ "start": 5203, "end": 11857 }
class ____: def __init__( self, host: str, port: int, selenium: Any, dist_dir: Path, prefer_jspi: bool ) -> None: self.host = host self.port = port self.selenium = selenium self.dist_dir = dist_dir self.prefer_jspi = prefer_jspi def run_webworker(self, code: str) -> Any: if isinstance(code, str) and code.startswith("\n"): # we have a multiline string, fix indentation code = textwrap.dedent(code) coverage_init_code, coverage_end_code = _get_coverage_code() jspi_monkeypatch_code, jspi_unmonkeypatch_code = _get_jspi_monkeypatch_code( self.selenium.browser, self.prefer_jspi ) # the ordering of these code blocks is important - makes sure # that the first thing that happens is our wheel is loaded code = ( coverage_init_code + "\n" + jspi_monkeypatch_code + "\n" + "try:\n" + textwrap.indent(code, " ") + "\n" + "finally:\n" + textwrap.indent(jspi_unmonkeypatch_code or "pass", " ") + "\n" + coverage_end_code ) if self.selenium.browser == "firefox": # running in worker is SLOW on firefox self.selenium.set_script_timeout(30) if self.selenium.browser == "node": worker_path = str(self.dist_dir / "webworker_dev.js") self.selenium.run_js( f"""const {{ Worker, isMainThread, parentPort, workerData, }} = require('node:worker_threads'); globalThis.Worker= Worker; process.chdir('{self.dist_dir}'); """ ) else: worker_path = f"https://{self.host}:{self.port}/pyodide/webworker_dev.js" coverage_out_binary = bytes( self.selenium.run_js( f""" let worker = new Worker('{worker_path}'); let p = new Promise((res, rej) => {{ worker.onmessageerror = e => rej(e); worker.onerror = e => rej(e); worker.onmessage = e => {{ if (e.data.results) {{ res(e.data.results); }} else {{ rej(e.data.error); }} }}; worker.postMessage({{ python: {repr(code)} }}); }}); return await p; """, pyodide_checks=False, ) ) with open( f"{_get_coverage_filename('.coverage.emscripten.worker.')}", "wb" ) as outfile: outfile.write(coverage_out_binary) # run pyodide on our test server instead of on the default # pytest-pyodide one - this makes it so that # we are at the same origin as web requests to server_host @pytest.fixture() def run_from_server( selenium: Any, testserver_http: PyodideServerInfo, prefer_jspi: bool ) -> Generator[ServerRunnerInfo]: if selenium.browser != "node": # on node, we don't need to be on the same origin # so we can ignore all this addr = f"https://{testserver_http.http_host}:{testserver_http.https_port}/pyodide/test.html" selenium.goto(addr) selenium.javascript_setup() selenium.load_pyodide() selenium.initialize_pyodide() selenium.save_state() selenium.restore_state() dist_dir = testserver_http.pyodide_dist_dir yield ServerRunnerInfo( testserver_http.http_host, testserver_http.https_port, selenium, dist_dir, prefer_jspi, ) def pytest_collection_modifyitems( config: pytest.Config, items: list[pytest.Item] ) -> None: """ A pytest hook modifying collected test items for Emscripten. """ selected_tests = [] deselected_tests = [] runtime = config.getoption("--runtime", default=None) if not runtime: return for item in items: # Deselect tests which Node.js cannot run. if runtime.startswith("node"): if ( item.get_closest_marker("webworkers") or item.get_closest_marker("in_webbrowser") or item.get_closest_marker("without_jspi") ): deselected_tests.append(item) continue # Tests marked with `in_webbrowser` are only for Node.js. elif item.get_closest_marker("node_without_jspi"): deselected_tests.append(item) continue # Firefox cannot run JSPI tests. if runtime.startswith("firefox") and item.get_closest_marker("with_jspi"): deselected_tests.append(item) continue selected_tests.append(item) config.hook.pytest_deselected(items=deselected_tests) items[:] = selected_tests def pytest_generate_tests(metafunc: pytest.Metafunc) -> None: """ A pytest hook generating parametrized calls to a test function. """ # Set proper `prefer_jspi` values for tests with WebAssembly # JavaScript Promise Integration both enabled and disabled depending # on browser/Node.js support for features. if "prefer_jspi" in metafunc.fixturenames: # node only supports JSPI and doesn't support workers or # webbrowser specific tests if metafunc.config.getoption("--runtime").startswith("node"): if metafunc.definition.get_closest_marker("node_without_jspi"): can_run_with_jspi = False can_run_without_jspi = True else: can_run_with_jspi = True can_run_without_jspi = False # firefox doesn't support JSPI elif metafunc.config.getoption("--runtime").startswith("firefox"): can_run_with_jspi = False can_run_without_jspi = True else: # chrome supports JSPI on or off can_run_without_jspi = True can_run_with_jspi = True # if the function is marked to only run with or without jspi, # then disable the alternative option if metafunc.definition.get_closest_marker("with_jspi"): can_run_without_jspi = False elif metafunc.definition.get_closest_marker("without_jspi"): can_run_with_jspi = False jspi_options = [] if can_run_without_jspi: jspi_options.append(False) if can_run_with_jspi: jspi_options.append(True) metafunc.parametrize("prefer_jspi", jspi_options)
ServerRunnerInfo
python
huggingface__transformers
src/transformers/models/bamba/modeling_bamba.py
{ "start": 52764, "end": 63839 }
class ____(BambaPreTrainedModel): def __init__(self, config: BambaConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) decoder_layers = [] for i in range(config.num_hidden_layers): decoder_layers.append(BambaDecoderLayer(config, layer_idx=i, layer_type=config.layers_block_type[i])) self.layers = nn.ModuleList(decoder_layers) self._attn_implementation = config._attn_implementation self.final_layernorm = BambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = BambaRotaryEmbedding(config=config) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[HybridMambaAttentionDynamicCache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[BambaFlashAttentionKwargs], ) -> BaseModelOutputWithPast: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if self.gradient_checkpointing and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) hidden_states = inputs_embeds if use_cache and past_key_values is None: logger.warning_once( "Bamba requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. None was " "provided, so no cache will be returned." ) if cache_position is None: cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device) if position_ids is None: position_ids = cache_position.unsqueeze(0) causal_mask = self._update_causal_mask( attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions ) mamba_mask = self._update_mamba_mask(attention_mask, cache_position) position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids) all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for decoder_layer in self.layers: # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention) layer_mask = mamba_mask if decoder_layer.layer_type == "mamba" else causal_mask if output_hidden_states: all_hidden_states += (hidden_states,) layer_outputs = decoder_layer( hidden_states, attention_mask=layer_mask, position_ids=position_ids, past_key_values=past_key_values, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = layer_outputs[0] if output_attentions: if layer_outputs[1] is not None: # append attentions only of attention layers. Mamba layers return `None` as the attention weights all_self_attns += (layer_outputs[1],) hidden_states = self.final_layernorm(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) if past_key_values and not past_key_values.has_previous_state: past_key_values.has_previous_state = True next_cache = None if not use_cache else past_key_values return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, ) def _update_causal_mask( self, attention_mask: torch.Tensor, input_tensor: torch.Tensor, cache_position: torch.Tensor, past_key_values: HybridMambaAttentionDynamicCache, output_attentions: bool, ): if self.config._attn_implementation == "flash_attention_2": if attention_mask is not None and 0.0 in attention_mask: return attention_mask return None # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail # to infer the attention mask. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward if self.config._attn_implementation == "sdpa" and not output_attentions: if AttentionMaskConverter._ignore_causal_mask_sdpa( attention_mask, inputs_embeds=input_tensor, past_key_values_length=past_seen_tokens, is_training=self.training, ): return None dtype = input_tensor.dtype sequence_length = input_tensor.shape[1] target_length = ( attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else past_seen_tokens + sequence_length + 1 ) # In case the provided `attention` mask is 2D, we generate a causal mask here (4D). causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( attention_mask, sequence_length=sequence_length, target_length=target_length, dtype=dtype, cache_position=cache_position, batch_size=input_tensor.shape[0], ) if ( self.config._attn_implementation == "sdpa" and attention_mask is not None and attention_mask.device.type in ["cuda", "xpu", "npu"] and not output_attentions ): # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. # Details: https://github.com/pytorch/pytorch/issues/110213 min_dtype = torch.finfo(dtype).min causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) return causal_mask @staticmethod def _prepare_4d_causal_attention_mask_with_cache_position( attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, cache_position: torch.Tensor, batch_size: int, **kwargs, ): """ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. Args: attention_mask (`torch.Tensor`): A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`. sequence_length (`int`): The sequence length being processed. target_length (`int`): The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet. dtype (`torch.dtype`): The dtype to use for the 4D attention mask. cache_position (`torch.Tensor`): Indices depicting the position of the input sequence tokens in the sequence. batch_size (`torch.Tensor`): Batch size. """ if attention_mask is not None and attention_mask.dim() == 4: # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. causal_mask = attention_mask else: min_dtype = torch.finfo(dtype).min causal_mask = torch.full( (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device ) if sequence_length != 1: causal_mask = torch.triu(causal_mask, diagonal=1) causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1) causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) if attention_mask is not None: causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit mask_length = attention_mask.shape[-1] padding_attention_mask = (attention_mask[:, None, None, :] == attention_mask[:, None, :, None])[ :, :, -sequence_length:, : ].to(dtype) padding_mask = causal_mask[:, :, :, :mask_length] + padding_attention_mask padding_mask = padding_mask == 0 causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( padding_mask, min_dtype ) return causal_mask def _update_mamba_mask(self, attention_mask, cache_position): """ No need for zeroing states when 1. Cached forward 2. Attending to all inputs """ mamba_mask = attention_mask if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)): mamba_mask = None return mamba_mask @auto_docstring
BambaModel
python
skorch-dev__skorch
skorch/llm/classifier.py
{ "start": 30553, "end": 42864 }
class ____(_LlmBase): """Few-shot classification using a Large Language Model (LLM). This class allows you to use an LLM from Hugging Face transformers for few-shot classification. There is no training during the ``fit`` call, instead, the LLM will be prompted to predict the labels for each sample. Parameters ---------- model_name : str or None (default=None) The name of the model to use. This is the same name as used on Hugging Face Hub. For example, to use GPT2, pass ``'gpt2'``, to use the small flan-t5 model, pass ``'google/flan-t5-small'``. If the ``model_name`` parameter is passed, don't pass ``model`` or ``tokenizer`` parameters. model : torch.nn.Module or None (default=None) The model to use. This should be a PyTorch text generation model from Hugging Face Hub or a model with the same API. Most notably, the model should have a ``generate`` method. If you pass the ``model``, you should also pass the ``tokenizer``, but you shall not pass the ``model_name``. Passing the model explicitly instead of the ``model_name`` can have a few advantages. Most notably, this allows you to modify the model, e.g. changing its config or how the model is loaded. For instance, some models can only be loaded with the option ``trust_remote_code=True``. If using the ``model_name`` argument, the default settings will be used instead. Passing the model explicitly also allows you to use custom models that are not uploaded to Hugging Face Hub. tokenizer (default=None) A tokenizer that is compatible with the model. Typically, this is loaded using the ``AutoTokenizer.from_pretrained`` method provided by Hugging Face transformers. If you pass the ``tokenizer``, you should also pass the ``model``, but you should not pass the ``model_name``. prompt : str or None (default=None) The prompt to use. This is the text that will be passed to the model to generate the prediction. If no prompt is passed, a default prompt will be used. The prompt should be a Python string with three placeholders, one called ``text``, one called ``labels``, and one called ``examples``. The ``text`` placeholder will replaced by the contents from ``X`` passed to during inference and the ``labels`` placeholder will be replaced by the unique labels taken from ``y``. The examples will be taken from the ``X`` and ``y`` seen during ``fit``. An example prompt could be something like this: "Classify this text: {text}. Possible labels are: {labels}. Here are some examples: {examples}. Your response: ". All general tips for good prompt crafting apply here as well. Be aware that if the prompt is too long, it will exceed the context size of the model. probas_sum_to_1 : bool (default=True) If ``True``, then the probabilities for each sample will be normalized to sum to 1. If ``False``, the probabilities will not be normalized. In general, without normalization, the probabilities will not sum to 1 because the LLM can generate any token, not just the labels. Since the model is restricted to only generate the available labels, there will be some probability mass that is unaccounted for. You could consider the missing probability mass to be an implicit 'other' class. In general, you should set this parameter to ``True`` because the default assumption is that probabilities sum to 1. However, setting this to ``False`` can be useful for debugging purposes, as it allows you to see how much probability the LLM assigns to different tokens. If the total probabilities are very low, it could be a sign that the LLM is not powerful enough or that the prompt is not well crafted. max_samples: int (default=5) The number of samples to use for few-shot learning. The few-shot samples are taken from the ``X`` and ``y`` passed to ``fit``. This number should be large enough for the LLM to generalize, but not too large so as to exceed the context window size. More samples will also lower prediction speed. device : str or torch.device (default='cpu') The device to use. In general, using a GPU or other accelerated hardware is advised if runtime performance is critical. Note that if the ``model`` parameter is passed explicitly, the device of that model takes precedence over the value of ``device``. error_low_prob : {'ignore', 'warn', 'raise', 'return_none'} (default='ignore') Controls what should happen if the sum of the probabilities for a sample is below a given threshold. When encountering low probabilities, the options are to do one of the following: - ``'ignore'``: do nothing - ``'warn'``: issue a warning - ``'raise'``: raise an error - ``'return_none'``: return ``None`` as the prediction when calling ``.predict`` The threshold is controlled by the ``threshold_low_prob`` parameter. threshold_low_prob : float (default=0.0) The threshold for the sum of the probabilities below which they are considered to be too low. The consequences of low probabilities are controlled by the ``error_low_prob`` parameter. use_caching : bool (default=True) If ``True``, the predictions for each sample will be cached, as well as the intermediate result for each generated token. This can speed up predictions when some samples are duplicated, or when labels have a long common prefix. An example of the latter would be if a label is called "intent.support.email" and another label is called "intent.support.phone", then the tokens for the common prefix "intent.support." are reused for both labels, as their probabilities are identical. Note that caching is currently not supported for encoder-decoder architectures such as flan-t5. If you want to use such an architecture, turn caching off. If you see any issues you might suspect are caused by caching, turn this option off, see if it helps, and report the issue on the skorch GitHub page. random_state : int, RandomState instance or None (default=None) The choice of examples that are picked for few-shot learning is random. To fix the random seed, use this argument. Attributes ---------- classes_ : ndarray of shape (n_classes, ) A list of class labels known to the classifier. This attribute can be used to identify which column in the probabilties returned by ``predict_proba`` corresponds to which class. """ def __init__( self, model_name=None, *, model=None, tokenizer=None, prompt=None, probas_sum_to_1=True, max_samples=5, device='cpu', error_low_prob='ignore', threshold_low_prob=0.0, use_caching=True, random_state=None, ): self.model_name = model_name self.model = model self.tokenizer = tokenizer self.prompt = prompt self.probas_sum_to_1 = probas_sum_to_1 self.max_samples = max_samples self.device = device self.error_low_prob = error_low_prob self.threshold_low_prob = threshold_low_prob self.use_caching = use_caching self.random_state = random_state def check_prompt(self, prompt): """Check if the prompt is well formed. If no prompt is provided, return the default prompt. Raises ------ ValueError When the prompt is not well formed. """ if prompt is None: prompt = DEFAULT_PROMPT_FEW_SHOT kwargs = { 'text': "some text", 'labels': ["foo", "bar"], 'examples': ["some examples"], } _check_format_string(prompt, kwargs) return prompt def get_examples(self, X, y, n_samples): """Given input data ``X`` and ``y``, return a subset of ``n_samples`` for few-shot learning. This method aims at providing at least one example for each existing class. """ examples = [] seen_X = set() seen_y = set() rng = check_random_state(self.random_state) indices = rng.permutation(np.arange(len(y))) # first batch, fill with one example for each label for i in indices: if y[i] not in seen_y: examples.append((X[i], y[i])) seen_X.add(str(X[i])) seen_y.add(y[i]) if len(seen_y) == len(self.classes_): # each label is represented break if len(examples) == n_samples: break if len(examples) == n_samples: return examples # second batch, fill with random other examples for i in indices: if str(X[i]) in seen_X: continue examples.append((X[i], y[i])) if len(examples) == n_samples: break # return in reverse order so that the label diversity from the 1st batch # comes last return examples[::-1] def fit(self, X, y, **fit_params): """Prepare everything to enable predictions. There is no actual fitting going on here, as the LLM is used as is. The examples used for few-shot learning will be derived from the provided input data. The selection mechanism for this is that, for each possible label, at least one example is taken from the data (if ``max_samples`` is large enough). To change the way that examples are selected, override the ``get_examples`` method. Parameters ---------- X : array-like of shape (n_samples,) The input data. For zero-shot classification, this can be ``None``. y : array-like of shape (n_samples,) The target classes. Ensure that each class that the LLM should be able to predict is present at least once. Classes that are not present during the ``fit`` call will never be predicted. **fit_params : dict Additional fitting parameters. This is mostly a placeholder for sklearn-compatibility, as there is no actual fitting process. Returns ------- self The fitted estimator. """ self._fit(X, y, **fit_params) n_samples = min(self.max_samples, len(y)) self.examples_ = self.get_examples(X, y, n_samples=n_samples) return self def get_prompt(self, text): """Return the prompt for the given sample.""" self.check_is_fitted() few_shot_examples = [] for xi, yi in self.examples_: few_shot_examples.append( f"{DELIM}\n{xi}\n{DELIM}\n\nYour response:\n{yi}\n" ) examples = "\n".join(few_shot_examples) return self.prompt_.format( text=text, labels=self.classes_.tolist(), examples=examples ) def check_X_y(self, X, y, **fit_params): """Check that input data is well-behaved.""" if (X is None) or (not len(X)): raise ValueError("For few-shot learning, pass at least one example") if y is None: raise ValueError( "y cannot be None, as it is used to infer the existing classes" ) if not isinstance(y[0], str): # don't raise an error, as, hypothetically, the LLM could also # predict encoded targets, but it's not advisable warnings.warn( "y should contain the name of the labels as strings, e.g. " "'positive' and 'negative', don't pass label-encoded targets" ) len_X, len_y = len(X), len(y) if len_X != len_y: raise ValueError( "X and y don't have the same number of samples, found " f"{len_X} and {len_y} samples, respectively" )
FewShotClassifier
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 154937, "end": 156100 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, start_date: str, auth_url: str, api_key: str, timezone: Optional[str] = None, ): """Airbyte Source for Talkdesk Explore. Args: name (str): The name of the destination. start_date (str): The date from which you'd like to replicate data for Talkdesk Explore API, in the format YYYY-MM-DDT00:00:00. All data generated after this date will be replicated. timezone (Optional[str]): Timezone to use when generating reports. Only IANA timezones are supported (https://nodatime.org/TimeZones) auth_url (str): Talkdesk Auth URL. Only 'client_credentials' auth type supported at the moment. api_key (str): Talkdesk API key. """ self.start_date = check.str_param(start_date, "start_date") self.timezone = check.opt_str_param(timezone, "timezone") self.auth_url = check.str_param(auth_url, "auth_url") self.api_key = check.str_param(api_key, "api_key") super().__init__("Talkdesk Explore", name)
TalkdeskExploreSource
python
sympy__sympy
sympy/solvers/ode/single.py
{ "start": 33683, "end": 35891 }
class ____(SinglePatternODESolver): r""" Gives general solutions to the first order Riccati differential equations that have atleast one rational particular solution. .. math :: y' = b_0(x) + b_1(x) y + b_2(x) y^2 where `b_0`, `b_1` and `b_2` are rational functions of `x` with `b_2 \ne 0` (`b_2 = 0` would make it a Bernoulli equation). Examples ======== >>> from sympy import Symbol, Function, dsolve, checkodesol >>> f = Function('f') >>> x = Symbol('x') >>> eq = -x**4*f(x)**2 + x**3*f(x).diff(x) + x**2*f(x) + 20 >>> sol = dsolve(eq, hint="1st_rational_riccati") >>> sol Eq(f(x), (4*C1 - 5*x**9 - 4)/(x**2*(C1 + x**9 - 1))) >>> checkodesol(eq, sol) (True, 0) References ========== - Riccati ODE: https://en.wikipedia.org/wiki/Riccati_equation - N. Thieu Vo - Rational and Algebraic Solutions of First-Order Algebraic ODEs: Algorithm 11, pp. 78 - https://www3.risc.jku.at/publications/download/risc_5387/PhDThesisThieu.pdf """ has_integral = False hint = "1st_rational_riccati" order = [1] def _wilds(self, f, x, order): b0 = Wild('b0', exclude=[f(x), f(x).diff(x)]) b1 = Wild('b1', exclude=[f(x), f(x).diff(x)]) b2 = Wild('b2', exclude=[f(x), f(x).diff(x)]) return (b0, b1, b2) def _equation(self, fx, x, order): b0, b1, b2 = self.wilds() return fx.diff(x) - b0 - b1*fx - b2*fx**2 def _matches(self): eq = self.ode_problem.eq_expanded f = self.ode_problem.func.func x = self.ode_problem.sym order = self.ode_problem.order if order != 1: return False match, funcs = match_riccati(eq, f, x) if not match: return False _b0, _b1, _b2 = funcs b0, b1, b2 = self.wilds() self._wilds_match = match = {b0: _b0, b1: _b1, b2: _b2} return True def _get_general_solution(self, *, simplify_flag: bool = True): # Match the equation b0, b1, b2 = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym return solve_riccati(fx, x, b0, b1, b2, gensol=True)
RationalRiccati
python
apache__airflow
airflow-core/src/airflow/utils/state.py
{ "start": 3132, "end": 3559 }
class ____(str, Enum): """ All possible states that a DagRun can be in. These are "shared" with TaskInstanceState in some parts of the code, so please ensure that their values always match the ones with the same name in TaskInstanceState. """ QUEUED = "queued" RUNNING = "running" SUCCESS = "success" FAILED = "failed" def __str__(self) -> str: return self.value
DagRunState
python
pypa__pip
src/pip/_vendor/urllib3/response.py
{ "start": 1669, "end": 3389 }
class ____(object): def __init__(self): self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) self._state = GzipDecoderState.FIRST_MEMBER def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): ret = bytearray() if self._state == GzipDecoderState.SWALLOW_DATA or not data: return bytes(ret) while True: try: ret += self._obj.decompress(data) except zlib.error: previous_state = self._state # Ignore data after the first error self._state = GzipDecoderState.SWALLOW_DATA if previous_state == GzipDecoderState.OTHER_MEMBERS: # Allow trailing garbage acceptable in other gzip clients return bytes(ret) raise data = self._obj.unused_data if not data: return bytes(ret) self._state = GzipDecoderState.OTHER_MEMBERS self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) if brotli is not None: class BrotliDecoder(object): # Supports both 'brotlipy' and 'Brotli' packages # since they share an import name. The top branches # are for 'brotlipy' and bottom branches for 'Brotli' def __init__(self): self._obj = brotli.Decompressor() if hasattr(self._obj, "decompress"): self.decompress = self._obj.decompress else: self.decompress = self._obj.process def flush(self): if hasattr(self._obj, "flush"): return self._obj.flush() return b""
GzipDecoder
python
kubernetes-client__python
kubernetes/client/models/v1beta2_resource_claim_spec.py
{ "start": 383, "end": 3469 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'devices': 'V1beta2DeviceClaim' } attribute_map = { 'devices': 'devices' } def __init__(self, devices=None, local_vars_configuration=None): # noqa: E501 """V1beta2ResourceClaimSpec - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._devices = None self.discriminator = None if devices is not None: self.devices = devices @property def devices(self): """Gets the devices of this V1beta2ResourceClaimSpec. # noqa: E501 :return: The devices of this V1beta2ResourceClaimSpec. # noqa: E501 :rtype: V1beta2DeviceClaim """ return self._devices @devices.setter def devices(self, devices): """Sets the devices of this V1beta2ResourceClaimSpec. :param devices: The devices of this V1beta2ResourceClaimSpec. # noqa: E501 :type: V1beta2DeviceClaim """ self._devices = devices def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1beta2ResourceClaimSpec): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1beta2ResourceClaimSpec): return True return self.to_dict() != other.to_dict()
V1beta2ResourceClaimSpec
python
airbytehq__airbyte
airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_external_account_bank_accounts.py
{ "start": 3598, "end": 8069 }
class ____(TestCase): @HttpMocker() def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None: http_mocker.get( _external_accounts_request().with_object(_OBJECT).with_limit(100).build(), _external_bank_accounts_response().with_record(_an_external_bank_account()).with_record(_an_external_bank_account()).build(), ) output = self._read(_config().with_start_date(_A_START_DATE)) assert len(output.records) == 2 @HttpMocker() def test_given_many_pages_when_read_then_return_records(self, http_mocker: HttpMocker) -> None: http_mocker.get( _external_accounts_request().with_object(_OBJECT).with_limit(100).build(), _external_bank_accounts_response() .with_pagination() .with_record(_an_external_bank_account().with_id("last_record_id_from_first_page")) .build(), ) http_mocker.get( _external_accounts_request().with_starting_after("last_record_id_from_first_page").with_object(_OBJECT).with_limit(100).build(), _external_bank_accounts_response().with_record(_an_external_bank_account()).with_record(_an_external_bank_account()).build(), ) output = self._read(_config().with_start_date(_A_START_DATE)) assert len(output.records) == 3 @HttpMocker() def test_when_read_then_add_cursor_field(self, http_mocker: HttpMocker) -> None: http_mocker.get( _external_accounts_request().with_object(_OBJECT).with_limit(100).build(), _external_bank_accounts_response().with_record(_an_external_bank_account()).build(), ) output = self._read(_config().with_start_date(_A_START_DATE).with_lookback_window_in_days(10)) assert output.records[0].record.data["updated"] == int(_NOW.timestamp()) @HttpMocker() def test_given_http_status_400_when_read_then_stream_did_not_run(self, http_mocker: HttpMocker) -> None: http_mocker.get( _external_accounts_request().with_any_query_params().build(), a_response_with_status(400), ) output = self._read(_config()) assert_stream_did_not_run(output, _STREAM_NAME, "Your account is not set up to use Issuing") @HttpMocker() def test_given_http_status_401_when_read_then_config_error(self, http_mocker: HttpMocker) -> None: http_mocker.get( _external_accounts_request().with_any_query_params().build(), a_response_with_status(401), ) output = self._read(_config(), expecting_exception=True) assert output.errors[-1].trace.error.failure_type == FailureType.config_error @HttpMocker() def test_given_rate_limited_when_read_then_retry_and_return_records(self, http_mocker: HttpMocker) -> None: http_mocker.get( _external_accounts_request().with_any_query_params().build(), [ a_response_with_status(429), _external_bank_accounts_response().with_record(_an_external_bank_account()).build(), ], ) output = self._read(_config().with_start_date(_A_START_DATE)) assert len(output.records) == 1 @HttpMocker() def test_given_http_status_500_once_before_200_when_read_then_retry_and_return_records(self, http_mocker: HttpMocker) -> None: http_mocker.get( _external_accounts_request().with_any_query_params().build(), [a_response_with_status(500), _external_bank_accounts_response().with_record(_an_external_bank_account()).build()], ) output = self._read(_config()) assert len(output.records) == 1 @HttpMocker() def test_given_http_status_500_when_read_then_raise_config_error(self, http_mocker: HttpMocker) -> None: http_mocker.get( _external_accounts_request().with_any_query_params().build(), a_response_with_status(500), ) with patch.object(HttpStatusErrorHandler, "max_retries", new=0): output = self._read(_config(), expecting_exception=True) assert output.errors[-1].trace.error.failure_type == FailureType.config_error def _read(self, config: ConfigBuilder, expecting_exception: bool = False) -> EntrypointOutput: return _read(config, SyncMode.full_refresh, expecting_exception=expecting_exception) @freezegun.freeze_time(_NOW.isoformat())
FullRefreshTest
python
PrefectHQ__prefect
src/prefect/server/api/concurrency_limits_v2.py
{ "start": 5933, "end": 6034 }
class ____(PrefectBaseModel): id: UUID name: str limit: int
MinimalConcurrencyLimitResponse
python
keras-team__keras
keras/src/distillation/distiller_test.py
{ "start": 631, "end": 1064 }
class ____(keras.Model): """Simple student model for testing.""" def __init__(self, vocab_size=10, hidden_dim=16): super().__init__() self.dense1 = keras.layers.Dense(hidden_dim, activation="relu") self.dense2 = keras.layers.Dense(vocab_size) def call(self, inputs, training=None): x = self.dense1(inputs) return self.dense2(x) @pytest.mark.requires_trainable_backend
SimpleStudent
python
walkccc__LeetCode
solutions/2077. Paths in Maze That Lead to Same Room/2077.py
{ "start": 0, "end": 367 }
class ____: def numberOfPaths(self, n: int, corridors: list[list[int]]) -> int: ans = 0 graph = [[False] * 1001 for _ in range(n + 1)] for u, v in corridors: graph[u][v] = True graph[v][u] = True for u, v in corridors: for i in range(1, n + 1): if graph[u][i] and graph[i][v]: ans += 1 return ans // 3
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py
{ "start": 2229, "end": 2359 }
class ____: def __post_init__(self, x: tuple[int, ...] = ( 1, 2, )) -> None: self.x = x @dataclass
C
python
tensorflow__tensorflow
tensorflow/python/ops/init_ops.py
{ "start": 14350, "end": 17402 }
class ____(Initializer): """Initializer that generates tensors with a uniform distribution. Args: minval: A python scalar or a scalar tensor. Lower bound of the range of random values to generate. maxval: A python scalar or a scalar tensor. Upper bound of the range of random values to generate. Defaults to 1 for float types. seed: A Python integer. Used to create random seeds. See `tf.compat.v1.set_random_seed` for behavior. dtype: Default data type, used if no `dtype` argument is provided when calling the initializer. @compatibility(TF2) Although it is a legacy compat.v1 API, this symbol is compatible with eager execution and `tf.function`. To switch to TF2, switch to using either `tf.initializers.RandomUniform` or `tf.keras.initializers.RandomUniform` (neither from `compat.v1`) and pass the dtype when calling the initializer. Keep in mind that the default minval, maxval and the behavior of fixed seeds have changed. #### Structural Mapping to TF2 Before: ```python initializer = tf.compat.v1.random_uniform_initializer( minval=minval, maxval=maxval, seed=seed, dtype=dtype) weight_one = tf.Variable(initializer(shape_one)) weight_two = tf.Variable(initializer(shape_two)) ``` After: ```python initializer = tf.initializers.RandomUniform( minval=minval, maxval=maxval, seed=seed) weight_one = tf.Variable(initializer(shape_one, dtype=dtype)) weight_two = tf.Variable(initializer(shape_two, dtype=dtype)) ``` #### How to Map Arguments | TF1 Arg Name | TF2 Arg Name | Note | | :-------------------- | :-------------- | :------------------------- | | `minval` | `minval` | Default changes from 0 to -0.05 | | `maxval` | `maxval` | Default changes from 1.0 to 0.05 | | `seed` | `seed` | | | `dtype` | `dtype` | The TF2 native api only takes it | : : : as a `__call__` arg, not a constructor arg. : | `partition_info` | - | (`__call__` arg in TF1) Not supported | @end_compatibility """ @deprecated_args(None, "Call initializer instance with the dtype argument instead " "of passing it to the constructor", "dtype") def __init__(self, minval=.0, maxval=None, seed=None, dtype=dtypes.float32): self.minval = minval self.maxval = maxval self.seed = seed self.dtype = dtypes.as_dtype(dtype) def __call__(self, shape, dtype=None, partition_info=None): if dtype is None: dtype = self.dtype return random_ops.random_uniform( shape, self.minval, self.maxval, dtype, seed=self.seed) def get_config(self): return { "minval": self.minval, "maxval": self.maxval, "seed": self.seed, "dtype": self.dtype.name } @tf_export(v1=["initializers.random_normal", "random_normal_initializer"]) @deprecation.deprecated_endpoints("initializers.random_normal")
RandomUniform
python
ApeWorX__ape
src/ape/managers/_deploymentscache.py
{ "start": 870, "end": 1026 }
class ____(DiskCacheableModel): """The deployments structured JSON.""" ecosystems: dict[str, dict[str, dict[str, list[Deployment]]]] = {}
Deployments
python
huggingface__transformers
src/transformers/models/vit/modeling_vit.py
{ "start": 18276, "end": 19269 }
class ____(nn.Module): def __init__(self, config: ViTConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, config.pooler_output_size) self.activation = ACT2FN[config.pooler_act] def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output @auto_docstring( custom_intro=""" ViT Model with a decoder on top for masked image modeling, as proposed in [SimMIM](https://huggingface.co/papers/2111.09886). <Tip> Note that we provide a script to pre-train this model on custom data in our [examples directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining). </Tip> """ )
ViTPooler
python
getsentry__sentry
src/sentry/projects/services/project/impl.py
{ "start": 983, "end": 6755 }
class ____(ProjectService): def get_by_id(self, *, organization_id: int, id: int) -> RpcProject | None: try: project: Project | None = Project.objects.get_from_cache( id=id, organization=organization_id ) except ValueError: project = Project.objects.filter(id=id, organization=organization_id).first() except Project.DoesNotExist: return None if project: return serialize_project(project) return None def get_by_slug(self, *, organization_id: int, slug: str) -> RpcProject | None: project: Project | None = Project.objects.filter( slug=slug, organization=organization_id ).first() if project: return serialize_project(project) return None def get_many_by_organizations( self, *, region_name: str, organization_ids: list[int], ) -> list[RpcProject]: projects = Project.objects.filter( organization__in=organization_ids, status=ObjectStatus.ACTIVE, ).order_by("-date_added") return [serialize_project(p) for p in projects] def get_option(self, *, project: RpcProject, key: str) -> RpcProjectOptionValue: from sentry import projectoptions orm_project = Project.objects.get_from_cache(id=project.id) result = ProjectOption.objects.get_all_values(orm_project) keyed_result = result.get(key) well_known_key = projectoptions.lookup_well_known_key(key) well_known_result = None if well_known_key is None else well_known_key.get_default(project) return RpcProjectOptionValue(keyed_result=keyed_result, well_known_result=well_known_result) def update_option(self, *, project: RpcProject, key: str, value: OptionValue) -> bool: orm_project = Project.objects.get(id=project.id) return ProjectOption.objects.set_value(orm_project, key, value) def delete_option(self, *, project: RpcProject, key: str) -> None: orm_project = Project.objects.get(id=project.id) ProjectOption.objects.unset_value(orm_project, key) def serialize_many( self, *, organization_id: int, filter: ProjectFilterArgs, as_user: RpcUser | None = None, auth_context: AuthenticationContext | None = None, ) -> list[OpaqueSerializedResponse]: from sentry.api.serializers import serialize if as_user is None and auth_context: as_user = auth_context.user return serialize( list( Project.objects.filter( id__in=filter.get("project_ids", []), organization_id=organization_id ) ), user=as_user, serializer=ProjectSerializer(), ) def create_project_for_organization( self, *, organization_id: int, project_name: str, platform: str, user_id: int, add_org_default_team: bool | None = False, external_id: str | None = None, ) -> RpcProject: with transaction.atomic(router.db_for_write(Project)): project = Project.objects.create( name=project_name, organization_id=organization_id, platform=platform, external_id=external_id, ) if add_org_default_team: team = ( Team.objects.filter(organization_id=organization_id, status=TeamStatus.ACTIVE) .order_by("date_added") .first() ) # Makes a best effort to add the default org team, # but doesn't block if one doesn't exist. if team: project.add_team(team) set_default_symbol_sources(project) project_created.send_robust( project=project, default_rules=True, sender=self.create_project_for_organization, user_id=user_id, ) return serialize_project(project) def get_or_create_project_for_organization( self, *, organization_id: int, project_name: str, platform: str, user_id: int, add_org_default_team: bool | None = False, external_id: str | None = None, ) -> RpcProject: project_query = Project.objects.filter( organization_id=organization_id, name=project_name, platform=platform, external_id=external_id, status=ObjectStatus.ACTIVE, ).order_by("date_added") if project_query.exists(): return serialize_project(project_query[0]) return self.create_project_for_organization( organization_id=organization_id, project_name=project_name, platform=platform, user_id=user_id, add_org_default_team=add_org_default_team, external_id=external_id, ) def update_project( self, *, organization_id: int, project_id: int, attrs: ProjectUpdateArgs, ) -> RpcProject: project: Project = Project.objects.get( id=project_id, organization_id=organization_id, ) serializer = ProjectUpdateArgsSerializer(data=attrs) serializer.is_valid(raise_exception=True) if serializer.validated_data: for key, value in serializer.validated_data.items(): setattr(project, key, value) project.save() return serialize_project(project)
DatabaseBackedProjectService
python
getsentry__sentry
tests/sentry/monitors/migrations/test_0010_delete_orphaned_detectors.py
{ "start": 308, "end": 3389 }
class ____(TestMigrations): migrate_from = "0009_backfill_monitor_detectors" migrate_to = "0010_delete_orphaned_detectors" app = "monitors" def setup_initial_state(self) -> None: self.monitor_with_detector = self.create_monitor(name="Monitor with detector") ensure_cron_detector(self.monitor_with_detector) self.monitor_without_detector = self.create_monitor(name="Monitor without detector") self.orphaned_monitor = self.create_monitor(name="Orphaned monitor") ensure_cron_detector(self.orphaned_monitor) self.orphaned_data_source = DataSource.objects.get( type=DATA_SOURCE_CRON_MONITOR, organization_id=self.orphaned_monitor.organization_id, source_id=str(self.orphaned_monitor.id), ) self.orphaned_datasource_detector = DataSourceDetector.objects.get( data_source=self.orphaned_data_source ) self.orphaned_detector = self.orphaned_datasource_detector.detector self.orphaned_monitor.delete() self.standalone_orphaned_data_source = DataSource.objects.create( type=DATA_SOURCE_CRON_MONITOR, organization_id=self.organization.id, source_id="999999999", ) self.standalone_orphaned_detector = Detector.objects.create( project_id=self.project.id, type="monitor_check_in_failure", name="Standalone orphaned detector", config={}, ) DataSourceDetector.objects.create( data_source=self.standalone_orphaned_data_source, detector=self.standalone_orphaned_detector, ) assert get_detector_for_monitor(self.monitor_with_detector) is not None assert get_detector_for_monitor(self.monitor_without_detector) is None assert DataSource.objects.filter(id=self.orphaned_data_source.id).exists() assert Detector.objects.filter(id=self.orphaned_detector.id).exists() assert DataSource.objects.filter(id=self.standalone_orphaned_data_source.id).exists() assert Detector.objects.filter(id=self.standalone_orphaned_detector.id).exists() def test(self) -> None: detector = get_detector_for_monitor(self.monitor_with_detector) assert detector is not None assert get_detector_for_monitor(self.monitor_without_detector) is None assert not DataSource.objects.filter(id=self.orphaned_data_source.id).exists() assert not Detector.objects.filter(id=self.orphaned_detector.id).exists() assert not DataSource.objects.filter(id=self.standalone_orphaned_data_source.id).exists() assert not Detector.objects.filter(id=self.standalone_orphaned_detector.id).exists() valid_data_sources = DataSource.objects.filter(type=DATA_SOURCE_CRON_MONITOR) assert valid_data_sources.count() == 1 remaining_data_source = valid_data_sources.first() assert remaining_data_source assert remaining_data_source.source_id == str(self.monitor_with_detector.id)
DeleteOrphanedDetectorsTest
python
getsentry__sentry
src/sentry/apidocs/parameters.py
{ "start": 20881, "end": 21377 }
class ____: UPTIME_ALERT_ID = OpenApiParameter( name="uptime_detector_id", location="path", required=True, type=int, description="The ID of the uptime alert rule you'd like to query.", ) OWNER = OpenApiParameter( name="owner", location="query", required=False, type=str, description="The owner of the uptime alert, in the format `user:id` or `team:id`. May be specified multiple times.", )
UptimeParams
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1406351, "end": 1409006 }
class ____(VegaLiteSchema): """ TimeUnitTransformParams schema wrapper. Parameters ---------- maxbins : float If no ``unit`` is specified, maxbins is used to infer time units. step : float The number of steps between bins, in terms of the least significant unit provided. unit : :class:`TimeUnit`, :class:`MultiTimeUnit`, :class:`SingleTimeUnit`, :class:`UtcMultiTimeUnit`, :class:`UtcSingleTimeUnit`, :class:`LocalMultiTimeUnit`, :class:`LocalSingleTimeUnit`, Literal['utcyear', 'utcquarter', 'utcmonth', 'utcweek', 'utcday', 'utcdayofyear', 'utcdate', 'utchours', 'utcminutes', 'utcseconds', 'utcmilliseconds', 'year', 'quarter', 'month', 'week', 'day', 'dayofyear', 'date', 'hours', 'minutes', 'seconds', 'milliseconds', 'utcyearquarter', 'utcyearquartermonth', 'utcyearmonth', 'utcyearmonthdate', 'utcyearmonthdatehours', 'utcyearmonthdatehoursminutes', 'utcyearmonthdatehoursminutesseconds', 'utcyearweek', 'utcyearweekday', 'utcyearweekdayhours', 'utcyearweekdayhoursminutes', 'utcyearweekdayhoursminutesseconds', 'utcyeardayofyear', 'utcquartermonth', 'utcmonthdate', 'utcmonthdatehours', 'utcmonthdatehoursminutes', 'utcmonthdatehoursminutesseconds', 'utcweekday', 'utcweekdayhours', 'utcweekdayhoursminutes', 'utcweekdayhoursminutesseconds', 'utcdayhours', 'utcdayhoursminutes', 'utcdayhoursminutesseconds', 'utchoursminutes', 'utchoursminutesseconds', 'utcminutesseconds', 'utcsecondsmilliseconds', 'yearquarter', 'yearquartermonth', 'yearmonth', 'yearmonthdate', 'yearmonthdatehours', 'yearmonthdatehoursminutes', 'yearmonthdatehoursminutesseconds', 'yearweek', 'yearweekday', 'yearweekdayhours', 'yearweekdayhoursminutes', 'yearweekdayhoursminutesseconds', 'yeardayofyear', 'quartermonth', 'monthdate', 'monthdatehours', 'monthdatehoursminutes', 'monthdatehoursminutesseconds', 'weekday', 'weekdayhours', 'weekdayhoursminutes', 'weekdayhoursminutesseconds', 'dayhours', 'dayhoursminutes', 'dayhoursminutesseconds', 'hoursminutes', 'hoursminutesseconds', 'minutesseconds', 'secondsmilliseconds'] Defines how date-time values should be binned. utc : bool True to use UTC timezone. Equivalent to using a ``utc`` prefixed ``TimeUnit``. """ _schema = {"$ref": "#/definitions/TimeUnitTransformParams"} def __init__( self, maxbins: Optional[float] = Undefined, step: Optional[float] = Undefined, unit: Optional[SchemaBase | MultiTimeUnit_T | SingleTimeUnit_T] = Undefined, utc: Optional[bool] = Undefined, **kwds, ): super().__init__(maxbins=maxbins, step=step, unit=unit, utc=utc, **kwds)
TimeUnitTransformParams
python
realpython__materials
django-vue-graphql/source_code_final/back_end/blog/schema.py
{ "start": 384, "end": 462 }
class ____(DjangoObjectType): class Meta: model = models.Tag
TagType
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/namedTuple4.py
{ "start": 397, "end": 501 }
class ____(Class3): some_class_member = 1 reveal_type(Class4(name="a"), expected_text="Class4")
Class4
python
ansible__ansible
test/lib/ansible_test/_internal/commands/coverage/report.py
{ "start": 4555, "end": 4869 }
class ____(CoverageCombineConfig): """Configuration for the coverage report command.""" def __init__(self, args: t.Any) -> None: super().__init__(args) self.show_missing: bool = args.show_missing self.include: str = args.include self.omit: str = args.omit
CoverageReportConfig
python
huggingface__transformers
tests/models/ernie4_5_moe/test_modeling_ernie4_5_moe.py
{ "start": 1291, "end": 1434 }
class ____(CausalLMModelTester): if is_torch_available(): base_model_class = Ernie4_5_MoeModel @require_torch
Ernie4_5_MoeModelTester
python
PyCQA__pylint
tests/functional/i/inherit_non_class.py
{ "start": 462, "end": 540 }
class ____(1): # [inherit-non-class] """ Can't inherit from instance. """
Bad
python
pytorch__pytorch
torch/_inductor/runtime/autotune_cache.py
{ "start": 21622, "end": 23066 }
class ____(RemoteCache[JsonDataTy]): def __init__(self) -> None: backend = _LocalAutotuneCacheBackend() serde = RemoteCacheJsonSerde() super().__init__(backend, serde) @override def _get(self, key: str, sample: Sample | None) -> JsonDataTy | None: AutotuneCacheBundler.sync() result = super()._get(key, sample) if result is not None: assert isinstance(result, dict) # What? Why are we doing a put() here? Imagine we have a new model # that reuses some existing kernels that have already been # compiled. If we didn't do a `put` here (on cache hit) then the new # model would only bundle *newly* compiled kernels, not existing # kernels that were already compiled and cached. AutotuneCacheBundler.put(key, result) autotune_artifact_key = os.path.join(*key.split(os.sep)[-2:]) CacheArtifactManager.record_artifact( AutotuneCacheArtifact.type(), autotune_artifact_key, result ) return result @override def _put(self, key: str, value: JsonDataTy, sample: Sample | None) -> None: AutotuneCacheBundler.put(key, value) super()._put(key, value, sample) def _splitext_nodot(basename: str) -> tuple[str, str]: root, ext = os.path.splitext(basename) if ext: ext = ext[1:] return root, ext
LocalAutotuneCache
python
wandb__wandb
wandb/vendor/pygments/sphinxext.py
{ "start": 805, "end": 4655 }
class ____(Directive): """ A directive to collect all lexers/formatters/filters and generate autoclass directives for them. """ has_content = False required_arguments = 1 optional_arguments = 0 final_argument_whitespace = False option_spec = {} def run(self): self.filenames = set() if self.arguments[0] == 'lexers': out = self.document_lexers() elif self.arguments[0] == 'formatters': out = self.document_formatters() elif self.arguments[0] == 'filters': out = self.document_filters() else: raise Exception('invalid argument for "pygmentsdoc" directive') node = nodes.compound() vl = ViewList(out.split('\n'), source='') nested_parse_with_titles(self.state, vl, node) for fn in self.filenames: self.state.document.settings.record_dependencies.add(fn) return node.children def document_lexers(self): from pygments.lexers._mapping import LEXERS out = [] modules = {} moduledocstrings = {} for classname, data in sorted(LEXERS.items(), key=lambda x: x[0]): module = data[0] mod = __import__(module, None, None, [classname]) self.filenames.add(mod.__file__) cls = getattr(mod, classname) if not cls.__doc__: print("Warning: %s does not have a docstring." % classname) docstring = cls.__doc__ if isinstance(docstring, bytes): docstring = docstring.decode('utf8') modules.setdefault(module, []).append(( classname, ', '.join(data[2]) or 'None', ', '.join(data[3]).replace('*', '\\*').replace('_', '\\') or 'None', ', '.join(data[4]) or 'None', docstring)) if module not in moduledocstrings: moddoc = mod.__doc__ if isinstance(moddoc, bytes): moddoc = moddoc.decode('utf8') moduledocstrings[module] = moddoc for module, lexers in sorted(modules.items(), key=lambda x: x[0]): if moduledocstrings[module] is None: raise Exception("Missing docstring for %s" % (module,)) heading = moduledocstrings[module].splitlines()[4].strip().rstrip('.') out.append(MODULEDOC % (module, heading, '-'*len(heading))) for data in lexers: out.append(LEXERDOC % data) return ''.join(out) def document_formatters(self): from pygments.formatters import FORMATTERS out = [] for classname, data in sorted(FORMATTERS.items(), key=lambda x: x[0]): module = data[0] mod = __import__(module, None, None, [classname]) self.filenames.add(mod.__file__) cls = getattr(mod, classname) docstring = cls.__doc__ if isinstance(docstring, bytes): docstring = docstring.decode('utf8') heading = cls.__name__ out.append(FMTERDOC % (heading, ', '.join(data[2]) or 'None', ', '.join(data[3]).replace('*', '\\*') or 'None', docstring)) return ''.join(out) def document_filters(self): from pygments.filters import FILTERS out = [] for name, cls in FILTERS.items(): self.filenames.add(sys.modules[cls.__module__].__file__) docstring = cls.__doc__ if isinstance(docstring, bytes): docstring = docstring.decode('utf8') out.append(FILTERDOC % (cls.__name__, name, docstring)) return ''.join(out) def setup(app): app.add_directive('pygmentsdoc', PygmentsDoc)
PygmentsDoc
python
Netflix__metaflow
metaflow/_vendor/yaml/representer.py
{ "start": 9752, "end": 14184 }
class ____(SafeRepresenter): def represent_complex(self, data): if data.imag == 0.0: data = '%r' % data.real elif data.real == 0.0: data = '%rj' % data.imag elif data.imag > 0: data = '%r+%rj' % (data.real, data.imag) else: data = '%r%rj' % (data.real, data.imag) return self.represent_scalar('tag:yaml.org,2002:python/complex', data) def represent_tuple(self, data): return self.represent_sequence('tag:yaml.org,2002:python/tuple', data) def represent_name(self, data): name = '%s.%s' % (data.__module__, data.__name__) return self.represent_scalar('tag:yaml.org,2002:python/name:'+name, '') def represent_module(self, data): return self.represent_scalar( 'tag:yaml.org,2002:python/module:'+data.__name__, '') def represent_object(self, data): # We use __reduce__ API to save the data. data.__reduce__ returns # a tuple of length 2-5: # (function, args, state, listitems, dictitems) # For reconstructing, we calls function(*args), then set its state, # listitems, and dictitems if they are not None. # A special case is when function.__name__ == '__newobj__'. In this # case we create the object with args[0].__new__(*args). # Another special case is when __reduce__ returns a string - we don't # support it. # We produce a !!python/object, !!python/object/new or # !!python/object/apply node. cls = type(data) if cls in copyreg.dispatch_table: reduce = copyreg.dispatch_table[cls](data) elif hasattr(data, '__reduce_ex__'): reduce = data.__reduce_ex__(2) elif hasattr(data, '__reduce__'): reduce = data.__reduce__() else: raise RepresenterError("cannot represent an object", data) reduce = (list(reduce)+[None]*5)[:5] function, args, state, listitems, dictitems = reduce args = list(args) if state is None: state = {} if listitems is not None: listitems = list(listitems) if dictitems is not None: dictitems = dict(dictitems) if function.__name__ == '__newobj__': function = args[0] args = args[1:] tag = 'tag:yaml.org,2002:python/object/new:' newobj = True else: tag = 'tag:yaml.org,2002:python/object/apply:' newobj = False function_name = '%s.%s' % (function.__module__, function.__name__) if not args and not listitems and not dictitems \ and isinstance(state, dict) and newobj: return self.represent_mapping( 'tag:yaml.org,2002:python/object:'+function_name, state) if not listitems and not dictitems \ and isinstance(state, dict) and not state: return self.represent_sequence(tag+function_name, args) value = {} if args: value['args'] = args if state or not isinstance(state, dict): value['state'] = state if listitems: value['listitems'] = listitems if dictitems: value['dictitems'] = dictitems return self.represent_mapping(tag+function_name, value) def represent_ordered_dict(self, data): # Provide uniform representation across different Python versions. data_type = type(data) tag = 'tag:yaml.org,2002:python/object/apply:%s.%s' \ % (data_type.__module__, data_type.__name__) items = [[key, value] for key, value in data.items()] return self.represent_sequence(tag, [items]) Representer.add_representer(complex, Representer.represent_complex) Representer.add_representer(tuple, Representer.represent_tuple) Representer.add_representer(type, Representer.represent_name) Representer.add_representer(collections.OrderedDict, Representer.represent_ordered_dict) Representer.add_representer(types.FunctionType, Representer.represent_name) Representer.add_representer(types.BuiltinFunctionType, Representer.represent_name) Representer.add_representer(types.ModuleType, Representer.represent_module) Representer.add_multi_representer(object, Representer.represent_object)
Representer
python
boto__boto3
boto3/docs/docstring.py
{ "start": 1763, "end": 1905 }
class ____(LazyLoadedDocstring): def _write_docstring(self, *args, **kwargs): document_reference(*args, **kwargs)
ReferenceDocstring
python
pytorch__pytorch
test/nn/test_pruning.py
{ "start": 361, "end": 38241 }
class ____(NNTestCase): _do_cuda_memory_leak_check = True _do_cuda_non_default_stream = True # torch/nn/utils/prune.py @unittest.skipIf(not TEST_NUMPY, "numpy not found") def test_validate_pruning_amount_init(self): r"""Test the first util function that validates the pruning amount requested by the user the moment the pruning method is initialized. This test checks that the expected errors are raised whenever the amount is invalid. The original function runs basic type checking + value range checks. It doesn't check the validity of the pruning amount with respect to the size of the tensor to prune. That's left to `_validate_pruning_amount`, tested below. """ # neither float not int should raise TypeError with self.assertRaises(TypeError): prune._validate_pruning_amount_init(amount="I'm a string") # float not in [0, 1] should raise ValueError with self.assertRaises(ValueError): prune._validate_pruning_amount_init(amount=1.1) with self.assertRaises(ValueError): prune._validate_pruning_amount_init(amount=20.0) # negative int should raise ValueError with self.assertRaises(ValueError): prune._validate_pruning_amount_init(amount=-10) # all these should pass without errors because they're valid amounts prune._validate_pruning_amount_init(amount=0.34) prune._validate_pruning_amount_init(amount=1500) prune._validate_pruning_amount_init(amount=0) prune._validate_pruning_amount_init(amount=0.0) prune._validate_pruning_amount_init(amount=1) prune._validate_pruning_amount_init(amount=1.0) self.assertTrue(True) @unittest.skipIf(not TEST_NUMPY, "numpy not found") def test_validate_pruning_amount(self): r"""Tests the second util function that validates the pruning amount requested by the user, this time with respect to the size of the tensor to prune. The rationale is that if the pruning amount, converted to absolute value of units to prune, is larger than the number of units in the tensor, then we expect the util function to raise a value error. """ # if amount is int and amount > tensor_size, raise ValueError with self.assertRaises(ValueError): prune._validate_pruning_amount(amount=20, tensor_size=19) # amount is a float so this should not raise an error prune._validate_pruning_amount(amount=0.3, tensor_size=0) # this is okay prune._validate_pruning_amount(amount=19, tensor_size=20) prune._validate_pruning_amount(amount=0, tensor_size=0) prune._validate_pruning_amount(amount=1, tensor_size=1) self.assertTrue(True) @unittest.skipIf(not TEST_NUMPY, "numpy not found") def test_compute_nparams_to_prune(self): r"""Test that requested pruning `amount` gets translated into the correct absolute number of units to prune. """ self.assertEqual(prune._compute_nparams_toprune(amount=0, tensor_size=15), 0) self.assertEqual(prune._compute_nparams_toprune(amount=10, tensor_size=15), 10) # if 1 is int, means 1 unit self.assertEqual(prune._compute_nparams_toprune(amount=1, tensor_size=15), 1) # if 1. is float, means 100% of units self.assertEqual(prune._compute_nparams_toprune(amount=1.0, tensor_size=15), 15) self.assertEqual(prune._compute_nparams_toprune(amount=0.4, tensor_size=17), 7) def test_random_pruning_sizes(self): r"""Test that the new parameters and buffers created by the pruning method have the same size as the input tensor to prune. These, in fact, correspond to the pruned version of the tensor itself, its mask, and its original copy, so the size must match. """ # fixturize test # TODO: add other modules modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)] names = ["weight", "bias"] for m in modules: for name in names: with self.subTest(m=m, name=name): original_tensor = getattr(m, name) prune.random_unstructured(m, name=name, amount=0.1) # mask has the same size as tensor being pruned self.assertEqual( original_tensor.size(), getattr(m, name + "_mask").size() ) # 'orig' tensor has the same size as the original tensor self.assertEqual( original_tensor.size(), getattr(m, name + "_orig").size() ) # new tensor has the same size as the original tensor self.assertEqual(original_tensor.size(), getattr(m, name).size()) def test_random_pruning_orig(self): r"""Test that original tensor is correctly stored in 'orig' after pruning is applied. Important to make sure we don't lose info about the original unpruned parameter. """ # fixturize test # TODO: add other modules modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)] names = ["weight", "bias"] for m in modules: for name in names: with self.subTest(m=m, name=name): # tensor prior to pruning original_tensor = getattr(m, name) prune.random_unstructured(m, name=name, amount=0.1) self.assertEqual(original_tensor, getattr(m, name + "_orig")) def test_random_pruning_new_weight(self): r"""Test that module.name now contains a pruned version of the original tensor obtained from multiplying it by the mask. """ # fixturize test # TODO: add other modules modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)] names = ["weight", "bias"] for m in modules: for name in names: with self.subTest(m=m, name=name): # tensor prior to pruning original_tensor = getattr(m, name) prune.random_unstructured(m, name=name, amount=0.1) # weight = weight_orig * weight_mask self.assertEqual( getattr(m, name), getattr(m, name + "_orig") * getattr(m, name + "_mask").to(dtype=original_tensor.dtype), ) def test_identity_pruning(self): r"""Test that a mask of 1s does not change forward or backward.""" input_ = torch.ones(1, 5) m = nn.Linear(5, 2) y_prepruning = m(input_) # output prior to pruning # compute grad pre-pruning and check it's equal to all ones y_prepruning.sum().backward() old_grad_weight = m.weight.grad.clone() # don't grab pointer! self.assertEqual(old_grad_weight, torch.ones_like(m.weight)) old_grad_bias = m.bias.grad.clone() self.assertEqual(old_grad_bias, torch.ones_like(m.bias)) # remove grads m.zero_grad() # force the mask to be made of all 1s prune.identity(m, name="weight") # with mask of 1s, output should be identical to no mask y_postpruning = m(input_) self.assertEqual(y_prepruning, y_postpruning) # with mask of 1s, grad should be identical to no mask y_postpruning.sum().backward() self.assertEqual(old_grad_weight, m.weight_orig.grad) self.assertEqual(old_grad_bias, m.bias.grad) # calling forward twice in a row shouldn't change output y1 = m(input_) y2 = m(input_) self.assertEqual(y1, y2) def test_random_pruning_0perc(self): r"""Test that a mask of 1s does not change forward or backward.""" input_ = torch.ones(1, 5) m = nn.Linear(5, 2) y_prepruning = m(input_) # output prior to pruning # compute grad pre-pruning and check it's equal to all ones y_prepruning.sum().backward() old_grad_weight = m.weight.grad.clone() # don't grab pointer! self.assertEqual(old_grad_weight, torch.ones_like(m.weight)) old_grad_bias = m.bias.grad.clone() self.assertEqual(old_grad_bias, torch.ones_like(m.bias)) # remove grads m.zero_grad() # force the mask to be made of all 1s with mock.patch( "torch.nn.utils.prune.RandomUnstructured.compute_mask" ) as compute_mask: compute_mask.return_value = torch.ones_like(m.weight) prune.random_unstructured( m, name="weight", amount=0.9 ) # amount won't count # with mask of 1s, output should be identical to no mask y_postpruning = m(input_) self.assertEqual(y_prepruning, y_postpruning) # with mask of 1s, grad should be identical to no mask y_postpruning.sum().backward() self.assertEqual(old_grad_weight, m.weight_orig.grad) self.assertEqual(old_grad_bias, m.bias.grad) # calling forward twice in a row shouldn't change output y1 = m(input_) y2 = m(input_) self.assertEqual(y1, y2) def test_random_pruning(self): input_ = torch.ones(1, 5) m = nn.Linear(5, 2) # define custom mask to assign with mock mask = torch.ones_like(m.weight) mask[1, 0] = 0 mask[0, 3] = 0 # check grad is zero for masked weights with mock.patch( "torch.nn.utils.prune.RandomUnstructured.compute_mask" ) as compute_mask: compute_mask.return_value = mask prune.random_unstructured(m, name="weight", amount=0.9) y_postpruning = m(input_) y_postpruning.sum().backward() # weight_orig is the parameter, so it's the tensor that will accumulate the grad self.assertEqual(m.weight_orig.grad, mask) # all 1s, except for masked units self.assertEqual(m.bias.grad, torch.ones_like(m.bias)) # make sure that weight_orig update doesn't modify [1, 0] and [0, 3] old_weight_orig = m.weight_orig.clone() # update weights learning_rate = 1.0 for p in m.parameters(): p.data.sub_(p.grad.data * learning_rate) # since these are pruned, they should not be updated self.assertEqual(old_weight_orig[1, 0], m.weight_orig[1, 0]) self.assertEqual(old_weight_orig[0, 3], m.weight_orig[0, 3]) def test_random_pruning_forward(self): r"""check forward with mask (by hand).""" input_ = torch.ones(1, 5) m = nn.Linear(5, 2) # define custom mask to assign with mock mask = torch.zeros_like(m.weight) mask[1, 0] = 1 mask[0, 3] = 1 with mock.patch( "torch.nn.utils.prune.RandomUnstructured.compute_mask" ) as compute_mask: compute_mask.return_value = mask prune.random_unstructured(m, name="weight", amount=0.9) yhat = m(input_) self.assertEqual(yhat[0, 0], m.weight_orig[0, 3] + m.bias[0]) self.assertEqual(yhat[0, 1], m.weight_orig[1, 0] + m.bias[1]) def test_remove_pruning_forward(self): r"""Remove pruning and check forward is unchanged from previous pruned state. """ input_ = torch.ones(1, 5) m = nn.Linear(5, 2) # define custom mask to assign with mock mask = torch.ones_like(m.weight) mask[1, 0] = 0 mask[0, 3] = 0 # check grad is zero for masked weights with mock.patch( "torch.nn.utils.prune.RandomUnstructured.compute_mask" ) as compute_mask: compute_mask.return_value = mask prune.random_unstructured(m, name="weight", amount=0.9) y_postpruning = m(input_) prune.remove(m, "weight") y_postremoval = m(input_) self.assertEqual(y_postpruning, y_postremoval) def test_pruning_id_consistency(self): r"""Test that pruning doesn't change the id of the parameters, which would otherwise introduce issues with pre-existing optimizers that point to old parameters. """ m = nn.Linear(5, 2, bias=False) tensor_id = id(next(iter(m.parameters()))) prune.random_unstructured(m, name="weight", amount=0.9) self.assertEqual(tensor_id, id(next(iter(m.parameters())))) prune.remove(m, "weight") self.assertEqual(tensor_id, id(next(iter(m.parameters())))) def test_random_pruning_pickle(self): modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)] names = ["weight", "bias"] for m in modules: for name in names: with self.subTest(m=m, name=name): prune.random_unstructured(m, name=name, amount=0.1) m_new = pickle.loads(pickle.dumps(m)) self.assertIsInstance(m_new, type(m)) def test_multiple_pruning_calls(self): # if you call pruning twice, the hook becomes a PruningContainer m = nn.Conv3d(2, 2, 2) prune.l1_unstructured(m, name="weight", amount=0.1) weight_mask0 = m.weight_mask # save it for later sanity check # prune again prune.ln_structured(m, name="weight", amount=0.3, n=2, dim=0) hook = next(iter(m._forward_pre_hooks.values())) self.assertIsInstance(hook, torch.nn.utils.prune.PruningContainer) # check that container._tensor_name is correctly set no matter how # many pruning methods are in the container self.assertEqual(hook._tensor_name, "weight") # check that the pruning container has the right length # equal to the number of pruning iters self.assertEqual(len(hook), 2) # m.weight has been pruned twice # check that the entries of the pruning container are of the expected # type and in the expected order self.assertIsInstance(hook[0], torch.nn.utils.prune.L1Unstructured) self.assertIsInstance(hook[1], torch.nn.utils.prune.LnStructured) # check that all entries that are 0 in the 1st mask are 0 in the # 2nd mask too self.assertTrue(torch.all(m.weight_mask[weight_mask0 == 0] == 0)) # prune again prune.ln_structured(m, name="weight", amount=0.1, n=float("inf"), dim=1) # check that container._tensor_name is correctly set no matter how # many pruning methods are in the container hook = next(iter(m._forward_pre_hooks.values())) self.assertEqual(hook._tensor_name, "weight") def test_pruning_container(self): # create an empty container container = prune.PruningContainer() container._tensor_name = "test" self.assertEqual(len(container), 0) p = prune.L1Unstructured(amount=2) p._tensor_name = "test" # test adding a pruning method to a container container.add_pruning_method(p) # test error raised if tensor name is different q = prune.L1Unstructured(amount=2) q._tensor_name = "another_test" with self.assertRaises(ValueError): container.add_pruning_method(q) # test that adding a non-pruning method object to a pruning container # raises a TypeError with self.assertRaises(TypeError): container.add_pruning_method(10) with self.assertRaises(TypeError): container.add_pruning_method("ugh") def test_pruning_container_compute_mask(self): r"""Test `compute_mask` of pruning container with a known `t` and `default_mask`. Indirectly checks that Ln structured pruning is acting on the right axis. """ # create an empty container container = prune.PruningContainer() container._tensor_name = "test" # 1) test unstructured pruning # create a new pruning method p = prune.L1Unstructured(amount=2) p._tensor_name = "test" # add the pruning method to the container container.add_pruning_method(p) # create tensor to be pruned t = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).to(dtype=torch.float32) # create prior mask by hand default_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 1]]) # since we are pruning the two lowest magnitude units, the outcome of # the calculation should be this: expected_mask = torch.tensor([[0, 0, 1, 0], [1, 1, 0, 1]], dtype=torch.float32) computed_mask = container.compute_mask(t, default_mask) self.assertEqual(expected_mask, computed_mask) # 2) test structured pruning q = prune.LnStructured(amount=1, n=2, dim=0) q._tensor_name = "test" container.add_pruning_method(q) # since we are pruning the lowest magnitude one of the two rows, the # outcome of the calculation should be this: expected_mask = torch.tensor([[0, 0, 0, 0], [1, 1, 0, 1]], dtype=torch.float32) computed_mask = container.compute_mask(t, default_mask) self.assertEqual(expected_mask, computed_mask) # 2) test structured pruning, along another axis r = prune.LnStructured(amount=1, n=2, dim=1) r._tensor_name = "test" container.add_pruning_method(r) # since we are pruning the lowest magnitude of the four columns, the # outcome of the calculation should be this: expected_mask = torch.tensor([[0, 1, 1, 0], [0, 1, 0, 1]], dtype=torch.float32) computed_mask = container.compute_mask(t, default_mask) self.assertEqual(expected_mask, computed_mask) def test_l1_unstructured_pruning(self): r"""Test that l1 unstructured pruning actually removes the lowest entries by l1 norm (by hand). It also checks that applying l1 unstructured pruning more than once respects the previous mask. """ m = nn.Linear(4, 2) # modify its weight matrix by hand m.weight = torch.nn.Parameter( torch.tensor([[1, 2, 3, 4], [-4, -3, -2, -1]], dtype=torch.float32) ) prune.l1_unstructured(m, "weight", amount=2) expected_weight = torch.tensor( [[0, 2, 3, 4], [-4, -3, -2, 0]], dtype=m.weight.dtype ) self.assertEqual(expected_weight, m.weight) # check that pruning again removes the next two smallest entries prune.l1_unstructured(m, "weight", amount=2) expected_weight = torch.tensor( [[0, 0, 3, 4], [-4, -3, 0, 0]], dtype=m.weight.dtype ) self.assertEqual(expected_weight, m.weight) def test_l1_unstructured_pruning_with_importance_scores(self): r"""Test that l1 unstructured pruning actually removes the lowest entries of importance scores and not the parameter by l1 norm (by hand). It also checks that applying l1 unstructured pruning more than once respects the previous mask. """ m = nn.Linear(4, 2) # modify its weight matrix by hand m.weight = torch.nn.Parameter( torch.tensor([[1, 2, 3, 4], [-4, -3, -2, -1]], dtype=torch.float32) ) importance_scores = torch.tensor( [[4, 2, 1, 3], [-3, -1, -2, -4]], dtype=torch.float32 ) prune.l1_unstructured( m, "weight", amount=2, importance_scores=importance_scores ) expected_weight = torch.tensor( [[1, 2, 0, 4], [-4, 0, -2, -1]], dtype=m.weight.dtype ) self.assertEqual(expected_weight, m.weight) # check that pruning again removes two entries of m.weight that are colocated with # the next two smallest absolute values of importance scores. prune.l1_unstructured( m, "weight", amount=2, importance_scores=importance_scores ) expected_weight = torch.tensor( [[1, 0, 0, 4], [-4, 0, 0, -1]], dtype=m.weight.dtype ) self.assertEqual(expected_weight, m.weight) def test_unstructured_pruning_same_magnitude(self): r"""Since it may happen that the tensor to prune has entries with the same exact magnitude, it is important to check that pruning happens consistently based on the bottom % of weights, and not by threshold, which would instead kill off *all* units with magnitude = threshold. """ AMOUNT = 0.2 p = prune.L1Unstructured(amount=AMOUNT) # create a random tensors with entries in {-2, 0, 2} t = 2 * torch.randint(low=-1, high=2, size=(10, 7)) nparams_toprune = prune._compute_nparams_toprune(AMOUNT, t.nelement()) computed_mask = p.compute_mask(t, default_mask=torch.ones_like(t)) nparams_pruned = torch.sum(computed_mask == 0) self.assertEqual(nparams_toprune, nparams_pruned) def test_random_structured_pruning_amount(self): AMOUNT = 0.6 AXIS = 2 p = prune.RandomStructured(amount=AMOUNT, dim=AXIS) t = 2 * torch.randint(low=-1, high=2, size=(5, 4, 2)).to(dtype=torch.float32) prune._compute_nparams_toprune(AMOUNT, t.shape[AXIS]) computed_mask = p.compute_mask(t, default_mask=torch.ones_like(t)) # check that 1 column is fully prune, the others are left untouched remaining_axes = [_ for _ in range(len(t.shape)) if _ != AXIS] per_column_sums = sorted(torch.sum(computed_mask == 0, axis=remaining_axes)) assert per_column_sums == [0, 20] def test_ln_structured_pruning(self): r"""Check Ln structured pruning by hand.""" m = nn.Conv2d(3, 1, 2) m.weight.data = torch.tensor( [ [ [[1.0, 2.0], [1.0, 2.5]], [[0.5, 1.0], [0.1, 0.1]], [[-3.0, -5.0], [0.1, -1.0]], ] ] ) # expected effect of pruning 1 of the 3 channels by L2-norm expected_mask_axis1 = torch.ones_like(m.weight) expected_mask_axis1[:, 1] = 0.0 prune.ln_structured(m, "weight", amount=1, n=2, dim=1) self.assertEqual(expected_mask_axis1, m.weight_mask) # expected effect of pruning 1 of the 2 columns along axis -1 by L1-norm expected_mask_axis3 = expected_mask_axis1 expected_mask_axis3[:, :, :, 0] = 0.0 prune.ln_structured(m, "weight", amount=1, n=1, dim=-1) self.assertEqual(expected_mask_axis3, m.weight_mask) def test_ln_structured_pruning_importance_scores(self): r"""Check Ln structured pruning by hand.""" m = nn.Conv2d(3, 1, 2) m.weight.data = torch.tensor( [ [ [[1.0, 2.0], [1.0, 2.5]], [[0.5, 1.0], [0.1, 0.1]], [[-3.0, -5.0], [0.1, -1.0]], ] ] ) importance_scores = torch.tensor( [ [ [[10.0, 1.0], [10.0, 1.0]], [[30.0, 3.0], [30.0, 3.0]], [[-20.0, -2.0], [-20.0, -2.0]], ] ] ) # expected effect of pruning 1 of the 3 channels by L2-norm expected_mask_axis1 = torch.ones_like(m.weight) expected_mask_axis1[:, 0] = 0.0 prune.ln_structured( m, "weight", amount=1, n=2, dim=1, importance_scores=importance_scores ) self.assertEqual(expected_mask_axis1, m.weight_mask) # expected effect of pruning 1 of the 2 columns along axis -1 by L1-norm expected_mask_axis3 = expected_mask_axis1 expected_mask_axis3[:, :, :, 1] = 0.0 prune.ln_structured( m, "weight", amount=1, n=1, dim=-1, importance_scores=importance_scores ) self.assertEqual(expected_mask_axis3, m.weight_mask) def test_remove_pruning(self): r"""`prune.remove` removes the hook and the reparametrization and makes the pruning final in the original parameter. """ modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)] names = ["weight", "bias"] for m in modules: for name in names: with self.subTest(m=m, name=name): # first prune prune.random_unstructured(m, name, amount=0.5) self.assertIn(name + "_orig", dict(m.named_parameters())) self.assertIn(name + "_mask", dict(m.named_buffers())) self.assertNotIn(name, dict(m.named_parameters())) self.assertTrue(hasattr(m, name)) pruned_t = getattr(m, name) # then remove pruning prune.remove(m, name) self.assertIn(name, dict(m.named_parameters())) self.assertNotIn(name + "_orig", dict(m.named_parameters())) self.assertNotIn(name + "_mask", dict(m.named_buffers())) final_t = getattr(m, name) self.assertEqual(pruned_t, final_t) def test_remove_pruning_exception(self): r"""Removing from an unpruned tensor throws an assertion error""" modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)] names = ["weight", "bias"] for m in modules: for name in names: with self.subTest(m=m, name=name): # check that the module isn't pruned self.assertFalse(prune.is_pruned(m)) # since it isn't pruned, pruning can't be removed from it with self.assertRaises(ValueError): prune.remove(m, name) def test_global_pruning(self): r"""Test that global l1 unstructured pruning over 2 parameters removes the `amount=4` smallest global weights across the 2 parameters. """ m = nn.Linear(4, 2) n = nn.Linear(3, 1) # modify the weight matrices by hand m.weight = torch.nn.Parameter( torch.tensor([[1, 2, 3, 4], [-4, -3, -2, -1]]).to(dtype=torch.float32) ) n.weight = torch.nn.Parameter( torch.tensor([[0, 0.1, -2]]).to(dtype=torch.float32) ) params_to_prune = ( (m, "weight"), (n, "weight"), ) # prune the 4 smallest weights globally by L1 magnitude prune.global_unstructured( params_to_prune, pruning_method=prune.L1Unstructured, amount=4 ) expected_mweight = torch.tensor( [[0, 2, 3, 4], [-4, -3, -2, 0]], dtype=m.weight.dtype ) self.assertEqual(expected_mweight, m.weight) expected_nweight = torch.tensor([[0, 0, -2]]).to(dtype=n.weight.dtype) self.assertEqual(expected_nweight, n.weight) def test_global_pruning_importance_scores(self): r"""Test that global l1 unstructured pruning over 2 parameters removes the `amount=4` smallest global weights across the 2 parameters. """ m = nn.Linear(4, 2) n = nn.Linear(3, 1) # modify the weight matrices by hand m.weight = torch.nn.Parameter( torch.tensor([[1, 2, 3, 4], [-4, -3, -2, -1]]).to(dtype=torch.float32) ) m_importance_scores = torch.tensor( [[4, 2, 1, 3], [-3, -1, -2, -4]], dtype=torch.float32 ) n.weight = torch.nn.Parameter( torch.tensor([[0, 0.1, -2]]).to(dtype=torch.float32) ) n_importance_scores = torch.tensor([[0, 10.0, -0.2]]).to(dtype=torch.float32) params_to_prune = ( (m, "weight"), (n, "weight"), ) importance_scores = { (m, "weight"): m_importance_scores, (n, "weight"): n_importance_scores, } # prune the 4 smallest weights globally by L1 magnitude prune.global_unstructured( params_to_prune, pruning_method=prune.L1Unstructured, amount=4, importance_scores=importance_scores, ) expected_m_weight = torch.tensor( [[1, 2, 0, 4], [-4, 0, -2, -1]], dtype=m.weight.dtype ) self.assertEqual(expected_m_weight, m.weight) expected_n_weight = torch.tensor([[0, 0.1, 0]]).to(dtype=n.weight.dtype) self.assertEqual(expected_n_weight, n.weight) def test_custom_from_mask_pruning(self): r"""Test that the CustomFromMask is capable of receiving as input at instantiation time a custom mask, and combining it with the previous default mask to generate the correct final mask. """ # new mask mask = torch.tensor([[0, 1, 1, 0], [0, 0, 1, 1]]) # old mask default_mask = torch.tensor([[0, 0, 0, 0], [1, 1, 1, 1]]) # some tensor (not actually used) t = torch.rand_like(mask.to(dtype=torch.float32)) p = prune.CustomFromMask(mask=mask) computed_mask = p.compute_mask(t, default_mask) expected_mask = torch.tensor( [[0, 0, 0, 0], [0, 0, 1, 1]], dtype=computed_mask.dtype ) self.assertEqual(computed_mask, expected_mask) def test_pruning_rollback(self): r"""Test that if something fails when the we try to compute the mask, then the model isn't left in some intermediate half-pruned state. The try/except statement in `apply` should handle rolling back to the previous state before pruning began. """ modules = [nn.Linear(5, 7), nn.Conv3d(2, 2, 2)] names = ["weight", "bias"] for m in modules: for name in names: with self.subTest(m=m, name=name): with mock.patch( "torch.nn.utils.prune.L1Unstructured.compute_mask" ) as compute_mask: compute_mask.side_effect = Exception("HA!") with self.assertRaises(Exception): prune.l1_unstructured(m, name=name, amount=0.9) self.assertTrue(name in dict(m.named_parameters())) self.assertFalse(name + "_mask" in dict(m.named_buffers())) self.assertFalse(name + "_orig" in dict(m.named_parameters())) def test_pruning_serialization_model(self): # create a model model = torch.nn.Sequential( torch.nn.Linear(10, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1), ) # check that everything looks normal before pruning self.assertNotIn("0.weight_orig", model.state_dict()) self.assertNotIn("0.weight_mask", model.state_dict()) self.assertIn("0.weight", model.state_dict()) # prune one of its parameters prune.l1_unstructured(module=model[0], name="weight", amount=0.9) # check that the original weight and the new mask are present self.assertIn("0.weight_orig", model.state_dict()) self.assertIn("0.weight_mask", model.state_dict()) self.assertNotIn("0.weight", model.state_dict()) self.assertTrue(hasattr(model[0], "weight")) pruned_weight = model[0].weight with TemporaryFileName() as fname: torch.save(model, fname) # weights_only=False as this is legacy code that saves the model new_model = torch.load(fname, weights_only=False) # check that the original weight and the new mask are present self.assertIn("0.weight_orig", new_model.state_dict()) self.assertIn("0.weight_mask", new_model.state_dict()) self.assertNotIn("0.weight", new_model.state_dict()) self.assertTrue(hasattr(new_model[0], "weight")) self.assertEqual(pruned_weight, new_model[0].weight) def test_pruning_serialization_state_dict(self): # create a model model = torch.nn.Sequential( torch.nn.Linear(10, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1), ) # check that everything looks normal before pruning self.assertNotIn("0.weight_orig", model.state_dict()) self.assertNotIn("0.weight_mask", model.state_dict()) self.assertIn("0.weight", model.state_dict()) # prune one of its parameters prune.l1_unstructured(module=model[0], name="weight", amount=0.9) # check that the original weight and the new mask are present self.assertIn("0.weight_orig", model.state_dict()) self.assertIn("0.weight_mask", model.state_dict()) self.assertNotIn("0.weight", model.state_dict()) self.assertTrue(hasattr(model[0], "weight")) pruned_weight = model[0].weight # make pruning permanent and restore parameter names as in base # architecture prune.remove(module=model[0], name="weight") # check that the original weight and the new mask are no longer present self.assertNotIn("0.weight_orig", model.state_dict()) self.assertNotIn("0.weight_mask", model.state_dict()) self.assertIn("0.weight", model.state_dict()) # save the state dict of model and reload it into new_model new_model = torch.nn.Sequential( torch.nn.Linear(10, 10), torch.nn.ReLU(), torch.nn.Linear(10, 1), ) with TemporaryFileName() as fname: torch.save(model.state_dict(), fname) new_model.load_state_dict(torch.load(fname)) # check that the original weight and the new mask are not present in # new_model either. self.assertNotIn("0.weight_orig", new_model.state_dict()) self.assertNotIn("0.weight_mask", new_model.state_dict()) self.assertIn("0.weight", new_model.state_dict()) self.assertEqual(pruned_weight, new_model[0].weight) def test_prune(self): # create a new pruning method p = prune.L1Unstructured(amount=2) # create tensor to be pruned t = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).to(dtype=torch.float32) # create prior mask by hand default_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 1]]) # since we are pruning the two lowest magnitude units, the outcome of # the calculation should be this: expected_mask = torch.tensor([[0, 0, 1, 0], [1, 1, 0, 1]]) pruned_tensor = p.prune(t, default_mask) self.assertEqual(t * expected_mask, pruned_tensor) def test_prune_importance_scores(self): # create a new pruning method p = prune.L1Unstructured(amount=2) # create tensor to be pruned t = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).to(dtype=torch.float32) importance_scores = torch.tensor([[1, 2, 3, 4], [1.5, 1.6, 1.7, 1.8]]).to( dtype=torch.float32 ) # create prior mask by hand default_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 1]]) # since we are pruning the two lowest magnitude units, the outcome of # the calculation should be this: expected_mask = torch.tensor([[0, 1, 1, 0], [0, 1, 0, 1]]) pruned_tensor = p.prune(t, default_mask, importance_scores=importance_scores) self.assertEqual(t * expected_mask, pruned_tensor) def test_prune_importance_scores_mimic_default(self): # create a new pruning method p = prune.L1Unstructured(amount=2) # create tensor to be pruned t = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]).to(dtype=torch.float32) # create prior mask by hand default_mask = torch.tensor([[1, 1, 1, 0], [1, 1, 0, 1]]) # since we are pruning the two lowest magnitude units, the outcome of # the calculation should be this: expected_mask = torch.tensor([[0, 0, 1, 0], [1, 1, 0, 1]]) pruned_tensor_without_importance_scores = p.prune(t, default_mask) pruned_tensor_with_importance_scores = p.prune( t, default_mask, importance_scores=t ) self.assertEqual( pruned_tensor_without_importance_scores, pruned_tensor_with_importance_scores, ) self.assertEqual(t * expected_mask, pruned_tensor_without_importance_scores) def test_rnn_pruning(self): l = torch.nn.LSTM(32, 32) # This Module has 4 parameters called: # 'weight_ih_l0', 'weight_hh_l0', 'bias_ih_l0', 'bias_hh_l0' # Pruning one of them causes one of the weights to become a tensor prune.l1_unstructured(l, "weight_ih_l0", 0.5) assert sum(isinstance(p, torch.nn.Parameter) for p in l._flat_weights) == 3 # Removing the pruning reparameterization restores the Parameter prune.remove(l, "weight_ih_l0") assert sum(isinstance(p, torch.nn.Parameter) for p in l._flat_weights) == 4 # Make sure that, upon removal of the reparameterization, the # `._parameters` and `.named_parameters` contain the right params. # Specifically, the original weight ('weight_ih_l0') should be placed # back in the parameters, while the reparameterization component # ('weight_ih_l0_orig') should be removed. assert "weight_ih_l0" in l._parameters assert l._parameters["weight_ih_l0"] is not None assert "weight_ih_l0_orig" not in l._parameters assert "weight_ih_l0" in dict(l.named_parameters()) assert dict(l.named_parameters())["weight_ih_l0"] is not None assert "weight_ih_l0_orig" not in dict(l.named_parameters()) instantiate_parametrized_tests(TestPruningNN) if __name__ == "__main__": run_tests()
TestPruningNN
python
getsentry__sentry
src/sentry/api/endpoints/source_map_debug_blue_thunder_edition.py
{ "start": 2002, "end": 2099 }
class ____(TypedDict): url: str status: Literal["not_attempted"]
ScrapingResultNotAttempted
python
walkccc__LeetCode
solutions/720. Longest Word in Dictionary/720.py
{ "start": 0, "end": 636 }
class ____: def longestWord(self, words: list[str]) -> str: root = {} for word in words: node = root for c in word: if c not in node: node[c] = {} node = node[c] node['word'] = word def dfs(node: dict) -> str: ans = node['word'] if 'word' in node else '' for child in node: if 'word' in node[child] and len(node[child]['word']) > 0: childWord = dfs(node[child]) if len(childWord) > len(ans) or ( len(childWord) == len(ans) and childWord < ans): ans = childWord return ans return dfs(root)
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/snap/dep_snapshot.py
{ "start": 2606, "end": 3200 }
class ____( NamedTuple("_InputHandle", [("node_def_name", str), ("node_name", str), ("input_name", str)]) ): def __new__(cls, node_def_name: str, node_name: str, input_name: str): return super().__new__( cls, node_def_name=check.str_param(node_def_name, "node_def_name"), node_name=check.str_param(node_name, "node_name"), input_name=check.str_param(input_name, "input_name"), ) # This class contains all the dependency information # for a given "level" in a pipeline. So either the pipelines # or within a graph
InputHandle
python
ZoranPandovski__al-go-rithms
search/best_first_search/Python3/best_first_search.py
{ "start": 31, "end": 1324 }
class ____: # Initialize the class def __init__(self, graph_dict=None, directed=True): self.graph_dict = graph_dict or {} self.directed = directed if not directed: self.make_undirected() # Create an undirected graph by adding symmetric edges def make_undirected(self): for a in list(self.graph_dict.keys()): for (b, dist) in self.graph_dict[a].items(): self.graph_dict.setdefault(b, {})[a] = dist # Add a link from A and B of given distance, and also add the inverse link if the graph is undirected def connect(self, A, B, distance=1): self.graph_dict.setdefault(A, {})[B] = distance if not self.directed: self.graph_dict.setdefault(B, {})[A] = distance # Get neighbors or a neighbor def get(self, a, b=None): links = self.graph_dict.setdefault(a, {}) if b is None: return links else: return links.get(b) # Return a list of nodes in the graph def nodes(self): s1 = set([k for k in self.graph_dict.keys()]) s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in v.items()]) nodes = s1.union(s2) return list(nodes) # This class represent a node
Graph
python
gevent__gevent
src/gevent/_monitor.py
{ "start": 1046, "end": 1586 }
class ____(object): __slots__ = ('function', 'period', 'last_run_time') def __init__(self, function, period): self.function = function self.period = period self.last_run_time = 0 def __eq__(self, other): return self.function == other.function and self.period == other.period def __hash__(self): return hash((self.function, self.period)) def __repr__(self): return repr((self.function, self.period, self.last_run_time)) @implementer(IPeriodicMonitorThread)
_MonitorEntry
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 108676, "end": 109348 }
class ____(GeneratedAirbyteSource): @public def __init__(self, name: str, domain_name: str, api_key: str): """Airbyte Source for Freshsales. Documentation can be found at https://docs.airbyte.com/integrations/sources/freshsales Args: name (str): The name of the destination. domain_name (str): The Name of your Freshsales domain api_key (str): Freshsales API Key. See here. The key is case sensitive. """ self.domain_name = check.str_param(domain_name, "domain_name") self.api_key = check.str_param(api_key, "api_key") super().__init__("Freshsales", name)
FreshsalesSource