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
wandb__wandb
wandb/vendor/pygments/lexers/go.py
{ "start": 427, "end": 3701 }
class ____(RegexLexer): """ For `Go <http://golang.org>`_ source. .. versionadded:: 1.2 """ name = 'Go' filenames = ['*.go'] aliases = ['go'] mimetypes = ['text/x-gosrc'] flags = re.MULTILINE | re.UNICODE tokens = { 'root': [ (r'\n', Text), (r'\...
GoLexer
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 101308, "end": 102760 }
class ____(Structure): _fields_ = [("flags", c_uint), ("utilization", c_nvmlGpuDynamicPstatesUtilization_t * NVML_MAX_GPU_UTILIZATIONS)] NVML_MAX_THERMAL_SENSORS_PER_GPU = 3 NVML_THERMAL_TARGET_NONE = 0 NVML_THERMAL_TARGET_GPU = 1 NVML_THERMAL_TARGET_MEMORY = 2 NVML_THERM...
c_nvmlGpuDynamicPstatesInfo_t
python
kamyu104__LeetCode-Solutions
Python/make-array-strictly-increasing.py
{ "start": 73, "end": 851 }
class ____(object): def makeArrayIncreasing(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: int """ arr2 = sorted(set(arr2)) dp = {0: -1} # dp[min_cost] = end_with_val for val1 in arr1: next_dp = collections.defa...
Solution
python
pytorch__pytorch
torch/ao/quantization/quantizer/quantizer.py
{ "start": 847, "end": 2188 }
class ____(QuantizationSpecBase): """Quantization spec for common operators that allows user to specify how to quantize a Tensor, this includes dtype, quant_min, quant_max etc. """ dtype: torch.dtype # observer or fake_quantize constructor such as # MinMaxObserver, PerChannelHistogramObserver e...
QuantizationSpec
python
scipy__scipy
scipy/optimize/_differentiable_functions.py
{ "start": 447, "end": 1495 }
class ____: """ Wrapper class for gradient calculation """ def __init__( self, grad, fun=None, args=None, finite_diff_options=None, ): self.fun = fun self.grad = grad self.args = [] if args is None else args ...
_ScalarGradWrapper
python
mahmoud__glom
glom/core.py
{ "start": 39035, "end": 46498 }
class ____: """Specifier type designed for easy invocation of callables from glom. Args: func (callable): A function or other callable object. ``Invoke`` is similar to :func:`functools.partial`, but with the ability to set up a "templated" call which interleaves constants and glom specs. ...
Invoke
python
run-llama__llama_index
llama-index-core/llama_index/core/download/utils.py
{ "start": 4400, "end": 4806 }
class ____: """Context manager for changing the current working directory.""" def __init__(self, new_path: str): self.new_path = os.path.expanduser(new_path) def __enter__(self) -> None: self.saved_path = os.getcwd() os.chdir(self.new_path) def __exit__(self, etype: object, va...
ChangeDirectory
python
networkx__networkx
networkx/classes/reportviews.py
{ "start": 12224, "end": 15277 }
class ____: """A View class for degree of nodes in a NetworkX Graph The functionality is like dict.items() with (node, degree) pairs. Additional functionality includes read-only lookup of node degree, and calling with optional features nbunch (for only a subset of nodes) and weight (use edge weight...
DiDegreeView
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 95119, "end": 96887 }
class ____(Expr): """Mixin class for partition filtering A ``PartitionsFiltered`` subclass must define a ``_partitions`` parameter. When ``_partitions`` is defined, the following expressions must produce the same output for :cls:`PartitionsFiltered`: - ``cls(expr: Expr, ..., _partitions)`` - `...
PartitionsFiltered
python
crytic__slither
slither/detectors/attributes/const_functions_state.py
{ "start": 440, "end": 3411 }
class ____(AbstractDetector): """ Constant function detector """ ARGUMENT = "constant-function-state" # run the detector with slither.py --ARGUMENT HELP = "Constant functions changing the state" # help information IMPACT = DetectorClassification.MEDIUM CONFIDENCE = DetectorClassification....
ConstantFunctionsState
python
coleifer__peewee
examples/analytics/app.py
{ "start": 1952, "end": 4355 }
class ____(BaseModel): account = ForeignKeyField(Account, backref='pageviews') url = TextField() timestamp = DateTimeField(default=datetime.datetime.now) title = TextField(default='') ip = CharField(default='') referrer = TextField(default='') headers = BinaryJSONField() params = BinaryJ...
PageView
python
openai__openai-python
src/openai/resources/containers/files/files.py
{ "start": 19111, "end": 19790 }
class ____: def __init__(self, files: AsyncFiles) -> None: self._files = files self.create = _legacy_response.async_to_raw_response_wrapper( files.create, ) self.retrieve = _legacy_response.async_to_raw_response_wrapper( files.retrieve, ) self...
AsyncFilesWithRawResponse
python
huggingface__transformers
tests/models/pixtral/test_processing_pixtral.py
{ "start": 972, "end": 13015 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = PixtralProcessor model_id = "mistral-community/pixtral-12b" url_0 = url_to_local_path( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" ) image_0 = np.random...
PixtralProcessorTest
python
wandb__wandb
wandb/vendor/pygments/lexers/algebra.py
{ "start": 6167, "end": 7201 }
class ____(RegexLexer): """ A `BC <https://www.gnu.org/software/bc/>`_ lexer. .. versionadded:: 2.1 """ name = 'BC' aliases = ['bc'] filenames = ['*.bc'] tokens = { 'root': [ (r'/\*', Comment.Multiline, 'comment'), (r'"(?:[^"\\]|\\.)*"', String), ...
BCLexer
python
ray-project__ray
rllib/examples/envs/classes/cartpole_with_protobuf_observation_space.py
{ "start": 208, "end": 2973 }
class ____(CartPoleEnv): """CartPole gym environment that has a protobuf observation space. Sometimes, it is more performant for an environment to publish its observations as a protobuf message (instead of a heavily nested Dict). The protobuf message used here is originally defined in the `./utils...
CartPoleWithProtobufObservationSpace
python
pypa__pipenv
pipenv/vendor/click/core.py
{ "start": 111658, "end": 114142 }
class ____(Parameter): """Arguments are positional parameters to a command. They generally provide fewer features than options but can have infinite ``nargs`` and are required by default. All parameters are passed onwards to the constructor of :class:`Parameter`. """ param_type_name = "argume...
Argument
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/bounding_boxes/formats.py
{ "start": 2829, "end": 3377 }
class ____: """REL_YXYX contains axis indices for the REL_YXYX format. REL_YXYX is like YXYX, but each value is relative to the width and height of the origin image. Values are percentages of the origin images' width and height respectively. The REL_YXYX format consists of the following required i...
REL_YXYX
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 31182, "end": 31420 }
class ____(Structure): _fields_ = (("offset", p_uint32), ("nhints", p_uint32)) def describe(self): s = {} s["offset"] = int(self.offset) s["nhints"] = int(self.nhints) return s
twolevel_hints_command
python
astropy__astropy
astropy/table/column.py
{ "start": 41330, "end": 50645 }
class ____(BaseColumn): """Define a data column for use in a Table object. Parameters ---------- data : list, ndarray, or None Column data values name : str Column name and key for reference within Table dtype : `~numpy.dtype`-like Data type for column shape : tuple ...
Column
python
getsentry__sentry
tests/sentry/relocation/tasks/test_process.py
{ "start": 45032, "end": 49447 }
class ____(RelocationTaskTestCase): def setUp(self) -> None: super().setUp() self.relocation.step = Relocation.Step.PREPROCESSING.value self.relocation.latest_task = OrderedTask.PREPROCESSING_BASELINE_CONFIG.name self.relocation.want_usernames = ["a", "b", "c"] self.relocatio...
PreprocessingCollidingUsersTest
python
lepture__mistune
tests/test_directives.py
{ "start": 1211, "end": 2294 }
class ____(BaseTestCase): def test_rst_toc(self): md = create_markdown( escape=False, plugins=[ RSTDirective([CustomizeTableOfContents()]), ], ) html = md("# h1\n\n.. toc::\n") self.assertIn('<h1 id="t-1">h1</h1>', html) sel...
TestCustomizeToc
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/legacy_resources.py
{ "start": 1146, "end": 1353 }
class ____: def __init__(self) -> None: self.request_cache: dict[str, Optional[Mapping[str, object]]] = {} # Int in case we nest contexts self.cache_enabled = 0
AirbyteResourceState
python
pytest-dev__pytest
testing/python/approx.py
{ "start": 38588, "end": 39128 }
class ____: # incomplete """sequence like""" _x: int _y: int _z: int def __init__(self, x: int, y: int, z: int): self._x, self._y, self._z = x, y, z def __repr__(self) -> str: return f"<MyVec3 {self._x} {self._y} {self._z}>" def __len__(self) -> int: return 3 ...
MyVec3
python
cherrypy__cherrypy
cherrypy/lib/encoding.py
{ "start": 2302, "end": 18361 }
class ____: """An HTTP response payload encoder.""" default_encoding = 'utf-8' failmsg = 'Response body could not be encoded with %r.' encoding = None errors = 'strict' text_only = True add_charset = True debug = False def __init__(self, **kwargs): """Initialize HTTP respon...
ResponseEncoder
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 970994, "end": 971382 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field(SocialAccount, graphql_nam...
SocialAccountEdge
python
wandb__wandb
wandb/sdk/lib/retry.py
{ "start": 10705, "end": 10980 }
class ____(abc.ABC): """A backoff strategy: decides whether to sleep or give up when an exception is raised.""" @abc.abstractmethod def next_sleep_or_reraise(self, exc: Exception) -> datetime.timedelta: raise NotImplementedError # pragma: no cover
Backoff
python
joke2k__faker
faker/providers/address/ro_RO/__init__.py
{ "start": 71, "end": 9605 }
class ____(AddressProvider): street_prefixes = ( "Strada", "Aleea", "Intrarea", "Bulevardul", "Soseaua", "Drumul", ) street_name_formats = ( "{{street_prefix}} {{last_name}}", "{{street_prefix}} {{first_name}} {{last_name}}", "{{street_...
Provider
python
google__pytype
pytype/typegraph/typegraph_serializer_test.py
{ "start": 165, "end": 1464 }
class ____(test_base.BaseTest): def test_basic(self): ctx = test_utils.make_context(self.options) # Max depth is arbitrarily chosen from analyze.py. loc, defs = ctx.vm.run_program(src="", filename="", maximum_depth=3) ctx.vm.analyze(loc, defs, maximum_depth=3) prog = ctx.program enc = typegr...
TypegraphSerializerTest
python
pypa__hatch
tests/publish/plugin/test_interface.py
{ "start": 79, "end": 214 }
class ____(PublisherInterface): # no cov PLUGIN_NAME = "mock" def publish(self, artifacts, options): pass
MockPublisher
python
oauthlib__oauthlib
tests/oauth1/rfc5849/test_signatures.py
{ "start": 1958, "end": 36119 }
class ____(TestCase): """ Unit tests for the oauthlib/oauth1/rfc5849/signature.py module. The tests in this class are organised into sections, to test the functions relating to: - Signature base string calculation - HMAC-based signature methods - RSA-based signature methods - P...
SignatureTests
python
davidhalter__parso
parso/python/errors.py
{ "start": 18215, "end": 18295 }
class ____(NormalizerConfig): normalizer_class = ErrorFinder
ErrorFinderConfig
python
getsentry__sentry
src/sentry/users/models/authenticator.py
{ "start": 6524, "end": 8850 }
class ____(ControlOutboxProducingModel): # It only makes sense to import/export this data when doing a full global backup/restore, so it # lives in the `Global` scope, even though it only depends on the `User` model. __relocation_scope__ = RelocationScope.Global id = BoundedAutoField(primary_key=True) ...
Authenticator
python
tensorflow__tensorflow
tensorflow/python/keras/losses.py
{ "start": 41087, "end": 71120 }
class ____(LossFunctionWrapper): """Computes the Huber loss between `y_true` and `y_pred`. For each value x in `error = y_true - y_pred`: ``` loss = 0.5 * x^2 if |x| <= d loss = 0.5 * d^2 + d * (|x| - d) if |x| > d ``` where d is `delta`. See: https://en.wikipedia.org/wiki/Huber_loss ...
Huber
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F706.py
{ "start": 31, "end": 66 }
class ____: return 2 return 3
Foo
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/interfaces.py
{ "start": 98633, "end": 108216 }
class ____: """A messenger object for a Dialect that corresponds to a single execution. """ engine: Engine """engine which the Connection is associated with""" connection: Connection """Connection object which can be freely used by default value generators to execute SQL. This Conn...
ExecutionContext
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingTypeIs1.py
{ "start": 1218, "end": 1621 }
class ____: pass def func6(val: AFinal | BFinal) -> None: if type(val) is AFinal: reveal_type(val, expected_text="AFinal") else: reveal_type(val, expected_text="BFinal") def func7(val: Any): if type(val) is int: reveal_type(val, expected_text="int") else: reveal_t...
BFinal
python
huggingface__transformers
src/transformers/models/bridgetower/modeling_bridgetower.py
{ "start": 29624, "end": 32754 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_idx=None): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = BridgeTowerAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx) ...
BridgeTowerTextLayer
python
mahmoud__boltons
boltons/socketutils.py
{ "start": 3696, "end": 24349 }
class ____: """Mainly provides recv_until and recv_size. recv, send, sendall, and peek all function as similarly as possible to the built-in socket API. This type has been tested against both the built-in socket type as well as those from gevent and eventlet. It also features support for socket...
BufferedSocket
python
ethereum__web3.py
web3/contract/base_contract.py
{ "start": 47561, "end": 50631 }
class ____: """ An alternative Contract API. This call: > contract.caller({'from': eth.accounts[1], 'gas': 100000, ...}).add(2, 3) is equivalent to this call in the classic contract: > contract.functions.add(2, 3).call({'from': eth.accounts[1], 'gas': 100000, ...}) Other options for invok...
BaseContractCaller
python
PrefectHQ__prefect
src/prefect/task_worker.py
{ "start": 2527, "end": 20805 }
class ____: """This class is responsible for serving tasks that may be executed in the background by a task runner via the traditional engine machinery. When `start()` is called, the task worker will open a websocket connection to a server-side queue of scheduled task runs. When a scheduled task run is...
TaskWorker
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/array_ops_test.py
{ "start": 12968, "end": 14453 }
class ____(test_util.TensorFlowTestCase): def testExpandScalar(self): scalar = "hello" scalar_expanded = array_ops.expand_dims(scalar, [0]) self.assertEqual(scalar_expanded.get_shape(), (1,)) def testSqueezeScalar(self): scalar = "hello" scalar_squeezed = array_ops.squeeze(scalar, ()) self...
OperatorShapeTest
python
pytorch__pytorch
test/inductor/test_remote_cache.py
{ "start": 872, "end": 1833 }
class ____(TestCase): def test_normal_logging( self, ) -> None: c = RemoteCache(NoopBackend(), RemoteCachePassthroughSerde()) c.put("test", "value") c.get("test") def test_failure_no_sample( self, ) -> None: c = RemoteCache(FailingBackend(), RemoteCachePa...
TestRemoteCache
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 9907, "end": 9977 }
class ____(_CollectionsPermission): pass
CollectionsPermissionOutput
python
kamyu104__LeetCode-Solutions
Python/process-string-with-special-operations-ii.py
{ "start": 51, "end": 805 }
class ____(object): def processStr(self, s, k): """ :type s: str :type k: int :rtype: str """ l = 0 for x in s: if x == '*': l = max(l-1, 0) elif x == '#': l <<= 1 elif x == '%': ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-tiktok-marketing/unit_tests/integration/test_reports_hourly.py
{ "start": 16238, "end": 20643 }
class ____(TestCase): stream_name = "advertisers_reports_hourly" advertiser_id = "872746382648" cursor = "2024-01-01 10:00:00" cursor_field = "stat_time_hour" metrics = [ "spend", "cpc", "cpm", "impressions", "clicks", "ctr", "reach", "...
TestAdvertisersReportsHourly
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 15779, "end": 16528 }
class ____(RenderedComponentContent): def __init__( self, content_blocks, styling=None, content_block_type="content_block_container" ) -> None: super().__init__(content_block_type=content_block_type, styling=styling) self.content_blocks = content_blocks @override def to_json_dic...
RenderedContentBlockContainer
python
ray-project__ray
python/ray/util/collective/examples/nccl_allreduce_multigpu_example.py
{ "start": 126, "end": 1201 }
class ____: def __init__(self): with Device(0): self.send1 = cp.ones((4,), dtype=cp.float32) with Device(1): self.send2 = cp.ones((4,), dtype=cp.float32) * 2 self.recv = cp.zeros((4,), dtype=cp.float32) def setup(self, world_size, rank): collective.init_...
Worker
python
facebook__pyre-check
client/commands/tests/infer_test.py
{ "start": 28905, "end": 49690 }
class ____(testslide.TestCase): def _assert_stubs( self, data: Dict[str, Any], expected: str, annotate_attributes: bool = False, use_future_annotations: bool = False, quote_annotations: bool = False, simple_annotations: bool = False, test_path: str = "...
StubGenerationTest
python
gevent__gevent
src/greentest/3.14/test_smtplib.py
{ "start": 37799, "end": 38628 }
class ____(smtpd.SMTPServer): channel_class = SimSMTPChannel def __init__(self, *args, **kw): self._extra_features = [] self._addresses = {} smtpd.SMTPServer.__init__(self, *args, **kw) def handle_accepted(self, conn, addr): self._SMTPchannel = self.channel_class( ...
SimSMTPServer
python
numpy__numpy
numpy/_core/tests/test_item_selection.py
{ "start": 131, "end": 3769 }
class ____: def test_simple(self): a = [[1, 2], [3, 4]] a_str = [[b'1', b'2'], [b'3', b'4']] modes = ['raise', 'wrap', 'clip'] indices = [-1, 4] index_arrays = [np.empty(0, dtype=np.intp), np.empty((), dtype=np.intp), np.empty((...
TestTake
python
pytorch__pytorch
torch/_higher_order_ops/utils.py
{ "start": 1145, "end": 39717 }
class ____(RuntimeError): reason: str def autograd_not_implemented_inner( operator: OperatorBase, delayed_error: bool, *args: Any, **kwargs: Any ) -> Any: """If autograd is enabled and any of the arguments require grad this will either raise an error or return a DelayedError depending on the value of ...
UnsupportedAliasMutationException
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/traversals.py
{ "start": 14473, "end": 33091 }
class ____(HasTraversalDispatch, util.MemoizedSlots): __slots__ = "stack", "cache", "anon_map" def __init__(self): self.stack: Deque[ Tuple[ Optional[ExternallyTraversible], Optional[ExternallyTraversible], ] ] = deque() self.cache...
TraversalComparatorStrategy
python
bokeh__bokeh
tests/unit/bokeh/colors/test_util__colors.py
{ "start": 1014, "end": 1432 }
class ____(bcu.ColorGroup): _colors = ("Red", "Green", "Blue") #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- #-----------------------------------------------------------------------------...
_TestGroup
python
kubernetes-client__python
kubernetes/client/models/v1_service_list.py
{ "start": 383, "end": 6798 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1ServiceList
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/openapi/exceptions.py
{ "start": 855, "end": 1637 }
class ____(BaseModel): """HTTPException Model used for error response.""" detail: str | dict def create_openapi_http_exception_doc(responses_status_code: list[int]) -> dict: """ Will create additional response example for errors raised by the endpoint. There is no easy way to introspect the code...
HTTPExceptionResponse
python
readthedocs__readthedocs.org
readthedocs/embed/v3/tests/test_basics.py
{ "start": 163, "end": 2479 }
class ____: @pytest.fixture(autouse=True) def setup_method(self, settings): settings.PUBLIC_DOMAIN = "readthedocs.io" settings.RTD_EMBED_API_EXTERNAL_DOMAINS = [r"^docs\.project\.com$"] self.api_url = reverse("embed_api_v3") yield cache.clear() def test_not_url_que...
TestEmbedAPIv3Basics
python
huggingface__transformers
src/transformers/models/sam2_video/modular_sam2_video.py
{ "start": 64012, "end": 65878 }
class ____(nn.Module): def __init__(self, config: Sam2VideoConfig): super().__init__() hidden_size = config.memory_encoder_hidden_size output_channels = config.memory_encoder_output_channels self.mask_downsampler = Sam2VideoMaskDownSampler(config) self.feature_projection = n...
Sam2VideoMemoryEncoder
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-google/llama_index/vector_stores/google/genai_extension.py
{ "start": 3604, "end": 4732 }
class ____: """ Global configuration for Google Generative AI API. Normally, the defaults should work fine. Use this to pass Google Auth credentials such as using a service account. Refer to for auth credentials documentation: https://developers.google.com/identity/protocols/oauth2/service-account#...
Config
python
etianen__django-reversion
tests/test_app/tests/test_models.py
{ "start": 16522, "end": 17321 }
class ____(TestBase): def setUp(self): reversion.register(TestModelInlineByNaturalKey, use_natural_foreign_keys=True) reversion.register(TestModelWithNaturalKey) def testNaturalKeyInline(self): with reversion.create_revision(): inline = TestModelWithNaturalKey.objects.creat...
NaturalKeyTest
python
ray-project__ray
python/ray/_private/runtime_env/uv.py
{ "start": 1512, "end": 7742 }
class ____: def __init__( self, target_dir: str, runtime_env: "RuntimeEnv", # noqa: F821 logger: Optional[logging.Logger] = default_logger, ): try: import virtualenv # noqa: F401 ensure virtualenv exists. except ImportError: raise Runtime...
UvProcessor
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 4720, "end": 5425 }
class ____(Base): """SQLAlchemy mixin of a flow.""" name: Mapped[str] tags: Mapped[list[str]] = mapped_column(JSON, server_default="[]", default=list) labels: Mapped[Optional[schemas.core.KeyValueLabels]] = mapped_column(JSON) flow_runs: Mapped[list["FlowRun"]] = relationship( back_populat...
Flow
python
pytorch__pytorch
test/test_serialization.py
{ "start": 4256, "end": 4738 }
class ____(torch.Tensor): @staticmethod def __new__(cls, elem, **kwargs): assert elem.dtype is torch.uint8 assert not kwargs.get("requires_grad", False) kwargs["requires_grad"] = False return torch.Tensor._make_wrapper_subclass(cls, up_size(elem.shape), dtype=torch.int4, **kwargs...
Int4Tensor
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 36280, "end": 39491 }
class ____(GoogleCloudBaseOperator): """ Deletes a DataScan resource. :param project_id: Required. The ID of the Google Cloud project that the lake belongs to. :param region: Required. The ID of the Google Cloud region that the lake belongs to. :param data_scan_id: Required. Data Quality scan ident...
DataplexDeleteDataQualityScanOperator
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/annotation.py
{ "start": 1441, "end": 2989 }
class ____(ExternallyTraversible): __slots__ = () _annotations: util.immutabledict[str, Any] = EMPTY_ANNOTATIONS proxy_set: util.generic_fn_descriptor[FrozenSet[Any]] _is_immutable: bool def _annotate(self, values: _AnnotationDict) -> Self: raise NotImplementedError() @overload ...
SupportsAnnotations
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/test_response_format.py
{ "start": 2930, "end": 5869 }
class ____: def test_pydantic_model(self) -> None: """Test response_format as Pydantic model.""" tool_calls = [ [{"args": {}, "id": "1", "name": "get_weather"}], [ { "name": "WeatherBaseModel", "id": "2", ...
TestResponseFormatAsModel
python
TheAlgorithms__Python
machine_learning/automatic_differentiation.py
{ "start": 3962, "end": 4715 }
class ____: """ Class represents operation between single or two Variable objects. Operation objects contains type of operation, pointers to input Variable objects and pointer to resulting Variable from the operation. """ def __init__( self, op_type: OpType, other_params...
Operation
python
etianen__django-reversion
tests/test_app/tests/test_models.py
{ "start": 5526, "end": 5993 }
class ____(TestModelMixin, TestBase): databases = {"default", "postgres"} def testGetForObjectReferenceModelDb(self): with reversion.create_revision(using="postgres"): obj = TestModel.objects.create() self.assertEqual(Version.objects.get_for_object_reference(TestModel, obj.pk).count...
GetForObjectReferenceDbTest
python
django-import-export__django-import-export
tests/core/tests/test_command_utils.py
{ "start": 1038, "end": 2514 }
class ____(TestCase): def test_load_by_format_name(self): format_class = get_format_class("CSV", None) self.assertIsInstance(format_class, base_formats.CSV) def test_load_by_full_format_path(self): format_class = get_format_class("import_export.formats.base_formats.CSV", None) s...
GetFormatClassTest
python
getsentry__sentry
tests/sentry/event_manager/test_severity.py
{ "start": 1079, "end": 11270 }
class ____(TestCase): @patch( "sentry.event_manager.severity_connection_pool.urlopen", return_value=HTTPResponse(body=orjson.dumps({"severity": 0.1231})), ) def test_error_event_simple(self, mock_urlopen: MagicMock) -> None: manager = EventManager( make_event( ...
TestGetEventSeverity
python
huggingface__transformers
src/transformers/models/cvt/modeling_cvt.py
{ "start": 16827, "end": 17866 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.stages = nn.ModuleList([]) for stage_idx in range(len(config.depth)): self.stages.append(CvtStage(config, stage_idx)) def forward(self, pixel_values, output_hidden_states=...
CvtEncoder
python
numba__numba
numba/tests/test_parfors_passes.py
{ "start": 4650, "end": 7154 }
class ____(BaseTest): sub_pass_class = numba.parfors.parfor.ConvertSetItemPass def test_setitem_full_slice(self): def test_impl(): n = 10 a = np.ones(n) a[:] = 7 return a sub_pass = self.run_parfor_sub_pass(test_impl, ()) self.assertEqual...
TestConvertSetItemPass
python
numpy__numpy
numpy/_core/tests/test_datetime.py
{ "start": 593, "end": 123524 }
class ____: def test_string(self): msg = "no explicit representation of timezones available for " \ "np.datetime64" with pytest.warns(UserWarning, match=msg): np.datetime64('2000-01-01T00+01') def test_datetime(self): msg = "no explicit representation of timez...
TestDateTime
python
networkx__networkx
networkx/classes/reportviews.py
{ "start": 44310, "end": 44809 }
class ____(OutMultiEdgeView): """A EdgeView class for edges of a MultiGraph""" __slots__ = () dataview = MultiEdgeDataView def __len__(self): return sum(1 for e in self) def __iter__(self): seen = {} for n, nbrs in self._nodes_nbrs(): for nbr, kd in nbrs.items...
MultiEdgeView
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 75416, "end": 78437 }
class ____(Elemwise): """Reset the index of a Series or DataFrame""" _parameters = ["frame", "drop", "name"] _defaults = {"drop": False, "name": no_default} _keyword_only = ["drop", "name"] operation = M.reset_index _filter_passthrough = True _preserves_partitioning_information = True ...
ResetIndex
python
apache__airflow
providers/google/tests/unit/google/common/test_deprecated.py
{ "start": 1110, "end": 10201 }
class ____: @mock.patch(f"{ADAPTER_CLASS_PATH}._validate_fields") @mock.patch(f"{ADAPTER_CLASS_PATH}._validate_removal_release") @mock.patch(f"{ADAPTER_CLASS_PATH}._validate_date") def test_init(self, mock_validate_date, mock_validate_removal_release, mock_validate_fields): mock_date = mock_vali...
TestAirflowDeprecationAdapter
python
facebookresearch__faiss
benchs/bench_all_ivf/datasets_oss.py
{ "start": 678, "end": 3655 }
class ____(faiss_datasets.Dataset): def __init__(self, ds, indexfile): self.d = ds.d self.metric = ds.metric self.nq = ds.nq self.xq = ds.get_queries() # get the xb set src_index = faiss.read_index(indexfile) src_quant = faiss.downcast_index(src_index.quanti...
DatasetCentroids
python
django-guardian__django-guardian
guardian/testapp/tests/test_managers.py
{ "start": 167, "end": 1364 }
class ____(TestCase): def test_user_manager_assign(self): manager = UserObjectPermissionManager() manager.assign_perm = mock.Mock() with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") manager.assign("perm", "user", "object") mana...
TestManagers
python
pytorch__pytorch
test/inductor/test_cutlass_backend.py
{ "start": 4647, "end": 85723 }
class ____(TestCase): def setUp(self): if not HAS_CUDA_AND_TRITON: self.skipTest("CUDA and triton are not available") if torch.version.hip: self.skipTest("CUTLASS backend is not supported on HIP") # The new inductor cache refresh mechanism # introduced with h...
TestCutlassBackend
python
sphinx-doc__sphinx
sphinx/builders/linkcheck.py
{ "start": 27327, "end": 31154 }
class ____(NamedTuple): delay: float next_check: float def rewrite_github_anchor(app: Sphinx, uri: str) -> str | None: """Rewrite anchor name of the hyperlink to github.com The hyperlink anchors in github.com are dynamically generated. This rewrites them before checking and makes them comparable...
RateLimit
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 183043, "end": 183661 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateEnvironment""" __schema__ = github_schema __field_names__ = ("repository_id", "name", "client_mutation_id") repository_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="repositoryId") """The node ID of the repository."...
CreateEnvironmentInput
python
PyCQA__pylint
doc/data/messages/a/arguments-differ/bad.py
{ "start": 93, "end": 251 }
class ____(Drink): def mix(self, fluid_one, fluid_two, alcoholic_fluid): # [arguments-differ] return fluid_one + fluid_two + alcoholic_fluid
Cocktail
python
scikit-learn__scikit-learn
sklearn/utils/_param_validation.py
{ "start": 22963, "end": 23231 }
class ____(_Constraint): """Constraint representing iterables that are not strings.""" def is_satisfied_by(self, val): return isinstance(val, Iterable) and not isinstance(val, str) def __str__(self): return "an iterable"
_IterablesNotString
python
doocs__leetcode
solution/1000-1099/1073.Adding Two Negabinary Numbers/Solution.py
{ "start": 0, "end": 618 }
class ____: def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]: i, j = len(arr1) - 1, len(arr2) - 1 c = 0 ans = [] while i >= 0 or j >= 0 or c: a = 0 if i < 0 else arr1[i] b = 0 if j < 0 else arr2[j] x = a + b + c c ...
Solution
python
kamyu104__LeetCode-Solutions
Python/maximum-non-negative-product-in-a-matrix.py
{ "start": 58, "end": 1161 }
class ____(object): def maxProductPath(self, grid): """ :type grid: List[List[int]] :rtype: int """ MOD = 10**9+7 max_dp = [[0]*len(grid[0]) for _ in xrange(2)] min_dp = [[0]*len(grid[0]) for _ in xrange(2)] for i in xrange(len(grid)): for ...
Solution
python
pypa__warehouse
warehouse/oidc/forms/google.py
{ "start": 973, "end": 1030 }
class ____(GooglePublisherBase): pass
GooglePublisherForm
python
scipy__scipy
scipy/spatial/tests/test_kdtree.py
{ "start": 16107, "end": 16264 }
class ____(_Test_two_random_trees): def setup_method(self): super().setup_method() self.p = np.inf @KDTreeTest
_Test_two_random_trees_linf
python
openai__openai-python
src/openai/types/vector_stores/vector_store_file_deleted.py
{ "start": 199, "end": 321 }
class ____(BaseModel): id: str deleted: bool object: Literal["vector_store.file.deleted"]
VectorStoreFileDeleted
python
patrick-kidger__equinox
equinox/nn/_conv.py
{ "start": 11539, "end": 12504 }
class ____(Conv): """As [`equinox.nn.Conv`][] with `num_spatial_dims=3`.""" def __init__( self, in_channels: int, out_channels: int, kernel_size: int | Sequence[int], stride: int | Sequence[int] = (1, 1, 1), padding: str | int | Sequence[int] | Sequence[tuple[int...
Conv3d
python
django__django
tests/nested_foreign_keys/models.py
{ "start": 105, "end": 236 }
class ____(models.Model): title = models.CharField(max_length=200) director = models.ForeignKey(Person, models.CASCADE)
Movie
python
pyparsing__pyparsing
examples/tiny/tiny_engine.py
{ "start": 917, "end": 1923 }
class ____: """A single stack frame holding local variables and their types. Variables in TINY are stored per-frame; lookups search the current frame first, then the global frame. """ def __init__(self) -> None: # maintain mapping of name -> var definitions self._vars: dict[str, li...
TinyFrame
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py
{ "start": 113334, "end": 124366 }
class ____(ShopifyBulkQuery): """ Output example to BULK query `order agreement` from `orders` with `filter query` by `updated_at` sorted `ASC`: { orders(query: "updated_at:>='2020-06-13T00:00:00+00:00' AND updated_at:<'2024-06-14T00:00:00+00:00'", sortKey:UPDATED_AT) { edges...
OrderAgreement
python
numpy__numpy
numpy/_build_utils/tempita/_looper.py
{ "start": 987, "end": 1338 }
class ____: def __init__(self, seq): self.seq = list(seq) self.pos = 0 def __iter__(self): return self def __next__(self): if self.pos >= len(self.seq): raise StopIteration result = loop_pos(self.seq, self.pos), self.seq[self.pos] self.pos += 1 ...
looper_iter
python
sympy__sympy
sympy/physics/quantum/qft.py
{ "start": 1252, "end": 2817 }
class ____(OneQubitGate): """This is the R_k gate of the QTF.""" gate_name = 'Rk' gate_name_latex = 'R' def __new__(cls, *args): if len(args) != 2: raise QuantumError( 'Rk gates only take two arguments, got: %r' % args ) # For small k, Rk gates si...
RkGate
python
PrefectHQ__prefect
src/prefect/futures.py
{ "start": 16628, "end": 19736 }
class ____(list[PrefectFuture[R]], Iterator[PrefectFuture[R]]): """ A list of Prefect futures. This class provides methods to wait for all futures in the list to complete and to retrieve the results of all task runs. """ def wait(self, timeout: float | None = None) -> None: """ ...
PrefectFutureList
python
paramiko__paramiko
paramiko/auth_strategy.py
{ "start": 1340, "end": 2804 }
class ____(AuthSource): """ Password authentication. :param callable password_getter: A lazy callable that should return a `str` password value at authentication time, such as a `functools.partial` wrapping `getpass.getpass`, an API call to a secrets store, or similar. If y...
Password
python
chroma-core__chroma
chromadb/utils/embedding_functions/fastembed_sparse_embedding_function.py
{ "start": 459, "end": 7228 }
class ____(SparseEmbeddingFunction[Documents]): def __init__( self, model_name: str, task: Optional[TaskType] = "document", cache_dir: Optional[str] = None, threads: Optional[int] = None, cuda: Optional[bool] = None, device_ids: Optional[list[int]] = None, ...
FastembedSparseEmbeddingFunction
python
python-openxml__python-docx
tests/test_package.py
{ "start": 1769, "end": 5517 }
class ____: """Unit-test suite for `docx.package.Package`.""" def it_can_get_a_matching_image_part( self, Image_: Mock, image_: Mock, _get_by_sha1_: Mock, image_part_: Mock, ): Image_.from_file.return_value = image_ image_.sha1 = "f005ba11" _g...
DescribeImageParts
python
google__jax
docs/autodidax.py
{ "start": 25806, "end": 26259 }
class ____(Tracer): def __init__(self, trace, val, batch_dim: BatchAxis): self._trace = trace self.val = val self.batch_dim = batch_dim @property def aval(self): if self.batch_dim is not_mapped: return get_aval(self.val) else: return mapped_aval(self.batch_dim, get_aval(self.val))...
BatchTracer
python
PrefectHQ__prefect
src/prefect/utilities/schema_tools/hydration.py
{ "start": 4131, "end": 9436 }
class ____(Placeholder): def __init__(self, template: str) -> None: self.template = template def __eq__(self, other: Any) -> bool: return isinstance(other, type(self)) and self.template == other.template def handler(kind: PrefectKind) -> Callable[[Handler], Handler]: def decorator(func: H...
ValidJinja
python
walkccc__LeetCode
solutions/2997. Minimum Number of Operations to Make Array XOR Equal to K/2997.py
{ "start": 0, "end": 138 }
class ____: def minOperations(self, nums: list[int], k: int) -> int: return functools.reduce(operator.xor, nums, k).bit_count()
Solution