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
google__pytype
pytype/rewrite/convert.py
{ "start": 196, "end": 297 }
class ____: def __init__(self): self.classes = {} self.funcs = {} self.types = {}
_Cache
python
falconry__falcon
tests/test_uri_templates.py
{ "start": 1849, "end": 2111 }
class ____: def __init__(self): self.file_id = None self.ext = None self.called = False def on_get(self, req, resp, file_id, ext): self.file_id = file_id self.ext = ext self.called = True
FileDetailsResource
python
tensorflow__tensorflow
tensorflow/python/keras/legacy_tf_layers/pooling.py
{ "start": 6327, "end": 9428 }
class ____(keras_layers.AveragePooling2D, base.Layer): """Average pooling layer for 2D inputs (e.g. images). Args: pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. padding: A string. The padding method, either 'valid' or 'same'. Case-insensitive. data_format: A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. name: A string, the name of the layer. """ def __init__(self, pool_size, strides, padding='valid', data_format='channels_last', name=None, **kwargs): if strides is None: raise ValueError('Argument `strides` must not be None.') super(AveragePooling2D, self).__init__( pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, name=name, **kwargs) def average_pooling2d(inputs, pool_size, strides, padding='valid', data_format='channels_last', name=None): """Average pooling layer for 2D inputs (e.g. images). Args: inputs: The tensor over which to pool. Must have rank 4. pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. padding: A string. The padding method, either 'valid' or 'same'. Case-insensitive. data_format: A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. name: A string, the name of the layer. Returns: Output tensor. Raises: ValueError: if eager execution is enabled. """ warnings.warn('`tf.layers.average_pooling2d` is deprecated and ' 'will be removed in a future version. ' 'Please use `tf.keras.layers.AveragePooling2D` instead.') layer = AveragePooling2D(pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, name=name) return layer.apply(inputs)
AveragePooling2D
python
airbytehq__airbyte
airbyte-integrations/connectors/source-azure-blob-storage/source_azure_blob_storage/stream_reader.py
{ "start": 798, "end": 2352 }
class ____(Oauth2Authenticator, TokenCredential): def __init__(self, tenant_id: str, client_id: str, client_secret: str, **kwargs): super().__init__( token_refresh_endpoint=f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token", client_id=client_id, client_secret=client_secret, grant_type="client_credentials", scopes=["https://storage.azure.com/.default"], refresh_token=None, ) def build_refresh_request_body(self) -> Mapping[str, Any]: """ Returns the request body to set on the refresh request Override to define additional parameters """ payload: MutableMapping[str, Any] = { "grant_type": self.get_grant_type(), "client_id": self.get_client_id(), "client_secret": self.get_client_secret(), } if self.get_scopes(): payload["scope"] = " ".join(self.get_scopes()) if self.get_refresh_request_body(): for key, val in self.get_refresh_request_body().items(): # We defer to existing oauth constructs over custom configured fields if key not in payload: payload[key] = val return payload def get_token(self, *args, **kwargs) -> AccessToken: """Parent class handles Oauth Refresh token logic.""" return AccessToken(token=self.get_access_token(), expires_on=int(self.get_token_expiry_date().timestamp()))
AzureClientCredentialsAuthenticator
python
gawel__pyquery
tests/test_pyquery.py
{ "start": 26689, "end": 27977 }
class ____(TestCase): xml = "<div>I'm valid XML</div>" html = '''<div class="portlet"> <a href="/toto">TestimageMy link text</a> <a href="/toto2">imageMy link text 2</a> Behind you, a three-headed HTML&dash;Entity! </div>''' def test_parser_persistance(self): d = pq(self.xml, parser='xml') self.assertRaises(etree.XMLSyntaxError, lambda: d.after(self.html)) d = pq(self.xml, parser='html') d.after(self.html) # this should not fail def test_replaceWith(self): expected = '''<div class="portlet"> <a href="/toto">TestimageMy link text</a> <a href="/toto2">imageMy link text 2</a> Behind you, a three-headed HTML&amp;dash;Entity! </div>''' d = pq(self.html) d('img').replace_with('image') val = d.__html__() assert val == expected, (repr(val), repr(expected)) def test_replaceWith_with_function(self): expected = '''<div class="portlet"> TestimageMy link text imageMy link text 2 Behind you, a three-headed HTML&amp;dash;Entity! </div>''' d = pq(self.html) d('a').replace_with(lambda i, e: pq(e).html()) val = d.__html__() assert val == expected, (repr(val), repr(expected))
TestHTMLParser
python
realpython__materials
python-protocol/birds_v2.py
{ "start": 0, "end": 119 }
class ____: def quack(self): raise NotImplementedError("Subclasses must implement this method")
QuackingThing
python
gevent__gevent
src/greentest/3.10/test_threading.py
{ "start": 55545, "end": 55635 }
class ____(lock_tests.RLockTests): locktype = staticmethod(threading._CRLock)
CRLockTests
python
kamyu104__LeetCode-Solutions
Python/implement-strstr.py
{ "start": 1013, "end": 1335 }
class ____(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ for i in xrange(len(haystack) - len(needle) + 1): if haystack[i : i + len(needle)] == needle: return i return -1
Solution2
python
sympy__sympy
sympy/functions/special/polynomials.py
{ "start": 1063, "end": 1511 }
class ____(DefinedFunction): """Base class for orthogonal polynomials. """ @classmethod def _eval_at_order(cls, n, x): if n.is_integer and n >= 0: return cls._ortho_poly(int(n), _x).subs(_x, x) def _eval_conjugate(self): return self.func(self.args[0], self.args[1].conjugate()) #---------------------------------------------------------------------------- # Jacobi polynomials #
OrthogonalPolynomial
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 603567, "end": 604174 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "actor", "client_mutation_id", "pull_request", "requested_reviewers_edge", ) actor = sgqlc.types.Field(Actor, graphql_name="actor") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") pull_request = sgqlc.types.Field("PullRequest", graphql_name="pullRequest") requested_reviewers_edge = sgqlc.types.Field( "UserEdge", graphql_name="requestedReviewersEdge" )
RequestReviewsPayload
python
pypa__warehouse
warehouse/observations/models.py
{ "start": 737, "end": 1118 }
class ____(db.Model): """Associate an Observer with a given parent.""" __tablename__ = "observer_association" discriminator: Mapped[str] = mapped_column(comment="The type of the parent") observer: Mapped[Observer] = relationship( back_populates="_association", uselist=False ) __mapper_args__ = {"polymorphic_on": discriminator}
ObserverAssociation
python
Lightning-AI__lightning
src/lightning/fabric/strategies/parallel.py
{ "start": 1186, "end": 4515 }
class ____(Strategy, ABC): """Strategy for training with multiple processes in parallel.""" def __init__( self, accelerator: Optional[Accelerator] = None, parallel_devices: Optional[list[torch.device]] = None, cluster_environment: Optional[ClusterEnvironment] = None, checkpoint_io: Optional[CheckpointIO] = None, precision: Optional[Precision] = None, ): super().__init__(accelerator=accelerator, checkpoint_io=checkpoint_io, precision=precision) self.parallel_devices = parallel_devices self.cluster_environment: Optional[ClusterEnvironment] = cluster_environment @property def global_rank(self) -> int: return self.cluster_environment.global_rank() if self.cluster_environment is not None else 0 @property def local_rank(self) -> int: return self.cluster_environment.local_rank() if self.cluster_environment is not None else 0 @property def node_rank(self) -> int: return self.cluster_environment.node_rank() if self.cluster_environment is not None else 0 @property def world_size(self) -> int: return self.cluster_environment.world_size() if self.cluster_environment is not None else 1 @property @override def is_global_zero(self) -> bool: return self.global_rank == 0 @property def parallel_devices(self) -> Optional[list[torch.device]]: return self._parallel_devices @parallel_devices.setter def parallel_devices(self, parallel_devices: Optional[list[torch.device]]) -> None: self._parallel_devices = parallel_devices @property def distributed_sampler_kwargs(self) -> Optional[dict[str, Any]]: """Arguments for the ``DistributedSampler``. If this method is not defined, or it returns ``None``, then the ``DistributedSampler`` will not be used. """ return {"num_replicas": self.world_size, "rank": self.global_rank} @override def all_gather(self, tensor: Tensor, group: Optional[Any] = None, sync_grads: bool = False) -> Tensor: """Perform a all_gather on all processes.""" return _all_gather_ddp_if_available(tensor, group=group, sync_grads=sync_grads) @override def reduce_boolean_decision(self, decision: bool, all: bool = True) -> bool: """Reduces a boolean decision over distributed processes. By default is analogous to ``all`` from the standard library, returning ``True`` only if all input decisions evaluate to ``True``. If ``all`` is set to ``False``, it behaves like ``any`` instead. Args: decision: A single input decision. all: Whether to logically emulate ``all`` or ``any``. Defaults to True. Returns: bool: The reduced boolean decision. """ decision = torch.tensor(int(decision), device=self.root_device) decision = self.all_reduce( decision, reduce_op=ReduceOp.SUM, # type: ignore[arg-type] ) decision = bool(decision == self.world_size) if all else bool(decision) return decision @override def teardown(self) -> None: assert self.cluster_environment is not None self.cluster_environment.teardown() return super().teardown()
ParallelStrategy
python
sqlalchemy__sqlalchemy
test/orm/test_cycles.py
{ "start": 47584, "end": 53105 }
class ____(fixtures.MappedTest): """test that lots of post update cols batch together into a single UPDATE.""" @classmethod def define_tables(cls, metadata): Table( "parent", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50), nullable=False), Column( "c1_id", Integer, ForeignKey("child1.id", name="c1"), nullable=True, ), Column( "c2_id", Integer, ForeignKey("child2.id", name="c2"), nullable=True, ), Column( "c3_id", Integer, ForeignKey("child3.id", name="c3"), nullable=True, ), ) Table( "child1", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50), nullable=False), Column( "parent_id", Integer, ForeignKey("parent.id"), nullable=False ), ) Table( "child2", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50), nullable=False), Column( "parent_id", Integer, ForeignKey("parent.id"), nullable=False ), ) Table( "child3", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50), nullable=False), Column( "parent_id", Integer, ForeignKey("parent.id"), nullable=False ), ) @classmethod def setup_classes(cls): class Parent(cls.Basic): def __init__(self, name=""): self.name = name class Child1(cls.Basic): def __init__(self, name=""): self.name = name class Child2(cls.Basic): def __init__(self, name=""): self.name = name class Child3(cls.Basic): def __init__(self, name=""): self.name = name def test_one(self): child1, child2, child3, Parent, parent, Child1, Child2, Child3 = ( self.tables.child1, self.tables.child2, self.tables.child3, self.classes.Parent, self.tables.parent, self.classes.Child1, self.classes.Child2, self.classes.Child3, ) self.mapper_registry.map_imperatively( Parent, parent, properties={ "c1s": relationship( Child1, primaryjoin=child1.c.parent_id == parent.c.id ), "c2s": relationship( Child2, primaryjoin=child2.c.parent_id == parent.c.id ), "c3s": relationship( Child3, primaryjoin=child3.c.parent_id == parent.c.id ), "c1": relationship( Child1, primaryjoin=child1.c.id == parent.c.c1_id, post_update=True, ), "c2": relationship( Child2, primaryjoin=child2.c.id == parent.c.c2_id, post_update=True, ), "c3": relationship( Child3, primaryjoin=child3.c.id == parent.c.c3_id, post_update=True, ), }, ) self.mapper_registry.map_imperatively(Child1, child1) self.mapper_registry.map_imperatively(Child2, child2) self.mapper_registry.map_imperatively(Child3, child3) sess = fixture_session() p1 = Parent("p1") c11, c12, c13 = Child1("c1"), Child1("c2"), Child1("c3") c21, c22, c23 = Child2("c1"), Child2("c2"), Child2("c3") c31, c32, c33 = Child3("c1"), Child3("c2"), Child3("c3") p1.c1s = [c11, c12, c13] p1.c2s = [c21, c22, c23] p1.c3s = [c31, c32, c33] sess.add(p1) sess.flush() p1.c1 = c12 p1.c2 = c23 p1.c3 = c31 self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "UPDATE parent SET c1_id=:c1_id, c2_id=:c2_id, c3_id=:c3_id " "WHERE parent.id = :parent_id", lambda ctx: { "c2_id": c23.id, "parent_id": p1.id, "c1_id": c12.id, "c3_id": c31.id, }, ), ) p1.c1 = p1.c2 = p1.c3 = None self.assert_sql_execution( testing.db, sess.flush, CompiledSQL( "UPDATE parent SET c1_id=:c1_id, c2_id=:c2_id, c3_id=:c3_id " "WHERE parent.id = :parent_id", lambda ctx: { "c2_id": None, "parent_id": p1.id, "c1_id": None, "c3_id": None, }, ), )
PostUpdateBatchingTest
python
tensorflow__tensorflow
tensorflow/python/autograph/converters/variables.py
{ "start": 911, "end": 2806 }
class ____(converter.Base): """Rewrites basic symbol reads. This transformer rewrites variable reads with a "read" operator which allows tracking activity. Example: For a basic statement: a = b + c This is translated to: a = ld(b) + ld(c) Augmented assignment operations also introduce a `ld` operator: a += b The assignment target also receives an operator to properly represent the read: a = ld(a) a += ld(b) """ def visit_Name(self, node): # Only the loads which existed in the original code are overloaded. if not anno.hasanno(node, anno.Static.ORIG_DEFINITIONS): return node if isinstance(node.ctx, gast.Load): node = templates.replace_as_expression('ag__.ld(var_)', var_=node) return node def visit_Delete(self, node): node = self.generic_visit(node) rewrite_targets = [] for tgt in node.targets: # Don't rewrite composites like `del a[0]`. if isinstance(tgt, gast.Name): rewrite_targets.append(tgt) if not rewrite_targets: return node results = [] for tgt in rewrite_targets: template = """ var_ = ag__.Undefined(var_name) """ results.extend(templates.replace( template, var_=tgt, var_name=gast.Constant(tgt.id, kind=None))) remaining_targets = [n for n in node.targets if n not in rewrite_targets] if remaining_targets: results.append(gast.Delete(targets=remaining_targets)) return results def visit_AugAssign(self, node): if isinstance(node.target, gast.Name): template = """ var_ = ag__.ld(var_) original """ node = templates.replace(template, var_=node.target, original=node) else: node = self.generic_visit(node) return node def transform(node, ctx): return VariableAccessTransformer(ctx).visit(node)
VariableAccessTransformer
python
imageio__imageio
imageio/plugins/opencv.py
{ "start": 1189, "end": 11629 }
class ____(PluginV3): def __init__(self, request: Request) -> None: super().__init__(request) self.file_handle = request.get_local_filename() if request._uri_type is URI_BYTES: self.filename = "<bytes>" else: self.filename = request.raw_uri mode = request.mode.io_mode if mode == IOMode.read and not cv2.haveImageReader(self.file_handle): raise InitializationError(f"OpenCV can't read `{self.filename}`.") elif mode == IOMode.write and not cv2.haveImageWriter(self.file_handle): raise InitializationError(f"OpenCV can't write to `{self.filename}`.") def read( self, *, index: int = None, colorspace: Union[int, str] = None, flags: int = cv2.IMREAD_COLOR, ) -> np.ndarray: """Read an image from the ImageResource. Parameters ---------- index : int, Ellipsis If int, read the index-th image from the ImageResource. If ``...``, read all images from the ImageResource and stack them along a new, prepended, batch dimension. If None (default), use ``index=0`` if the image contains exactly one image and ``index=...`` otherwise. colorspace : str, int The colorspace to convert into after loading and before returning the image. If None (default) keep grayscale images as is, convert images with an alpha channel to ``RGBA`` and all other images to ``RGB``. If int, interpret ``colorspace`` as one of OpenCVs `conversion flags <https://docs.opencv.org/4.x/d8/d01/group__imgproc__color__conversions.html>`_ and use it for conversion. If str, convert the image into the given colorspace. Possible string values are: ``"RGB"``, ``"BGR"``, ``"RGBA"``, ``"BGRA"``, ``"GRAY"``, ``"HSV"``, or ``"LAB"``. flags : int The OpenCV flag(s) to pass to the reader. Refer to the `OpenCV docs <https://docs.opencv.org/4.x/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56>`_ for details. Returns ------- ndimage : np.ndarray The decoded image as a numpy array. """ if index is None: n_images = cv2.imcount(self.file_handle, flags) index = 0 if n_images == 1 else ... if index is ...: retval, img = cv2.imreadmulti(self.file_handle, flags=flags) is_batch = True else: retval, img = cv2.imreadmulti(self.file_handle, index, 1, flags=flags) is_batch = False if retval is False: raise ValueError(f"Could not read index `{index}` from `{self.filename}`.") if img[0].ndim == 2: in_colorspace = "GRAY" out_colorspace = colorspace or "GRAY" elif img[0].shape[-1] == 4: in_colorspace = "BGRA" out_colorspace = colorspace or "RGBA" else: in_colorspace = "BGR" out_colorspace = colorspace or "RGB" if isinstance(colorspace, int): cvt_space = colorspace elif in_colorspace == out_colorspace.upper(): cvt_space = None else: out_colorspace = out_colorspace.upper() cvt_space = getattr(cv2, f"COLOR_{in_colorspace}2{out_colorspace}") if cvt_space is not None: img = np.stack([cv2.cvtColor(x, cvt_space) for x in img]) else: img = np.stack(img) return img if is_batch else img[0] def iter( self, colorspace: Union[int, str] = None, flags: int = cv2.IMREAD_COLOR, ) -> np.ndarray: """Yield images from the ImageResource. Parameters ---------- colorspace : str, int The colorspace to convert into after loading and before returning the image. If None (default) keep grayscale images as is, convert images with an alpha channel to ``RGBA`` and all other images to ``RGB``. If int, interpret ``colorspace`` as one of OpenCVs `conversion flags <https://docs.opencv.org/4.x/d8/d01/group__imgproc__color__conversions.html>`_ and use it for conversion. If str, convert the image into the given colorspace. Possible string values are: ``"RGB"``, ``"BGR"``, ``"RGBA"``, ``"BGRA"``, ``"GRAY"``, ``"HSV"``, or ``"LAB"``. flags : int The OpenCV flag(s) to pass to the reader. Refer to the `OpenCV docs <https://docs.opencv.org/4.x/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56>`_ for details. Yields ------ ndimage : np.ndarray The decoded image as a numpy array. """ for idx in range(cv2.imcount(self.file_handle)): yield self.read(index=idx, flags=flags, colorspace=colorspace) def write( self, ndimage: Union[ArrayLike, List[ArrayLike]], is_batch: bool = False, params: List[int] = None, ) -> Optional[bytes]: """Save an ndimage in the ImageResource. Parameters ---------- ndimage : ArrayLike, List[ArrayLike] The image data that will be written to the file. It is either a single image, a batch of images, or a list of images. is_batch : bool If True, the provided ndimage is a batch of images. If False (default), the provided ndimage is a single image. If the provided ndimage is a list of images, this parameter has no effect. params : List[int] A list of parameters that will be passed to OpenCVs imwrite or imwritemulti functions. Possible values are documented in the `OpenCV documentation <https://docs.opencv.org/4.x/d4/da8/group__imgcodecs.html#gabbc7ef1aa2edfaa87772f1202d67e0ce>`_. Returns ------- encoded_image : bytes, None If the ImageResource is ``"<bytes>"`` the call to write returns the encoded image as a bytes string. Otherwise it returns None. """ if isinstance(ndimage, list): ndimage = np.stack(ndimage, axis=0) elif not is_batch: ndimage = ndimage[None, ...] if ndimage[0].ndim == 2: n_channels = 1 else: n_channels = ndimage[0].shape[-1] if n_channels == 1: ndimage_cv2 = [x for x in ndimage] elif n_channels == 4: ndimage_cv2 = [cv2.cvtColor(x, cv2.COLOR_RGBA2BGRA) for x in ndimage] else: ndimage_cv2 = [cv2.cvtColor(x, cv2.COLOR_RGB2BGR) for x in ndimage] retval = cv2.imwritemulti(self.file_handle, ndimage_cv2, params) if retval is False: # not sure what scenario would trigger this, but # it can occur theoretically. raise IOError("OpenCV failed to write.") # pragma: no cover if self.request._uri_type == URI_BYTES: return Path(self.file_handle).read_bytes() def properties( self, index: int = None, colorspace: Union[int, str] = None, flags: int = cv2.IMREAD_COLOR, ) -> ImageProperties: """Standardized image metadata. Parameters ---------- index : int, Ellipsis If int, get the properties of the index-th image in the ImageResource. If ``...``, get the properties of the image stack that contains all images. If None (default), use ``index=0`` if the image contains exactly one image and ``index=...`` otherwise. colorspace : str, int The colorspace to convert into after loading and before returning the image. If None (default) keep grayscale images as is, convert images with an alpha channel to ``RGBA`` and all other images to ``RGB``. If int, interpret ``colorspace`` as one of OpenCVs `conversion flags <https://docs.opencv.org/4.x/d8/d01/group__imgproc__color__conversions.html>`_ and use it for conversion. If str, convert the image into the given colorspace. Possible string values are: ``"RGB"``, ``"BGR"``, ``"RGBA"``, ``"BGRA"``, ``"GRAY"``, ``"HSV"``, or ``"LAB"``. flags : int The OpenCV flag(s) to pass to the reader. Refer to the `OpenCV docs <https://docs.opencv.org/4.x/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56>`_ for details. Returns ------- props : ImageProperties A dataclass filled with standardized image metadata. Notes ----- Reading properties with OpenCV involves decoding pixel data, because OpenCV doesn't provide a direct way to access metadata. """ if index is None: n_images = cv2.imcount(self.file_handle, flags) is_batch = n_images > 1 elif index is Ellipsis: n_images = cv2.imcount(self.file_handle, flags) is_batch = True else: is_batch = False # unfortunately, OpenCV doesn't allow reading shape without reading pixel data if is_batch: img = self.read(index=0, flags=flags, colorspace=colorspace) return ImageProperties( shape=(n_images, *img.shape), dtype=img.dtype, n_images=n_images, is_batch=True, ) img = self.read(index=index, flags=flags, colorspace=colorspace) return ImageProperties(shape=img.shape, dtype=img.dtype, is_batch=False) def metadata( self, index: int = None, exclude_applied: bool = True ) -> Dict[str, Any]: """Format-specific metadata. .. warning:: OpenCV does not support reading metadata. When called, this function will raise a ``NotImplementedError``. Parameters ---------- index : int This parameter has no effect. exclude_applied : bool This parameter has no effect. """ warnings.warn("OpenCV does not support reading metadata.", UserWarning) return dict()
OpenCVPlugin
python
catalyst-team__catalyst
catalyst/metrics/_classification.py
{ "start": 16879, "end": 21222 }
class ____(BinaryStatisticsMetric): """Precision, recall, f1_score and support metrics for binary classification. Args: zero_division: value to set in case of zero division during metrics (precision, recall) computation; should be one of 0 or 1 compute_on_call: if True, allows compute metric's value on call prefix: metric prefix suffix: metric suffix """ def __init__( self, zero_division: int = 0, compute_on_call: bool = True, prefix: Optional[str] = None, suffix: Optional[str] = None, ): """Init BinaryPrecisionRecallF1SupportMetric instance""" super().__init__( compute_on_call=compute_on_call, prefix=prefix, suffix=suffix, ) self.statistics = None self.zero_division = zero_division self.reset() @staticmethod def _convert_metrics_to_kv( precision_value: float, recall_value: float, f1_value: float ) -> Dict[str, float]: """ Convert list of metrics to key-value Args: precision_value: precision value recall_value: recall value f1_value: f1 value Returns: dict of metrics """ kv_metrics = { "precision": precision_value, "recall": recall_value, "f1": f1_value, } return kv_metrics def reset(self) -> None: """Reset all the statistics and metrics fields.""" self.statistics = defaultdict(int) def update( self, outputs: torch.Tensor, targets: torch.Tensor ) -> Tuple[float, float, float]: """ Update statistics and return metrics intermediate results Args: outputs: predicted labels targets: target labels Returns: tuple of intermediate metrics: precision, recall, f1 score """ tn, fp, fn, tp, support = super().update(outputs=outputs, targets=targets) precision_value, recall_value, f1_value = get_binary_metrics( tp=tp, fp=fp, fn=fn, zero_division=self.zero_division ) return precision_value, recall_value, f1_value def update_key_value( self, outputs: torch.Tensor, targets: torch.Tensor ) -> Dict[str, float]: """ Update statistics and return metrics intermediate results Args: outputs: predicted labels targets: target labels Returns: dict of intermediate metrics """ precision_value, recall_value, f1_value = self.update( outputs=outputs, targets=targets ) kv_metrics = self._convert_metrics_to_kv( precision_value=precision_value, recall_value=recall_value, f1_value=f1_value ) return kv_metrics def compute(self) -> Tuple[float, float, float]: """ Compute metrics with accumulated statistics Returns: tuple of metrics: precision, recall, f1 score """ # ddp hotfix, could be done better # but metric must handle DDP on it's own if self._ddp_backend == "xla": self.statistics = { k: xm.mesh_reduce(k, v, np.sum) for k, v in self.statistics.items() } elif self._ddp_backend == "ddp": for key in self.statistics: value: List[int] = all_gather(self.statistics[key]) value: int = sum(value) self.statistics[key] = value precision_value, recall_value, f1_value = get_binary_metrics( tp=self.statistics["tp"], fp=self.statistics["fp"], fn=self.statistics["fn"], zero_division=self.zero_division, ) return precision_value, recall_value, f1_value def compute_key_value(self) -> Dict[str, float]: """ Compute metrics with all accumulated statistics Returns: dict of metrics """ precision_value, recall_value, f1_value = self.compute() kv_metrics = self._convert_metrics_to_kv( precision_value=precision_value, recall_value=recall_value, f1_value=f1_value ) return kv_metrics
BinaryPrecisionRecallF1Metric
python
getsentry__sentry
src/sentry/models/groupinbox.py
{ "start": 917, "end": 1107 }
class ____(Enum): NEW = 0 REGRESSION = 2 MANUAL = 3 REPROCESSED = 4 ESCALATING = 5 ONGOING = 6 # DEPRECATED: Use ONGOING instead UNIGNORED = 1
GroupInboxReason
python
matplotlib__matplotlib
lib/matplotlib/widgets.py
{ "start": 71066, "end": 75749 }
class ____(Widget): """ Provide a vertical (default) and/or horizontal line cursor shared between multiple Axes. For the cursor to remain responsive you must keep a reference to it. Parameters ---------- canvas : object This parameter is entirely unused and only kept for back-compatibility. axes : list of `~matplotlib.axes.Axes` The `~.axes.Axes` to attach the cursor to. useblit : bool, default: True Use blitting for faster drawing if supported by the backend. See the tutorial :ref:`blitting` for details. horizOn : bool, default: False Whether to draw the horizontal line. vertOn : bool, default: True Whether to draw the vertical line. Other Parameters ---------------- **lineprops `.Line2D` properties that control the appearance of the lines. See also `~.Axes.axhline`. Examples -------- See :doc:`/gallery/widgets/multicursor`. """ def __init__(self, canvas, axes, *, useblit=True, horizOn=False, vertOn=True, **lineprops): # canvas is stored only to provide the deprecated .canvas attribute; # once it goes away the unused argument won't need to be stored at all. self._canvas = canvas self.axes = axes self.horizOn = horizOn self.vertOn = vertOn self._canvas_infos = { ax.get_figure(root=True).canvas: {"cids": [], "background": None} for ax in axes} xmin, xmax = axes[-1].get_xlim() ymin, ymax = axes[-1].get_ylim() xmid = 0.5 * (xmin + xmax) ymid = 0.5 * (ymin + ymax) self.visible = True self.useblit = ( useblit and all(canvas.supports_blit for canvas in self._canvas_infos)) if self.useblit: lineprops['animated'] = True self.vlines = [ax.axvline(xmid, visible=False, **lineprops) for ax in axes] self.hlines = [ax.axhline(ymid, visible=False, **lineprops) for ax in axes] self.connect() def connect(self): """Connect events.""" for canvas, info in self._canvas_infos.items(): info["cids"] = [ canvas.mpl_connect('motion_notify_event', self.onmove), canvas.mpl_connect('draw_event', self.clear), ] def disconnect(self): """Disconnect events.""" for canvas, info in self._canvas_infos.items(): for cid in info["cids"]: canvas.mpl_disconnect(cid) info["cids"].clear() def clear(self, event): """Clear the cursor.""" if self.ignore(event): return if self.useblit: for canvas, info in self._canvas_infos.items(): # someone has switched the canvas on us! This happens if # `savefig` needs to save to a format the previous backend did # not support (e.g. saving a figure using an Agg based backend # saved to a vector format). if canvas is not canvas.figure.canvas: continue info["background"] = canvas.copy_from_bbox(canvas.figure.bbox) def onmove(self, event): axs = [ax for ax in self.axes if ax.contains(event)[0]] if self.ignore(event) or not axs or not event.canvas.widgetlock.available(self): return ax = cbook._topmost_artist(axs) xdata, ydata = ((event.xdata, event.ydata) if event.inaxes is ax else ax.transData.inverted().transform((event.x, event.y))) for line in self.vlines: line.set_xdata((xdata, xdata)) line.set_visible(self.visible and self.vertOn) for line in self.hlines: line.set_ydata((ydata, ydata)) line.set_visible(self.visible and self.horizOn) if not (self.visible and (self.vertOn or self.horizOn)): return # Redraw. if self.useblit: for canvas, info in self._canvas_infos.items(): if info["background"]: canvas.restore_region(info["background"]) if self.vertOn: for ax, line in zip(self.axes, self.vlines): ax.draw_artist(line) if self.horizOn: for ax, line in zip(self.axes, self.hlines): ax.draw_artist(line) for canvas in self._canvas_infos: canvas.blit() else: for canvas in self._canvas_infos: canvas.draw_idle()
MultiCursor
python
huggingface__transformers
tests/models/longt5/test_modeling_longt5.py
{ "start": 41790, "end": 45735 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (LongT5EncoderModel,) if is_torch_available() else () test_resize_embeddings = False def setUp(self): self.model_tester = LongT5EncoderOnlyModelTester(self) self.config_tester = ConfigTester(self, config_class=LongT5Config, d_model=37) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_attention_outputs(self): if not self.has_attentions: self.skipTest(reason="has_attentions is set to False") else: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True block_len = getattr(self.model_tester, "block_len", 4) for model_class in self.all_model_classes: inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = False config.return_dict = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] config.output_attentions = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, block_len, 3 * block_len], ) out_len = len(outputs) # Check attention is always last and order is fine inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) if hasattr(self.model_tester, "num_hidden_states_types"): added_hidden_states = self.model_tester.num_hidden_states_types elif self.is_encoder_decoder: added_hidden_states = 2 else: added_hidden_states = 1 self.assertEqual(out_len + added_hidden_states, len(outputs)) self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, block_len, 3 * block_len], ) @unittest.skip( reason="This architecture has tied weights by default and there is no way to remove it, check: https://github.com/huggingface/transformers/pull/31771#issuecomment-2210915245" ) def test_load_save_without_tied_weights(self): pass
LongT5EncoderOnlyModelTest
python
kamyu104__LeetCode-Solutions
Python/make-array-empty.py
{ "start": 40, "end": 418 }
class ____(object): def countOperationsToEmptyArray(self, nums): """ :type nums: List[int] :rtype: int """ idxs = range(len(nums)) idxs.sort(key=lambda x: nums[x]) return len(idxs)+sum(len(idxs)-(i+1) for i in xrange(len(idxs)-1) if idxs[i] > idxs[i+1]) # Time: O(nlogn) # Space: O(n) # sort, bit, fenwick tree
Solution
python
ray-project__ray
python/ray/data/tests/unit/test_arrow_type_conversion.py
{ "start": 684, "end": 6106 }
class ____: i: int = field() @pytest.mark.parametrize( "input", [ # Python native lists [ [1, 2], [3, 4], ], # Python native tuples [ (1, 2), (3, 4), ], # Lists as PA scalars [ pa.scalar([1, 2]), pa.scalar([3, 4]), ], ], ) def test_arrow_native_list_conversion(input, disable_fallback_to_object_extension): """Test asserts that nested lists are represented as native Arrow lists upon serialization into Arrow format (and are NOT converted to numpy tensor using extension)""" if isinstance(input[0], pa.Scalar) and get_pyarrow_version() <= parse_version( "13.0.0" ): pytest.skip( "Pyarrow < 13.0 not able to properly infer native types from its own Scalars" ) pa_arr = convert_to_pyarrow_array(input, "a") # Should be able to natively convert back to Pyarrow array, # not using any extensions assert pa_arr.type == pa.list_(pa.int64()), pa_arr.type assert pa.array(input) == pa_arr, pa_arr @pytest.mark.parametrize("arg_type", ["list", "ndarray"]) @pytest.mark.parametrize( "numpy_precision, expected_arrow_timestamp_type", [ ("ms", pa.timestamp("ms")), ("us", pa.timestamp("us")), ("ns", pa.timestamp("ns")), # The coarsest resolution Arrow supports is seconds. ("Y", pa.timestamp("s")), ("M", pa.timestamp("s")), ("D", pa.timestamp("s")), ("h", pa.timestamp("s")), ("m", pa.timestamp("s")), ("s", pa.timestamp("s")), # The finest resolution Arrow supports is nanoseconds. ("ps", pa.timestamp("ns")), ("fs", pa.timestamp("ns")), ("as", pa.timestamp("ns")), ], ) def test_convert_datetime_array( numpy_precision: str, expected_arrow_timestamp_type: pa.TimestampType, arg_type: str, restore_data_context, ): DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False ndarray = np.ones(1, dtype=f"datetime64[{numpy_precision}]") if arg_type == "ndarray": column_values = ndarray elif arg_type == "list": column_values = [ndarray] else: pytest.fail(f"Unknown type: {arg_type}") # Step 1: Convert to PA array converted = convert_to_pyarrow_array(column_values, "") if arg_type == "ndarray": expected = pa.array( column_values.astype(f"datetime64[{expected_arrow_timestamp_type.unit}]") ) elif arg_type == "list": expected = ArrowTensorArray.from_numpy( [ column_values[0].astype( f"datetime64[{expected_arrow_timestamp_type.unit}]" ) ] ) else: pytest.fail(f"Unknown type: {arg_type}") assert expected.type == converted.type assert expected == converted @pytest.mark.parametrize("dtype", ["int64", "float64", "datetime64[ns]"]) def test_infer_type_does_not_leak_memory(dtype): # Test for https://github.com/apache/arrow/issues/45493. ndarray = np.zeros(923040, dtype=dtype) # A ~7 MiB column process = psutil.Process() gc.collect() pa.default_memory_pool().release_unused() before = process.memory_info().rss # Call the function several times. If there's a memory leak, this loop will leak # as much as 1 GiB of memory with 8 repetitions. 8 was chosen arbitrarily. num_repetitions = 8 for _ in range(num_repetitions): _infer_pyarrow_type(ndarray) gc.collect() pa.default_memory_pool().release_unused() after = process.memory_info().rss margin_of_error = 64 * MiB assert after - before < margin_of_error, memory_string(after - before) def test_pa_infer_type_failing_to_infer(): # Represent a single column that will be using `ArrowPythonObjectExtension` type # to ser/de native Python objects into bytes column_vals = create_ragged_ndarray( [ "hi", 1, None, [[[[]]]], {"a": [[{"b": 2, "c": UserObj(i=123)}]]}, UserObj(i=456), ] ) inferred_dtype = _infer_pyarrow_type(column_vals) # Arrow (17.0) seem to fallback to assume the dtype of the first element assert pa.string().equals(inferred_dtype) def test_convert_to_pyarrow_array_object_ext_type_fallback(): column_values = create_ragged_ndarray( [ "hi", 1, None, [[[[]]]], {"a": [[{"b": 2, "c": UserObj(i=123)}]]}, UserObj(i=456), ] ) column_name = "py_object_column" # First, assert that straightforward conversion into Arrow native types fails with pytest.raises(ArrowConversionError) as exc_info: _convert_to_pyarrow_native_array(column_values, column_name) assert ( str(exc_info.value) == "Error converting data to Arrow: ['hi' 1 None list([[[[]]]]) {'a': [[{'b': 2, 'c': UserObj(i=123)}]]}\n UserObj(i=456)]" # noqa: E501 ) # Subsequently, assert that fallback to `ArrowObjectExtensionType` succeeds pa_array = convert_to_pyarrow_array(column_values, column_name) assert pa_array.to_pylist() == column_values.tolist() if __name__ == "__main__": import sys sys.exit(pytest.main(["-v", "-x", __file__]))
UserObj
python
readthedocs__readthedocs.org
readthedocs/oauth/migrations/0002_combine_services.py
{ "start": 163, "end": 7337 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("oauth", "0001_initial"), ] operations = [ migrations.CreateModel( name="RemoteOrganization", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "pub_date", models.DateTimeField(auto_now_add=True, verbose_name="Publication date"), ), ( "modified_date", models.DateTimeField(auto_now=True, verbose_name="Modified date"), ), ("active", models.BooleanField(default=False, verbose_name="Active")), ( "slug", models.CharField(unique=True, max_length=255, verbose_name="Slug"), ), ( "name", models.CharField(max_length=255, null=True, verbose_name="Name", blank=True), ), ( "email", models.EmailField(max_length=255, null=True, verbose_name="Email", blank=True), ), ( "avatar_url", models.URLField(null=True, verbose_name="Avatar image URL", blank=True), ), ( "url", models.URLField(null=True, verbose_name="URL to organization page", blank=True), ), ( "source", models.CharField( max_length=16, verbose_name="Repository source", choices=[(b"github", "GitHub"), (b"bitbucket", "Bitbucket")], ), ), ("json", models.TextField(verbose_name="Serialized API response")), ( "users", models.ManyToManyField( related_name="oauth_organizations", verbose_name="Users", to=settings.AUTH_USER_MODEL, ), ), ], ), migrations.CreateModel( name="RemoteRepository", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "pub_date", models.DateTimeField(auto_now_add=True, verbose_name="Publication date"), ), ( "modified_date", models.DateTimeField(auto_now=True, verbose_name="Modified date"), ), ("active", models.BooleanField(default=False, verbose_name="Active")), ("name", models.CharField(max_length=255, verbose_name="Name")), ( "full_name", models.CharField(max_length=255, verbose_name="Full Name"), ), ( "description", models.TextField( help_text="Description of the project", null=True, verbose_name="Description", blank=True, ), ), ( "avatar_url", models.URLField(null=True, verbose_name="Owner avatar image URL", blank=True), ), ( "ssh_url", models.URLField( blank=True, max_length=512, verbose_name="SSH URL", validators=[django.core.validators.URLValidator(schemes=[b"ssh"])], ), ), ( "clone_url", models.URLField( blank=True, max_length=512, verbose_name="Repository clone URL", validators=[ django.core.validators.URLValidator( schemes=[b"http", b"https", b"ssh", b"git", b"svn"] ) ], ), ), ( "html_url", models.URLField(null=True, verbose_name="HTML URL", blank=True), ), ( "private", models.BooleanField(default=False, verbose_name="Private repository"), ), ( "admin", models.BooleanField(default=False, verbose_name="Has admin privilege"), ), ( "vcs", models.CharField( blank=True, max_length=200, verbose_name="vcs", choices=[ (b"git", "Git"), (b"svn", "Subversion"), (b"hg", "Mercurial"), (b"bzr", "Bazaar"), ], ), ), ( "source", models.CharField( max_length=16, verbose_name="Repository source", choices=[(b"github", "GitHub"), (b"bitbucket", "Bitbucket")], ), ), ("json", models.TextField(verbose_name="Serialized API response")), ( "organization", models.ForeignKey( related_name="repositories", verbose_name="Organization", blank=True, to="oauth.RemoteOrganization", null=True, on_delete=models.CASCADE, ), ), ( "users", models.ManyToManyField( related_name="oauth_repositories", verbose_name="Users", to=settings.AUTH_USER_MODEL, ), ), ], options={ "ordering": ["organization__name", "name"], "verbose_name_plural": "remote repositories", }, ), ]
Migration
python
celery__celery
celery/contrib/abortable.py
{ "start": 2704, "end": 3682 }
class ____(AsyncResult): """Represents an abortable result. Specifically, this gives the `AsyncResult` a :meth:`abort()` method, that sets the state of the underlying Task to `'ABORTED'`. """ def is_aborted(self): """Return :const:`True` if the task is (being) aborted.""" return self.state == ABORTED def abort(self): """Set the state of the task to :const:`ABORTED`. Abortable tasks monitor their state at regular intervals and terminate execution if so. Warning: Be aware that invoking this method does not guarantee when the task will be aborted (or even if the task will be aborted at all). """ # TODO: store_result requires all four arguments to be set, # but only state should be updated here return self.backend.store_result(self.id, result=None, state=ABORTED, traceback=None)
AbortableAsyncResult
python
getsentry__sentry
src/sentry/sentry_metrics/indexer/cache.py
{ "start": 1592, "end": 8651 }
class ____: def __init__(self, cache_name: str, partition_key: str): self.version = 1 self.cache = caches[cache_name] self.partition_key = partition_key @property def randomized_ttl(self) -> int: # introduce jitter in the cache_ttl so that when we have large # amount of new keys written into the cache, they don't expire all at once cache_ttl = settings.SENTRY_METRICS_INDEXER_CACHE_TTL jitter = random.uniform(0, 0.25) * cache_ttl return int(cache_ttl + jitter) def _make_cache_key(self, key: str) -> str: use_case_id, org_id, string = key.split(":", 2) org_string = org_id + ":" + string hashed = md5_text(org_string).hexdigest() return f"indexer:{self.partition_key}:org:str:{use_case_id}:{hashed}" # The new namespaced version of the above function, eventually this will replace # _make_cache_key def _make_namespaced_cache_key(self, namespace: str, key: str) -> str: use_case_id, org_id, string = key.split(":", 2) org_string = f"{org_id}:{string}" hashed = md5_text(org_string).hexdigest() return f"indexer:{self.partition_key}:{namespace}:org:str:{use_case_id}:{hashed}" def _make_cache_val(self, val: int, timestamp: int) -> str: return f"{val}:{timestamp}" def _format_results( self, keys: Iterable[str], results: Mapping[str, int | None] ) -> MutableMapping[str, int | None]: """ Takes in keys formatted like "use_case_id:org_id:string", and results that have the internally used hashed key such as: {"indexer:org:str:transactions:b0a0e436f6fa42b9e33e73befbdbb9ba": 2} and returns results that replace the hashed internal key with the externally used key: {"transactions:3:a": 2} """ formatted: MutableMapping[str, int | None] = {} for key in keys: cache_key = self._make_cache_key(key) formatted[key] = results.get(cache_key) return formatted # The new namespaced version of the above function, eventually this will replace # _format_results def _format_namespaced_results( self, namespace: str, keys: Iterable[str], results: Mapping[str, int | None] ) -> MutableMapping[str, int | None]: """ Takes in keys formatted like "use_case_id:org_id:string", and results that have the internally used hashed key such as: {"indexer:org:str:transactions:b0a0e436f6fa42b9e33e73befbdbb9ba": 2} and returns results that replace the hashed internal key with the externally used key: {"transactions:3:a": 2} """ formatted: MutableMapping[str, int | None] = {} for key in keys: cache_key = self._make_namespaced_cache_key(namespace, key) formatted[key] = results.get(cache_key) return formatted def _is_valid_timestamp(self, timestamp: str) -> bool: return int(timestamp) >= int((datetime.now(UTC) - timedelta(hours=3)).timestamp()) def _validate_result(self, result: str | None) -> int | None: if result is None: return None result, timestamp = result.split(":") if not self._is_valid_timestamp(timestamp): metrics.incr(_INDEXER_CACHE_STALE_KEYS_METRIC) return None return int(result) def get(self, namespace: str, key: str) -> int | None: if options.get(NAMESPACED_READ_FEAT_FLAG): metrics.incr(_INDEXER_CACHE_DOUBLE_READ_METRIC) result = self.cache.get( self._make_namespaced_cache_key(namespace, key), version=self.version ) return self._validate_result(result) return self.cache.get(self._make_cache_key(key), version=self.version) def set(self, namespace: str, key: str, value: int) -> None: self.cache.set( key=self._make_cache_key(key), value=value, timeout=self.randomized_ttl, version=self.version, ) if options.get(NAMESPACED_WRITE_FEAT_FLAG): metrics.incr(_INDEXER_CACHE_DOUBLE_WRITE_METRIC) self.cache.set( key=self._make_namespaced_cache_key(namespace, key), value=self._make_cache_val(value, int(datetime.now(UTC).timestamp())), timeout=self.randomized_ttl, version=self.version, ) def get_many(self, namespace: str, keys: Iterable[str]) -> MutableMapping[str, int | None]: if options.get(NAMESPACED_READ_FEAT_FLAG): metrics.incr(_INDEXER_CACHE_DOUBLE_READ_METRIC) cache_keys = {self._make_namespaced_cache_key(namespace, key): key for key in keys} namespaced_results: MutableMapping[str, int | None] = { k: self._validate_result(v) for k, v in self.cache.get_many(cache_keys.keys(), version=self.version).items() } return self._format_namespaced_results( namespace, keys, namespaced_results, ) else: cache_keys = {self._make_cache_key(key): key for key in keys} results: Mapping[str, int | None] = self.cache.get_many( cache_keys.keys(), version=self.version ) return self._format_results(keys, results) def set_many(self, namespace: str, key_values: Mapping[str, int]) -> None: cache_key_values = {self._make_cache_key(k): v for k, v in key_values.items()} self.cache.set_many(cache_key_values, timeout=self.randomized_ttl, version=self.version) if options.get(NAMESPACED_WRITE_FEAT_FLAG): metrics.incr(_INDEXER_CACHE_DOUBLE_WRITE_METRIC) timestamp = int(datetime.now(UTC).timestamp()) namespaced_cache_key_values = { self._make_namespaced_cache_key(namespace, k): self._make_cache_val(v, timestamp) for k, v in key_values.items() } self.cache.set_many( namespaced_cache_key_values, timeout=self.randomized_ttl, version=self.version ) def delete(self, namespace: str, key: str) -> None: self.cache.delete(self._make_cache_key(key), version=self.version) if options.get(NAMESPACED_WRITE_FEAT_FLAG): metrics.incr(_INDEXER_CACHE_DOUBLE_WRITE_METRIC) self.cache.delete(self._make_namespaced_cache_key(namespace, key), version=self.version) def delete_many(self, namespace: str, keys: Sequence[str]) -> None: self.cache.delete_many([self._make_cache_key(key) for key in keys], version=self.version) if options.get(NAMESPACED_WRITE_FEAT_FLAG): metrics.incr(_INDEXER_CACHE_DOUBLE_WRITE_METRIC) self.cache.delete_many( [self._make_namespaced_cache_key(namespace, key) for key in keys], version=self.version, )
StringIndexerCache
python
google__pytype
pytype/tests/test_reingest2.py
{ "start": 79, "end": 1274 }
class ____(test_base.BaseTest): """Tests for reloading the pyi we generate.""" def test_type_parameter_bound(self): foo = """ from typing import TypeVar T = TypeVar("T", bound=float) def f(x: T) -> T: return x """ with self.DepTree([("foo.py", foo)]): errors = self.CheckWithErrors(""" import foo foo.f("") # wrong-arg-types[e] """) self.assertErrorRegexes(errors, {"e": r"float.*str"}) def test_default_argument_type(self): foo = """ from typing import Any, Callable, TypeVar T = TypeVar("T") def f(x): return True def g(x: Callable[[T], Any]) -> T: ... """ with self.DepTree([("foo.py", foo)]): self.Check(""" import foo foo.g(foo.f).upper() """) def test_duplicate_anystr_import(self): dep1 = """ from typing import AnyStr def f(x: AnyStr) -> AnyStr: return x """ dep2 = """ from typing import AnyStr from dep1 import f def g(x: AnyStr) -> AnyStr: return x """ deps = [("dep1.py", dep1), ("dep2.py", dep2)] with self.DepTree(deps): self.Check("import dep2")
ReingestTest
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/errors.py
{ "start": 6679, "end": 6861 }
class ____(HypothesisWarning): """SearchStrategy.example() is designed for interactive use, but should never be used in the body of a test. """
NonInteractiveExampleWarning
python
streamlit__streamlit
lib/streamlit/runtime/metrics_util.py
{ "start": 7146, "end": 17844 }
class ____: _instance_lock = threading.Lock() _instance: Installation | None = None @classmethod def instance(cls) -> Installation: """Returns the singleton Installation.""" # We use a double-checked locking optimization to avoid the overhead # of acquiring the lock in the common case: # https://en.wikipedia.org/wiki/Double-checked_locking if cls._instance is None: with cls._instance_lock: if cls._instance is None: cls._instance = Installation() return cls._instance def __init__(self) -> None: self.installation_id_v3 = str( uuid.uuid5(uuid.NAMESPACE_DNS, _get_machine_id_v3()) ) self.installation_id_v4 = _get_machine_id_v4() def __repr__(self) -> str: return util.repr_(self) @property def installation_id(self) -> str: return self.installation_id_v3 def _get_type_name(obj: object) -> str: """Get a simplified name for the type of the given object.""" with contextlib.suppress(Exception): obj_type = obj if inspect.isclass(obj) else type(obj) type_name = "unknown" if hasattr(obj_type, "__qualname__"): type_name = obj_type.__qualname__ elif hasattr(obj_type, "__name__"): type_name = obj_type.__name__ if obj_type.__module__ != "builtins": # Add the full module path type_name = f"{obj_type.__module__}.{type_name}" if type_name in _OBJECT_NAME_MAPPING: type_name = _OBJECT_NAME_MAPPING[type_name] return type_name return "failed" def _get_top_level_module(func: Callable[..., Any]) -> str: """Get the top level module for the given function.""" module = inspect.getmodule(func) if module is None or not module.__name__: return "unknown" return module.__name__.split(".")[0] def _get_arg_metadata(arg: object) -> str | None: """Get metadata information related to the value of the given object.""" with contextlib.suppress(Exception): if isinstance(arg, (bool)): return f"val:{arg}" if isinstance(arg, Sized): return f"len:{len(arg)}" return None def _get_command_telemetry( _command_func: Callable[..., Any], _command_name: str, *args: Any, **kwargs: Any ) -> Command: """Get telemetry information for the given callable and its arguments.""" arg_keywords = inspect.getfullargspec(_command_func).args self_arg: Any | None = None arguments: list[Argument] = [] is_method = inspect.ismethod(_command_func) name = _command_name for i, arg in enumerate(args): pos = i if is_method: # If func is a method, ignore the first argument (self) i = i + 1 # noqa: PLW2901 keyword = arg_keywords[i] if len(arg_keywords) > i else f"{i}" if keyword == "self": self_arg = arg continue argument = Argument(k=keyword, t=_get_type_name(arg), p=pos) arg_metadata = _get_arg_metadata(arg) if arg_metadata: argument.m = arg_metadata arguments.append(argument) for kwarg, kwarg_value in kwargs.items(): argument = Argument(k=kwarg, t=_get_type_name(kwarg_value)) arg_metadata = _get_arg_metadata(kwarg_value) if arg_metadata: argument.m = arg_metadata arguments.append(argument) top_level_module = _get_top_level_module(_command_func) if top_level_module != "streamlit": # If the gather_metrics decorator is used outside of streamlit library # we enforce a prefix to be added to the tracked command: name = f"external:{top_level_module}:{name}" if ( name == "create_instance" and self_arg and hasattr(self_arg, "name") and self_arg.name ): name = f"component:{self_arg.name}" if name == "_bidi_component" and len(args) > 1 and isinstance(args[1], str): # Bound DeltaGenerator methods always receive `self` as args[0], so args[1] # is the user-supplied component name. component_name = args[1] name = f"component_v2:{component_name}" return Command(name=name, args=arguments) def to_microseconds(seconds: float) -> int: """Convert seconds into microseconds.""" return int(seconds * 1_000_000) F = TypeVar("F", bound=Callable[..., Any]) @overload def gather_metrics( name: str, func: F, ) -> F: ... @overload def gather_metrics( name: str, func: None = None, ) -> Callable[[F], F]: ... def gather_metrics(name: str, func: F | None = None) -> Callable[[F], F] | F: """Function decorator to add telemetry tracking to commands. Parameters ---------- func : callable The function to track for telemetry. name : str or None Overwrite the function name with a custom name that is used for telemetry tracking. Example ------- >>> @st.gather_metrics ... def my_command(url): ... return url >>> @st.gather_metrics(name="custom_name") ... def my_command(url): ... return url """ if not name: _LOGGER.warning("gather_metrics: name is empty") name = "undefined" if func is None: # Support passing the params via function decorator def wrapper(f: F) -> F: return gather_metrics( name=name, func=f, ) return wrapper # To make mypy type narrow F | None -> F non_optional_func = func @wraps(non_optional_func) def wrapped_func(*args: Any, **kwargs: Any) -> Any: from timeit import default_timer as timer exec_start = timer() ctx = get_script_run_ctx(suppress_warning=True) tracking_activated = ( ctx is not None and ctx.gather_usage_stats and not ctx.command_tracking_deactivated and len(ctx.tracked_commands) < _MAX_TRACKED_COMMANDS # Prevent too much memory usage ) command_telemetry: Command | None = None # This flag is needed to make sure that only the command (the outermost command) # that deactivated tracking (via ctx.command_tracking_deactivated) is able to reset it # again. This is important to prevent nested commands from reactivating tracking. # At this point, we don't know yet if the command will deactivated tracking. has_set_command_tracking_deactivated = False if ctx and tracking_activated: try: command_telemetry = _get_command_telemetry( non_optional_func, name, *args, **kwargs ) if ( command_telemetry.name not in ctx.tracked_commands_counter or ctx.tracked_commands_counter[command_telemetry.name] < _MAX_TRACKED_PER_COMMAND ): ctx.tracked_commands.append(command_telemetry) ctx.tracked_commands_counter.update([command_telemetry.name]) # Deactivate tracking to prevent calls inside already tracked commands ctx.command_tracking_deactivated = True # The ctx.command_tracking_deactivated flag was set to True, # we also need to set has_set_command_tracking_deactivated to True # to make sure that this command is able to reset it again. has_set_command_tracking_deactivated = True except Exception as ex: # Always capture all exceptions since we want to make sure that # the telemetry never causes any issues. _LOGGER.debug("Failed to collect command telemetry", exc_info=ex) try: result = non_optional_func(*args, **kwargs) except RerunException: # Duplicated from below, because static analysis tools get confused # by deferring the rethrow. if tracking_activated and command_telemetry: command_telemetry.time = to_microseconds(timer() - exec_start) raise finally: # Activate tracking again if command executes without any exceptions # we only want to do that if this command has set the # flag to deactivate tracking. if ctx and has_set_command_tracking_deactivated: ctx.command_tracking_deactivated = False if tracking_activated and command_telemetry: # Set the execution time to the measured value command_telemetry.time = to_microseconds(timer() - exec_start) return result with contextlib.suppress(AttributeError): # Make this a well-behaved decorator by preserving important function # attributes. wrapped_func.__dict__.update(non_optional_func.__dict__) wrapped_func.__signature__ = inspect.signature(non_optional_func) # type: ignore return cast("F", wrapped_func) def create_page_profile_message( commands: list[Command], exec_time: int, prep_time: int, uncaught_exception: str | None = None, ) -> ForwardMsg: """Create and return the full PageProfile ForwardMsg.""" msg = ForwardMsg() page_profile = msg.page_profile page_profile.commands.extend(commands) page_profile.exec_time = exec_time page_profile.prep_time = prep_time page_profile.headless = config.get_option("server.headless") # Collect all config options that have been manually set config_options: set[str] = set() if config._config_options: for option_name in config._config_options: if not config.is_manually_set(option_name): # We only care about manually defined options continue config_option = config._config_options[option_name] config_options.add( f"{option_name}:default" if config_option.is_default else option_name ) page_profile.config.extend(config_options) # Check the predefined set of modules for attribution attributions: set[str] = { attribution for attribution in _ATTRIBUTIONS_TO_CHECK if attribution in sys.modules } page_profile.os = str(sys.platform) page_profile.timezone = str(time.tzname) page_profile.attributions.extend(attributions) if uncaught_exception: page_profile.uncaught_exception = uncaught_exception if ctx := get_script_run_ctx(): page_profile.is_fragment_run = bool(ctx.fragment_ids_this_run) return msg
Installation
python
Textualize__textual
src/textual/_log.py
{ "start": 298, "end": 436 }
class ____(Enum): """Tags log messages as being verbose and potentially excluded from output.""" NORMAL = 0 HIGH = 1
LogVerbosity
python
django__django
tests/select_related_regress/models.py
{ "start": 2813, "end": 2876 }
class ____(Base): b_field = models.CharField(max_length=10)
B
python
kamyu104__LeetCode-Solutions
Python/sort-integers-by-the-power-value.py
{ "start": 1823, "end": 2426 }
class ____(object): dp = {} def getKth(self, lo, hi, k): """ :type lo: int :type hi: int :type k: int :rtype: int """ def power_value(x): y, result = x, 0 while x > 1 and x not in Solution2.dp: result += 1 if x%2: x = 3*x + 1 else: x //= 2 Solution2.dp[y] = result + (Solution2.dp[x] if x > 1 else 0) return Solution2.dp[y], y return sorted(range(lo, hi+1), key=power_value)[k-1]
Solution2
python
docker__docker-py
docker/types/services.py
{ "start": 21230, "end": 23000 }
class ____(dict): """ Describes properties to access and load-balance a service. Args: mode (string): The mode of resolution to use for internal load balancing between tasks (``'vip'`` or ``'dnsrr'``). Defaults to ``'vip'`` if not provided. ports (dict): Exposed ports that this service is accessible on from the outside, in the form of ``{ published_port: target_port }`` or ``{ published_port: <port_config_tuple> }``. Port config tuple format is ``(target_port [, protocol [, publish_mode]])``. Ports can only be provided if the ``vip`` resolution mode is used. """ def __init__(self, mode=None, ports=None): if ports: self['Ports'] = convert_service_ports(ports) if mode: self['Mode'] = mode def convert_service_ports(ports): if isinstance(ports, list): return ports if not isinstance(ports, dict): raise TypeError( 'Invalid type for ports, expected dict or list' ) result = [] for k, v in ports.items(): port_spec = { 'Protocol': 'tcp', 'PublishedPort': k } if isinstance(v, tuple): port_spec['TargetPort'] = v[0] if len(v) >= 2 and v[1] is not None: port_spec['Protocol'] = v[1] if len(v) == 3: port_spec['PublishMode'] = v[2] if len(v) > 3: raise ValueError( 'Service port configuration can have at most 3 elements: ' '(target_port, protocol, mode)' ) else: port_spec['TargetPort'] = v result.append(port_spec) return result
EndpointSpec
python
pandas-dev__pandas
pandas/tests/indexing/test_categorical.py
{ "start": 807, "end": 20439 }
class ____: def test_loc_scalar(self, df): dtype = CategoricalDtype(list("cab")) result = df.loc["a"] bidx = Series(list("aaa"), name="B").astype(dtype) assert bidx.dtype == dtype expected = DataFrame({"A": [0, 1, 5]}, index=Index(bidx)) tm.assert_frame_equal(result, expected) df = df.copy() df.loc["a"] = 20 bidx2 = Series(list("aabbca"), name="B").astype(dtype) assert bidx2.dtype == dtype expected = DataFrame( { "A": [20, 20, 2, 3, 4, 20], }, index=Index(bidx2), ) tm.assert_frame_equal(df, expected) # value not in the categories with pytest.raises(KeyError, match=r"^'d'$"): df.loc["d"] df2 = df.copy() expected = df2.copy() expected.index = expected.index.astype(object) expected.loc["d"] = 10 df2.loc["d"] = 10 tm.assert_frame_equal(df2, expected) def test_loc_setitem_with_expansion_non_category(self, df): # Setting-with-expansion with a new key "d" that is not among caegories df.loc["a"] = 20 # Setting a new row on an existing column df3 = df.copy() df3.loc["d", "A"] = 10 bidx3 = Index(list("aabbcad"), name="B") expected3 = DataFrame( { "A": [20, 20, 2, 3, 4, 20, 10.0], }, index=Index(bidx3), ) tm.assert_frame_equal(df3, expected3) # Setting a new row _and_ new column df4 = df.copy() df4.loc["d", "C"] = 10 expected3 = DataFrame( { "A": [20, 20, 2, 3, 4, 20, np.nan], "C": [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 10], }, index=Index(bidx3), ) tm.assert_frame_equal(df4, expected3) def test_loc_getitem_scalar_non_category(self, df): with pytest.raises(KeyError, match="^1$"): df.loc[1] def test_slicing(self): cat = Series(Categorical([1, 2, 3, 4])) reverse = cat[::-1] exp = np.array([4, 3, 2, 1], dtype=np.int64) tm.assert_numpy_array_equal(reverse.__array__(), exp) df = DataFrame({"value": (np.arange(100) + 1).astype("int64")}) df["D"] = pd.cut(df.value, bins=[0, 25, 50, 75, 100]) expected = Series([11, Interval(0, 25)], index=["value", "D"], name=10) result = df.iloc[10] tm.assert_series_equal(result, expected) expected = DataFrame( {"value": np.arange(11, 21).astype("int64")}, index=np.arange(10, 20).astype("int64"), ) expected["D"] = pd.cut(expected.value, bins=[0, 25, 50, 75, 100]) result = df.iloc[10:20] tm.assert_frame_equal(result, expected) expected = Series([9, Interval(0, 25)], index=["value", "D"], name=8) result = df.loc[8] tm.assert_series_equal(result, expected) def test_slicing_and_getting_ops(self): # systematically test the slicing operations: # for all slicing ops: # - returning a dataframe # - returning a column # - returning a row # - returning a single value cats = Categorical( ["a", "c", "b", "c", "c", "c", "c"], categories=["a", "b", "c"] ) idx = Index(["h", "i", "j", "k", "l", "m", "n"]) values = [1, 2, 3, 4, 5, 6, 7] df = DataFrame({"cats": cats, "values": values}, index=idx) # the expected values cats2 = Categorical(["b", "c"], categories=["a", "b", "c"]) idx2 = Index(["j", "k"]) values2 = [3, 4] # 2:4,: | "j":"k",: exp_df = DataFrame({"cats": cats2, "values": values2}, index=idx2) # :,"cats" | :,0 exp_col = Series(cats, index=idx, name="cats") # "j",: | 2,: exp_row = Series(["b", 3], index=["cats", "values"], dtype="object", name="j") # "j","cats | 2,0 exp_val = "b" # iloc # frame res_df = df.iloc[2:4, :] tm.assert_frame_equal(res_df, exp_df) assert isinstance(res_df["cats"].dtype, CategoricalDtype) # row res_row = df.iloc[2, :] tm.assert_series_equal(res_row, exp_row) assert isinstance(res_row["cats"], str) # col res_col = df.iloc[:, 0] tm.assert_series_equal(res_col, exp_col) assert isinstance(res_col.dtype, CategoricalDtype) # single value res_val = df.iloc[2, 0] assert res_val == exp_val # loc # frame res_df = df.loc["j":"k", :] tm.assert_frame_equal(res_df, exp_df) assert isinstance(res_df["cats"].dtype, CategoricalDtype) # row res_row = df.loc["j", :] tm.assert_series_equal(res_row, exp_row) assert isinstance(res_row["cats"], str) # col res_col = df.loc[:, "cats"] tm.assert_series_equal(res_col, exp_col) assert isinstance(res_col.dtype, CategoricalDtype) # single value res_val = df.loc["j", "cats"] assert res_val == exp_val # single value res_val = df.loc["j", df.columns[0]] assert res_val == exp_val # iat res_val = df.iat[2, 0] assert res_val == exp_val # at res_val = df.at["j", "cats"] assert res_val == exp_val # fancy indexing exp_fancy = df.iloc[[2]] res_fancy = df[df["cats"] == "b"] tm.assert_frame_equal(res_fancy, exp_fancy) res_fancy = df[df["values"] == 3] tm.assert_frame_equal(res_fancy, exp_fancy) # get_value res_val = df.at["j", "cats"] assert res_val == exp_val # i : int, slice, or sequence of integers res_row = df.iloc[2] tm.assert_series_equal(res_row, exp_row) assert isinstance(res_row["cats"], str) res_df = df.iloc[slice(2, 4)] tm.assert_frame_equal(res_df, exp_df) assert isinstance(res_df["cats"].dtype, CategoricalDtype) res_df = df.iloc[[2, 3]] tm.assert_frame_equal(res_df, exp_df) assert isinstance(res_df["cats"].dtype, CategoricalDtype) res_col = df.iloc[:, 0] tm.assert_series_equal(res_col, exp_col) assert isinstance(res_col.dtype, CategoricalDtype) res_df = df.iloc[:, slice(0, 2)] tm.assert_frame_equal(res_df, df) assert isinstance(res_df["cats"].dtype, CategoricalDtype) res_df = df.iloc[:, [0, 1]] tm.assert_frame_equal(res_df, df) assert isinstance(res_df["cats"].dtype, CategoricalDtype) def test_slicing_doc_examples(self): # GH 7918 cats = Categorical( ["a", "b", "b", "b", "c", "c", "c"], categories=["a", "b", "c"] ) idx = Index(["h", "i", "j", "k", "l", "m", "n"]) values = [1, 2, 2, 2, 3, 4, 5] df = DataFrame({"cats": cats, "values": values}, index=idx) result = df.iloc[2:4, :] expected = DataFrame( { "cats": Categorical(["b", "b"], categories=["a", "b", "c"]), "values": [2, 2], }, index=["j", "k"], ) tm.assert_frame_equal(result, expected) result = df.iloc[2:4, :].dtypes expected = Series(["category", "int64"], ["cats", "values"], dtype=object) tm.assert_series_equal(result, expected) result = df.loc["h":"j", "cats"] expected = Series( Categorical(["a", "b", "b"], categories=["a", "b", "c"]), index=["h", "i", "j"], name="cats", ) tm.assert_series_equal(result, expected) result = df.loc["h":"j", df.columns[0:1]] expected = DataFrame( {"cats": Categorical(["a", "b", "b"], categories=["a", "b", "c"])}, index=["h", "i", "j"], ) tm.assert_frame_equal(result, expected) def test_loc_getitem_listlike_labels(self, df): # list of labels result = df.loc[["c", "a"]] expected = df.iloc[[4, 0, 1, 5]] tm.assert_frame_equal(result, expected, check_index_type=True) def test_loc_getitem_listlike_unused_category(self, df2): # GH#37901 a label that is in index.categories but not in index # listlike containing an element in the categories but not in the values with pytest.raises(KeyError, match=re.escape("['e'] not in index")): df2.loc[["a", "b", "e"]] def test_loc_getitem_label_unused_category(self, df2): # element in the categories but not in the values with pytest.raises(KeyError, match=r"^'e'$"): df2.loc["e"] def test_loc_getitem_non_category(self, df2): # not all labels in the categories with pytest.raises(KeyError, match=re.escape("['d'] not in index")): df2.loc[["a", "d"]] def test_loc_setitem_expansion_label_unused_category(self, df2): # assigning with a label that is in the categories but not in the index df = df2.copy() df.loc["e"] = 20 result = df.loc[["a", "b", "e"]] exp_index = CategoricalIndex(list("aaabbe"), categories=list("cabe"), name="B") expected = DataFrame({"A": [0, 1, 5, 2, 3, 20]}, index=exp_index) tm.assert_frame_equal(result, expected) def test_loc_listlike_dtypes(self): # GH 11586 # unique categories and codes index = CategoricalIndex(["a", "b", "c"]) df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index) # unique slice res = df.loc[["a", "b"]] exp_index = CategoricalIndex(["a", "b"], categories=index.categories) exp = DataFrame({"A": [1, 2], "B": [4, 5]}, index=exp_index) tm.assert_frame_equal(res, exp, check_index_type=True) # duplicated slice res = df.loc[["a", "a", "b"]] exp_index = CategoricalIndex(["a", "a", "b"], categories=index.categories) exp = DataFrame({"A": [1, 1, 2], "B": [4, 4, 5]}, index=exp_index) tm.assert_frame_equal(res, exp, check_index_type=True) with pytest.raises(KeyError, match=re.escape("['x'] not in index")): df.loc[["a", "x"]] def test_loc_listlike_dtypes_duplicated_categories_and_codes(self): # duplicated categories and codes index = CategoricalIndex(["a", "b", "a"]) df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index) # unique slice res = df.loc[["a", "b"]] exp = DataFrame( {"A": [1, 3, 2], "B": [4, 6, 5]}, index=CategoricalIndex(["a", "a", "b"]) ) tm.assert_frame_equal(res, exp, check_index_type=True) # duplicated slice res = df.loc[["a", "a", "b"]] exp = DataFrame( {"A": [1, 3, 1, 3, 2], "B": [4, 6, 4, 6, 5]}, index=CategoricalIndex(["a", "a", "a", "a", "b"]), ) tm.assert_frame_equal(res, exp, check_index_type=True) with pytest.raises(KeyError, match=re.escape("['x'] not in index")): df.loc[["a", "x"]] def test_loc_listlike_dtypes_unused_category(self): # contains unused category index = CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde")) df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=index) res = df.loc[["a", "b"]] exp = DataFrame( {"A": [1, 3, 2], "B": [5, 7, 6]}, index=CategoricalIndex(["a", "a", "b"], categories=list("abcde")), ) tm.assert_frame_equal(res, exp, check_index_type=True) # duplicated slice res = df.loc[["a", "a", "b"]] exp = DataFrame( {"A": [1, 3, 1, 3, 2], "B": [5, 7, 5, 7, 6]}, index=CategoricalIndex(["a", "a", "a", "a", "b"], categories=list("abcde")), ) tm.assert_frame_equal(res, exp, check_index_type=True) with pytest.raises(KeyError, match=re.escape("['x'] not in index")): df.loc[["a", "x"]] def test_loc_getitem_listlike_unused_category_raises_keyerror(self): # key that is an *unused* category raises index = CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde")) df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=index) with pytest.raises(KeyError, match="e"): # For comparison, check the scalar behavior df.loc["e"] with pytest.raises(KeyError, match=re.escape("['e'] not in index")): df.loc[["a", "e"]] def test_ix_categorical_index(self): # GH 12531 df = DataFrame( np.random.default_rng(2).standard_normal((3, 3)), index=list("ABC"), columns=list("XYZ"), ) cdf = df.copy() cdf.index = CategoricalIndex(df.index) cdf.columns = CategoricalIndex(df.columns) expect = Series(df.loc["A", :], index=cdf.columns, name="A") tm.assert_series_equal(cdf.loc["A", :], expect) expect = Series(df.loc[:, "X"], index=cdf.index, name="X") tm.assert_series_equal(cdf.loc[:, "X"], expect) exp_index = CategoricalIndex(list("AB"), categories=["A", "B", "C"]) expect = DataFrame(df.loc[["A", "B"], :], columns=cdf.columns, index=exp_index) tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect) exp_columns = CategoricalIndex(list("XY"), categories=["X", "Y", "Z"]) expect = DataFrame(df.loc[:, ["X", "Y"]], index=cdf.index, columns=exp_columns) tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect) @pytest.mark.parametrize( "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))] ) def test_ix_categorical_index_non_unique(self, infer_string): # non-unique with option_context("future.infer_string", infer_string): df = DataFrame( np.random.default_rng(2).standard_normal((3, 3)), index=list("ABA"), columns=list("XYX"), ) cdf = df.copy() cdf.index = CategoricalIndex(df.index) cdf.columns = CategoricalIndex(df.columns) exp_index = CategoricalIndex(list("AA"), categories=["A", "B"]) expect = DataFrame(df.loc["A", :], columns=cdf.columns, index=exp_index) tm.assert_frame_equal(cdf.loc["A", :], expect) exp_columns = CategoricalIndex(list("XX"), categories=["X", "Y"]) expect = DataFrame(df.loc[:, "X"], index=cdf.index, columns=exp_columns) tm.assert_frame_equal(cdf.loc[:, "X"], expect) expect = DataFrame( df.loc[["A", "B"], :], columns=cdf.columns, index=CategoricalIndex(list("AAB")), ) tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect) expect = DataFrame( df.loc[:, ["X", "Y"]], index=cdf.index, columns=CategoricalIndex(list("XXY")), ) tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect) def test_loc_slice(self, df): # GH9748 msg = ( "cannot do slice indexing on CategoricalIndex with these " r"indexers \[1\] of type int" ) with pytest.raises(TypeError, match=msg): df.loc[1:5] result = df.loc["b":"c"] expected = df.iloc[[2, 3, 4]] tm.assert_frame_equal(result, expected) def test_loc_and_at_with_categorical_index(self): # GH 20629 df = DataFrame( [[1, 2], [3, 4], [5, 6]], index=CategoricalIndex(["A", "B", "C"]) ) s = df[0] assert s.loc["A"] == 1 assert s.at["A"] == 1 assert df.loc["B", 1] == 4 assert df.at["B", 1] == 4 @pytest.mark.parametrize( "idx_values", [ # python types [1, 2, 3], [-1, -2, -3], [1.5, 2.5, 3.5], [-1.5, -2.5, -3.5], # numpy int/uint *(np.array([1, 2, 3], dtype=dtype) for dtype in tm.ALL_INT_NUMPY_DTYPES), # numpy floats *(np.array([1.5, 2.5, 3.5], dtype=dtyp) for dtyp in tm.FLOAT_NUMPY_DTYPES), # numpy object np.array([1, "b", 3.5], dtype=object), # pandas scalars [Interval(1, 4), Interval(4, 6), Interval(6, 9)], [Timestamp(2019, 1, 1), Timestamp(2019, 2, 1), Timestamp(2019, 3, 1)], [Timedelta(1, "D"), Timedelta(2, "D"), Timedelta(3, "D")], # pandas Integer arrays *(pd.array([1, 2, 3], dtype=dtype) for dtype in tm.ALL_INT_EA_DTYPES), # other pandas arrays pd.IntervalIndex.from_breaks([1, 4, 6, 9]).array, pd.date_range("2019-01-01", periods=3).array, pd.timedelta_range(start="1D", periods=3).array, ], ) def test_loc_getitem_with_non_string_categories(self, idx_values, ordered): # GH-17569 cat_idx = CategoricalIndex(idx_values, ordered=ordered) df = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx) sl = slice(idx_values[0], idx_values[1]) # scalar selection result = df.loc[idx_values[0]] expected = Series(["foo"], index=["A"], name=idx_values[0]) tm.assert_series_equal(result, expected) # list selection result = df.loc[idx_values[:2]] expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"]) tm.assert_frame_equal(result, expected) # slice selection result = df.loc[sl] expected = DataFrame(["foo", "bar"], index=cat_idx[:2], columns=["A"]) tm.assert_frame_equal(result, expected) # scalar assignment result = df.copy() result.loc[idx_values[0]] = "qux" expected = DataFrame({"A": ["qux", "bar", "baz"]}, index=cat_idx) tm.assert_frame_equal(result, expected) # list assignment result = df.copy() result.loc[idx_values[:2], "A"] = ["qux", "qux2"] expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx) tm.assert_frame_equal(result, expected) # slice assignment result = df.copy() result.loc[sl, "A"] = ["qux", "qux2"] expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx) tm.assert_frame_equal(result, expected) def test_getitem_categorical_with_nan(self): # GH#41933 ci = CategoricalIndex(["A", "B", np.nan]) ser = Series(range(3), index=ci) assert ser[np.nan] == 2 assert ser.loc[np.nan] == 2 df = DataFrame(ser) assert df.loc[np.nan, 0] == 2 assert df.loc[np.nan][0] == 2 def test_getitem_row_categorical_with_nan(self): # GH#58954 df = DataFrame({"a": [1, 2], "b": CategoricalIndex([1, None])}) res = df.iloc[1] expected = Series([2, np.nan], index=df.columns, name=1) tm.assert_series_equal(res, expected) res = df.loc[1] tm.assert_series_equal(res, expected) def test_getitem_row_categorical_with_nan_bool(self): # GH#58954 df = DataFrame({"a": [True, False], "b": CategoricalIndex([False, None])}) res = df.iloc[1] expected = Series([False, np.nan], index=df.columns, dtype=object, name=1) tm.assert_series_equal(res, expected) res = df.loc[1] tm.assert_series_equal(res, expected)
TestCategoricalIndex
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/test_basic_configuration.py
{ "start": 2763, "end": 2965 }
class ____(SimpleTestCase): @given(integers()) def test_that_doesnt_need_db(self, z: int): company = Company(name="Company-" + str(z)) assert company.name.endswith(str(z))
TestSimple
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_qt.py
{ "start": 41924, "end": 44466 }
class ____(ToolContainerBase, QtWidgets.QToolBar): def __init__(self, toolmanager, parent=None): ToolContainerBase.__init__(self, toolmanager) QtWidgets.QToolBar.__init__(self, parent) self.setAllowedAreas(QtCore.Qt.ToolBarArea( _to_int(QtCore.Qt.ToolBarArea.TopToolBarArea) | _to_int(QtCore.Qt.ToolBarArea.BottomToolBarArea))) message_label = QtWidgets.QLabel("") message_label.setAlignment(QtCore.Qt.AlignmentFlag( _to_int(QtCore.Qt.AlignmentFlag.AlignRight) | _to_int(QtCore.Qt.AlignmentFlag.AlignVCenter))) message_label.setSizePolicy(QtWidgets.QSizePolicy( QtWidgets.QSizePolicy.Policy.Expanding, QtWidgets.QSizePolicy.Policy.Ignored, )) self._message_action = self.addWidget(message_label) self._toolitems = {} self._groups = {} def add_toolitem( self, name, group, position, image_file, description, toggle): button = QtWidgets.QToolButton(self) if image_file: button.setIcon(NavigationToolbar2QT._icon(self, image_file)) button.setText(name) if description: button.setToolTip(description) def handler(): self.trigger_tool(name) if toggle: button.setCheckable(True) button.toggled.connect(handler) else: button.clicked.connect(handler) self._toolitems.setdefault(name, []) self._add_to_group(group, name, button, position) self._toolitems[name].append((button, handler)) def _add_to_group(self, group, name, button, position): gr = self._groups.get(group, []) if not gr: sep = self.insertSeparator(self._message_action) gr.append(sep) before = gr[position] widget = self.insertWidget(before, button) gr.insert(position, widget) self._groups[group] = gr def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for button, handler in self._toolitems[name]: button.toggled.disconnect(handler) button.setChecked(toggled) button.toggled.connect(handler) def remove_toolitem(self, name): for button, handler in self._toolitems.pop(name, []): button.setParent(None) def set_message(self, s): self.widgetForAction(self._message_action).setText(s) @backend_tools._register_tool_class(FigureCanvasQT)
ToolbarQt
python
django__django
tests/user_commands/management/commands/no_system_checks.py
{ "start": 54, "end": 168 }
class ____(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): pass
Command
python
streamlit__streamlit
lib/streamlit/git_util.py
{ "start": 2102, "end": 6516 }
class ____: repo: Repo | None def __init__(self, path: str) -> None: # If we have a valid repo, git_version will be a tuple # of 3+ ints: (major, minor, patch, possible_additional_patch_number) self.git_version: tuple[int, ...] | None = None self.module: str = "" try: import git self.repo = git.Repo(path, search_parent_directories=True) self.git_version = self.repo.git.version_info if self.git_version is not None and self.git_version >= _MIN_GIT_VERSION: git_root = self.repo.git.rev_parse("--show-toplevel") self.module = str(os.path.relpath(path, git_root)) except Exception: _LOGGER.debug( "Did not find a git repo at %s. This is expected if this isn't a git repo, but could " "also fail for other reasons: " "1) git binary or GitPython not installed " "2) No .git folder " "3) Corrupted .git folder " "4) Path is invalid.", path, exc_info=True, ) self.repo = None def __repr__(self) -> str: return util.repr_(self) def is_valid(self) -> bool: """True if there's a git repo here, and git.version >= _MIN_GIT_VERSION.""" return ( self.repo is not None and self.git_version is not None and self.git_version >= _MIN_GIT_VERSION ) @property def tracking_branch(self) -> RemoteReference | None: if self.repo is None or not self.is_valid(): return None if self.is_head_detached: return None return self.repo.active_branch.tracking_branch() @property def untracked_files(self) -> list[str] | None: if self.repo is None or not self.is_valid(): return None return self.repo.untracked_files @property def is_head_detached(self) -> bool: if self.repo is None or not self.is_valid(): return False return self.repo.head.is_detached @property def uncommitted_files(self) -> list[str] | None: if self.repo is None or not self.is_valid(): return None return [cast("str", item.a_path) for item in self.repo.index.diff(None)] @property def ahead_commits(self) -> list[Commit] | None: if self.repo is None or not self.is_valid(): return None try: tracking_branch_info = self.get_tracking_branch_remote() if tracking_branch_info is None: return None remote, branch_name = tracking_branch_info remote_branch = f"{remote.name}/{branch_name}" return list(self.repo.iter_commits(f"{remote_branch}..{branch_name}")) except Exception: return [] def get_tracking_branch_remote(self) -> tuple[Remote, str] | None: if self.repo is None or not self.is_valid(): return None tracking_branch = self.tracking_branch if tracking_branch is None: return None remote_name, *branch = tracking_branch.name.split("/") branch_name = "/".join(branch) try: return self.repo.remote(remote_name), branch_name except Exception: _LOGGER.debug("Failed to resolve remote %s", remote_name, exc_info=True) return None def get_repo_info(self) -> tuple[str, str, str] | None: if not self.is_valid(): _LOGGER.debug( "No valid git information found. Git version: %s", self.git_version ) return None remote_info = self.get_tracking_branch_remote() if remote_info is None: _LOGGER.debug("No tracking remote branch found for the git repo.") return None remote, branch = remote_info remote_urls = list(remote.urls) repo = None for url in remote_urls: repo = _extract_github_repo_from_url(url) if repo is not None: break if repo is None: _LOGGER.debug( "Unable to determine repo name from configured remote URLs. URLs: %s", remote_urls, ) return None return repo, branch, self.module
GitRepo
python
cython__cython
Cython/Compiler/Tests/TestParseTreeTransforms.py
{ "start": 289, "end": 2282 }
class ____(TransformTest): def test_parserbehaviour_is_what_we_coded_for(self): t = self.fragment("if x: y").root self.assertLines(""" (root): StatListNode stats[0]: IfStatNode if_clauses[0]: IfClauseNode condition: NameNode body: ExprStatNode expr: NameNode """, self.treetypes(t)) def test_wrap_singlestat(self): t = self.run_pipeline([NormalizeTree(None)], "if x: y") self.assertLines(""" (root): StatListNode stats[0]: IfStatNode if_clauses[0]: IfClauseNode condition: NameNode body: StatListNode stats[0]: ExprStatNode expr: NameNode """, self.treetypes(t)) def test_wrap_multistat(self): t = self.run_pipeline([NormalizeTree(None)], """ if z: x y """) self.assertLines(""" (root): StatListNode stats[0]: IfStatNode if_clauses[0]: IfClauseNode condition: NameNode body: StatListNode stats[0]: ExprStatNode expr: NameNode stats[1]: ExprStatNode expr: NameNode """, self.treetypes(t)) def test_statinexpr(self): t = self.run_pipeline([NormalizeTree(None)], """ a, b = x, y """) self.assertLines(""" (root): StatListNode stats[0]: SingleAssignmentNode lhs: TupleNode args[0]: NameNode args[1]: NameNode rhs: TupleNode args[0]: NameNode args[1]: NameNode """, self.treetypes(t)) def test_wrap_offagain(self): t = self.run_pipeline([NormalizeTree(None)], """ x y if z: x """) self.assertLines(""" (root): StatListNode stats[0]: ExprStatNode expr: NameNode stats[1]: ExprStatNode expr: NameNode stats[2]: IfStatNode if_clauses[0]: IfClauseNode condition: NameNode body: StatListNode stats[0]: ExprStatNode expr: NameNode """, self.treetypes(t))
TestNormalizeTree
python
pypa__hatch
tests/backend/metadata/test_build.py
{ "start": 1523, "end": 2156 }
class ____: def test_default(self, isolation): metadata = BuildMetadata(str(isolation), {}) assert metadata.build_backend == metadata.build_backend == "" def test_not_string(self, isolation): metadata = BuildMetadata(str(isolation), {"build-backend": 10}) with pytest.raises(TypeError, match="Field `build-system.build-backend` must be a string"): _ = metadata.build_backend def test_correct(self, isolation): metadata = BuildMetadata(str(isolation), {"build-backend": "foo"}) assert metadata.build_backend == metadata.build_backend == "foo"
TestBuildBackend
python
Lightning-AI__lightning
tests/tests_pytorch/utilities/test_model_summary.py
{ "start": 2062, "end": 2817 }
class ____(LightningModule): """A model in which the layers not defined in order of execution.""" def __init__(self): super().__init__() # note: the definition order is intentionally scrambled for this test self.layer2 = nn.Linear(10, 2) self.combine = nn.Linear(7, 9) self.layer1 = nn.Linear(3, 5) self.relu = nn.ReLU() # this layer is unused, therefore input-/output shapes are unknown self.unused = nn.Conv2d(1, 1, 1) self.example_input_array = (torch.rand(2, 3), torch.rand(2, 10)) def forward(self, x, y): out1 = self.layer1(x) out2 = self.layer2(y) out = self.relu(torch.cat((out1, out2), 1)) return self.combine(out)
UnorderedModel
python
huggingface__transformers
src/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py
{ "start": 45598, "end": 48397 }
class ____(nn.Module): def __init__(self, config: Phi4MultimodalConfig): super().__init__() self.config = config self.layer_idx = config.audio_config.feature_layer self.drop = nn.Dropout(config.embd_pdrop) self.encoder = Phi4MultimodalAudioModel._from_config(config.audio_config) self.up_proj_for_speech = nn.Linear( config.audio_config.hidden_size * config.audio_config.downsample_rate, config.hidden_size ) self.down_proj_for_speech = nn.Linear(config.hidden_size, config.hidden_size) self.up_proj_for_vision_speech = nn.Linear( config.audio_config.hidden_size * config.audio_config.downsample_rate, config.hidden_size ) self.down_proj_for_vision_speech = nn.Linear(config.hidden_size, config.hidden_size) def forward( self, input_ids: torch.LongTensor, inputs_embeds: torch.Tensor, audio_input_features: torch.FloatTensor, audio_embed_sizes=None, audio_attention_mask=None, audio_projection_mode="speech", ) -> torch.FloatTensor: with torch.no_grad(): positions_tuple = torch.nonzero(input_ids == self.config.audio_config.audio_token_id, as_tuple=True) up_proj = self.up_proj_for_speech if audio_projection_mode == "speech" else self.up_proj_for_vision_speech down_proj = ( self.down_proj_for_speech if audio_projection_mode == "speech" else self.down_proj_for_vision_speech ) target_device = up_proj.bias.device target_dtype = up_proj.bias.dtype audio_input_features = audio_input_features.to(device=target_device, dtype=target_dtype) audio_encoder_hidden_states = self.encoder(audio_input_features, audio_attention_mask) audio_encoder_hidden_states = up_proj(audio_encoder_hidden_states) audio_encoder_hidden_states = nn.functional.gelu(audio_encoder_hidden_states) audio_embeds = down_proj(audio_encoder_hidden_states) merged_audio_embeds = torch.cat( [audio_embeds[i, : audio_embed_sizes[i], :] for i in range(len(audio_embed_sizes))], dim=0 ) merged_audio_embeds = merged_audio_embeds.to(dtype=inputs_embeds.dtype, device=inputs_embeds.device) # Temporarily disable autocast to avoid issue on bf16 tensors # Ref: https://github.com/pytorch/pytorch/issues/132715 with torch.autocast(device_type=inputs_embeds.device.type, enabled=False): audio_embeds = inputs_embeds.index_put( indices=positions_tuple, values=merged_audio_embeds, accumulate=False ) audio_embeds = self.drop(audio_embeds) return audio_embeds @use_kernel_forward_from_hub("RMSNorm")
Phi4MultimodalAudioEmbedding
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_type_checking/TC005.py
{ "start": 150, "end": 513 }
class ____: if TYPE_CHECKING: pass # TC005 x = 2 if TYPE_CHECKING: if 2: pass if TYPE_CHECKING: x: List from typing_extensions import TYPE_CHECKING if TYPE_CHECKING: pass # TC005 # https://github.com/astral-sh/ruff/issues/11368 if TYPE_CHECKING: pass else: pass if TYPE_CHECKING: pass elif test: pass
Test
python
spack__spack
lib/spack/spack/compilers/libraries.py
{ "start": 9218, "end": 12121 }
class ____: """Remove rpaths to directories that are default search paths of the dynamic linker.""" _CACHE: Dict[Optional[str], Set[Tuple[int, int]]] = {} def __init__(self, dynamic_linker: Optional[str]) -> None: if dynamic_linker not in DefaultDynamicLinkerFilter._CACHE: # Identify directories by (inode, device) tuple, which handles symlinks too. default_path_identifiers: Set[Tuple[int, int]] = set() if not dynamic_linker: self.default_path_identifiers = None return for path in spack.util.libc.default_search_paths_from_dynamic_linker(dynamic_linker): try: s = os.stat(path) if stat.S_ISDIR(s.st_mode): default_path_identifiers.add((s.st_ino, s.st_dev)) except OSError: continue DefaultDynamicLinkerFilter._CACHE[dynamic_linker] = default_path_identifiers self.default_path_identifiers = DefaultDynamicLinkerFilter._CACHE[dynamic_linker] def is_dynamic_loader_default_path(self, p: str) -> bool: if self.default_path_identifiers is None: return False try: s = os.stat(p) return (s.st_ino, s.st_dev) in self.default_path_identifiers except OSError: return False def __call__(self, dirs: List[str]) -> List[str]: if not self.default_path_identifiers: return dirs return [p for p in dirs if not self.is_dynamic_loader_default_path(p)] def dynamic_linker_filter_for(node: spack.spec.Spec) -> Optional[DefaultDynamicLinkerFilter]: compiler = compiler_spec(node) if compiler is None: return None detector = CompilerPropertyDetector(compiler) dynamic_linker = detector.default_dynamic_linker() if dynamic_linker is None: return None return DefaultDynamicLinkerFilter(dynamic_linker) def compiler_spec(node: spack.spec.Spec) -> Optional[spack.spec.Spec]: """Returns a compiler :class:`~spack.spec.Spec` associated with the node passed as argument. The function looks for a ``c``, ``cxx``, and ``fortran`` compiler in that order, and returns the first found. If the node does not depend on any of these languages, it returns :obj:`None`. Use of this function is *discouraged*, because a single spec can have multiple compilers associated with it, and this function only returns one of them. It can be better to refer to compilers on a per-language basis, through the language virtuals: ``spec["c"]``, ``spec["cxx"]``, and ``spec["fortran"]``. """ for language in ("c", "cxx", "fortran"): candidates = node.dependencies(virtuals=[language]) if candidates: break else: return None return candidates[0]
DefaultDynamicLinkerFilter
python
huggingface__transformers
tests/models/qwen3_next/test_modeling_qwen3_next.py
{ "start": 1296, "end": 1768 }
class ____(CausalLMModelTester): if is_torch_available(): base_model_class = Qwen3NextModel def __init__(self, parent): super().__init__(parent=parent) self.layer_types = ["linear_attention", "full_attention"] self.linear_conv_kernel_dim = 2 self.linear_key_head_dim = 16 self.linear_value_head_dim = 16 self.linear_num_key_heads = 4 self.linear_num_value_heads = 8 @require_torch
Qwen3NextModelTester
python
ray-project__ray
python/ray/dashboard/modules/metrics/dashboards/common.py
{ "start": 999, "end": 11708 }
class ____: """Defines a Grafana target (time-series query) within a panel. A panel will have one or more targets. By default, all targets are rendered as stacked area charts, with the exception of legend="MAX", which is rendered as a blue dotted line. Any legend="FINISHED|FAILED|DEAD|REMOVED" series will also be rendered hidden by default. Attributes: expr: The prometheus query to evaluate. legend: The legend string to format for each time-series. """ expr: str legend: str template: Optional[TargetTemplate] = TargetTemplate.GRAPH HEATMAP_TEMPLATE = { "datasource": r"${datasource}", "description": "<Description>", "fieldConfig": {"defaults": {}, "overrides": []}, "id": 12, "options": { "calculate": False, "cellGap": 1, "cellValues": {"unit": "none"}, "color": { "exponent": 0.5, "fill": "dark-orange", "min": 0, "mode": "scheme", "reverse": False, "scale": "exponential", "scheme": "Spectral", "steps": 64, }, "exemplars": {"color": "rgba(255,0,255,0.7)"}, "filterValues": {"le": 1e-9}, "legend": {"show": True}, "rowsFrame": {"layout": "auto", "value": "Request count"}, "tooltip": {"mode": "single", "showColorScale": False, "yHistogram": True}, "yAxis": {"axisPlacement": "left", "reverse": False, "unit": "none"}, }, "pluginVersion": "11.2.0", "targets": [], "title": "<Title>", "type": "heatmap", "yaxes": [ { "$$hashKey": "object:628", "format": "units", "label": "", "logBase": 1, "max": None, "min": "0", "show": True, }, { "$$hashKey": "object:629", "format": "short", "label": None, "logBase": 1, "max": None, "min": None, "show": True, }, ], } GRAPH_PANEL_TEMPLATE = { "aliasColors": {}, "bars": False, "dashLength": 10, "dashes": False, "datasource": r"${datasource}", "description": "<Description>", "fieldConfig": {"defaults": {}, "overrides": []}, # Setting height and width is important here to ensure the default panel has some size to it. "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}, "fill": 10, "fillGradient": 0, "hiddenSeries": False, "id": 26, "legend": { "alignAsTable": True, "avg": True, "current": True, "hideEmpty": False, "hideZero": True, "max": True, "min": False, "rightSide": False, "show": True, "sort": "current", "sortDesc": True, "total": False, "values": True, }, "lines": True, "linewidth": 1, "nullPointMode": None, "options": {"alertThreshold": True}, "percentage": False, "pluginVersion": "7.5.17", "pointradius": 2, "points": False, "renderer": "flot", # These series overrides are necessary to make the "MAX" and "MAX + PENDING" dotted lines # instead of stacked filled areas. "seriesOverrides": [ { "$$hashKey": "object:2987", "alias": "MAX", "dashes": True, "color": "#1F60C4", "fill": 0, "stack": False, }, { "$$hashKey": "object:78", "alias": "/FINISHED|FAILED|DEAD|REMOVED|Failed Nodes:/", "hiddenSeries": True, }, { "$$hashKey": "object:2987", "alias": "MAX + PENDING", "dashes": True, "color": "#777777", "fill": 0, "stack": False, }, ], "spaceLength": 10, "stack": True, "steppedLine": False, "targets": [], "thresholds": [], "timeFrom": None, "timeRegions": [], "timeShift": None, "title": "<Title>", "tooltip": {"shared": True, "sort": 0, "value_type": "individual"}, "type": "graph", "xaxis": { "buckets": None, "mode": "time", "name": None, "show": True, "values": [], }, "yaxes": [ { "$$hashKey": "object:628", "format": "units", "label": "", "logBase": 1, "max": None, "min": "0", "show": True, }, { "$$hashKey": "object:629", "format": "short", "label": None, "logBase": 1, "max": None, "min": None, "show": True, }, ], "yaxis": {"align": False, "alignLevel": None}, } STAT_PANEL_TEMPLATE = { "datasource": r"${datasource}", "fieldConfig": { "defaults": { "color": {"mode": "thresholds"}, "mappings": [], "min": 0, "thresholds": { "mode": "percentage", "steps": [ {"color": "super-light-yellow", "value": None}, {"color": "super-light-green", "value": 50}, {"color": "green", "value": 100}, ], }, "unit": "short", }, "overrides": [], }, "id": 78, "options": { "colorMode": "value", "graphMode": "area", "justifyMode": "auto", "orientation": "auto", "reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False}, "text": {}, "textMode": "auto", }, "pluginVersion": "7.5.17", "targets": [], "timeFrom": None, "timeShift": None, "title": "<Title>", "type": "stat", "yaxes": [ { "$$hashKey": "object:628", "format": "Tokens", "label": "", "logBase": 1, "max": None, "min": "0", "show": True, }, { "$$hashKey": "object:629", "format": "short", "label": None, "logBase": 1, "max": None, "min": None, "show": True, }, ], } GAUGE_PANEL_TEMPLATE = { "datasource": r"${datasource}", "fieldConfig": { "defaults": { "color": {"mode": "continuous-YlBl"}, "mappings": [], "thresholds": { "mode": "percentage", "steps": [{"color": "rgb(230, 230, 230)", "value": None}], }, "unit": "short", }, "overrides": [], }, "id": 10, "options": { "reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False}, "showThresholdLabels": False, "showThresholdMarkers": False, "text": {"titleSize": 12}, }, "pluginVersion": "7.5.17", "targets": [], "title": "<Title>", "type": "gauge", "yaxes": [ { "$$hashKey": "object:628", "format": "Tokens", "label": "", "logBase": 1, "max": None, "min": "0", "show": True, }, { "$$hashKey": "object:629", "format": "short", "label": None, "logBase": 1, "max": None, "min": None, "show": True, }, ], } PIE_CHART_TEMPLATE = { "datasource": r"${datasource}", "description": "<Description>", "fieldConfig": {"defaults": {}, "overrides": []}, "id": 26, "options": { "displayLabels": [], "legend": { "displayMode": "table", "placement": "right", "values": ["percent", "value"], }, "pieType": "pie", "reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False}, "text": {}, }, "pluginVersion": "7.5.17", "targets": [], "timeFrom": None, "timeShift": None, "title": "<Title>", "type": "piechart", "yaxes": [ { "$$hashKey": "object:628", "format": "units", "label": "", "logBase": 1, "max": None, "min": "0", "show": True, }, { "$$hashKey": "object:629", "format": "short", "label": None, "logBase": 1, "max": None, "min": None, "show": True, }, ], } BAR_CHART_PANEL_TEMPLATE = { "aliasColors": {}, "dashLength": 10, "dashes": False, "datasource": r"${datasource}", "description": "<Description>", "fieldConfig": {"defaults": {}, "overrides": []}, # Setting height and width is important here to ensure the default panel has some size to it. "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}, "hiddenSeries": False, "id": 26, "legend": { "alignAsTable": True, "avg": False, "current": True, "hideEmpty": False, "hideZero": True, "max": False, "min": False, "rightSide": False, "show": False, "sort": "current", "sortDesc": True, "total": False, "values": True, }, "lines": False, "linewidth": 1, "bars": True, "nullPointMode": None, "options": { "alertThreshold": True, "legend": { "showLegend": False, "displayMode": "table", "placement": "bottom", }, }, "percentage": False, "pluginVersion": "7.5.17", "pointradius": 2, "points": False, "renderer": "flot", "spaceLength": 10, "stack": True, "steppedLine": False, "targets": [], "thresholds": [], "timeFrom": None, "timeRegions": [], "timeShift": None, "title": "<Title>", "tooltip": {"shared": True, "sort": 0, "value_type": "individual"}, "type": "graph", "xaxis": { "buckets": None, "mode": "series", "name": None, "show": True, "values": [ "total", ], }, "yaxes": [ { "$$hashKey": "object:628", "format": "units", "label": "", "logBase": 1, "max": None, "min": "0", "show": True, }, { "$$hashKey": "object:629", "format": "short", "label": None, "logBase": 1, "max": None, "min": None, "show": True, }, ], "yaxis": {"align": False, "alignLevel": None}, } @DeveloperAPI
Target
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-chroma/llama_index/vector_stores/chroma/base.py
{ "start": 3460, "end": 24430 }
class ____(BasePydanticVectorStore): """ Chroma vector store. In this vector store, embeddings are stored within a ChromaDB collection. During query time, the index uses ChromaDB to query for the top k most similar nodes. Supports MMR (Maximum Marginal Relevance) search mode for improved diversity in search results. Args: chroma_collection (chromadb.api.models.Collection.Collection): ChromaDB collection instance Examples: `uv add llama-index-vector-stores-chroma` ```python import chromadb from llama_index.vector_stores.chroma import ChromaVectorStore # Create a Chroma client and collection chroma_client = chromadb.EphemeralClient() chroma_collection = chroma_client.create_collection("example_collection") # Set up the ChromaVectorStore and StorageContext vector_store = ChromaVectorStore(chroma_collection=chroma_collection) # Use MMR mode with threshold query_engine = index.as_query_engine( vector_store_query_mode="mmr", vector_store_kwargs={"mmr_threshold": 0.5} ) ``` """ stores_text: bool = True flat_metadata: bool = True collection_name: Optional[str] host: Optional[str] port: Optional[Union[str, int]] ssl: bool headers: Optional[Dict[str, str]] persist_dir: Optional[str] collection_kwargs: Dict[str, Any] = Field(default_factory=dict) _collection: Collection = PrivateAttr() def __init__( self, chroma_collection: Optional[Any] = None, collection_name: Optional[str] = None, host: Optional[str] = None, port: Optional[Union[str, int]] = None, ssl: bool = False, headers: Optional[Dict[str, str]] = None, persist_dir: Optional[str] = None, collection_kwargs: Optional[dict] = None, **kwargs: Any, ) -> None: """Init params.""" collection_kwargs = collection_kwargs or {} super().__init__( host=host, port=port, ssl=ssl, headers=headers, collection_name=collection_name, persist_dir=persist_dir, collection_kwargs=collection_kwargs or {}, ) if chroma_collection is None: client = chromadb.HttpClient(host=host, port=port, ssl=ssl, headers=headers) self._collection = client.get_or_create_collection( name=collection_name, **collection_kwargs ) else: self._collection = cast(Collection, chroma_collection) @classmethod def from_collection(cls, collection: Any) -> "ChromaVectorStore": try: from chromadb import Collection except ImportError: raise ImportError(import_err_msg) if not isinstance(collection, Collection): raise Exception("argument is not chromadb collection instance") return cls(chroma_collection=collection) @classmethod def from_params( cls, collection_name: str, host: Optional[str] = None, port: Optional[Union[str, int]] = None, ssl: bool = False, headers: Optional[Dict[str, str]] = None, persist_dir: Optional[str] = None, collection_kwargs: dict = {}, **kwargs: Any, ) -> "ChromaVectorStore": if persist_dir: client = chromadb.PersistentClient(path=persist_dir) collection = client.get_or_create_collection( name=collection_name, **collection_kwargs ) elif host and port: client = chromadb.HttpClient(host=host, port=port, ssl=ssl, headers=headers) collection = client.get_or_create_collection( name=collection_name, **collection_kwargs ) else: raise ValueError( "Either `persist_dir` or (`host`,`port`) must be specified" ) return cls( chroma_collection=collection, host=host, port=port, ssl=ssl, headers=headers, persist_dir=persist_dir, collection_kwargs=collection_kwargs, **kwargs, ) @classmethod def class_name(cls) -> str: return "ChromaVectorStore" def get_nodes( self, node_ids: Optional[List[str]], filters: Optional[List[MetadataFilters]] = None, ) -> List[BaseNode]: """ Get nodes from index. Args: node_ids (List[str]): list of node ids filters (List[MetadataFilters]): list of metadata filters """ if not self._collection: raise ValueError("Collection not initialized") node_ids = node_ids or None if filters: where = _to_chroma_filter(filters) else: where = None result = self._get(None, where=where, ids=node_ids) return result.nodes def add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]: """ Add nodes to index. Args: nodes: List[BaseNode]: list of nodes with embeddings """ if not self._collection: raise ValueError("Collection not initialized") max_chunk_size = MAX_CHUNK_SIZE node_chunks = chunk_list(nodes, max_chunk_size) all_ids = [] for node_chunk in node_chunks: embeddings = [] metadatas = [] ids = [] documents = [] for node in node_chunk: embeddings.append(node.get_embedding()) metadata_dict = node_to_metadata_dict( node, remove_text=True, flat_metadata=self.flat_metadata ) for key in metadata_dict: if metadata_dict[key] is None: metadata_dict[key] = "" metadatas.append(metadata_dict) ids.append(node.node_id) documents.append(node.get_content(metadata_mode=MetadataMode.NONE)) self._collection.add( embeddings=embeddings, ids=ids, metadatas=metadatas, documents=documents, ) all_ids.extend(ids) return all_ids def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None: """ Delete nodes using with ref_doc_id. Args: ref_doc_id (str): The doc_id of the document to delete. """ self._collection.delete(where={"document_id": ref_doc_id}) def delete_nodes( self, node_ids: Optional[List[str]] = None, filters: Optional[List[MetadataFilters]] = None, ) -> None: """ Delete nodes from index. Args: node_ids (List[str]): list of node ids filters (List[MetadataFilters]): list of metadata filters """ if not self._collection: raise ValueError("Collection not initialized") node_ids = node_ids or [] if filters: where = _to_chroma_filter(filters) self._collection.delete(ids=node_ids, where=where) else: self._collection.delete(ids=node_ids) def clear(self) -> None: """Clear the collection.""" ids = self._collection.get()["ids"] self._collection.delete(ids=ids) @property def client(self) -> Any: """Return client.""" return self._collection def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult: """ Query index for top k most similar nodes. Args: query (VectorStoreQuery): Query object containing: - query_embedding (List[float]): query embedding - similarity_top_k (int): top k most similar nodes - filters (Optional[MetadataFilters]): metadata filters to apply - mode (VectorStoreQueryMode): query mode (default or MMR) **kwargs: Additional keyword arguments passed to ChromaDB query method. For MMR mode, supports: - mmr_threshold (Optional[float]): MMR threshold between 0 and 1 - mmr_prefetch_factor (Optional[float]): Factor to multiply similarity_top_k for prefetching candidates (default: 4.0) - mmr_prefetch_k (Optional[int]): Explicit number of candidates to prefetch (cannot be used with mmr_prefetch_factor) For ChromaDB-specific parameters: - where (dict): ChromaDB where clause (use query.filters instead for standard filtering) - include (List[str]): ChromaDB include parameter - where_document (dict): ChromaDB where_document parameter Returns: VectorStoreQueryResult: Query result containing matched nodes, similarities, and IDs. Raises: ValueError: If MMR parameters are invalid or if both query.filters and where kwargs are specified. """ if query.filters is not None: if "where" in kwargs: raise ValueError( "Cannot specify metadata filters via both query and kwargs. " "Use kwargs only for chroma specific items that are " "not supported via the generic query interface." ) where = _to_chroma_filter(query.filters) else: where = kwargs.pop("where", None) if not query.query_embedding: return self._get(limit=query.similarity_top_k, where=where, **kwargs) # Handle MMR mode if query.mode == VectorStoreQueryMode.MMR: return self._mmr_search(query, where, **kwargs) return self._query( query_embeddings=query.query_embedding, n_results=query.similarity_top_k, where=where, **kwargs, ) def _query( self, query_embeddings: List["float"], n_results: int, where: dict, **kwargs ) -> VectorStoreQueryResult: if where: results = self._collection.query( query_embeddings=query_embeddings, n_results=n_results, where=where, **kwargs, ) else: results = self._collection.query( query_embeddings=query_embeddings, n_results=n_results, **kwargs, ) logger.debug(f"> Top {len(results['documents'][0])} nodes:") nodes = [] similarities = [] ids = [] for node_id, text, metadata, distance in zip( results["ids"][0], results["documents"][0], results["metadatas"][0], results["distances"][0], ): try: node = metadata_dict_to_node(metadata) node.set_content(text) except Exception: # NOTE: deprecated legacy logic for backward compatibility metadata, node_info, relationships = legacy_metadata_dict_to_node( metadata ) node = TextNode( text=text, id_=node_id, metadata=metadata, start_char_idx=node_info.get("start", None), end_char_idx=node_info.get("end", None), relationships=relationships, ) nodes.append(node) similarity_score = math.exp(-distance) similarities.append(similarity_score) logger.debug( f"> [Node {node_id}] [Similarity score: {similarity_score}] " f"{truncate_text(str(text), 100)}" ) ids.append(node_id) return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids) def _mmr_search( self, query: VectorStoreQuery, where: dict, **kwargs ) -> VectorStoreQueryResult: """ Perform MMR search using ChromaDB. Args: query: VectorStoreQuery object containing the query parameters where: ChromaDB filter conditions **kwargs: Additional keyword arguments including mmr_threshold Returns: VectorStoreQueryResult: Query result with MMR-applied nodes """ # Extract MMR parameters mmr_threshold = kwargs.get("mmr_threshold") # Validate MMR parameters if mmr_threshold is not None and ( not isinstance(mmr_threshold, (int, float)) or mmr_threshold < 0 or mmr_threshold > 1 ): raise ValueError("mmr_threshold must be a float between 0 and 1") # Validate prefetch parameters (check before popping) raw_prefetch_factor = kwargs.get("mmr_prefetch_factor") raw_prefetch_k = kwargs.get("mmr_prefetch_k") if raw_prefetch_factor is not None and raw_prefetch_k is not None: raise ValueError( "'mmr_prefetch_factor' and 'mmr_prefetch_k' " "cannot coexist in a call to query()" ) # Strip MMR-only kwargs so they aren't forwarded to Chroma mmr_threshold = kwargs.pop("mmr_threshold", None) prefetch_k_override = kwargs.pop("mmr_prefetch_k", None) prefetch_factor = kwargs.pop("mmr_prefetch_factor", DEFAULT_MMR_PREFETCH_FACTOR) # Calculate prefetch size (get more candidates than needed for MMR) if prefetch_k_override is not None: prefetch_k = int(prefetch_k_override) else: prefetch_k = int(query.similarity_top_k * prefetch_factor) # Ensure prefetch_k is at least as large as similarity_top_k prefetch_k = max(prefetch_k, query.similarity_top_k) logger.debug( f"MMR search: prefetching {prefetch_k} candidates for {query.similarity_top_k} final results" ) # Query ChromaDB for more candidates than needed (kwargs now safe) if where: prefetch_results = self._collection.query( query_embeddings=query.query_embedding, n_results=prefetch_k, where=where, include=["embeddings", "documents", "metadatas", "distances"], **kwargs, ) else: prefetch_results = self._collection.query( query_embeddings=query.query_embedding, n_results=prefetch_k, include=["embeddings", "documents", "metadatas", "distances"], **kwargs, ) # Extract embeddings and metadata for MMR processing prefetch_embeddings = [] prefetch_ids = [] prefetch_metadata = [] prefetch_documents = [] prefetch_distances = [] # Process prefetch results for i in range(len(prefetch_results["ids"][0])): node_id = prefetch_results["ids"][0][i] text = prefetch_results["documents"][0][i] metadata = prefetch_results["metadatas"][0][i] distance = prefetch_results["distances"][0][i] # Get the actual embedding from ChromaDB results if "embeddings" in prefetch_results and prefetch_results["embeddings"]: embedding = prefetch_results["embeddings"][0][i] else: # Fallback: if embeddings not available, we'll use distance-based approach embedding = None # Store for MMR processing prefetch_embeddings.append(embedding) prefetch_ids.append(node_id) prefetch_metadata.append(metadata) prefetch_documents.append(text) prefetch_distances.append(distance) if not prefetch_embeddings: logger.warning("No results found during MMR prefetch") return VectorStoreQueryResult(nodes=[], similarities=[], ids=[]) # Check if we have valid embeddings for MMR valid_embeddings = [emb for emb in prefetch_embeddings if emb is not None] if len(valid_embeddings) < query.similarity_top_k: logger.warning( f"Not enough valid embeddings for MMR: {len(valid_embeddings)} < {query.similarity_top_k}" ) # Fallback to regular similarity search return self._query( query_embeddings=query.query_embedding, n_results=query.similarity_top_k, where=where, **kwargs, ) # Apply MMR algorithm using the core utility function mmr_similarities, mmr_indices = get_top_k_mmr_embeddings( query_embedding=query.query_embedding, embeddings=valid_embeddings, similarity_top_k=query.similarity_top_k, embedding_ids=list(range(len(valid_embeddings))), mmr_threshold=mmr_threshold, ) # Build final results based on MMR selection final_nodes = [] final_similarities = [] final_ids = [] # Create a mapping from valid embedding indices to original prefetch indices valid_indices = [ i for i, emb in enumerate(prefetch_embeddings) if emb is not None ] for mmr_index in mmr_indices: if mmr_index < len(valid_indices): original_index = valid_indices[mmr_index] if original_index < len(prefetch_ids): node_id = prefetch_ids[original_index] text = prefetch_documents[original_index] metadata = prefetch_metadata[original_index] distance = prefetch_distances[original_index] # Create node (reusing logic from _query method) try: node = metadata_dict_to_node(metadata) node.set_content(text) except Exception: # NOTE: deprecated legacy logic for backward compatibility metadata, node_info, relationships = ( legacy_metadata_dict_to_node(metadata) ) node = TextNode( text=text, id_=node_id, metadata=metadata, start_char_idx=node_info.get("start", None), end_char_idx=node_info.get("end", None), relationships=relationships, ) final_nodes.append(node) final_similarities.append(math.exp(-distance)) final_ids.append(node_id) logger.debug( f"MMR search completed: {len(final_nodes)} results selected from {len(prefetch_embeddings)} candidates" ) return VectorStoreQueryResult( nodes=final_nodes, similarities=final_similarities, ids=final_ids ) def _get( self, limit: Optional[int], where: dict, **kwargs ) -> VectorStoreQueryResult: if where: results = self._collection.get( limit=limit, where=where, **kwargs, ) else: results = self._collection.get( limit=limit, **kwargs, ) logger.debug(f"> Top {len(results['documents'])} nodes:") nodes = [] ids = [] if not results["ids"]: results["ids"] = [[]] for node_id, text, metadata in zip( results["ids"], results["documents"], results["metadatas"] ): try: node = metadata_dict_to_node(metadata) node.set_content(text) except Exception: # NOTE: deprecated legacy logic for backward compatibility metadata, node_info, relationships = legacy_metadata_dict_to_node( metadata ) node = TextNode( text=text, id_=node_id, metadata=metadata, start_char_idx=node_info.get("start", None), end_char_idx=node_info.get("end", None), relationships=relationships, ) nodes.append(node) logger.debug( f"> [Node {node_id}] [Similarity score: N/A - using get()] " f"{truncate_text(str(text), 100)}" ) ids.append(node_id) return VectorStoreQueryResult(nodes=nodes, ids=ids)
ChromaVectorStore
python
pytorch__pytorch
torch/_dynamo/variables/user_defined.py
{ "start": 4315, "end": 36880 }
class ____(UserDefinedVariable): value: type[object] def __init__(self, value, **kwargs) -> None: super().__init__(**kwargs) self.value = value # Used when we materialize class.__dict__ to a MappingProxyObject. In # this case, we don't want to allow mutation in the class because there # is no way to reflect it in the created MappingProxyVariable. self.ban_mutation = False def as_python_constant(self): return self.value def as_proxy(self): return self.value def __repr__(self) -> str: return f"{self.__class__.__name__}({self.value})" @staticmethod @functools.cache def _constant_fold_classes(): return { torch.device, torch.finfo, torch.iinfo, torch.Size, } @staticmethod @functools.cache def _in_graph_classes(): _in_graph_class_list = { torch.Tensor, torch.cuda.FloatTensor, torch.cuda.DoubleTensor, torch.cuda.HalfTensor, torch.cuda.BFloat16Tensor, torch.cuda.ByteTensor, torch.cuda.CharTensor, torch.cuda.IntTensor, torch.cuda.ShortTensor, torch.cuda.LongTensor, torch.Stream, torch.Event, torch.cuda.Stream, torch.cuda.Event, torch.xpu.Stream, torch.xpu.Event, } if hasattr(torch, "hpu"): _in_graph_class_list.update( { torch.hpu.Stream, torch.hpu.Event, } ) return set(tensortype_to_dtype.keys()) | _in_graph_class_list @staticmethod @functools.cache def supported_c_new_functions(): exceptions = [ getattr(builtins, name).__new__ for name in dir(builtins) if isinstance(getattr(builtins, name), type) and issubclass(getattr(builtins, name), BaseException) ] return { object.__new__, dict.__new__, set.__new__, frozenset.__new__, tuple.__new__, list.__new__, }.union(exceptions) @staticmethod def is_supported_new_method(value): # TODO(anijain2305) - Extend this to support objects with default tp_new # functions. return value in UserDefinedClassVariable.supported_c_new_functions() def can_constant_fold_through(self): return self.value in self._constant_fold_classes() def has_key_in_generic_dict(self, tx: "InstructionTranslator", key): if tx.output.side_effects.has_pending_mutation_of_attr(self, key): mutated_attr = tx.output.side_effects.load_attr(self, key, deleted_ok=True) return not isinstance(mutated_attr, variables.DeletedVariable) return key in self.value.__dict__ def var_getattr(self, tx: "InstructionTranslator", name: str) -> "VariableTracker": from . import ConstantVariable, EnumVariable source = AttrSource(self.source, name) if self.source is not None else None if name == "__name__": return ConstantVariable.create(self.value.__name__) elif name == "__qualname__": return ConstantVariable.create(self.value.__qualname__) elif name == "__dict__": options = {"source": source} return variables.GetAttrVariable(self, name, **options) elif name == "__mro__": attr_source = self.source and TypeMROSource(self.source) return VariableTracker.build(tx, self.value.__mro__, attr_source) # Special handling of collections.OrderedDict.fromkeys() # Wrap it as GetAttrVariable(collections.OrderedDict, "fromkeys") to make it consistent with # collections.defaultdict, and both will be handled at UserDefinedClassVariable.call_method(). # Otherwise, it would be wrapped as UserDefinedObjectVariable(collections.OrderedDict.fromkeys), # and we need duplicate code to handle both cases. if ( self.value in {collections.OrderedDict, collections.defaultdict} and name == "fromkeys" ): return super().var_getattr(tx, name) try: obj = inspect.getattr_static(self.value, name) except AttributeError: if type(self.value) is type: raise_observed_exception( AttributeError, tx, msg=f"type object '{self.value.__name__}' has no attribute '{name}'", ) else: # Cannot reason about classes with a custom metaclass # See: test_functions::test_getattr_metaclass obj = None if name == "__new__" and UserDefinedClassVariable.is_supported_new_method(obj): return super().var_getattr(tx, name) if name in cmp_name_to_op_mapping and not isinstance(obj, types.FunctionType): return variables.GetAttrVariable(self, name, source=source) if isinstance(obj, staticmethod): return VariableTracker.build(tx, obj.__get__(self.value), source) elif isinstance(obj, classmethod): if isinstance(obj.__func__, property): fget_vt = VariableTracker.build(tx, obj.__func__.fget) return fget_vt.call_function(tx, [self], {}) return variables.UserMethodVariable(obj.__func__, self, source=source) elif isinstance(obj, types.ClassMethodDescriptorType): # e.g.: inspect.getattr_static(dict, "fromkeys") # inspect.getattr_static(itertools.chain, "from_iterable") func = obj.__get__(None, self.value) return VariableTracker.build(tx, func, source) elif source: if inspect.ismemberdescriptor(obj): return VariableTracker.build(tx, obj.__get__(self.value), source) if ConstantVariable.is_literal(obj): return ConstantVariable.create(obj) elif isinstance(obj, enum.Enum): return EnumVariable(obj) elif self.value is collections.OrderedDict: return variables.GetAttrVariable(self, name) elif name in getattr(self.value, "__dict__", {}) or ( self.value.__module__.startswith("torch.") or self.value.__module__ == "torch" ): if source: return VariableTracker.build(tx, obj, source) if ( source and not inspect.ismethoddescriptor(obj) and not is_wrapper_or_member_descriptor(obj) ): return VariableTracker.build(tx, obj, source) return super().var_getattr(tx, name) def _call_cross_entropy_loss(self, tx: "InstructionTranslator", args, kwargs): """ functional: input, target, weight=None, size_average=None, ignore_index=- 100, reduce=None, reduction='mean', label_smoothing=0.0 non functional ctor: weight=None, size_average=None, ignore_index=- 100, reduce=None, reduction='mean', label_smoothing=0.0 non functional loss call: input, target, optional_output """ from . import ConstantVariable def normalize_args( weight=ConstantVariable.create(None), size_average=ConstantVariable.create(None), ignore_index=ConstantVariable.create(-100), reduce=ConstantVariable.create(None), reduction=ConstantVariable.create("mean"), label_smoothing=ConstantVariable.create(0.0), ): return ( weight, size_average, ignore_index, reduce, reduction, label_smoothing, ) ( weight, size_average, ignore_index, reduce_arg, reduction, label_smoothing, ) = normalize_args(*args, **kwargs) def fake_cross_entropy_loss(input, target): from .builder import wrap_fx_proxy return wrap_fx_proxy( tx=tx, proxy=tx.output.create_proxy( "call_function", torch.nn.functional.cross_entropy, *proxy_args_kwargs( [ input, target, weight, size_average, ignore_index, reduce_arg, reduction, label_smoothing, ], {}, ), ), ) return variables.LambdaVariable(fake_cross_entropy_loss) def call_method( self, tx, name, args: "list[VariableTracker]", kwargs: "dict[str, VariableTracker]", ) -> "VariableTracker": if ( name == "__subclasses__" and len(args) == 0 and not kwargs and "__subclasses__" not in self.value.__dict__ ): source = self.source if self.source: source = AttrSource(self.source, "__subclasses__") source = CallFunctionNoArgsSource(source) return VariableTracker.build(tx, self.value.__subclasses__(), source) elif ( self.value in {collections.OrderedDict, collections.defaultdict} and name == "fromkeys" ): return variables.BuiltinVariable.call_custom_dict_fromkeys( tx, self.value, *args, **kwargs ) elif self.value is collections.OrderedDict and name == "move_to_end": return args[0].call_method(tx, name, [*args[1:]], kwargs) elif name == "__eq__" and len(args) == 1 and hasattr(args[0], "value"): return variables.ConstantVariable(self.value == args[0].value) elif name == "__ne__" and len(args) == 1 and hasattr(args[0], "value"): return variables.ConstantVariable(self.value != args[0].value) elif issubclass(self.value, dict) and name != "__new__": # __new__ is handled below return variables.BuiltinVariable(dict).call_method(tx, name, args, kwargs) elif issubclass(self.value, (set, frozenset)) and name != "__new__": # __new__ is handled below return variables.BuiltinVariable(set).call_method(tx, name, args, kwargs) elif ( name == "__new__" and self.value is collections.OrderedDict and isinstance(args[0], UserDefinedClassVariable) and args[0].value is collections.OrderedDict ): if kwargs and len(args) != 1: raise_args_mismatch( tx, name, "1 args and 0 kwargs", f"{len(args)} args and {len(kwargs)} kwargs", ) return variables.ConstDictVariable( {}, collections.OrderedDict, mutation_type=ValueMutationNew() ) elif name == "__new__" and UserDefinedClassVariable.is_supported_new_method( self.value.__new__ ): return tx.output.side_effects.track_new_user_defined_object( self, args[0], args[1:], ) elif name == "__setattr__" and self.ban_mutation: unimplemented( gb_type="Class attribute mutation when the __dict__ was already materialized", context=str(self.value), explanation="Dyanmo does not support tracing mutations on a class when its __dict__ is materialized", hints=graph_break_hints.SUPPORTABLE, ) return super().call_method(tx, name, args, kwargs) def call_function( self, tx: "InstructionTranslator", args: "list[VariableTracker]", kwargs: "dict[str, VariableTracker]", ) -> "VariableTracker": from ..side_effects import SideEffects from .builder import wrap_fx_proxy constant_args = check_constant_args(args, kwargs) if self.can_constant_fold_through() and constant_args: # constant fold return variables.ConstantVariable.create( self.as_python_constant()( *[x.as_python_constant() for x in args], **{k: v.as_python_constant() for k, v in kwargs.items()}, ), ) elif self.value is torch.nn.CrossEntropyLoss: return self._call_cross_entropy_loss(tx, args, kwargs) elif self.value is contextlib.nullcontext: # import here to avoid circular dependency from .ctx_manager import NullContextVariable return NullContextVariable(*args, **kwargs) elif self.value is collections.OrderedDict: return tx.inline_user_function_return( VariableTracker.build(tx, polyfills.construct_dict), [self, *args], kwargs, ) elif self.value is collections.defaultdict: if len(args) == 0: default_factory = variables.ConstantVariable.create(None) else: default_factory, *args = args dict_vt = variables.BuiltinVariable.call_custom_dict( tx, dict, *args, **kwargs ) return DefaultDictVariable( dict_vt.items, collections.defaultdict, default_factory, mutation_type=ValueMutationNew(), ) elif is_typeddict(self.value): if self.value.__optional_keys__: unimplemented( gb_type="TypedDict with optional keys", context=str(self.value), explanation="Dyanmo does not support tracing TypedDict with optional keys", hints=[ "Avoid using TypedDict with optional keys", *graph_break_hints.SUPPORTABLE, ], ) return variables.BuiltinVariable(dict).call_dict(tx, *args, **kwargs) elif self.value is collections.deque: maxlen = variables.ConstantVariable.create(None) def deque_signature(iterable=None, maxlen=None): pass try: bound_args = inspect.signature(deque_signature).bind(*args, **kwargs) except TypeError as e: unimplemented( gb_type="collections.deque() with bad arguments", context=f"args={args}, kwargs={kwargs}", explanation="Detected call to collections.deque() with bad arguments.", hints=[ "Fix the call to collections.deque().", *graph_break_hints.USER_ERROR, ], from_exc=e, ) if "iterable" in bound_args.arguments: if not bound_args.arguments["iterable"].has_force_unpack_var_sequence( tx ): unimplemented( gb_type="collections.deque() with bad iterable argument", context=f"args={args}, kwargs={kwargs}", explanation="Call to collections.deque() has an iterable argument that Dynamo cannot " "convert to a list.", hints=[ "Use a simpler sequence type that Dynamo can convert to a list " "(e.g. list, tuple, list iterator, etc.)", *graph_break_hints.USER_ERROR, ], ) items = bound_args.arguments["iterable"].force_unpack_var_sequence(tx) else: items = [] if "maxlen" in bound_args.arguments: maxlen = bound_args.arguments["maxlen"] return variables.lists.DequeVariable( items, maxlen=maxlen, mutation_type=ValueMutationNew() ) elif self.value is weakref.ref: if len(args) > 1: callback = args[1] else: callback = variables.ConstantVariable.create(None) return variables.WeakRefVariable(args[0], callback) elif self.value is functools.partial: if not args: unimplemented( gb_type="missing args to functools.partial", context="", explanation="functools.partial requires at least one argument", hints=[ "Fix the functools.partial call.", *graph_break_hints.USER_ERROR, ], ) # The first arg, a callable (the ctor below will assert on types) fn = args[0] rest_args = args[1:] # guards for the produced FunctoolsPartialVariable are installed in FunctoolsPartialVariable ctor from the # args and keywords return variables.functions.FunctoolsPartialVariable( fn, args=rest_args, keywords=kwargs ) elif self.value is warnings.catch_warnings and not args: return variables.CatchWarningsCtxManagerVariable.create(tx, kwargs) elif self.value is torch.cuda.device and not kwargs and len(args) == 1: if not args[0].is_python_constant(): raise_type_error_exc( tx, "torch.cuda.device() requires a constant argument" ) return variables.CUDADeviceVariable.create(tx, args[0].as_python_constant()) elif ( issubclass(type(self.value), type) and hasattr( self.value, "__enter__" ) # TODO(voz): These can invoke user code! and hasattr( self.value, "__exit__" ) # TODO(voz): These can invoke user code! and self.is_standard_new() and SideEffects.cls_supports_mutation_side_effects(self.value) and self.source and not is_forbidden_context_manager(self.value) ): from . import TorchCtxManagerClassVariable from .functions import ( BaseUserFunctionVariable, FunctionDecoratedByContextlibContextManagerVariable, ) # graph break on any contextlib.* that it is not contextlib.contextmanager # Some of the APIs below are not supported because they rely on features # that Dynamo doesn't play well today (i.e. contextlib.suppress) if self.value in ( contextlib._AsyncGeneratorContextManager, contextlib.closing, contextlib.redirect_stdout, contextlib.redirect_stderr, contextlib.suppress, contextlib.ExitStack, contextlib.AsyncExitStack, ): # We are not changing the behavior of Dynamo as these function were # already ignored on trace_rules.py before #136033 landed unimplemented( gb_type="unsupported contextlib.* API", context=f"{self.value}", explanation=f"{self.value} not supported. This may be due to its use of " "context-specific operations that are not supported in " "Dynamo yet (i.e. Exception handling)", hints=[ *graph_break_hints.SUPPORTABLE, ], ) if self.value is contextlib._GeneratorContextManager and isinstance( args[0], (BaseUserFunctionVariable, TorchCtxManagerClassVariable) ): if not torch._dynamo.config.enable_trace_contextlib: unimplemented( gb_type="attempted to trace contextlib.contextmanager", context=f"args={args}", explanation="Tracing contextlib.contextmanager is disabled.", hints=[ "Set torch._dynamo.config.enable_trace_contextlib = True", ], ) # Special treatments for certain context managers created via # contextlib, because # 1. we (pytorch) own their impls # 2. it's tedious to trace through them, so we effectively # "allow in graph" them without sacrificing soundness. # # We would typically reach here via either # 1. the instance construction in `with ctx_manager(...):`: # https://github.com/python/cpython/blob/3.12/Lib/contextlib.py#L301 # 2. calling a function decorated with a context manager: # https://github.com/python/cpython/blob/3.12/Lib/contextlib.py#L122 # # So we basically trace through the surface part of the # contextlib code, and then special case the shared remaining # logic (the actual context manager instance construction and # usage later on). if isinstance(args[0], TorchCtxManagerClassVariable): fn_var = args[0] args_list = args[1].items kwargs_dict = args[2].keys_as_python_constant() return fn_var.call_function(tx, args_list, kwargs_dict) # Wrap UserFunctionVariable in FunctionDecoratedByContextlibContextManagerVariable # if the function is annotated with @contextlib.contextmanager # This shouldn't be necessary once generator functions are fully # supported in dynamo args = [ FunctionDecoratedByContextlibContextManagerVariable( args[0], source=args[0].source ) ] + args[1:] cm_obj = tx.output.side_effects.track_new_user_defined_object( variables.BuiltinVariable(object), self, args, ) cm_obj.call_method(tx, "__init__", args, kwargs) return cm_obj elif is_namedtuple_cls(self.value): fields = namedtuple_fields(self.value) # check if this a quasi-namedtuple or a real one if self.value.__module__ == "torch.return_types": if kwargs or len(args) != 1: raise_args_mismatch( tx, "torch.return_types", "1 args and 0 kwargs", f"{len(args)} args and {len(kwargs)} kwargs", ) items = args[0].force_unpack_var_sequence(tx) else: field_defaults = self.value._field_defaults items = list(args) items.extend([None] * (len(fields) - len(items))) var_tracker_kwargs = {} for field_name, var_tracker in zip(fields, items): if var_tracker is None: if field_name in kwargs: field_var = kwargs[field_name] else: assert field_name in field_defaults field_var = VariableTracker.build( tx, field_defaults[field_name] ) var_tracker_kwargs[field_name] = field_var for name, value in var_tracker_kwargs.items(): assert name in fields items[fields.index(name)] = value assert all(x is not None for x in items) # Modify mutability of namedtuple for sourcelesss instantiations. from .base import AttributeMutationNew return variables.NamedTupleVariable( items, self.value, mutation_type=AttributeMutationNew() ) elif self.value is torch.Size: # This simulates `THPSize_pynew`, the C impl for `Size.__new__`. tup = variables.BuiltinVariable(tuple).call_function(tx, args, kwargs) return SizeVariable(tup.items) elif is_frozen_dataclass(self.value) and self.is_standard_new(): fields = dataclasses.fields(self.value) fields_source = DataclassFieldsSource(self.source) items = list(args) items.extend([None] * (len(fields) - len(items))) default_kwargs = {} for ind, field, var_tracker in zip(itertools.count(), fields, items): if var_tracker is None: if field.name in kwargs: var_tracker = kwargs[field.name] else: if not field.init: continue if field.default is not dataclasses.MISSING: var_tracker = VariableTracker.build( tx, field.default, source=AttrSource( GetItemSource(fields_source, ind), "default" ), ) elif field.default_factory is not dataclasses.MISSING: factory_fn = VariableTracker.build( tx, field.default_factory ) var_tracker = factory_fn.call_function(tx, [], {}) else: # if we are subclass, the constructor could possibly # be missing args continue default_kwargs[field.name] = var_tracker kwargs.update(default_kwargs) var = tx.output.side_effects.track_new_user_defined_object( variables.BuiltinVariable(object), self, args ) var.call_method(tx, "__init__", args, kwargs) return var elif ( self.value in self._in_graph_classes() or is_traceable_wrapper_subclass_type(self.value) ): # torch.LongTensor cannot accept a list of FakeTensors. # So we stack the list of FakeTensors instead. if ( np and self.value in tensortype_to_dtype and len(args) == 1 and isinstance(args[0], variables.ListVariable) and len(args[0].items) > 1 and all(isinstance(x, variables.TensorVariable) for x in args[0].items) ): # Stack FakeTensor stacked = wrap_fx_proxy( tx=tx, proxy=tx.output.create_proxy( "call_function", torch.stack, *proxy_args_kwargs(args, kwargs), ), ) args = [stacked] if issubclass(self.value, torch.Stream): from .constant import ConstantVariable from .lists import TupleVariable # Register newly created stream for reconstruction var_kwargs = ConstDictVariable( {ConstantVariable(k): v for k, v in kwargs.items()} ) var_args = TupleVariable(list(args)) stream = self.value( *(var_args.as_python_constant()), **(var_kwargs.as_python_constant()), ) from ..graph_bytecode_inputs import register_graph_created_object from .streams import StreamVariable ind = register_graph_created_object( stream, StreamVariable.make_construct_in_graph_stream_fn( var_args, var_kwargs ), ) tensor_variable = wrap_fx_proxy( tx=tx, proxy=tx.output.create_proxy( "call_function", get_external_object_by_index, (ind,), {} ), ) elif issubclass(self.value, torch.Event): from .constant import ConstantVariable from .lists import TupleVariable # Register newly created event for reconstruction var_kwargs = ConstDictVariable( {ConstantVariable(k): v for k, v in kwargs.items()} ) var_args = TupleVariable(list(args)) event = self.value( *(var_args.as_python_constant()), **(var_kwargs.as_python_constant()), ) from ..graph_bytecode_inputs import register_graph_created_object from .streams import EventVariable ind = register_graph_created_object( event, EventVariable.make_construct_in_graph_event_fn( var_args, var_kwargs ), ) tensor_variable = wrap_fx_proxy( tx=tx, proxy=tx.output.create_proxy( "call_function", get_external_object_by_index, (ind,), {} ), ) else: tensor_variable = wrap_fx_proxy( tx=tx, proxy=tx.output.create_proxy( "call_function", self.value, *proxy_args_kwargs(args, kwargs), ), ) return tensor_variable elif self.value is random.Random: if len(args) == 1 and isinstance(args[0], variables.ConstantVariable): seed = args[0].value else: seed = None random_object = random.Random(seed) return RandomVariable(random_object) elif ( self.value is types.MappingProxyType and len(args) == 1 and isinstance(args[0], variables.ConstDictVariable) ): # types.MappingProxyType is a read-only proxy of the dict. If the # original dict changes, the changes are reflected in proxy as well. return variables.MappingProxyVariable(args[0]) elif SideEffects.cls_supports_mutation_side_effects(self.value) and self.source: with do_not_convert_to_tracable_parameter(): return tx.inline_user_function_return( VariableTracker.build( tx, polyfills.instantiate_user_defined_class_object ), [self, *args], kwargs, ) return super().call_function(tx, args, kwargs) def is_standard_new(self): """Check for __new__ being overridden""" new_fn = inspect.getattr_static(self.value, "__new__", None) if isinstance(new_fn, staticmethod): new_fn = new_fn.__func__ return new_fn is object.__new__ def call_obj_hasattr( self, tx: "InstructionTranslator", name: str ) -> "ConstantVariable": if self.source: source = AttrSource(self.source, name) install_guard(source.make_guard(GuardBuilder.HASATTR)) return variables.ConstantVariable(hasattr(self.value, name)) return super().call_obj_hasattr(tx, name) def const_getattr(self, tx: "InstructionTranslator", name): if name == "__name__": return self.value.__name__ return super().const_getattr(tx, name)
UserDefinedClassVariable
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 15892, "end": 16422 }
class ____(LocalizableStreamlitException): """Exception raised when a component is missing required content.""" def __init__(self, component_name: str) -> None: super().__init__( "Component `{component_name}` must have either JavaScript content " "(`js_content` or `js_url`) or HTML content (`html_content`), or both. " "Please ensure the component definition includes at least one of these.", component_name=component_name, )
BidiComponentMissingContentError
python
tornadoweb__tornado
tornado/test/httpclient_test.py
{ "start": 4453, "end": 4750 }
class ____(RequestHandler): def get(self): self.finish(self.request.headers["Foo"].encode("ISO8859-1")) # These tests end up getting run redundantly: once here with the default # HTTPClient implementation, and then again in each implementation's own # test suite.
HeaderEncodingHandler
python
django__django
tests/aggregation_regress/models.py
{ "start": 1674, "end": 1906 }
class ____(models.Model): ID = models.AutoField(primary_key=True) EntryID = models.ForeignKey( Entries, models.CASCADE, verbose_name="Entry", db_column="Entry ID" ) Clue = models.CharField(max_length=150)
Clues
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/pyodbc.py
{ "start": 17112, "end": 17776 }
class ____: """Wraps binary values in dialect-specific Binary wrapper. If the value is null, return a pyodbc-specific BinaryNull object to prevent pyODBC [and FreeTDS] from defaulting binary NULL types to SQLWCHAR and causing implicit conversion errors. """ def bind_processor(self, dialect): if dialect.dbapi is None: return None DBAPIBinary = dialect.dbapi.Binary def process(value): if value is not None: return DBAPIBinary(value) else: # pyodbc-specific return dialect.dbapi.BinaryNull return process
_ms_binary_pyodbc
python
pypa__pip
src/pip/_internal/resolution/legacy/resolver.py
{ "start": 3696, "end": 24060 }
class ____(BaseResolver): """Resolves which packages need to be installed/uninstalled to perform \ the requested operation without breaking the requirements of any package. """ _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"} def __init__( self, preparer: RequirementPreparer, finder: PackageFinder, wheel_cache: WheelCache | None, make_install_req: InstallRequirementProvider, use_user_site: bool, ignore_dependencies: bool, ignore_installed: bool, ignore_requires_python: bool, force_reinstall: bool, upgrade_strategy: str, py_version_info: tuple[int, ...] | None = None, ) -> None: super().__init__() assert upgrade_strategy in self._allowed_strategies if py_version_info is None: py_version_info = sys.version_info[:3] else: py_version_info = normalize_version_info(py_version_info) self._py_version_info = py_version_info self.preparer = preparer self.finder = finder self.wheel_cache = wheel_cache self.upgrade_strategy = upgrade_strategy self.force_reinstall = force_reinstall self.ignore_dependencies = ignore_dependencies self.ignore_installed = ignore_installed self.ignore_requires_python = ignore_requires_python self.use_user_site = use_user_site self._make_install_req = make_install_req self._discovered_dependencies: DiscoveredDependencies = defaultdict(list) def resolve( self, root_reqs: list[InstallRequirement], check_supported_wheels: bool ) -> RequirementSet: """Resolve what operations need to be done As a side-effect of this method, the packages (and their dependencies) are downloaded, unpacked and prepared for installation. This preparation is done by ``pip.operations.prepare``. Once PyPI has static dependency metadata available, it would be possible to move the preparation to become a step separated from dependency resolution. """ requirement_set = RequirementSet(check_supported_wheels=check_supported_wheels) for req in root_reqs: if req.constraint: check_invalid_constraint_type(req) self._add_requirement_to_set(requirement_set, req) # Actually prepare the files, and collect any exceptions. Most hash # exceptions cannot be checked ahead of time, because # _populate_link() needs to be called before we can make decisions # based on link type. discovered_reqs: list[InstallRequirement] = [] hash_errors = HashErrors() for req in chain(requirement_set.all_requirements, discovered_reqs): try: discovered_reqs.extend(self._resolve_one(requirement_set, req)) except HashError as exc: exc.req = req hash_errors.append(exc) if hash_errors: raise hash_errors return requirement_set def _add_requirement_to_set( self, requirement_set: RequirementSet, install_req: InstallRequirement, parent_req_name: str | None = None, extras_requested: Iterable[str] | None = None, ) -> tuple[list[InstallRequirement], InstallRequirement | None]: """Add install_req as a requirement to install. :param parent_req_name: The name of the requirement that needed this added. The name is used because when multiple unnamed requirements resolve to the same name, we could otherwise end up with dependency links that point outside the Requirements set. parent_req must already be added. Note that None implies that this is a user supplied requirement, vs an inferred one. :param extras_requested: an iterable of extras used to evaluate the environment markers. :return: Additional requirements to scan. That is either [] if the requirement is not applicable, or [install_req] if the requirement is applicable and has just been added. """ # If the markers do not match, ignore this requirement. if not install_req.match_markers(extras_requested): logger.info( "Ignoring %s: markers '%s' don't match your environment", install_req.name, install_req.markers, ) return [], None # If the wheel is not supported, raise an error. # Should check this after filtering out based on environment markers to # allow specifying different wheels based on the environment/OS, in a # single requirements file. if install_req.link and install_req.link.is_wheel: wheel = Wheel(install_req.link.filename) tags = compatibility_tags.get_supported() if requirement_set.check_supported_wheels and not wheel.supported(tags): raise InstallationError( f"{wheel.filename} is not a supported wheel on this platform." ) # This next bit is really a sanity check. assert ( not install_req.user_supplied or parent_req_name is None ), "a user supplied req shouldn't have a parent" # Unnamed requirements are scanned again and the requirement won't be # added as a dependency until after scanning. if not install_req.name: requirement_set.add_unnamed_requirement(install_req) return [install_req], None try: existing_req: InstallRequirement | None = requirement_set.get_requirement( install_req.name ) except KeyError: existing_req = None has_conflicting_requirement = ( parent_req_name is None and existing_req and not existing_req.constraint and existing_req.extras == install_req.extras and existing_req.req and install_req.req and existing_req.req.specifier != install_req.req.specifier ) if has_conflicting_requirement: raise InstallationError( f"Double requirement given: {install_req} " f"(already in {existing_req}, name={install_req.name!r})" ) # When no existing requirement exists, add the requirement as a # dependency and it will be scanned again after. if not existing_req: requirement_set.add_named_requirement(install_req) # We'd want to rescan this requirement later return [install_req], install_req # Assume there's no need to scan, and that we've already # encountered this for scanning. if install_req.constraint or not existing_req.constraint: return [], existing_req does_not_satisfy_constraint = install_req.link and not ( existing_req.link and install_req.link.path == existing_req.link.path ) if does_not_satisfy_constraint: raise InstallationError( f"Could not satisfy constraints for '{install_req.name}': " "installation from path or url cannot be " "constrained to a version" ) # If we're now installing a constraint, mark the existing # object for real installation. existing_req.constraint = False # If we're now installing a user supplied requirement, # mark the existing object as such. if install_req.user_supplied: existing_req.user_supplied = True existing_req.extras = tuple( sorted(set(existing_req.extras) | set(install_req.extras)) ) logger.debug( "Setting %s extras to: %s", existing_req, existing_req.extras, ) # Return the existing requirement for addition to the parent and # scanning again. return [existing_req], existing_req def _is_upgrade_allowed(self, req: InstallRequirement) -> bool: if self.upgrade_strategy == "to-satisfy-only": return False elif self.upgrade_strategy == "eager": return True else: assert self.upgrade_strategy == "only-if-needed" return req.user_supplied or req.constraint def _set_req_to_reinstall(self, req: InstallRequirement) -> None: """ Set a requirement to be installed. """ # Don't uninstall the conflict if doing a user install and the # conflict is not a user install. assert req.satisfied_by is not None if not self.use_user_site or req.satisfied_by.in_usersite: req.should_reinstall = True req.satisfied_by = None def _check_skip_installed(self, req_to_install: InstallRequirement) -> str | None: """Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only have satisfied_by set to None if the req_to_install is to be upgraded/reinstalled etc. Any other value will be a dist recording the current thing installed that satisfies the requirement. Note that for vcs urls and the like we can't assess skipping in this routine - we simply identify that we need to pull the thing down, then later on it is pulled down and introspected to assess upgrade/ reinstalls etc. :return: A text reason for why it was skipped, or None. """ if self.ignore_installed: return None req_to_install.check_if_exists(self.use_user_site) if not req_to_install.satisfied_by: return None if self.force_reinstall: self._set_req_to_reinstall(req_to_install) return None if not self._is_upgrade_allowed(req_to_install): if self.upgrade_strategy == "only-if-needed": return "already satisfied, skipping upgrade" return "already satisfied" # Check for the possibility of an upgrade. For link-based # requirements we have to pull the tree down and inspect to assess # the version #, so it's handled way down. if not req_to_install.link: try: self.finder.find_requirement(req_to_install, upgrade=True) except BestVersionAlreadyInstalled: # Then the best version is installed. return "already up-to-date" except DistributionNotFound: # No distribution found, so we squash the error. It will # be raised later when we re-try later to do the install. # Why don't we just raise here? pass self._set_req_to_reinstall(req_to_install) return None def _find_requirement_link(self, req: InstallRequirement) -> Link | None: upgrade = self._is_upgrade_allowed(req) best_candidate = self.finder.find_requirement(req, upgrade) if not best_candidate: return None # Log a warning per PEP 592 if necessary before returning. link = best_candidate.link if link.is_yanked: reason = link.yanked_reason or "<none given>" msg = ( # Mark this as a unicode string to prevent # "UnicodeEncodeError: 'ascii' codec can't encode character" # in Python 2 when the reason contains non-ascii characters. "The candidate selected for download or install is a " f"yanked version: {best_candidate}\n" f"Reason for being yanked: {reason}" ) logger.warning(msg) return link def _populate_link(self, req: InstallRequirement) -> None: """Ensure that if a link can be found for this, that it is found. Note that req.link may still be None - if the requirement is already installed and not needed to be upgraded based on the return value of _is_upgrade_allowed(). If preparer.require_hashes is True, don't use the wheel cache, because cached wheels, always built locally, have different hashes than the files downloaded from the index server and thus throw false hash mismatches. Furthermore, cached wheels at present have undeterministic contents due to file modification times. """ if req.link is None: req.link = self._find_requirement_link(req) if self.wheel_cache is None or self.preparer.require_hashes: return assert req.link is not None, "_find_requirement_link unexpectedly returned None" cache_entry = self.wheel_cache.get_cache_entry( link=req.link, package_name=req.name, supported_tags=get_supported(), ) if cache_entry is not None: logger.debug("Using cached wheel link: %s", cache_entry.link) if req.link is req.original_link and cache_entry.persistent: req.cached_wheel_source_link = req.link if cache_entry.origin is not None: req.download_info = cache_entry.origin else: # Legacy cache entry that does not have origin.json. # download_info may miss the archive_info.hashes field. req.download_info = direct_url_from_link( req.link, link_is_in_wheel_cache=cache_entry.persistent ) req.link = cache_entry.link def _get_dist_for(self, req: InstallRequirement) -> BaseDistribution: """Takes a InstallRequirement and returns a single AbstractDist \ representing a prepared variant of the same. """ if req.editable: return self.preparer.prepare_editable_requirement(req) # satisfied_by is only evaluated by calling _check_skip_installed, # so it must be None here. assert req.satisfied_by is None skip_reason = self._check_skip_installed(req) if req.satisfied_by: return self.preparer.prepare_installed_requirement(req, skip_reason) # We eagerly populate the link, since that's our "legacy" behavior. self._populate_link(req) dist = self.preparer.prepare_linked_requirement(req) # NOTE # The following portion is for determining if a certain package is # going to be re-installed/upgraded or not and reporting to the user. # This should probably get cleaned up in a future refactor. # req.req is only avail after unpack for URL # pkgs repeat check_if_exists to uninstall-on-upgrade # (#14) if not self.ignore_installed: req.check_if_exists(self.use_user_site) if req.satisfied_by: should_modify = ( self.upgrade_strategy != "to-satisfy-only" or self.force_reinstall or self.ignore_installed or req.link.scheme == "file" ) if should_modify: self._set_req_to_reinstall(req) else: logger.info( "Requirement already satisfied (use --upgrade to upgrade): %s", req, ) return dist def _resolve_one( self, requirement_set: RequirementSet, req_to_install: InstallRequirement, ) -> list[InstallRequirement]: """Prepare a single requirements file. :return: A list of additional InstallRequirements to also install. """ # Tell user what we are doing for this requirement: # obtain (editable), skipping, processing (local url), collecting # (remote url or package name) if req_to_install.constraint or req_to_install.prepared: return [] req_to_install.prepared = True # Parse and return dependencies dist = self._get_dist_for(req_to_install) # This will raise UnsupportedPythonVersion if the given Python # version isn't compatible with the distribution's Requires-Python. _check_dist_requires_python( dist, version_info=self._py_version_info, ignore_requires_python=self.ignore_requires_python, ) more_reqs: list[InstallRequirement] = [] def add_req(subreq: Requirement, extras_requested: Iterable[str]) -> None: # This idiosyncratically converts the Requirement to str and let # make_install_req then parse it again into Requirement. But this is # the legacy resolver so I'm just not going to bother refactoring. sub_install_req = self._make_install_req(str(subreq), req_to_install) parent_req_name = req_to_install.name to_scan_again, add_to_parent = self._add_requirement_to_set( requirement_set, sub_install_req, parent_req_name=parent_req_name, extras_requested=extras_requested, ) if parent_req_name and add_to_parent: self._discovered_dependencies[parent_req_name].append(add_to_parent) more_reqs.extend(to_scan_again) with indent_log(): # We add req_to_install before its dependencies, so that we # can refer to it when adding dependencies. assert req_to_install.name is not None if not requirement_set.has_requirement(req_to_install.name): # 'unnamed' requirements will get added here # 'unnamed' requirements can only come from being directly # provided by the user. assert req_to_install.user_supplied self._add_requirement_to_set( requirement_set, req_to_install, parent_req_name=None ) if not self.ignore_dependencies: if req_to_install.extras: logger.debug( "Installing extra requirements: %r", ",".join(req_to_install.extras), ) missing_requested = sorted( set(req_to_install.extras) - set(dist.iter_provided_extras()) ) for missing in missing_requested: logger.warning( "%s %s does not provide the extra '%s'", dist.raw_name, dist.version, missing, ) available_requested = sorted( set(dist.iter_provided_extras()) & set(req_to_install.extras) ) for subreq in dist.iter_dependencies(available_requested): add_req(subreq, extras_requested=available_requested) return more_reqs def get_installation_order( self, req_set: RequirementSet ) -> list[InstallRequirement]: """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. """ # The current implementation, which we may change at any point # installs the user specified things in the order given, except when # dependencies must come earlier to achieve topological order. order = [] ordered_reqs: set[InstallRequirement] = set() def schedule(req: InstallRequirement) -> None: if req.satisfied_by or req in ordered_reqs: return if req.constraint: return ordered_reqs.add(req) for dep in self._discovered_dependencies[req.name]: schedule(dep) order.append(req) for install_req in req_set.requirements.values(): schedule(install_req) return order
Resolver
python
walkccc__LeetCode
solutions/3271. Hash Divided String/3271.py
{ "start": 0, "end": 292 }
class ____: def stringHash(self, s: str, k: int) -> str: ans = [] for i in range(0, len(s), k): sumHash = sum(string.ascii_lowercase.index(s[j]) for j in range(i, i + k)) ans.append(string.ascii_lowercase[sumHash % 26]) return ''.join(ans)
Solution
python
ray-project__ray
python/ray/util/client/common.py
{ "start": 6523, "end": 8379 }
class ____(raylet.ActorID): def __init__( self, id: Union[bytes, Future], weak_ref: Optional[bool] = False, ): self._weak_ref = weak_ref self._mutex = threading.Lock() self._worker = ray.get_context().client_worker if isinstance(id, bytes): self._set_id(id) self._id_future = None elif isinstance(id, Future): self._id_future = id else: raise TypeError("Unexpected type for id {}".format(id)) def __del__(self): if self._weak_ref: return if self._worker is not None and self._worker.is_connected(): try: if not self.is_nil(): self._worker.call_release(self.id) except Exception: logger.debug( "Exception from actor creation is ignored in destructor. " "To receive this exception in application code, call " "a method on the actor reference before its destructor " "is run." ) def binary(self): self._wait_for_id() return super().binary() def hex(self): self._wait_for_id() return super().hex() def is_nil(self): self._wait_for_id() return super().is_nil() def __hash__(self): self._wait_for_id() return hash(self.id) @property def id(self): return self.binary() def _set_id(self, id): super()._set_id(id) self._worker.call_retain(id) def _wait_for_id(self, timeout=None): if self._id_future: with self._mutex: if self._id_future: self._set_id(self._id_future.result(timeout=timeout)) self._id_future = None
ClientActorRef
python
getsentry__sentry
src/sentry/models/groupassignee.py
{ "start": 9467, "end": 10982 }
class ____(Model): """ Identifies an assignment relationship between a user/team and an aggregated event (Group). """ __relocation_scope__ = RelocationScope.Excluded objects: ClassVar[GroupAssigneeManager] = GroupAssigneeManager() project = FlexibleForeignKey("sentry.Project", related_name="assignee_set") group = FlexibleForeignKey("sentry.Group", related_name="assignee_set", unique=True) user_id = HybridCloudForeignKey(settings.AUTH_USER_MODEL, on_delete="CASCADE", null=True) team = FlexibleForeignKey("sentry.Team", related_name="sentry_assignee_set", null=True) date_added = models.DateTimeField(default=timezone.now) class Meta: app_label = "sentry" db_table = "sentry_groupasignee" unique_together = [("project", "group")] __repr__ = sane_repr("group_id", "user_id", "team_id") def save(self, *args: Any, **kwargs: Any) -> None: assert not (self.user_id is not None and self.team_id is not None) and not ( self.user_id is None and self.team_id is None ), "Must have Team or User, not both" super().save(*args, **kwargs) def assigned_actor(self) -> Actor: if self.user_id is not None: return Actor( id=self.user_id, actor_type=ActorType.USER, ) if self.team_id is not None: return Actor(id=self.team_id, actor_type=ActorType.TEAM) raise NotImplementedError("Unknown Assignee")
GroupAssignee
python
getsentry__sentry
src/sentry/replays/_case_studies/INC_1184_consumer_backlog_from_increased_threads/report.py
{ "start": 1242, "end": 1545 }
class ____(ProcessingStrategy[FilteredPayload | None]): def __init__(self): self.consumed_count = 0 def submit(self, message): self.consumed_count += 1 def poll(self): ... def close(self): ... def join(self, timeout=None): ... def terminate(self): ...
Consumer
python
huggingface__transformers
src/transformers/models/qwen2/modeling_qwen2.py
{ "start": 14521, "end": 15062 }
class ____(PreTrainedModel): config: Qwen2Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Qwen2DecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _can_compile_fullgraph = True _supports_attention_backend = True _can_record_outputs = { "hidden_states": Qwen2DecoderLayer, "attentions": Qwen2Attention, } @auto_docstring
Qwen2PreTrainedModel
python
viewflow__viewflow
tests/test_urls__base.py
{ "start": 426, "end": 608 }
class ____(NestedViewset): app_name = "nested" page_path = path( "page2/", TemplateView.as_view(template_name="viewflow/base.html"), name="page" )
InheritedViewset
python
plotly__plotly.py
plotly/graph_objs/carpet/aaxis/_title.py
{ "start": 233, "end": 3564 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "carpet.aaxis" _path_str = "carpet.aaxis.title" _valid_props = {"font", "offset", "text"} @property def font(self): """ Sets this axis' title font. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.carpet.aaxis.title.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.carpet.aaxis.title.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def offset(self): """ An additional amount by which to offset the title from the tick labels, given in pixels. The 'offset' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["offset"] @offset.setter def offset(self, val): self["offset"] = val @property def text(self): """ Sets the title of this axis. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def _prop_descriptions(self): return """\ font Sets this axis' title font. offset An additional amount by which to offset the title from the tick labels, given in pixels. text Sets the title of this axis. """ def __init__(self, arg=None, font=None, offset=None, text=None, **kwargs): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.carpet.aaxis.Title` font Sets this axis' title font. offset An additional amount by which to offset the title from the tick labels, given in pixels. text Sets the title of this axis. Returns ------- Title """ super().__init__("title") 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.carpet.aaxis.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.carpet.aaxis.Title`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("font", arg, font) self._set_property("offset", arg, offset) self._set_property("text", arg, text) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Title
python
huggingface__transformers
tests/models/canine/test_modeling_canine.py
{ "start": 20795, "end": 36418 }
class ____(unittest.TestCase): @slow def test_inference_no_head(self): model = CanineModel.from_pretrained("google/canine-s") # this one corresponds to the first example of the TydiQA dev set (in Swahili) # fmt: off input_ids = [57344, 57349, 85, 107, 117, 98, 119, 97, 32, 119, 97, 32, 82, 105, 106, 105, 108, 105, 32, 75, 97, 110, 116, 111, 114, 105, 32, 110, 105, 32, 107, 105, 97, 115, 105, 32, 103, 97, 110, 105, 63, 57345, 57350, 32, 82, 105, 106, 105, 108, 105, 32, 75, 97, 110, 116, 111, 114, 105, 32, 44, 32, 82, 105, 106, 105, 108, 105, 32, 75, 97, 110, 116, 97, 114, 117, 115, 105, 32, 97, 117, 32, 105, 110, 103, 46, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 40, 112, 105, 97, 58, 32, 84, 111, 108, 105, 109, 97, 110, 32, 97, 117, 32, 82, 105, 103, 105, 108, 32, 75, 101, 110, 116, 97, 117, 114, 117, 115, 41, 32, 110, 105, 32, 110, 121, 111, 116, 97, 32, 105, 110, 97, 121, 111, 110, 103, 39, 97, 97, 32, 115, 97, 110, 97, 32, 107, 97, 116, 105, 107, 97, 32, 97, 110, 103, 97, 32, 121, 97, 32, 107, 117, 115, 105, 110, 105, 32, 107, 119, 101, 110, 121, 101, 32, 107, 117, 110, 100, 105, 110, 121, 111, 116, 97, 32, 121, 97, 32, 75, 97, 110, 116, 97, 114, 117, 115, 105, 32, 40, 112, 105, 97, 58, 32, 105, 110, 103, 46, 32, 67, 101, 110, 116, 97, 117, 114, 117, 115, 41, 46, 32, 78, 105, 32, 110, 121, 111, 116, 97, 32, 121, 97, 32, 107, 117, 110, 103, 97, 97, 32, 115, 97, 110, 97, 32, 121, 97, 32, 110, 110, 101, 32, 97, 110, 103, 97, 110, 105, 32, 108, 97, 107, 105, 110, 105, 32, 104, 97, 105, 111, 110, 101, 107, 97, 110, 105, 32, 107, 119, 101, 110, 121, 101, 32, 110, 117, 115, 117, 100, 117, 110, 105, 97, 32, 121, 97, 32, 107, 97, 115, 107, 97, 122, 105, 110, 105, 46, 32, 57351, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 110, 105, 32, 110, 121, 111, 116, 97, 32, 121, 97, 32, 112, 101, 107, 101, 101, 32, 107, 119, 97, 32, 115, 97, 98, 97, 98, 117, 32, 110, 105, 32, 110, 121, 111, 116, 97, 32, 121, 101, 116, 117, 32, 106, 105, 114, 97, 110, 105, 32, 107, 97, 116, 105, 107, 97, 32, 97, 110, 103, 97, 32, 105, 110, 97, 32, 117, 109, 98, 97, 108, 105, 32, 119, 97, 32, 109, 105, 97, 107, 97, 32, 121, 97, 32, 110, 117, 114, 117, 32, 52, 46, 50, 46, 32, 73, 110, 97, 111, 110, 101, 107, 97, 110, 97, 32, 97, 110, 103, 97, 110, 105, 32, 107, 97, 114, 105, 98, 117, 32, 110, 97, 32, 107, 117, 110, 100, 105, 110, 121, 111, 116, 97, 32, 121, 97, 32, 83, 97, 108, 105, 98, 117, 32, 40, 67, 114, 117, 120, 41, 46, 32, 57352, 32, 82, 105, 106, 105, 108, 105, 32, 75, 97, 110, 116, 97, 114, 117, 115, 105, 32, 40, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 41, 32, 105, 110, 97, 111, 110, 101, 107, 97, 110, 97, 32, 107, 97, 109, 97, 32, 110, 121, 111, 116, 97, 32, 109, 111, 106, 97, 32, 108, 97, 107, 105, 110, 105, 32, 107, 119, 97, 32, 100, 97, 114, 117, 98, 105, 110, 105, 32, 107, 117, 98, 119, 97, 32, 105, 110, 97, 111, 110, 101, 107, 97, 110, 97, 32, 107, 117, 119, 97, 32, 109, 102, 117, 109, 111, 32, 119, 97, 32, 110, 121, 111, 116, 97, 32, 116, 97, 116, 117, 32, 122, 105, 110, 97, 122, 111, 107, 97, 97, 32, 107, 97, 114, 105, 98, 117, 32, 110, 97, 32, 107, 117, 115, 104, 105, 107, 97, 109, 97, 110, 97, 32, 107, 97, 116, 105, 32, 121, 97, 111, 46, 32, 78, 121, 111, 116, 97, 32, 109, 97, 112, 97, 99, 104, 97, 32, 122, 97, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 65, 32, 110, 97, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 66, 32, 122, 105, 107, 111, 32, 109, 105, 97, 107, 97, 32, 121, 97, 32, 110, 117, 114, 117, 32, 52, 46, 51, 54, 32, 107, 117, 116, 111, 107, 97, 32, 107, 119, 101, 116, 117, 32, 110, 97, 32, 110, 121, 111, 116, 97, 32, 121, 97, 32, 116, 97, 116, 117, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 67, 32, 97, 117, 32, 80, 114, 111, 120, 105, 109, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 105, 110, 97, 32, 117, 109, 98, 97, 108, 105, 32, 119, 97, 32, 109, 105, 97, 107, 97, 32, 121, 97, 32, 110, 117, 114, 117, 32, 52, 46, 50, 50, 46, 32, 57353, 32, 80, 114, 111, 120, 105, 109, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 40, 121, 97, 97, 110, 105, 32, 110, 121, 111, 116, 97, 32, 121, 97, 32, 75, 97, 110, 116, 97, 114, 117, 115, 105, 32, 105, 108, 105, 121, 111, 32, 107, 97, 114, 105, 98, 117, 32, 122, 97, 105, 100, 105, 32, 110, 97, 115, 105, 41, 32, 105, 109, 101, 103, 117, 110, 100, 117, 108, 105, 119, 97, 32, 107, 117, 119, 97, 32, 110, 97, 32, 115, 97, 121, 97, 114, 105, 32, 109, 111, 106, 97, 46, 32, 86, 105, 112, 105, 109, 111, 32, 118, 105, 110, 97, 118, 121, 111, 112, 97, 116, 105, 107, 97, 110, 97, 32, 104, 97, 100, 105, 32, 115, 97, 115, 97, 32, 122, 105, 110, 97, 111, 110, 121, 101, 115, 104, 97, 32, 117, 119, 101, 122, 101, 107, 97, 110, 111, 32, 109, 107, 117, 98, 119, 97, 32, 121, 97, 32, 107, 119, 97, 109, 98, 97, 32, 115, 97, 121, 97, 114, 105, 32, 104, 105, 105, 32, 110, 105, 32, 121, 97, 32, 109, 119, 97, 109, 98, 97, 32, 40, 107, 97, 109, 97, 32, 100, 117, 110, 105, 97, 32, 121, 101, 116, 117, 44, 32, 77, 105, 114, 105, 104, 105, 32, 97, 117, 32, 90, 117, 104, 117, 114, 97, 41, 32, 110, 97, 32, 105, 110, 97, 119, 101, 122, 97, 32, 107, 117, 119, 97, 32, 110, 97, 32, 97, 110, 103, 97, 104, 101, 119, 97, 44, 32, 116, 101, 110, 97, 32, 107, 97, 116, 105, 107, 97, 32, 117, 112, 101, 111, 32, 119, 97, 32, 106, 111, 116, 111, 32, 117, 110, 97, 111, 114, 117, 104, 117, 115, 117, 32, 107, 117, 119, 101, 112, 111, 32, 107, 119, 97, 32, 117, 104, 97, 105, 46, 32, 91, 49, 93, 57345, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] attention_mask = [1 if x != 0 else 0 for x in input_ids] token_type_ids = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # fmt: on input_ids = torch.tensor([input_ids]) attention_mask = torch.tensor([attention_mask]) token_type_ids = torch.tensor([token_type_ids]) outputs = model(input_ids, attention_mask, token_type_ids) # verify sequence output expected_shape = torch.Size((1, 2048, 768)) self.assertEqual(outputs.last_hidden_state.shape, expected_shape) expected_slice = torch.tensor( [ [-0.161433131, 0.395568609, 0.0407391489], [-0.108025983, 0.362060368, -0.544592619], [-0.141537309, 0.180541009, 0.076907], ] ) torch.testing.assert_close(outputs.last_hidden_state[0, :3, :3], expected_slice, rtol=1e-2, atol=1e-2) # verify pooled output expected_shape = torch.Size((1, 768)) self.assertEqual(outputs.pooler_output.shape, expected_shape) expected_slice = torch.tensor([-0.884311497, -0.529064834, 0.723164916]) torch.testing.assert_close(outputs.pooler_output[0, :3], expected_slice, rtol=1e-2, atol=1e-2)
CanineModelIntegrationTest
python
huggingface__transformers
src/transformers/models/mistral/modeling_mistral.py
{ "start": 11825, "end": 14844 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: MistralConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.config = config self.rope_type = self.config.rope_parameters["rope_type"] rope_init_fn: Callable = self.compute_default_rope_parameters if self.rope_type != "default": rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.original_inv_freq = inv_freq @staticmethod def compute_default_rope_parameters( config: Optional[MistralConfig] = None, device: Optional["torch.device"] = None, seq_len: Optional[int] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Unused for this type of RoPE. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies inv_freq = 1.0 / ( base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim) ) return inv_freq, attention_factor @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) position_ids_expanded = position_ids[:, None, :].float() device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) @auto_docstring
MistralRotaryEmbedding
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/pipes_tests/in_process_client.py
{ "start": 2767, "end": 4564 }
class ____(dg.PipesClient, TreatAsResourceParam): """An in-process pipes clients unusable in test cases. A function inside the orchestration process actually serves as the "external" execution. This allows us to test the inner machinery of pipes without actually launching subprocesses, which makes the tests much more lightweight and repeatable. """ @public def run( # pyright: ignore[reportIncompatibleMethodOverride] self, *, context: Union[dg.OpExecutionContext, dg.AssetExecutionContext], fn: Callable[[PipesContext], None], extras: Optional[PipesExtras] = None, metadata: Optional[RawMetadataMapping] = None, # metadata to attach to all materializations ) -> PipesClientCompletedInvocation: pipes_context_data = build_external_execution_context_data(context=context, extras=extras) pipes_context_loader = InProcessPipesContextLoader(pipes_context_data) pipes_message_writer = InProcessPipesMessageWriter() with ( PipesContext( # construct PipesContext directly to avoid env var check in open_dagster_pipes context_loader=pipes_context_loader, message_writer=pipes_message_writer, params_loader=InProcessPipesParamLoader(), ) as pipes_context ): with dg.open_pipes_session( context=context, context_injector=InProcessContextInjector(), message_reader=InProcessMessageReader( pipes_message_writer, pipes_context=pipes_context, ), ) as session: fn(pipes_context) return PipesClientCompletedInvocation(session, metadata=metadata)
InProcessPipesClient
python
kamyu104__LeetCode-Solutions
Python/apply-discount-to-prices.py
{ "start": 917, "end": 1321 }
class ____(object): def discountPrices(self, sentence, discount): """ :type sentence: str :type discount: int :rtype: str """ def format(discount, x): return "${:d}.{:02d}".format(*divmod(int(x[1:])*(100-discount), 100)) if x[0] == '$' and x[1:].isdigit() else x return " ".join(format(discount, x) for x in sentence.split())
Solution2
python
pytorch__pytorch
test/jit/test_torchbind.py
{ "start": 615, "end": 16167 }
class ____(JitTestCase): def setUp(self): load_torchbind_test_lib() def test_torchbind(self): def test_equality(f, cmp_key): obj1 = f() obj2 = torch.jit.script(f)() return (cmp_key(obj1), cmp_key(obj2)) def f(): val = torch.classes._TorchScriptTesting._Foo(5, 3) val.increment(1) return val test_equality(f, lambda x: x) with self.assertRaisesRegex(RuntimeError, "Expected a value of type 'int'"): val = torch.classes._TorchScriptTesting._Foo(5, 3) val.increment("foo") def f(): ss = torch.classes._TorchScriptTesting._StackString(["asdf", "bruh"]) return ss.pop() test_equality(f, lambda x: x) def f(): ss1 = torch.classes._TorchScriptTesting._StackString(["asdf", "bruh"]) ss2 = torch.classes._TorchScriptTesting._StackString(["111", "222"]) ss1.push(ss2.pop()) return ss1.pop() + ss2.pop() test_equality(f, lambda x: x) # test nn module with prepare_scriptable function class NonJitableClass: def __init__(self, int1, int2): self.int1 = int1 self.int2 = int2 def return_vals(self): return self.int1, self.int2 class CustomWrapper(torch.nn.Module): def __init__(self, foo): super().__init__() self.foo = foo def forward(self) -> None: self.foo.increment(1) return def __prepare_scriptable__(self): int1, int2 = self.foo.return_vals() foo = torch.classes._TorchScriptTesting._Foo(int1, int2) return CustomWrapper(foo) foo = CustomWrapper(NonJitableClass(1, 2)) jit_foo = torch.jit.script(foo) def test_torchbind_take_as_arg(self): global StackString # see [local resolution in python] StackString = torch.classes._TorchScriptTesting._StackString def foo(stackstring): # type: (StackString) stackstring.push("lel") return stackstring script_input = torch.classes._TorchScriptTesting._StackString([]) scripted = torch.jit.script(foo) script_output = scripted(script_input) self.assertEqual(script_output.pop(), "lel") def test_torchbind_return_instance(self): def foo(): ss = torch.classes._TorchScriptTesting._StackString(["hi", "mom"]) return ss scripted = torch.jit.script(foo) # Ensure we are creating the object and calling __init__ # rather than calling the __init__wrapper nonsense fc = ( FileCheck() .check("prim::CreateObject()") .check('prim::CallMethod[name="__init__"]') ) fc.run(str(scripted.graph)) out = scripted() self.assertEqual(out.pop(), "mom") self.assertEqual(out.pop(), "hi") def test_torchbind_return_instance_from_method(self): def foo(): ss = torch.classes._TorchScriptTesting._StackString(["hi", "mom"]) clone = ss.clone() ss.pop() return ss, clone scripted = torch.jit.script(foo) out = scripted() self.assertEqual(out[0].pop(), "hi") self.assertEqual(out[1].pop(), "mom") self.assertEqual(out[1].pop(), "hi") def test_torchbind_def_property_getter_setter(self): def foo_getter_setter_full(): fooGetterSetter = torch.classes._TorchScriptTesting._FooGetterSetter(5, 6) # getX method intentionally adds 2 to x old = fooGetterSetter.x # setX method intentionally adds 2 to x fooGetterSetter.x = old + 4 new = fooGetterSetter.x return old, new self.checkScript(foo_getter_setter_full, ()) def foo_getter_setter_lambda(): foo = torch.classes._TorchScriptTesting._FooGetterSetterLambda(5) old = foo.x foo.x = old + 4 new = foo.x return old, new self.checkScript(foo_getter_setter_lambda, ()) def test_torchbind_def_property_just_getter(self): def foo_just_getter(): fooGetterSetter = torch.classes._TorchScriptTesting._FooGetterSetter(5, 6) # getY method intentionally adds 4 to x return fooGetterSetter, fooGetterSetter.y scripted = torch.jit.script(foo_just_getter) out, result = scripted() self.assertEqual(result, 10) with self.assertRaisesRegex(RuntimeError, "can't set attribute"): out.y = 5 def foo_not_setter(): fooGetterSetter = torch.classes._TorchScriptTesting._FooGetterSetter(5, 6) old = fooGetterSetter.y fooGetterSetter.y = old + 4 # getY method intentionally adds 4 to x return fooGetterSetter.y with self.assertRaisesRegexWithHighlight( RuntimeError, "Tried to set read-only attribute: y", "fooGetterSetter.y = old + 4", ): scripted = torch.jit.script(foo_not_setter) def test_torchbind_def_property_readwrite(self): def foo_readwrite(): fooReadWrite = torch.classes._TorchScriptTesting._FooReadWrite(5, 6) old = fooReadWrite.x fooReadWrite.x = old + 4 return fooReadWrite.x, fooReadWrite.y self.checkScript(foo_readwrite, ()) def foo_readwrite_error(): fooReadWrite = torch.classes._TorchScriptTesting._FooReadWrite(5, 6) fooReadWrite.y = 5 return fooReadWrite with self.assertRaisesRegexWithHighlight( RuntimeError, "Tried to set read-only attribute: y", "fooReadWrite.y = 5" ): scripted = torch.jit.script(foo_readwrite_error) def test_torchbind_take_instance_as_method_arg(self): def foo(): ss = torch.classes._TorchScriptTesting._StackString(["mom"]) ss2 = torch.classes._TorchScriptTesting._StackString(["hi"]) ss.merge(ss2) return ss scripted = torch.jit.script(foo) out = scripted() self.assertEqual(out.pop(), "hi") self.assertEqual(out.pop(), "mom") def test_torchbind_return_tuple(self): def f(): val = torch.classes._TorchScriptTesting._StackString(["3", "5"]) return val.return_a_tuple() scripted = torch.jit.script(f) tup = scripted() self.assertEqual(tup, (1337.0, 123)) def test_torchbind_save_load(self): def foo(): ss = torch.classes._TorchScriptTesting._StackString(["mom"]) ss2 = torch.classes._TorchScriptTesting._StackString(["hi"]) ss.merge(ss2) return ss scripted = torch.jit.script(foo) self.getExportImportCopy(scripted) def test_torchbind_lambda_method(self): def foo(): ss = torch.classes._TorchScriptTesting._StackString(["mom"]) return ss.top() scripted = torch.jit.script(foo) self.assertEqual(scripted(), "mom") def test_torchbind_class_attr_recursive(self): class FooBar(torch.nn.Module): def __init__(self, foo_model): super().__init__() self.foo_mod = foo_model def forward(self) -> int: return self.foo_mod.info() def to_ivalue(self): torchbind_model = torch.classes._TorchScriptTesting._Foo( self.foo_mod.info(), 1 ) return FooBar(torchbind_model) inst = FooBar(torch.classes._TorchScriptTesting._Foo(2, 3)) scripted = torch.jit.script(inst.to_ivalue()) self.assertEqual(scripted(), 6) def test_torchbind_class_attribute(self): class FooBar1234(torch.nn.Module): def __init__(self) -> None: super().__init__() self.f = torch.classes._TorchScriptTesting._StackString(["3", "4"]) def forward(self): return self.f.top() inst = FooBar1234() scripted = torch.jit.script(inst) eic = self.getExportImportCopy(scripted) assert eic() == "deserialized" for expected in ["deserialized", "was", "i"]: assert eic.f.pop() == expected def test_torchbind_getstate(self): class FooBar4321(torch.nn.Module): def __init__(self) -> None: super().__init__() self.f = torch.classes._TorchScriptTesting._PickleTester([3, 4]) def forward(self): return self.f.top() inst = FooBar4321() scripted = torch.jit.script(inst) eic = self.getExportImportCopy(scripted) # NB: we expect the values {7, 3, 3, 1} as __getstate__ is defined to # return {1, 3, 3, 7}. I tried to make this actually depend on the # values at instantiation in the test with some transformation, but # because it seems we serialize/deserialize multiple times, that # transformation isn't as you would it expect it to be. assert eic() == 7 for expected in [7, 3, 3, 1]: assert eic.f.pop() == expected def test_torchbind_deepcopy(self): class FooBar4321(torch.nn.Module): def __init__(self) -> None: super().__init__() self.f = torch.classes._TorchScriptTesting._PickleTester([3, 4]) def forward(self): return self.f.top() inst = FooBar4321() scripted = torch.jit.script(inst) copied = copy.deepcopy(scripted) assert copied.forward() == 7 for expected in [7, 3, 3, 1]: assert copied.f.pop() == expected def test_torchbind_python_deepcopy(self): class FooBar4321(torch.nn.Module): def __init__(self) -> None: super().__init__() self.f = torch.classes._TorchScriptTesting._PickleTester([3, 4]) def forward(self): return self.f.top() inst = FooBar4321() copied = copy.deepcopy(inst) assert copied() == 7 for expected in [7, 3, 3, 1]: assert copied.f.pop() == expected def test_torchbind_tracing(self): class TryTracing(torch.nn.Module): def __init__(self) -> None: super().__init__() self.f = torch.classes._TorchScriptTesting._PickleTester([3, 4]) def forward(self): return torch.ops._TorchScriptTesting.take_an_instance(self.f) traced = torch.jit.trace(TryTracing(), ()) self.assertEqual(torch.zeros(4, 4), traced()) def test_torchbind_pass_wrong_type(self): with self.assertRaisesRegex(RuntimeError, "but instead found type 'Tensor'"): torch.ops._TorchScriptTesting.take_an_instance(torch.rand(3, 4)) def test_torchbind_tracing_nested(self): class TryTracingNest(torch.nn.Module): def __init__(self) -> None: super().__init__() self.f = torch.classes._TorchScriptTesting._PickleTester([3, 4]) class TryTracing123(torch.nn.Module): def __init__(self) -> None: super().__init__() self.nest = TryTracingNest() def forward(self): return torch.ops._TorchScriptTesting.take_an_instance(self.nest.f) traced = torch.jit.trace(TryTracing123(), ()) self.assertEqual(torch.zeros(4, 4), traced()) def test_torchbind_pickle_serialization(self): nt = torch.classes._TorchScriptTesting._PickleTester([3, 4]) b = io.BytesIO() torch.save(nt, b) b.seek(0) # weights_only=False as trying to load ScriptObject nt_loaded = torch.load(b, weights_only=False) for exp in [7, 3, 3, 1]: self.assertEqual(nt_loaded.pop(), exp) def test_torchbind_instantiate_missing_class(self): with self.assertRaisesRegex( RuntimeError, "Tried to instantiate class 'foo.IDontExist', but it does not exist!", ): torch.classes.foo.IDontExist(3, 4, 5) def test_torchbind_optional_explicit_attr(self): class TorchBindOptionalExplicitAttr(torch.nn.Module): foo: Optional[torch.classes._TorchScriptTesting._StackString] def __init__(self) -> None: super().__init__() self.foo = torch.classes._TorchScriptTesting._StackString(["test"]) def forward(self) -> str: foo_obj = self.foo if foo_obj is not None: return foo_obj.pop() else: return "<None>" mod = TorchBindOptionalExplicitAttr() scripted = torch.jit.script(mod) def test_torchbind_no_init(self): with self.assertRaisesRegex(RuntimeError, "torch::init"): x = torch.classes._TorchScriptTesting._NoInit() def test_profiler_custom_op(self): inst = torch.classes._TorchScriptTesting._PickleTester([3, 4]) with torch.autograd.profiler.profile() as prof: torch.ops._TorchScriptTesting.take_an_instance(inst) found_event = False for e in prof.function_events: if e.name == "_TorchScriptTesting::take_an_instance": found_event = True self.assertTrue(found_event) def test_torchbind_getattr(self): foo = torch.classes._TorchScriptTesting._StackString(["test"]) self.assertEqual(None, getattr(foo, "bar", None)) def test_torchbind_attr_exception(self): foo = torch.classes._TorchScriptTesting._StackString(["test"]) with self.assertRaisesRegex(AttributeError, "does not have a field"): foo.bar def test_lambda_as_constructor(self): obj_no_swap = torch.classes._TorchScriptTesting._LambdaInit(4, 3, False) self.assertEqual(obj_no_swap.diff(), 1) obj_swap = torch.classes._TorchScriptTesting._LambdaInit(4, 3, True) self.assertEqual(obj_swap.diff(), -1) def test_staticmethod(self): def fn(inp: int) -> int: return torch.classes._TorchScriptTesting._StaticMethod.staticMethod(inp) self.checkScript(fn, (1,)) def test_hasattr(self): ss = torch.classes._TorchScriptTesting._StackString(["foo", "bar"]) self.assertFalse(hasattr(ss, "baz")) def test_default_args(self): def fn() -> int: obj = torch.classes._TorchScriptTesting._DefaultArgs() obj.increment(5) obj.decrement() obj.decrement(2) obj.divide() obj.scale_add(5) obj.scale_add(3, 2) obj.divide(3) return obj.increment() self.checkScript(fn, ()) def gn() -> int: obj = torch.classes._TorchScriptTesting._DefaultArgs(5) obj.increment(3) obj.increment() obj.decrement(2) obj.divide() obj.scale_add(3) obj.scale_add(3, 2) obj.divide(2) return obj.decrement() self.checkScript(gn, ()) if __name__ == "__main__": raise_on_run_directly("test/test_jit.py")
TestTorchbind
python
mlflow__mlflow
mlflow/data/http_dataset_source.py
{ "start": 605, "end": 4599 }
class ____(DatasetSource): """ Represents the source of a dataset stored at a web location and referred to by an HTTP or HTTPS URL. """ def __init__(self, url): self._url = url @property def url(self): """The HTTP/S URL referring to the dataset source location. Returns: The HTTP/S URL referring to the dataset source location. """ return self._url @staticmethod def _get_source_type() -> str: return "http" def _extract_filename(self, response) -> str: """ Extracts a filename from the Content-Disposition header or the URL's path. """ if content_disposition := response.headers.get("Content-Disposition"): for match in re.finditer(r"filename=(.+)", content_disposition): filename = match[1].strip("'\"") if _is_path(filename): raise MlflowException.invalid_parameter_value( f"Invalid filename in Content-Disposition header: {filename}. " "It must be a file name, not a path." ) return filename # Extract basename from URL if no valid filename in Content-Disposition return os.path.basename(urlparse(self.url).path) def load(self, dst_path=None) -> str: """Downloads the dataset source to the local filesystem. Args: dst_path: Path of the local filesystem destination directory to which to download the dataset source. If the directory does not exist, it is created. If unspecified, the dataset source is downloaded to a new uniquely-named directory on the local filesystem. Returns: The path to the downloaded dataset source on the local filesystem. """ resp = cloud_storage_http_request( method="GET", url=self.url, stream=True, ) augmented_raise_for_status(resp) basename = self._extract_filename(resp) if not basename: basename = "dataset_source" if dst_path is None: dst_path = create_tmp_dir() dst_path = os.path.join(dst_path, basename) with open(dst_path, "wb") as f: chunk_size = 1024 * 1024 # 1 MB for chunk in resp.iter_content(chunk_size=chunk_size): f.write(chunk) return dst_path @staticmethod def _can_resolve(raw_source: Any) -> bool: """ Args: raw_source: The raw source, e.g. a string like "http://mysite/mydata.tar.gz". Returns: True if this DatasetSource can resolve the raw source, False otherwise. """ if not isinstance(raw_source, str): return False try: parsed_source = urlparse(str(raw_source)) return parsed_source.scheme in ["http", "https"] except Exception: return False @classmethod def _resolve(cls, raw_source: Any) -> "HTTPDatasetSource": """ Args: raw_source: The raw source, e.g. a string like "http://mysite/mydata.tar.gz". """ return HTTPDatasetSource(raw_source) def to_dict(self) -> dict[Any, Any]: """ Returns: A JSON-compatible dictionary representation of the HTTPDatasetSource. """ return { "url": self.url, } @classmethod def from_dict(cls, source_dict: dict[Any, Any]) -> "HTTPDatasetSource": """ Args: source_dict: A dictionary representation of the HTTPDatasetSource. """ url = source_dict.get("url") if url is None: raise MlflowException( 'Failed to parse HTTPDatasetSource. Missing expected key: "url"', INVALID_PARAMETER_VALUE, ) return cls(url=url)
HTTPDatasetSource
python
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 4193, "end": 4938 }
class ____(BaseLinksSerializer, serializers.Serializer): build = serializers.URLField(source="get_full_url") project = serializers.SerializerMethodField() version = serializers.SerializerMethodField() def get_project(self, obj): path = reverse("projects_detail", kwargs={"project_slug": obj.project.slug}) return self._absolute_url(path) def get_version(self, obj): if obj.version: path = reverse( "project_version_detail", kwargs={ "project_slug": obj.project.slug, "version_slug": obj.version.slug, }, ) return self._absolute_url(path) return None
BuildURLsSerializer
python
modin-project__modin
modin/core/storage_formats/pandas/groupby.py
{ "start": 1109, "end": 9114 }
class ____: """Provide TreeReduce implementations for certain groupby aggregations.""" @classmethod def get_impl(cls, agg_name): """ Get TreeReduce implementations for the specified `agg_name`. Parameters ---------- agg_name : hashable Returns ------- (map_fn: Union[callable, str], reduce_fn: Union[callable, str], default2pandas_fn: callable) """ try: return cls._groupby_reduce_impls[agg_name] except KeyError: raise KeyError(f"Have no implementation for {agg_name}.") @classmethod def has_impl_for(cls, agg_func): """ Check whether the class has TreeReduce implementation for the specified `agg_func`. Parameters ---------- agg_func : hashable or dict Returns ------- bool """ if hashable(agg_func): return agg_func in cls._groupby_reduce_impls if not isinstance(agg_func, dict): return False # We have to keep this import away from the module level to avoid circular import from modin.pandas.utils import walk_aggregation_dict for _, func, _, _ in walk_aggregation_dict(agg_func): if func not in cls._groupby_reduce_impls: return False return True @classmethod def build_qc_method(cls, agg_name, finalizer_fn=None): """ Build a TreeReduce implemented query compiler method for the specified groupby aggregation. Parameters ---------- agg_name : hashable finalizer_fn : callable(pandas.DataFrame) -> pandas.DataFrame, default: None A callable to execute at the end a groupby kernel against groupby result. Returns ------- callable Function that takes query compiler and executes GroupBy aggregation with TreeReduce algorithm. """ map_fn, reduce_fn, d2p_fn = cls.get_impl(agg_name) map_reduce_method = GroupByReduce.register( map_fn, reduce_fn, default_to_pandas_func=d2p_fn, finalizer_fn=finalizer_fn ) def method(query_compiler, *args, **kwargs): if RangePartitioning.get(): try: if finalizer_fn is not None: raise NotImplementedError( "Range-partitioning groupby is not implemented yet when a finalizing function is specified." ) return query_compiler._groupby_shuffle( *args, agg_func=agg_name, **kwargs ) except NotImplementedError as e: ErrorMessage.warn( f"Can't use range-partitioning groupby implementation because of: {e}" + "\nFalling back to a TreeReduce implementation." ) return map_reduce_method(query_compiler, *args, **kwargs) return method @staticmethod def _build_skew_impl(): """ Build TreeReduce implementation for 'skew' groupby aggregation. Returns ------- (map_fn: callable, reduce_fn: callable, default2pandas_fn: callable) """ def skew_map(dfgb, *args, **kwargs): if dfgb._selection is not None: data_to_agg = dfgb._selected_obj else: cols_to_agg = dfgb.obj.columns.difference(dfgb.exclusions) data_to_agg = dfgb.obj[cols_to_agg] df_pow2 = data_to_agg**2 df_pow3 = data_to_agg**3 return pandas.concat( [ dfgb.count(*args, **kwargs), dfgb.sum(*args, **kwargs), df_pow2.groupby(dfgb.grouper).sum(*args, **kwargs), df_pow3.groupby(dfgb.grouper).sum(*args, **kwargs), ], copy=False, axis=1, keys=["count", "sum", "pow2_sum", "pow3_sum"], names=[GroupByReduce.ID_LEVEL_NAME], ) def skew_reduce(dfgb, *args, **kwargs): df = dfgb.sum(*args, **kwargs) if df.empty: return df.droplevel(GroupByReduce.ID_LEVEL_NAME, axis=1) count = df["count"] s = df["sum"] s2 = df["pow2_sum"] s3 = df["pow3_sum"] # mean = sum(x) / count m = s / count # m2 = sum( (x - m)^ 2) = sum(x^2 - 2*x*m + m^2) m2 = s2 - 2 * m * s + count * (m**2) # m3 = sum( (x - m)^ 3) = sum(x^3 - 3*x^2*m + 3*x*m^2 - m^3) m3 = s3 - 3 * m * s2 + 3 * s * (m**2) - count * (m**3) # The equation for the 'skew' was taken directly from pandas: # https://github.com/pandas-dev/pandas/blob/8dab54d6573f7186ff0c3b6364d5e4dd635ff3e7/pandas/core/nanops.py#L1226 with np.errstate(invalid="ignore", divide="ignore"): skew_res = (count * (count - 1) ** 0.5 / (count - 2)) * (m3 / m2**1.5) # Setting dummy values for invalid results in accordance with pandas skew_res[m2 == 0] = 0 skew_res[count < 3] = np.nan return skew_res GroupByReduce.register_implementation(skew_map, skew_reduce) return ( skew_map, skew_reduce, lambda grp, *args, **kwargs: grp.skew(*args, **kwargs), ) @staticmethod def _build_mean_impl(): """ Build TreeReduce implementation for 'mean' groupby aggregation. Returns ------- (map_fn: callable, reduce_fn: callable, default2pandas_fn: callable) """ def mean_map(dfgb, **kwargs): return pandas.concat( [dfgb.sum(**kwargs), dfgb.count()], axis=1, copy=False, keys=["sum", "count"], names=[GroupByReduce.ID_LEVEL_NAME], ) def mean_reduce(dfgb, **kwargs): """ Compute mean value in each group using sums/counts values within reduce phase. Parameters ---------- dfgb : pandas.DataFrameGroupBy GroupBy object for column-partition. **kwargs : dict Additional keyword parameters to be passed in ``pandas.DataFrameGroupBy.sum``. Returns ------- pandas.DataFrame A pandas Dataframe with mean values in each column of each group. """ sums_counts_df = dfgb.sum(**kwargs) if sums_counts_df.empty: return sums_counts_df.droplevel(GroupByReduce.ID_LEVEL_NAME, axis=1) sum_df = sums_counts_df["sum"] count_df = sums_counts_df["count"] return sum_df / count_df GroupByReduce.register_implementation(mean_map, mean_reduce) return ( mean_map, mean_reduce, lambda grp, *args, **kwargs: grp.mean(*args, **kwargs), ) GroupbyReduceImpl._groupby_reduce_impls = { "all": ("all", "all", lambda grp, *args, **kwargs: grp.all(*args, **kwargs)), "any": ("any", "any", lambda grp, *args, **kwargs: grp.any(*args, **kwargs)), "count": ("count", "sum", lambda grp, *args, **kwargs: grp.count(*args, **kwargs)), "max": ("max", "max", lambda grp, *args, **kwargs: grp.max(*args, **kwargs)), "mean": GroupbyReduceImpl._build_mean_impl(), "min": ("min", "min", lambda grp, *args, **kwargs: grp.min(*args, **kwargs)), "prod": ("prod", "prod", lambda grp, *args, **kwargs: grp.prod(*args, **kwargs)), "size": ("size", "sum", lambda grp, *args, **kwargs: grp.size(*args, **kwargs)), "skew": GroupbyReduceImpl._build_skew_impl(), "sum": ("sum", "sum", lambda grp, *args, **kwargs: grp.sum(*args, **kwargs)), }
GroupbyReduceImpl
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mysql/json.py
{ "start": 1250, "end": 2178 }
class ____: def _format_value(self, value: Any) -> str: raise NotImplementedError() def bind_processor(self, dialect: Dialect) -> _BindProcessorType[Any]: super_proc = self.string_bind_processor(dialect) # type: ignore[attr-defined] # noqa: E501 def process(value: Any) -> Any: value = self._format_value(value) if super_proc: value = super_proc(value) return value return process def literal_processor( self, dialect: Dialect ) -> _LiteralProcessorType[Any]: super_proc = self.string_literal_processor(dialect) # type: ignore[attr-defined] # noqa: E501 def process(value: Any) -> str: value = self._format_value(value) if super_proc: value = super_proc(value) return value # type: ignore[no-any-return] return process
_FormatTypeMixin
python
realpython__materials
python-raise-exception/divide2.py
{ "start": 0, "end": 171 }
class ____(Exception): pass def divide(a, b): try: return a / b except ZeroDivisionError as error: raise MathLibraryError(error)
MathLibraryError
python
PrefectHQ__prefect
src/prefect/client/schemas/actions.py
{ "start": 25699, "end": 26190 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to update a block document.""" block_schema_id: Optional[UUID] = Field( default=None, description="A block schema ID" ) data: dict[str, Any] = Field( default_factory=dict, description="The block document's data" ) merge_existing_data: bool = Field( default=True, description="Whether to merge the existing data with the new data or replace it", )
BlockDocumentUpdate
python
walkccc__LeetCode
solutions/954. Array of Doubled Pairs/954.py
{ "start": 0, "end": 259 }
class ____: def canReorderDoubled(self, arr: list[int]) -> bool: count = collections.Counter(arr) for key in sorted(count, key=abs): if count[key] > count[2 * key]: return False count[2 * key] -= count[key] return True
Solution
python
astropy__astropy
astropy/utils/masked/tests/test_function_helpers.py
{ "start": 36363, "end": 38295 }
class ____: @classmethod def setup_class(cls): cls.a = np.arange(36.0).reshape(6, 6) cls.mask_a = np.zeros_like(cls.a, bool) # On purpose fill diagonal, so we get all masked elements. cls.mask_a[np.tril_indices_from(cls.a)] = True cls.ma = Masked(cls.a, mask=cls.mask_a) def check(self, function, *args, **kwargs): # Check function by comparing to nan-equivalent, with masked # values set to NaN. o = function(self.ma, *args, **kwargs) nanfunc = getattr(np, "nan" + function.__name__) nanfilled = self.ma.filled(np.nan) expected = nanfunc(nanfilled, *args, **kwargs) assert_array_equal(o.filled(np.nan), expected) assert_array_equal(o.mask, np.isnan(expected)) # Also check that we can give an output MaskedArray. out = np.zeros_like(o) o2 = function(self.ma, *args, out=out, **kwargs) assert o2 is out assert_masked_equal(o2, o) # But that a regular array cannot be used since it has no mask. with pytest.raises(TypeError): function(self.ma, *args, out=np.zeros_like(expected), **kwargs) @pytest.mark.parametrize("keepdims", [False, True]) @pytest.mark.parametrize("axis", [None, 0, 1]) def test_median(self, axis, keepdims): self.check(np.median, axis=axis, keepdims=keepdims) @pytest.mark.parametrize("keepdims", [False, True]) @pytest.mark.parametrize("axis", [None, 0, 1]) def test_quantile(self, axis, keepdims): self.check(np.quantile, q=[0.25, 0.5], axis=axis, keepdims=keepdims) def test_quantile_out_of_range(self): with pytest.raises(ValueError, match="must be in the range"): np.quantile(self.ma, q=1.5) @pytest.mark.parametrize("axis", [None, 0, 1]) def test_percentile(self, axis): self.check(np.percentile, q=50, axis=axis)
TestPartitionLikeFunctions
python
doocs__leetcode
solution/1600-1699/1615.Maximal Network Rank/Solution.py
{ "start": 0, "end": 390 }
class ____: def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: g = defaultdict(set) for a, b in roads: g[a].add(b) g[b].add(a) ans = 0 for a in range(n): for b in range(a + 1, n): if (t := len(g[a]) + len(g[b]) - (a in g[b])) > ans: ans = t return ans
Solution
python
modin-project__modin
modin/config/envvars.py
{ "start": 41114, "end": 41283 }
class ____(EnvironmentVariable, type=int): """Number of threads per Dask worker.""" varname = "MODIN_DASK_THREADS_PER_WORKER" default = 1
DaskThreadsPerWorker
python
huggingface__transformers
tests/models/layoutlmv2/test_image_processing_layoutlmv2.py
{ "start": 1293, "end": 2708 }
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, apply_ocr=True, ): size = size if size is not None else {"height": 18, "width": 18} 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.apply_ocr = apply_ocr def prepare_image_processor_dict(self): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} 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_pytesseract
LayoutLMv2ImageProcessingTester
python
google__pytype
pytype/tests/test_operators1.py
{ "start": 6830, "end": 8062 }
class ____(test_base.BaseTest, test_utils.OperatorsTestMixin): """Tests for overloading operators.""" def test_add(self): self.check_binary("__add__", "+") def test_and(self): self.check_binary("__and__", "&") def test_or(self): self.check_binary("__or__", "|") def test_sub(self): self.check_binary("__sub__", "-") def test_floordiv(self): self.check_binary("__floordiv__", "//") def test_mod(self): self.check_binary("__mod__", "%") def test_mul(self): self.check_binary("__mul__", "*") def test_pow(self): self.check_binary("__pow__", "**") def test_lshift(self): self.check_binary("__lshift__", "<<") def test_rshift(self): self.check_binary("__rshift__", ">>") def test_invert(self): self.check_unary("__invert__", "~") def test_neg(self): self.check_unary("__neg__", "-") def test_pos(self): self.check_unary("__pos__", "+") def test_nonzero(self): # __nonzero__ is hard to test, because you can never call it directly - # "not x" will call __nonzero__ on x, but then convert the result to boolean # and invert it. Hence, we're only checking for bool here. self.check_unary("__nonzero__", "not", "bool")
OverloadTest
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py
{ "start": 1887, "end": 2798 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.max_text_len = config.max_text_len self.bias = nn.Parameter(torch.tensor(0.0)) def forward( self, vision_hidden_state: torch.FloatTensor, text_hidden_state: torch.FloatTensor, text_token_mask: torch.BoolTensor, ) -> torch.FloatTensor: res = vision_hidden_state @ text_hidden_state.transpose(-1, -2) res = res / math.sqrt(vision_hidden_state.shape[-1]) res = res + self.bias res.masked_fill_(~text_token_mask[:, None, :], float("-inf")) # padding to max_text_len new_res = torch.full((*res.shape[:-1], self.max_text_len), float("-inf"), device=res.device) new_res[..., : res.shape[-1]] = res return new_res @use_kernel_forward_from_hub("MultiScaleDeformableAttention")
MMGroundingDinoContrastiveEmbedding
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 145515, "end": 146224 }
class ____(sgqlc.types.Input): """Parameters to be used for the branch_name_pattern rule""" __schema__ = github_schema __field_names__ = ("name", "negate", "operator", "pattern") name = sgqlc.types.Field(String, graphql_name="name") """How this rule will appear to users.""" negate = sgqlc.types.Field(Boolean, graphql_name="negate") """If true, the rule will fail if the pattern matches.""" operator = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="operator") """The operator to use for matching.""" pattern = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="pattern") """The pattern to match with."""
BranchNamePatternParametersInput
python
ipython__ipython
IPython/lib/display.py
{ "start": 10185, "end": 11643 }
class ____(IFrame): """Class for embedding a YouTube Video in an IPython session, based on its video id. e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would do:: vid = YouTubeVideo("foo") display(vid) To start from 30 seconds:: vid = YouTubeVideo("abc", start=30) display(vid) To calculate seconds from time as hours, minutes, seconds use :class:`datetime.timedelta`:: start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) Other parameters can be provided as documented at https://developers.google.com/youtube/player_parameters#Parameters When converting the notebook using nbconvert, a jpeg representation of the video will be inserted in the document. """ def __init__(self, id, width=400, height=300, allow_autoplay=False, **kwargs): self.id=id src = "https://www.youtube.com/embed/{0}".format(id) if allow_autoplay: extras = list(kwargs.get("extras", [])) + ['allow="autoplay"'] kwargs.update(autoplay=1, extras=extras) super(YouTubeVideo, self).__init__(src, width, height, **kwargs) def _repr_jpeg_(self): # Deferred import from urllib.request import urlopen try: return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read() except IOError: return None
YouTubeVideo
python
google__pytype
pytype_extensions/instrumentation_for_testing_test.py
{ "start": 1987, "end": 2334 }
class ____(WithCtor, i4t.ProductionType[WithCtor]): def __init__(self): # pylint: disable=super-init-not-called # Assume state is difficult to generate via the normal __init__, which is # therefore intentionally not called from here. self.state = 5 def ProductionCodePassWithCtor(obj: WithCtor): return obj.Mul100(7)
FakeWithCtor
python
fluentpython__example-code-2e
24-class-metaprog/checked/initsub/checkedlib.py
{ "start": 2919, "end": 4748 }
class ____: @classmethod def _fields(cls) -> dict[str, type]: # <1> return get_type_hints(cls) def __init_subclass__(subclass) -> None: # <2> super().__init_subclass__() # <3> for name, constructor in subclass._fields().items(): # <4> setattr(subclass, name, Field(name, constructor)) # <5> def __init__(self, **kwargs: Any) -> None: for name in self._fields(): # <6> value = kwargs.pop(name, ...) # <7> setattr(self, name, value) # <8> if kwargs: # <9> self.__flag_unknown_attrs(*kwargs) # <10> # end::CHECKED_TOP[] # tag::CHECKED_BOTTOM[] def __setattr__(self, name: str, value: Any) -> None: # <1> if name in self._fields(): # <2> cls = self.__class__ descriptor = getattr(cls, name) descriptor.__set__(self, value) # <3> else: # <4> self.__flag_unknown_attrs(name) def __flag_unknown_attrs(self, *names: str) -> NoReturn: # <5> plural = 's' if len(names) > 1 else '' extra = ', '.join(f'{name!r}' for name in names) cls_name = repr(self.__class__.__name__) raise AttributeError(f'{cls_name} object has no attribute{plural} {extra}') def _asdict(self) -> dict[str, Any]: # <6> return { name: getattr(self, name) for name, attr in self.__class__.__dict__.items() if isinstance(attr, Field) } def __repr__(self) -> str: # <7> kwargs = ', '.join( f'{key}={value!r}' for key, value in self._asdict().items() ) return f'{self.__class__.__name__}({kwargs})' # end::CHECKED_BOTTOM[]
Checked
python
geekcomputers__Python
BlackJack_game/blackjack_rr.py
{ "start": 16, "end": 695 }
class ____: BLACK = "\033[30m" RED = "\033[91m" GREEN = "\033[32m" END = "\033[0m" suits = ( Colour.RED + "Hearts" + Colour.END, Colour.RED + "Diamonds" + Colour.END, Colour.BLACK + "Spades" + Colour.END, Colour.BLACK + "Clubs" + Colour.END, ) ranks = ( "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace", ) values = { "Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8, "Nine": 9, "Ten": 10, "Jack": 10, "Queen": 10, "King": 10, "Ace": 11, } playing = True
Colour
python
getsentry__sentry
tests/sentry/db/models/test_utils.py
{ "start": 2816, "end": 4147 }
class ____(TestCase): def test_no_conflict(self) -> None: org = Organization(name="matt") slugify_instance(org, org.name) assert org.slug == "matt" def test_conflict(self) -> None: base_slug = self.organization.slug org = Organization(name="foo") slugify_instance(org, base_slug) assert org.slug.startswith(base_slug + "-") def test_reserved(self) -> None: base_slug = self.organization.slug org = Organization(name="foo") slugify_instance(org, base_slug, reserved=(base_slug,)) assert not org.slug.startswith(base_slug + "-") def test_max_length(self) -> None: org = Organization(name="matt") slugify_instance(org, org.name, max_length=2) assert org.slug == "ma" def test_appends_to_entirely_numeric(self) -> None: org = Organization(name="1234") slugify_instance(org, org.name) assert org.slug.startswith("1234" + "-") def test_replaces_space_with_hyphen(self) -> None: org = Organization(name="f o o") slugify_instance(org, org.name) assert org.slug == "f-o-o" def test_removes_underscores(self) -> None: org = Organization(name="_foo_") slugify_instance(org, org.name) assert org.slug == "foo"
SlugifyInstanceTest
python
joke2k__faker
faker/providers/credit_card/fa_IR/__init__.py
{ "start": 122, "end": 5042 }
class ____(CreditCardProvider): """Implement credit card provider for ``fa_IR`` locale. For all methods that take ``card_type`` as an argument, a random card type will be used if the supplied value is ``None``. The list of valid card types includes ``'ansar'``, ``'bim'``, ``'day'``, ``'eghtesad_novin'``, ``'ghavamin'``, ``'hekmat'``, ``'iran_zamin'``, ``'kar_afarin'``, ``'keshavarzi'``, ``'kosar'``, ``'maskan'``, ``'mehre_ghtesad'``, ``'meli'``, ``'mellal'``, ``'mellat'``, ``'parsian'``, ``'pasargad'``, ``'post_bank'``, ``'refah'``, ``'saderat'``, ``'saman'``, ``'sarmayeh'``, ``'sepah'``, ``'shahr'``, ``'sina'``, ``'tat'``, ``'tejarat'``, ``'tose'``, and ``'tourism_bank'``. Sources: - https://way2pay.ir/21653 """ prefix_ansar = ["627381"] prefix_iran_zamin = ["505785"] prefix_hekmat = ["636949"] prefix_keshavarzi = ["603770"] prefix_shahr = ["502806"] prefix_mehr_eghtesad = ["606373"] prefix_sarmayeh = ["639607"] prefix_post_bank = ["627760"] prefix_tose = ["628157"] prefix_eghtesad_novin = ["627412"] prefix_meli = ["603799"] prefix_pasargad = ["502229"] prefix_tourism_bank = ["505416"] prefix_ghavamin = ["639599"] prefix_day = ["502938"] prefix_mellat = ["610433"] prefix_tejarat = ["585983"] prefix_moasse_mellal = ["606256"] prefix_saman_bank = ["621986"] prefix_kosar = ["505801"] prefix_refah = ["589463"] prefix_saderat = ["603761"] prefix_tat = ["621986"] prefix_sina = ["639346"] prefix_kar_afarin = ["627488"] prefix_sepah = ["589210"] prefix_maskan = ["628023"] prefix_parsian = ["622106"] prefix_bim = ["627961"] credit_card_types = OrderedDict( ( ("ansar", CreditCard("انصار", prefix_ansar, 16, security_code="CVV2")), ( "iran_zamin", CreditCard("ایران زمین", prefix_iran_zamin, 16, security_code="CVV2"), ), ("hekmat", CreditCard("حکمت", prefix_hekmat, 16, security_code="CVV2")), ( "keshavarzi", CreditCard("کشاورزی", prefix_keshavarzi, 16, security_code="CVV2"), ), ("shahr", CreditCard("شهر", prefix_shahr, 16, security_code="CVV2")), ( "mehre_ghtesad", CreditCard("مهراقتصاد", prefix_mehr_eghtesad, 16, security_code="CVV2"), ), ( "sarmayeh", CreditCard("سرمایه", prefix_sarmayeh, 16, security_code="CVV2"), ), ( "post_bank", CreditCard("پست بانک", prefix_post_bank, 16, security_code="CVV2"), ), ("tose", CreditCard("توسعه", prefix_tose, 16, security_code="CVV2")), ( "eghtesad_novin", CreditCard("اقتصاد نوین", prefix_eghtesad_novin, 16, security_code="CVV2"), ), ("meli", CreditCard("ملی", prefix_meli, 16, security_code="CVV2")), ( "pasargad", CreditCard("پاسارگاد", prefix_pasargad, 16, security_code="CVV2"), ), ( "tourism_bank", CreditCard("گردشگری", prefix_tourism_bank, 16, security_code="CVV2"), ), ( "ghavamin", CreditCard("قوامین", prefix_ghavamin, 16, security_code="CVV2"), ), ("day", CreditCard("دی", prefix_day, 16, security_code="CVV2")), ("mellat", CreditCard("ملت", prefix_mellat, 16, security_code="CVV2")), ("tejarat", CreditCard("تجارت", prefix_tejarat, 16, security_code="CVV2")), ( "mellal", CreditCard("ملل", prefix_moasse_mellal, 16, security_code="CVV2"), ), ("saman", CreditCard("سامان", prefix_saman_bank, 16, security_code="CVV2")), ("kosar", CreditCard("کوثر", prefix_kosar, 16, security_code="CVV2")), ("refah", CreditCard("رفاه", prefix_refah, 16, security_code="CVV2")), ("saderat", CreditCard("صادرات", prefix_saderat, 16, security_code="CVV2")), ("tat", CreditCard("تات", prefix_tat, 16, security_code="CVV2")), ("sina", CreditCard("سینا", prefix_sina, 16, security_code="CVV2")), ( "kar_afarin", CreditCard("کار آفرین", prefix_kar_afarin, 16, security_code="CVV2"), ), ("sepah", CreditCard("سپه", prefix_sepah, 16, security_code="CVV2")), ("maskan", CreditCard("مسکن", prefix_maskan, 16, security_code="CVV2")), ( "parsian", CreditCard("پارسیان", prefix_parsian, 16, security_code="CVV2"), ), ("bim", CreditCard("صنعت و معدن", prefix_bim, 16, security_code="CVV2")), ) )
Provider
python
pymupdf__PyMuPDF
src/__init__.py
{ "start": 631501, "end": 646198 }
class ____: """ IRect() - all zeros IRect(x0, y0, x1, y1) - 4 coordinates IRect(top-left, x1, y1) - point and 2 coordinates IRect(x0, y0, bottom-right) - 2 coordinates and point IRect(top-left, bottom-right) - 2 points IRect(sequ) - new from sequence or rect-like """ def __add__(self, p): return Rect.__add__(self, p).round() def __and__(self, x): return Rect.__and__(self, x).round() def __contains__(self, x): return Rect.__contains__(self, x) def __eq__(self, r): if not hasattr(r, "__len__"): return False return len(r) == 4 and self.x0 == r[0] and self.y0 == r[1] and self.x1 == r[2] and self.y1 == r[3] def __getitem__(self, i): return (self.x0, self.y0, self.x1, self.y1)[i] def __hash__(self): return hash(tuple(self)) def __init__(self, *args, p0=None, p1=None, x0=None, y0=None, x1=None, y1=None): self.x0, self.y0, self.x1, self.y1 = util_make_irect( *args, p0=p0, p1=p1, x0=x0, y0=y0, x1=x1, y1=y1) def __len__(self): return 4 def __mul__(self, m): return Rect.__mul__(self, m).round() def __neg__(self): return IRect(-self.x0, -self.y0, -self.x1, -self.y1) def __or__(self, x): return Rect.__or__(self, x).round() def __pos__(self): return IRect(self) def __repr__(self): return "IRect" + str(tuple(self)) def __setitem__(self, i, v): v = int(v) if i == 0: self.x0 = v elif i == 1: self.y0 = v elif i == 2: self.x1 = v elif i == 3: self.y1 = v else: raise IndexError("index out of range") return None def __sub__(self, p): return Rect.__sub__(self, p).round() def __truediv__(self, m): return Rect.__truediv__(self, m).round() @property def bottom_left(self): """Bottom-left corner.""" return Point(self.x0, self.y1) @property def bottom_right(self): """Bottom-right corner.""" return Point(self.x1, self.y1) @property def height(self): return max(0, self.y1 - self.y0) def contains(self, x): """Check if x is in the rectangle.""" return self.__contains__(x) def get_area(self, *args) -> float: """Calculate area of rectangle.\nparameter is one of 'px' (default), 'in', 'cm', or 'mm'.""" return _rect_area(self.width, self.height, args) def include_point(self, p): """Extend rectangle to include point p.""" rect = self.rect.include_point(p) return rect.irect def include_rect(self, r): """Extend rectangle to include rectangle r.""" rect = self.rect.include_rect(r) return rect.irect def intersect(self, r): """Restrict rectangle to intersection with rectangle r.""" return Rect.intersect(self, r).round() def intersects(self, x): return Rect.intersects(self, x) @property def is_empty(self): """True if rectangle area is empty.""" return self.x0 >= self.x1 or self.y0 >= self.y1 @property def is_infinite(self): """True if rectangle is infinite.""" return self.x0 == self.y0 == FZ_MIN_INF_RECT and self.x1 == self.y1 == FZ_MAX_INF_RECT @property def is_valid(self): """True if rectangle is valid.""" return self.x0 <= self.x1 and self.y0 <= self.y1 def morph(self, p, m): """Morph with matrix-like m and point-like p. Returns a new quad.""" if self.is_infinite: return INFINITE_QUAD() return self.quad.morph(p, m) def norm(self): return math.sqrt(sum([c*c for c in self])) def normalize(self): """Replace rectangle with its valid version.""" if self.x1 < self.x0: self.x0, self.x1 = self.x1, self.x0 if self.y1 < self.y0: self.y0, self.y1 = self.y1, self.y0 return self @property def quad(self): """Return Quad version of rectangle.""" return Quad(self.tl, self.tr, self.bl, self.br) @property def rect(self): return Rect(self) @property def top_left(self): """Top-left corner.""" return Point(self.x0, self.y0) @property def top_right(self): """Top-right corner.""" return Point(self.x1, self.y0) def torect(self, r): """Return matrix that converts to target rect.""" r = Rect(r) if self.is_infinite or self.is_empty or r.is_infinite or r.is_empty: raise ValueError("rectangles must be finite and not empty") return ( Matrix(1, 0, 0, 1, -self.x0, -self.y0) * Matrix(r.width / self.width, r.height / self.height) * Matrix(1, 0, 0, 1, r.x0, r.y0) ) def transform(self, m): return Rect.transform(self, m).round() @property def width(self): return max(0, self.x1 - self.x0) br = bottom_right bl = bottom_left tl = top_left tr = top_right # Data # if 1: _self = sys.modules[__name__] if 1: for _name, _value in mupdf.__dict__.items(): if _name.startswith(('PDF_', 'UCDN_SCRIPT_')): if _name.startswith('PDF_ENUM_NAME_'): # Not a simple enum. pass else: #assert not inspect.isroutine(value) #log(f'importing {_name=} {_value=}.') setattr(_self, _name, _value) #log(f'{getattr( self, name, None)=}') else: # This is slow due to importing inspect, e.g. 0.019 instead of 0.004. for _name, _value in inspect.getmembers(mupdf): if _name.startswith(('PDF_', 'UCDN_SCRIPT_')): if _name.startswith('PDF_ENUM_NAME_'): # Not a simple enum. pass else: #assert not inspect.isroutine(value) #log(f'importing {name}') setattr(_self, _name, _value) #log(f'{getattr( self, name, None)=}') # This is a macro so not preserved in mupdf C++/Python bindings. # PDF_SIGNATURE_DEFAULT_APPEARANCE = (0 | mupdf.PDF_SIGNATURE_SHOW_LABELS | mupdf.PDF_SIGNATURE_SHOW_DN | mupdf.PDF_SIGNATURE_SHOW_DATE | mupdf.PDF_SIGNATURE_SHOW_TEXT_NAME | mupdf.PDF_SIGNATURE_SHOW_GRAPHIC_NAME | mupdf.PDF_SIGNATURE_SHOW_LOGO ) #UCDN_SCRIPT_ADLAM = mupdf.UCDN_SCRIPT_ADLAM #setattr(self, 'UCDN_SCRIPT_ADLAM', mupdf.UCDN_SCRIPT_ADLAM) assert mupdf.UCDN_EAST_ASIAN_H == 1 # Flake8 incorrectly fails next two lines because we've dynamically added # items to self. assert PDF_TX_FIELD_IS_MULTILINE == mupdf.PDF_TX_FIELD_IS_MULTILINE # noqa: F821 assert UCDN_SCRIPT_ADLAM == mupdf.UCDN_SCRIPT_ADLAM # noqa: F821 del _self, _name, _value AnyType = typing.Any Base14_fontnames = ( "Courier", "Courier-Oblique", "Courier-Bold", "Courier-BoldOblique", "Helvetica", "Helvetica-Oblique", "Helvetica-Bold", "Helvetica-BoldOblique", "Times-Roman", "Times-Italic", "Times-Bold", "Times-BoldItalic", "Symbol", "ZapfDingbats", ) Base14_fontdict = {} for f in Base14_fontnames: Base14_fontdict[f.lower()] = f Base14_fontdict["helv"] = "Helvetica" Base14_fontdict["heit"] = "Helvetica-Oblique" Base14_fontdict["hebo"] = "Helvetica-Bold" Base14_fontdict["hebi"] = "Helvetica-BoldOblique" Base14_fontdict["cour"] = "Courier" Base14_fontdict["coit"] = "Courier-Oblique" Base14_fontdict["cobo"] = "Courier-Bold" Base14_fontdict["cobi"] = "Courier-BoldOblique" Base14_fontdict["tiro"] = "Times-Roman" Base14_fontdict["tibo"] = "Times-Bold" Base14_fontdict["tiit"] = "Times-Italic" Base14_fontdict["tibi"] = "Times-BoldItalic" Base14_fontdict["symb"] = "Symbol" Base14_fontdict["zadb"] = "ZapfDingbats" EPSILON = 1e-5 FLT_EPSILON = 1e-5 # largest 32bit integers surviving C float conversion roundtrips # used by MuPDF to define infinite rectangles FZ_MIN_INF_RECT = -0x80000000 FZ_MAX_INF_RECT = 0x7fffff80 JM_annot_id_stem = "fitz" JM_mupdf_warnings_store = [] JM_mupdf_show_errors = 1 JM_mupdf_show_warnings = 0 # ------------------------------------------------------------------------------ # Image recompression constants # ------------------------------------------------------------------------------ FZ_RECOMPRESS_NEVER = mupdf.FZ_RECOMPRESS_NEVER FZ_RECOMPRESS_SAME = mupdf.FZ_RECOMPRESS_SAME FZ_RECOMPRESS_LOSSLESS = mupdf.FZ_RECOMPRESS_LOSSLESS FZ_RECOMPRESS_JPEG = mupdf.FZ_RECOMPRESS_JPEG FZ_RECOMPRESS_J2K = mupdf.FZ_RECOMPRESS_J2K FZ_RECOMPRESS_FAX = mupdf.FZ_RECOMPRESS_FAX FZ_SUBSAMPLE_AVERAGE = mupdf.FZ_SUBSAMPLE_AVERAGE FZ_SUBSAMPLE_BICUBIC = mupdf.FZ_SUBSAMPLE_BICUBIC # ------------------------------------------------------------------------------ # Various PDF Optional Content Flags # ------------------------------------------------------------------------------ PDF_OC_ON = 0 PDF_OC_TOGGLE = 1 PDF_OC_OFF = 2 # ------------------------------------------------------------------------------ # link kinds and link flags # ------------------------------------------------------------------------------ LINK_NONE = 0 LINK_GOTO = 1 LINK_URI = 2 LINK_LAUNCH = 3 LINK_NAMED = 4 LINK_GOTOR = 5 LINK_FLAG_L_VALID = 1 LINK_FLAG_T_VALID = 2 LINK_FLAG_R_VALID = 4 LINK_FLAG_B_VALID = 8 LINK_FLAG_FIT_H = 16 LINK_FLAG_FIT_V = 32 LINK_FLAG_R_IS_ZOOM = 64 SigFlag_SignaturesExist = 1 SigFlag_AppendOnly = 2 STAMP_Approved = 0 STAMP_AsIs = 1 STAMP_Confidential = 2 STAMP_Departmental = 3 STAMP_Experimental = 4 STAMP_Expired = 5 STAMP_Final = 6 STAMP_ForComment = 7 STAMP_ForPublicRelease = 8 STAMP_NotApproved = 9 STAMP_NotForPublicRelease = 10 STAMP_Sold = 11 STAMP_TopSecret = 12 STAMP_Draft = 13 TEXT_ALIGN_LEFT = 0 TEXT_ALIGN_CENTER = 1 TEXT_ALIGN_RIGHT = 2 TEXT_ALIGN_JUSTIFY = 3 TEXT_FONT_SUPERSCRIPT = 1 TEXT_FONT_ITALIC = 2 TEXT_FONT_SERIFED = 4 TEXT_FONT_MONOSPACED = 8 TEXT_FONT_BOLD = 16 TEXT_OUTPUT_TEXT = 0 TEXT_OUTPUT_HTML = 1 TEXT_OUTPUT_JSON = 2 TEXT_OUTPUT_XML = 3 TEXT_OUTPUT_XHTML = 4 TEXT_PRESERVE_LIGATURES = mupdf.FZ_STEXT_PRESERVE_LIGATURES TEXT_PRESERVE_WHITESPACE = mupdf.FZ_STEXT_PRESERVE_WHITESPACE TEXT_PRESERVE_IMAGES = mupdf.FZ_STEXT_PRESERVE_IMAGES TEXT_INHIBIT_SPACES = mupdf.FZ_STEXT_INHIBIT_SPACES TEXT_DEHYPHENATE = mupdf.FZ_STEXT_DEHYPHENATE TEXT_PRESERVE_SPANS = mupdf.FZ_STEXT_PRESERVE_SPANS TEXT_MEDIABOX_CLIP = mupdf.FZ_STEXT_MEDIABOX_CLIP TEXT_USE_CID_FOR_UNKNOWN_UNICODE = mupdf.FZ_STEXT_USE_CID_FOR_UNKNOWN_UNICODE TEXT_COLLECT_STRUCTURE = mupdf.FZ_STEXT_COLLECT_STRUCTURE TEXT_ACCURATE_BBOXES = mupdf.FZ_STEXT_ACCURATE_BBOXES TEXT_COLLECT_VECTORS = mupdf.FZ_STEXT_COLLECT_VECTORS TEXT_IGNORE_ACTUALTEXT = mupdf.FZ_STEXT_IGNORE_ACTUALTEXT TEXT_SEGMENT = mupdf.FZ_STEXT_SEGMENT if mupdf_version_tuple >= (1, 26): TEXT_PARAGRAPH_BREAK = mupdf.FZ_STEXT_PARAGRAPH_BREAK TEXT_TABLE_HUNT = mupdf.FZ_STEXT_TABLE_HUNT TEXT_COLLECT_STYLES = mupdf.FZ_STEXT_COLLECT_STYLES TEXT_USE_GID_FOR_UNKNOWN_UNICODE = mupdf.FZ_STEXT_USE_GID_FOR_UNKNOWN_UNICODE TEXT_CLIP_RECT = mupdf.FZ_STEXT_CLIP_RECT TEXT_ACCURATE_ASCENDERS = mupdf.FZ_STEXT_ACCURATE_ASCENDERS TEXT_ACCURATE_SIDE_BEARINGS = mupdf.FZ_STEXT_ACCURATE_SIDE_BEARINGS # 2025-05-07: Non-standard names preserved for backwards compatibility. TEXT_STEXT_SEGMENT = TEXT_SEGMENT TEXT_CID_FOR_UNKNOWN_UNICODE = TEXT_USE_CID_FOR_UNKNOWN_UNICODE TEXTFLAGS_WORDS = (0 | TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE | TEXT_MEDIABOX_CLIP | TEXT_USE_CID_FOR_UNKNOWN_UNICODE ) TEXTFLAGS_BLOCKS = (0 | TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE | TEXT_MEDIABOX_CLIP | TEXT_USE_CID_FOR_UNKNOWN_UNICODE ) TEXTFLAGS_DICT = (0 | TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE | TEXT_MEDIABOX_CLIP | TEXT_PRESERVE_IMAGES | TEXT_USE_CID_FOR_UNKNOWN_UNICODE ) TEXTFLAGS_RAWDICT = TEXTFLAGS_DICT TEXTFLAGS_SEARCH = (0 | TEXT_PRESERVE_WHITESPACE | TEXT_MEDIABOX_CLIP | TEXT_DEHYPHENATE | TEXT_USE_CID_FOR_UNKNOWN_UNICODE ) TEXTFLAGS_HTML = (0 | TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE | TEXT_MEDIABOX_CLIP | TEXT_PRESERVE_IMAGES | TEXT_USE_CID_FOR_UNKNOWN_UNICODE ) TEXTFLAGS_XHTML = (0 | TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE | TEXT_MEDIABOX_CLIP | TEXT_PRESERVE_IMAGES | TEXT_USE_CID_FOR_UNKNOWN_UNICODE ) TEXTFLAGS_XML = (0 | TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE | TEXT_MEDIABOX_CLIP | TEXT_USE_CID_FOR_UNKNOWN_UNICODE ) TEXTFLAGS_TEXT = (0 | TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE | TEXT_MEDIABOX_CLIP | TEXT_USE_CID_FOR_UNKNOWN_UNICODE ) # Simple text encoding options TEXT_ENCODING_LATIN = 0 TEXT_ENCODING_GREEK = 1 TEXT_ENCODING_CYRILLIC = 2 TOOLS_JM_UNIQUE_ID = 0 # colorspace identifiers CS_RGB = 1 CS_GRAY = 2 CS_CMYK = 3 # PDF Blend Modes PDF_BM_Color = "Color" PDF_BM_ColorBurn = "ColorBurn" PDF_BM_ColorDodge = "ColorDodge" PDF_BM_Darken = "Darken" PDF_BM_Difference = "Difference" PDF_BM_Exclusion = "Exclusion" PDF_BM_HardLight = "HardLight" PDF_BM_Hue = "Hue" PDF_BM_Lighten = "Lighten" PDF_BM_Luminosity = "Luminosity" PDF_BM_Multiply = "Multiply" PDF_BM_Normal = "Normal" PDF_BM_Overlay = "Overlay" PDF_BM_Saturation = "Saturation" PDF_BM_Screen = "Screen" PDF_BM_SoftLight = "Softlight" annot_skel = { "goto1": lambda a, b, c, d, e: f"<</A<</S/GoTo/D[{a} 0 R/XYZ {_format_g((b, c, d))}]>>/Rect[{e}]/BS<</W 0>>/Subtype/Link>>", "goto2": lambda a, b: f"<</A<</S/GoTo/D{a}>>/Rect[{b}]/BS<</W 0>>/Subtype/Link>>", "gotor1": lambda a, b, c, d, e, f, g: f"<</A<</S/GoToR/D[{a} /XYZ {_format_g((b, c, d))}]/F<</F({e})/UF({f})/Type/Filespec>>>>/Rect[{g}]/BS<</W 0>>/Subtype/Link>>", "gotor2": lambda a, b, c: f"<</A<</S/GoToR/D{a}/F({b})>>/Rect[{c}]/BS<</W 0>>/Subtype/Link>>", "launch": lambda a, b, c: f"<</A<</S/Launch/F<</F({a})/UF({b})/Type/Filespec>>>>/Rect[{c}]/BS<</W 0>>/Subtype/Link>>", "uri": lambda a, b: f"<</A<</S/URI/URI({a})>>/Rect[{b}]/BS<</W 0>>/Subtype/Link>>", "named": lambda a, b: f"<</A<</S/GoTo/D({a})/Type/Action>>/Rect[{b}]/BS<</W 0>>/Subtype/Link>>", }
IRect
python
keon__algorithms
algorithms/dp/knapsack.py
{ "start": 461, "end": 849 }
class ____: def __init__(self, value, weight): self.value = value self.weight = weight def get_maximum_value(items, capacity): dp = [0] * (capacity + 1) for item in items: for cur_weight in reversed(range(item.weight, capacity+1)): dp[cur_weight] = max(dp[cur_weight], item.value + dp[cur_weight - item.weight]) return dp[capacity]
Item
python
numba__numba
numba/cuda/cudadecl.py
{ "start": 15615, "end": 16042 }
class ____(AbstractTemplate): key = cuda.atomic.cas def generic(self, args, kws): assert not kws ary, idx, old, val = args dty = ary.dtype if dty not in integer_numba_types: return if ary.ndim == 1: return signature(dty, ary, types.intp, dty, dty) elif ary.ndim > 1: return signature(dty, ary, idx, dty, dty) @register
Cuda_atomic_cas
python
numba__llvmlite
llvmlite/tests/test_binding.py
{ "start": 19110, "end": 20139 }
class ____(TestCase): def setUp(self): llvm.initialize_native_target() llvm.initialize_native_asmprinter() gc.collect() self.old_garbage = gc.garbage[:] gc.garbage[:] = [] def tearDown(self): # Test that no uncollectable objects were created # (llvmlite objects have a __del__ so a reference cycle could # create some). gc.collect() self.assertEqual(gc.garbage, []) # This will probably put any existing garbage in gc.garbage again del self.old_garbage def module(self, asm=asm_sum, context=None): asm = asm.format(triple=llvm.get_default_triple()) mod = llvm.parse_assembly(asm, context) return mod def glob(self, name='glob', mod=None): if mod is None: mod = self.module() return mod.get_global_variable(name) def target_machine(self, *, jit): target = llvm.Target.from_default_triple() return target.create_target_machine(jit=jit)
BaseTest
python
walkccc__LeetCode
solutions/2449. Minimum Number of Operations to Make Arrays Similar/2449.py
{ "start": 0, "end": 228 }
class ____: def makeSimilar(self, nums: list[int], target: list[int]) -> int: nums.sort(key=lambda x: (x % 2, x)) target.sort(key=lambda x: (x % 2, x)) return sum(abs(a - b) for a, b in zip(nums, target)) // 4
Solution
python
sanic-org__sanic
sanic/mixins/listeners.py
{ "start": 863, "end": 16473 }
class ____(metaclass=SanicMeta): def __init__(self, *args, **kwargs) -> None: self._future_listeners: list[FutureListener] = [] def _apply_listener(self, listener: FutureListener): raise NotImplementedError # noqa @overload def listener( self, listener_or_event: ListenerType[Sanic], event_or_none: str, apply: bool = ..., *, priority: int = 0, ) -> ListenerType[Sanic]: ... @overload def listener( self, listener_or_event: str, event_or_none: None = ..., apply: bool = ..., *, priority: int = 0, ) -> Callable[[ListenerType[Sanic]], ListenerType[Sanic]]: ... def listener( self, listener_or_event: Union[ListenerType[Sanic], str], event_or_none: Optional[str] = None, apply: bool = True, *, priority: int = 0, ) -> Union[ ListenerType[Sanic], Callable[[ListenerType[Sanic]], ListenerType[Sanic]], ]: """Create a listener for a specific event in the application's lifecycle. See [Listeners](/en/guide/basics/listeners) for more details. .. note:: Overloaded signatures allow for different ways of calling this method, depending on the types of the arguments. Usually, it is prederred to use one of the convenience methods such as `before_server_start` or `after_server_stop` instead of calling this method directly. ```python @app.before_server_start async def prefered_method(_): ... @app.listener("before_server_start") async def not_prefered_method(_): ... Args: listener_or_event (Union[ListenerType[Sanic], str]): A listener function or an event name. event_or_none (Optional[str]): The event name to listen for if `listener_or_event` is a function. Defaults to `None`. apply (bool): Whether to apply the listener immediately. Defaults to `True`. priority (int): The priority of the listener. Defaults to `0`. Returns: Union[ListenerType[Sanic], Callable[[ListenerType[Sanic]], ListenerType[Sanic]]]: The listener or a callable that takes a listener. Example: The following code snippet shows how you can use this method as a decorator: ```python @bp.listener("before_server_start") async def before_server_start(app, loop): ... ``` """ # noqa: E501 def register_listener( listener: ListenerType[Sanic], event: str, priority: int = 0 ) -> ListenerType[Sanic]: """A helper function to register a listener for an event. Typically will not be called directly. Args: listener (ListenerType[Sanic]): The listener function to register. event (str): The event name to listen for. Returns: ListenerType[Sanic]: The listener function that was registered. """ nonlocal apply future_listener = FutureListener(listener, event, priority) self._future_listeners.append(future_listener) if apply: self._apply_listener(future_listener) return listener if callable(listener_or_event): if event_or_none is None: raise BadRequest( "Invalid event registration: Missing event name." ) return register_listener( listener_or_event, event_or_none, priority ) else: return partial( register_listener, event=listener_or_event, priority=priority ) def _setup_listener( self, listener: Optional[ListenerType[Sanic]], event: str, priority: int, ) -> ListenerType[Sanic]: if listener is not None: return self.listener(listener, event, priority=priority) return cast( ListenerType[Sanic], partial(self.listener, event_or_none=event, priority=priority), ) def main_process_start( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the main_process_start event. This event is fired only on the main process and **NOT** on any worker processes. You should typically use this event to initialize resources that are shared across workers, or to initialize resources that are not safe to be initialized in a worker process. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.main_process_start async def on_main_process_start(app: Sanic): print("Main process started") ``` """ # noqa: E501 return self._setup_listener(listener, "main_process_start", priority) def main_process_ready( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the main_process_ready event. This event is fired only on the main process and **NOT** on any worker processes. It is fired after the main process has started and the Worker Manager has been initialized (ie, you will have access to `app.manager` instance). The typical use case for this event is to add a managed process to the Worker Manager. See [Running custom processes](/en/guide/deployment/manager.html#running-custom-processes) and [Listeners](/en/guide/basics/listeners.html) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.main_process_ready async def on_main_process_ready(app: Sanic): print("Main process ready") ``` """ # noqa: E501 return self._setup_listener(listener, "main_process_ready", priority) def main_process_stop( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the main_process_stop event. This event is fired only on the main process and **NOT** on any worker processes. You should typically use this event to clean up resources that were initialized in the main_process_start event. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.main_process_stop async def on_main_process_stop(app: Sanic): print("Main process stopped") ``` """ # noqa: E501 return self._setup_listener(listener, "main_process_stop", priority) def reload_process_start( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the reload_process_start event. This event is fired only on the reload process and **NOT** on any worker processes. This is similar to the main_process_start event, except that it is fired only when the reload process is started. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.reload_process_start async def on_reload_process_start(app: Sanic): print("Reload process started") ``` """ # noqa: E501 return self._setup_listener(listener, "reload_process_start", priority) def reload_process_stop( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the reload_process_stop event. This event is fired only on the reload process and **NOT** on any worker processes. This is similar to the main_process_stop event, except that it is fired only when the reload process is stopped. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.reload_process_stop async def on_reload_process_stop(app: Sanic): print("Reload process stopped") ``` """ # noqa: E501 return self._setup_listener(listener, "reload_process_stop", priority) def before_reload_trigger( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the before_reload_trigger event. This event is fired only on the reload process and **NOT** on any worker processes. This event is fired before the reload process triggers the reload. A change event has been detected and the reload process is about to be triggered. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.before_reload_trigger async def on_before_reload_trigger(app: Sanic): print("Before reload trigger") ``` """ # noqa: E501 return self._setup_listener( listener, "before_reload_trigger", priority ) def after_reload_trigger( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the after_reload_trigger event. This event is fired only on the reload process and **NOT** on any worker processes. This event is fired after the reload process triggers the reload. A change event has been detected and the reload process has been triggered. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.after_reload_trigger async def on_after_reload_trigger(app: Sanic, changed: set[str]): print("After reload trigger, changed files: ", changed) ``` """ # noqa: E501 return self._setup_listener(listener, "after_reload_trigger", priority) def before_server_start( self, listener: Optional[ListenerType[Sanic]] = None, *, priority: int = 0, ) -> ListenerType[Sanic]: """Decorator for registering a listener for the before_server_start event. This event is fired on all worker processes. You should typically use this event to initialize resources that are global in nature, or will be shared across requests and various parts of the application. A common use case for this event is to initialize a database connection pool, or to initialize a cache client. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.before_server_start async def on_before_server_start(app: Sanic): print("Before server start") ``` """ # noqa: E501 return self._setup_listener(listener, "before_server_start", priority) def after_server_start( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the after_server_start event. This event is fired on all worker processes. You should typically use this event to run background tasks, or perform other actions that are not directly related to handling requests. In theory, it is possible that some requests may be handled before this event is fired, so you should not use this event to initialize resources that are required for handling requests. A common use case for this event is to start a background task that periodically performs some action, such as clearing a cache or performing a health check. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.after_server_start async def on_after_server_start(app: Sanic): print("After server start") ``` """ # noqa: E501 return self._setup_listener(listener, "after_server_start", priority) def before_server_stop( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the before_server_stop event. This event is fired on all worker processes. This event is fired before the server starts shutting down. You should not use this event to perform any actions that are required for handling requests, as some requests may continue to be handled after this event is fired. A common use case for this event is to stop a background task that was started in the after_server_start event. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.before_server_stop async def on_before_server_stop(app: Sanic): print("Before server stop") ``` """ # noqa: E501 return self._setup_listener(listener, "before_server_stop", priority) def after_server_stop( self, listener: Optional[ListenerType[Sanic]], *, priority: int = 0 ) -> ListenerType[Sanic]: """Decorator for registering a listener for the after_server_stop event. This event is fired on all worker processes. This event is fired after the server has stopped shutting down, and all requests have been handled. You should typically use this event to clean up resources that were initialized in the before_server_start event. A common use case for this event is to close a database connection pool, or to close a cache client. See [Listeners](/en/guide/basics/listeners) for more details. Args: listener (ListenerType[Sanic]): The listener handler to attach. Examples: ```python @app.after_server_stop async def on_after_server_stop(app: Sanic): print("After server stop") ``` """ # noqa: E501 return self._setup_listener(listener, "after_server_stop", priority)
ListenerMixin
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 199062, "end": 199500 }
class ____: _col_type = INT8MULTIRANGE _col_str = "INT8MULTIRANGE" def _data_str(self): return ( "{[9223372036854775801,9223372036854775803)," + "[9223372036854775805,9223372036854775807)}" ) def _data_obj(self): return [ Range(9223372036854775801, 9223372036854775803), Range(9223372036854775805, 9223372036854775807), ]
_Int8MultiRangeTests
python
sympy__sympy
sympy/stats/stochastic_process_types.py
{ "start": 11397, "end": 11852 }
class ____(TransitionMatrixOf): """ Assumes that the matrix is the generator matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, ContinuousMarkovChain): raise ValueError("Currently only ContinuousMarkovChain " "support GeneratorMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix)
GeneratorMatrixOf
python
jd__tenacity
tenacity/stop.py
{ "start": 2574, "end": 3350 }
class ____(stop_base): """ Stop when the time from the first attempt >= limit. Note: `max_delay` will be exceeded, so when used with a `wait`, the actual total delay will be greater than `max_delay` by some of the final sleep period before `max_delay` is exceeded. If you need stricter timing with waits, consider `stop_before_delay` instead. """ def __init__(self, max_delay: _utils.time_unit_type) -> None: self.max_delay = _utils.to_seconds(max_delay) def __call__(self, retry_state: "RetryCallState") -> bool: if retry_state.seconds_since_start is None: raise RuntimeError("__call__() called but seconds_since_start is not set") return retry_state.seconds_since_start >= self.max_delay
stop_after_delay
python
google__pytype
pytype/pytd/type_match.py
{ "start": 2138, "end": 2416 }
class ____(node.Node): """A type that doesn't allow sub- or superclasses to match. For example, "int" is considered a valid argument for a function that accepts "object", but StrictType("int") is not. """ name: str def __str__(self): return self.name
StrictType
python
celery__celery
t/unit/backends/test_redis.py
{ "start": 50187, "end": 54965 }
class ____: def get_backend(self): from celery.backends.redis import SentinelBackend class _SentinelBackend(SentinelBackend): redis = redis sentinel = sentinel return _SentinelBackend def get_E_LOST(self): from celery.backends.redis import E_LOST return E_LOST def setup_method(self): self.Backend = self.get_backend() self.E_LOST = self.get_E_LOST() self.b = self.Backend(app=self.app) @pytest.mark.usefixtures('depends_on_current_app') def test_reduce(self): pytest.importorskip('redis') from celery.backends.redis import SentinelBackend x = SentinelBackend(app=self.app) assert loads(dumps(x)) def test_no_redis(self): self.Backend.redis = None with pytest.raises(ImproperlyConfigured): self.Backend(app=self.app) def test_url(self): self.app.conf.redis_socket_timeout = 30.0 self.app.conf.redis_socket_connect_timeout = 100.0 x = self.Backend( 'sentinel://:test@github.com:123/1;' 'sentinel://:test@github.com:124/1', app=self.app, ) assert x.connparams assert "host" not in x.connparams assert x.connparams['db'] == 1 assert "port" not in x.connparams assert x.connparams['password'] == "test" assert len(x.connparams['hosts']) == 2 expected_hosts = ["github.com", "github.com"] found_hosts = [cp['host'] for cp in x.connparams['hosts']] assert found_hosts == expected_hosts expected_ports = [123, 124] found_ports = [cp['port'] for cp in x.connparams['hosts']] assert found_ports == expected_ports expected_passwords = ["test", "test"] found_passwords = [cp['password'] for cp in x.connparams['hosts']] assert found_passwords == expected_passwords expected_dbs = [1, 1] found_dbs = [cp['db'] for cp in x.connparams['hosts']] assert found_dbs == expected_dbs # By default passwords should be sanitized display_url = x.as_uri() assert "test" not in display_url # We can choose not to sanitize with the `include_password` argument unsanitized_display_url = x.as_uri(include_password=True) assert unsanitized_display_url == x.url # or to explicitly sanitize forcibly_sanitized_display_url = x.as_uri(include_password=False) assert forcibly_sanitized_display_url == display_url def test_get_sentinel_instance(self): x = self.Backend( 'sentinel://:test@github.com:123/1;' 'sentinel://:test@github.com:124/1', app=self.app, ) sentinel_instance = x._get_sentinel_instance(**x.connparams) assert sentinel_instance.sentinel_kwargs == {} assert sentinel_instance.connection_kwargs['db'] == 1 assert sentinel_instance.connection_kwargs['password'] == "test" assert len(sentinel_instance.sentinels) == 2 def test_get_pool(self): x = self.Backend( 'sentinel://:test@github.com:123/1;' 'sentinel://:test@github.com:124/1', app=self.app, ) pool = x._get_pool(**x.connparams) assert pool def test_backend_ssl(self): pytest.importorskip('redis') from celery.backends.redis import SentinelBackend self.app.conf.redis_backend_use_ssl = { 'ssl_cert_reqs': "CERT_REQUIRED", 'ssl_ca_certs': '/path/to/ca.crt', 'ssl_certfile': '/path/to/client.crt', 'ssl_keyfile': '/path/to/client.key', } self.app.conf.redis_socket_timeout = 30.0 self.app.conf.redis_socket_connect_timeout = 100.0 x = SentinelBackend( 'sentinel://:bosco@vandelay.com:123//1', app=self.app, ) assert x.connparams assert len(x.connparams['hosts']) == 1 assert x.connparams['hosts'][0]['host'] == 'vandelay.com' assert x.connparams['hosts'][0]['db'] == 1 assert x.connparams['hosts'][0]['port'] == 123 assert x.connparams['hosts'][0]['password'] == 'bosco' assert x.connparams['socket_timeout'] == 30.0 assert x.connparams['socket_connect_timeout'] == 100.0 assert x.connparams['ssl_cert_reqs'] == ssl.CERT_REQUIRED assert x.connparams['ssl_ca_certs'] == '/path/to/ca.crt' assert x.connparams['ssl_certfile'] == '/path/to/client.crt' assert x.connparams['ssl_keyfile'] == '/path/to/client.key' from celery.backends.redis import SentinelManagedSSLConnection assert x.connparams['connection_class'] is SentinelManagedSSLConnection
test_SentinelBackend
python
dagster-io__dagster
python_modules/libraries/dagster-gcp-pyspark/dagster_gcp_pyspark/bigquery/bigquery_pyspark_type_handler.py
{ "start": 7348, "end": 11283 }
class ____(BigQueryIOManager): """An I/O manager definition that reads inputs from and writes PySpark DataFrames to BigQuery. Returns: IOManagerDefinition Examples: .. code-block:: python from dagster_gcp_pyspark import BigQueryPySparkIOManager from dagster import Definitions, EnvVar @asset( key_prefix=["my_dataset"] # will be used as the dataset in BigQuery ) def my_table() -> pyspark.sql.DataFrame: # the name of the asset will be the table name ... Definitions( assets=[my_table], resources={ "io_manager": BigQueryPySparkIOManager(project=EnvVar("GCP_PROJECT")) } ) You can set a default dataset to store the assets using the ``dataset`` configuration value of the BigQuery I/O Manager. This dataset will be used if no other dataset is specified directly on an asset or op. .. code-block:: python Definitions( assets=[my_table], resources={ "io_manager": BigQueryPySparkIOManager(project=EnvVar("GCP_PROJECT"), dataset="my_dataset") } ) On individual assets, you an also specify the dataset where they should be stored using metadata or by adding a ``key_prefix`` to the asset key. If both ``key_prefix`` and metadata are defined, the metadata will take precedence. .. code-block:: python @asset( key_prefix=["my_dataset"] # will be used as the dataset in BigQuery ) def my_table() -> pyspark.sql.DataFrame: ... @asset( # note that the key needs to be "schema" metadata={"schema": "my_dataset"} # will be used as the dataset in BigQuery ) def my_other_table() -> pyspark.sql.DataFrame: ... For ops, the dataset can be specified by including a "schema" entry in output metadata. .. code-block:: python @op( out={"my_table": Out(metadata={"schema": "my_schema"})} ) def make_my_table() -> pyspark.sql.DataFrame: ... If none of these is provided, the dataset will default to "public". To only use specific columns of a table as input to a downstream op or asset, add the metadata "columns" to the In or AssetIn. .. code-block:: python @asset( ins={"my_table": AssetIn("my_table", metadata={"columns": ["a"]})} ) def my_table_a(my_table: pyspark.sql.DataFrame) -> pyspark.sql.DataFrame: # my_table will just contain the data from column "a" ... If you cannot upload a file to your Dagster deployment, or otherwise cannot `authenticate with GCP <https://cloud.google.com/docs/authentication/provide-credentials-adc>`_ via a standard method, you can provide a service account key as the "gcp_credentials" configuration. Dagster will store this key in a temporary file and set GOOGLE_APPLICATION_CREDENTIALS to point to the file. After the run completes, the file will be deleted, and GOOGLE_APPLICATION_CREDENTIALS will be unset. The key must be base64 encoded to avoid issues with newlines in the keys. You can retrieve the base64 encoded key with this shell command: cat $GOOGLE_APPLICATION_CREDENTIALS | base64 """ @classmethod def _is_dagster_maintained(cls) -> bool: return True @staticmethod def type_handlers() -> Sequence[DbTypeHandler]: return [BigQueryPySparkTypeHandler()] @staticmethod def default_load_type() -> Optional[type]: return DataFrame
BigQueryPySparkIOManager
python
pandas-dev__pandas
asv_bench/benchmarks/arithmetic.py
{ "start": 11405, "end": 11685 }
class ____: params = other_offsets param_names = ["offset"] def setup(self, offset): N = 10000 rng = date_range(start="1/1/2000", periods=N, freq="min") self.rng = rng def time_apply_index(self, offset): self.rng + offset
ApplyIndex
python
gabrielfalcao__HTTPretty
httpretty/core.py
{ "start": 11505, "end": 11632 }
class ____(dict): """A dict subclass used as internal representation of empty request headers """
EmptyRequestHeaders
python
Textualize__textual
tests/test_message_pump.py
{ "start": 1833, "end": 5367 }
class ____(App): def __init__(self) -> None: self.input_changed_events = [] super().__init__() def compose(self) -> ComposeResult: yield Input() def on_input_changed(self, event: Input.Changed) -> None: self.input_changed_events.append(event) async def test_message_queue_size(): """Test message queue size property.""" app = App() assert app.message_queue_size == 0 class TestMessage(Message): pass async with app.run_test() as pilot: assert app.message_queue_size == 0 app.post_message(TestMessage()) assert app.message_queue_size == 1 app.post_message(TestMessage()) assert app.message_queue_size == 2 # A pause will process all the messages await pilot.pause() assert app.message_queue_size == 0 async def test_prevent() -> None: app = PreventTestApp() async with app.run_test() as pilot: assert not app.input_changed_events input = app.query_one(Input) input.value = "foo" await pilot.pause() assert len(app.input_changed_events) == 1 assert app.input_changed_events[0].value == "foo" with input.prevent(Input.Changed): input.value = "bar" await pilot.pause() assert len(app.input_changed_events) == 1 assert app.input_changed_events[0].value == "foo" async def test_prevent_with_call_next() -> None: """Test for https://github.com/Textualize/textual/issues/3166. Does a callback scheduled with `call_next` respect messages that were prevented when it was scheduled? """ hits = 0 class PreventTestApp(App[None]): def compose(self) -> ComposeResult: yield Input() def change_input(self) -> None: self.query_one(Input).value += "a" def on_input_changed(self) -> None: nonlocal hits hits += 1 app = PreventTestApp() async with app.run_test() as pilot: app.call_next(app.change_input) await pilot.pause() assert hits == 1 with app.prevent(Input.Changed): app.call_next(app.change_input) await pilot.pause() assert hits == 1 app.call_next(app.change_input) await pilot.pause() assert hits == 2 async def test_prevent_default(): """Test that prevent_default doesn't apply when a message is bubbled.""" app_button_pressed = False class MyButton(Button): def _on_button_pressed(self, event: Button.Pressed) -> None: event.prevent_default() class PreventApp(App[None]): def compose(self) -> ComposeResult: yield MyButton("Press me") yield Label("No pressure") def on_button_pressed(self, event: Button.Pressed) -> None: nonlocal app_button_pressed app_button_pressed = True self.query_one(Label).update("Ouch!") app = PreventApp() async with app.run_test() as pilot: await pilot.click(MyButton) assert app_button_pressed async def test_thread_safe_post_message(): class TextMessage(Message): pass class TestApp(App): def on_mount(self) -> None: msg = TextMessage() threading.Thread(target=self.post_message, args=(msg,)).start() def on_text_message(self, message): self.exit() app = TestApp() async with app.run_test() as pilot: await pilot.pause()
PreventTestApp
python
weaviate__weaviate-python-client
weaviate/collections/classes/filters.py
{ "start": 4109, "end": 4243 }
class ____(_WeaviateInput): link_on: str target: Optional["_FilterTargets"] = Field(exclude=True, default=None)
_SingleTargetRef
python
walkccc__LeetCode
solutions/559. Maximum Depth of N-ary Tree/559.py
{ "start": 0, "end": 200 }
class ____: def maxDepth(self, root: 'Node') -> int: if not root: return 0 if not root.children: return 1 return 1 + max(self.maxDepth(child) for child in root.children)
Solution