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
matplotlib__matplotlib
lib/matplotlib/tri/_triinterpolate.py
{ "start": 43974, "end": 44249 }
class ____(_DOF_estimator): """dz is imposed by user; accounts for scaling if any.""" def compute_dz(self, dz): (dzdx, dzdy) = dz dzdx = dzdx * self._unit_x dzdy = dzdy * self._unit_y return np.vstack([dzdx, dzdy]).T
_DOF_estimator_user
python
pypa__warehouse
warehouse/utils/webauthn.py
{ "start": 743, "end": 5609 }
class ____(Exception): pass def _get_webauthn_user_public_key_credential_descriptors(user, *, rp_id): """ Returns a webauthn.WebAuthnUser instance corresponding to the given user model, with properties suitable for usage within the webauthn API. """ return [ PublicKeyCredentialDescriptor(id=base64url_to_bytes(credential.credential_id)) for credential in user.webauthn ] def _get_webauthn_user_public_keys(user, *, rp_id): return [ ( base64url_to_bytes(credential.public_key), credential.sign_count, ) for credential in user.webauthn ] def _webauthn_b64encode(source): return base64.urlsafe_b64encode(source).rstrip(b"=") def generate_webauthn_challenge(): """ Returns a random challenge suitable for use within Webauthn's credential and configuration option objects. See: https://w3c.github.io/webauthn/#cryptographic-challenges """ return generate_challenge() def get_credential_options(user, *, challenge, rp_name, rp_id): """ Returns a dictionary of options for credential creation on the client side. """ _authenticator_selection = AuthenticatorSelectionCriteria() _authenticator_selection.user_verification = UserVerificationRequirement.DISCOURAGED options = pywebauthn.generate_registration_options( rp_id=rp_id, rp_name=rp_name, user_id=str(user.id).encode(), user_name=user.username, user_display_name=user.name or user.username, challenge=challenge, attestation=AttestationConveyancePreference.NONE, authenticator_selection=_authenticator_selection, ) return json.loads(options_to_json(options)) def get_assertion_options(user, *, challenge, rp_id): """ Returns a dictionary of options for assertion retrieval on the client side. """ options = pywebauthn.generate_authentication_options( rp_id=rp_id, challenge=challenge, allow_credentials=_get_webauthn_user_public_key_credential_descriptors( user, rp_id=rp_id ), user_verification=UserVerificationRequirement.DISCOURAGED, ) return json.loads(options_to_json(options)) def verify_registration_response(response, challenge, *, rp_id, origin): """ Validates the challenge and attestation information sent from the client during device registration. Returns a WebAuthnCredential on success. Raises RegistrationRejectedError on failire. """ # NOTE: We re-encode the challenge below, because our # response's clientData.challenge is encoded twice: # first for the entire clientData payload, and then again # for the individual challenge. encoded_challenge = _webauthn_b64encode(challenge) try: _credential = parse_registration_credential_json(response.decode()) return pywebauthn.verify_registration_response( credential=_credential, expected_challenge=encoded_challenge, expected_rp_id=rp_id, expected_origin=origin, require_user_verification=False, ) except ( InvalidAuthenticatorDataStructure, InvalidRegistrationResponse, UnsupportedPublicKeyType, ) as e: raise RegistrationRejectedError(str(e)) def verify_assertion_response(assertion, *, challenge, user, origin, rp_id): """ Validates the challenge and assertion information sent from the client during authentication. Returns an updated signage count on success. Raises AuthenticationRejectedError on failure. """ # NOTE: We re-encode the challenge below, because our # response's clientData.challenge is encoded twice: # first for the entire clientData payload, and then again # for the individual challenge. encoded_challenge = _webauthn_b64encode(challenge) webauthn_user_public_keys = _get_webauthn_user_public_keys(user, rp_id=rp_id) for public_key, current_sign_count in webauthn_user_public_keys: try: _credential = parse_authentication_credential_json(assertion.decode()) return pywebauthn.verify_authentication_response( credential=_credential, expected_challenge=encoded_challenge, expected_rp_id=rp_id, expected_origin=origin, credential_public_key=public_key, credential_current_sign_count=current_sign_count, require_user_verification=False, ) except InvalidAuthenticationResponse: pass # If we exit the loop, then we've failed to verify the assertion against # any of the user's WebAuthn credentials. Fail. raise AuthenticationRejectedError("Invalid WebAuthn credential")
RegistrationRejectedError
python
pypa__pip
src/pip/_vendor/urllib3/contrib/_securetransport/bindings.py
{ "start": 14267, "end": 14456 }
class ____(object): """ A class object that acts as essentially a namespace for CoreFoundation constants. """ kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)
CFConst
python
django__django
tests/select_for_update/models.py
{ "start": 714, "end": 925 }
class ____(models.Model): name = models.CharField(max_length=30) born = models.ForeignKey(City, models.CASCADE, related_name="+") died = models.ForeignKey(City, models.CASCADE, related_name="+")
Person
python
celery__celery
t/unit/worker/test_state.py
{ "start": 520, "end": 797 }
class ____(dict): filename = None in_sync = False closed = False def open(self, filename, **kwargs): self.filename = filename return self def sync(self): self.in_sync = True def close(self): self.closed = True
MockShelve
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1382474, "end": 1398500 }
class ____(VegaLiteSchema): r""" TimeFieldDef schema wrapper. Parameters ---------- aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', 'variancep', 'exponential', 'exponentialb'] Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``, ``"min"``, ``"max"``, ``"count"``). **Default value:** ``undefined`` (None) **See also:** `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__ documentation. 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``. bin : bool, dict, :class:`BinParams`, None A flag for binning a ``quantitative`` field, `an object defining binning parameters <https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__, or indicating that the data for ``x`` or ``y`` channel are binned before they are imported into Vega-Lite (``"binned"``). * If ``true``, default `binning parameters <https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__ will be applied. * If ``"binned"``, this indicates that the data for the ``x`` (or ``y``) channel are already binned. You can map the bin-start field to ``x`` (or ``y``) and the bin-end field to ``x2`` (or ``y2``). The scale and axis will be formatted similar to binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can also set the axis's `tickMinStep <https://vega.github.io/vega-lite/docs/axis.html#ticks>`__ property. **Default value:** ``false`` **See also:** `bin <https://vega.github.io/vega-lite/docs/bin.html>`__ documentation. field : str, dict, :class:`Field`, :class:`FieldName`, :class:`RepeatRef` **Required.** A string defining the name of the field from which to pull a data value or an object defining iterated values from the `repeat <https://vega.github.io/vega-lite/docs/repeat.html>`__ operator. **See also:** `field <https://vega.github.io/vega-lite/docs/field.html>`__ documentation. **Notes:** 1) Dots (``.``) and brackets (``[`` and ``]``) can be used to access nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"``). If field names contain dots or brackets but are not nested, you can use ``\\`` to escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"``). See more details about escaping in the `field documentation <https://vega.github.io/vega-lite/docs/field.html>`__. 2) ``field`` is not required if ``aggregate`` is ``count``. rescale : bool scale : dict, :class:`Scale`, None An object defining properties of the channel's scale, which is the function that transforms values in the data domain (numbers, dates, strings, etc) to visual values (pixels, colors, sizes) of the encoding channels. If ``null``, the scale will be `disabled and the data value will be directly encoded <https://vega.github.io/vega-lite/docs/scale.html#disable>`__. **Default value:** If undefined, default `scale properties <https://vega.github.io/vega-lite/docs/scale.html>`__ are applied. **See also:** `scale <https://vega.github.io/vega-lite/docs/scale.html>`__ documentation. sort : dict, :class:`Sort`, Sequence[str], Sequence[bool], Sequence[float], :class:`SortArray`, :class:`SortOrder`, :class:`AllSortString`, :class:`SortByChannel`, :class:`SortByEncoding`, :class:`EncodingSortField`, :class:`SortByChannelDesc`, Sequence[dict, :class:`DateTime`], Literal['-x', '-y', '-color', '-fill', '-stroke', '-strokeWidth', '-size', '-shape', '-fillOpacity', '-strokeOpacity', '-opacity', '-text', 'ascending', 'descending', 'x', 'y', 'color', 'fill', 'stroke', 'strokeWidth', 'size', 'shape', 'fillOpacity', 'strokeOpacity', 'opacity', 'text'], None Sort order for the encoded field. For continuous fields (quantitative or temporal), ``sort`` can be either ``"ascending"`` or ``"descending"``. For discrete fields, ``sort`` can be one of the following: * ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in JavaScript. * `A string indicating an encoding channel name to sort by <https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__ (e.g., ``"x"`` or ``"y"``) with an optional minus prefix for descending sort (e.g., ``"-x"`` to sort by x-field, descending). This channel string is short-form of `a sort-by-encoding definition <https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__. For example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order": "descending"}``. * `A sort field definition <https://vega.github.io/vega-lite/docs/sort.html#sort-field>`__ for sorting by another field. * `An array specifying the field values in preferred order <https://vega.github.io/vega-lite/docs/sort.html#sort-array>`__. In this case, the sort order will obey the values in the array, followed by any unspecified values in their original order. For discrete time field, values in the sort array can be `date-time definition objects <https://vega.github.io/vega-lite/docs/datetime.html>`__. In addition, for time units ``"month"`` and ``"day"``, the values can be the month or day names (case insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"``). * ``null`` indicating no sort. **Default value:** ``"ascending"`` **Note:** ``null`` and sorting by another channel is not supported for ``row`` and ``column``. **See also:** `sort <https://vega.github.io/vega-lite/docs/sort.html>`__ documentation. timeUnit : dict, :class:`TimeUnit`, :class:`MultiTimeUnit`, :class:`BinnedTimeUnit`, :class:`SingleTimeUnit`, :class:`TimeUnitParams`, :class:`UtcMultiTimeUnit`, :class:`UtcSingleTimeUnit`, :class:`LocalMultiTimeUnit`, :class:`LocalSingleTimeUnit`, Literal['binnedyear', 'binnedyearquarter', 'binnedyearquartermonth', 'binnedyearmonth', 'binnedyearmonthdate', 'binnedyearmonthdatehours', 'binnedyearmonthdatehoursminutes', 'binnedyearmonthdatehoursminutesseconds', 'binnedyearweek', 'binnedyearweekday', 'binnedyearweekdayhours', 'binnedyearweekdayhoursminutes', 'binnedyearweekdayhoursminutesseconds', 'binnedyeardayofyear', 'binnedutcyear', 'binnedutcyearquarter', 'binnedutcyearquartermonth', 'binnedutcyearmonth', 'binnedutcyearmonthdate', 'binnedutcyearmonthdatehours', 'binnedutcyearmonthdatehoursminutes', 'binnedutcyearmonthdatehoursminutesseconds', 'binnedutcyearweek', 'binnedutcyearweekday', 'binnedutcyearweekdayhours', 'binnedutcyearweekdayhoursminutes', 'binnedutcyearweekdayhoursminutesseconds', 'binnedutcyeardayofyear', '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'] Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours``) for a temporal field. or `a temporal field that gets casted as ordinal <https://vega.github.io/vega-lite/docs/type.html#cast>`__. **Default value:** ``undefined`` (None) **See also:** `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__ documentation. 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:`StandardType`, Literal['quantitative', 'ordinal', 'temporal', 'nominal'] 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. """ _schema = {"$ref": "#/definitions/TimeFieldDef"} def __init__( self, aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined, bandPosition: Optional[float] = Undefined, bin: Optional[bool | SchemaBase | Map | None] = Undefined, field: Optional[str | SchemaBase | Map] = Undefined, rescale: Optional[bool] = Undefined, scale: Optional[SchemaBase | Map | None] = Undefined, sort: Optional[ SchemaBase | Sequence[str] | Sequence[bool] | Sequence[float] | Sequence[Temporal | SchemaBase | Map] | Map | AllSortString_T | None ] = Undefined, timeUnit: Optional[ SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T ] = Undefined, title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined, type: Optional[SchemaBase | StandardType_T] = Undefined, **kwds, ): super().__init__( aggregate=aggregate, bandPosition=bandPosition, bin=bin, field=field, rescale=rescale, scale=scale, sort=sort, timeUnit=timeUnit, title=title, type=type, **kwds, )
TimeFieldDef
python
getsentry__sentry
src/sentry/ingest/transaction_clusterer/tree.py
{ "start": 1750, "end": 3744 }
class ____(Clusterer): def __init__(self, *, merge_threshold: int) -> None: self._merge_threshold = merge_threshold self._tree = Node() self._rules: list[ReplacementRule] | None = None def add_input(self, strings: Iterable[str]) -> None: for string in strings: parts = string.split(SEP, maxsplit=MAX_DEPTH) node = self._tree for part in parts: node = node.setdefault(part, Node()) def get_rules(self) -> list[ReplacementRule]: """Computes the rules for the current tree.""" self._extract_rules() self._clean_rules() self._sort_rules() assert self._rules is not None # Keep mypy happy return self._rules def _extract_rules(self) -> None: """Merge high-cardinality nodes in the graph and extract rules""" with sentry_sdk.start_span(op="cluster_merge"): self._tree.merge(self._merge_threshold) # Generate exactly 1 rule for every merge rule_paths = [path for path in self._tree.paths() if path[-1] is MERGED] self._rules = [self._build_rule(path) for path in rule_paths] def _clean_rules(self) -> None: """Deletes the rules that are not valid.""" if not self._rules: return self._rules = [rule for rule in self._rules if RuleValidator(rule).is_valid()] def _sort_rules(self) -> None: """Sorts the rules by path length, descending (most specific rule first).""" if not self._rules: return self._rules.sort(key=len, reverse=True) @staticmethod def _build_rule(path: list["Edge"]) -> ReplacementRule: path_str = SEP.join(["*" if isinstance(key, Merged) else key for key in path]) path_str += "/**" return ReplacementRule(path_str) #: Represents the edges between graph nodes. These edges serve as keys in the #: node dictionary. Edge: TypeAlias = Union[str, Merged]
TreeClusterer
python
conda__conda
conda/exceptions.py
{ "start": 16051, "end": 16605 }
class ____(ChannelError): warning = "Channel not included in allowlist" def __init__(self, channel: Channel): channel_name = channel.name channel_url = maybe_unquote(channel.base_url) message = dals( """ %(warning)s: channel name: %(channel_name)s channel url: %(channel_url)s """ ) super().__init__( message, channel_url=channel_url, channel_name=channel_name, warning=self.warning, )
ChannelNotAllowed
python
spack__spack
lib/spack/spack/new_installer.py
{ "start": 25947, "end": 26777 }
class ____: """Information about a package being built.""" __slots__ = ( "state", "explicit", "version", "hash", "name", "external", "prefix", "finished_time", "progress_percent", "control_w_conn", ) def __init__(self, spec: spack.spec.Spec, explicit: bool, control_w_conn: Connection) -> None: self.state: str = "starting" self.explicit: bool = explicit self.version: str = str(spec.version) self.hash: str = spec.dag_hash(7) self.name: str = spec.name self.external: bool = spec.external self.prefix: str = spec.prefix self.finished_time: Optional[float] = None self.progress_percent: Optional[int] = None self.control_w_conn = control_w_conn
BuildInfo
python
ZoranPandovski__al-go-rithms
data_structures/Queue/python/queue.py
{ "start": 214, "end": 1066 }
class ____(object): """Represents a Queue (FIFO) datastructure """ length = 0 head = None last = None def __init__(self): """Constructor""" self.length = 0 self.head = None self.last = None def is_empty(self): return self.length == 0 def insert(self, cargo): node = Node(cargo) # If list is empty the new node goes first if self.head is None: self.head = node self.last = self.head # Insert at the end else: self.last.next = node self.last = self.last.next self.length += 1 def remove(self): cargo = self.head.cargo self.head = self.head.next self.length -= 1 return cargo
Queue
python
numba__numba
numba/tests/test_parfors.py
{ "start": 91868, "end": 93312 }
class ____(TestParforsBase): def test_parfor_bitmask1(self): def test_impl(a, n): b = a > n a[b] = 0 return a self.check(test_impl, np.arange(10), 5) def test_parfor_bitmask2(self): def test_impl(a, b): a[b] = 0 return a a = np.arange(10) b = a > 5 self.check(test_impl, a, b) def test_parfor_bitmask3(self): def test_impl(a, b): a[b] = a[b] return a a = np.arange(10) b = a > 5 self.check(test_impl, a, b) def test_parfor_bitmask4(self): def test_impl(a, b): a[b] = (2 * a)[b] return a a = np.arange(10) b = a > 5 self.check(test_impl, a, b) def test_parfor_bitmask5(self): def test_impl(a, b): a[b] = a[b] * a[b] return a a = np.arange(10) b = a > 5 self.check(test_impl, a, b) def test_parfor_bitmask6(self): def test_impl(a, b, c): a[b] = c return a a = np.arange(10) b = a > 5 c = np.zeros(sum(b)) # expect failure due to lack of parallelism with self.assertRaises(AssertionError) as raises: self.check(test_impl, a, b, c) self.assertIn("\'@do_scheduling\' not found", str(raises.exception)) @skip_parfors_unsupported
TestParforsBitMask
python
numpy__numpy
numpy/typing/tests/data/pass/dtype.py
{ "start": 730, "end": 1070 }
class ____: dtype = np.dtype(float) np.dtype(Test()) # Methods and attributes dtype_obj.base dtype_obj.subdtype dtype_obj.newbyteorder() dtype_obj.type dtype_obj.name dtype_obj.names dtype_obj * 0 dtype_obj * 2 0 * dtype_obj 2 * dtype_obj void_dtype_obj["f0"] void_dtype_obj[0] void_dtype_obj[["f0", "f1"]] void_dtype_obj[["f0"]]
Test
python
huggingface__transformers
src/transformers/models/afmoe/modular_afmoe.py
{ "start": 7000, "end": 10195 }
class ____(LlamaAttention): """ Multi-headed attention module with optional sliding window and gating. This attention mechanism supports both full attention and sliding window attention, and includes Q/K normalization and gating of the output. It inherits from [`LlamaAttention`] to minimize the amount of custom logic we need to maintain. """ def __init__(self, config: AfmoeConfig, layer_idx: int): super().__init__(config, layer_idx) # Parent LlamaAttention already sets: layer_idx, num_heads, num_key_value_heads, num_key_value_groups, head_dim # We only add AFMoE-specific attributes self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention" self.sliding_window = config.sliding_window if self.is_local_attention else None self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps) self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps) self.gate_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False) def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_value: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape) key_states = self.k_proj(hidden_states).view(hidden_shape) value_states = self.v_proj(hidden_states).view(hidden_shape) gate_states = self.gate_proj(hidden_states) query_states = self.q_norm(query_states).transpose(1, 2) key_states = self.k_norm(key_states).transpose(1, 2) value_states = value_states.transpose(1, 2) if self.is_local_attention: cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_value is not None: cache_kwargs = {"cache_position": cache_position} key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask=attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, sliding_window=self.sliding_window, **kwargs, ) output = output.view(*input_shape, -1).contiguous() output = output * torch.sigmoid(gate_states) attn_output = self.o_proj(output) return attn_output, attn_weights
AfmoeAttention
python
kamyu104__LeetCode-Solutions
Python/maximum-product-of-two-elements-in-an-array.py
{ "start": 29, "end": 343 }
class ____(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ m1 = m2 = 0 for num in nums: if num > m1: m1, m2 = num, m1 elif num > m2: m2 = num return (m1-1)*(m2-1)
Solution
python
huggingface__transformers
tests/models/blip/test_image_processing_blip.py
{ "start": 1007, "end": 2952 }
class ____: def __init__( self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_normalize=True, do_pad=False, image_mean=[0.48145466, 0.4578275, 0.40821073], image_std=[0.26862954, 0.26130258, 0.27577711], do_convert_rgb=True, ): size = size if size is not None else {"height": 20, "width": 20} self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_resize = do_resize self.size = size self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std self.do_pad = do_pad self.do_convert_rgb = do_convert_rgb def prepare_image_processor_dict(self): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, "do_pad": self.do_pad, } def expected_output_image_shape(self, images): return self.num_channels, self.size["height"], self.size["width"] def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision
BlipImageProcessingTester
python
celery__celery
t/smoke/tests/quorum_queues/test_native_delayed_delivery.py
{ "start": 3773, "end": 10128 }
class ____: @pytest.fixture def default_worker_app(self, default_worker_app: Celery) -> Celery: app = default_worker_app app.conf.broker_transport_options = {"confirm_publish": True} app.conf.task_default_queue_type = "quorum" app.conf.task_default_exchange_type = 'topic' app.conf.task_default_routing_key = 'celery' return app def test_countdown(self, celery_setup: CeleryTestSetup): s = noop.s().set(queue=celery_setup.worker.worker_queue) result = s.apply_async(countdown=5) result.get(timeout=10) def test_countdown__no_queue_arg(self, celery_setup: CeleryTestSetup): task_route_function = lambda *args, **kwargs: { # noqa: E731 "routing_key": "celery", "exchange": "celery", "exchange_type": "topic", } celery_setup.app.conf.task_routes = (task_route_function,) s = noop.s().set() result = s.apply_async() result.get(timeout=3) def test_countdown__no_queue_arg__countdown(self, celery_setup: CeleryTestSetup): task_route_function = lambda *args, **kwargs: { # noqa: E731 "routing_key": "celery", "exchange": "celery", "exchange_type": "topic", } celery_setup.app.conf.task_routes = (task_route_function,) s = noop.s().set() result = s.apply_async(countdown=5) result.get(timeout=10) def test_eta(self, celery_setup: CeleryTestSetup): s = noop.s().set(queue=celery_setup.worker.worker_queue) result = s.apply_async(eta=datetime.now(datetime_timezone.utc) + timedelta(0, 5)) result.get(timeout=10) def test_eta_str(self, celery_setup: CeleryTestSetup): s = noop.s().set(queue=celery_setup.worker.worker_queue) result = s.apply_async(eta=(datetime.now(datetime_timezone.utc) + timedelta(0, 5)).isoformat()) result.get(timeout=10) def test_eta_in_the_past(self, celery_setup: CeleryTestSetup): s = noop.s().set(queue=celery_setup.worker.worker_queue) result = s.apply_async(eta=(datetime.now(datetime_timezone.utc) - timedelta(0, 5)).isoformat()) result.get(timeout=10) def test_long_delay(self, celery_setup: CeleryTestSetup, queues: list): """Test task with a delay longer than 24 hours.""" s = noop.s().set(queue=celery_setup.worker.worker_queue) future_time = datetime.now(datetime_timezone.utc) + timedelta(hours=25) result = s.apply_async(eta=future_time) assert result.status == "PENDING", ( f"Task should be PENDING but was {result.status}" ) assert result.ready() is False, ( "Task with future ETA should not be ready" ) def test_multiple_tasks_same_eta(self, celery_setup: CeleryTestSetup): """Test multiple tasks scheduled for the same time.""" s = noop.s().set(queue=celery_setup.worker.worker_queue) future_time = datetime.now(datetime_timezone.utc) + timedelta(seconds=5) results = [ s.apply_async(eta=future_time) for _ in range(5) ] for result in results: result.get(timeout=10) assert result.status == "SUCCESS" def test_multiple_tasks_different_delays(self, celery_setup: CeleryTestSetup): """Test multiple tasks with different delay times.""" s = noop.s().set(queue=celery_setup.worker.worker_queue) now = datetime.now(datetime_timezone.utc) results = [ s.apply_async(eta=now + timedelta(seconds=delay)) for delay in (2, 4, 6) ] completion_times = [] for result in results: result.get(timeout=10) completion_times.append(datetime.now(datetime_timezone.utc)) for i in range(1, len(completion_times)): assert completion_times[i] > completion_times[i-1], ( f"Task {i} completed at {completion_times[i]} which is not after " f"task {i-1} completed at {completion_times[i-1]}" ) def test_revoke_delayed_task(self, celery_setup: CeleryTestSetup): """Test revoking a delayed task before it executes.""" s = noop.s().set(queue=celery_setup.worker.worker_queue) result = s.apply_async(countdown=10) assert result.status == "PENDING" result.revoke() time.sleep(12) assert result.status == "REVOKED" def test_chain_with_delays(self, celery_setup: CeleryTestSetup): """Test chain of tasks with delays between them.""" c = chain( add.s(1, 2).set(countdown=2), add.s(3).set(countdown=2), add.s(4).set(countdown=2) ).set(queue=celery_setup.worker.worker_queue) result = c() assert result.get(timeout=15) == 10 def test_zero_delay(self, celery_setup: CeleryTestSetup): """Test task with zero delay/countdown.""" s = noop.s().set(queue=celery_setup.worker.worker_queue) result = s.apply_async(countdown=0) result.get(timeout=10) assert result.status == "SUCCESS" def test_negative_countdown(self, celery_setup: CeleryTestSetup): """Test task with negative countdown (should execute immediately).""" s = noop.s().set(queue=celery_setup.worker.worker_queue) result = s.apply_async(countdown=-5) result.get(timeout=10) assert result.status == "SUCCESS" def test_very_short_delay(self, celery_setup: CeleryTestSetup): """Test task with very short delay (1 second).""" s = noop.s().set(queue=celery_setup.worker.worker_queue) result = s.apply_async(countdown=1) result.get(timeout=10) assert result.status == "SUCCESS" def test_concurrent_delayed_tasks(self, celery_setup: CeleryTestSetup): """Test many concurrent delayed tasks.""" s = noop.s().set(queue=celery_setup.worker.worker_queue) future_time = datetime.now(datetime_timezone.utc) + timedelta(seconds=2) results = [ s.apply_async(eta=future_time) for _ in range(100) ] for result in results: result.get(timeout=10) assert result.status == "SUCCESS"
test_native_delayed_delivery
python
psf__black
src/black/mode.py
{ "start": 355, "end": 673 }
class ____(Enum): PY33 = 3 PY34 = 4 PY35 = 5 PY36 = 6 PY37 = 7 PY38 = 8 PY39 = 9 PY310 = 10 PY311 = 11 PY312 = 12 PY313 = 13 PY314 = 14 def pretty(self) -> str: assert self.name[:2] == "PY" return f"Python {self.name[2]}.{self.name[3:]}"
TargetVersion
python
ApeWorX__ape
src/ape_ethereum/trace.py
{ "start": 1533, "end": 2748 }
class ____(Enum): """RPC trace_transaction.""" BASIC = 0 """No tracing support; think of EthTester.""" PARITY = 1 """RPC 'trace_transaction'.""" GETH_CALL_TRACER = 2 """RPC debug_traceTransaction using tracer='callTracer'.""" GETH_STRUCT_LOG_PARSE = 3 """ RPC debug_traceTransaction using struct-log tracer and sophisticated parsing from the evm-trace library. NOT RECOMMENDED. """ @classmethod def from_key(cls, key: str) -> "TraceApproach": return cls(cls._validate(key)) @classmethod def _validate(cls, key: Any) -> "TraceApproach": if isinstance(key, TraceApproach): return key elif isinstance(key, int) or (isinstance(key, str) and key.isnumeric()): return cls(int(key)) # Check if given a name. key = key.replace("-", "_").upper() # Allow shorter, nicer values for the geth-struct-log approach. if key in ("GETH", "GETH_STRUCT_LOG", "GETH_STRUCT_LOGS"): key = "GETH_STRUCT_LOG_PARSE" for member in cls: if member.name == key: return member raise ValueError(f"No enum named '{key}'.")
TraceApproach
python
keon__algorithms
tests/test_backtrack.py
{ "start": 8434, "end": 9276 }
class ____(unittest.TestCase): def test_palindromic_substrings(self): string1 = "abc" answer1 = [['a', 'b', 'c']] self.assertEqual(palindromic_substrings(string1), sorted(answer1)) string2 = "abcba" answer2 = [['abcba'], ['a', 'bcb', 'a'], ['a', 'b', 'c', 'b', 'a']] self.assertEqual(sorted(palindromic_substrings(string2)), sorted(answer2)) string3 = "abcccba" answer3 = [['abcccba'], ['a', 'bcccb', 'a'], ['a', 'b', 'ccc', 'b', 'a'], ['a', 'b', 'cc', 'c', 'b', 'a'], ['a', 'b', 'c', 'cc', 'b', 'a'], ['a', 'b', 'c', 'c', 'c', 'b', 'a']] self.assertEqual(sorted(palindromic_substrings(string3)), sorted(answer3))
TestPalindromicSubstrings
python
encode__django-rest-framework
tests/test_request.py
{ "start": 5740, "end": 6321 }
class ____(APIView): def post(self, request): filenames = [file.temporary_file_path() for file in request.FILES.values()] for filename in filenames: assert os.path.exists(filename) return Response(status=status.HTTP_200_OK, data=filenames) urlpatterns = [ path('', MockView.as_view()), path('echo/', EchoView.as_view()), path('upload/', FileUploadView.as_view()) ] @override_settings( ROOT_URLCONF='tests.test_request', FILE_UPLOAD_HANDLERS=['django.core.files.uploadhandler.TemporaryFileUploadHandler'])
FileUploadView
python
python__mypy
mypy/nodes.py
{ "start": 67112, "end": 67596 }
class ____(Expression): """Star expression""" __slots__ = ("expr", "valid") __match_args__ = ("expr", "valid") expr: Expression valid: bool def __init__(self, expr: Expression) -> None: super().__init__() self.expr = expr # Whether this starred expression is used in a tuple/list and as lvalue self.valid = False def accept(self, visitor: ExpressionVisitor[T]) -> T: return visitor.visit_star_expr(self)
StarExpr
python
tensorflow__tensorflow
tensorflow/python/compiler/tensorrt/test/combined_nms_test.py
{ "start": 1163, "end": 3855 }
class ____(trt_test.TfTrtIntegrationTestBase): """Test for CombinedNMS op in TF-TRT.""" def setUp(self): super().setUp() self.num_boxes = 200 def GraphFn(self, boxes, scores): max_total_size = 3 score_threshold = 0.1 iou_threshold = 0.5 # Shapes max_total_size_tensor = constant_op.constant( max_total_size, dtype=dtypes.int32, name='max_total_size') iou_threshold_tensor = constant_op.constant( iou_threshold, dtype=dtypes.float32, name='iou_threshold') score_threshold_tensor = constant_op.constant( score_threshold, dtype=dtypes.float32, name='score_threshold') nms_output = image_ops_impl.combined_non_max_suppression( boxes, scores, max_total_size_tensor, max_total_size_tensor, iou_threshold_tensor, score_threshold_tensor, name='combined_nms') return [ array_ops.identity(output, name=('output_%d' % i)) for i, output in enumerate(nms_output) ] def GetParams(self): # Parameters q = 1 batch_size = 2 num_classes = 2 max_total_size = 3 boxes_shape = [batch_size, self.num_boxes, q, 4] scores_shape = [batch_size, self.num_boxes, num_classes] nmsed_boxes_shape = [batch_size, max_total_size, 4] nmsed_scores_shape = [batch_size, max_total_size] nmsed_classes_shape = [batch_size, max_total_size] valid_detections_shape = [batch_size] return self.BuildParams(self.GraphFn, dtypes.float32, [boxes_shape, scores_shape], [ nmsed_boxes_shape, nmsed_scores_shape, nmsed_classes_shape, valid_detections_shape ]) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" if not run_params.dynamic_shape: return { 'TRTEngineOp_000': [ 'combined_nms/CombinedNonMaxSuppression', 'max_total_size', 'iou_threshold', 'score_threshold' ] } else: # The CombinedNMS op is currently not converted in dynamic shape mode. # This branch shall be removed once the converter is updated to handle # input with dynamic shape. return dict() def ShouldRunTest(self, run_params): should_run, reason = super().ShouldRunTest(run_params) should_run = should_run and \ not trt_test.IsQuantizationMode(run_params.precision_mode) reason += ' and precision != INT8' # Only run for TRT 7.1.3 and above. return should_run and trt_utils.is_linked_tensorrt_version_greater_equal( 7, 1, 3), reason + ' and >= TRT 7.1.3'
CombinedNmsTest
python
huggingface__transformers
src/transformers/tokenization_utils_base.py
{ "start": 5602, "end": 45658 }
class ____(UserDict): """ Holds the output of the [`~tokenization_utils_base.PreTrainedTokenizerBase.__call__`], [`~tokenization_utils_base.PreTrainedTokenizerBase.encode_plus`] and [`~tokenization_utils_base.PreTrainedTokenizerBase.batch_encode_plus`] methods (tokens, attention_masks, etc). This class is derived from a python dictionary and can be used as a dictionary. In addition, this class exposes utility methods to map from word/character space to token space. Args: data (`dict`, *optional*): Dictionary of lists/arrays/tensors returned by the `__call__`/`encode_plus`/`batch_encode_plus` methods ('input_ids', 'attention_mask', etc.). encoding (`tokenizers.Encoding` or `Sequence[tokenizers.Encoding]`, *optional*): If the tokenizer is a fast tokenizer which outputs additional information like mapping from word/character space to token space the `tokenizers.Encoding` instance or list of instance (for batches) hold this information. tensor_type (`Union[None, str, TensorType]`, *optional*): You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization. prepend_batch_axis (`bool`, *optional*, defaults to `False`): Whether or not to add a batch axis when converting to tensors (see `tensor_type` above). Note that this parameter has an effect if the parameter `tensor_type` is set, *otherwise has no effect*. n_sequences (`Optional[int]`, *optional*): You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization. """ def __init__( self, data: Optional[dict[str, Any]] = None, encoding: Optional[Union[EncodingFast, Sequence[EncodingFast]]] = None, tensor_type: Union[None, str, TensorType] = None, prepend_batch_axis: bool = False, n_sequences: Optional[int] = None, ): super().__init__(data) # If encoding is not None, the fast tokenization is used if encoding is not None and isinstance(encoding, EncodingFast): encoding = [encoding] self._encodings = encoding if n_sequences is None and encoding is not None and encoding: n_sequences = encoding[0].n_sequences self._n_sequences = n_sequences self.convert_to_tensors(tensor_type=tensor_type, prepend_batch_axis=prepend_batch_axis) @property def n_sequences(self) -> Optional[int]: """ `Optional[int]`: The number of sequences used to generate each sample from the batch encoded in this [`BatchEncoding`]. Currently can be one of `None` (unknown), `1` (a single sentence) or `2` (a pair of sentences) """ return self._n_sequences def __getitem__(self, item: Union[int, str]) -> Union[Any, EncodingFast]: """ If the key is a string, returns the value of the dict associated to `key` ('input_ids', 'attention_mask', etc.). If the key is an integer, get the `tokenizers.Encoding` for batch item with index `key`. If the key is a slice, returns the value of the dict associated to `key` ('input_ids', 'attention_mask', etc.) with the constraint of slice. """ if isinstance(item, str): return self.data[item] elif self._encodings is not None: return self._encodings[item] elif isinstance(item, slice): return {key: self.data[key][item] for key in self.data} else: raise KeyError( "Invalid key. Only three types of key are available: " "(1) string, (2) integers for backend Encoding, and (3) slices for data subsetting." ) def __getattr__(self, item: str): try: return self.data[item] except KeyError: raise AttributeError def __getstate__(self): return {"data": self.data, "encodings": self._encodings} def __setstate__(self, state): if "data" in state: self.data = state["data"] if "encodings" in state: self._encodings = state["encodings"] # After this point: # Extended properties and methods only available for fast (Rust-based) tokenizers # provided by HuggingFace tokenizers library. @property def is_fast(self) -> bool: """ TOOD: ita i will rm this `bool`: Whether or not this BatchEncoding was created by a fast tokenizer. """ return self._encodings is not None @property def encodings(self) -> Optional[list[EncodingFast]]: """ `Optional[list[tokenizers.Encoding]]`: The list all encodings from the tokenization process. Returns `None` if the input was tokenized through Python (i.e., not a fast) tokenizer. """ return self._encodings def tokens(self, batch_index: int = 0) -> list[str]: """ Return the list of tokens (sub-parts of the input strings after word/subword splitting and before conversion to integer indices) at a given batch index (only works for the output of a fast tokenizer). Args: batch_index (`int`, *optional*, defaults to 0): The index to access in the batch. Returns: `list[str]`: The list of tokens at that index. """ if not self._encodings: raise ValueError( "tokens() is not available when using non-fast tokenizers (e.g. instance of a `XxxTokenizerFast`" " class)." ) return self._encodings[batch_index].tokens def sequence_ids(self, batch_index: int = 0) -> list[Optional[int]]: """ Return a list mapping the tokens to the id of their original sentences: - `None` for special tokens added around or between sequences, - `0` for tokens corresponding to words in the first sequence, - `1` for tokens corresponding to words in the second sequence when a pair of sequences was jointly encoded. Args: batch_index (`int`, *optional*, defaults to 0): The index to access in the batch. Returns: `list[Optional[int]]`: A list indicating the sequence id corresponding to each token. Special tokens added by the tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding sequence. """ if not self._encodings: raise ValueError( "sequence_ids() is not available when using non-fast tokenizers (e.g. instance of a `XxxTokenizerFast`" " class)." ) return self._encodings[batch_index].sequence_ids def word_ids(self, batch_index: int = 0) -> list[Optional[int]]: """ Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer. Args: batch_index (`int`, *optional*, defaults to 0): The index to access in the batch. Returns: `list[Optional[int]]`: A list indicating the word corresponding to each token. Special tokens added by the tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding word (several tokens will be mapped to the same word index if they are parts of that word). """ if not self._encodings: raise ValueError( "word_ids() is not available when using non-fast tokenizers (e.g. instance of a `XxxTokenizerFast`" " class)." ) return self._encodings[batch_index].word_ids def token_to_sequence(self, batch_or_token_index: int, token_index: Optional[int] = None) -> int: """ Get the index of the sequence represented by the given token. In the general use case, this method returns `0` for a single sequence or the first sequence of a pair, and `1` for the second sequence of a pair Can be called as: - `self.token_to_sequence(token_index)` if batch size is 1 - `self.token_to_sequence(batch_index, token_index)` if batch size is greater than 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e., words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_token_index (`int`): Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of the token in the sequence. token_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the sequence. Returns: `int`: Index of the word in the input sequence. """ if not self._encodings: raise ValueError("token_to_sequence() is not available when using Python based tokenizers") if token_index is not None: batch_index = batch_or_token_index else: batch_index = 0 token_index = batch_or_token_index if batch_index < 0: batch_index = self._batch_size + batch_index if token_index < 0: token_index = self._seq_len + token_index return self._encodings[batch_index].token_to_sequence(token_index) def token_to_word(self, batch_or_token_index: int, token_index: Optional[int] = None) -> int: """ Get the index of the word corresponding (i.e. comprising) to an encoded token in a sequence of the batch. Can be called as: - `self.token_to_word(token_index)` if batch size is 1 - `self.token_to_word(batch_index, token_index)` if batch size is greater than 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e., words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_token_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the token in the sequence. token_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the sequence. Returns: `int`: Index of the word in the input sequence. """ if not self._encodings: raise ValueError("token_to_word() is not available when using Python based tokenizers") if token_index is not None: batch_index = batch_or_token_index else: batch_index = 0 token_index = batch_or_token_index if batch_index < 0: batch_index = self._batch_size + batch_index if token_index < 0: token_index = self._seq_len + token_index return self._encodings[batch_index].token_to_word(token_index) def word_to_tokens( self, batch_or_word_index: int, word_index: Optional[int] = None, sequence_index: int = 0 ) -> Optional[TokenSpan]: """ Get the encoded token span corresponding to a word in a sequence of the batch. Token spans are returned as a [`~tokenization_utils_base.TokenSpan`] with: - **start** -- Index of the first token. - **end** -- Index of the token following the last token. Can be called as: - `self.word_to_tokens(word_index, sequence_index: int = 0)` if batch size is 1 - `self.word_to_tokens(batch_index, word_index, sequence_index: int = 0)` if batch size is greater or equal to 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_word_index (`int`): Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of the word in the sequence. word_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the sequence. sequence_index (`int`, *optional*, defaults to 0): If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided word index belongs to. Returns: ([`~tokenization_utils_base.TokenSpan`], *optional*): Span of tokens in the encoded sequence. Returns `None` if no tokens correspond to the word. This can happen especially when the token is a special token that has been used to format the tokenization. For example when we add a class token at the very beginning of the tokenization. """ if not self._encodings: raise ValueError("word_to_tokens() is not available when using Python based tokenizers") if word_index is not None: batch_index = batch_or_word_index else: batch_index = 0 word_index = batch_or_word_index if batch_index < 0: batch_index = self._batch_size + batch_index if word_index < 0: word_index = self._seq_len + word_index span = self._encodings[batch_index].word_to_tokens(word_index, sequence_index) return TokenSpan(*span) if span is not None else None def token_to_chars(self, batch_or_token_index: int, token_index: Optional[int] = None) -> Optional[CharSpan]: """ Get the character span corresponding to an encoded token in a sequence of the batch. Character spans are returned as a [`~tokenization_utils_base.CharSpan`] with: - **start** -- Index of the first character in the original string associated to the token. - **end** -- Index of the character following the last character in the original string associated to the token. Can be called as: - `self.token_to_chars(token_index)` if batch size is 1 - `self.token_to_chars(batch_index, token_index)` if batch size is greater or equal to 1 Args: batch_or_token_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the token in the sequence. token_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the token or tokens in the sequence. Returns: [`~tokenization_utils_base.CharSpan`]: Span of characters in the original string, or None, if the token (e.g. <s>, </s>) doesn't correspond to any chars in the origin string. """ if not self._encodings: raise ValueError("token_to_chars() is not available when using Python based tokenizers") if token_index is not None: batch_index = batch_or_token_index else: batch_index = 0 token_index = batch_or_token_index span_indices = self._encodings[batch_index].token_to_chars(token_index) return CharSpan(*span_indices) if span_indices is not None else None def char_to_token( self, batch_or_char_index: int, char_index: Optional[int] = None, sequence_index: int = 0 ) -> int: """ Get the index of the token in the encoded output comprising a character in the original string for a sequence of the batch. Can be called as: - `self.char_to_token(char_index)` if batch size is 1 - `self.char_to_token(batch_index, char_index)` if batch size is greater or equal to 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_char_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the word in the sequence char_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the sequence. sequence_index (`int`, *optional*, defaults to 0): If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided character index belongs to. Returns: `int`: Index of the token, or None if the char index refers to a whitespace only token and whitespace is trimmed with `trim_offsets=True`. """ if not self._encodings: raise ValueError("char_to_token() is not available when using Python based tokenizers") if char_index is not None: batch_index = batch_or_char_index else: batch_index = 0 char_index = batch_or_char_index return self._encodings[batch_index].char_to_token(char_index, sequence_index) def word_to_chars( self, batch_or_word_index: int, word_index: Optional[int] = None, sequence_index: int = 0 ) -> CharSpan: """ Get the character span in the original string corresponding to given word in a sequence of the batch. Character spans are returned as a CharSpan NamedTuple with: - start: index of the first character in the original string - end: index of the character following the last character in the original string Can be called as: - `self.word_to_chars(word_index)` if batch size is 1 - `self.word_to_chars(batch_index, word_index)` if batch size is greater or equal to 1 Args: batch_or_word_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the word in the sequence word_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the sequence. sequence_index (`int`, *optional*, defaults to 0): If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided word index belongs to. Returns: `CharSpan` or `list[CharSpan]`: Span(s) of the associated character or characters in the string. CharSpan are NamedTuple with: - start: index of the first character associated to the token in the original string - end: index of the character following the last character associated to the token in the original string """ if not self._encodings: raise ValueError("word_to_chars() is not available when using Python based tokenizers") if word_index is not None: batch_index = batch_or_word_index else: batch_index = 0 word_index = batch_or_word_index return CharSpan(*(self._encodings[batch_index].word_to_chars(word_index, sequence_index))) def char_to_word(self, batch_or_char_index: int, char_index: Optional[int] = None, sequence_index: int = 0) -> int: """ Get the word in the original string corresponding to a character in the original string of a sequence of the batch. Can be called as: - `self.char_to_word(char_index)` if batch size is 1 - `self.char_to_word(batch_index, char_index)` if batch size is greater than 1 This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized words. Args: batch_or_char_index (`int`): Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of the character in the original string. char_index (`int`, *optional*): If a batch index is provided in *batch_or_token_index*, this can be the index of the character in the original string. sequence_index (`int`, *optional*, defaults to 0): If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0 or 1) the provided character index belongs to. Returns: `int` or `list[int]`: Index or indices of the associated encoded token(s). """ if not self._encodings: raise ValueError("char_to_word() is not available when using Python based tokenizers") if char_index is not None: batch_index = batch_or_char_index else: batch_index = 0 char_index = batch_or_char_index return self._encodings[batch_index].char_to_word(char_index, sequence_index) def convert_to_tensors( self, tensor_type: Optional[Union[str, TensorType]] = None, prepend_batch_axis: bool = False ): """ Convert the inner content to tensors. Args: tensor_type (`str` or [`~utils.TensorType`], *optional*): The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If `None`, no modification is done. prepend_batch_axis (`int`, *optional*, defaults to `False`): Whether or not to add the batch dimension during the conversion. """ if tensor_type is None: return self # Convert to TensorType if not isinstance(tensor_type, TensorType): tensor_type = TensorType(tensor_type) if tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.") import torch def as_tensor(value, dtype=None): if isinstance(value, list) and len(value) > 0 and isinstance(value[0], np.ndarray): return torch.from_numpy(np.array(value)) if len(flatten(value)) == 0 and dtype is None: dtype = torch.int64 return torch.tensor(value, dtype=dtype) is_tensor = torch.is_tensor elif tensor_type == TensorType.MLX: if not is_mlx_available(): raise ImportError("Unable to convert output to MLX tensors format, MLX is not installed.") import mlx.core as mx def as_tensor(value, dtype=None): if len(flatten(value)) == 0 and dtype is None: dtype = mx.int32 return mx.array(value, dtype=dtype) def is_tensor(obj): return isinstance(obj, mx.array) else: def as_tensor(value, dtype=None): if ( isinstance(value, (list, tuple)) and len(value) > 0 and isinstance(value[0], (list, tuple, np.ndarray)) ): value_lens = [len(val) for val in value] if len(set(value_lens)) > 1 and dtype is None: # we have a ragged list so handle explicitly value = as_tensor([np.asarray(val) for val in value], dtype=object) if len(flatten(value)) == 0 and dtype is None: dtype = np.int64 return np.asarray(value, dtype=dtype) is_tensor = is_numpy_array # Do the tensor conversion in batch for key, value in self.items(): try: if prepend_batch_axis: value = [value] if not is_tensor(value): tensor = as_tensor(value) # Removing this for now in favor of controlling the shape with `prepend_batch_axis` # # at-least2d # if tensor.ndim > 2: # tensor = tensor.squeeze(0) # elif tensor.ndim < 2: # tensor = tensor[None, :] self[key] = tensor except Exception as e: if key == "overflowing_tokens": raise ValueError( "Unable to create tensor returning overflowing tokens of different lengths. " "Please see if a fast version of this tokenizer is available to have this feature available." ) from e raise ValueError( "Unable to create tensor, you should probably activate truncation and/or padding with" " 'padding=True' 'truncation=True' to have batched tensors with the same length. Perhaps your" f" features (`{key}` in this case) have excessive nesting (inputs type `list` where type `int` is" " expected)." ) from e return self def to(self, device: Union[str, "torch.device"], *, non_blocking: bool = False) -> "BatchEncoding": """ Send all values to device by calling `v.to(device, non_blocking=non_blocking)` (PyTorch only). Args: device (`str` or `torch.device`): The device to put the tensors on. non_blocking (`bool`): Whether to perform the copy asynchronously. Returns: [`BatchEncoding`]: The same instance after modification. """ requires_backends(self, ["torch"]) # This check catches things like APEX blindly calling "to" on all inputs to a module # Otherwise it passes the casts down and casts the LongTensor containing the token idxs # into a HalfTensor if isinstance(device, str) or is_torch_device(device) or isinstance(device, int): self.data = { k: v.to(device=device, non_blocking=non_blocking) if hasattr(v, "to") and callable(v.to) else v for k, v in self.data.items() } else: logger.warning(f"Attempting to cast a BatchEncoding to type {str(device)}. This is not supported.") return self ENCODE_KWARGS_DOCSTRING = r""" add_special_tokens (`bool`, *optional*, defaults to `True`): Whether or not to add special tokens when encoding the sequences. This will use the underlying `PretrainedTokenizerBase.build_inputs_with_special_tokens` function, which defines which tokens are automatically added to the input ids. This is useful if you want to add `bos` or `eos` tokens automatically. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence is provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. stride (`int`, *optional*, defaults to 0): If set to a number along with `max_length`, the overflowing tokens returned when `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence returned to provide some overlap between truncated and overflowing sequences. The value of this argument defines the number of overlapping tokens. is_split_into_words (`bool`, *optional*, defaults to `False`): Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace) which it will tokenize. This is useful for NER or token classification. pad_to_multiple_of (`int`, *optional*): If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta). padding_side (`str`, *optional*): The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. """ ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r""" return_token_type_ids (`bool`, *optional*): Whether to return token type IDs. If left to the default, will return the token type IDs according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are token type IDs?](../glossary#token-type-ids) return_attention_mask (`bool`, *optional*): Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) return_overflowing_tokens (`bool`, *optional*, defaults to `False`): Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead of returning overflowing tokens. return_special_tokens_mask (`bool`, *optional*, defaults to `False`): Whether or not to return special tokens mask information. return_offsets_mapping (`bool`, *optional*, defaults to `False`): Whether or not to return `(char_start, char_end)` for each token. This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using Python's tokenizer, this method will raise `NotImplementedError`. return_length (`bool`, *optional*, defaults to `False`): Whether or not to return the lengths of the encoded inputs. verbose (`bool`, *optional*, defaults to `True`): Whether or not to print more information and warnings. **kwargs: passed to the `self.tokenize()` method Return: [`BatchEncoding`]: A [`BatchEncoding`] with the following fields: - **input_ids** -- List of token ids to be fed to a model. [What are input IDs?](../glossary#input-ids) - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or if *"token_type_ids"* is in `self.model_input_names`). [What are token type IDs?](../glossary#token-type-ids) - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`). [What are attention masks?](../glossary#attention-mask) - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and `return_overflowing_tokens=True`). - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and `return_overflowing_tokens=True`). - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`). - **length** -- The length of the inputs (when `return_length=True`) """ INIT_TOKENIZER_DOCSTRING = r""" Class attributes (overridden by derived classes) - **vocab_files_names** (`dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each vocabulary file required by the model, and as associated values, the filename for saving the associated file (string). - **pretrained_vocab_files_map** (`dict[str, dict[str, str]]`) -- A dictionary of dictionaries, with the high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the associated pretrained vocabulary file. - **model_input_names** (`list[str]`) -- A list of inputs expected in the forward pass of the model. - **padding_side** (`str`) -- The default value for the side on which the model should have padding applied. Should be `'right'` or `'left'`. - **truncation_side** (`str`) -- The default value for the side on which the model should have truncation applied. Should be `'right'` or `'left'`. Args: model_max_length (`int`, *optional*): The maximum length (in number of tokens) for the inputs to the transformer model. When the tokenizer is loaded with [`~tokenization_utils_base.PreTrainedTokenizerBase.from_pretrained`], this will be set to the value stored for the associated model in `max_model_input_sizes` (see above). If no value is provided, will default to VERY_LARGE_INTEGER (`int(1e30)`). padding_side (`str`, *optional*): The side on which the model should have padding applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name. truncation_side (`str`, *optional*): The side on which the model should have truncation applied. Should be selected between ['right', 'left']. Default value is picked from the class attribute of the same name. chat_template (`str`, *optional*): A Jinja template string that will be used to format lists of chat messages. See https://huggingface.co/docs/transformers/chat_templating for a full description. model_input_names (`list[string]`, *optional*): The list of inputs accepted by the forward pass of the model (like `"token_type_ids"` or `"attention_mask"`). Default value is picked from the class attribute of the same name. bos_token (`str` or `tokenizers.AddedToken`, *optional*): A special token representing the beginning of a sentence. eos_token (`str` or `tokenizers.AddedToken`, *optional*): A special token representing the end of a sentence. unk_token (`str` or `tokenizers.AddedToken`, *optional*): A special token representing an out-of-vocabulary token. sep_token (`str` or `tokenizers.AddedToken`, *optional*): A special token separating two different sentences in the same input (used by BERT for instance). pad_token (`str` or `tokenizers.AddedToken`, *optional*): A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by attention mechanisms or loss computation. cls_token (`str` or `tokenizers.AddedToken`, *optional*): A special token representing the class of the input (used by BERT for instance). mask_token (`str` or `tokenizers.AddedToken`, *optional*): A special token representing a masked token (used by masked-language modeling pretraining objectives, like BERT). Will be associated to `self.mask_token` and `self.mask_token_id`. extra_special_tokens (list of `str` or `tokenizers.AddedToken`, *optional*): A list of extra model-specific special tokens. Add them here to ensure they are skipped when decoding with `skip_special_tokens` is set to True. If they are not part of the vocabulary, they will be added at the end of the vocabulary. split_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the special tokens should be split during the tokenization process. Passing will affect the internal state of the tokenizer. The default behavior is to not split special tokens. This means that if `<s>` is the `bos_token`, then `tokenizer.tokenize("<s>") = ['<s>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<s>")` will be give `['<','s', '>']`. """ @add_end_docstrings(INIT_TOKENIZER_DOCSTRING)
BatchEncoding
python
jamielennox__requests-mock
tests/pytest/test_with_pytest.py
{ "start": 4113, "end": 4393 }
class ____(object): def configure(self, requests_mock): requests_mock.get('https://httpbin.org/get', text='data') def test_one(self, requests_mock): self.configure(requests_mock) assert 'data' == requests.get('https://httpbin.org/get').text
TestClass
python
getsentry__sentry
tests/sentry/receivers/test_sentry_apps.py
{ "start": 10663, "end": 13403 }
class ____(APITestCase): def setUp(self) -> None: self.issue = self.create_group(project=self.project) self.sentry_app = self.create_sentry_app( organization=self.project.organization, events=["comment.updated", "comment.created", "comment.deleted"], ) self.install = self.create_sentry_app_installation( organization=self.organization, slug=self.sentry_app.slug ) self.login_as(self.user) def test_comment_created(self, delay: MagicMock) -> None: url = f"/api/0/issues/{self.issue.id}/notes/" data = {"text": "hello world"} self.client.post(url, data=data, format="json") note = Activity.objects.get( group=self.issue, project=self.project, type=ActivityType.NOTE.value ) comment_data = { "comment_id": note.id, "timestamp": note.datetime.isoformat(), "comment": "hello world", "project_slug": self.project.slug, } delay.assert_called_once_with( installation_id=self.install.id, issue_id=self.issue.id, type="comment.created", user_id=self.user.id, data=comment_data, ) def test_comment_updated(self, delay: MagicMock) -> None: note = self.create_comment(self.issue, self.project, self.user) url = f"/api/0/issues/{self.issue.id}/notes/{note.id}/" data = {"text": "goodbye cruel world"} self.client.put(url, data=data, format="json") data = { "comment_id": note.id, "timestamp": note.datetime.isoformat(), "comment": "goodbye cruel world", "project_slug": self.project.slug, } delay.assert_called_once_with( installation_id=self.install.id, issue_id=self.issue.id, type="comment.updated", user_id=self.user.id, data=data, ) def test_comment_deleted(self, delay: MagicMock) -> None: note = self.create_comment(self.issue, self.project, self.user) url = f"/api/0/issues/{self.issue.id}/notes/{note.id}/" self.client.delete(url, format="json") data = { "comment_id": note.id, "timestamp": note.datetime.isoformat(), "comment": "hello world", "project_slug": self.project.slug, } delay.assert_called_once_with( installation_id=self.install.id, issue_id=self.issue.id, type="comment.deleted", user_id=self.user.id, data=data, ) @patch("sentry.sentry_apps.tasks.sentry_apps.workflow_notification.delay")
TestComments
python
arrow-py__arrow
arrow/locales.py
{ "start": 40237, "end": 42436 }
class ____(SlavicBaseLocale): names = ["mk", "mk-mk"] past = "пред {0}" future = "за {0}" timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { "now": "сега", "second": "една секунда", "seconds": { "singular": "{0} секунда", "dual": "{0} секунди", "plural": "{0} секунди", }, "minute": "една минута", "minutes": { "singular": "{0} минута", "dual": "{0} минути", "plural": "{0} минути", }, "hour": "еден саат", "hours": {"singular": "{0} саат", "dual": "{0} саати", "plural": "{0} саати"}, "day": "еден ден", "days": {"singular": "{0} ден", "dual": "{0} дена", "plural": "{0} дена"}, "week": "една недела", "weeks": { "singular": "{0} недела", "dual": "{0} недели", "plural": "{0} недели", }, "month": "еден месец", "months": { "singular": "{0} месец", "dual": "{0} месеци", "plural": "{0} месеци", }, "year": "една година", "years": { "singular": "{0} година", "dual": "{0} години", "plural": "{0} години", }, } meridians = {"am": "дп", "pm": "пп", "AM": "претпладне", "PM": "попладне"} month_names = [ "", "Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември", ] month_abbreviations = [ "", "Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Септ", "Окт", "Ноем", "Декем", ] day_names = [ "", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота", "Недела", ] day_abbreviations = [ "", "Пон", "Вт", "Сре", "Чет", "Пет", "Саб", "Нед", ]
MacedonianLocale
python
pytorch__pytorch
test/test_opaque_obj_v2.py
{ "start": 1977, "end": 19718 }
class ____(TestCase): def setUp(self): self.lib = torch.library.Library("_TestOpaqueObject", "FRAGMENT") # noqa: TOR901 torch.library.define( "_TestOpaqueObject::queue_push", "(_TestOpaqueObject_OpaqueQueue a, Tensor b) -> ()", tags=torch.Tag.pt2_compliant_tag, lib=self.lib, ) @torch.library.impl( "_TestOpaqueObject::queue_push", "CompositeExplicitAutograd", lib=self.lib ) def push_impl(queue: OpaqueQueue, b: torch.Tensor) -> None: assert isinstance(queue, OpaqueQueue) queue.push(b) @torch.library.register_fake("_TestOpaqueObject::queue_push", lib=self.lib) def push_impl_fake(q: OpaqueQueue, b: torch.Tensor) -> None: pass self.lib.define( "queue_pop(_TestOpaqueObject_OpaqueQueue a) -> Tensor", ) def pop_impl(queue: OpaqueQueue) -> torch.Tensor: assert isinstance(queue, OpaqueQueue) return queue.pop() self.lib.impl("queue_pop", pop_impl, "CompositeExplicitAutograd") def pop_impl_fake(q: OpaqueQueue) -> torch.Tensor: # This is not accurate since the queue could have tensors that are # not rank 1 ctx = torch.library.get_ctx() u0 = ctx.new_dynamic_size() return torch.empty(u0) self.lib._register_fake("queue_pop", pop_impl_fake) @torch.library.custom_op( "_TestOpaqueObject::queue_size", mutates_args=[], ) def size_impl(queue: OpaqueQueue) -> int: assert isinstance(queue, OpaqueQueue) return queue.size() @size_impl.register_fake def size_impl_fake(q: OpaqueQueue) -> int: ctx = torch._custom_op.impl.get_ctx() u0 = ctx.new_dynamic_size() torch._check_is_size(u0) return u0 torch.library.define( "_TestOpaqueObject::noisy_inject", "(Tensor x, _TestOpaqueObject_RNGState obj) -> Tensor", tags=torch.Tag.pt2_compliant_tag, lib=self.lib, ) @torch.library.impl( "_TestOpaqueObject::noisy_inject", "CompositeExplicitAutograd", lib=self.lib ) def noisy_inject(x: torch.Tensor, rng_state: RNGState) -> torch.Tensor: assert isinstance(rng_state, RNGState) out = x.clone() for i in range(out.numel()): out.view(-1)[i] += rng_state.rng.random() return out @torch.library.register_fake("_TestOpaqueObject::noisy_inject", lib=self.lib) def noisy_inject_fake(x: torch.Tensor, obj: RNGState) -> torch.Tensor: return torch.empty_like(x) @torch.library.custom_op( "_TestOpaqueObject::increment_counter", mutates_args=["prev"], ) def increment_counter_impl(c: Counter, prev: torch.Tensor) -> torch.Tensor: assert isinstance(c, Counter) prev.copy_(c.counter) c.increment_counter() return c.counter @increment_counter_impl.register_fake def increment_counter_fake(c: Counter, prev: torch.Tensor) -> torch.Tensor: return torch.empty_like(prev) super().setUp() def tearDown(self): self.lib._destroy() super().tearDown() def test_ops(self): queue = OpaqueQueue([], torch.zeros(3)) torch.ops._TestOpaqueObject.queue_push(queue, torch.ones(3) + 1) size = torch.ops._TestOpaqueObject.queue_size(queue) self.assertEqual(size, 1) popped = torch.ops._TestOpaqueObject.queue_pop(queue) self.assertEqual(popped, torch.ones(3) + 1) size = torch.ops._TestOpaqueObject.queue_size(queue) self.assertEqual(size, 0) @parametrize("make_fx_tracing_mode", ["fake", "symbolic"]) def test_make_fx(self, make_fx_tracing_mode): class M(torch.nn.Module): def forward(self, queue, x): torch.ops._TestOpaqueObject.queue_push(queue, x.tan()) torch.ops._TestOpaqueObject.queue_push(queue, x.cos()) torch.ops._TestOpaqueObject.queue_push(queue, x.sin()) pop1 = torch.ops._TestOpaqueObject.queue_pop(queue) size1 = torch.ops._TestOpaqueObject.queue_size(queue) pop2 = torch.ops._TestOpaqueObject.queue_pop(queue) size2 = torch.ops._TestOpaqueObject.queue_size(queue) x_cos = pop1 + size1 x_sin = pop2 - size2 return x_sin + x_cos q1 = OpaqueQueue([], torch.empty(0).fill_(-1)) q2 = OpaqueQueue([], torch.empty(0).fill_(-1)) x = torch.ones(2, 3) gm = make_fx(M(), tracing_mode=make_fx_tracing_mode)(q1, x) self.assertTrue(torch.allclose(gm(q1, x), M()(q2, x))) self.assertEqual(q1._push_counter, 3) self.assertEqual(q1._pop_counter, 2) self.assertEqual(q1._size_counter, 2) self.assertEqual(q1.size(), 1) self.assertExpectedInline( gm.code.strip("\n"), """\ def forward(self, arg0_1, arg1_1): tan = torch.ops.aten.tan.default(arg1_1) queue_push = torch.ops._TestOpaqueObject.queue_push.default(arg0_1, tan); tan = queue_push = None cos = torch.ops.aten.cos.default(arg1_1) queue_push_1 = torch.ops._TestOpaqueObject.queue_push.default(arg0_1, cos); cos = queue_push_1 = None sin = torch.ops.aten.sin.default(arg1_1); arg1_1 = None queue_push_2 = torch.ops._TestOpaqueObject.queue_push.default(arg0_1, sin); sin = queue_push_2 = None queue_pop = torch.ops._TestOpaqueObject.queue_pop.default(arg0_1) queue_size = torch.ops._TestOpaqueObject.queue_size.default(arg0_1) queue_pop_1 = torch.ops._TestOpaqueObject.queue_pop.default(arg0_1) queue_size_1 = torch.ops._TestOpaqueObject.queue_size.default(arg0_1); arg0_1 = None add = torch.ops.aten.add.Tensor(queue_pop, queue_size); queue_pop = queue_size = None sub = torch.ops.aten.sub.Tensor(queue_pop_1, queue_size_1); queue_pop_1 = queue_size_1 = None add_1 = torch.ops.aten.add.Tensor(sub, add); sub = add = None return add_1 """, ) @parametrize("make_fx_tracing_mode", ["fake", "symbolic"]) def test_bad_fake(self, make_fx_tracing_mode): torch.library.define( "_TestOpaqueObject::bad_fake", "(Tensor x, _TestOpaqueObject_RNGState obj) -> Tensor", tags=torch.Tag.pt2_compliant_tag, lib=self.lib, ) def f(q, x): torch.ops._TestOpaqueObject.bad_fake(x, q) return x.cos() def bad_fake1(x, rng_state) -> torch.Tensor: self.assertTrue(isinstance(rng_state, FakeScriptObject)) out = x.clone() for i in range(out.numel()): out.view(-1)[i] += rng_state.rng.random() # bad: accessing attributes return out torch.library.register_fake( "_TestOpaqueObject::bad_fake", bad_fake1, lib=self.lib, allow_override=True ) with self.assertRaisesRegex( AttributeError, "Tried to call __getattr__ with attr", ): make_fx(f, tracing_mode=make_fx_tracing_mode)(RNGState(0), torch.ones(3)) def bad_fake2(x, rng_state) -> torch.Tensor: rng_state.rng = "foo" return torch.empty_like(x) torch.library.register_fake( "_TestOpaqueObject::bad_fake", bad_fake2, lib=self.lib, allow_override=True ) with self.assertRaisesRegex( AttributeError, "Tried to call __setattr__ with attr", ): make_fx(f, tracing_mode=make_fx_tracing_mode)(RNGState(0), torch.ones(3)) def test_aot_export(self): class Model(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, rng_state, x): x = torch.ops._TestOpaqueObject.noisy_inject(x, rng_state) x = x * x x = torch.ops._TestOpaqueObject.noisy_inject(x, rng_state) x = x + x return (x,) mod = Model() rng = RNGState(0) x = torch.ones(2, 3) fake_mode = torch._subclasses.fake_tensor.FakeTensorMode() fake_rng = torch._library.fake_class_registry.maybe_to_fake_obj(fake_mode, rng) fake_x = fake_mode.from_tensor(x) gm = aot_export_module(mod, (fake_rng, fake_x), trace_joint=False)[0] # By default we don't register ops containing PyObjs as being effectful self.assertExpectedInline( gm.code.strip(), """\ def forward(self, arg0_1, arg1_1): noisy_inject = torch.ops._TestOpaqueObject.noisy_inject.default(arg1_1, arg0_1); arg1_1 = None mul = torch.ops.aten.mul.Tensor(noisy_inject, noisy_inject); noisy_inject = None noisy_inject_1 = torch.ops._TestOpaqueObject.noisy_inject.default(mul, arg0_1); mul = arg0_1 = None add = torch.ops.aten.add.Tensor(noisy_inject_1, noisy_inject_1); noisy_inject_1 = None return (add,)""", # noqa: B950 ) torch.library._register_effectful_op( "_TestOpaqueObject::noisy_inject", EffectType.ORDERED ) try: gm = aot_export_module(mod, (rng, fake_x), trace_joint=False)[0] # inputs: token, rng, x # return: token, res self.assertExpectedInline( gm.code.strip(), """\ def forward(self, arg0_1, arg1_1, arg2_1): with_effects = torch.ops.higher_order.with_effects(arg0_1, torch.ops._TestOpaqueObject.noisy_inject.default, arg2_1, arg1_1); arg0_1 = arg2_1 = None getitem = with_effects[0] getitem_1 = with_effects[1]; with_effects = None mul = torch.ops.aten.mul.Tensor(getitem_1, getitem_1); getitem_1 = None with_effects_1 = torch.ops.higher_order.with_effects(getitem, torch.ops._TestOpaqueObject.noisy_inject.default, mul, arg1_1); getitem = mul = arg1_1 = None getitem_2 = with_effects_1[0] getitem_3 = with_effects_1[1]; with_effects_1 = None add = torch.ops.aten.add.Tensor(getitem_3, getitem_3); getitem_3 = None return (getitem_2, add)""", # noqa: B950 ) finally: torch.library._register_effectful_op( "_TestOpaqueObject::noisy_inject", None ) def test_compile(self): def foo(rng_state, x): x = torch.ops._TestOpaqueObject.noisy_inject(x, rng_state) x = x * x x = torch.ops._TestOpaqueObject.noisy_inject(x, rng_state) x = x + x return x rng = RNGState(0) x = torch.ones(2, 3) res = torch.compile(foo, fullgraph=True, backend="inductor")(rng, x) self.assertFalse(torch.allclose(res, x * x + x)) backend = AotEagerAndRecordGraphs() torch.compile(foo, fullgraph=True, backend=backend)(rng, x) self.assertExpectedInline( backend.graphs[0].code.strip(), """\ def forward(self, L_x_ : torch.Tensor, L_rng_state_ : __main___RNGState): l_x_ = L_x_ l_rng_state_ = L_rng_state_ x = torch.ops._TestOpaqueObject.noisy_inject(l_x_, l_rng_state_); l_x_ = None x_1 = x * x; x = None x_2 = torch.ops._TestOpaqueObject.noisy_inject(x_1, l_rng_state_); x_1 = l_rng_state_ = None x_3 = x_2 + x_2; x_2 = None return (x_3,)""", # noqa: B950 ) self.assertExpectedInline( backend.fw_graphs[0].code.strip(), """\ def forward(self, arg0_1, arg1_1): noisy_inject = torch.ops._TestOpaqueObject.noisy_inject.default(arg0_1, arg1_1); arg0_1 = None mul = torch.ops.aten.mul.Tensor(noisy_inject, noisy_inject); noisy_inject = None noisy_inject_1 = torch.ops._TestOpaqueObject.noisy_inject.default(mul, arg1_1); mul = arg1_1 = None add = torch.ops.aten.add.Tensor(noisy_inject_1, noisy_inject_1); noisy_inject_1 = None return (add,)""", # noqa: B950 ) def test_compile_intermediate(self): counter = Counter(0) def foo(x, y): z = torch.ops._TestOpaqueObject.increment_counter(counter, y) x = x * z z = torch.ops._TestOpaqueObject.increment_counter(counter, y) x = x + z return x, counter inp = (torch.tensor(1), torch.tensor(0)) backend = AotEagerAndRecordGraphs() opt_f = torch.compile(foo, fullgraph=True, backend=backend) res = opt_f(*inp) self.assertEqual(res[0], torch.tensor(3)) self.assertEqual(res[1].counter, torch.tensor(2)) res = opt_f(*inp) self.assertEqual(res[0], torch.tensor(7)) self.assertEqual(res[1].counter, torch.tensor(4)) # counter is automatically lifted as an input # Even though we returned counter in the eager code, it does not get # returned in the graph because dynamo does not detect that the object # is mutated. self.assertExpectedInline( backend.fw_graphs[0].code.strip(), """\ def forward(self, arg0_1, arg1_1, arg2_1): auto_functionalized_v2 = torch.ops.higher_order.auto_functionalized_v2(torch.ops._TestOpaqueObject.increment_counter.default, c = arg1_1, _prev_base_index = 0, _all_bases = [arg0_1]) getitem = auto_functionalized_v2[0] getitem_1 = auto_functionalized_v2[1]; auto_functionalized_v2 = None mul = torch.ops.aten.mul.Tensor(arg2_1, getitem); arg2_1 = getitem = None auto_functionalized_v2_1 = torch.ops.higher_order.auto_functionalized_v2(torch.ops._TestOpaqueObject.increment_counter.default, c = arg1_1, _prev_base_index = 0, _all_bases = [getitem_1]); arg1_1 = getitem_1 = None getitem_2 = auto_functionalized_v2_1[0] getitem_3 = auto_functionalized_v2_1[1]; auto_functionalized_v2_1 = None add = torch.ops.aten.add.Tensor(mul, getitem_2); mul = getitem_2 = None copy_ = torch.ops.aten.copy_.default(arg0_1, getitem_3); arg0_1 = getitem_3 = copy_ = None return (add,)""", # noqa: B950 ) def test_compile_attribute(self): counter = Counter(0) def foo(counter, x): x = x * x counter.increment_counter() return x with self.assertRaisesRegex( RuntimeError, "Attempted to access attributes/methods on an OpaqueObject" ): torch.compile(foo)(counter, torch.ones(2, 3)) def bar(counter, x): x = x * x x += counter.counter return x with self.assertRaisesRegex( RuntimeError, "Attempted to access attributes/methods on an OpaqueObject" ): torch.compile(bar)(counter, torch.ones(2, 3)) def test_export_joint(self): class Moo(torch.nn.Module): def forward(self, x, y): return x * y register_opaque_type(Moo, "_TestOpaqueObject_Moo") torch.library.define( "_TestOpaqueObject::module_mul", "(_TestOpaqueObject_Moo a, Tensor b, SymInt c) -> Tensor", tags=torch.Tag.pt2_compliant_tag, lib=self.lib, ) @torch.library.impl( "_TestOpaqueObject::module_mul", "CompositeExplicitAutograd", lib=self.lib ) def module_mul_impl(m: Moo, a: torch.Tensor, b: int) -> torch.Tensor: assert isinstance(m, Moo) return m(a, b) @torch.library.register_fake("_TestOpaqueObject::module_mul", lib=self.lib) def module_mul_fake(m: Moo, a: torch.Tensor, b: int) -> torch.Tensor: return torch.empty_like(a) def module_mul_setup_context(ctx, inputs, output): m, a, b = inputs ctx.b = b def module_mul_backward(ctx, grad) -> torch.Tensor: return None, grad * ctx.b, None torch.library.register_autograd( "_TestOpaqueObject::module_mul", module_mul_backward, setup_context=module_mul_setup_context, lib=self.lib, ) class M(torch.nn.Module): def __init__(self): super().__init__() self.moo = Moo() def forward(self, x, y): b = y.item() return torch.ops._TestOpaqueObject.module_mul(self.moo, x, b) inp = (torch.randn(3, requires_grad=True), torch.tensor(4)) with ExitStack() as stack: with FakeTensorMode(shape_env=ShapeEnv()): joint = aot_export_joint_with_descriptors(stack, M(), inp) self.assertExpectedInline( joint.graph_module.code.strip(), """\ def forward(self, primals, tangents): primals_1, primals_2, tangents_1, = fx_pytree.tree_flatten_spec([primals, tangents], self._in_spec) _local_scalar_dense = torch.ops.aten._local_scalar_dense.default(primals_2); primals_2 = None _opaque_obj0 = self._opaque_obj0 module_mul = torch.ops._TestOpaqueObject.module_mul.default(_opaque_obj0, primals_1, _local_scalar_dense); _opaque_obj0 = primals_1 = None mul_1 = torch.ops.aten.mul.Tensor(tangents_1, _local_scalar_dense); tangents_1 = _local_scalar_dense = None return pytree.tree_unflatten([module_mul, mul_1, None], self._out_spec)""", # noqa: B950 ) compiled_fn = aot_compile_joint_with_descriptors(joint) self.assertEqual(compiled_fn(*inp), M()(*inp)) instantiate_parametrized_tests(TestOpaqueObject) if __name__ == "__main__": run_tests()
TestOpaqueObject
python
getsentry__sentry
tests/sentry/api/endpoints/test_organization_projects_sent_first_event.py
{ "start": 118, "end": 2479 }
class ____(APITestCase): def setUp(self) -> None: self.foo = self.create_user("foo@example.com") self.org = self.create_organization(owner=self.user) self.team = self.create_team(organization=self.org) self.url = reverse( "sentry-api-0-organization-sent-first-event", kwargs={"organization_id_or_slug": self.org.slug}, ) def test_simple_sent_first_event(self) -> None: self.create_project(teams=[self.team], first_event=datetime.now(UTC)) self.create_member(organization=self.org, user=self.foo, teams=[self.team]) self.login_as(user=self.foo) response = self.client.get(self.url) assert response.status_code == 200 assert response.data["sentFirstEvent"] def test_simple_no_first_event(self) -> None: self.create_project(teams=[self.team]) self.create_member(organization=self.org, user=self.foo, teams=[self.team]) self.login_as(user=self.foo) response = self.client.get(self.url) assert response.status_code == 200 assert not response.data["sentFirstEvent"] def test_first_event_in_org(self) -> None: self.create_project(teams=[self.team], first_event=datetime.now(UTC)) self.create_member(organization=self.org, user=self.foo) self.login_as(user=self.foo) response = self.client.get(f"{self.url}?project=-1") assert response.status_code == 200 assert response.data["sentFirstEvent"] def test_no_first_event_in_member_projects(self) -> None: self.create_project(teams=[self.team], first_event=datetime.now(UTC)) self.create_member(organization=self.org, user=self.foo) self.login_as(user=self.foo) response = self.client.get(self.url) assert response.status_code == 200 assert not response.data["sentFirstEvent"] def test_first_event_from_project_ids(self) -> None: project = self.create_project(teams=[self.team], first_event=datetime.now(UTC)) self.create_member(organization=self.org, user=self.foo) self.login_as(user=self.foo) response = self.client.get(f"{self.url}?project={project.id}") assert response.status_code == 200 assert response.data["sentFirstEvent"]
OrganizationProjectsSentFirstEventEndpointTest
python
astropy__astropy
astropy/constants/codata2010.py
{ "start": 294, "end": 710 }
class ____(Constant): default_reference = "CODATA 2010" _registry = {} _has_incompatible_units = set() def __new__( cls, abbrev, name, value, unit, uncertainty, reference=default_reference, system=None, ): return super().__new__( cls, abbrev, name, value, unit, uncertainty, reference, system )
CODATA2010
python
Farama-Foundation__Gymnasium
gymnasium/envs/classic_control/mountain_car.py
{ "start": 290, "end": 10366 }
class ____(gym.Env): """ ## Description The Mountain Car MDP is a deterministic MDP that consists of a car placed stochastically at the bottom of a sinusoidal valley, with the only possible actions being the accelerations that can be applied to the car in either direction. The goal of the MDP is to strategically accelerate the car to reach the goal state on top of the right hill. There are two versions of the mountain car domain in gymnasium: one with discrete actions and one with continuous. This version is the one with discrete actions. This MDP first appeared in [Andrew Moore's PhD Thesis (1990)](https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-209.pdf) ``` @TECHREPORT{Moore90efficientmemory-based, author = {Andrew William Moore}, title = {Efficient Memory-based Learning for Robot Control}, institution = {University of Cambridge}, year = {1990} } ``` ## Observation Space The observation is a `ndarray` with shape `(2,)` where the elements correspond to the following: | Num | Observation | Min | Max | Unit | |-----|--------------------------------------|-------|------|--------------| | 0 | position of the car along the x-axis | -1.2 | 0.6 | position (m) | | 1 | velocity of the car | -0.07 | 0.07 | velocity (v) | ## Action Space There are 3 discrete deterministic actions: - 0: Accelerate to the left - 1: Don't accelerate - 2: Accelerate to the right ## Transition Dynamics: Given an action, the mountain car follows the following transition dynamics: *velocity<sub>t+1</sub> = velocity<sub>t</sub> + (action - 1) * force - cos(3 * position<sub>t</sub>) * gravity* *position<sub>t+1</sub> = position<sub>t</sub> + velocity<sub>t+1</sub>* where force = 0.001 and gravity = 0.0025. The collisions at either end are inelastic with the velocity set to 0 upon collision with the wall. The position is clipped to the range `[-1.2, 0.6]` and velocity is clipped to the range `[-0.07, 0.07]`. ## Reward: The goal is to reach the flag placed on top of the right hill as quickly as possible, as such the agent is penalised with a reward of -1 for each timestep. ## Starting State The position of the car is assigned a uniform random value in *[-0.6 , -0.4]*. The starting velocity of the car is always assigned to 0. ## Episode End The episode ends if either of the following happens: 1. Termination: The position of the car is greater than or equal to 0.5 (the goal position on top of the right hill) 2. Truncation: The length of the episode is 200. ## Arguments Mountain Car has two parameters for `gymnasium.make` with `render_mode` and `goal_velocity`. On reset, the `options` parameter allows the user to change the bounds used to determine the new random state. ```python >>> import gymnasium as gym >>> env = gym.make("MountainCar-v0", render_mode="rgb_array", goal_velocity=0.1) # default goal_velocity=0 >>> env <TimeLimit<OrderEnforcing<PassiveEnvChecker<MountainCarEnv<MountainCar-v0>>>>> >>> env.reset(seed=123, options={"x_init": np.pi/2, "y_init": 0.5}) # default x_init=np.pi, y_init=1.0 (array([-0.46352962, 0. ], dtype=float32), {}) ``` ## Version History * v0: Initial versions release """ metadata = { "render_modes": ["human", "rgb_array"], "render_fps": 30, } def __init__(self, render_mode: str | None = None, goal_velocity=0): self.min_position = -1.2 self.max_position = 0.6 self.max_speed = 0.07 self.goal_position = 0.5 self.goal_velocity = goal_velocity self.force = 0.001 self.gravity = 0.0025 self.low = np.array([self.min_position, -self.max_speed], dtype=np.float32) self.high = np.array([self.max_position, self.max_speed], dtype=np.float32) self.render_mode = render_mode self.screen_width = 600 self.screen_height = 400 self.screen = None self.clock = None self.isopen = True self.action_space = spaces.Discrete(3) self.observation_space = spaces.Box(self.low, self.high, dtype=np.float32) def step(self, action: int): assert self.action_space.contains( action ), f"{action!r} ({type(action)}) invalid" position, velocity = self.state velocity += (action - 1) * self.force + math.cos(3 * position) * (-self.gravity) velocity = np.clip(velocity, -self.max_speed, self.max_speed) position += velocity position = np.clip(position, self.min_position, self.max_position) if position == self.min_position and velocity < 0: velocity = 0 terminated = bool( position >= self.goal_position and velocity >= self.goal_velocity ) reward = -1.0 self.state = (position, velocity) if self.render_mode == "human": self.render() # truncation=False as the time limit is handled by the `TimeLimit` wrapper added during `make` return np.array(self.state, dtype=np.float32), reward, terminated, False, {} def reset( self, *, seed: int | None = None, options: dict | None = None, ): super().reset(seed=seed) # Note that if you use custom reset bounds, it may lead to out-of-bound # state/observations. low, high = utils.maybe_parse_reset_bounds(options, -0.6, -0.4) self.state = np.array([self.np_random.uniform(low=low, high=high), 0]) if self.render_mode == "human": self.render() return np.array(self.state, dtype=np.float32), {} def _height(self, xs): return np.sin(3 * xs) * 0.45 + 0.55 def render(self): if self.render_mode is None: assert self.spec is not None gym.logger.warn( "You are calling render method without specifying any render mode. " "You can specify the render_mode at initialization, " f'e.g. gym.make("{self.spec.id}", render_mode="rgb_array")' ) return try: import pygame from pygame import gfxdraw except ImportError as e: raise DependencyNotInstalled( 'pygame is not installed, run `pip install "gymnasium[classic_control]"`' ) from e if self.screen is None: pygame.init() if self.render_mode == "human": pygame.display.init() self.screen = pygame.display.set_mode( (self.screen_width, self.screen_height) ) else: # mode in "rgb_array" self.screen = pygame.Surface((self.screen_width, self.screen_height)) if self.clock is None: self.clock = pygame.time.Clock() world_width = self.max_position - self.min_position scale = self.screen_width / world_width carwidth = 40 carheight = 20 self.surf = pygame.Surface((self.screen_width, self.screen_height)) self.surf.fill((255, 255, 255)) pos = self.state[0] xs = np.linspace(self.min_position, self.max_position, 100) ys = self._height(xs) xys = list(zip((xs - self.min_position) * scale, ys * scale)) pygame.draw.aalines(self.surf, points=xys, closed=False, color=(0, 0, 0)) clearance = 10 l, r, t, b = -carwidth / 2, carwidth / 2, carheight, 0 coords = [] for c in [(l, b), (l, t), (r, t), (r, b)]: c = pygame.math.Vector2(c).rotate_rad(math.cos(3 * pos)) coords.append( ( c[0] + (pos - self.min_position) * scale, c[1] + clearance + self._height(pos) * scale, ) ) gfxdraw.aapolygon(self.surf, coords, (0, 0, 0)) gfxdraw.filled_polygon(self.surf, coords, (0, 0, 0)) for c in [(carwidth / 4, 0), (-carwidth / 4, 0)]: c = pygame.math.Vector2(c).rotate_rad(math.cos(3 * pos)) wheel = ( int(c[0] + (pos - self.min_position) * scale), int(c[1] + clearance + self._height(pos) * scale), ) gfxdraw.aacircle( self.surf, wheel[0], wheel[1], int(carheight / 2.5), (128, 128, 128) ) gfxdraw.filled_circle( self.surf, wheel[0], wheel[1], int(carheight / 2.5), (128, 128, 128) ) flagx = int((self.goal_position - self.min_position) * scale) flagy1 = int(self._height(self.goal_position) * scale) flagy2 = flagy1 + 50 gfxdraw.vline(self.surf, flagx, flagy1, flagy2, (0, 0, 0)) gfxdraw.aapolygon( self.surf, [(flagx, flagy2), (flagx, flagy2 - 10), (flagx + 25, flagy2 - 5)], (204, 204, 0), ) gfxdraw.filled_polygon( self.surf, [(flagx, flagy2), (flagx, flagy2 - 10), (flagx + 25, flagy2 - 5)], (204, 204, 0), ) self.surf = pygame.transform.flip(self.surf, False, True) self.screen.blit(self.surf, (0, 0)) if self.render_mode == "human": pygame.event.pump() self.clock.tick(self.metadata["render_fps"]) pygame.display.flip() elif self.render_mode == "rgb_array": return np.transpose( np.array(pygame.surfarray.pixels3d(self.screen)), axes=(1, 0, 2) ) def get_keys_to_action(self): # Control with left and right arrow keys. return {(): 1, (276,): 0, (275,): 2, (275, 276): 1} def close(self): if self.screen is not None: import pygame pygame.display.quit() pygame.quit() self.isopen = False
MountainCarEnv
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataprep.py
{ "start": 6240, "end": 8125 }
class ____(GoogleCloudBaseOperator): """ Create a copy of the provided flow id, as well as all contained recipes. :param dataprep_conn_id: The Dataprep connection ID :param flow_id: ID of the flow to be copied :param name: Name for the copy of the flow :param description: Description of the copy of the flow :param copy_datasources: Bool value to define should the copy of data inputs be made or not. """ template_fields: Sequence[str] = ( "flow_id", "name", "project_id", "description", ) operator_extra_links = (DataprepFlowLink(),) def __init__( self, *, project_id: str = PROVIDE_PROJECT_ID, dataprep_conn_id: str = "dataprep_default", flow_id: int | str, name: str = "", description: str = "", copy_datasources: bool = False, **kwargs, ) -> None: super().__init__(**kwargs) self.project_id = project_id self.dataprep_conn_id = dataprep_conn_id self.flow_id = flow_id self.name = name self.description = description self.copy_datasources = copy_datasources def execute(self, context: Context) -> dict: self.log.info("Copying flow with id %d...", self.flow_id) hook = GoogleDataprepHook(dataprep_conn_id=self.dataprep_conn_id) response = hook.copy_flow( flow_id=int(self.flow_id), name=self.name, description=self.description, copy_datasources=self.copy_datasources, ) copied_flow_id = response.get("id") if self.project_id and copied_flow_id: DataprepFlowLink.persist( context=context, project_id=self.project_id, flow_id=int(copied_flow_id), ) return response
DataprepCopyFlowOperator
python
Textualize__textual
docs/examples/widgets/text_area_extended.py
{ "start": 109, "end": 420 }
class ____(TextArea): """A subclass of TextArea with parenthesis-closing functionality.""" def _on_key(self, event: events.Key) -> None: if event.character == "(": self.insert("()") self.move_cursor_relative(columns=-1) event.prevent_default()
ExtendedTextArea
python
kamyu104__LeetCode-Solutions
Python/maximum-profit-from-trading-stocks-with-discounts.py
{ "start": 2474, "end": 3950 }
class ____(object): def maxProfit(self, n, present, future, hierarchy, budget): """ :type n: int :type present: List[int] :type future: List[int] :type hierarchy: List[List[int]] :type budget: int :rtype: int """ def dfs(u): dp = [collections.defaultdict(int) for _ in xrange(2)] dp[0][0] = dp[1][0] = 0 for v in adj[u]: new_dp = dfs(v) for i in xrange(2): for j1, v1 in dp[i].items(): for j2, v2 in new_dp[i].iteritems(): if j1+j2 <= budget: dp[i][j1+j2] = max(dp[i][j1+j2], v1+v2) result = [collections.defaultdict(int) for _ in xrange(2)] for i in xrange(2): for j, v in dp[0].iteritems(): result[i][j] = max(result[i][j], v) cost = present[u]>>i if cost > budget: continue profit = future[u]-cost for j, v in dp[1].iteritems(): if j+cost <= budget: result[i][j+cost] = max(result[i][j+cost], v+profit) return result # result[i][j]: max profit for budget j with i discount adj = [[] for _ in xrange(n)] for u, v in hierarchy: adj[u-1].append(v-1) return max(dfs(0)[0].itervalues())
Solution2
python
lazyprogrammer__machine_learning_examples
nlp_class2/recursive_tensorflow.py
{ "start": 916, "end": 7189 }
class ____: def __init__(self, V, D, K, activation): self.D = D self.f = activation # word embedding We = init_weight(V, D) # linear terms W1 = init_weight(D, D) W2 = init_weight(D, D) # bias bh = np.zeros(D) # output layer Wo = init_weight(D, K) bo = np.zeros(K) # make them tensorflow variables self.We = tf.Variable(We.astype(np.float32)) self.W1 = tf.Variable(W1.astype(np.float32)) self.W2 = tf.Variable(W2.astype(np.float32)) self.bh = tf.Variable(bh.astype(np.float32)) self.Wo = tf.Variable(Wo.astype(np.float32)) self.bo = tf.Variable(bo.astype(np.float32)) self.params = [self.We, self.W1, self.W2, self.Wo] def fit(self, trees, lr=1e-1, mu=0.9, reg=0.1, epochs=5): train_ops = [] costs = [] predictions = [] all_labels = [] i = 0 N = len(trees) print("Compiling ops") for t in trees: i += 1 sys.stdout.write("%d/%d\r" % (i, N)) sys.stdout.flush() logits = self.get_output(t) labels = get_labels(t) all_labels.append(labels) cost = self.get_cost(logits, labels, reg) costs.append(cost) prediction = tf.argmax(input=logits, axis=1) predictions.append(prediction) train_op = tf.compat.v1.train.MomentumOptimizer(lr, mu).minimize(cost) train_ops.append(train_op) # save for later so we don't have to recompile self.predictions = predictions self.all_labels = all_labels self.saver = tf.compat.v1.train.Saver() init = tf.compat.v1.initialize_all_variables() actual_costs = [] per_epoch_costs = [] correct_rates = [] with tf.compat.v1.Session() as session: session.run(init) for i in range(epochs): t0 = datetime.now() train_ops, costs, predictions, all_labels = shuffle(train_ops, costs, predictions, all_labels) epoch_cost = 0 n_correct = 0 n_total = 0 j = 0 N = len(train_ops) for train_op, cost, prediction, labels in zip(train_ops, costs, predictions, all_labels): _, c, p = session.run([train_op, cost, prediction]) epoch_cost += c actual_costs.append(c) n_correct += np.sum(p == labels) n_total += len(labels) j += 1 if j % 10 == 0: sys.stdout.write("j: %d, N: %d, c: %f\r" % (j, N, c)) sys.stdout.flush() print( "epoch:", i, "cost:", epoch_cost, "elapsed time:", (datetime.now() - t0) ) per_epoch_costs.append(epoch_cost) correct_rates.append(n_correct / float(n_total)) self.saver.save(session, "recursive.ckpt") plt.plot(actual_costs) plt.title("cost per train_op call") plt.show() plt.plot(per_epoch_costs) plt.title("per epoch costs") plt.show() plt.plot(correct_rates) plt.title("correct rates") plt.show() def get_cost(self, logits, labels, reg): cost = tf.reduce_mean( input_tensor=tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels ) ) rcost = sum(tf.nn.l2_loss(p) for p in self.params) cost += reg*rcost return cost # list_of_logits is an output! # it is added to using post-order traversal def get_output_recursive(self, tree, list_of_logits, is_root=True): if tree.word is not None: # this is a leaf node x = tf.nn.embedding_lookup(params=self.We, ids=[tree.word]) else: # this node has children x1 = self.get_output_recursive(tree.left, list_of_logits, is_root=False) x2 = self.get_output_recursive(tree.right, list_of_logits, is_root=False) x = self.f( tf.matmul(x1, self.W1) + tf.matmul(x2, self.W2) + self.bh) logits = tf.matmul(x, self.Wo) + self.bo list_of_logits.append(logits) return x def get_output(self, tree): logits = [] # try: self.get_output_recursive(tree, logits) # except Exception as e: # display_tree(tree) # raise e return tf.concat(logits, 0) def score(self, trees): if trees is None: predictions = self.predictions all_labels = self.all_labels else: # just build and run the predict_op for each tree # and accumulate the total predictions = [] all_labels = [] i = 0 N = len(trees) print("Compiling ops") for t in trees: i += 1 sys.stdout.write("%d/%d\r" % (i, N)) sys.stdout.flush() logits = self.get_output(t) labels = get_labels(t) all_labels.append(labels) prediction = tf.argmax(input=logits, axis=1) predictions.append(prediction) n_correct = 0 n_total = 0 with tf.compat.v1.Session() as session: self.saver.restore(session, "recursive.ckpt") for prediction, y in zip(predictions, all_labels): p = session.run(prediction) n_correct += (p[-1] == y[-1]) # we only care about the root n_total += len(y) return float(n_correct) / n_total def main(): train, test, word2idx = get_ptb_data() train = train[:100] test = test[:100] V = len(word2idx) D = 80 K = 5 model = TNN(V, D, K, tf.nn.relu) model.fit(train) print("train accuracy:", model.score(None)) print("test accuracy:", model.score(test)) if __name__ == '__main__': main()
TNN
python
coleifer__peewee
playhouse/sqlite_udf.py
{ "start": 11317, "end": 13665 }
class ____(object): def __init__(self): self.n = 0 self.values = [] def step(self, v): self.n += 1 self.values.append(v) def finalize(self): if self.n <= 1: return 0 mean = sum(self.values) / self.n return math.sqrt(sum((i - mean) ** 2 for i in self.values) / (self.n - 1)) if cython_udf is not None: damerau_levenshtein_dist = udf(STRING)(cython_udf.damerau_levenshtein_dist) levenshtein_dist = udf(STRING)(cython_udf.levenshtein_dist) str_dist = udf(STRING)(cython_udf.str_dist) median = aggregate(MATH)(cython_udf.median) if TableFunction is not None: @table_function(STRING) class RegexSearch(TableFunction): params = ['regex', 'search_string'] columns = ['match'] name = 'regex_search' def initialize(self, regex=None, search_string=None): self._iter = re.finditer(regex, search_string) def iterate(self, idx): return (next(self._iter).group(0),) @table_function(DATE) class DateSeries(TableFunction): params = ['start', 'stop', 'step_seconds'] columns = ['date'] name = 'date_series' def initialize(self, start, stop, step_seconds=86400): self.start = format_date_time_sqlite(start) self.stop = format_date_time_sqlite(stop) step_seconds = int(step_seconds) self.step_seconds = datetime.timedelta(seconds=step_seconds) if (self.start.hour == 0 and self.start.minute == 0 and self.start.second == 0 and step_seconds >= 86400): self.format = '%Y-%m-%d' elif (self.start.year == 1900 and self.start.month == 1 and self.start.day == 1 and self.stop.year == 1900 and self.stop.month == 1 and self.stop.day == 1 and step_seconds < 86400): self.format = '%H:%M:%S' else: self.format = '%Y-%m-%d %H:%M:%S' def iterate(self, idx): if self.start > self.stop: raise StopIteration current = self.start self.start += self.step_seconds return (current.strftime(self.format),)
stddev
python
jazzband__django-oauth-toolkit
oauth2_provider/middleware.py
{ "start": 223, "end": 1760 }
class ____: """ Middleware for OAuth2 user authentication This middleware is able to work along with AuthenticationMiddleware and its behaviour depends on the order it's processed with. If it comes *after* AuthenticationMiddleware and request.user is valid, leave it as is and does not proceed with token validation. If request.user is the Anonymous user proceeds and try to authenticate the user using the OAuth2 access token. If it comes *before* AuthenticationMiddleware, or AuthenticationMiddleware is not used at all, tries to authenticate user with the OAuth2 access token and set request.user field. Setting also request._cached_user field makes AuthenticationMiddleware use that instead of the one from the session. It also adds "Authorization" to the "Vary" header, so that django's cache middleware or a reverse proxy can create proper cache keys. """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # do something only if request contains a Bearer token if request.META.get("HTTP_AUTHORIZATION", "").startswith("Bearer"): if not hasattr(request, "user") or request.user.is_anonymous: user = authenticate(request=request) if user: request.user = request._cached_user = user response = self.get_response(request) patch_vary_headers(response, ("Authorization",)) return response
OAuth2TokenMiddleware
python
paramiko__paramiko
paramiko/auth_strategy.py
{ "start": 2804, "end": 3348 }
class ____(AuthSource): """ Essentially a mixin for private keys. Knows how to auth, but leaves key material discovery/loading/decryption to subclasses. Subclasses **must** ensure that they've set ``self.pkey`` to a decrypted `.PKey` instance before calling ``super().authenticate``; typically either in their ``__init__``, or in an overridden ``authenticate`` prior to its `super` call. """ def authenticate(self, transport): return transport.auth_publickey(self.username, self.pkey)
PrivateKey
python
pytorch__pytorch
torch/_jit_internal.py
{ "start": 2106, "end": 6044 }
class ____: def __getitem__(self, types): return # mypy doesn't support parameters on types, so we have to explicitly type each # list size BroadcastingList1 = BroadcastingListCls() for i in range(2, 7): globals()[f"BroadcastingList{i}"] = BroadcastingList1 def is_scripting() -> bool: r""" Function that returns True when in compilation and False otherwise. This is useful especially with the @unused decorator to leave code in your model that is not yet TorchScript compatible. .. testcode:: import torch @torch.jit.unused def unsupported_linear_op(x): return x def linear(x): if torch.jit.is_scripting(): return torch.linear(x) else: return unsupported_linear_op(x) """ return False # Retrieves a fully-qualified name (module hierarchy + classname) for a given obj. def _qualified_name(obj, mangle_name=True) -> str: # This special case allows us to override the qualified name on a type. # It's currently used in conjunction with tracing, where we create a # fake module to filter only supported attributes. However, since this # new type is defined as a local class, we need a mechanism to override # its qualname so it appears correctly in the TorchScript system. This, # we set '_jit_override_qualname' with the original traced module's # qualified name, which is picked up here if hasattr(obj, "_jit_override_qualname"): return obj._jit_override_qualname # short-circuit in cases where the object already has a known qualified name if isinstance(obj, torch._C.ScriptFunction): return obj.qualified_name if getattr(obj, "__name__", None): name = obj.__name__ # Enum classes do not have `__name__` attr, instead they have `name`. elif isinstance(obj, enum.Enum): name = obj.name else: raise RuntimeError("Could not get name of python class object") if name == "<lambda>": name = "_lambda" # make name a valid identifier module_name = obj.__module__ # If the module is actually a torchbind module, then we should short circuit if module_name == "torch._classes": return obj.qualified_name # pyrefly: ignore [missing-attribute] # The Python docs are very clear that `__module__` can be None, but I can't # figure out when it actually would be. if module_name is None: raise RuntimeError( f"Could not get qualified name for class '{name}': " "__module__ can't be None." ) # if getattr(sys.modules[module_name], name) is not obj: # raise RuntimeError(f"Could not get qualified name for class '{name}': " # f"the attr {name} on module {module_name} is not the class") # torch.package and TorchScript have separate mangling schemes to avoid # name collisions from multiple packages. To avoid them interfering with # each other, normalize the package managing here. if package_mangling.is_mangled(module_name): module_name = module_name.replace("<", "_") module_name = module_name.replace(">", "_") # The PythonExceptionValue C++ class in torch/csrc/jit/python/python_sugared_value.h # does not need mangle the python class name. if mangle_name: # __main__ is a builtin module, so rewrite it to "__torch__". if module_name == "__main__": module_name = "__torch__" else: # Everything else gets a "__torch__" prefix to avoid name collisions # with the names of user values. module_name = "__torch__." + module_name if "." in name: raise RuntimeError( f"Could not get qualified name for class '{name}': " f"'{name}' is not a valid identifier" ) return module_name + "." + name
BroadcastingListCls
python
huggingface__transformers
src/transformers/models/video_llama_3/modular_video_llama_3.py
{ "start": 15715, "end": 16942 }
class ____(SiglipEncoder): def __init__(self, config: VideoLlama3VisionConfig): super().__init__(config) self.layers = nn.ModuleList([VideoLlama3VisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]) @can_return_tuple @auto_docstring def forward( self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, BaseModelOutput]: r""" cu_seqlens (`torch.Tensor` of shape `(num_images_or_videos + 1,)`): The cumulative sequence lengths of each image or video feature. position_embeddings (`tuple(torch.Tensor, torch.Tensor)` of shape `(num_patches, head_dim // 2)`): The cosine and sine position embeddings for vision attention. """ for encoder_layer in self.layers: hidden_states = encoder_layer( hidden_states, cu_seqlens=cu_seqlens, position_embeddings=position_embeddings, **kwargs, ) return BaseModelOutput(last_hidden_state=hidden_states)
VideoLlama3VisionEncoder
python
apache__airflow
providers/openlineage/src/airflow/providers/openlineage/utils/utils.py
{ "start": 40234, "end": 47089 }
class ____(SecretsMasker): """ This class redacts sensitive data similar to SecretsMasker in Airflow logs. The difference is that our default max recursion depth is way higher - due to the structure of OL events we need more depth. Additionally, we allow data structures to specify data that needs not to be redacted by specifying _skip_redact list by deriving RedactMixin. """ @classmethod def from_masker(cls, other: SecretsMasker) -> OpenLineageRedactor: instance = cls() instance.patterns = other.patterns instance.replacer = other.replacer for attr in ["sensitive_variables_fields", "min_length_to_mask", "secret_mask_adapter"]: if hasattr(other, attr): setattr(instance, attr, getattr(other, attr)) return instance def _should_hide_value_for_key(self, name): """Compatibility helper for should_hide_value_for_key across Airflow versions.""" try: return self.should_hide_value_for_key(name) except AttributeError: # fallback to module level function return should_hide_value_for_key(name) def _redact(self, item: Redactable, name: str | None, depth: int, max_depth: int, **kwargs) -> Redacted: # type: ignore[override] if AIRFLOW_V_3_0_PLUS: # Keep compatibility for Airflow 2.x, remove when Airflow 3.0 is the minimum version class AirflowContextDeprecationWarning(UserWarning): pass else: from airflow.utils.context import ( # type: ignore[attr-defined,no-redef] AirflowContextDeprecationWarning, ) if depth > max_depth: return item try: # It's impossible to check the type of variable in a dict without accessing it, and # this already causes warning - so suppress it with suppress(AirflowContextDeprecationWarning): if type(item).__name__ == "Proxy": # Those are deprecated values in _DEPRECATION_REPLACEMENTS # in airflow.utils.context.Context return "<<non-redactable: Proxy>>" if name and self._should_hide_value_for_key(name): return self._redact_all(item, depth, max_depth) if attrs.has(type(item)): # TODO: FIXME when mypy gets compatible with new attrs for dict_key, subval in attrs.asdict( item, # type: ignore[arg-type] recurse=False, ).items(): if _is_name_redactable(dict_key, item): setattr( item, dict_key, self._redact( subval, name=dict_key, depth=(depth + 1), max_depth=max_depth, ), ) return item if is_json_serializable(item) and hasattr(item, "__dict__"): for dict_key, subval in item.__dict__.items(): if type(subval).__name__ == "Proxy": return "<<non-redactable: Proxy>>" if _is_name_redactable(dict_key, item): setattr( item, dict_key, self._redact( subval, name=dict_key, depth=(depth + 1), max_depth=max_depth, ), ) return item return super()._redact(item, name, depth, max_depth, **kwargs) except Exception as exc: log.warning("Unable to redact %r. Error was: %s: %s", item, type(exc).__name__, exc) return item def is_json_serializable(item): try: json.dumps(item) return True except (TypeError, ValueError): return False def _is_name_redactable(name, redacted): if not issubclass(redacted.__class__, RedactMixin): return not name.startswith("_") return name not in redacted.skip_redact def print_warning(log): def decorator(f): @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except Exception: log.warning( "OpenLineage event emission failed. " "Exception below is being caught but it's printed for visibility. " "This has no impact on actual task execution status.", exc_info=True, ) return wrapper return decorator def get_filtered_unknown_operator_keys(operator: BaseOperator) -> dict: not_required_keys = {"dag", "task_group"} return {attr: value for attr, value in operator.__dict__.items() if attr not in not_required_keys} def should_use_external_connection(hook) -> bool: # If we're at Airflow 2.10, the execution is process-isolated, so we can safely run those again. return True def translate_airflow_asset(asset: Asset, lineage_context) -> OpenLineageDataset | None: """ Convert an Asset with an AIP-60 compliant URI to an OpenLineageDataset. This function returns None if no URI normalizer is defined, no asset converter is found or some core Airflow changes are missing and ImportError is raised. """ if AIRFLOW_V_3_0_PLUS: from airflow.sdk.definitions.asset import _get_normalized_scheme else: try: from airflow.datasets import _get_normalized_scheme # type: ignore[no-redef] except ImportError: return None try: from airflow.providers_manager import ProvidersManager ol_converters = getattr(ProvidersManager(), "asset_to_openlineage_converters", None) if not ol_converters: ol_converters = ProvidersManager().dataset_to_openlineage_converters # type: ignore[attr-defined] normalized_uri = asset.normalized_uri except (ImportError, AttributeError): return None if normalized_uri is None: return None if not (normalized_scheme := _get_normalized_scheme(normalized_uri)): return None if (airflow_to_ol_converter := ol_converters.get(normalized_scheme)) is None: return None return airflow_to_ol_converter(Asset(uri=normalized_uri, extra=asset.extra), lineage_context)
OpenLineageRedactor
python
doocs__leetcode
solution/2700-2799/2745.Construct the Longest New String/Solution.py
{ "start": 0, "end": 221 }
class ____: def longestString(self, x: int, y: int, z: int) -> int: if x < y: return (x * 2 + z + 1) * 2 if x > y: return (y * 2 + z + 1) * 2 return (x + y + z) * 2
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 111402, "end": 115886 }
class ____(roles.InElementRole, HasCTE, Generative, LateralFromClause): """Represent a ``VALUES`` construct that can be used as a FROM element in a statement. The :class:`_expression.Values` object is created from the :func:`_expression.values` function. .. versionadded:: 1.4 """ __visit_name__ = "values" _data: Tuple[Sequence[Tuple[Any, ...]], ...] = () _unnamed: bool _traverse_internals: _TraverseInternalsType = [ ("_column_args", InternalTraversal.dp_clauseelement_list), ("_data", InternalTraversal.dp_dml_multi_values), ("name", InternalTraversal.dp_string), ("literal_binds", InternalTraversal.dp_boolean), ] + HasCTE._has_ctes_traverse_internals name_cte_columns = True def __init__( self, *columns: ColumnClause[Any], name: Optional[str] = None, literal_binds: bool = False, ): super().__init__() self._column_args = columns if name is None: self._unnamed = True self.name = _anonymous_label.safe_construct(id(self), "anon") else: self._unnamed = False self.name = name self.literal_binds = literal_binds self.named_with_column = not self._unnamed @property def _column_types(self) -> List[TypeEngine[Any]]: return [col.type for col in self._column_args] @util.ro_non_memoized_property def _all_selected_columns(self) -> _SelectIterable: return self._column_args @_generative def alias(self, name: Optional[str] = None, flat: bool = False) -> Self: """Return a new :class:`_expression.Values` construct that is a copy of this one with the given name. This method is a VALUES-specific specialization of the :meth:`_expression.FromClause.alias` method. .. seealso:: :ref:`tutorial_using_aliases` :func:`_expression.alias` """ non_none_name: str if name is None: non_none_name = _anonymous_label.safe_construct(id(self), "anon") else: non_none_name = name self.name = non_none_name self.named_with_column = True self._unnamed = False return self @_generative def lateral(self, name: Optional[str] = None) -> Self: """Return a new :class:`_expression.Values` with the lateral flag set, so that it renders as LATERAL. .. seealso:: :func:`_expression.lateral` """ non_none_name: str if name is None: non_none_name = self.name else: non_none_name = name self._is_lateral = True self.name = non_none_name self._unnamed = False return self @_generative def data(self, values: Sequence[Tuple[Any, ...]]) -> Self: """Return a new :class:`_expression.Values` construct, adding the given data to the data list. E.g.:: my_values = my_values.data([(1, "value 1"), (2, "value2")]) :param values: a sequence (i.e. list) of tuples that map to the column expressions given in the :class:`_expression.Values` constructor. """ self._data += (values,) return self def scalar_values(self) -> ScalarValues: """Returns a scalar ``VALUES`` construct that can be used as a COLUMN element in a statement. .. versionadded:: 2.0.0b4 """ return ScalarValues(self._column_args, self._data, self.literal_binds) def _populate_column_collection( self, columns: ColumnCollection[str, KeyedColumnElement[Any]], primary_key: ColumnSet, foreign_keys: Set[KeyedColumnElement[Any]], ) -> None: for c in self._column_args: if c.table is not None and c.table is not self: _, c = c._make_proxy( self, primary_key=primary_key, foreign_keys=foreign_keys ) else: # if the column was used in other contexts, ensure # no memoizations of other FROM clauses. # see test_values.py -> test_auto_proxy_select_direct_col c._reset_memoizations() columns.add(c) c.table = self @util.ro_non_memoized_property def _from_objects(self) -> List[FromClause]: return [self]
Values
python
Textualize__textual
src/textual/map_geometry.py
{ "start": 120, "end": 1363 }
class ____(NamedTuple): """Defines the absolute location of a Widget.""" region: Region """The (screen) [region][textual.geometry.Region] occupied by the widget.""" order: tuple[tuple[int, int, int], ...] """Tuple of tuples defining the painting order of the widget. Each successive triple represents painting order information with regards to ancestors in the DOM hierarchy and the last triple provides painting order information for this specific widget. """ clip: Region """A [region][textual.geometry.Region] to clip the widget by (if a Widget is within a container).""" virtual_size: Size """The virtual [size][textual.geometry.Size] (scrollable area) of a widget if it is a container.""" container_size: Size """The container [size][textual.geometry.Size] (area not occupied by scrollbars).""" virtual_region: Region """The [region][textual.geometry.Region] relative to the container (but not necessarily visible).""" dock_gutter: Spacing """Space from the container reserved by docked widgets.""" @property def visible_region(self) -> Region: """The Widget region after clipping.""" return self.clip.intersection(self.region)
MapGeometry
python
plotly__plotly.py
plotly/graph_objs/streamtube/colorbar/title/_font.py
{ "start": 233, "end": 9929 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "streamtube.colorbar.title" _path_str = "streamtube.colorbar.title.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["family"] @family.setter def family(self, val): self["family"] = val @property def lineposition(self): """ Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. The 'lineposition' property is a flaglist and may be specified as a string containing: - Any combination of ['under', 'over', 'through'] joined with '+' characters (e.g. 'under+over') OR exactly one of ['none'] (e.g. 'none') Returns ------- Any """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = val @property def shadow(self): """ Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options. The 'shadow' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = val @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def style(self): """ Sets whether a font should be styled with a normal or italic face from its family. The 'style' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'italic'] Returns ------- Any """ return self["style"] @style.setter def style(self, val): self["style"] = val @property def textcase(self): """ Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. The 'textcase' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'word caps', 'upper', 'lower'] Returns ------- Any """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = val @property def variant(self): """ Sets the variant of the font. The 'variant' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'] Returns ------- Any """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = val @property def weight(self): """ Sets the weight (or boldness) of the font. The 'weight' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 1000] OR exactly one of ['normal', 'bold'] (e.g. 'bold') Returns ------- int """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def _prop_descriptions(self): return """\ color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. """ def __init__( self, arg=None, color=None, family=None, lineposition=None, shadow=None, size=None, style=None, textcase=None, variant=None, weight=None, **kwargs, ): """ Construct a new Font object Sets this color bar's title font. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.streamtube.col orbar.title.Font` color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. Returns ------- Font """ super().__init__("font") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.streamtube.colorbar.title.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.streamtube.colorbar.title.Font`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("family", arg, family) self._set_property("lineposition", arg, lineposition) self._set_property("shadow", arg, shadow) self._set_property("size", arg, size) self._set_property("style", arg, style) self._set_property("textcase", arg, textcase) self._set_property("variant", arg, variant) self._set_property("weight", arg, weight) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Font
python
xlwings__xlwings
xlwings/constants.py
{ "start": 58395, "end": 58715 }
class ____: xlErrorBarTypeCustom = -4114 # from enum XlErrorBarType xlErrorBarTypeFixedValue = 1 # from enum XlErrorBarType xlErrorBarTypePercent = 2 # from enum XlErrorBarType xlErrorBarTypeStDev = -4155 # from enum XlErrorBarType xlErrorBarTypeStError = 4 # from enum XlErrorBarType
ErrorBarType
python
huggingface__transformers
src/transformers/models/kyutai_speech_to_text/processing_kyutai_speech_to_text.py
{ "start": 917, "end": 1499 }
class ____(ProcessorMixin): r""" Constructs a Moshi ASR processor which wraps [`EncodecFeatureExtractor`] and [`PreTrainedTokenizerFast`] into a single processor that inherits both the audio feature extraction and tokenizer functionalities. See the [`~KyutaiSpeechToTextProcessor.__call__`] for more information. """ valid_processor_kwargs = KyutaiSpeechToTextProcessorKwargs def __init__(self, feature_extractor, tokenizer): super().__init__(feature_extractor, tokenizer) __all__ = ["KyutaiSpeechToTextProcessor"]
KyutaiSpeechToTextProcessor
python
tensorflow__tensorflow
tensorflow/python/tpu/feature_column_v2_test.py
{ "start": 8005, "end": 12356 }
class ____(test.TestCase, parameterized.TestCase): @test_util.deprecated_graph_mode_only def test_defaults(self): vocabulary_size = 3 categorical_column_a = fc_lib.categorical_column_with_identity( key='aaa', num_buckets=vocabulary_size) categorical_column_b = fc_lib.categorical_column_with_identity( key='bbb', num_buckets=vocabulary_size) embedding_dimension = 2 embedding_column_b, embedding_column_a = tpu_fc.shared_embedding_columns_v2( [categorical_column_b, categorical_column_a], dimension=embedding_dimension) self.assertIs(categorical_column_a, embedding_column_a.categorical_column) self.assertIs(categorical_column_b, embedding_column_b.categorical_column) self.assertEqual((vocabulary_size, embedding_dimension), embedding_column_a.get_embedding_table_size()) self.assertEqual((vocabulary_size, embedding_dimension), embedding_column_a.get_embedding_table_size()) self.assertEqual('mean', embedding_column_a.combiner) self.assertEqual('mean', embedding_column_b.combiner) self.assertIsNotNone(embedding_column_a.get_initializer()) self.assertIsNotNone(embedding_column_b.get_initializer()) self.assertEqual('aaa_bbb_shared_embedding', embedding_column_a.get_embedding_var_name()) self.assertEqual('aaa_bbb_shared_embedding', embedding_column_b.get_embedding_var_name()) self.assertEqual('aaa_shared_embedding', embedding_column_a.name) self.assertEqual('bbb_shared_embedding', embedding_column_b.name) self.assertEqual((embedding_dimension,), embedding_column_a.variable_shape) self.assertEqual((embedding_dimension,), embedding_column_b.variable_shape) @test_util.deprecated_graph_mode_only def test_all_constructor_args(self): vocabulary_size = 3 categorical_column_a = fc_lib.categorical_column_with_identity( key='aaa', num_buckets=vocabulary_size) categorical_column_b = fc_lib.categorical_column_with_identity( key='bbb', num_buckets=vocabulary_size) embedding_dimension = 2 embedding_column_a, embedding_column_b = tpu_fc.shared_embedding_columns_v2( [categorical_column_a, categorical_column_b], dimension=embedding_dimension, combiner='my_combiner', initializer=lambda: 'my_initializer', shared_embedding_collection_name='var_scope_name') self.assertIs(categorical_column_a, embedding_column_a.categorical_column) self.assertIs(categorical_column_b, embedding_column_b.categorical_column) self.assertEqual((vocabulary_size, embedding_dimension), embedding_column_a.get_embedding_table_size()) self.assertEqual((vocabulary_size, embedding_dimension), embedding_column_a.get_embedding_table_size()) self.assertEqual('my_combiner', embedding_column_a.combiner) self.assertEqual('my_combiner', embedding_column_b.combiner) self.assertEqual('my_initializer', embedding_column_a.get_initializer()()) self.assertEqual('my_initializer', embedding_column_b.get_initializer()()) self.assertEqual('var_scope_name', embedding_column_a.get_embedding_var_name()) self.assertEqual('var_scope_name', embedding_column_b.get_embedding_var_name()) self.assertEqual('aaa_shared_embedding', embedding_column_a.name) self.assertEqual('bbb_shared_embedding', embedding_column_b.name) self.assertEqual((embedding_dimension,), embedding_column_a.variable_shape) self.assertEqual((embedding_dimension,), embedding_column_b.variable_shape) def test_deepcopy(self): vocabulary_size = 3 categorical_column_a = fc_lib.categorical_column_with_identity( key='aaa', num_buckets=vocabulary_size) categorical_column_b = fc_lib.categorical_column_with_identity( key='bbb', num_buckets=vocabulary_size) embedding_dimension = 2 columns = tpu_fc.shared_embedding_columns_v2( [categorical_column_b, categorical_column_a], dimension=embedding_dimension) columns_copy = copy.deepcopy(columns) self.assertEqual( [column._shared_embedding_collection_name for column in columns], [column._shared_embedding_collection_name for column in columns_copy])
SharedEmbeddingColumnTestV2
python
chroma-core__chroma
chromadb/api/async_api.py
{ "start": 998, "end": 10651 }
class ____(ABC): @abstractmethod async def heartbeat(self) -> int: """Get the current time in nanoseconds since epoch. Used to check if the server is alive. Returns: int: The current time in nanoseconds since epoch """ pass # # COLLECTION METHODS # @abstractmethod async def count_collections(self) -> int: """Count the number of collections. Returns: int: The number of collections. Examples: ```python await client.count_collections() # 1 ``` """ pass @abstractmethod async def _modify( self, id: UUID, new_name: Optional[str] = None, new_metadata: Optional[CollectionMetadata] = None, new_configuration: Optional[UpdateCollectionConfiguration] = None, ) -> None: """[Internal] Modify a collection by UUID. Can update the name and/or metadata. Args: id: The internal UUID of the collection to modify. new_name: The new name of the collection. If None, the existing name will remain. Defaults to None. new_metadata: The new metadata to associate with the collection. Defaults to None. new_configuration: The new configuration to associate with the collection. Defaults to None. """ pass @abstractmethod async def delete_collection( self, name: str, ) -> None: """Delete a collection with the given name. Args: name: The name of the collection to delete. Raises: ValueError: If the collection does not exist. Examples: ```python await client.delete_collection("my_collection") ``` """ pass # # ITEM METHODS # @abstractmethod async def _add( self, ids: IDs, collection_id: UUID, embeddings: Embeddings, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> bool: """[Internal] Add embeddings to a collection specified by UUID. If (some) ids already exist, only the new embeddings will be added. Args: ids: The ids to associate with the embeddings. collection_id: The UUID of the collection to add the embeddings to. embedding: The sequence of embeddings to add. metadata: The metadata to associate with the embeddings. Defaults to None. documents: The documents to associate with the embeddings. Defaults to None. uris: URIs of data sources for each embedding. Defaults to None. Returns: True if the embeddings were added successfully. """ pass @abstractmethod async def _update( self, collection_id: UUID, ids: IDs, embeddings: Optional[Embeddings] = None, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> bool: """[Internal] Update entries in a collection specified by UUID. Args: collection_id: The UUID of the collection to update the embeddings in. ids: The IDs of the entries to update. embeddings: The sequence of embeddings to update. Defaults to None. metadatas: The metadata to associate with the embeddings. Defaults to None. documents: The documents to associate with the embeddings. Defaults to None. uris: URIs of data sources for each embedding. Defaults to None. Returns: True if the embeddings were updated successfully. """ pass @abstractmethod async def _upsert( self, collection_id: UUID, ids: IDs, embeddings: Embeddings, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> bool: """[Internal] Add or update entries in the a collection specified by UUID. If an entry with the same id already exists, it will be updated, otherwise it will be added. Args: collection_id: The collection to add the embeddings to ids: The ids to associate with the embeddings. Defaults to None. embeddings: The sequence of embeddings to add metadatas: The metadata to associate with the embeddings. Defaults to None. documents: The documents to associate with the embeddings. Defaults to None. uris: URIs of data sources for each embedding. Defaults to None. """ pass @abstractmethod async def _count(self, collection_id: UUID) -> int: """[Internal] Returns the number of entries in a collection specified by UUID. Args: collection_id: The UUID of the collection to count the embeddings in. Returns: int: The number of embeddings in the collection """ pass @abstractmethod async def _peek(self, collection_id: UUID, n: int = 10) -> GetResult: """[Internal] Returns the first n entries in a collection specified by UUID. Args: collection_id: The UUID of the collection to peek into. n: The number of entries to peek. Defaults to 10. Returns: GetResult: The first n entries in the collection. """ pass @abstractmethod async def _get( self, collection_id: UUID, ids: Optional[IDs] = None, where: Optional[Where] = None, limit: Optional[int] = None, offset: Optional[int] = None, where_document: Optional[WhereDocument] = None, include: Include = IncludeMetadataDocuments, ) -> GetResult: """[Internal] Returns entries from a collection specified by UUID. Args: ids: The IDs of the entries to get. Defaults to None. where: Conditional filtering on metadata. Defaults to None. limit: The maximum number of entries to return. Defaults to None. offset: The number of entries to skip before returning. Defaults to None. where_document: Conditional filtering on documents. Defaults to None. include: The fields to include in the response. Defaults to ["embeddings", "metadatas", "documents"]. Returns: GetResult: The entries in the collection that match the query. """ pass @abstractmethod async def _delete( self, collection_id: UUID, ids: Optional[IDs], where: Optional[Where] = None, where_document: Optional[WhereDocument] = None, ) -> None: """[Internal] Deletes entries from a collection specified by UUID. Args: collection_id: The UUID of the collection to delete the entries from. ids: The IDs of the entries to delete. Defaults to None. where: Conditional filtering on metadata. Defaults to None. where_document: Conditional filtering on documents. Defaults to None. Returns: IDs: The list of IDs of the entries that were deleted. """ pass @abstractmethod async def _query( self, collection_id: UUID, query_embeddings: Embeddings, ids: Optional[IDs] = None, n_results: int = 10, where: Optional[Where] = None, where_document: Optional[WhereDocument] = None, include: Include = IncludeMetadataDocumentsDistances, ) -> QueryResult: """[Internal] Performs a nearest neighbors query on a collection specified by UUID. Args: collection_id: The UUID of the collection to query. query_embeddings: The embeddings to use as the query. n_results: The number of results to return. Defaults to 10. where: Conditional filtering on metadata. Defaults to None. where_document: Conditional filtering on documents. Defaults to None. include: The fields to include in the response. Defaults to ["embeddings", "metadatas", "documents", "distances"]. Returns: QueryResult: The results of the query. """ pass @abstractmethod async def reset(self) -> bool: """Resets the database. This will delete all collections and entries. Returns: bool: True if the database was reset successfully. """ pass @abstractmethod async def get_version(self) -> str: """Get the version of Chroma. Returns: str: The version of Chroma """ pass @abstractmethod def get_settings(self) -> Settings: """Get the settings used to initialize. Returns: Settings: The settings used to initialize. """ pass @abstractmethod async def get_max_batch_size(self) -> int: """Return the maximum number of records that can be created or mutated in a single call.""" pass @abstractmethod async def get_user_identity(self) -> UserIdentity: """Resolve the tenant and databases for the client. Returns the default values if can't be resolved. """ pass
AsyncBaseAPI
python
huggingface__transformers
src/transformers/generation/logits_process.py
{ "start": 120514, "end": 127894 }
class ____(LogitsProcessor): r""" Logits processor for watermarking generated text. The processor modifies model output scores by adding a small bias to randomized set of "green" tokens before generating the next token. "Green" tokens selection process depends on the `seeding_scheme` used. The code was based on the [original repo](https://github.com/jwkirchenbauer/lm-watermarking/tree/main). The text generated by this `LogitsProcessor` can be detected using `WatermarkDetector`. See [`~WatermarkDetector.__call__`] for details, See [the paper](https://huggingface.co/papers/2306.04634) for more information. Args: vocab_size (`int`): The model tokenizer's vocab_size. Used to calculate "green" tokens ratio. device (`str`): The device where model is allocated. greenlist_ratio (`float`, optional, *optional*, defaults to 0.25): The ratio of "green" tokens used to the vocabulary size. Defaults to 0.25. bias (`float`, optional, *optional*, defaults to 2.0): The bias added to the selected "green" tokens' logits. Consider lowering the `bias` if the text generation quality degrades. Recommended values are in the range of [0.5, 2.0]. Defaults to 2.0. hashing_key (`int`, optional, *optional*, defaults to 15485863): Key used for hashing. If you deploy this watermark, we advise using another private key. Defaults to 15485863 (the millionth prime). seeding_scheme (`str`, optional, *optional*, defaults to `"lefthash"`): The seeding scheme used for selecting "green" tokens. Accepts values: - "lefthash" (default): "green" tokens selection depend on the last token (Algorithm 2 from paper) - "selfhash": "green" tokens selection depends on the current token itself (Algorithm 3 from paper) The downside of this scheme is that it considers all possible next tokens and can be slower than "lefthash". The context length of previous tokens to use in seeding. Higher context length makes watermarking more robust. context_width (`int`, *optional*, defaults to 1): The number of previous tokens to use when setting the seed. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkingConfig >>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") >>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") >>> inputs = tokenizer(["Alice and Bob are"], return_tensors="pt") >>> # normal generation >>> out = model.generate(inputs["input_ids"], max_length=20, do_sample=False) >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0] 'Alice and Bob are both in the same room.\n\n"I\'m not sure if you\'re' >>> # watermarked generation >>> watermarking_config = WatermarkingConfig(bias=2.5, context_width=2, seeding_scheme="selfhash") >>> out = model.generate(inputs["input_ids"], watermarking_config=watermarking_config, max_length=20, do_sample=False) >>> tokenizer.batch_decode(out, skip_special_tokens=True)[0] 'Alice and Bob are both still alive and well and the story is pretty much a one-hour adventure' >>> # to detect watermarked text use the WatermarkDetector class >>> from transformers import WatermarkDetector >>> detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config= watermarking_config) >>> detection_preds = detector(out) >>> detection_preds array([ True]) ``` """ def __init__( self, vocab_size, device, greenlist_ratio: float = 0.25, bias: float = 2.0, hashing_key: int = 15485863, seeding_scheme: str = "lefthash", context_width: int = 1, ): if seeding_scheme not in ["selfhash", "lefthash"]: raise ValueError(f"seeding_scheme has to be one of [`selfhash`, `lefthash`], but found {seeding_scheme}") if greenlist_ratio >= 1.0 or greenlist_ratio <= 0.0: raise ValueError( f"greenlist_ratio has be in range between 0.0 and 1.0, exclusively. but found {greenlist_ratio}" ) self.vocab_size = vocab_size self.greenlist_size = int(self.vocab_size * greenlist_ratio) self.bias = bias self.seeding_scheme = seeding_scheme self.rng = torch.Generator(device=device) self.hash_key = hashing_key self.context_width = context_width self.rng.manual_seed(hashing_key) self.table_size = 1_000_003 self.fixed_table = torch.randperm(self.table_size, generator=self.rng, device=device) def set_seed(self, input_seq: torch.LongTensor): input_seq = input_seq[-self.context_width :] if self.seeding_scheme == "selfhash": a = self.fixed_table[input_seq % self.table_size] + 1 b = self.fixed_table[input_seq[-1] % self.table_size] + 1 seed = (self.hash_key * a * b).min().item() else: seed = self.hash_key * input_seq[-1].item() self.rng.manual_seed(seed % (2**64 - 1)) def _get_greenlist_ids(self, input_seq: torch.LongTensor) -> torch.LongTensor: self.set_seed(input_seq) vocab_permutation = torch.randperm(self.vocab_size, device=input_seq.device, generator=self.rng) greenlist_ids = vocab_permutation[: self.greenlist_size] return greenlist_ids def _score_rejection_sampling(self, input_seq: torch.LongTensor, scores: torch.FloatTensor) -> torch.LongTensor: """ Generate greenlist based on current candidate next token. Reject and move on if necessary. Runs for a fixed number of steps only for efficiency, since the methods is not batched. """ final_greenlist = [] _, greedy_predictions = scores.sort(dim=-1, descending=True) # 40 is an arbitrary number chosen to save compute and not run for long (taken from orig repo) for i in range(40): greenlist_ids = self._get_greenlist_ids(torch.cat([input_seq, greedy_predictions[i, None]], dim=-1)) if greedy_predictions[i] in greenlist_ids: final_greenlist.append(greedy_predictions[i]) return torch.tensor(final_greenlist, device=input_seq.device) @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING) def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor: if input_ids.shape[-1] < self.context_width: logger.warning( f"`input_ids` should have at least `{self.context_width}` tokens but has {input_ids.shape[-1]}. " "The seeding will be skipped for this generation step!" ) return scores scores_processed = scores.clone() for b_idx, input_seq in enumerate(input_ids): if self.seeding_scheme == "selfhash": greenlist_ids = self._score_rejection_sampling(input_seq, scores[b_idx]) else: greenlist_ids = self._get_greenlist_ids(input_seq) scores_processed[b_idx, greenlist_ids] = scores_processed[b_idx, greenlist_ids] + self.bias return scores_processed
WatermarkLogitsProcessor
python
PrefectHQ__prefect
src/prefect/server/orchestration/global_policy.py
{ "start": 4194, "end": 4736 }
class ____( BaseUniversalTransform[ orm_models.Run, Union[core.FlowRunPolicy, core.TaskRunPolicy] ] ): """ Updates the state name of a run on a state transition. """ async def before_transition( self, context: GenericOrchestrationContext[orm_models.Run, Any] ) -> None: if self.nullified_transition(): return if context.proposed_state is not None: # record the new state's name context.run.state_name = context.proposed_state.name
SetRunStateName
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/rds.py
{ "start": 33991, "end": 38353 }
class ____(RdsBaseOperator): """ Starts an RDS DB instance / cluster. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:RdsStartDbOperator` :param db_identifier: The AWS identifier of the DB to start :param db_type: Type of the DB - either "instance" or "cluster" (default: "instance") :param wait_for_completion: If True, waits for DB to start. (default: True) :param waiter_delay: Time (in seconds) to wait between two consecutive calls to check DB instance state :param waiter_max_attempts: The maximum number of attempts to check DB instance state :param deferrable: If True, the operator will wait asynchronously for the DB instance to be created. This implies waiting for completion. This mode requires aiobotocore module to be installed. :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether or not to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html :param botocore_config: Configuration dictionary (key-values) for botocore client. See: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html """ template_fields = aws_template_fields("db_identifier", "db_type") def __init__( self, *, db_identifier: str, db_type: RdsDbType | str = RdsDbType.INSTANCE, wait_for_completion: bool = True, waiter_delay: int = 30, waiter_max_attempts: int = 40, deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), **kwargs, ): super().__init__(**kwargs) self.db_identifier = db_identifier self.db_type = db_type self.wait_for_completion = wait_for_completion self.waiter_delay = waiter_delay self.waiter_max_attempts = waiter_max_attempts self.deferrable = deferrable def execute(self, context: Context) -> str: self.db_type = RdsDbType(self.db_type) start_db_response: dict[str, Any] = self._start_db() if self.deferrable: self.defer( trigger=RdsDbAvailableTrigger( db_identifier=self.db_identifier, waiter_delay=self.waiter_delay, waiter_max_attempts=self.waiter_max_attempts, aws_conn_id=self.aws_conn_id, region_name=self.region_name, response=start_db_response, db_type=self.db_type, ), method_name="execute_complete", ) elif self.wait_for_completion: self._wait_until_db_available() return json.dumps(start_db_response, default=str) def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str: validated_event = validate_execute_complete_event(event) if validated_event["status"] != "success": raise AirflowException(f"Failed to start DB: {validated_event}") return json.dumps(validated_event["response"], default=str) def _start_db(self): self.log.info("Starting DB %s '%s'", self.db_type.value, self.db_identifier) if self.db_type == RdsDbType.INSTANCE: response = self.hook.conn.start_db_instance( DBInstanceIdentifier=self.db_identifier, ) else: response = self.hook.conn.start_db_cluster(DBClusterIdentifier=self.db_identifier) return response def _wait_until_db_available(self): self.log.info("Waiting for DB %s to reach 'available' state", self.db_type.value) if self.db_type == RdsDbType.INSTANCE: self.hook.wait_for_db_instance_state( self.db_identifier, target_state="available", check_interval=self.waiter_delay, max_attempts=self.waiter_max_attempts, ) else: self.hook.wait_for_db_cluster_state( self.db_identifier, target_state="available", check_interval=self.waiter_delay, max_attempts=self.waiter_max_attempts, )
RdsStartDbOperator
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/concatenate_test.py
{ "start": 13135, "end": 21129 }
class ____( checkpoint_test_base.CheckpointTestBase, parameterized.TestCase ): @combinations.generate( combinations.times( test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine( dataset_ranges=[(10, 8), (9, 5), (4, 7), (5, 8)], reshuffle_each_iteration=[True, False], symbolic_checkpoint=[True, False], ), ) ) def testConcatenate( self, verify_fn: Callable[..., None], dataset_ranges: Tuple[int, int], reshuffle_each_iteration: bool, symbolic_checkpoint: bool, ): def _build_dataset(): first_dataset = dataset_ops.Dataset.range(dataset_ranges[0]) second_dataset = dataset_ops.Dataset.range( dataset_ranges[0], dataset_ranges[0] + dataset_ranges[1] ) dataset = first_dataset.concatenate(second_dataset) dataset = global_shuffle_op._global_shuffle( dataset, seed=10, reshuffle_each_iteration=reshuffle_each_iteration ) options = options_lib.Options() options.experimental_optimization.apply_default_optimizations = False options.experimental_symbolic_checkpoint = symbolic_checkpoint return dataset.with_options(options) verify_fn( self, _build_dataset, num_outputs=sum(dataset_ranges), assert_items_equal=reshuffle_each_iteration, ) @combinations.generate( combinations.times( test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine( dataset_ranges=[(10, 8, 11), (9, 5, 3)], reshuffle_each_iteration=[True, False], symbolic_checkpoint=[True, False], ), ) ) def testNestedConcatenate( self, verify_fn: Callable[..., None], dataset_ranges: Tuple[int, int], reshuffle_each_iteration: bool, symbolic_checkpoint: bool, ): def _build_dataset(): first_dataset = dataset_ops.Dataset.range(dataset_ranges[0]) second_dataset = dataset_ops.Dataset.range( dataset_ranges[0], dataset_ranges[0] + dataset_ranges[1] ) third_dataset = dataset_ops.Dataset.range( sum(dataset_ranges[:2]), sum(dataset_ranges[:3]) ) dataset = first_dataset.concatenate(second_dataset) dataset = dataset.concatenate(third_dataset) dataset = global_shuffle_op._global_shuffle( dataset, seed=10, reshuffle_each_iteration=reshuffle_each_iteration ) options = options_lib.Options() options.experimental_optimization.apply_default_optimizations = False options.experimental_symbolic_checkpoint = symbolic_checkpoint return dataset.with_options(options) verify_fn( self, _build_dataset, num_outputs=sum(dataset_ranges), assert_items_equal=reshuffle_each_iteration, ) @combinations.generate( combinations.times( test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine( dataset_ranges=[(3, 4, 6, 5)], reshuffle_each_iteration=[True, False], symbolic_checkpoint=[True, False], ), ) ) def testFourNestedConcatenate( self, verify_fn: Callable[..., None], dataset_ranges: Tuple[int, int], reshuffle_each_iteration: bool, symbolic_checkpoint: bool, ): def _build_dataset(): first_dataset = dataset_ops.Dataset.range(dataset_ranges[0]) second_dataset = dataset_ops.Dataset.range( dataset_ranges[0], sum(dataset_ranges[:2]) ) third_dataset = dataset_ops.Dataset.range( sum(dataset_ranges[:2]), sum(dataset_ranges[:3]) ) fourth_dataset = dataset_ops.Dataset.range( sum(dataset_ranges[:3]), sum(dataset_ranges) ) left = first_dataset.concatenate(second_dataset) right = third_dataset.concatenate(fourth_dataset) dataset = left.concatenate(right) dataset = global_shuffle_op._global_shuffle( dataset, seed=10, reshuffle_each_iteration=reshuffle_each_iteration ) options = options_lib.Options() options.experimental_optimization.apply_default_optimizations = False options.experimental_symbolic_checkpoint = symbolic_checkpoint return dataset.with_options(options) verify_fn( self, _build_dataset, num_outputs=sum(dataset_ranges), assert_items_equal=reshuffle_each_iteration, ) @combinations.generate( combinations.times( test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine( dataset_ranges=[(1, 2, 3, 4, 5, 6)], reshuffle_each_iteration=[True, False], symbolic_checkpoint=[True, False], ), ) ) def testDeepConcatenate( self, verify_fn: Callable[..., None], dataset_ranges: Tuple[int, ...], reshuffle_each_iteration: bool, symbolic_checkpoint: bool, ): def _build_dataset(): prefix_sums = [0] * (len(dataset_ranges) + 1) for i, value in enumerate(dataset_ranges): prefix_sums[i + 1] = prefix_sums[i] + value dataset = dataset_ops.Dataset.range(prefix_sums[0], prefix_sums[1]) for i in range(1, len(dataset_ranges)): to_concat = dataset_ops.Dataset.range( prefix_sums[i], prefix_sums[i + 1] ) dataset = dataset.concatenate(to_concat) dataset = global_shuffle_op._global_shuffle( dataset, seed=10, reshuffle_each_iteration=reshuffle_each_iteration ) options = options_lib.Options() options.experimental_optimization.apply_default_optimizations = False options.experimental_symbolic_checkpoint = symbolic_checkpoint return dataset.with_options(options) verify_fn( self, _build_dataset, num_outputs=sum(dataset_ranges), assert_items_equal=reshuffle_each_iteration, ) @combinations.generate( combinations.times( test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine( dataset_ranges=[(1, 2, 3, 4, 5, 6)], reshuffle_each_iteration=[True, False], symbolic_checkpoint=[True, False], ), ) ) def testDeepConcatenateWithBatchAndPrefetch( self, verify_fn: Callable[..., None], dataset_ranges: Tuple[int, ...], reshuffle_each_iteration: bool, symbolic_checkpoint: bool, ): def _build_dataset(): prefix_sums = [0] * (len(dataset_ranges) + 1) for i, value in enumerate(dataset_ranges): prefix_sums[i + 1] = prefix_sums[i] + value dataset = dataset_ops.Dataset.range(prefix_sums[0], prefix_sums[1]) for i in range(1, len(dataset_ranges)): to_concat = dataset_ops.Dataset.range( prefix_sums[i], prefix_sums[i + 1] ) dataset = dataset.concatenate(to_concat) dataset = dataset.batch(2, drop_remainder=True) dataset = dataset.prefetch(buffer_size=dataset_ops.AUTOTUNE) dataset = global_shuffle_op._global_shuffle( dataset, seed=10, reshuffle_each_iteration=reshuffle_each_iteration ) dataset = dataset.unbatch() options = options_lib.Options() options.experimental_optimization.apply_default_optimizations = False options.experimental_symbolic_checkpoint = symbolic_checkpoint return dataset.with_options(options) verify_fn( self, _build_dataset, num_outputs=(sum(dataset_ranges) // 2) * 2, assert_items_equal=reshuffle_each_iteration, ) if __name__ == "__main__": test.main()
ConcatenateGlobalShuffleCheckpointTest
python
pallets__flask
src/flask/app.py
{ "start": 3572, "end": 64297 }
class ____(App): """The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more. The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file). For more information about resource loading, see :func:`open_resource`. Usually you create a :class:`Flask` instance in your main module or in the :file:`__init__.py` file of your package like this:: from flask import Flask app = Flask(__name__) .. admonition:: About the First Parameter The idea of the first parameter is to give Flask an idea of what belongs to your application. This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more. So it's important what you provide there. If you are using a single module, `__name__` is always the correct value. If you however are using a package, it's usually recommended to hardcode the name of your package there. For example if your application is defined in :file:`yourapplication/app.py` you should create it with one of the two versions below:: app = Flask('yourapplication') app = Flask(__name__.split('.')[0]) Why is that? The application will work even with `__name__`, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that triggered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in `yourapplication.app` and not `yourapplication.views.frontend`) .. versionadded:: 0.7 The `static_url_path`, `static_folder`, and `template_folder` parameters were added. .. versionadded:: 0.8 The `instance_path` and `instance_relative_config` parameters were added. .. versionadded:: 0.11 The `root_path` parameter was added. .. versionadded:: 1.0 The ``host_matching`` and ``static_host`` parameters were added. .. versionadded:: 1.0 The ``subdomain_matching`` parameter was added. Subdomain matching needs to be enabled manually now. Setting :data:`SERVER_NAME` does not implicitly enable it. :param import_name: the name of the application package :param static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the `static_folder` folder. :param static_folder: The folder with static files that is served at ``static_url_path``. Relative to the application ``root_path`` or an absolute path. Defaults to ``'static'``. :param static_host: the host to use when adding the static route. Defaults to None. Required when using ``host_matching=True`` with a ``static_folder`` configured. :param host_matching: set ``url_map.host_matching`` attribute. Defaults to False. :param subdomain_matching: consider the subdomain relative to :data:`SERVER_NAME` when matching routes. Defaults to False. :param template_folder: the folder that contains the templates that should be used by the application. Defaults to ``'templates'`` folder in the root path of the application. :param instance_path: An alternative instance path for the application. By default the folder ``'instance'`` next to the package or module is assumed to be the instance path. :param instance_relative_config: if set to ``True`` relative filenames for loading the config are assumed to be relative to the instance path instead of the application root. :param root_path: The path to the root of the application files. This should only be set manually when it can't be detected automatically, such as for namespace packages. """ default_config = ImmutableDict( { "DEBUG": None, "TESTING": False, "PROPAGATE_EXCEPTIONS": None, "SECRET_KEY": None, "SECRET_KEY_FALLBACKS": None, "PERMANENT_SESSION_LIFETIME": timedelta(days=31), "USE_X_SENDFILE": False, "TRUSTED_HOSTS": None, "SERVER_NAME": None, "APPLICATION_ROOT": "/", "SESSION_COOKIE_NAME": "session", "SESSION_COOKIE_DOMAIN": None, "SESSION_COOKIE_PATH": None, "SESSION_COOKIE_HTTPONLY": True, "SESSION_COOKIE_SECURE": False, "SESSION_COOKIE_PARTITIONED": False, "SESSION_COOKIE_SAMESITE": None, "SESSION_REFRESH_EACH_REQUEST": True, "MAX_CONTENT_LENGTH": None, "MAX_FORM_MEMORY_SIZE": 500_000, "MAX_FORM_PARTS": 1_000, "SEND_FILE_MAX_AGE_DEFAULT": None, "TRAP_BAD_REQUEST_ERRORS": None, "TRAP_HTTP_EXCEPTIONS": False, "EXPLAIN_TEMPLATE_LOADING": False, "PREFERRED_URL_SCHEME": "http", "TEMPLATES_AUTO_RELOAD": None, "MAX_COOKIE_SIZE": 4093, "PROVIDE_AUTOMATIC_OPTIONS": True, } ) #: The class that is used for request objects. See :class:`~flask.Request` #: for more information. request_class: type[Request] = Request #: The class that is used for response objects. See #: :class:`~flask.Response` for more information. response_class: type[Response] = Response #: the session interface to use. By default an instance of #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here. #: #: .. versionadded:: 0.8 session_interface: SessionInterface = SecureCookieSessionInterface() def __init_subclass__(cls, **kwargs: t.Any) -> None: import warnings # These method signatures were updated to take a ctx param. Detect # overridden methods in subclasses that still have the old signature. # Show a deprecation warning and wrap to call with correct args. for method in ( cls.handle_http_exception, cls.handle_user_exception, cls.handle_exception, cls.log_exception, cls.dispatch_request, cls.full_dispatch_request, cls.finalize_request, cls.make_default_options_response, cls.preprocess_request, cls.process_response, cls.do_teardown_request, cls.do_teardown_appcontext, ): base_method = getattr(Flask, method.__name__) if method is base_method: # not overridden continue # get the second parameter (first is self) iter_params = iter(inspect.signature(method).parameters.values()) next(iter_params) param = next(iter_params, None) # must have second parameter named ctx or annotated AppContext if param is None or not ( # no annotation, match name (param.annotation is inspect.Parameter.empty and param.name == "ctx") or ( # string annotation, access path ends with AppContext isinstance(param.annotation, str) and param.annotation.rpartition(".")[2] == "AppContext" ) or ( # class annotation inspect.isclass(param.annotation) and issubclass(param.annotation, AppContext) ) ): warnings.warn( f"The '{method.__name__}' method now takes 'ctx: AppContext'" " as the first parameter. The old signature is deprecated" " and will not be supported in Flask 4.0.", DeprecationWarning, stacklevel=2, ) setattr(cls, method.__name__, remove_ctx(method)) setattr(Flask, method.__name__, add_ctx(base_method)) def __init__( self, import_name: str, static_url_path: str | None = None, static_folder: str | os.PathLike[str] | None = "static", static_host: str | None = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: str | os.PathLike[str] | None = "templates", instance_path: str | None = None, instance_relative_config: bool = False, root_path: str | None = None, ): super().__init__( import_name=import_name, static_url_path=static_url_path, static_folder=static_folder, static_host=static_host, host_matching=host_matching, subdomain_matching=subdomain_matching, template_folder=template_folder, instance_path=instance_path, instance_relative_config=instance_relative_config, root_path=root_path, ) #: The Click command group for registering CLI commands for this #: object. The commands are available from the ``flask`` command #: once the application has been discovered and blueprints have #: been registered. self.cli = cli.AppGroup() # Set the name of the Click group in case someone wants to add # the app's commands to another CLI tool. self.cli.name = self.name # Add a static route using the provided static_url_path, static_host, # and static_folder if there is a configured static_folder. # Note we do this without checking if static_folder exists. # For one, it might be created while the server is running (e.g. during # development). Also, Google App Engine stores static files somewhere if self.has_static_folder: assert bool(static_host) == host_matching, ( "Invalid static_host/host_matching combination" ) # Use a weakref to avoid creating a reference cycle between the app # and the view function (see #3761). self_ref = weakref.ref(self) self.add_url_rule( f"{self.static_url_path}/<path:filename>", endpoint="static", host=static_host, view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950 ) def get_send_file_max_age(self, filename: str | None) -> int | None: """Used by :func:`send_file` to determine the ``max_age`` cache value for a given file path if it wasn't passed. By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from the configuration of :data:`~flask.current_app`. This defaults to ``None``, which tells the browser to use conditional requests instead of a timed cache, which is usually preferable. Note this is a duplicate of the same method in the Flask class. .. versionchanged:: 2.0 The default configuration is ``None`` instead of 12 hours. .. versionadded:: 0.9 """ value = self.config["SEND_FILE_MAX_AGE_DEFAULT"] if value is None: return None if isinstance(value, timedelta): return int(value.total_seconds()) return value # type: ignore[no-any-return] def send_static_file(self, filename: str) -> Response: """The view function used to serve files from :attr:`static_folder`. A route is automatically registered for this view at :attr:`static_url_path` if :attr:`static_folder` is set. Note this is a duplicate of the same method in the Flask class. .. versionadded:: 0.5 """ if not self.has_static_folder: raise RuntimeError("'static_folder' must be set to serve static_files.") # send_file only knows to call get_send_file_max_age on the app, # call it here so it works for blueprints too. max_age = self.get_send_file_max_age(filename) return send_from_directory( t.cast(str, self.static_folder), filename, max_age=max_age ) def open_resource( self, resource: str, mode: str = "rb", encoding: str | None = None ) -> t.IO[t.AnyStr]: """Open a resource file relative to :attr:`root_path` for reading. For example, if the file ``schema.sql`` is next to the file ``app.py`` where the ``Flask`` app is defined, it can be opened with: .. code-block:: python with app.open_resource("schema.sql") as f: conn.executescript(f.read()) :param resource: Path to the resource relative to :attr:`root_path`. :param mode: Open the file in this mode. Only reading is supported, valid values are ``"r"`` (or ``"rt"``) and ``"rb"``. :param encoding: Open the file with this encoding when opening in text mode. This is ignored when opening in binary mode. .. versionchanged:: 3.1 Added the ``encoding`` parameter. """ if mode not in {"r", "rt", "rb"}: raise ValueError("Resources can only be opened for reading.") path = os.path.join(self.root_path, resource) if mode == "rb": return open(path, mode) # pyright: ignore return open(path, mode, encoding=encoding) def open_instance_resource( self, resource: str, mode: str = "rb", encoding: str | None = "utf-8" ) -> t.IO[t.AnyStr]: """Open a resource file relative to the application's instance folder :attr:`instance_path`. Unlike :meth:`open_resource`, files in the instance folder can be opened for writing. :param resource: Path to the resource relative to :attr:`instance_path`. :param mode: Open the file in this mode. :param encoding: Open the file with this encoding when opening in text mode. This is ignored when opening in binary mode. .. versionchanged:: 3.1 Added the ``encoding`` parameter. """ path = os.path.join(self.instance_path, resource) if "b" in mode: return open(path, mode) return open(path, mode, encoding=encoding) def create_jinja_environment(self) -> Environment: """Create the Jinja environment based on :attr:`jinja_options` and the various Jinja-related methods of the app. Changing :attr:`jinja_options` after this will have no effect. Also adds Flask-related globals and filters to the environment. .. versionchanged:: 0.11 ``Environment.auto_reload`` set in accordance with ``TEMPLATES_AUTO_RELOAD`` configuration option. .. versionadded:: 0.5 """ options = dict(self.jinja_options) if "autoescape" not in options: options["autoescape"] = self.select_jinja_autoescape if "auto_reload" not in options: auto_reload = self.config["TEMPLATES_AUTO_RELOAD"] if auto_reload is None: auto_reload = self.debug options["auto_reload"] = auto_reload rv = self.jinja_environment(self, **options) rv.globals.update( url_for=self.url_for, get_flashed_messages=get_flashed_messages, config=self.config, # request, session and g are normally added with the # context processor for efficiency reasons but for imported # templates we also want the proxies in there. request=request, session=session, g=g, ) rv.policies["json.dumps_function"] = self.json.dumps return rv def create_url_adapter(self, request: Request | None) -> MapAdapter | None: """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionchanged:: 3.1 If :data:`SERVER_NAME` is set, it does not restrict requests to only that domain, for both ``subdomain_matching`` and ``host_matching``. .. versionchanged:: 1.0 :data:`SERVER_NAME` no longer implicitly enables subdomain matching. Use :attr:`subdomain_matching` instead. .. versionchanged:: 0.9 This can be called outside a request when the URL adapter is created for an application context. .. versionadded:: 0.6 """ if request is not None: if (trusted_hosts := self.config["TRUSTED_HOSTS"]) is not None: request.trusted_hosts = trusted_hosts # Check trusted_hosts here until bind_to_environ does. request.host = get_host(request.environ, request.trusted_hosts) # pyright: ignore subdomain = None server_name = self.config["SERVER_NAME"] if self.url_map.host_matching: # Don't pass SERVER_NAME, otherwise it's used and the actual # host is ignored, which breaks host matching. server_name = None elif not self.subdomain_matching: # Werkzeug doesn't implement subdomain matching yet. Until then, # disable it by forcing the current subdomain to the default, or # the empty string. subdomain = self.url_map.default_subdomain or "" return self.url_map.bind_to_environ( request.environ, server_name=server_name, subdomain=subdomain ) # Need at least SERVER_NAME to match/build outside a request. if self.config["SERVER_NAME"] is not None: return self.url_map.bind( self.config["SERVER_NAME"], script_name=self.config["APPLICATION_ROOT"], url_scheme=self.config["PREFERRED_URL_SCHEME"], ) return None def raise_routing_exception(self, request: Request) -> t.NoReturn: """Intercept routing exceptions and possibly do something else. In debug mode, intercept a routing redirect and replace it with an error if the body will be discarded. With modern Werkzeug this shouldn't occur, since it now uses a 308 status which tells the browser to resend the method and body. .. versionchanged:: 2.1 Don't intercept 307 and 308 redirects. :meta private: :internal: """ if ( not self.debug or not isinstance(request.routing_exception, RequestRedirect) or request.routing_exception.code in {307, 308} or request.method in {"GET", "HEAD", "OPTIONS"} ): raise request.routing_exception # type: ignore[misc] from .debughelpers import FormDataRoutingRedirect raise FormDataRoutingRedirect(request) def update_template_context( self, ctx: AppContext, context: dict[str, t.Any] ) -> None: """Update the template context with some commonly used variables. This injects request, session, config and g into the template context as well as everything template context processors want to inject. Note that the as of Flask 0.6, the original values in the context will not be overridden if a context processor decides to return a value with the same key. :param context: the context as a dictionary that is updated in place to add extra variables. """ names: t.Iterable[str | None] = (None,) # A template may be rendered outside a request context. if ctx.has_request: names = chain(names, reversed(ctx.request.blueprints)) # The values passed to render_template take precedence. Keep a # copy to re-apply after all context functions. orig_ctx = context.copy() for name in names: if name in self.template_context_processors: for func in self.template_context_processors[name]: context.update(self.ensure_sync(func)()) context.update(orig_ctx) def make_shell_context(self) -> dict[str, t.Any]: """Returns the shell context for an interactive shell for this application. This runs all the registered shell context processors. .. versionadded:: 0.11 """ rv = {"app": self, "g": g} for processor in self.shell_context_processors: rv.update(processor()) return rv def run( self, host: str | None = None, port: int | None = None, debug: bool | None = None, load_dotenv: bool = True, **options: t.Any, ) -> None: """Runs the application on a local development server. Do not use ``run()`` in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see :doc:`/deploying/index` for WSGI server recommendations. If the :attr:`debug` flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass ``use_evalex=False`` as parameter. This will keep the debugger's traceback screen active, but disable code execution. It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the :command:`flask` command line script's ``run`` support. .. admonition:: Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``. Setting ``use_debugger`` to ``True`` without being in debug mode won't catch any exceptions because there won't be any to catch. :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to have the server available externally as well. Defaults to ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable if present. :param port: the port of the webserver. Defaults to ``5000`` or the port defined in the ``SERVER_NAME`` config variable if present. :param debug: if given, enable or disable debug mode. See :attr:`debug`. :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv` files to set environment variables. Will also change the working directory to the directory containing the first file found. :param options: the options to be forwarded to the underlying Werkzeug server. See :func:`werkzeug.serving.run_simple` for more information. .. versionchanged:: 1.0 If installed, python-dotenv will be used to load environment variables from :file:`.env` and :file:`.flaskenv` files. The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`. Threaded mode is enabled by default. .. versionchanged:: 0.10 The default port is now picked from the ``SERVER_NAME`` variable. """ # Ignore this call so that it doesn't start another server if # the 'flask run' command is used. if os.environ.get("FLASK_RUN_FROM_CLI") == "true": if not is_running_from_reloader(): click.secho( " * Ignoring a call to 'app.run()' that would block" " the current 'flask' CLI command.\n" " Only call 'app.run()' in an 'if __name__ ==" ' "__main__"\' guard.', fg="red", ) return if get_load_dotenv(load_dotenv): cli.load_dotenv() # if set, env var overrides existing value if "FLASK_DEBUG" in os.environ: self.debug = get_debug_flag() # debug passed to method overrides all other sources if debug is not None: self.debug = bool(debug) server_name = self.config.get("SERVER_NAME") sn_host = sn_port = None if server_name: sn_host, _, sn_port = server_name.partition(":") if not host: if sn_host: host = sn_host else: host = "127.0.0.1" if port or port == 0: port = int(port) elif sn_port: port = int(sn_port) else: port = 5000 options.setdefault("use_reloader", self.debug) options.setdefault("use_debugger", self.debug) options.setdefault("threaded", True) cli.show_server_banner(self.debug, self.name) from werkzeug.serving import run_simple try: run_simple(t.cast(str, host), port, self, **options) finally: # reset the first request information if the development server # reset normally. This makes it possible to restart the server # without reloader and that stuff from an interactive shell. self._got_first_request = False def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient: """Creates a test client for this application. For information about unit testing head over to :doc:`/testing`. Note that if you are testing for assertions or exceptions in your application code, you must set ``app.testing = True`` in order for the exceptions to propagate to the test client. Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client. See the :attr:`testing` attribute. For example:: app.testing = True client = app.test_client() The test client can be used in a ``with`` block to defer the closing down of the context until the end of the ``with`` block. This is useful if you want to access the context locals for testing:: with app.test_client() as c: rv = c.get('/?vodka=42') assert request.args['vodka'] == '42' Additionally, you may pass optional keyword arguments that will then be passed to the application's :attr:`test_client_class` constructor. For example:: from flask.testing import FlaskClient class CustomClient(FlaskClient): def __init__(self, *args, **kwargs): self._authentication = kwargs.pop("authentication") super(CustomClient,self).__init__( *args, **kwargs) app.test_client_class = CustomClient client = app.test_client(authentication='Basic ....') See :class:`~flask.testing.FlaskClient` for more information. .. versionchanged:: 0.4 added support for ``with`` block usage for the client. .. versionadded:: 0.7 The `use_cookies` parameter was added as well as the ability to override the client to be used by setting the :attr:`test_client_class` attribute. .. versionchanged:: 0.11 Added `**kwargs` to support passing additional keyword arguments to the constructor of :attr:`test_client_class`. """ cls = self.test_client_class if cls is None: from .testing import FlaskClient as cls return cls( # type: ignore self, self.response_class, use_cookies=use_cookies, **kwargs ) def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner: """Create a CLI runner for testing CLI commands. See :ref:`testing-cli`. Returns an instance of :attr:`test_cli_runner_class`, by default :class:`~flask.testing.FlaskCliRunner`. The Flask app object is passed as the first argument. .. versionadded:: 1.0 """ cls = self.test_cli_runner_class if cls is None: from .testing import FlaskCliRunner as cls return cls(self, **kwargs) # type: ignore def handle_http_exception( self, ctx: AppContext, e: HTTPException ) -> HTTPException | ft.ResponseReturnValue: """Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionchanged:: 1.0.3 ``RoutingException``, used internally for actions such as slash redirects during routing, is not passed to error handlers. .. versionchanged:: 1.0 Exceptions are looked up by code *and* by MRO, so ``HTTPException`` subclasses can be handled with a catch-all handler for the base ``HTTPException``. .. versionadded:: 0.3 """ # Proxy exceptions don't have error codes. We want to always return # those unchanged as errors if e.code is None: return e # RoutingExceptions are used internally to trigger routing # actions, such as slash redirects raising RequestRedirect. They # are not raised or handled in user code. if isinstance(e, RoutingException): return e handler = self._find_error_handler(e, ctx.request.blueprints) if handler is None: return e return self.ensure_sync(handler)(e) # type: ignore[no-any-return] def handle_user_exception( self, ctx: AppContext, e: Exception ) -> HTTPException | ft.ResponseReturnValue: """This method is called whenever an exception occurs that should be handled. A special case is :class:`~werkzeug .exceptions.HTTPException` which is forwarded to the :meth:`handle_http_exception` method. This function will either return a response value or reraise the exception with the same traceback. .. versionchanged:: 1.0 Key errors raised from request data like ``form`` show the bad key in debug mode rather than a generic bad request message. .. versionadded:: 0.7 """ if isinstance(e, BadRequestKeyError) and ( self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"] ): e.show_exception = True if isinstance(e, HTTPException) and not self.trap_http_exception(e): return self.handle_http_exception(ctx, e) handler = self._find_error_handler(e, ctx.request.blueprints) if handler is None: raise return self.ensure_sync(handler)(e) # type: ignore[no-any-return] def handle_exception(self, ctx: AppContext, e: Exception) -> Response: """Handle an exception that did not have an error handler associated with it, or that was raised from an error handler. This always causes a 500 ``InternalServerError``. Always sends the :data:`got_request_exception` signal. If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug mode, the error will be re-raised so that the debugger can display it. Otherwise, the original exception is logged, and an :exc:`~werkzeug.exceptions.InternalServerError` is returned. If an error handler is registered for ``InternalServerError`` or ``500``, it will be used. For consistency, the handler will always receive the ``InternalServerError``. The original unhandled exception is available as ``e.original_exception``. .. versionchanged:: 1.1.0 Always passes the ``InternalServerError`` instance to the handler, setting ``original_exception`` to the unhandled error. .. versionchanged:: 1.1.0 ``after_request`` functions and other finalization is done even for the default 500 response when there is no handler. .. versionadded:: 0.3 """ exc_info = sys.exc_info() got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e) propagate = self.config["PROPAGATE_EXCEPTIONS"] if propagate is None: propagate = self.testing or self.debug if propagate: # Re-raise if called with an active exception, otherwise # raise the passed in exception. if exc_info[1] is e: raise raise e self.log_exception(ctx, exc_info) server_error: InternalServerError | ft.ResponseReturnValue server_error = InternalServerError(original_exception=e) handler = self._find_error_handler(server_error, ctx.request.blueprints) if handler is not None: server_error = self.ensure_sync(handler)(server_error) return self.finalize_request(ctx, server_error, from_error_handler=True) def log_exception( self, ctx: AppContext, exc_info: tuple[type, BaseException, TracebackType] | tuple[None, None, None], ) -> None: """Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`. .. versionadded:: 0.8 """ self.logger.error( f"Exception on {ctx.request.path} [{ctx.request.method}]", exc_info=exc_info ) def dispatch_request(self, ctx: AppContext) -> ft.ResponseReturnValue: """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. .. versionchanged:: 0.7 This no longer does the exception handling, this code was moved to the new :meth:`full_dispatch_request`. """ req = ctx.request if req.routing_exception is not None: self.raise_routing_exception(req) rule: Rule = req.url_rule # type: ignore[assignment] # if we provide automatic options for this URL and the # request came with the OPTIONS method, reply automatically if ( getattr(rule, "provide_automatic_options", False) and req.method == "OPTIONS" ): return self.make_default_options_response(ctx) # otherwise dispatch to the handler for that endpoint view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment] return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return] def full_dispatch_request(self, ctx: AppContext) -> Response: """Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling. .. versionadded:: 0.7 """ self._got_first_request = True try: request_started.send(self, _async_wrapper=self.ensure_sync) rv = self.preprocess_request(ctx) if rv is None: rv = self.dispatch_request(ctx) except Exception as e: rv = self.handle_user_exception(ctx, e) return self.finalize_request(ctx, rv) def finalize_request( self, ctx: AppContext, rv: ft.ResponseReturnValue | HTTPException, from_error_handler: bool = False, ) -> Response: """Given the return value from a view function this finalizes the request by converting it into a response and invoking the postprocessing functions. This is invoked for both normal request dispatching as well as error handlers. Because this means that it might be called as a result of a failure a special safe mode is available which can be enabled with the `from_error_handler` flag. If enabled, failures in response processing will be logged and otherwise ignored. :internal: """ response = self.make_response(rv) try: response = self.process_response(ctx, response) request_finished.send( self, _async_wrapper=self.ensure_sync, response=response ) except Exception: if not from_error_handler: raise self.logger.exception( "Request finalizing failed with an error while handling an error" ) return response def make_default_options_response(self, ctx: AppContext) -> Response: """This method is called to create the default ``OPTIONS`` response. This can be changed through subclassing to change the default behavior of ``OPTIONS`` responses. .. versionadded:: 0.7 """ methods = ctx.url_adapter.allowed_methods() # type: ignore[union-attr] rv = self.response_class() rv.allow.update(methods) return rv def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: """Ensure that the function is synchronous for WSGI workers. Plain ``def`` functions are returned as-is. ``async def`` functions are wrapped to run and wait for the response. Override this method to change how the app runs async views. .. versionadded:: 2.0 """ if iscoroutinefunction(func): return self.async_to_sync(func) return func def async_to_sync( self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]] ) -> t.Callable[..., t.Any]: """Return a sync function that will run the coroutine function. .. code-block:: python result = app.async_to_sync(func)(*args, **kwargs) Override this method to change how the app converts async code to be synchronously callable. .. versionadded:: 2.0 """ try: from asgiref.sync import async_to_sync as asgiref_async_to_sync except ImportError: raise RuntimeError( "Install Flask with the 'async' extra in order to use async views." ) from None return asgiref_async_to_sync(func) def url_for( self, /, endpoint: str, *, _anchor: str | None = None, _method: str | None = None, _scheme: str | None = None, _external: bool | None = None, **values: t.Any, ) -> str: """Generate a URL to the given endpoint with the given values. This is called by :func:`flask.url_for`, and can be called directly as well. An *endpoint* is the name of a URL rule, usually added with :meth:`@app.route() <route>`, and usually the same name as the view function. A route defined in a :class:`~flask.Blueprint` will prepend the blueprint's name separated by a ``.`` to the endpoint. In some cases, such as email messages, you want URLs to include the scheme and domain, like ``https://example.com/hello``. When not in an active request, URLs will be external by default, but this requires setting :data:`SERVER_NAME` so Flask knows what domain to use. :data:`APPLICATION_ROOT` and :data:`PREFERRED_URL_SCHEME` should also be configured as needed. This config is only used when not in an active request. Functions can be decorated with :meth:`url_defaults` to modify keyword arguments before the URL is built. If building fails for some reason, such as an unknown endpoint or incorrect values, the app's :meth:`handle_url_build_error` method is called. If that returns a string, that is returned, otherwise a :exc:`~werkzeug.routing.BuildError` is raised. :param endpoint: The endpoint name associated with the URL to generate. If this starts with a ``.``, the current blueprint name (if any) will be used. :param _anchor: If given, append this as ``#anchor`` to the URL. :param _method: If given, generate the URL associated with this method for the endpoint. :param _scheme: If given, the URL will have this scheme if it is external. :param _external: If given, prefer the URL to be internal (False) or require it to be external (True). External URLs include the scheme and domain. When not in an active request, URLs are external by default. :param values: Values to use for the variable parts of the URL rule. Unknown keys are appended as query string arguments, like ``?a=b&c=d``. .. versionadded:: 2.2 Moved from ``flask.url_for``, which calls this method. """ if (ctx := _cv_app.get(None)) is not None and ctx.has_request: url_adapter = ctx.url_adapter blueprint_name = ctx.request.blueprint # If the endpoint starts with "." and the request matches a # blueprint, the endpoint is relative to the blueprint. if endpoint[:1] == ".": if blueprint_name is not None: endpoint = f"{blueprint_name}{endpoint}" else: endpoint = endpoint[1:] # When in a request, generate a URL without scheme and # domain by default, unless a scheme is given. if _external is None: _external = _scheme is not None else: # If called by helpers.url_for, an app context is active, # use its url_adapter. Otherwise, app.url_for was called # directly, build an adapter. if ctx is not None: url_adapter = ctx.url_adapter else: url_adapter = self.create_url_adapter(None) if url_adapter is None: raise RuntimeError( "Unable to build URLs outside an active request" " without 'SERVER_NAME' configured. Also configure" " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as" " needed." ) # When outside a request, generate a URL with scheme and # domain by default. if _external is None: _external = True # It is an error to set _scheme when _external=False, in order # to avoid accidental insecure URLs. if _scheme is not None and not _external: raise ValueError("When specifying '_scheme', '_external' must be True.") self.inject_url_defaults(endpoint, values) try: rv = url_adapter.build( # type: ignore[union-attr] endpoint, values, method=_method, url_scheme=_scheme, force_external=_external, ) except BuildError as error: values.update( _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external ) return self.handle_url_build_error(error, endpoint, values) if _anchor is not None: _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@") rv = f"{rv}#{_anchor}" return rv def make_response(self, rv: ft.ResponseReturnValue) -> Response: """Convert the return value from a view function to an instance of :attr:`response_class`. :param rv: the return value from the view function. The view function must return a response. Returning ``None``, or the view ending without returning, is not allowed. The following types are allowed for ``view_rv``: ``str`` A response object is created with the string encoded to UTF-8 as the body. ``bytes`` A response object is created with the bytes as the body. ``dict`` A dictionary that will be jsonify'd before being returned. ``list`` A list that will be jsonify'd before being returned. ``generator`` or ``iterator`` A generator that returns ``str`` or ``bytes`` to be streamed as the response. ``tuple`` Either ``(body, status, headers)``, ``(body, status)``, or ``(body, headers)``, where ``body`` is any of the other types allowed here, ``status`` is a string or an integer, and ``headers`` is a dictionary or a list of ``(key, value)`` tuples. If ``body`` is a :attr:`response_class` instance, ``status`` overwrites the exiting value and ``headers`` are extended. :attr:`response_class` The object is returned unchanged. other :class:`~werkzeug.wrappers.Response` class The object is coerced to :attr:`response_class`. :func:`callable` The function is called as a WSGI application. The result is used to create a response object. .. versionchanged:: 2.2 A generator will be converted to a streaming response. A list will be converted to a JSON response. .. versionchanged:: 1.1 A dict will be converted to a JSON response. .. versionchanged:: 0.9 Previously a tuple was interpreted as the arguments for the response object. """ status: int | None = None headers: HeadersValue | None = None # unpack tuple returns if isinstance(rv, tuple): len_rv = len(rv) # a 3-tuple is unpacked directly if len_rv == 3: rv, status, headers = rv # type: ignore[misc] # decide if a 2-tuple has status or headers elif len_rv == 2: if isinstance(rv[1], (Headers, dict, tuple, list)): rv, headers = rv # pyright: ignore else: rv, status = rv # type: ignore[assignment,misc] # other sized tuples are not allowed else: raise TypeError( "The view function did not return a valid response tuple." " The tuple must have the form (body, status, headers)," " (body, status), or (body, headers)." ) # the body must not be None if rv is None: raise TypeError( f"The view function for {request.endpoint!r} did not" " return a valid response. The function either returned" " None or ended without a return statement." ) # make sure the body is an instance of the response class if not isinstance(rv, self.response_class): if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator): # let the response class set the status and headers instead of # waiting to do it manually, so that the class can handle any # special logic rv = self.response_class( rv, # pyright: ignore status=status, headers=headers, # type: ignore[arg-type] ) status = headers = None elif isinstance(rv, (dict, list)): rv = self.json.response(rv) elif isinstance(rv, BaseResponse) or callable(rv): # evaluate a WSGI callable, or coerce a different response # class to the correct type try: rv = self.response_class.force_type( rv, # type: ignore[arg-type] request.environ, ) except TypeError as e: raise TypeError( f"{e}\nThe view function did not return a valid" " response. The return type must be a string," " dict, list, tuple with headers or status," " Response instance, or WSGI callable, but it" f" was a {type(rv).__name__}." ).with_traceback(sys.exc_info()[2]) from None else: raise TypeError( "The view function did not return a valid" " response. The return type must be a string," " dict, list, tuple with headers or status," " Response instance, or WSGI callable, but it was a" f" {type(rv).__name__}." ) rv = t.cast(Response, rv) # prefer the status if it was provided if status is not None: if isinstance(status, (str, bytes, bytearray)): rv.status = status else: rv.status_code = status # extend existing headers with provided headers if headers: rv.headers.update(headers) return rv def preprocess_request(self, ctx: AppContext) -> ft.ResponseReturnValue | None: """Called before the request is dispatched. Calls :attr:`url_value_preprocessors` registered with the app and the current blueprint (if any). Then calls :attr:`before_request_funcs` registered with the app and the blueprint. If any :meth:`before_request` handler returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. """ req = ctx.request names = (None, *reversed(req.blueprints)) for name in names: if name in self.url_value_preprocessors: for url_func in self.url_value_preprocessors[name]: url_func(req.endpoint, req.view_args) for name in names: if name in self.before_request_funcs: for before_func in self.before_request_funcs[name]: rv = self.ensure_sync(before_func)() if rv is not None: return rv # type: ignore[no-any-return] return None def process_response(self, ctx: AppContext, response: Response) -> Response: """Can be overridden in order to modify the response object before it's sent to the WSGI server. By default this will call all the :meth:`after_request` decorated functions. .. versionchanged:: 0.5 As of Flask 0.5 the functions registered for after request execution are called in reverse order of registration. :param response: a :attr:`response_class` object. :return: a new response object or the same, has to be an instance of :attr:`response_class`. """ for func in ctx._after_request_functions: response = self.ensure_sync(func)(response) for name in chain(ctx.request.blueprints, (None,)): if name in self.after_request_funcs: for func in reversed(self.after_request_funcs[name]): response = self.ensure_sync(func)(response) if not self.session_interface.is_null_session(ctx.session): self.session_interface.save_session(self, ctx.session, response) return response def do_teardown_request( self, ctx: AppContext, exc: BaseException | None = None ) -> None: """Called after the request is dispatched and the response is finalized, right before the request context is popped. Called by :meth:`.AppContext.pop`. This calls all functions decorated with :meth:`teardown_request`, and :meth:`Blueprint.teardown_request` if a blueprint handled the request. Finally, the :data:`request_tearing_down` signal is sent. :param exc: An unhandled exception raised while dispatching the request. Passed to each teardown function. .. versionchanged:: 0.9 Added the ``exc`` argument. """ for name in chain(ctx.request.blueprints, (None,)): if name in self.teardown_request_funcs: for func in reversed(self.teardown_request_funcs[name]): self.ensure_sync(func)(exc) request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc) def do_teardown_appcontext( self, ctx: AppContext, exc: BaseException | None = None ) -> None: """Called right before the application context is popped. Called by :meth:`.AppContext.pop`. This calls all functions decorated with :meth:`teardown_appcontext`. Then the :data:`appcontext_tearing_down` signal is sent. :param exc: An unhandled exception raised while the context was active. Passed to each teardown function. .. versionadded:: 0.9 """ for func in reversed(self.teardown_appcontext_funcs): self.ensure_sync(func)(exc) appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc) def app_context(self) -> AppContext: """Create an :class:`.AppContext`. When the context is pushed, :data:`.current_app` and :data:`.g` become available. A context is automatically pushed when handling each request, and when running any ``flask`` CLI command. Use this as a ``with`` block to manually push a context outside of those situations, such as during setup or testing. .. code-block:: python with app.app_context(): init_db() See :doc:`/appcontext`. .. versionadded:: 0.9 """ return AppContext(self) def request_context(self, environ: WSGIEnvironment) -> AppContext: """Create an :class:`.AppContext` with request information representing the given WSGI environment. A context is automatically pushed when handling each request. When the context is pushed, :data:`.request`, :data:`.session`, :data:`g:, and :data:`.current_app` become available. This method should not be used in your own code. Creating a valid WSGI environ is not trivial. Use :meth:`test_request_context` to correctly create a WSGI environ and request context instead. See :doc:`/appcontext`. :param environ: A WSGI environment. """ return AppContext.from_environ(self, environ) def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> AppContext: """Create an :class:`.AppContext` with request information created from the given arguments. When the context is pushed, :data:`.request`, :data:`.session`, :data:`g:, and :data:`.current_app` become available. This is useful during testing to run a function that uses request data without dispatching a full request. Use this as a ``with`` block to push a context. .. code-block:: python with app.test_request_context(...): generate_report() See :doc:`/appcontext`. Takes the same arguments as Werkzeug's :class:`~werkzeug.test.EnvironBuilder`, with some defaults from the application. See the linked Werkzeug docs for most of the available arguments. Flask-specific behavior is listed here. :param path: URL path being requested. :param base_url: Base URL where the app is being served, which ``path`` is relative to. If not given, built from :data:`PREFERRED_URL_SCHEME`, ``subdomain``, :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`. :param subdomain: Subdomain name to prepend to :data:`SERVER_NAME`. :param url_scheme: Scheme to use instead of :data:`PREFERRED_URL_SCHEME`. :param data: The request body text or bytes,or a dict of form data. :param json: If given, this is serialized as JSON and passed as ``data``. Also defaults ``content_type`` to ``application/json``. :param args: Other positional arguments passed to :class:`~werkzeug.test.EnvironBuilder`. :param kwargs: Other keyword arguments passed to :class:`~werkzeug.test.EnvironBuilder`. """ from .testing import EnvironBuilder builder = EnvironBuilder(self, *args, **kwargs) try: environ = builder.get_environ() finally: builder.close() return self.request_context(environ) def wsgi_app( self, environ: WSGIEnvironment, start_response: StartResponse ) -> cabc.Iterable[bytes]: """The actual WSGI application. This is not implemented in :meth:`__call__` so that middlewares can be applied without losing a reference to the app object. Instead of doing this:: app = MyMiddleware(app) It's a better idea to do this instead:: app.wsgi_app = MyMiddleware(app.wsgi_app) Then you still have the original application object around and can continue to call methods on it. .. versionchanged:: 0.7 Teardown events for the request and app contexts are called even if an unhandled error occurs. Other events may not be called depending on when an error occurs during dispatch. :param environ: A WSGI environment. :param start_response: A callable accepting a status code, a list of headers, and an optional exception context to start the response. """ ctx = self.request_context(environ) error: BaseException | None = None try: try: ctx.push() response = self.full_dispatch_request(ctx) except Exception as e: error = e response = self.handle_exception(ctx, e) except: # noqa: B001 error = sys.exc_info()[1] raise return response(environ, start_response) finally: if "werkzeug.debug.preserve_context" in environ: environ["werkzeug.debug.preserve_context"](ctx) if error is not None and self.should_ignore_error(error): error = None ctx.pop(error) def __call__( self, environ: WSGIEnvironment, start_response: StartResponse ) -> cabc.Iterable[bytes]: """The WSGI server calls the Flask application object as the WSGI application. This calls :meth:`wsgi_app`, which can be wrapped to apply middleware. """ return self.wsgi_app(environ, start_response)
Flask
python
doocs__leetcode
solution/2200-2299/2215.Find the Difference of Two Arrays/Solution.py
{ "start": 0, "end": 187 }
class ____: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: s1, s2 = set(nums1), set(nums2) return [list(s1 - s2), list(s2 - s1)]
Solution
python
huggingface__transformers
tests/models/instructblipvideo/test_modeling_instructblipvideo.py
{ "start": 14076, "end": 18253 }
class ____: def __init__( self, parent, vision_kwargs=None, qformer_kwargs=None, text_kwargs=None, is_training=True, num_query_tokens=10, video_token_index=4, ): if vision_kwargs is None: vision_kwargs = {} if qformer_kwargs is None: qformer_kwargs = {} if text_kwargs is None: text_kwargs = {} self.parent = parent self.vision_model_tester = InstructBlipVideoVisionModelTester(parent, **vision_kwargs) self.qformer_model_tester = InstructBlipVideoQFormerModelTester(parent, **qformer_kwargs) self.text_model_tester = InstructBlipVideoTextModelDecoderOnlyTester(parent, **text_kwargs) self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test self.frames = self.vision_model_tester.frames # need seq_length for common tests self.seq_length = self.text_model_tester.seq_length + (num_query_tokens * self.frames) self.is_training = is_training self.num_query_tokens = num_query_tokens self.video_token_index = video_token_index def prepare_config_and_inputs(self): _, pixel_values = self.vision_model_tester.prepare_config_and_inputs() _, _, _, qformer_input_ids, qformer_attention_mask = self.qformer_model_tester.prepare_config_and_inputs() _, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs() _, c, h, w = pixel_values.shape pixel_values = pixel_values.reshape(-1, self.frames, c, h, w) vision_tokens = ( torch.ones( (input_ids.shape[0], self.num_query_tokens * self.frames), device=torch_device, dtype=input_ids.dtype ) * self.video_token_index ) input_ids[input_ids == self.video_token_index] = self.text_model_tester.pad_token_id input_ids = torch.cat([vision_tokens, input_ids], dim=-1) vision_attention_mask = torch.ones_like(vision_tokens) attention_mask = torch.cat([vision_attention_mask, attention_mask], dim=-1) config = self.get_config() return config, input_ids, attention_mask, qformer_input_ids, qformer_attention_mask, pixel_values def get_config(self): return InstructBlipVideoConfig( vision_config=self.vision_model_tester.get_config(), qformer_config=self.qformer_model_tester.get_config(), text_config=self.text_model_tester.get_config(), num_query_tokens=self.num_query_tokens, video_token_index=self.video_token_index, ) def create_and_check_for_conditional_generation( self, config, input_ids, attention_mask, qformer_input_ids, qformer_attention_mask, pixel_values ): model = InstructBlipVideoForConditionalGeneration(config).to(torch_device).eval() with torch.no_grad(): result = model( pixel_values, input_ids=input_ids, attention_mask=attention_mask, qformer_input_ids=qformer_input_ids, qformer_attention_mask=qformer_attention_mask, ) expected_seq_length = ( self.num_query_tokens * self.vision_model_tester.frames ) + self.text_model_tester.seq_length self.parent.assertEqual( result.logits.shape, (self.vision_model_tester.batch_size, expected_seq_length, self.text_model_tester.vocab_size), ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, attention_mask, qformer_input_ids, qformer_attention_mask, pixel_values = config_and_inputs inputs_dict = { "pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask, "qformer_input_ids": qformer_input_ids, "qformer_attention_mask": qformer_attention_mask, } return config, inputs_dict @require_torch
InstructBlipVideoForConditionalGenerationDecoderOnlyModelTester
python
Farama-Foundation__Gymnasium
gymnasium/envs/phys2d/pendulum.py
{ "start": 750, "end": 1013 }
class ____: """Parameters for the jax Pendulum environment.""" max_speed: float = 8.0 dt: float = 0.05 g: float = 10.0 m: float = 1.0 l: float = 1.0 high_x: float = jnp.pi high_y: float = 1.0 screen_dim: int = 500
PendulumParams
python
pytorch__pytorch
test/distributed/test_c10d_common.py
{ "start": 7161, "end": 7847 }
class ____(nn.Module): def __init__(self, gpus): super().__init__() self.fc1 = nn.Linear(2, 10, bias=False).to(gpus[0]) self.fc2 = nn.Linear(10, 50, bias=False).to(gpus[1]) self.fc3 = nn.Linear(50, 4, bias=False).to(gpus[1]) self.relu = nn.ReLU() self.no_grad_param = nn.Parameter( torch.tensor([2, 2]).long(), requires_grad=False ).to(gpus[0]) def forward(self, x): dev0 = self.fc1.weight.device dev1 = self.fc2.weight.device x = self.relu(self.fc1(x.to(dev0))) x = self.relu(self.fc2(x.to(dev1))) x = self.fc3(x) return F.softmax(x, dim=1).to(dev0)
DoubleGpuNet
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image24.py
{ "start": 315, "end": 847 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image24.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_image("B2", self.image_dir + "black_300.png") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/pvt_v2/modeling_pvt_v2.py
{ "start": 4584, "end": 8985 }
class ____(nn.Module): """Efficient self-attention mechanism.""" def __init__(self, config: PvtV2Config, hidden_size: int, num_attention_heads: int, spatial_reduction_ratio: int): super().__init__() self.linear_attention = config.linear_attention self.hidden_size = hidden_size self.num_attention_heads = num_attention_heads if self.hidden_size % self.num_attention_heads != 0: raise ValueError( f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention " f"heads ({self.num_attention_heads})" ) self.attention_head_size = int(self.hidden_size / self.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(self.hidden_size, self.all_head_size, bias=config.qkv_bias) self.key = nn.Linear(self.hidden_size, self.all_head_size, bias=config.qkv_bias) self.value = nn.Linear(self.hidden_size, self.all_head_size, bias=config.qkv_bias) self.attn_drop = nn.Dropout(config.attention_probs_dropout_prob) self.proj = nn.Linear(self.hidden_size, self.hidden_size) self.proj_drop = nn.Dropout(config.hidden_dropout_prob) self.spatial_reduction_ratio = spatial_reduction_ratio if self.linear_attention: self.pool = nn.AdaptiveAvgPool2d(7) self.spatial_reduction = nn.Conv2d(self.hidden_size, self.hidden_size, kernel_size=1, stride=1) self.layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps) self.act = nn.GELU() elif spatial_reduction_ratio > 1: self.spatial_reduction = nn.Conv2d( self.hidden_size, self.hidden_size, kernel_size=spatial_reduction_ratio, stride=spatial_reduction_ratio ) self.layer_norm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_eps) def transpose_for_scores(self, hidden_states) -> torch.Tensor: new_shape = hidden_states.size()[:-1] + (self.num_attention_heads, self.attention_head_size) hidden_states = hidden_states.view(new_shape) return hidden_states.permute(0, 2, 1, 3) def forward( self, hidden_states: torch.Tensor, height: int, width: int, output_attentions: bool = False, ) -> tuple[torch.Tensor]: batch_size, seq_len, num_channels = hidden_states.shape query_layer = self.transpose_for_scores(self.query(hidden_states)) if self.linear_attention: hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, num_channels, height, width) hidden_states = ( self.spatial_reduction(self.pool(hidden_states)).reshape(batch_size, num_channels, -1).permute(0, 2, 1) ) hidden_states = self.act(self.layer_norm(hidden_states)) elif self.spatial_reduction_ratio > 1: hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, num_channels, height, width) hidden_states = ( self.spatial_reduction(hidden_states).reshape(batch_size, num_channels, -1).permute(0, 2, 1) ) hidden_states = self.layer_norm(hidden_states) key_layer = self.transpose_for_scores(self.key(hidden_states)) value_layer = self.transpose_for_scores(self.value(hidden_states)) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.attention_head_size) # Normalize the attention scores to probabilities. attention_probs = nn.functional.softmax(attention_scores, dim=-1) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.attn_drop(attention_probs) context_layer = (attention_probs @ value_layer).transpose(1, 2).reshape(batch_size, seq_len, num_channels) context_layer = self.proj(context_layer) context_layer = self.proj_drop(context_layer) outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) return outputs
PvtV2SelfAttention
python
mlflow__mlflow
tests/sagemaker/mock/__init__.py
{ "start": 36204, "end": 36790 }
class ____(TimestampedResource): """ Object representing a SageMaker endpoint configuration. The SageMakerBackend will create and manage EndpointConfigs. """ def __init__(self, config_name, production_variants, tags, async_inference_config=None): super().__init__() self.config_name = config_name self.production_variants = production_variants self.tags = tags self.async_inference_config = async_inference_config @property def arn_descriptor(self): return f":endpoint-config/{self.config_name}"
EndpointConfig
python
kubernetes-client__python
kubernetes/client/models/v1beta1_match_condition.py
{ "start": 383, "end": 7355 }
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 = { 'expression': 'str', 'name': 'str' } attribute_map = { 'expression': 'expression', 'name': 'name' } def __init__(self, expression=None, name=None, local_vars_configuration=None): # noqa: E501 """V1beta1MatchCondition - 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._expression = None self._name = None self.discriminator = None self.expression = expression self.name = name @property def expression(self): """Gets the expression of this V1beta1MatchCondition. # noqa: E501 Expression represents the expression which will be evaluated by CEL. Must evaluate to bool. CEL expressions have access to the contents of the AdmissionRequest and Authorizer, organized into CEL variables: 'object' - The object from the incoming request. The value is null for DELETE requests. 'oldObject' - The existing object. The value is null for CREATE requests. 'request' - Attributes of the admission request(/pkg/apis/admission/types.go#AdmissionRequest). 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request. See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the request resource. Documentation on CEL: https://kubernetes.io/docs/reference/using-api/cel/ Required. # noqa: E501 :return: The expression of this V1beta1MatchCondition. # noqa: E501 :rtype: str """ return self._expression @expression.setter def expression(self, expression): """Sets the expression of this V1beta1MatchCondition. Expression represents the expression which will be evaluated by CEL. Must evaluate to bool. CEL expressions have access to the contents of the AdmissionRequest and Authorizer, organized into CEL variables: 'object' - The object from the incoming request. The value is null for DELETE requests. 'oldObject' - The existing object. The value is null for CREATE requests. 'request' - Attributes of the admission request(/pkg/apis/admission/types.go#AdmissionRequest). 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request. See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the request resource. Documentation on CEL: https://kubernetes.io/docs/reference/using-api/cel/ Required. # noqa: E501 :param expression: The expression of this V1beta1MatchCondition. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and expression is None: # noqa: E501 raise ValueError("Invalid value for `expression`, must not be `None`") # noqa: E501 self._expression = expression @property def name(self): """Gets the name of this V1beta1MatchCondition. # noqa: E501 Name is an identifier for this match condition, used for strategic merging of MatchConditions, as well as providing an identifier for logging purposes. A good name should be descriptive of the associated expression. Name must be a qualified name consisting of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName', or 'my.name', or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]') with an optional DNS subdomain prefix and '/' (e.g. 'example.com/MyName') Required. # noqa: E501 :return: The name of this V1beta1MatchCondition. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this V1beta1MatchCondition. Name is an identifier for this match condition, used for strategic merging of MatchConditions, as well as providing an identifier for logging purposes. A good name should be descriptive of the associated expression. Name must be a qualified name consisting of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName', or 'my.name', or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]') with an optional DNS subdomain prefix and '/' (e.g. 'example.com/MyName') Required. # noqa: E501 :param name: The name of this V1beta1MatchCondition. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501 raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name 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, V1beta1MatchCondition): 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, V1beta1MatchCondition): return True return self.to_dict() != other.to_dict()
V1beta1MatchCondition
python
run-llama__llama_index
llama-index-core/llama_index/core/llama_dataset/evaluator_evaluation.py
{ "start": 12255, "end": 12829 }
class ____(LabelledEvaluatorDataExample): """Labelled pairwise evaluation data example class.""" second_answer: str = Field( default_factory=str, description="The second answer to the example that is to be evaluated along versus `answer`.", ) second_answer_by: Optional[CreatedBy] = Field( default=None, description="What generated the second answer." ) @property def class_name(self) -> str: """Data example class name.""" return "LabelledPairwiseEvaluatorDataExample"
LabelledPairwiseEvaluatorDataExample
python
sphinx-doc__sphinx
sphinx/ext/autodoc/_legacy_class_based/_documenters.py
{ "start": 108491, "end": 112547 }
class ____(DocstringStripSignatureMixin, ClassLevelDocumenter): # type: ignore[misc] """Specialized Documenter subclass for properties.""" objtype = 'property' member_order = 60 # before AttributeDocumenter priority = AttributeDocumenter.priority + 1 @classmethod def can_document_member( cls: type[Documenter], member: Any, membername: str, isattr: bool, parent: Any ) -> bool: if isinstance(parent, ClassDocumenter): if inspect.isproperty(member): return True else: __dict__ = safe_getattr(parent.object, '__dict__', {}) obj = __dict__.get(membername) return isinstance(obj, classmethod) and inspect.isproperty(obj.__func__) else: return False def import_object(self, raiseerror: bool = False) -> bool: """Check the existence of uninitialized instance attribute when failed to import the attribute. """ ret = super().import_object(raiseerror) if ret and not inspect.isproperty(self.object): __dict__ = safe_getattr(self.parent, '__dict__', {}) obj = __dict__.get(self.objpath[-1]) if isinstance(obj, classmethod) and inspect.isproperty(obj.__func__): self.object = obj.__func__ self.isclassmethod: bool = True return True else: return False self.isclassmethod = False return ret def format_args(self, **kwargs: Any) -> str: func = self._get_property_getter() if func is None: return '' # update the annotations of the property getter self._events.emit('autodoc-before-process-signature', func, False) # correctly format the arguments for a property return super().format_args(**kwargs) def document_members(self, all_members: bool = False) -> None: pass def get_real_modname(self) -> str: real_modname = self.get_attr(self.parent or self.object, '__module__', None) return real_modname or self.modname def add_directive_header(self, sig: str) -> None: super().add_directive_header(sig) sourcename = self.get_sourcename() if inspect.isabstractmethod(self.object): self.add_line(' :abstractmethod:', sourcename) if self.isclassmethod: self.add_line(' :classmethod:', sourcename) func = self._get_property_getter() if func is None or self.config.autodoc_typehints == 'none': return try: signature = inspect.signature( func, type_aliases=self.config.autodoc_type_aliases ) if signature.return_annotation is not Parameter.empty: mode = _get_render_mode(self.config.autodoc_typehints_format) short_literals = self.config.python_display_short_literal_types objrepr = stringify_annotation( signature.return_annotation, mode, short_literals=short_literals ) self.add_line(' :type: ' + objrepr, sourcename) except TypeError as exc: logger.warning( __('Failed to get a function signature for %s: %s'), self.fullname, exc ) pass except ValueError: pass def _get_property_getter(self) -> Callable[..., Any] | None: if safe_getattr(self.object, 'fget', None): # property return self.object.fget if safe_getattr(self.object, 'func', None): # cached_property return self.object.func return None def autodoc_attrgetter( obj: Any, name: str, *defargs: Any, registry: SphinxComponentRegistry ) -> Any: """Alternative getattr() for types""" for typ, func in registry.autodoc_attrgetters.items(): if isinstance(obj, typ): return func(obj, name, *defargs) return safe_getattr(obj, name, *defargs)
PropertyDocumenter
python
Pylons__pyramid
tests/test_config/test_actions.py
{ "start": 9035, "end": 20198 }
class ____(unittest.TestCase): def _makeOne(self): from pyramid.config.actions import ActionState return ActionState() def test_it(self): c = self._makeOne() self.assertEqual(c.actions, []) def test_action_simple(self): from . import dummyfactory as f c = self._makeOne() c.actions = [] c.action(1, f, (1,), {'x': 1}) self.assertEqual( c.actions, [ { 'args': (1,), 'callable': f, 'discriminator': 1, 'includepath': (), 'info': None, 'introspectables': (), 'kw': {'x': 1}, 'order': 0, } ], ) c.action(None) self.assertEqual( c.actions, [ { 'args': (1,), 'callable': f, 'discriminator': 1, 'includepath': (), 'info': None, 'introspectables': (), 'kw': {'x': 1}, 'order': 0, }, { 'args': (), 'callable': None, 'discriminator': None, 'includepath': (), 'info': None, 'introspectables': (), 'kw': {}, 'order': 0, }, ], ) def test_action_with_includepath(self): c = self._makeOne() c.actions = [] c.action(None, includepath=('abc',)) self.assertEqual( c.actions, [ { 'args': (), 'callable': None, 'discriminator': None, 'includepath': ('abc',), 'info': None, 'introspectables': (), 'kw': {}, 'order': 0, } ], ) def test_action_with_info(self): c = self._makeOne() c.action(None, info='abc') self.assertEqual( c.actions, [ { 'args': (), 'callable': None, 'discriminator': None, 'includepath': (), 'info': 'abc', 'introspectables': (), 'kw': {}, 'order': 0, } ], ) def test_action_with_includepath_and_info(self): c = self._makeOne() c.action(None, includepath=('spec',), info='bleh') self.assertEqual( c.actions, [ { 'args': (), 'callable': None, 'discriminator': None, 'includepath': ('spec',), 'info': 'bleh', 'introspectables': (), 'kw': {}, 'order': 0, } ], ) def test_action_with_order(self): c = self._makeOne() c.actions = [] c.action(None, order=99999) self.assertEqual( c.actions, [ { 'args': (), 'callable': None, 'discriminator': None, 'includepath': (), 'info': None, 'introspectables': (), 'kw': {}, 'order': 99999, } ], ) def test_action_with_introspectables(self): c = self._makeOne() c.actions = [] intr = DummyIntrospectable() c.action(None, introspectables=(intr,)) self.assertEqual( c.actions, [ { 'args': (), 'callable': None, 'discriminator': None, 'includepath': (), 'info': None, 'introspectables': (intr,), 'kw': {}, 'order': 0, } ], ) def test_processSpec(self): c = self._makeOne() self.assertTrue(c.processSpec('spec')) self.assertFalse(c.processSpec('spec')) def test_execute_actions_tuples(self): output = [] def f(*a, **k): output.append((a, k)) c = self._makeOne() c.actions = [ (1, f, (1,)), (1, f, (11,), {}, ('x',)), (2, f, (2,)), (None, None), ] c.execute_actions() self.assertEqual(output, [((1,), {}), ((2,), {})]) def test_execute_actions_dicts(self): output = [] def f(*a, **k): output.append((a, k)) c = self._makeOne() c.actions = [ { 'discriminator': 1, 'callable': f, 'args': (1,), 'kw': {}, 'order': 0, 'includepath': (), 'info': None, 'introspectables': (), }, { 'discriminator': 1, 'callable': f, 'args': (11,), 'kw': {}, 'includepath': ('x',), 'order': 0, 'info': None, 'introspectables': (), }, { 'discriminator': 2, 'callable': f, 'args': (2,), 'kw': {}, 'order': 0, 'includepath': (), 'info': None, 'introspectables': (), }, { 'discriminator': None, 'callable': None, 'args': (), 'kw': {}, 'order': 0, 'includepath': (), 'info': None, 'introspectables': (), }, ] c.execute_actions() self.assertEqual(output, [((1,), {}), ((2,), {})]) def test_execute_actions_with_introspectables(self): output = [] def f(*a, **k): output.append((a, k)) c = self._makeOne() intr = DummyIntrospectable() c.actions = [ { 'discriminator': 1, 'callable': f, 'args': (1,), 'kw': {}, 'order': 0, 'includepath': (), 'info': None, 'introspectables': (intr,), } ] introspector = object() c.execute_actions(introspector=introspector) self.assertEqual(output, [((1,), {})]) self.assertEqual(intr.registered, [(introspector, None)]) def test_execute_actions_with_introspectable_no_callable(self): c = self._makeOne() intr = DummyIntrospectable() c.actions = [ { 'discriminator': 1, 'callable': None, 'args': (1,), 'kw': {}, 'order': 0, 'includepath': (), 'info': None, 'introspectables': (intr,), } ] introspector = object() c.execute_actions(introspector=introspector) self.assertEqual(intr.registered, [(introspector, None)]) def test_execute_actions_error(self): output = [] def f(*a, **k): output.append(('f', a, k)) def bad(): raise NotImplementedError c = self._makeOne() c.actions = [ (1, f, (1,)), (1, f, (11,), {}, ('x',)), (2, f, (2,)), (3, bad, (), {}, (), 'oops'), ] self.assertRaises(ConfigurationExecutionError, c.execute_actions) self.assertEqual(output, [('f', (1,), {}), ('f', (2,), {})]) def test_reentrant_action(self): output = [] c = self._makeOne() def f(*a, **k): output.append(('f', a, k)) c.actions.append((3, g, (8,), {})) def g(*a, **k): output.append(('g', a, k)) c.actions = [(1, f, (1,))] c.execute_actions() self.assertEqual(output, [('f', (1,), {}), ('g', (8,), {})]) def test_reentrant_action_with_deferred_discriminator(self): # see https://github.com/Pylons/pyramid/issues/2697 from pyramid.registry import Deferred output = [] c = self._makeOne() def f(*a, **k): output.append(('f', a, k)) c.actions.append((4, g, (4,), {}, (), None, 2)) def g(*a, **k): output.append(('g', a, k)) def h(*a, **k): output.append(('h', a, k)) def discrim(): self.assertEqual(output, [('f', (1,), {}), ('g', (2,), {})]) return 3 d = Deferred(discrim) c.actions = [ (d, h, (3,), {}, (), None, 1), # order 1 (1, f, (1,)), # order 0 (2, g, (2,)), # order 0 ] c.execute_actions() self.assertEqual( output, [ ('f', (1,), {}), ('g', (2,), {}), ('h', (3,), {}), ('g', (4,), {}), ], ) def test_reentrant_action_error(self): from pyramid.exceptions import ConfigurationError c = self._makeOne() def f(*a, **k): c.actions.append((3, g, (8,), {}, (), None, -1)) def g(*a, **k): # pragma: no cover pass c.actions = [(1, f, (1,))] self.assertRaises(ConfigurationError, c.execute_actions) def test_reentrant_action_without_clear(self): c = self._makeOne() def f(*a, **k): c.actions.append((3, g, (8,))) def g(*a, **k): pass c.actions = [(1, f, (1,))] c.execute_actions(clear=False) self.assertEqual(c.actions, [(1, f, (1,)), (3, g, (8,))]) def test_executing_conflicting_action_across_orders(self): from pyramid.exceptions import ConfigurationConflictError c = self._makeOne() def f(*a, **k): pass def g(*a, **k): # pragma: no cover pass c.actions = [(1, f, (1,), {}, (), None, -1), (1, g, (2,))] self.assertRaises(ConfigurationConflictError, c.execute_actions) def test_executing_conflicting_action_across_reentrant_orders(self): from pyramid.exceptions import ConfigurationConflictError c = self._makeOne() def f(*a, **k): c.actions.append((1, g, (8,))) def g(*a, **k): # pragma: no cover pass c.actions = [(1, f, (1,), {}, (), None, -1)] self.assertRaises(ConfigurationConflictError, c.execute_actions)
TestActionState
python
coleifer__peewee
tests/signals.py
{ "start": 121, "end": 169 }
class ____(signals.Model): pass
BaseSignalModel
python
fsspec__filesystem_spec
fsspec/implementations/cache_mapper.py
{ "start": 722, "end": 1900 }
class ____(AbstractCacheMapper): """Cache mapper that uses the basename of the remote URL and a fixed number of directory levels above this. The default is zero directory levels, meaning different paths with the same basename will have the same cached basename. """ def __init__(self, directory_levels: int = 0): if directory_levels < 0: raise ValueError( "BasenameCacheMapper requires zero or positive directory_levels" ) self.directory_levels = directory_levels # Separator for directories when encoded as strings. self._separator = "_@_" def __call__(self, path: str) -> str: path = make_path_posix(path) prefix, *bits = path.rsplit("/", self.directory_levels + 1) if bits: return self._separator.join(bits) else: return prefix # No separator found, simple filename def __eq__(self, other: object) -> bool: return super().__eq__(other) and self.directory_levels == other.directory_levels def __hash__(self) -> int: return super().__hash__() ^ hash(self.directory_levels)
BasenameCacheMapper
python
apache__airflow
airflow-core/src/airflow/configuration.py
{ "start": 6042, "end": 39799 }
class ____(_SharedAirflowConfigParser): """ Custom Airflow Configparser supporting defaults and deprecated options. This is a subclass of the shared AirflowConfigParser that adds Core-specific initialization and functionality (providers, validation, writing, etc.). The defaults are stored in the ``_default_values``. The configuration description keeps description of all the options available in Airflow (description follow config.yaml.schema). :param default_config: default configuration (in the form of ini file). :param configuration_description: description of configuration to use """ def __init__( self, default_config: str | None = None, *args, **kwargs, ): configuration_description = retrieve_configuration_description(include_providers=False) # For those who would like to use a different data structure to keep defaults: # We have to keep the default values in a ConfigParser rather than in any other # data structure, because the values we have might contain %% which are ConfigParser # interpolation placeholders. The _default_values config parser will interpolate them # properly when we call get() on it. _default_values = create_default_config_parser(configuration_description) super().__init__(configuration_description, _default_values, *args, **kwargs) self.configuration_description = configuration_description self._default_values = _default_values self._provider_config_fallback_default_values = create_provider_config_fallback_defaults() if default_config is not None: self._update_defaults_from_string(default_config) self._update_logging_deprecated_template_to_one_from_defaults() self.is_validated = False self._suppress_future_warnings = False self._providers_configuration_loaded = False @property def _validators(self) -> list[Callable[[], None]]: """Overring _validators from shared base class to add core-specific validators.""" return [ self._validate_sqlite3_version, self._validate_enums, self._validate_deprecated_values, self._upgrade_postgres_metastore_conn, ] @property def _lookup_sequence(self) -> list[Callable]: """Overring _lookup_sequence from shared base class to add provider fallbacks.""" return super()._lookup_sequence + [self._get_option_from_provider_fallbacks] def _get_config_sources_for_as_dict(self) -> list[tuple[str, ConfigParser]]: """Override the base method to add provider fallbacks.""" return [ ("provider-fallback-defaults", self._provider_config_fallback_default_values), ("default", self._default_values), ("airflow.cfg", self), ] def _get_option_from_provider_fallbacks( self, deprecated_key: str | None, deprecated_section: str | None, key: str, section: str, issue_warning: bool = True, extra_stacklevel: int = 0, **kwargs, ) -> str | ValueNotFound: """Get config option from provider fallback defaults.""" if self.get_provider_config_fallback_defaults(section, key) is not None: # no expansion needed return self.get_provider_config_fallback_defaults(section, key, **kwargs) return VALUE_NOT_FOUND_SENTINEL def _update_logging_deprecated_template_to_one_from_defaults(self): default = self.get_default_value("logging", "log_filename_template") if default: # Tuple does not support item assignment, so we have to create a new tuple and replace it original_replacement = self.deprecated_values["logging"]["log_filename_template"] self.deprecated_values["logging"]["log_filename_template"] = ( original_replacement[0], default, ) def get_provider_config_fallback_defaults(self, section: str, key: str, **kwargs) -> Any: """Get provider config fallback default values.""" return self._provider_config_fallback_default_values.get(section, key, fallback=None, **kwargs) # A mapping of old default values that we want to change and warn the user # about. Mapping of section -> setting -> { old, replace } deprecated_values: dict[str, dict[str, tuple[Pattern, str]]] = { "logging": { "log_filename_template": ( re.compile( re.escape( "dag_id={{ ti.dag_id }}/run_id={{ ti.run_id }}/task_id={{ ti.task_id }}/{% if ti.map_index >= 0 %}map_index={{ ti.map_index }}/{% endif %}attempt={{ try_number }}.log" ) ), # The actual replacement value will be updated after defaults are loaded from config.yml "XX-set-after-default-config-loaded-XX", ), }, "core": { "executor": (re.compile(re.escape("SequentialExecutor")), "LocalExecutor"), }, } _available_logging_levels = ["CRITICAL", "FATAL", "ERROR", "WARN", "WARNING", "INFO", "DEBUG"] enums_options = { ("core", "default_task_weight_rule"): sorted(WeightRule.all_weight_rules()), ("core", "dag_ignore_file_syntax"): ["regexp", "glob"], ("core", "mp_start_method"): multiprocessing.get_all_start_methods(), ("dag_processor", "file_parsing_sort_mode"): [ "modified_time", "random_seeded_by_host", "alphabetical", ], ("logging", "logging_level"): _available_logging_levels, ("logging", "fab_logging_level"): _available_logging_levels, # celery_logging_level can be empty, which uses logging_level as fallback ("logging", "celery_logging_level"): [*_available_logging_levels, ""], ("webserver", "analytical_tool"): ["google_analytics", "metarouter", "segment", "matomo", ""], ("api", "grid_view_sorting_order"): ["topological", "hierarchical_alphabetical"], } upgraded_values: dict[tuple[str, str], str] """Mapping of (section,option) to the old value that was upgraded""" def write_custom_config( self, file: IO[str], comment_out_defaults: bool = True, include_descriptions: bool = True, extra_spacing: bool = True, modifications: ConfigModifications | None = None, ) -> None: """ Write a configuration file using a ConfigModifications object. This method includes only options from the current airflow.cfg. For each option: - If it's marked for removal, omit it. - If renamed, output it under its new name and add a comment indicating its original location. - If a default update is specified, apply the new default and output the option as a commented line. - Otherwise, if the current value equals the default and comment_out_defaults is True, output it as a comment. Options absent from the current airflow.cfg are omitted. :param file: File to write the configuration. :param comment_out_defaults: If True, options whose value equals the default are written as comments. :param include_descriptions: Whether to include section descriptions. :param extra_spacing: Whether to insert an extra blank line after each option. :param modifications: ConfigModifications instance with rename, remove, and default updates. """ modifications = modifications or ConfigModifications() output: dict[str, list[tuple[str, str, bool, str]]] = {} for section in self._sections: # type: ignore[attr-defined] # accessing _sections from ConfigParser for option, orig_value in self._sections[section].items(): # type: ignore[attr-defined] key = (section.lower(), option.lower()) if key in modifications.remove: continue mod_comment = "" if key in modifications.rename: new_sec, new_opt = modifications.rename[key] effective_section = new_sec effective_option = new_opt mod_comment += f"# Renamed from {section}.{option}\n" else: effective_section = section effective_option = option value = orig_value if key in modifications.default_updates: mod_comment += ( f"# Default updated from {orig_value} to {modifications.default_updates[key]}\n" ) value = modifications.default_updates[key] default_value = self.get_default_value(effective_section, effective_option, fallback="") is_default = str(value) == str(default_value) output.setdefault(effective_section.lower(), []).append( (effective_option, str(value), is_default, mod_comment) ) for section, options in output.items(): section_buffer = StringIO() section_buffer.write(f"[{section}]\n") if include_descriptions: description = self.configuration_description.get(section, {}).get("description", "") if description: for line in description.splitlines(): section_buffer.write(f"# {line}\n") section_buffer.write("\n") for option, value_str, is_default, mod_comment in options: key = (section.lower(), option.lower()) if key in modifications.default_updates and comment_out_defaults: section_buffer.write(f"# {option} = {value_str}\n") else: if mod_comment: section_buffer.write(mod_comment) if is_default and comment_out_defaults: section_buffer.write(f"# {option} = {value_str}\n") else: section_buffer.write(f"{option} = {value_str}\n") if extra_spacing: section_buffer.write("\n") content = section_buffer.getvalue().strip() if content: file.write(f"{content}\n\n") def _ensure_providers_config_loaded(self) -> None: """Ensure providers configurations are loaded.""" if not self._providers_configuration_loaded: from airflow.providers_manager import ProvidersManager ProvidersManager()._initialize_providers_configuration() def _ensure_providers_config_unloaded(self) -> bool: """Ensure providers configurations are unloaded temporarily to load core configs. Returns True if providers get unloaded.""" if self._providers_configuration_loaded: self.restore_core_default_configuration() return True return False def _reload_provider_configs(self) -> None: """Reload providers configuration.""" self.load_providers_configuration() def restore_core_default_configuration(self) -> None: """ Restore default configuration for core Airflow. It does not restore configuration for providers. If you want to restore configuration for providers, you need to call ``load_providers_configuration`` method. """ self.configuration_description = retrieve_configuration_description(include_providers=False) self._default_values = create_default_config_parser(self.configuration_description) self._providers_configuration_loaded = False def _upgrade_postgres_metastore_conn(self): """ Upgrade SQL schemas. As of SQLAlchemy 1.4, schemes `postgres+psycopg2` and `postgres` must be replaced with `postgresql`. """ section, key = "database", "sql_alchemy_conn" old_value = self.get(section, key, _extra_stacklevel=1) bad_schemes = ["postgres+psycopg2", "postgres"] good_scheme = "postgresql" parsed = urlsplit(old_value) if parsed.scheme in bad_schemes: warnings.warn( f"Bad scheme in Airflow configuration [database] sql_alchemy_conn: `{parsed.scheme}`. " "As of SQLAlchemy 1.4 (adopted in Airflow 2.3) this is no longer supported. You must " f"change to `{good_scheme}` before the next Airflow release.", FutureWarning, stacklevel=1, ) self.upgraded_values[(section, key)] = old_value new_value = re.sub("^" + re.escape(f"{parsed.scheme}://"), f"{good_scheme}://", old_value) self._update_env_var(section=section, name=key, new_value=new_value) # if the old value is set via env var, we need to wipe it # otherwise, it'll "win" over our adjusted value old_env_var = self._env_var_name("core", key) os.environ.pop(old_env_var, None) def _validate_enums(self): """Validate that enum type config has an accepted value.""" for (section_key, option_key), enum_options in self.enums_options.items(): if self.has_option(section_key, option_key): value = self.get(section_key, option_key, fallback=None) if value and value not in enum_options: raise AirflowConfigException( f"`[{section_key}] {option_key}` should not be " f"{value!r}. Possible values: {', '.join(enum_options)}." ) def _validate_sqlite3_version(self): """ Validate SQLite version. Some features in storing rendered fields require SQLite >= 3.15.0. """ if "sqlite" not in self.get("database", "sql_alchemy_conn"): return import sqlite3 min_sqlite_version = (3, 15, 0) if _parse_sqlite_version(sqlite3.sqlite_version) >= min_sqlite_version: return from airflow.utils.docs import get_docs_url min_sqlite_version_str = ".".join(str(s) for s in min_sqlite_version) raise AirflowConfigException( f"error: SQLite C library too old (< {min_sqlite_version_str}). " f"See {get_docs_url('howto/set-up-database.html#setting-up-a-sqlite-database')}" ) def mask_secrets(self): from airflow._shared.secrets_masker import mask_secret as mask_secret_core from airflow.sdk.log import mask_secret as mask_secret_sdk for section, key in self.sensitive_config_values: try: with self.suppress_future_warnings(): value = self.get(section, key, suppress_warnings=True) except AirflowConfigException: log.debug( "Could not retrieve value from section %s, for key %s. Skipping redaction of this conf.", section, key, ) continue mask_secret_core(value) mask_secret_sdk(value) def load_test_config(self): """ Use test configuration rather than the configuration coming from airflow defaults. When running tests we use special the unit_test configuration to avoid accidental modifications and different behaviours when running the tests. Values for those test configuration are stored in the "unit_tests.cfg" configuration file in the ``airflow/config_templates`` folder and you need to change values there if you want to make some specific configuration to be used """ # We need those globals before we run "get_all_expansion_variables" because this is where # the variables are expanded from in the configuration global FERNET_KEY, JWT_SECRET_KEY from cryptography.fernet import Fernet unit_test_config_file = pathlib.Path(__file__).parent / "config_templates" / "unit_tests.cfg" unit_test_config = unit_test_config_file.read_text() self.remove_all_read_configurations() with StringIO(unit_test_config) as test_config_file: self.read_file(test_config_file) # set fernet key to a random value FERNET_KEY = Fernet.generate_key().decode() JWT_SECRET_KEY = b64encode(os.urandom(16)).decode("utf-8") self.expand_all_configuration_values() log.info("Unit test configuration loaded from 'config_unit_tests.cfg'") def expand_all_configuration_values(self): """Expand all configuration values using global and local variables defined in this module.""" all_vars = get_all_expansion_variables() for section in self.sections(): for key, value in self.items(section): if value is not None: if self.has_option(section, key): self.remove_option(section, key) if self.is_template(section, key) or not isinstance(value, str): self.set(section, key, value) else: self.set(section, key, value.format(**all_vars)) def remove_all_read_configurations(self): """Remove all read configurations, leaving only default values in the config.""" for section in self.sections(): self.remove_section(section) @property def providers_configuration_loaded(self) -> bool: """Checks if providers have been loaded.""" return self._providers_configuration_loaded def load_providers_configuration(self): """ Load configuration for providers. This should be done after initial configuration have been performed. Initializing and discovering providers is an expensive operation and cannot be performed when we load configuration for the first time when airflow starts, because we initialize configuration very early, during importing of the `airflow` package and the module is not yet ready to be used when it happens and until configuration and settings are loaded. Therefore, in order to reload provider configuration we need to additionally load provider - specific configuration. """ log.debug("Loading providers configuration") from airflow.providers_manager import ProvidersManager self.restore_core_default_configuration() for provider, config in ProvidersManager().already_initialized_provider_configs: for provider_section, provider_section_content in config.items(): provider_options = provider_section_content["options"] section_in_current_config = self.configuration_description.get(provider_section) if not section_in_current_config: self.configuration_description[provider_section] = deepcopy(provider_section_content) section_in_current_config = self.configuration_description.get(provider_section) section_in_current_config["source"] = f"default-{provider}" for option in provider_options: section_in_current_config["options"][option]["source"] = f"default-{provider}" else: section_source = section_in_current_config.get("source", "Airflow's core package").split( "default-" )[-1] raise AirflowConfigException( f"The provider {provider} is attempting to contribute " f"configuration section {provider_section} that " f"has already been added before. The source of it: {section_source}. " "This is forbidden. A provider can only add new sections. It " "cannot contribute options to existing sections or override other " "provider's configuration.", UserWarning, ) self._default_values = create_default_config_parser(self.configuration_description) # sensitive_config_values needs to be refreshed here. This is a cached_property, so we can delete # the cached values, and it will be refreshed on next access. with contextlib.suppress(AttributeError): # no problem if cache is not set yet del self.sensitive_config_values self._providers_configuration_loaded = True def _get_config_value_from_secret_backend(self, config_key: str) -> str | None: """ Override to use module-level function that reads from global conf. This ensures as_dict() and other methods use the same secrets backend configuration as the global conf instance (set via conf_vars in tests). """ secrets_client = get_custom_secret_backend() if not secrets_client: return None try: return secrets_client.get_config(config_key) except Exception as e: raise AirflowConfigException( "Cannot retrieve config from alternative secrets backend. " "Make sure it is configured properly and that the Backend " "is accessible.\n" f"{e}" ) def __getstate__(self) -> dict[str, Any]: """Return the state of the object as a dictionary for pickling.""" return { name: getattr(self, name) for name in [ "_sections", "is_validated", "configuration_description", "upgraded_values", "_default_values", ] } def __setstate__(self, state) -> None: """Restore the state of the object from a dictionary representation.""" self.__init__() # type: ignore[misc] config = state.pop("_sections") self.read_dict(config) self.__dict__.update(state) def get_airflow_home() -> str: """Get path to Airflow Home.""" return expand_env_var(os.environ.get("AIRFLOW_HOME", "~/airflow")) def get_airflow_config(airflow_home: str) -> str: """Get Path to airflow.cfg path.""" airflow_config_var = os.environ.get("AIRFLOW_CONFIG") if airflow_config_var is None: return os.path.join(airflow_home, "airflow.cfg") return expand_env_var(airflow_config_var) def get_all_expansion_variables() -> dict[str, Any]: return {k: v for d in [globals(), locals()] for k, v in d.items() if not k.startswith("_")} def _generate_fernet_key() -> str: from cryptography.fernet import Fernet return Fernet.generate_key().decode() def create_default_config_parser(configuration_description: dict[str, dict[str, Any]]) -> ConfigParser: """ Create default config parser based on configuration description. It creates ConfigParser with all default values retrieved from the configuration description and expands all the variables from the global and local variables defined in this module. :param configuration_description: configuration description - retrieved from config.yaml files following the schema defined in "config.yml.schema.json" in the config_templates folder. :return: Default Config Parser that can be used to read configuration values from. """ parser = ConfigParser() all_vars = get_all_expansion_variables() for section, section_desc in configuration_description.items(): parser.add_section(section) options = section_desc["options"] for key in options: default_value = options[key]["default"] is_template = options[key].get("is_template", False) if default_value is not None: if is_template or not isinstance(default_value, str): parser.set(section, key, default_value) else: parser.set(section, key, default_value.format(**all_vars)) return parser def create_provider_config_fallback_defaults() -> ConfigParser: """ Create fallback defaults. This parser contains provider defaults for Airflow configuration, containing fallback default values that might be needed when provider classes are being imported - before provider's configuration is loaded. Unfortunately airflow currently performs a lot of stuff during importing and some of that might lead to retrieving provider configuration before the defaults for the provider are loaded. Those are only defaults, so if you have "real" values configured in your configuration (.cfg file or environment variables) those will be used as usual. NOTE!! Do NOT attempt to remove those default fallbacks thinking that they are unnecessary duplication, at least not until we fix the way how airflow imports "do stuff". This is unlikely to succeed. You've been warned! """ config_parser = ConfigParser() config_parser.read(_default_config_file_path("provider_config_fallback_defaults.cfg")) return config_parser def write_default_airflow_configuration_if_needed() -> AirflowConfigParser: global FERNET_KEY, JWT_SECRET_KEY airflow_config = pathlib.Path(AIRFLOW_CONFIG) if airflow_config.is_dir(): msg = ( "Airflow config expected to be a path to the configuration file, " f"but got a directory {airflow_config.__fspath__()!r}." ) raise IsADirectoryError(msg) if not airflow_config.exists(): log.debug("Creating new Airflow config file in: %s", airflow_config.__fspath__()) config_directory = airflow_config.parent if not config_directory.exists(): if not config_directory.is_relative_to(AIRFLOW_HOME): msg = ( f"Config directory {config_directory.__fspath__()!r} not exists " f"and it is not relative to AIRFLOW_HOME {AIRFLOW_HOME!r}. " "Please create this directory first." ) raise FileNotFoundError(msg) from None log.debug("Create directory %r for Airflow config", config_directory.__fspath__()) config_directory.mkdir(parents=True, exist_ok=True) if conf.get("core", "fernet_key", fallback=None) in (None, ""): # We know that FERNET_KEY is not set, so we can generate it, set as global key # and also write it to the config file so that same key will be used next time FERNET_KEY = _generate_fernet_key() conf.configuration_description["core"]["options"]["fernet_key"]["default"] = FERNET_KEY JWT_SECRET_KEY = b64encode(os.urandom(16)).decode("utf-8") conf.configuration_description["api_auth"]["options"]["jwt_secret"]["default"] = JWT_SECRET_KEY pathlib.Path(airflow_config.__fspath__()).touch() make_group_other_inaccessible(airflow_config.__fspath__()) with open(airflow_config, "w") as file: conf.write( file, include_sources=False, include_env_vars=True, include_providers=True, extra_spacing=True, only_defaults=True, ) return conf def load_standard_airflow_configuration(airflow_config_parser: AirflowConfigParser): """ Load standard airflow configuration. In case it finds that the configuration file is missing, it will create it and write the default configuration values there, based on defaults passed, and will add the comments and examples from the default configuration. :param airflow_config_parser: parser to which the configuration will be loaded """ global AIRFLOW_HOME log.info("Reading the config from %s", AIRFLOW_CONFIG) airflow_config_parser.read(AIRFLOW_CONFIG) if airflow_config_parser.has_option("core", "AIRFLOW_HOME"): msg = ( "Specifying both AIRFLOW_HOME environment variable and airflow_home " "in the config file is deprecated. Please use only the AIRFLOW_HOME " "environment variable and remove the config file entry." ) if "AIRFLOW_HOME" in os.environ: warnings.warn(msg, category=DeprecationWarning, stacklevel=1) elif airflow_config_parser.get("core", "airflow_home") == AIRFLOW_HOME: warnings.warn( "Specifying airflow_home in the config file is deprecated. As you " "have left it at the default value you should remove the setting " "from your airflow.cfg and suffer no change in behaviour.", category=DeprecationWarning, stacklevel=1, ) else: AIRFLOW_HOME = airflow_config_parser.get("core", "airflow_home") warnings.warn(msg, category=DeprecationWarning, stacklevel=1) def initialize_config() -> AirflowConfigParser: """ Load the Airflow config files. Called for you automatically as part of the Airflow boot process. """ airflow_config_parser = AirflowConfigParser() if airflow_config_parser.getboolean("core", "unit_test_mode"): airflow_config_parser.load_test_config() else: load_standard_airflow_configuration(airflow_config_parser) # If the user set unit_test_mode in the airflow.cfg, we still # want to respect that and then load the default unit test configuration # file on top of it. if airflow_config_parser.getboolean("core", "unit_test_mode"): airflow_config_parser.load_test_config() return airflow_config_parser def make_group_other_inaccessible(file_path: str): try: permissions = os.stat(file_path) os.chmod(file_path, permissions.st_mode & (stat.S_IRUSR | stat.S_IWUSR)) except Exception as e: log.warning( "Could not change permissions of config file to be group/other inaccessible. " "Continuing with original permissions: %s", e, ) def ensure_secrets_loaded( default_backends: list[str] = DEFAULT_SECRETS_SEARCH_PATH, ) -> list[BaseSecretsBackend]: """ Ensure that all secrets backends are loaded. If the secrets_backend_list contains only 2 default backends, reload it. """ # Check if the secrets_backend_list contains only 2 default backends. # Check if we are loading the backends for worker too by checking if the default_backends is equal # to DEFAULT_SECRETS_SEARCH_PATH. if len(secrets_backend_list) == 2 or default_backends != DEFAULT_SECRETS_SEARCH_PATH: return initialize_secrets_backends(default_backends=default_backends) return secrets_backend_list def get_custom_secret_backend(worker_mode: bool = False) -> BaseSecretsBackend | None: """ Get Secret Backend if defined in airflow.cfg. Conditionally selects the section, key and kwargs key based on whether it is called from worker or not. This is a convenience function that calls conf._get_custom_secret_backend(). """ return conf._get_custom_secret_backend(worker_mode=worker_mode) def initialize_secrets_backends( default_backends: list[str] = DEFAULT_SECRETS_SEARCH_PATH, ) -> list[BaseSecretsBackend]: """ Initialize secrets backend. * import secrets backend classes * instantiate them and return them in a list """ backend_list = [] worker_mode = False if default_backends != DEFAULT_SECRETS_SEARCH_PATH: worker_mode = True custom_secret_backend = get_custom_secret_backend(worker_mode) if custom_secret_backend is not None: backend_list.append(custom_secret_backend) for class_name in default_backends: secrets_backend_cls = import_string(class_name) backend_list.append(secrets_backend_cls()) return backend_list def initialize_auth_manager() -> BaseAuthManager: """ Initialize auth manager. * import user manager class * instantiate it and return it """ auth_manager_cls = conf.getimport(section="core", key="auth_manager") if not auth_manager_cls: raise AirflowConfigException( "No auth manager defined in the config. Please specify one using section/key [core/auth_manager]." ) return auth_manager_cls() # Setting AIRFLOW_HOME and AIRFLOW_CONFIG from environment variables, using # "~/airflow" and "$AIRFLOW_HOME/airflow.cfg" respectively as defaults. AIRFLOW_HOME = get_airflow_home() AIRFLOW_CONFIG = get_airflow_config(AIRFLOW_HOME) # Set up dags folder for unit tests # this directory won't exist if users install via pip _TEST_DAGS_FOLDER = os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "tests", "dags" ) if os.path.exists(_TEST_DAGS_FOLDER): TEST_DAGS_FOLDER = _TEST_DAGS_FOLDER else: TEST_DAGS_FOLDER = os.path.join(AIRFLOW_HOME, "dags") # Set up plugins folder for unit tests _TEST_PLUGINS_FOLDER = os.path.join( os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "tests", "plugins" ) if os.path.exists(_TEST_PLUGINS_FOLDER): TEST_PLUGINS_FOLDER = _TEST_PLUGINS_FOLDER else: TEST_PLUGINS_FOLDER = os.path.join(AIRFLOW_HOME, "plugins") SECRET_KEY = b64encode(os.urandom(16)).decode("utf-8") FERNET_KEY = "" # Set only if needed when generating a new file JWT_SECRET_KEY = "" conf: AirflowConfigParser = initialize_config() secrets_backend_list = initialize_secrets_backends() conf.validate()
AirflowConfigParser
python
encode__django-rest-framework
rest_framework/fields.py
{ "start": 58776, "end": 62139 }
class ____(Field): child = _UnvalidatedField() initial = [] default_error_messages = { 'not_a_list': _('Expected a list of items but got type "{input_type}".'), 'empty': _('This list may not be empty.'), 'min_length': _('Ensure this field has at least {min_length} elements.'), 'max_length': _('Ensure this field has no more than {max_length} elements.') } def __init__(self, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) self.allow_empty = kwargs.pop('allow_empty', True) self.max_length = kwargs.pop('max_length', None) self.min_length = kwargs.pop('min_length', None) assert not inspect.isclass(self.child), '`child` has not been instantiated.' assert self.child.source is None, ( "The `source` argument is not meaningful when applied to a `child=` field. " "Remove `source=` from the field declaration." ) super().__init__(**kwargs) self.child.bind(field_name='', parent=self) if self.max_length is not None: message = lazy_format(self.error_messages['max_length'], max_length=self.max_length) self.validators.append(MaxLengthValidator(self.max_length, message=message)) if self.min_length is not None: message = lazy_format(self.error_messages['min_length'], min_length=self.min_length) self.validators.append(MinLengthValidator(self.min_length, message=message)) def get_value(self, dictionary): if self.field_name not in dictionary: if getattr(self.root, 'partial', False): return empty # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): val = dictionary.getlist(self.field_name, []) if len(val) > 0: # Support QueryDict lists in HTML input. return val return html.parse_html_list(dictionary, prefix=self.field_name, default=empty) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): """ List of dicts of native values <- List of dicts of primitive datatypes. """ if html.is_html_input(data): data = html.parse_html_list(data, default=[]) if isinstance(data, (str, Mapping)) or not hasattr(data, '__iter__'): self.fail('not_a_list', input_type=type(data).__name__) if not self.allow_empty and len(data) == 0: self.fail('empty') return self.run_child_validation(data) def to_representation(self, data): """ List of object instances -> List of dicts of primitive datatypes. """ return [self.child.to_representation(item) if item is not None else None for item in data] def run_child_validation(self, data): result = [] errors = {} for idx, item in enumerate(data): try: result.append(self.child.run_validation(item)) except ValidationError as e: errors[idx] = e.detail except DjangoValidationError as e: errors[idx] = get_error_detail(e) if not errors: return result raise ValidationError(errors)
ListField
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pydocstyle/D.py
{ "start": 14791, "end": 14982 }
class ____: """This is a docstring on the same line""" def same_line(): """This is a docstring on the same line""" def single_line_docstring_with_an_escaped_backslash(): "\ "
SameLine
python
great-expectations__great_expectations
tests/integration/test_utils/data_source_config/pandas_filesystem_csv.py
{ "start": 1898, "end": 3177 }
class ____( BatchTestSetup[PandasFilesystemCsvDatasourceTestConfig, CSVAsset] ): def __init__( self, config: PandasFilesystemCsvDatasourceTestConfig, data: pd.DataFrame, base_dir: pathlib.Path, context: AbstractDataContext, ) -> None: super().__init__(config=config, data=data, context=context) self._base_dir = base_dir @override def make_asset(self) -> CSVAsset: return self.context.data_sources.add_pandas_filesystem( name=self._random_resource_name(), base_directory=self._base_dir ).add_csv_asset( name=self._random_resource_name(), **self.config.read_options, ) @override def make_batch(self) -> Batch: return ( self.make_asset() .add_batch_definition_path(name=self._random_resource_name(), path=self.csv_path) .get_batch() ) @override def setup(self) -> None: file_path = self._base_dir / self.csv_path self.data.to_csv(file_path, index=False, **self.config.write_options) @override def teardown(self) -> None: ... @property def csv_path(self) -> pathlib.Path: return pathlib.Path("data.csv")
PandasFilesystemCsvBatchTestSetup
python
Delgan__loguru
tests/test_reinstall.py
{ "start": 249, "end": 2332 }
class ____: def __init__(self): self._output = "" def write(self, message): self._output += message def read(self): return self._output def subworker(logger): logger.reinstall() logger.info("Child") deeper_subworker() def poolworker(_): logger.info("Child") deeper_subworker() def deeper_subworker(): logger.info("Grandchild") @pytest.mark.skipif(os.name == "nt", reason="Windows does not support forking") def test_process_fork(fork_context): writer = Writer() logger.add(writer, context=fork_context, format="{message}", enqueue=True, catch=False) process = fork_context.Process(target=subworker, args=(logger,)) process.start() process.join() assert process.exitcode == 0 logger.info("Main") logger.remove() assert writer.read() == "Child\nGrandchild\nMain\n" def test_process_spawn(spawn_context): writer = Writer() logger.add(writer, context=spawn_context, format="{message}", enqueue=True, catch=False) process = spawn_context.Process(target=subworker, args=(logger,)) process.start() process.join() assert process.exitcode == 0 logger.info("Main") logger.remove() assert writer.read() == "Child\nGrandchild\nMain\n" @pytest.mark.skipif(os.name == "nt", reason="Windows does not support forking") def test_pool_fork(fork_context): writer = Writer() logger.add(writer, context=fork_context, format="{message}", enqueue=True, catch=False) with fork_context.Pool(1, initializer=logger.reinstall) as pool: pool.map(poolworker, [None]) logger.info("Main") logger.remove() assert writer.read() == "Child\nGrandchild\nMain\n" def test_pool_spawn(spawn_context): writer = Writer() logger.add(writer, context=spawn_context, format="{message}", enqueue=True, catch=False) with spawn_context.Pool(1, initializer=logger.reinstall) as pool: pool.map(poolworker, [None]) logger.info("Main") logger.remove() assert writer.read() == "Child\nGrandchild\nMain\n"
Writer
python
Unity-Technologies__ml-agents
ml-agents-envs/tests/test_side_channel.py
{ "start": 798, "end": 8559 }
class ____(SideChannel): def __init__(self): self.list_int = [] super().__init__(uuid.UUID("a85ba5c0-4f87-11ea-a517-784f4387d1f7")) def on_message_received(self, msg: IncomingMessage) -> None: val = msg.read_int32() self.list_int += [val] def send_int(self, value): msg = OutgoingMessage() msg.write_int32(value) super().queue_message_to_send(msg) def test_int_channel(): sender = IntChannel() receiver = IntChannel() sender.send_int(5) sender.send_int(6) data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([receiver]).process_side_channel_message(data) assert receiver.list_int[0] == 5 assert receiver.list_int[1] == 6 def test_float_properties(): sender = FloatPropertiesChannel() receiver = FloatPropertiesChannel() sender.set_property("prop1", 1.0) data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([receiver]).process_side_channel_message(data) val = receiver.get_property("prop1") assert val == 1.0 val = receiver.get_property("prop2") assert val is None sender.set_property("prop2", 2.0) data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([receiver]).process_side_channel_message(data) val = receiver.get_property("prop1") assert val == 1.0 val = receiver.get_property("prop2") assert val == 2.0 assert len(receiver.list_properties()) == 2 assert "prop1" in receiver.list_properties() assert "prop2" in receiver.list_properties() val = sender.get_property("prop1") assert val == 1.0 assert receiver.get_property_dict_copy() == {"prop1": 1.0, "prop2": 2.0} assert receiver.get_property_dict_copy() == sender.get_property_dict_copy() def test_raw_bytes(): guid = uuid.uuid4() sender = RawBytesChannel(guid) receiver = RawBytesChannel(guid) sender.send_raw_data(b"foo") sender.send_raw_data(b"bar") data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([receiver]).process_side_channel_message(data) messages = receiver.get_and_clear_received_messages() assert len(messages) == 2 assert messages[0].decode("ascii") == "foo" assert messages[1].decode("ascii") == "bar" messages = receiver.get_and_clear_received_messages() assert len(messages) == 0 def test_message_bool(): vals = [True, False] msg_out = OutgoingMessage() for v in vals: msg_out.write_bool(v) msg_in = IncomingMessage(msg_out.buffer) read_vals = [] for _ in range(len(vals)): read_vals.append(msg_in.read_bool()) assert vals == read_vals # Test reading with defaults assert msg_in.read_bool() is False assert msg_in.read_bool(default_value=True) is True def test_message_int32(): val = 1337 msg_out = OutgoingMessage() msg_out.write_int32(val) msg_in = IncomingMessage(msg_out.buffer) read_val = msg_in.read_int32() assert val == read_val # Test reading with defaults assert 0 == msg_in.read_int32() assert val == msg_in.read_int32(default_value=val) def test_message_float32(): val = 42.0 msg_out = OutgoingMessage() msg_out.write_float32(val) msg_in = IncomingMessage(msg_out.buffer) read_val = msg_in.read_float32() # These won't be exactly equal in general, since python floats are 64-bit. assert val == read_val # Test reading with defaults assert 0.0 == msg_in.read_float32() assert val == msg_in.read_float32(default_value=val) def test_message_string(): val = "mlagents!" msg_out = OutgoingMessage() msg_out.write_string(val) msg_in = IncomingMessage(msg_out.buffer) read_val = msg_in.read_string() assert val == read_val # Test reading with defaults assert "" == msg_in.read_string() assert val == msg_in.read_string(default_value=val) def test_message_float_list(): val = [1.0, 3.0, 9.0] msg_out = OutgoingMessage() msg_out.write_float32_list(val) msg_in = IncomingMessage(msg_out.buffer) read_val = msg_in.read_float32_list() # These won't be exactly equal in general, since python floats are 64-bit. assert val == read_val # Test reading with defaults assert [] == msg_in.read_float32_list() assert val == msg_in.read_float32_list(default_value=val) def test_engine_configuration(): sender = EngineConfigurationChannel() # We use a raw bytes channel to interpred the data receiver = RawBytesChannel(sender.channel_id) config = EngineConfig.default_config() sender.set_configuration(config) data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([receiver]).process_side_channel_message(data) received_data = receiver.get_and_clear_received_messages() assert len(received_data) == 5 # 5 different messages one for each setting sent_time_scale = 4.5 sender.set_configuration_parameters(time_scale=sent_time_scale) data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([receiver]).process_side_channel_message(data) message = IncomingMessage(receiver.get_and_clear_received_messages()[0]) message.read_int32() time_scale = message.read_float32() assert time_scale == sent_time_scale with pytest.raises(UnitySideChannelException): sender.set_configuration_parameters(width=None, height=42) with pytest.raises(UnityCommunicationException): # try to send data to the EngineConfigurationChannel sender.set_configuration_parameters(time_scale=sent_time_scale) data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([sender]).process_side_channel_message(data) def test_environment_parameters(): sender = EnvironmentParametersChannel() # We use a raw bytes channel to interpred the data receiver = RawBytesChannel(sender.channel_id) sender.set_float_parameter("param-1", 0.1) data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([receiver]).process_side_channel_message(data) message = IncomingMessage(receiver.get_and_clear_received_messages()[0]) key = message.read_string() dtype = message.read_int32() value = message.read_float32() assert key == "param-1" assert dtype == EnvironmentParametersChannel.EnvironmentDataTypes.FLOAT assert value - 0.1 < 1e-8 sender.set_float_parameter("param-1", 0.1) sender.set_float_parameter("param-2", 0.1) sender.set_float_parameter("param-3", 0.1) data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([receiver]).process_side_channel_message(data) assert len(receiver.get_and_clear_received_messages()) == 3 with pytest.raises(UnityCommunicationException): # try to send data to the EngineConfigurationChannel sender.set_float_parameter("param-1", 0.1) data = SideChannelManager([sender]).generate_side_channel_messages() SideChannelManager([sender]).process_side_channel_message(data) def test_stats_channel(): receiver = StatsSideChannel() message = OutgoingMessage() message.write_string("stats-1") message.write_float32(42.0) message.write_int32(1) # corresponds to StatsAggregationMethod.MOST_RECENT receiver.on_message_received(IncomingMessage(message.buffer)) stats = receiver.get_and_reset_stats() assert len(stats) == 1 val, method = stats["stats-1"][0] assert val - 42.0 < 1e-8 assert method == StatsAggregationMethod.MOST_RECENT
IntChannel
python
apache__airflow
task-sdk/tests/task_sdk/execution_time/test_context_cache.py
{ "start": 11379, "end": 12520 }
class ____: """Test behavior when cache is disabled.""" @staticmethod @conf_vars({("secrets", "use_cache"): "false"}) def setup_method(): SecretCache.reset() SecretCache.init() @staticmethod def teardown_method(): SecretCache.reset() @patch("airflow.sdk.execution_time.supervisor.ensure_secrets_backend_loaded") def test_get_connection_no_cache_when_disabled(self, mock_ensure_backends, mock_supervisor_comms): """Test that cache is not used when disabled.""" conn_id = "test_conn" conn_result = ConnectionResult(conn_id=conn_id, conn_type="mysql", host="host") mock_ensure_backends.return_value = [ExecutionAPISecretsBackend()] mock_supervisor_comms.send.return_value = conn_result result = _get_connection(conn_id) assert result.conn_id == conn_id # Called for GetConnection (and possibly MaskSecret) assert mock_supervisor_comms.send.call_count >= 1 _get_connection(conn_id) # Called twice since cache is disabled assert mock_supervisor_comms.send.call_count >= 2
TestCacheDisabled
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol11.py
{ "start": 206, "end": 380 }
class ____: pass _T1 = TypeVar("_T1") _TBase1 = TypeVar("_TBase1", bound=Base) _TBase2 = TypeVar("_TBase2", bound=Base) def my_next(__i: Iterator[_T1]) -> _T1: ...
Base
python
google__jax
jax/_src/mesh.py
{ "start": 1241, "end": 3813 }
class ____(NamedTuple): physical_mesh: Mesh def with_mesh(self, mesh: Mesh): overlap = set(mesh.axis_names) & (self.resource_axes - set(self.physical_mesh.axis_names)) if overlap: raise ValueError(f"Cannot update the mesh of the current resource " f"environment. The new mesh shadows already defined axes " f"{show_axes(overlap)}") return self._replace(physical_mesh=mesh) @property def physical_resource_axes(self) -> set[ResourceAxisName]: return set(self.physical_mesh.axis_names) @property def resource_axes(self) -> set[ResourceAxisName]: return self.physical_resource_axes @property def shape(self): return self.physical_mesh.shape @property def local_shape(self): return self.physical_mesh.local_mesh.shape def __repr__(self): mesh_repr = ", ".join( f"'{k}': {v}" for k, v in self.physical_mesh.shape.items()) return f"ResourceEnv(mesh=Mesh({mesh_repr}))" @cache(max_size=128, trace_context_in_key=False) def _get_local_mesh(global_mesh: Mesh, process_index: int) -> Mesh: if global_mesh.empty: return global_mesh is_local_device = np.vectorize( lambda d: d.process_index == process_index, otypes=[bool])(global_mesh.devices) subcube_indices = [] # We take the smallest slice of each dimension that doesn't skip any local device. for axis in range(global_mesh.devices.ndim): other_axes = tuple_delete(tuple(range(global_mesh.devices.ndim)), axis) # NOTE: This re-reduces over many axes multiple times, so we could definitely # optimize it, but I hope it won't be a bottleneck anytime soon. local_slices = is_local_device.any(other_axes, keepdims=False) nonzero_indices = np.flatnonzero(local_slices) start, end = int(np.min(nonzero_indices)), int(np.max(nonzero_indices)) subcube_indices.append(slice(start, end + 1)) subcube_indices_tuple = tuple(subcube_indices) # We only end up with all conditions being true if the local devices formed a # subcube of the full array. This is because we were biased towards taking a # "hull" spanned by the devices, and in case the local devices don't form a # subcube that hull will contain non-local devices. if not is_local_device[subcube_indices_tuple].all(): raise ValueError( "When passing host local inputs to pjit, devices connected to a single" " host must form a contiguous subcube of the global device mesh" ) return Mesh(global_mesh.devices[subcube_indices_tuple], global_mesh.axis_names)
ResourceEnv
python
tensorflow__tensorflow
tensorflow/python/data/ops/padded_batch_op.py
{ "start": 6943, "end": 10741 }
class ____(dataset_ops.UnaryDataset): """A `Dataset` that batches and pads contiguous elements from its input.""" def __init__(self, input_dataset, batch_size, padded_shapes, padding_values, drop_remainder, name=None): """See `Dataset.batch()` for details.""" self._input_dataset = input_dataset def check_types(component_spec): if not isinstance(component_spec, tensor_spec.TensorSpec): if isinstance(component_spec, dataset_ops.DatasetSpec): raise TypeError( "`padded_batch` is not supported for datasets of datasets") raise TypeError(f"`padded_batch` is only supported for datasets that " f"produce tensor elements but type spec of elements in " f"the input dataset is not a subclass of TensorSpec: " f"`{component_spec}`.") nest.map_structure(check_types, input_dataset.element_spec) self._input_dataset = input_dataset self._batch_size = ops.convert_to_tensor( batch_size, dtype=dtypes.int64, name="batch_size") padding_values = _padding_values_or_default(padding_values, input_dataset) input_shapes = dataset_ops.get_legacy_output_shapes(input_dataset) flat_padded_shapes = nest.flatten_up_to(input_shapes, padded_shapes) flat_padded_shapes_as_tensors = [] for input_component_shape, padded_shape in zip( nest.flatten(input_shapes), flat_padded_shapes): flat_padded_shapes_as_tensors.append( _padded_shape_to_tensor(padded_shape, input_component_shape)) self._padded_shapes = nest.pack_sequence_as(input_shapes, flat_padded_shapes_as_tensors) # If padding_values is a single element and input_shapes is a structure, # "broadcast" padding_values to the same structure as input_shapes. if nest.is_nested(input_shapes) and not nest.is_nested(padding_values): padding_values = nest.map_structure(lambda _: padding_values, input_shapes) self._padding_values = nest.map_structure_up_to( input_shapes, _padding_value_to_tensor, padding_values, dataset_ops.get_legacy_output_types(input_dataset)) self._drop_remainder = ops.convert_to_tensor( drop_remainder, dtype=dtypes.bool, name="drop_remainder") def _padded_shape_to_batch_shape(s): return tensor_shape.TensorShape([ tensor_util.constant_value(self._batch_size) if smart_cond.smart_constant_value(self._drop_remainder) else None ]).concatenate(tensor_util.constant_value_as_shape(s)) output_shapes = nest.map_structure(_padded_shape_to_batch_shape, self._padded_shapes) self._structure = structure.convert_legacy_structure( dataset_ops.get_legacy_output_types(self._input_dataset), output_shapes, dataset_ops.get_legacy_output_classes(self._input_dataset)) self._name = name # pylint: disable=protected-access variant_tensor = gen_dataset_ops.padded_batch_dataset_v2( input_dataset._variant_tensor, # pylint: disable=protected-access batch_size=self._batch_size, padded_shapes=[ ops.convert_to_tensor(s, dtype=dtypes.int64) for s in nest.flatten(self._padded_shapes) ], padding_values=nest.flatten(self._padding_values), drop_remainder=self._drop_remainder, output_shapes=structure.get_flat_tensor_shapes(self._structure), metadata=self._metadata.SerializeToString()) super().__init__(input_dataset, variant_tensor) @property def element_spec(self): return self._structure
_PaddedBatchDataset
python
walkccc__LeetCode
solutions/2196. Create Binary Tree From Descriptions/2196.py
{ "start": 0, "end": 464 }
class ____: def createBinaryTree(self, descriptions: list[list[int]]) -> TreeNode | None: children = set() valToNode = {} for p, c, isLeft in descriptions: parent = valToNode.setdefault(p, TreeNode(p)) child = valToNode.setdefault(c, TreeNode(c)) if isLeft: parent.left = child else: parent.right = child children.add(c) root = (set(valToNode) - set(children)).pop() return valToNode[root]
Solution
python
bokeh__bokeh
src/bokeh/models/ui/dialogs.py
{ "start": 1651, "end": 6217 }
class ____(UIElement): """ A floating, movable and resizable container for UI elements. .. note:: This model and all its properties is experimental and may change at any point. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) title = Nullable(Either(String, Instance(DOMNode), Instance(UIElement)), help=""" The title of the dialog. This can be either a plain text string, a DOM node, a UI element or a layout. """) content = Required(Either(String, Instance(DOMNode), Instance(UIElement)), help=""" The contents of this dialog. This can be either a plain text string, a DOM node, a UI element or a layout. """) pinnable = Bool(default=True, help=""" Determines whether to allow to pin the dialog. A pinned dialog always stays on top of other dialogs. Pinning one dialog unpins any other dialogs. """) collapsible = Bool(default=True, help=""" Determines whether to allow to collapse the dialog. A collapsed dialog only shows its title, while its content is hidden from the view. This allows keep a dialog open while having a better accesses to UIs below it. .. note:: A dialog can be collapsed by scrolling on its title. """) minimizable = Bool(default=True, help=""" Determines whether to allow to minimize the dialog. Minimizing a dialog means collapsing it and moving it to a designated "minimization" area in the bottom left corner of the viewport. """) maximizable = Bool(default=True, help=""" Determines whether to allow to maximize the dialog. A maximized dialog covers the entire viewport area. Multiple dialogs can be maximized at the same time, but only one will be at the top of the viewport. """) closable = Bool(default=True, help=""" Determines whether to allow to close the dialog. Property ``close_action`` determines what happens when a dialog is closed. Note that even if dialog can't be closed through the UI, it can be closed programmatically. """) close_action = Enum("hide", "destroy", default="destroy", help=""" Determines the action when closing a dialog. Options are: * ``"hide"`` - Removes the dialog from the DOM, but keeps its view "alive", so that it can be opened another time. * ``"destroy"`` - Destroys the associated view and the state it stores. A dialog needs to be rebuilt with a fresh state before it can be opened again. """) resizable = Enum(Resizable, default="all", help=""" Determines whether or in which directions a dialog can be resized. """) movable = Enum(Movable, default="both", help=""" Determines whether or in which directions a dialog can be moved. """) symmetric = Bool(default=False, help=""" Determines if resizing one edge or corner affects the opposite one. """) top_limit = Nullable(Instance(Node), default=None, help=""" Optional top movement or resize limit. Together with ``bottom_limit``, ``left_limit`` and ``right_limit`` it forms a bounding box for movement and resizing of this dialog. """) bottom_limit = Nullable(Instance(Node), default=None, help=""" Optional bottom movement or resize limit. Together with ``top_limit``, ``left_limit`` and ``right_limit`` it forms a bounding box for movement and resizing of this dialog. """) left_limit = Nullable(Instance(Node), default=None, help=""" Optional left movement or resize limit. Together with ``top_limit``, ``bottom_limit`` and ``right_limit`` it forms a bounding box for movement and resizing of this dialog. """) right_limit = Nullable(Instance(Node), default=None, help=""" Optional right movement or resize limit. Together with ``top_limit``, ``bottom_limit`` and ``left_limit`` it forms a bounding box for movement and resizing of this dialog. """) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
Dialog
python
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 12290, "end": 12914 }
class ____(serializers.ModelSerializer): """ Used when modifying (update action) a ``Version``. It allows to change the version states and privacy level only. """ class Meta: model = Version fields = [ "active", "hidden", "privacy_level", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # If privacy levels are not allowed, # everything is public, we don't allow changing it. if not settings.ALLOW_PRIVATE_REPOS: self.fields.pop("privacy_level")
VersionUpdateSerializer
python
walkccc__LeetCode
solutions/3385. Minimum Time to Break Locks II/3385.py
{ "start": 0, "end": 2387 }
class ____: def findMinimumTime(self, strength: list[int]) -> int: costs = [[(s + turn - 1) // turn for s in strength] for turn in range(1, len(strength) + 1)] return self._hungarian(costs)[-1] def _hungarian(self, costs): """ Returns an array `res` of length n (costs.length), with `res[i]` equaling the minimum cost to assign the first (i + 1) turns to the first (i + 1) locks using Hungarian algorithm, where costs[i][j] is the energy required to break j-th lock in i-th turn. https://en.wikipedia.org/wiki/Hungarian_algorithm """ numLocks = len(costs) turnPotentials = [0] * numLocks lockPotentials = [0] * (numLocks + 1) lockAssignments = [-1] * (numLocks + 1) res = [] for currentTurn in range(numLocks): currentLock = numLocks lockAssignments[currentLock] = currentTurn minReducedCosts = [math.inf] * (numLocks + 1) previousLockAssignments = [-1] * (numLocks + 1) locksInOptimalPath = [False] * (numLocks + 1) while lockAssignments[currentLock] != -1: locksInOptimalPath[currentLock] = True assignedTurn = lockAssignments[currentLock] minCostDelta = math.inf nextLock = None for lock in range(numLocks): if not locksInOptimalPath[lock]: reducedCost = ( costs[assignedTurn][lock] - turnPotentials[assignedTurn] - lockPotentials[lock] ) oldMin = minReducedCosts[lock] minReducedCosts[lock] = min(oldMin, reducedCost) if minReducedCosts[lock] < oldMin: previousLockAssignments[lock] = currentLock if minReducedCosts[lock] < minCostDelta: minCostDelta = minReducedCosts[lock] nextLock = lock for lock in range(numLocks + 1): if locksInOptimalPath[lock]: turnPotentials[lockAssignments[lock]] += minCostDelta lockPotentials[lock] -= minCostDelta else: minReducedCosts[lock] -= minCostDelta currentLock = nextLock while currentLock != numLocks: lockAssignments[currentLock] = lockAssignments[previousLockAssignments[currentLock]] currentLock = previousLockAssignments[currentLock] res.append(-lockPotentials[numLocks]) return res
Solution
python
numba__numba
numba/tests/test_entrypoints.py
{ "start": 509, "end": 8152 }
class ____(TestCase): """ Test registration of init() functions from Numba extensions """ def test_init_entrypoint(self): # loosely based on Pandas test from: # https://github.com/pandas-dev/pandas/pull/27488 mod = mock.Mock(__name__='_test_numba_extension') try: # will remove this module at the end of the test sys.modules[mod.__name__] = mod my_entrypoint = importlib_metadata.EntryPoint( 'init', '_test_numba_extension:init_func', 'numba_extensions', ) with mock.patch.object( importlib_metadata, 'entry_points', return_value={'numba_extensions': (my_entrypoint,)}, ): from numba.core import entrypoints # Allow reinitialization entrypoints._already_initialized = False entrypoints.init_all() # was our init function called? mod.init_func.assert_called_once() # ensure we do not initialize twice entrypoints.init_all() mod.init_func.assert_called_once() finally: # remove fake module if mod.__name__ in sys.modules: del sys.modules[mod.__name__] def test_entrypoint_tolerance(self): # loosely based on Pandas test from: # https://github.com/pandas-dev/pandas/pull/27488 mod = mock.Mock(__name__='_test_numba_bad_extension') mod.configure_mock(**{'init_func.side_effect': ValueError('broken')}) try: # will remove this module at the end of the test sys.modules[mod.__name__] = mod my_entrypoint = importlib_metadata.EntryPoint( 'init', '_test_numba_bad_extension:init_func', 'numba_extensions', ) with mock.patch.object( importlib_metadata, 'entry_points', return_value={'numba_extensions': (my_entrypoint,)}, ): from numba.core import entrypoints # Allow reinitialization entrypoints._already_initialized = False with warnings.catch_warnings(record=True) as w: entrypoints.init_all() bad_str = "Numba extension module '_test_numba_bad_extension'" for x in w: if bad_str in str(x): break else: raise ValueError("Expected warning message not found") # was our init function called? mod.init_func.assert_called_once() finally: # remove fake module if mod.__name__ in sys.modules: del sys.modules[mod.__name__] _EP_MAGIC_TOKEN = 'RUN_ENTRY' @unittest.skipIf(os.environ.get('_EP_MAGIC_TOKEN', None) != _EP_MAGIC_TOKEN, "needs token") def test_entrypoint_handles_type_extensions(self): # loosely based on Pandas test from: # https://github.com/pandas-dev/pandas/pull/27488 import numba def init_function(): # This init function would normally just call a module init via # import or similar, for the sake of testing, inline registration # of how to handle the global "_DummyClass". class DummyType(numba.types.Type): def __init__(self): super(DummyType, self).__init__(name='DummyType') @numba.extending.typeof_impl.register(_DummyClass) def typer_DummyClass(val, c): return DummyType() @numba.extending.register_model(DummyType) class DummyModel(numba.extending.models.StructModel): def __init__(self, dmm, fe_type): members = [ ('value', numba.types.float64), ] super(DummyModel, self).__init__(dmm, fe_type, members) @numba.extending.unbox(DummyType) def unbox_dummy(typ, obj, c): value_obj = c.pyapi.object_getattr_string(obj, "value") dummy_struct_proxy = numba.core.cgutils.create_struct_proxy(typ) dummy_struct = dummy_struct_proxy(c.context, c.builder) dummy_struct.value = c.pyapi.float_as_double(value_obj) c.pyapi.decref(value_obj) err_flag = c.pyapi.err_occurred() is_error = numba.core.cgutils.is_not_null(c.builder, err_flag) return numba.extending.NativeValue(dummy_struct._getvalue(), is_error=is_error) @numba.extending.box(DummyType) def box_dummy(typ, val, c): dummy_struct_proxy = numba.core.cgutils.create_struct_proxy(typ) dummy_struct = dummy_struct_proxy(c.context, c.builder) value_obj = c.pyapi.float_from_double(dummy_struct.value) serialized_clazz = c.pyapi.serialize_object(_DummyClass) class_obj = c.pyapi.unserialize(serialized_clazz) res = c.pyapi.call_function_objargs(class_obj, (value_obj,)) c.pyapi.decref(value_obj) c.pyapi.decref(class_obj) return res mod = types.ModuleType("_test_numba_init_sequence") mod.init_func = init_function try: # will remove this module at the end of the test sys.modules[mod.__name__] = mod my_entrypoint = importlib_metadata.EntryPoint( 'init', '_test_numba_init_sequence:init_func', 'numba_extensions', ) with mock.patch.object( importlib_metadata, 'entry_points', return_value={'numba_extensions': (my_entrypoint,)}, ): @njit def foo(x): return x ival = _DummyClass(10) foo(ival) finally: # remove fake module if mod.__name__ in sys.modules: del sys.modules[mod.__name__] def run_cmd(self, cmdline, env): popen = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) # finish in _TEST_TIMEOUT seconds or kill it timeout = threading.Timer(_TEST_TIMEOUT, popen.kill) try: timeout.start() out, err = popen.communicate() if popen.returncode != 0: raise AssertionError( "process failed with code %s: stderr follows\n%s\n" % (popen.returncode, err.decode())) return out.decode(), err.decode() finally: timeout.cancel() return None, None def test_entrypoint_extension_sequence(self): env_copy = os.environ.copy() env_copy['_EP_MAGIC_TOKEN'] = str(self._EP_MAGIC_TOKEN) themod = self.__module__ thecls = type(self).__name__ methname = 'test_entrypoint_handles_type_extensions' injected_method = '%s.%s.%s' % (themod, thecls, methname) cmdline = [sys.executable, "-m", "numba.runtests", injected_method] out, err = self.run_cmd(cmdline, env_copy) _DEBUG = False if _DEBUG: print(out, err)
TestEntrypoints
python
doocs__leetcode
solution/1600-1699/1692.Count Ways to Distribute Candies/Solution.py
{ "start": 0, "end": 328 }
class ____: def waysToDistribute(self, n: int, k: int) -> int: mod = 10**9 + 7 f = [[0] * (k + 1) for _ in range(n + 1)] f[0][0] = 1 for i in range(1, n + 1): for j in range(1, k + 1): f[i][j] = (f[i - 1][j] * j + f[i - 1][j - 1]) % mod return f[n][k]
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 962053, "end": 962809 }
class ____(sgqlc.types.relay.Connection): """The connection type for SecurityAdvisory.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("SecurityAdvisoryEdge"), graphql_name="edges") """A list of edges.""" nodes = sgqlc.types.Field(sgqlc.types.list_of("SecurityAdvisory"), graphql_name="nodes") """A list of nodes.""" page_info = sgqlc.types.Field(sgqlc.types.non_null(PageInfo), graphql_name="pageInfo") """Information to aid in pagination.""" total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount") """Identifies the total count of items in the connection."""
SecurityAdvisoryConnection
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/kubernetes_engine.py
{ "start": 38037, "end": 41669 }
class ____(GKEOperatorMixin, GoogleCloudBaseOperator): """ Retrieve list of Jobs. If namespace parameter is specified, the list of Jobs from dedicated namespace will be retrieved. If no namespace specified, it will output Jobs from all namespaces. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:GKEListJobsOperator` :param location: The name of the Google Kubernetes Engine zone or region in which the cluster resides, e.g. 'us-central1-a' :param cluster_name: The name of the Google Kubernetes Engine cluster. :param use_internal_ip: Use the internal IP address as the endpoint. :param use_dns_endpoint: Use the DNS address as the endpoint. :param project_id: The Google Developers Console project id :param gcp_conn_id: The Google cloud connection id to use. This allows for users to specify a service account. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param namespace: The name of the Google Kubernetes Engine namespace. :param do_xcom_push: If set to True the result list of Jobs will be pushed to the task result. """ template_fields: Sequence[str] = tuple({"namespace"} | set(GKEOperatorMixin.template_fields)) operator_extra_links = (KubernetesEngineWorkloadsLink(),) def __init__( self, location: str, cluster_name: str, use_internal_ip: bool = False, use_dns_endpoint: bool = False, project_id: str = PROVIDE_PROJECT_ID, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, namespace: str | None = None, do_xcom_push: bool = True, *args, **kwargs, ) -> None: super().__init__(*args, **kwargs) self.project_id = project_id self.location = location self.cluster_name = cluster_name self.gcp_conn_id = gcp_conn_id self.use_internal_ip = use_internal_ip self.use_dns_endpoint = use_dns_endpoint self.impersonation_chain = impersonation_chain self.namespace = namespace self.do_xcom_push = do_xcom_push @property def extra_links_params(self) -> dict[str, Any]: return { "location": self.location, "cluster_name": self.cluster_name, "namespace": self.namespace, "project_id": self.project_id, } def execute(self, context: Context) -> dict: if self.namespace: jobs = self.hook.list_jobs_from_namespace(namespace=self.namespace) else: jobs = self.hook.list_jobs_all_namespaces() for job in jobs.items: self.log.info("Retrieved description of Job:\n %s", job) if self.do_xcom_push: ti = context["ti"] ti.xcom_push(key="jobs_list", value=V1JobList.to_dict(jobs)) KubernetesEngineWorkloadsLink.persist(context=context) return V1JobList.to_dict(jobs)
GKEListJobsOperator
python
gawel__pyquery
tests/browser_base.py
{ "start": 0, "end": 3042 }
class ____(): def _prepare_dom(self, html): self.last_html = '<html><body>' + html + '</body></html>' def _simple_test(self, html, expected_sq, expected_nosq, **kwargs): raise NotImplementedError def test_inline_tags(self): self._simple_test( 'Phas<em>ell</em>us<i> eget </i>sem <b>facilisis</b> justo', 'Phasellus eget sem facilisis justo', 'Phasellus eget sem facilisis justo', ) self._simple_test( 'Phasellus <span> eget </span> sem <b>facilisis\n</b> justo', 'Phasellus eget sem facilisis justo', 'Phasellus eget sem facilisis\n justo', ) self._simple_test( ('Phasellus <span>\n eget\n ' 'sem\n\tfacilisis</span> justo'), 'Phasellus eget sem facilisis justo', 'Phasellus \n eget\n sem\n\tfacilisis justo' ) def test_block_tags(self): self._simple_test( 'Phas<p>ell</p>us<div> eget </div>sem <h1>facilisis</h1> justo', 'Phas\nell\nus\neget\nsem\nfacilisis\njusto', 'Phas\nell\nus\n eget \nsem \nfacilisis\n justo', ) self._simple_test( '<p>In sagittis</p> <p>rutrum</p><p>condimentum</p>', 'In sagittis\nrutrum\ncondimentum', 'In sagittis\n \nrutrum\n\ncondimentum', ) self._simple_test( 'In <p>\nultricies</p>\n erat et <p>\n\n\nmaximus\n\n</p> mollis', 'In\nultricies\nerat et\nmaximus\nmollis', 'In \n\nultricies\n\n erat et \n\n\n\nmaximus\n\n\n mollis', ) self._simple_test( ('Integer <div><div>\n <div>quis commodo</div></div> ' '</div> libero'), 'Integer\nquis commodo\nlibero', 'Integer \n\n\n \nquis commodo\n\n \n libero', ) self._simple_test( 'Heading<ul><li>one</li><li>two</li><li>three</li></ul>', 'Heading\none\ntwo\nthree', 'Heading\n\none\n\ntwo\n\nthree', ) def test_separators(self): self._simple_test( 'Some words<br>test. Another word<br><br> <br> test.', 'Some words\ntest. Another word\n\n\ntest.', 'Some words\ntest. Another word\n\n \n test.', ) self._simple_test( 'Inline <span> split by\nbr<br>tag</span> test', 'Inline split by br\ntag test', 'Inline split by\nbr\ntag test', ) self._simple_test( 'Some words<hr>test. Another word<hr><hr> <hr> test.', 'Some words\ntest. Another word\ntest.', 'Some words\n\ntest. Another word\n\n\n\n \n\n test.', ) def test_strip(self): self._simple_test( ' text\n', 'text', ' text\n', ) def test_ul_li(self): self._simple_test( '<ul> <li> </li> </ul>', '', ' \n \n ' )
TextExtractionMixin
python
pypa__warehouse
warehouse/manage/views/__init__.py
{ "start": 8807, "end": 17436 }
class ____(ManageAccountMixin): @property def active_projects(self): return user_projects(request=self.request)["projects_sole_owned"] @property def default_response(self): return { "save_account_form": SaveAccountForm( name=self.request.user.name, public_email=getattr(self.request.user.public_email, "email", ""), user_service=self.user_service, user_id=self.request.user.id, ), "add_email_form": AddEmailForm( request=self.request, user_service=self.user_service, user_id=self.request.user.id, ), "change_password_form": ChangePasswordForm( request=self.request, user_service=self.user_service, breach_service=self.breach_service, ), "active_projects": self.active_projects, } @view_config(request_method="GET") def manage_account(self): return self.default_response @view_config(request_method="POST", request_param=["name"]) def save_account(self): form = SaveAccountForm( self.request.POST, user_service=self.user_service, user_id=self.request.user.id, ) if form.validate(): data = form.data public_email = data.pop("public_email", "") self.user_service.update_user(self.request.user.id, **data) for email in self.request.user.emails: email.public = email.email == public_email self.request.session.flash( self.request._("Account details updated"), queue="success" ) return HTTPSeeOther(self.request.path) return {**self.default_response, "save_account_form": form} @view_config( request_method="POST", request_param=AddEmailForm.__params__, require_reauth=True, ) def add_email(self): form = AddEmailForm( self.request.POST, request=self.request, user_service=self.user_service, user_id=self.request.user.id, ) if form.validate(): email = self.user_service.add_email(self.request.user.id, form.email.data) self.request.user.record_event( tag=EventTag.Account.EmailAdd, request=self.request, additional={"email": email.email}, ) send_email_verification_email(self.request, (self.request.user, email)) self.request.session.flash( self.request._( "Email ${email_address} added - check your email for " "a verification link", mapping={"email_address": email.email}, ), queue="success", ) for previously_registered_email in self.request.user.emails: if previously_registered_email != email: send_new_email_added_email( self.request, (self.request.user, previously_registered_email), new_email_address=email.email, ) return HTTPSeeOther(self.request.path) return {**self.default_response, "add_email_form": form} @view_config( request_method="POST", request_param=["delete_email_id"], require_reauth=True ) def delete_email(self): try: email = ( self.request.db.query(Email) .filter( Email.id == int(self.request.POST["delete_email_id"]), Email.user_id == self.request.user.id, ) .one() ) except NoResultFound: self.request.session.flash("Email address not found", queue="error") return self.default_response if email.primary: self.request.session.flash( "Cannot remove primary email address", queue="error" ) else: self.request.user.emails.remove(email) self.request.user.record_event( tag=EventTag.Account.EmailRemove, request=self.request, additional={"email": email.email}, ) self.request.session.flash( f"Email address {email.email} removed", queue="success" ) return HTTPSeeOther(self.request.path) return self.default_response @view_config(request_method="POST", request_param=ChangePasswordForm.__params__) def change_password(self): form = ChangePasswordForm( self.request.POST, request=self.request, username=self.request.user.username, full_name=self.request.user.name, email=self.request.user.email, user_service=self.user_service, breach_service=self.breach_service, check_password_metrics_tags=["method:new_password"], ) if form.validate(): self.user_service.update_user( self.request.user.id, password=form.new_password.data ) self.request.user.record_event( tag=EventTag.Account.PasswordChange, request=self.request, ) send_password_change_email(self.request, self.request.user) self.request.db.flush() # ensure password_date is available self.request.db.refresh(self.request.user) # Pickup new password_date self.request.session.record_password_timestamp( self.user_service.get_password_timestamp(self.request.user.id) ) self.request.session.flash("Password updated", queue="success") return HTTPSeeOther(self.request.path) return {**self.default_response, "change_password_form": form} @view_config( request_method="POST", request_param=DeleteTOTPForm.__params__ ) # TODO: gate_action instead of confirm pass form def delete_account(self): confirm_password = self.request.params.get("confirm_password") if not confirm_password: self.request.session.flash("Confirm the request", queue="error") return self.default_response form = ConfirmPasswordForm( formdata=MultiDict( { "password": confirm_password, "username": self.request.user.username, } ), request=self.request, user_service=self.user_service, ) if not form.validate(): self.request.session.flash( "Could not delete account - Invalid credentials. Please try again.", queue="error", ) return self.default_response if self.active_projects: self.request.session.flash( "Cannot delete account with active project ownerships", queue="error" ) return self.default_response # Update all journals to point to `deleted-user` instead deleted_user = ( self.request.db.query(User).filter(User.username == "deleted-user").one() ) # Update in bulk to avoid loading all journal entries into memory (n+1) self.request.db.execute( update(JournalEntry) .where(JournalEntry._submitted_by == self.request.user.username) .values(_submitted_by=deleted_user.username) .execution_options(synchronize_session=False) ) # Send a notification email send_account_deletion_email(self.request, self.request.user) # Actually delete the user self.request.db.delete(self.request.user) return logout(self.request) @view_config( route_name="manage.account.two-factor", renderer="warehouse:templates/manage/account/two-factor.html", uses_session=True, require_csrf=True, require_methods=False, permission=Permissions.Account2FA, has_translations=True, require_reauth=True, ) def manage_two_factor(request): return {} @view_defaults( route_name="manage.account.totp-provision", renderer="warehouse:templates/manage/account/totp-provision.html", uses_session=True, require_csrf=True, require_methods=False, permission=Permissions.Account2FA, http_cache=0, has_translations=True, )
ManageVerifiedAccountViews
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_autofilter00.py
{ "start": 315, "end": 1710 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("autofilter00.xlsx") self.set_text_file("autofilter_data.txt") def test_create_file(self): """ Test the creation of a simple XlsxWriter file with an autofilter. This test is the base comparison. It has data but no autofilter. """ workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() # Open a text file with autofilter example data. textfile = open(self.txt_filename) # Start writing data from the first worksheet row. row = 0 # Read the text file and write it to the worksheet. for line in textfile: # Split the input data based on whitespace. data = line.strip("\n").split() # Convert the number data from the text file. for i, item in enumerate(data): try: data[i] = float(item) except ValueError: pass for col in range(len(data)): worksheet.write(row, col, data[col]) # Move on to the next worksheet row. row += 1 textfile.close() workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
django-compressor__django-compressor
compressor/tests/test_offline.py
{ "start": 20929, "end": 21410 }
class ____( SuperMixin, OfflineTestCaseMixin, TestCase ): templates_dir = "test_with_context_variable_inheritance_super" additional_test_settings = { "COMPRESS_OFFLINE_CONTEXT": [ { "parent_template": "base1.html", }, { "parent_template": "base2.html", }, ] } expected_hash = ["cee48db7cedc", "c877c436363a"]
OfflineCompressTestCaseWithContextVariableInheritanceSuper
python
django__django
tests/model_formsets/models.py
{ "start": 696, "end": 993 }
class ____(models.Model): my_pk = models.DecimalField(max_digits=5, decimal_places=0, primary_key=True) author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100) def __str__(self): return "%s: %s" % (self.my_pk, self.title)
BookWithCustomPK
python
mwaskom__seaborn
seaborn/external/docscrape.py
{ "start": 3847, "end": 18365 }
class ____(Mapping): """Parses a numpydoc string to an abstract representation Instances define a mapping from section title to structured data. """ sections = { 'Signature': '', 'Summary': [''], 'Extended Summary': [], 'Parameters': [], 'Returns': [], 'Yields': [], 'Receives': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], 'Attributes': [], 'Methods': [], 'See Also': [], 'Notes': [], 'Warnings': [], 'References': '', 'Examples': '', 'index': {} } def __init__(self, docstring, config={}): orig_docstring = docstring docstring = textwrap.dedent(docstring).split('\n') self._doc = Reader(docstring) self._parsed_data = copy.deepcopy(self.sections) try: self._parse() except ParseError as e: e.docstring = orig_docstring raise def __getitem__(self, key): return self._parsed_data[key] def __setitem__(self, key, val): if key not in self._parsed_data: self._error_location(f"Unknown section {key}", error=False) else: self._parsed_data[key] = val def __iter__(self): return iter(self._parsed_data) def __len__(self): return len(self._parsed_data) def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith('.. index::'): return True l2 = self._doc.peek(1).strip() # ---------- or ========== return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1)) def _strip(self, doc): i = 0 j = 0 for i, line in enumerate(doc): if line.strip(): break for j, line in enumerate(doc[::-1]): if line.strip(): break return doc[i:len(doc)-j] def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [''] section += self._doc.read_to_next_empty_line() return section def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith('..'): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:]) def _parse_param_list(self, content, single_element_is_type=False): r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if ' : ' in header: arg_name, arg_type = header.split(' : ')[:2] else: if single_element_is_type: arg_name, arg_type = '', header else: arg_name, arg_type = header, '' desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) desc = strip_blank_lines(desc) params.append(Parameter(arg_name, arg_type, desc)) return params # See also supports the following formats. # # <FUNCNAME> # <FUNCNAME> SPACE* COLON SPACE+ <DESC> SPACE* # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)+ (COMMA | PERIOD)? SPACE* # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* COLON SPACE+ <DESC> SPACE* # <FUNCNAME> is one of # <PLAIN_FUNCNAME> # COLON <ROLE> COLON BACKTICK <PLAIN_FUNCNAME> BACKTICK # where # <PLAIN_FUNCNAME> is a legal function name, and # <ROLE> is any nonempty sequence of word characters. # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j` # <DESC> is a string describing the function. _role = r":(?P<role>\w+):" _funcbacktick = r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`" _funcplain = r"(?P<name2>[a-zA-Z0-9_\.-]+)" _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")" _funcnamenext = _funcname.replace('role', 'rolenext') _funcnamenext = _funcnamenext.replace('name', 'namenext') _description = r"(?P<description>\s*:(\s+(?P<desc>\S+.*))?)?\s*$" _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*") _line_rgx = re.compile( r"^\s*" + r"(?P<allfuncs>" + # group for all function names _funcname + r"(?P<morefuncs>([,]\s+" + _funcnamenext + r")*)" + r")" + # end of "allfuncs" r"(?P<trailing>[,\.])?" + # Some function lists have a trailing comma (or period) '\s*' _description) # Empty <DESC> elements are replaced with '..' empty_description = '..' def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'.""" m = self._func_rgx.match(text) if not m: raise ParseError(f"{text} is not a item name") role = m.group('role') name = m.group('name') if role else m.group('name2') return name, role, m.end() rest = [] for line in content: if not line.strip(): continue line_match = self._line_rgx.match(line) description = None if line_match: description = line_match.group('desc') if line_match.group('trailing') and description: self._error_location( 'Unexpected comma or period after function list at index %d of ' 'line "%s"' % (line_match.end('trailing'), line), error=False) if not description and line.startswith(' '): rest.append(line.strip()) elif line_match: funcs = [] text = line_match.group('allfuncs') while True: if not text.strip(): break name, role, match_end = parse_item_name(text) funcs.append((name, role)) text = text[match_end:].strip() if text and text[0] == ',': text = text[1:].strip() rest = list(filter(None, [description])) items.append((funcs, rest)) else: raise ParseError(f"{line} is not a item name") return items def _parse_index(self, section, content): """ .. index: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if len(section) > 1: out['default'] = strip_each_in(section[1].split(','))[0] for line in content: line = line.split(':') if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(',')) return out def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return # If several signatures present, take the last one while True: summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() compiled = re.compile(r'^([\w., ]+=)?\s*[\w\.]+\(.*\)$') if compiled.match(summary_str): self['Signature'] = summary_str if not self._is_at_section(): continue break if summary is not None: self['Summary'] = summary if not self._is_at_section(): self['Extended Summary'] = self._read_to_next_section() def _parse(self): self._doc.reset() self._parse_summary() sections = list(self._read_sections()) section_names = {section for section, content in sections} has_returns = 'Returns' in section_names has_yields = 'Yields' in section_names # We could do more tests, but we are not. Arbitrarily. if has_returns and has_yields: msg = 'Docstring contains both a Returns and Yields section.' raise ValueError(msg) if not has_yields and 'Receives' in section_names: msg = 'Docstring contains a Receives section but not Yields.' raise ValueError(msg) for (section, content) in sections: if not section.startswith('..'): section = (s.capitalize() for s in section.split(' ')) section = ' '.join(section) if self.get(section): self._error_location(f"The section {section} appears twice") if section in ('Parameters', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) elif section in ('Returns', 'Yields', 'Raises', 'Warns', 'Receives'): self[section] = self._parse_param_list( content, single_element_is_type=True) elif section.startswith('.. index::'): self['index'] = self._parse_index(section, content) elif section == 'See Also': self['See Also'] = self._parse_see_also(content) else: self[section] = content def _error_location(self, msg, error=True): if hasattr(self, '_obj'): # we know where the docs came from: try: filename = inspect.getsourcefile(self._obj) except TypeError: filename = None msg = msg + f" in the docstring of {self._obj} in {filename}." if error: raise ValueError(msg) else: warn(msg) # string conversion routines def _str_header(self, name, symbol='-'): return [name, len(name)*symbol] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): if self['Signature']: return [self['Signature'].replace('*', r'\*')] + [''] else: return [''] def _str_summary(self): if self['Summary']: return self['Summary'] + [''] else: return [] def _str_extended_summary(self): if self['Extended Summary']: return self['Extended Summary'] + [''] else: return [] def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param in self[name]: parts = [] if param.name: parts.append(param.name) if param.type: parts.append(param.type) out += [' : '.join(parts)] if param.desc and ''.join(param.desc).strip(): out += self._str_indent(param.desc) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [''] return out def _str_see_also(self, func_role): if not self['See Also']: return [] out = [] out += self._str_header("See Also") out += [''] last_had_desc = True for funcs, desc in self['See Also']: assert isinstance(funcs, list) links = [] for func, role in funcs: if role: link = f':{role}:`{func}`' elif func_role: link = f':{func_role}:`{func}`' else: link = f"`{func}`_" links.append(link) link = ', '.join(links) out += [link] if desc: out += self._str_indent([' '.join(desc)]) last_had_desc = True else: last_had_desc = False out += self._str_indent([self.empty_description]) if last_had_desc: out += [''] out += [''] return out def _str_index(self): idx = self['index'] out = [] output_index = False default_index = idx.get('default', '') if default_index: output_index = True out += [f'.. index:: {default_index}'] for section, references in idx.items(): if section == 'default': continue output_index = True out += [f" :{section}: {', '.join(references)}"] if output_index: return out else: return '' def __str__(self, func_role=''): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Returns', 'Yields', 'Receives', 'Other Parameters', 'Raises', 'Warns'): out += self._str_param_list(param_list) out += self._str_section('Warnings') out += self._str_see_also(func_role) for s in ('Notes', 'References', 'Examples'): out += self._str_section(s) for param_list in ('Attributes', 'Methods'): out += self._str_param_list(param_list) out += self._str_index() return '\n'.join(out) def indent(str, indent=4): indent_str = ' '*indent if str is None: return indent_str lines = str.split('\n') return '\n'.join(indent_str + l for l in lines) def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n") def header(text, style='-'): return text + '\n' + style*len(text) + '\n'
NumpyDocString
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/dynamodb.py
{ "start": 1234, "end": 5490 }
class ____(AwsBaseSensor[DynamoDBHook]): """ Waits for an attribute value to be present for an item in a DynamoDB table. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:DynamoDBValueSensor` :param table_name: DynamoDB table name :param partition_key_name: DynamoDB partition key name :param partition_key_value: DynamoDB partition key value :param attribute_name: DynamoDB attribute name :param attribute_value: DynamoDB attribute value :param sort_key_name: (optional) DynamoDB sort key name :param sort_key_value: (optional) DynamoDB sort key value :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether or not to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html :param botocore_config: Configuration dictionary (key-values) for botocore client. See: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html """ aws_hook_class = DynamoDBHook template_fields: Sequence[str] = aws_template_fields( "table_name", "partition_key_name", "partition_key_value", "attribute_name", "attribute_value", "sort_key_name", "sort_key_value", ) def __init__( self, table_name: str, partition_key_name: str, partition_key_value: str, attribute_name: str, attribute_value: str | Iterable[str], sort_key_name: str | None = None, sort_key_value: str | None = None, **kwargs: Any, ): super().__init__(**kwargs) self.table_name = table_name self.partition_key_name = partition_key_name self.partition_key_value = partition_key_value self.attribute_name = attribute_name self.attribute_value = attribute_value self.sort_key_name = sort_key_name self.sort_key_value = sort_key_value def poke(self, context: Context) -> bool: """Test DynamoDB item for matching attribute value.""" key = {self.partition_key_name: self.partition_key_value} msg = ( f"Checking table {self.table_name} for " f"item Partition Key: {self.partition_key_name}={self.partition_key_value}" ) if self.sort_key_name and self.sort_key_value: key = {self.partition_key_name: self.partition_key_value, self.sort_key_name: self.sort_key_value} msg += f"\nSort Key: {self.sort_key_name}={self.sort_key_value}" msg += f"\nattribute: {self.attribute_name}={self.attribute_value}" self.log.info(msg) table = self.hook.conn.Table(self.table_name) self.log.info("Table: %s", table) self.log.info("Key: %s", key) try: response = table.get_item(Key=key) except ClientError as err: self.log.error( "Couldn't get %s from table %s.\nError Code: %s\nError Message: %s", key, self.table_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) return False else: try: item_attribute_value = response["Item"][self.attribute_name] self.log.info("Response: %s", response) self.log.info("Want: %s = %s", self.attribute_name, self.attribute_value) self.log.info("Got: {response['Item'][self.attribute_name]} = %s", item_attribute_value) return item_attribute_value in ( [self.attribute_value] if isinstance(self.attribute_value, str) else self.attribute_value ) except KeyError: return False
DynamoDBValueSensor
python
getsentry__sentry
tests/sentry/utils/test_snuba.py
{ "start": 19752, "end": 20635 }
class ____(HTTPConnectionPool): def __init__(self, connection, **kwargs): self.connection = connection super().__init__(**kwargs) def _new_conn(self): return self.connection def test_retries() -> None: """ Tests that, even if I set up 5 retries, there is only one request made since it times out. """ connection_mock = mock.Mock() snuba_pool = FakeConnectionPool( connection=connection_mock, host="www.test.com", port=80, retries=RetrySkipTimeout(total=5, allowed_methods={"GET", "POST"}), timeout=30, maxsize=10, ) connection_mock.request.side_effect = ReadTimeoutError(snuba_pool, "test.com", "Timeout") with pytest.raises(HTTPError): snuba_pool.urlopen("POST", "/query", body="{}") assert connection_mock.request.call_count == 1
FakeConnectionPool
python
google__pytype
pytype/tools/merge_pyi/merge_pyi.py
{ "start": 2220, "end": 3886 }
class ____(cst.CSTTransformer): """Strips out trivial type of basic-types on variable assignments.""" def _is_trivial_type(self, annotation: expression.Annotation) -> bool: return annotation.annotation is not None and ( ( isinstance(annotation.annotation, expression.Name) and annotation.annotation.value in ("int", "str", "float", "bool", "complex") ) or # pytype infers enum members to be literal types, the type # annotation in that position is undesirable. ( isinstance(annotation.annotation, expression.Subscript) and isinstance(annotation.annotation.value, expression.Name) and annotation.annotation.value.value == "Literal" ) ) def leave_AnnAssign( self, original_node: cst.AnnAssign, updated_node: cst.AnnAssign ) -> cst.AnnAssign | cst.RemovalSentinel: if ( self._is_trivial_type(original_node.annotation) and updated_node.value is None ): # We need to remove the statement, because otherwise it will be an # invalid syntax in python . e.g. `a: str` --> `a`. return cst.RemovalSentinel.REMOVE return original_node def merge_sources(*, py: str, pyi: str) -> str: try: py_cst = cst.parse_module(py) pyi_cst = ( cst.parse_module(pyi) .visit(RemoveAnyNeverTransformer()) .visit(RemoveTrivialTypesTransformer()) ) merged_cst = _merge_csts(py_tree=py_cst, pyi_tree=pyi_cst) return merged_cst.code except Exception as e: # pylint: disable=broad-except raise MergeError(str(e)) from e
RemoveTrivialTypesTransformer
python
django-crispy-forms__django-crispy-forms
crispy_forms/layout.py
{ "start": 25512, "end": 27145 }
class ____(Div): """ Layout object. It wraps fields in a ``<div>`` and the template adds the appropriate class to render the contents in a row. e.g. ``form-row`` when using the Bootstrap4 template pack. Attributes ---------- template : str The default template which this Layout Object will be rendered with. css_class : str, optional CSS classes to be applied to the ``<div>``. By default None. Parameters ---------- *fields : str, LayoutObject Any number of fields as positional arguments to be rendered within the ``<div>``. css_id : str, optional A DOM id for the layout object which will be added to the ``<div>`` if provided. By default None. css_class : str, optional Additional CSS classes to be applied in addition to those declared by the class itself. By default None. template : str, optional Overrides the default template, if provided. By default None. **kwargs : dict, optional Additional attributes are passed to ``flatatt`` and converted into key="value", pairs. These attributes are added to the ``<div>``. Examples -------- In your ``Layout`` you can:: Row('form_field_1', 'form_field_2', css_id='row-example') It is also possible to nest Layout Objects within a Row:: Row( Div( Field('form_field', css_class='field-class'), css_class='div-class', ), Div('form_field_2', css_class='div-class'), ) """ template = "%s/layout/row.html"
Row
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/losses_test.py
{ "start": 10215, "end": 22784 }
class ____(test.TestCase): def testNoneWeightRaisesValueError(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[0], [1], [2]]) with self.cached_session(): with self.assertRaises(ValueError): losses.sparse_softmax_cross_entropy(labels, logits, weights=None) @test_util.run_deprecated_v1 def testAllCorrectInt32Labels(self): with self.cached_session(): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int32) loss = losses.sparse_softmax_cross_entropy(labels, logits) self.assertEqual(loss.op.name, 'sparse_softmax_cross_entropy_loss/value') self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) @test_util.assert_no_new_pyobjects_executing_eagerly() def testEagerNoMemoryLeaked(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int32) losses.sparse_softmax_cross_entropy(labels, logits) @test_util.run_deprecated_v1 def testAllCorrectInt64Labels(self): with self.cached_session(): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int64) loss = losses.sparse_softmax_cross_entropy(labels, logits) self.assertEqual(loss.op.name, 'sparse_softmax_cross_entropy_loss/value') self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) @test_util.run_deprecated_v1 def testAllCorrectNonColumnLabels(self): with self.cached_session(): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([0, 1, 2]) loss = losses.sparse_softmax_cross_entropy(labels, logits) self.assertEqual(loss.op.name, 'sparse_softmax_cross_entropy_loss/value') self.assertAlmostEqual(self.evaluate(loss), 0.0, 3) @test_util.run_deprecated_v1 def testAllWrongInt32Labels(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]], dtype=dtypes.int32) with self.cached_session(): loss = losses.sparse_softmax_cross_entropy(labels, logits) self.assertEqual(loss.op.name, 'sparse_softmax_cross_entropy_loss/value') self.assertAlmostEqual(self.evaluate(loss), 10.0, 3) @test_util.run_deprecated_v1 def testAllWrongInt64Labels(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]], dtype=dtypes.int64) with self.cached_session(): loss = losses.sparse_softmax_cross_entropy(labels, logits) self.assertEqual(loss.op.name, 'sparse_softmax_cross_entropy_loss/value') self.assertAlmostEqual(self.evaluate(loss), 10.0, 3) @test_util.run_deprecated_v1 def testAllWrongNonColumnLabels(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([2, 0, 1]) with self.cached_session(): loss = losses.sparse_softmax_cross_entropy(labels, logits) self.assertEqual(loss.op.name, 'sparse_softmax_cross_entropy_loss/value') self.assertAlmostEqual(self.evaluate(loss), 10.0, 3) @test_util.run_deprecated_v1 def testNonZeroLossWithPythonScalarWeight(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]]) weights = 2.3 with self.cached_session(): loss = losses.sparse_softmax_cross_entropy(labels, logits, weights) self.assertAlmostEqual(weights * 10.0, self.evaluate(loss), 3) @test_util.run_deprecated_v1 def testNonZeroLossWithScalarTensorWeight(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]]) weights = 2.3 with self.cached_session(): loss = losses.sparse_softmax_cross_entropy(labels, logits, constant_op.constant(weights)) self.assertAlmostEqual(weights * 10.0, self.evaluate(loss), 3) def testNonZeroLossWith1DTensorWeight(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]]) weights = 2.3 with self.cached_session(): loss = losses.sparse_softmax_cross_entropy( labels, logits, constant_op.constant((weights,))) self.assertAlmostEqual(weights * 10.0, self.evaluate(loss), 3) @test_util.run_deprecated_v1 def testNonZeroLossWithPlaceholderForWeights(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]]) weights = array_ops.placeholder(dtypes.float32) with self.cached_session() as sess: loss = losses.sparse_softmax_cross_entropy(labels, logits, weights) loss_val = sess.run(loss, feed_dict={weights: ((1.2,), (3.4,), (5.6,))}) self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss_val, 3) @test_util.run_deprecated_v1 def testUnknownShapePlaceholderForLogitsLabelsButScalarWeights(self): logits = array_ops.placeholder(dtypes.float32) labels = array_ops.placeholder(dtypes.int32) weights = 1.0 with self.cached_session() as sess: loss = losses.sparse_softmax_cross_entropy(labels, logits, weights) loss_val = sess.run(loss, feed_dict={ logits: [[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]], labels: [[2], [0], [1]], }) self.assertAlmostEqual((1.0 + 1.0 + 1.0) * 10.0 / 3.0, loss_val, 3) @test_util.run_deprecated_v1 def testNonZeroLossWithPlaceholderForLogitsLabelsAndWeights(self): logits = array_ops.placeholder(dtypes.float32, shape=(None, 3)) labels = array_ops.placeholder(dtypes.int32, shape=(None, 1)) weights = array_ops.placeholder(dtypes.float32) with self.cached_session() as sess: loss = losses.sparse_softmax_cross_entropy(labels, logits, weights) loss_val = sess.run(loss, feed_dict={ logits: [[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]], labels: [[2], [0], [1]], weights: ((1.2,), (3.4,), (5.6,)), }) self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss_val, 3) def testNonZeroLossWithOneDimBatchSpecificWeights(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]]) weights = constant_op.constant([1.2, 3.4, 5.6], shape=(3, 1)) with self.cached_session(): loss = losses.sparse_softmax_cross_entropy(labels, logits, weights) self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, self.evaluate(loss), 3) def testNonZeroLossWithColumnWeights(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]]) weights = constant_op.constant([[1.2], [3.4], [5.6]]) with self.cached_session(): loss = losses.sparse_softmax_cross_entropy(labels, logits, weights) self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, self.evaluate(loss), 3) def testAllWrongAllWeightsMissing(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]]) weights = constant_op.constant([0, 0, 0], shape=(3, 1)) with self.cached_session(): loss = losses.sparse_softmax_cross_entropy(labels, logits, weights) self.assertAlmostEqual(0.0, self.evaluate(loss), 3) def testSomeWeightsMissing(self): logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) labels = constant_op.constant([[2], [0], [1]]) weights = constant_op.constant([1.2, 0, 0], shape=(3, 1)) with self.cached_session(): loss = losses.sparse_softmax_cross_entropy(labels, logits, weights) self.assertAlmostEqual(12.0, self.evaluate(loss), 3) @test_util.run_deprecated_v1 def testMeasurementSpecificWeightsRaisesException(self): with self.cached_session(): logits = constant_op.constant([[100.0, -100.0, -100.0], [-100.0, 100.0, -100.0], [-100.0, -100.0, 100.0]]) labels = constant_op.constant([[0], [1], [2]]) weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]]) with self.assertRaises(ValueError): losses.sparse_softmax_cross_entropy( labels, logits, weights=weights).eval() def testInconsistentWeightSizeRaisesException(self): """The weight tensor has incorrect number of elements.""" with self.cached_session(): logits = constant_op.constant([[100.0, -100.0, -100.0], [-100.0, 100.0, -100.0], [-100.0, -100.0, 100.0]]) labels = constant_op.constant([[0], [1], [2]]) weights = constant_op.constant([1.2, 3.4, 5.6, 7.8]) with self.assertRaises(ValueError): losses.sparse_softmax_cross_entropy( labels, logits, weights=weights).eval() def testInconsistentLabelSizeRaisesException(self): """The label tensor has incorrect number of elements.""" with self.cached_session(): logits = constant_op.constant([[100.0, -100.0, -100.0], [-100.0, 100.0, -100.0], [-100.0, -100.0, 100.0]]) labels = constant_op.constant([[0], [1], [2], [3]]) weights = constant_op.constant([1.2, 3.4, 5.6]) with self.assertRaises(ValueError): losses.sparse_softmax_cross_entropy( labels, logits, weights=weights).eval() @test_util.run_deprecated_v1 def testInconsistentWeightShapeRaisesException(self): """The weight tensor has incorrect shape.""" with self.cached_session(): logits = constant_op.constant([[100.0, -100.0, -100.0, -100.0], [-100.0, 100.0, -100.0, -100.0], [-100.0, -100.0, 100.0, -100.0], [-100.0, -100.0, -100.0, 100.0]]) labels = constant_op.constant([[0], [1], [2], [3]]) weights = constant_op.constant([[1.2, 3.4], [5.6, 7.8]]) with self.assertRaises(ValueError): losses.sparse_softmax_cross_entropy( labels, logits, weights=weights).eval() @test_util.run_deprecated_v1 def testInconsistentLabelShapeRaisesException(self): """The label tensor has incorrect shape.""" with self.cached_session(): logits = constant_op.constant([[100.0, -100.0, -100.0, -100.0], [-100.0, 100.0, -100.0, -100.0], [-100.0, -100.0, 100.0, -100.0], [-100.0, -100.0, -100.0, 100.0]]) labels = constant_op.constant([[0, 1], [2, 3]]) weights = constant_op.constant(1.2) with self.assertRaisesRegex( ValueError, '`labels.shape.rank` must equal `logits.shape.rank - 1`'): losses.sparse_softmax_cross_entropy( labels, logits, weights=weights).eval()
SparseSoftmaxCrossEntropyLossTest
python
sympy__sympy
sympy/functions/combinatorial/numbers.py
{ "start": 36506, "end": 42496 }
class ____(DefinedFunction): r""" Euler numbers / Euler polynomials / Euler function The Euler numbers are given by: .. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j} \frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k} .. math:: E_{2n+1} = 0 Euler numbers and Euler polynomials are related by .. math:: E_n = 2^n E_n\left(\frac{1}{2}\right). We compute symbolic Euler polynomials using Appell sequences, but numerical evaluation of the Euler polynomial is computed more efficiently (and more accurately) using the mpmath library. The Euler polynomials are special cases of the generalized Euler function, related to the Genocchi function as .. math:: \operatorname{E}(s, a) = -\frac{\operatorname{G}(s+1, a)}{s+1} with the limit of `\psi\left(\frac{a+1}{2}\right) - \psi\left(\frac{a}{2}\right)` being taken when `s = -1`. The (ordinary) Euler function interpolating the Euler numbers is then obtained as `\operatorname{E}(s) = 2^s \operatorname{E}\left(s, \frac{1}{2}\right)`. * ``euler(n)`` gives the nth Euler number `E_n`. * ``euler(s)`` gives the Euler function `\operatorname{E}(s)`. * ``euler(n, x)`` gives the nth Euler polynomial `E_n(x)`. * ``euler(s, a)`` gives the generalized Euler function `\operatorname{E}(s, a)`. Examples ======== >>> from sympy import euler, Symbol, S >>> [euler(n) for n in range(10)] [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0] >>> [2**n*euler(n,1) for n in range(10)] [1, 1, 0, -2, 0, 16, 0, -272, 0, 7936] >>> n = Symbol("n") >>> euler(n + 2*n) euler(3*n) >>> x = Symbol("x") >>> euler(n, x) euler(n, x) >>> euler(0, x) 1 >>> euler(1, x) x - 1/2 >>> euler(2, x) x**2 - x >>> euler(3, x) x**3 - 3*x**2/2 + 1/4 >>> euler(4, x) x**4 - 2*x**3 + x >>> euler(12, S.Half) 2702765/4096 >>> euler(12) 2702765 See Also ======== andre, bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi, partition, tribonacci, sympy.polys.appellseqs.euler_poly References ========== .. [1] https://en.wikipedia.org/wiki/Euler_numbers .. [2] https://mathworld.wolfram.com/EulerNumber.html .. [3] https://en.wikipedia.org/wiki/Alternating_permutation .. [4] https://mathworld.wolfram.com/AlternatingPermutation.html """ @classmethod def eval(cls, n, x=None): if n.is_zero: return S.One elif n is S.NegativeOne: if x is None: return S.Pi/2 from sympy.functions.special.gamma_functions import digamma return digamma((x+1)/2) - digamma(x/2) elif n.is_integer is False or n.is_nonnegative is False: return # Euler numbers elif x is None: if n.is_odd and n.is_positive: return S.Zero elif n.is_Number: from mpmath import mp n = n._to_mpmath(mp.prec) res = mp.eulernum(n, exact=True) return Integer(res) # Euler polynomials elif n.is_Number: from sympy.core.evalf import pure_complex n = int(n) reim = pure_complex(x, or_real=True) if reim and all(a.is_Float or a.is_Integer for a in reim) \ and any(a.is_Float for a in reim): from mpmath import mp prec = min([a._prec for a in reim if a.is_Float]) with workprec(prec): res = mp.eulerpoly(n, x) return Expr._from_mpmath(res, prec) return euler_poly(n, x) def _eval_rewrite_as_Sum(self, n, x=None, **kwargs): from sympy.concrete.summations import Sum if x is None and n.is_even: k = Dummy("k", integer=True) j = Dummy("j", integer=True) n = n / 2 Em = (S.ImaginaryUnit * Sum(Sum(binomial(k, j) * (S.NegativeOne**j * (k - 2*j)**(2*n + 1)) / (2**k*S.ImaginaryUnit**k * k), (j, 0, k)), (k, 1, 2*n + 1))) return Em if x: k = Dummy("k", integer=True) return Sum(binomial(n, k)*euler(k)/2**k*(x - S.Half)**(n - k), (k, 0, n)) def _eval_rewrite_as_genocchi(self, n, x=None, **kwargs): if x is None: return Piecewise((S.Pi/2, Eq(n, -1)), (-2**n * genocchi(n+1, S.Half) / (n+1), True)) from sympy.functions.special.gamma_functions import digamma return Piecewise((digamma((x+1)/2) - digamma(x/2), Eq(n, -1)), (-genocchi(n+1, x) / (n+1), True)) def _eval_evalf(self, prec): if not all(i.is_number for i in self.args): return from mpmath import mp m, x = (self.args[0], None) if len(self.args) == 1 else self.args m = m._to_mpmath(prec) if x is not None: x = x._to_mpmath(prec) with workprec(prec): if mp.isint(m) and m >= 0: res = mp.eulernum(m) if x is None else mp.eulerpoly(m, x) else: if m == -1: res = mp.pi if x is None else mp.digamma((x+1)/2) - mp.digamma(x/2) else: y = 0.5 if x is None else x res = 2 * (mp.zeta(-m, y) - 2**(m+1) * mp.zeta(-m, (y+1)/2)) if x is None: res *= 2**m return Expr._from_mpmath(res, prec) #----------------------------------------------------------------------------# # # # Catalan numbers # # # #----------------------------------------------------------------------------#
euler
python
sympy__sympy
sympy/solvers/ode/single.py
{ "start": 35891, "end": 37868 }
class ____(SinglePatternODESolver): r""" Gives solution for the autonomous second order nonlinear differential equation of the form .. math :: f''(x) = g(f(x)) The solution for this differential equation can be computed by multiplying by `f'(x)` and integrating on both sides, converting it into a first order differential equation. Examples ======== >>> from sympy import Function, symbols, dsolve >>> f, g = symbols('f g', cls=Function) >>> x = symbols('x') >>> eq = f(x).diff(x, 2) - g(f(x)) >>> dsolve(eq, simplify=False) [Eq(Integral(1/sqrt(C1 + 2*Integral(g(_u), _u)), (_u, f(x))), C2 + x), Eq(Integral(1/sqrt(C1 + 2*Integral(g(_u), _u)), (_u, f(x))), C2 - x)] >>> from sympy import exp, log >>> eq = f(x).diff(x, 2) - exp(f(x)) + log(f(x)) >>> dsolve(eq, simplify=False) [Eq(Integral(1/sqrt(-2*_u*log(_u) + 2*_u + C1 + 2*exp(_u)), (_u, f(x))), C2 + x), Eq(Integral(1/sqrt(-2*_u*log(_u) + 2*_u + C1 + 2*exp(_u)), (_u, f(x))), C2 - x)] References ========== - https://eqworld.ipmnet.ru/en/solutions/ode/ode0301.pdf """ hint = "2nd_nonlinear_autonomous_conserved" has_integral = True order = [2] def _wilds(self, f, x, order): fy = Wild('fy', exclude=[0, f(x).diff(x), f(x).diff(x, 2)]) return (fy, ) def _equation(self, fx, x, order): fy = self.wilds()[0] return fx.diff(x, 2) + fy def _verify(self, fx): return self.ode_problem.is_autonomous def _get_general_solution(self, *, simplify_flag: bool = True): g = self.wilds_match()[0] fx = self.ode_problem.func x = self.ode_problem.sym u = Dummy('u') g = g.subs(fx, u) C1, C2 = self.ode_problem.get_numbered_constants(num=2) inside = -2*Integral(g, u) + C1 lhs = Integral(1/sqrt(inside), (u, fx)) return [Eq(lhs, C2 + x), Eq(lhs, C2 - x)]
SecondNonlinearAutonomousConserved
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 495555, "end": 496154 }
class ____(sgqlc.types.Type): """Autogenerated return type of CloneProject""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "job_status_id", "project") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" job_status_id = sgqlc.types.Field(String, graphql_name="jobStatusId") """The id of the JobStatus for populating cloned fields.""" project = sgqlc.types.Field("Project", graphql_name="project") """The new cloned project."""
CloneProjectPayload
python
huggingface__transformers
src/transformers/models/ctrl/modeling_ctrl.py
{ "start": 13653, "end": 19853 }
class ____(CTRLPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "transformer.w.weight"} def __init__(self, config): super().__init__(config) self.transformer = CTRLModel(config) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=True) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.Tensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs, ) -> Union[tuple[torch.Tensor], CausalLMOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]` Example: ```python >>> import torch >>> from transformers import AutoTokenizer, CTRLLMHeadModel >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl") >>> model = CTRLLMHeadModel.from_pretrained("Salesforce/ctrl") >>> # CTRL was trained with control codes as the first token >>> inputs = tokenizer("Wikipedia The llama is", return_tensors="pt") >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values() >>> sequence_ids = model.generate(inputs["input_ids"]) >>> sequences = tokenizer.batch_decode(sequence_ids) >>> sequences ['Wikipedia The llama is a member of the family Bovidae. It is native to the Andes of Peru,'] >>> outputs = model(**inputs, labels=inputs["input_ids"]) >>> round(outputs.loss.item(), 2) 9.21 >>> list(outputs.logits.shape) [1, 5, 246534] ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict transformer_outputs = self.transformer( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) hidden_states = transformer_outputs[0] # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function( logits, labels, vocab_size=self.config.vocab_size, **kwargs, ) if not return_dict: output = (logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) def prepare_inputs_for_generation(self, input_ids, past_key_values=None, use_cache=None, **kwargs): # Overwritten -- inputs_embeds not working properly # only last tokens for inputs_ids if past is defined in kwargs if past_key_values is not None: past_length = past_key_values.get_seq_length() # Some generation methods already pass only the last input ID if input_ids.shape[1] > past_length: remove_prefix_length = past_length else: # Default to old behavior: keep only final ID remove_prefix_length = input_ids.shape[1] - 1 input_ids = input_ids[:, remove_prefix_length:] model_inputs = {"input_ids": input_ids, "past_key_values": past_key_values, "use_cache": use_cache} # token_type_ids are computed on CTRLModel.forward() kwargs.pop("token_type_ids", None) # Forward ALL kwargs that are uninitialized (e.g. `use_cache`). for key, value in kwargs.items(): if key not in model_inputs: print(f"Warning: {key} is not a recognized input.") model_inputs[key] = value return model_inputs @auto_docstring( custom_intro=""" The CTRL Model transformer with a sequence classification head on top (linear layer). [`CTRLForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """ )
CTRLLMHeadModel
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/components.py
{ "start": 11481, "end": 12112 }
class ____(RecordExtractor): """ Transformation that encapsulates the list of properties under a single object because DynamicSchemaLoader only accepts the set of dynamic schema fields as a single record. This might be doable with the existing DpathExtractor configuration. """ config: Config parameters: InitVar[Mapping[str, Any]] decoder: Decoder = field(default_factory=lambda: JsonDecoder(parameters={})) def extract_records(self, response: requests.Response) -> Iterable[Mapping[str, Any]]: yield {"properties": list(self.decoder.decode(response))} @dataclass
HubspotSchemaExtractor