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 | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 485943,
"end": 486135
} | class ____(VegaLiteSchema):
"""Interpolate schema wrapper."""
_schema = {"$ref": "#/definitions/Interpolate"}
def __init__(self, *args):
super().__init__(*args)
| Interpolate |
python | networkx__networkx | networkx/readwrite/tests/test_graph6.py | {
"start": 1548,
"end": 1880
} | class ____:
def test_read_many_graph6(self):
"""Test for reading many graphs from a file into a list."""
data = b"DF{\nD`{\nDqK\nD~{\n"
fh = BytesIO(data)
glist = nx.read_graph6(fh)
assert len(glist) == 4
for G in glist:
assert sorted(G) == list(range(5))
... | TestReadGraph6 |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py | {
"start": 4166,
"end": 28571
} | class ____:
def setup_method(self):
clear_db_runs()
clear_db_serialized_dags()
clear_db_dags()
def teardown_method(self):
clear_db_runs()
clear_db_serialized_dags()
clear_db_dags()
@pytest.mark.parametrize(
("max_tries", "should_retry"),
[
... | TestTIRunState |
python | Textualize__textual | src/textual/containers.py | {
"start": 6499,
"end": 6672
} | class ____(Widget):
"""A container with grid layout."""
DEFAULT_CSS = """
Grid {
width: 1fr;
height: 1fr;
layout: grid;
}
"""
| Grid |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/class_as_data_structure.py | {
"start": 658,
"end": 960
} | class ____: # B903
"""This class has a docstring."""
# this next method is an init
def __init__(self,e:dict):
self.e = e
# <--- begin flake8-bugbear tests below
# (we have modified them to have type annotations,
# since our implementation only triggers in that
# stricter setting.)
| D |
python | boto__boto3 | tests/unit/docs/test_method.py | {
"start": 820,
"end": 12137
} | class ____(BaseDocsTest):
def setUp(self):
super().setUp()
self.event_emitter = HierarchicalEmitter()
self.service_model = self.client.meta.service_model
self.operation_model = self.service_model.operation_model(
'SampleOperation'
)
self.service_resource_m... | TestDocumentModelDrivenResourceMethod |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_version_querysets.py | {
"start": 3000,
"end": 4506
} | class ____(TestVersionQuerySetBase):
def test_public(self):
query = Version.objects.public()
versions = {
self.version_latest,
self.version,
self.another_version,
self.another_version_latest,
self.shared_version,
self.shared_ver... | VersionQuerySetTests |
python | python-openxml__python-docx | src/docx/image/constants.py | {
"start": 2486,
"end": 3466
} | class ____:
"""Tag codes for TIFF Image File Directory (IFD) entries."""
IMAGE_WIDTH = 0x0100
IMAGE_LENGTH = 0x0101
X_RESOLUTION = 0x011A
Y_RESOLUTION = 0x011B
RESOLUTION_UNIT = 0x0128
tag_names = {
0x00FE: "NewSubfileType",
0x0100: "ImageWidth",
0x0101: "ImageLengt... | TIFF_TAG |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/keyword_table/retrievers.py | {
"start": 6207,
"end": 6697
} | class ____(BaseKeywordTableRetriever):
"""
Keyword Table Index Simple Retriever.
Extracts keywords using simple regex-based keyword extractor.
Set when `retriever_mode="simple"`.
See BaseGPTKeywordTableQuery for arguments.
"""
def _get_keywords(self, query_str: str) -> List[str]:
... | KeywordTableSimpleRetriever |
python | google__jax | benchmarks/api_benchmark.py | {
"start": 1970,
"end": 25068
} | class ____(enum.IntEnum):
A = 123
B = 456
@google_benchmark.register
def eager_unary_dispatch(state):
a = jax.device_put(1)
x = lax.neg(a)
while state:
x = lax.neg(a)
x.block_until_ready()
@google_benchmark.register
def eager_unary(state):
a = jax.device_put(1)
lax.neg(a).block_until_ready()
wh... | AnEnum |
python | coleifer__peewee | tests/schema.py | {
"start": 31659,
"end": 31759
} | class ____(TestModel):
key = CharField()
value = IntegerField()
extra = IntegerField()
| TMKV |
python | plotly__plotly.py | plotly/graph_objs/mesh3d/colorbar/_tickfont.py | {
"start": 233,
"end": 9913
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "mesh3d.colorbar"
_path_str = "mesh3d.colorbar.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
... | Tickfont |
python | sqlalchemy__sqlalchemy | test/base/test_events.py | {
"start": 35063,
"end": 48985
} | class ____(TearDownLocalEventsFixture, fixtures.TestBase):
def _fixture(self):
class TargetEvents(event.Events):
def event_one(self, x, y):
pass
def event_two(self, x):
pass
def event_three(self, x):
pass
class Ta... | RemovalTest |
python | jupyterlab__jupyterlab | jupyterlab/utils.py | {
"start": 303,
"end": 2345
} | class ____: # noqa
"""Decorator to mark deprecated functions with warning.
Adapted from `scikit-image/skimage/_shared/utils.py`.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecate... | deprecated |
python | openai__openai-python | src/openai/resources/realtime/realtime.py | {
"start": 32694,
"end": 33456
} | class ____(BaseRealtimeConnectionResource):
def clear(self, *, event_id: str | Omit = omit) -> None:
"""**WebRTC Only:** Emit to cut off the current audio response.
This will trigger the server to
stop generating audio and emit a `output_audio_buffer.cleared` event. This
event shoul... | RealtimeOutputAudioBufferResource |
python | Lightning-AI__lightning | src/lightning/pytorch/core/datamodule.py | {
"start": 1359,
"end": 14554
} | class ____(DataHooks, HyperparametersMixin):
"""A DataModule standardizes the training, val, test splits, data preparation and transforms. The main advantage is
consistent data splits, data preparation and transforms across models.
Example::
import lightning as L
import torch.utils.data as... | LightningDataModule |
python | Netflix__metaflow | test/core/metaflow_test/formatter.py | {
"start": 63,
"end": 7886
} | class ____(object):
def __init__(self, graphspec, test):
self.graphspec = graphspec
self.test = test
self.should_resume = getattr(test, "RESUME", False)
self.resume_step = getattr(test, "RESUME_STEP", None)
self.should_fail = getattr(test, "SHOULD_FAIL", False)
self.f... | FlowFormatter |
python | pydata__xarray | xarray/tests/test_indexes.py | {
"start": 3279,
"end": 11845
} | class ____:
def test_constructor(self) -> None:
pd_idx = pd.Index([1, 2, 3])
index = PandasIndex(pd_idx, "x")
assert index.index.equals(pd_idx)
# makes a shallow copy
assert index.index is not pd_idx
assert index.dim == "x"
# test no name set for pd.Index
... | TestPandasIndex |
python | walkccc__LeetCode | solutions/2643. Row With Maximum Ones/2643.py | {
"start": 0,
"end": 241
} | class ____:
def rowAndMaximumOnes(self, mat: list[list[int]]) -> list[int]:
ans = [0, 0]
for i, row in enumerate(mat):
ones = row.count(1)
if ones > ans[1]:
ans[0] = i
ans[1] = ones
return ans
| Solution |
python | python-poetry__poetry | src/poetry/utils/isolated_build.py | {
"start": 2577,
"end": 3104
} | class ____(IsolatedBuildBaseError):
def __init__(self, requirements: Collection[str], output: str, error: str) -> None:
message = "\n\n".join(
(
f"Failed to install {', '.join(requirements)}.",
f"Output:\n{output}",
f"Error:\n{error}",
... | IsolatedBuildInstallError |
python | davidhalter__jedi | jedi/inference/names.py | {
"start": 8432,
"end": 9454
} | class ____:
def infer(self):
return ValueSet([self._value])
def py__doc__(self):
doc = self._value.py__doc__()
if not doc and self._value.is_stub():
from jedi.inference.gradual.conversion import convert_names
names = convert_names([self], prefer_stub_to_compiled=... | ValueNameMixin |
python | pytorch__pytorch | torch/__init__.py | {
"start": 73007,
"end": 73233
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.quint8
| QUInt8Storage |
python | huggingface__transformers | src/transformers/models/nougat/image_processing_nougat.py | {
"start": 2090,
"end": 24618
} | class ____(BaseImageProcessor):
r"""
Constructs a Nougat image processor.
Args:
do_crop_margin (`bool`, *optional*, defaults to `True`):
Whether to crop the image margins.
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, widt... | NougatImageProcessor |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_unshard_params.py | {
"start": 27040,
"end": 29426
} | class ____(TestUnshardParamsBase):
@property
def world_size(self) -> int:
return 2
@skip_if_lt_x_gpu(2)
def test_unshard_params_from_forward_raises(self):
class MyModule(nn.Module):
def __init__(self) -> None:
super().__init__()
self.a = nn.Pa... | TestUnshardParamsErrors |
python | keon__algorithms | tests/test_array.py | {
"start": 12937,
"end": 13144
} | class ____(unittest.TestCase):
def test_top_1(self):
self.assertListEqual(top_1([1, 1, 2, 2, 3]), [1, 2])
self.assertListEqual(top_1([1, 2, 3, 324, 234, 23, 23, 1, 23, 23]), [23])
| TestTop1 |
python | pallets__click | src/click/types.py | {
"start": 19122,
"end": 19264
} | class ____(_NumberParamTypeBase):
name = "integer"
_number_class = int
def __repr__(self) -> str:
return "INT"
| IntParamType |
python | crytic__slither | slither/slithir/operations/operation.py | {
"start": 398,
"end": 781
} | class ____(abc.ABC):
@property
@abc.abstractmethod
def read(self):
"""
Return the list of variables READ
"""
pass # pylint: disable=unnecessary-pass
@property
@abc.abstractmethod
def used(self):
"""
Return the list of variables used
"""
... | AbstractOperation |
python | pytorch__pytorch | test/test_datapipe.py | {
"start": 78322,
"end": 90311
} | class ____(TestCase):
def _serialization_test_helper(self, datapipe, use_dill):
if use_dill:
serialized_dp = dill.dumps(datapipe)
deserialized_dp = dill.loads(serialized_dp)
else:
serialized_dp = pickle.dumps(datapipe)
deserialized_dp = pickle.loads(se... | TestFunctionalMapDataPipe |
python | imageio__imageio | imageio/plugins/_bsdf.py | {
"start": 3490,
"end": 17263
} | class ____(object):
"""Instances of this class represent a BSDF encoder/decoder.
It acts as a placeholder for a set of extensions and encoding/decoding
options. Use this to predefine extensions and options for high
performance encoding/decoding. For general use, see the functions
`save()`, `encode(... | BsdfSerializer |
python | simonw__datasette | datasette/views/special.py | {
"start": 6415,
"end": 12329
} | class ____(BaseView):
name = "allowed"
has_json_alternate = False
async def get(self, request):
await self.ds.refresh_schemas()
# Check if user has permissions-debug (to show sensitive fields)
has_debug_permission = await self.ds.allowed(
action="permissions-debug", act... | AllowedResourcesView |
python | Netflix__metaflow | test/unit/inheritance/flows/mutator_with_derived_config_base.py | {
"start": 2164,
"end": 2453
} | class ____(FlowSpec):
"""
Base class with mutator that will use config from derived class.
The mutator looks for 'runtime_config' which will be defined in BaseC (derived class).
"""
base_param = Parameter("base_param", help="Base parameter", default="base_value")
| BaseA |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_gcs.py | {
"start": 13158,
"end": 14236
} | class ____:
def test_execute(self):
interp_dt = datetime(2015, 2, 1, 15, 16, 17, 345, tzinfo=timezone.utc)
assert GCSTimeSpanFileTransformOperator.interpolate_prefix(None, interp_dt) is None
assert (
GCSTimeSpanFileTransformOperator.interpolate_prefix("prefix_without_date", int... | TestGCSTimeSpanFileTransformOperatorDateInterpolation |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_opaque_device_configuration.py | {
"start": 383,
"end": 5952
} | 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... | V1beta1OpaqueDeviceConfiguration |
python | google__pytype | pytype/errors/errors.py | {
"start": 14480,
"end": 19577
} | class ____:
"""A stream of errors."""
def __init__(self, src: str):
self._errors = []
# An error filter (initially None)
self._filter = None
self._src = src
def __len__(self):
return len(self._errors)
def __iter__(self):
return iter(self._errors)
def __getitem__(self, index):
r... | ErrorLog |
python | ray-project__ray | python/ray/serve/_private/proxy_response_generator.py | {
"start": 2637,
"end": 6491
} | class ____(_ProxyResponseGeneratorBase):
"""Wraps a unary DeploymentResponse or streaming DeploymentResponseGenerator.
In the case of a unary DeploymentResponse, __anext__ will only ever return one
result.
"""
def __init__(
self,
response: Union[DeploymentResponse, DeploymentRespon... | ProxyResponseGenerator |
python | walkccc__LeetCode | solutions/1021. Remove Outermost Parentheses/1021.py | {
"start": 0,
"end": 314
} | class ____:
def removeOuterParentheses(self, s: str) -> str:
ans = []
opened = 0
for c in s:
if c == '(':
opened += 1
if opened > 1:
ans.append(c)
else: # c == ')'
opened -= 1
if opened > 0:
ans.append(c)
return ''.join(ans)
| Solution |
python | tensorflow__tensorflow | tensorflow/python/distribute/collective_all_reduce_strategy.py | {
"start": 11538,
"end": 12856
} | class ____(distribute_lib.StrategyV1):
__doc__ = CollectiveAllReduceStrategy.__doc__
# The starting number for collective keys. This should only be set in tests.
_collective_key_base = 0
def __init__(
self,
communication=collective_util.CommunicationImplementation.AUTO,
cluster_resolver=Non... | CollectiveAllReduceStrategyV1 |
python | getsentry__sentry | src/sentry/db/models/utils.py | {
"start": 3709,
"end": 4524
} | class ____(Generic[FieldSetType, FieldGetType]):
"""
A descriptor that invokes `to_python` when attributes are set.
This provides backwards compatibility for fields that used to use
SubfieldBase which will be removed in Django1.10
"""
def __init__(self, field: Field[FieldSetType, FieldGetType])... | Creator |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_connections.py | {
"start": 1022,
"end": 1993
} | class ____:
@skip_if_force_lowest_dependencies_marker
def test_hook_meta_data(self, test_client):
with assert_queries_count(0):
response = test_client.get("/connections/hook_meta")
response_data = response.json()
assert any(hook_data["connection_type"] == "generic" for hook_d... | TestHookMetaData |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/instance/methods/storage_methods.py | {
"start": 721,
"end": 4288
} | class ____:
"""Mixin class providing storage capabilities for DagsterInstance.
This class contains all non-public storage-related methods that were previously
in StorageDomain. Public methods remain directly on DagsterInstance.
"""
# These attributes are provided by DagsterInstance
_event_stor... | StorageMethods |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 792425,
"end": 792977
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "created_at", "label", "labelable")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime... | LabeledEvent |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared_tests/test_record.py | {
"start": 8654,
"end": 11256
} | class ____(IHaveNew):
name: str
secrets: list[str]
def __new__(cls, name: str, **kwargs):
return super().__new__(
cls,
name=name,
secrets=kwargs.get("secrets", []),
)
def test_pickle():
p = Person(name="Lyra", age=2)
assert p == pickle.loads(pic... | Agent |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/ecr/resources.py | {
"start": 269,
"end": 1130
} | class ____:
def __init__(
self,
region_name: Optional[str] = None,
endpoint_url: Optional[str] = None,
use_ssl: bool = True,
aws_access_key_id: Optional[str] = None,
aws_secret_access_key: Optional[str] = None,
aws_session_token: Optional[str] = None,
... | ECRPublicClient |
python | mlflow__mlflow | mlflow/entities/lifecycle_stage.py | {
"start": 95,
"end": 1202
} | class ____:
ACTIVE = "active"
DELETED = "deleted"
_VALID_STAGES = {ACTIVE, DELETED}
@classmethod
def view_type_to_stages(cls, view_type=ViewType.ALL):
stages = []
if view_type in (ViewType.ACTIVE_ONLY, ViewType.ALL):
stages.append(cls.ACTIVE)
if view_type in (Vie... | LifecycleStage |
python | ethereum__web3.py | web3/contract/async_contract.py | {
"start": 7194,
"end": 11965
} | class ____(BaseContractFunction):
# mypy types
w3: "AsyncWeb3[Any]"
async def call(
self,
transaction: TxParams | None = None,
block_identifier: BlockIdentifier = None,
state_override: StateOverride | None = None,
ccip_read_enabled: bool | None = None,
) -> Any:
... | AsyncContractFunction |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/schemas.py | {
"start": 53498,
"end": 53788
} | class ____(Protocol):
handle: JointFnHandle
def __call__(
self, primals: list[FxValue], tangents: list[FxValue]
) -> tuple[
tuple[list[FxValue], list[Optional[Tensor]]],
tuple[list[AOTOutput], list[Optional[AOTOutput]]],
]: ...
@dataclass
| JointTraceFn |
python | imageio__imageio | imageio/plugins/grab.py | {
"start": 1935,
"end": 2776
} | class ____(BaseGrabFormat):
"""The ClipboardGrabFormat provided a means to grab image data from
the clipboard, using the uri "<clipboard>"
This functionality is provided via Pillow. Note that "<clipboard>" is
only supported on Windows.
Parameters for reading
----------------------
No param... | ClipboardGrabFormat |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/splice_a/package.py | {
"start": 217,
"end": 974
} | class ____(Package):
"""Simple package with one optional dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/splice-a-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789efghij")
variant("foo", default=False, description="nope")
variant("bar", default=False, ... | SpliceA |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/call_graph.py | {
"start": 394,
"end": 517
} | class ____:
def __init__(self) -> None:
pass
def method(self) -> str:
return _test_source()
| IsSource |
python | huggingface__transformers | src/transformers/models/t5/tokenization_t5.py | {
"start": 999,
"end": 6505
} | class ____(TokenizersBackend):
"""
Construct a T5 tokenizer (backed by HuggingFace's *tokenizers* library). Based on
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
This tokenizer inherits from [`TokenizersBackend`] which contains most of the ma... | T5Tokenizer |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/inputs.py | {
"start": 3127,
"end": 3337
} | class ____(graphene.InputObjectType):
stepKey = graphene.NonNull(graphene.String)
outputName = graphene.NonNull(graphene.String)
class Meta:
name = "StepOutputHandle"
| GrapheneStepOutputHandle |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/base.py | {
"start": 102462,
"end": 130204
} | class ____(RunnableSerializable[Input, Output]):
"""Sequence of `Runnable` objects, where the output of one is the input of the next.
**`RunnableSequence`** is the most important composition operator in LangChain
as it is used in virtually every chain.
A `RunnableSequence` can be instantiated directly... | RunnableSequence |
python | pytorch__pytorch | torch/_inductor/runtime/caching/context.py | {
"start": 7335,
"end": 10315
} | class ____(TypedDict):
"""Schema for specifying which context forms to include in cache isolation.
Attributes:
runtime_context: Either True (include all runtime context), False (exclude all),
or a SelectedRuntimeContext dict specifying which forms to include.
compile_con... | IsolationSchema |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 4997,
"end": 5168
} | class ____(BaseModel):
model_config = {
"extra": "allow",
"json_schema_extra": {"$ref": create_definition_ref("io.k8s.api.core.v1.EnvVar")},
}
| EnvVar |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 24496,
"end": 25226
} | class ____(ChainedSource):
index: Any
def guard_source(self) -> GuardSource:
return self.base.guard_source()
def reconstruct(self, codegen: "PyCodegen") -> None:
codegen.add_push_null(
lambda: codegen.load_import_from(utils.__name__, "dict_keys_getitem")
)
codeg... | ConstDictKeySource |
python | realpython__materials | python-maze-solver/source_code_final/src/maze_solver/view/primitives.py | {
"start": 1129,
"end": 1300
} | class ____(tuple[Line, ...]):
def draw(self, **attributes) -> str:
return "".join(line.draw(**attributes) for line in self)
@dataclass(frozen=True)
| DisjointLines |
python | Netflix__metaflow | metaflow/plugins/datatools/s3/s3tail.py | {
"start": 184,
"end": 2597
} | class ____(object):
def __init__(self, s3url):
url = urlparse(s3url)
self.s3, self.ClientError = get_s3_client()
self._bucket = url.netloc
self._key = url.path.lstrip("/")
self._pos = 0
self._tail = b""
def reset_client(self, hard_reset=False):
# This met... | S3Tail |
python | numba__numba | numba/tests/test_array_return.py | {
"start": 269,
"end": 856
} | class ____(MemoryLeakMixin, unittest.TestCase):
def test_array_return(self):
a = np.arange(10)
i = 2
at, it = typeof(a), typeof(i)
cfunc = njit((at, it))(array_return)
self.assertIs(a, cfunc(a, i))
def test_array_return_start_with_loop(self):
"""
A bug br... | TestArrayReturn |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 26163,
"end": 34342
} | class ____(CompoundRequest):
"""
Adds a single event
"""
_service = "events"
_action = "add"
_version = "2.13"
_item_prop_name = "event"
_schema = {
"anyOf": [
{"$ref": "#/definitions/metrics_scalar_event"},
{"$ref": "#/definitions/metrics_vector_event"}... | AddRequest |
python | google__jax | tests/xla_metadata_test.py | {
"start": 997,
"end": 14568
} | class ____(jtu.JaxTestCase):
def _assert_metadata_appears_once_per_op(
self,
hlo_text: str,
expected_tagged_ops: list[str],
metadata: dict[str, str],
):
attribute_strings = [f'{k}="{v}"' for k, v in metadata.items()]
op_with_metadata_count = {op: 0 for op in expected_tagged_ops}
... | XlaMetadataTest |
python | django__django | tests/basic/tests.py | {
"start": 27936,
"end": 30361
} | class ____(SimpleTestCase):
QUERYSET_PROXY_METHODS = [
"none",
"count",
"dates",
"datetimes",
"distinct",
"extra",
"get",
"get_or_create",
"update_or_create",
"create",
"bulk_create",
"bulk_update",
"filter",
... | ManagerTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/row.py | {
"start": 9902,
"end": 12091
} | class ____(BaseRow, typing.Mapping["_KeyType", Any]):
"""A ``Mapping`` that maps column names and objects to :class:`.Row`
values.
The :class:`.RowMapping` is available from a :class:`.Row` via the
:attr:`.Row._mapping` attribute, as well as from the iterable interface
provided by the :class:`.Mapp... | RowMapping |
python | gevent__gevent | src/greentest/3.14/test_urllib2_localnet.py | {
"start": 6763,
"end": 8149
} | class ____(http.server.BaseHTTPRequestHandler):
"""Handler for performing basic authentication."""
# Server side values
USER = 'testUser'
PASSWD = 'testPass'
REALM = 'Test'
USER_PASSWD = "%s:%s" % (USER, PASSWD)
ENCODED_AUTH = base64.b64encode(USER_PASSWD.encode('ascii')).decode('ascii')
... | BasicAuthHandler |
python | spyder-ide__spyder | spyder/app/utils.py | {
"start": 1417,
"end": 13698
} | class ____:
"""
This is used to inject a 'spy' object in the internal console
namespace to inspect Spyder internals.
Attributes:
app Reference to main QApplication object
window Reference to spyder.MainWindow widget
"""
def __init__(self, app, window):
self.app ... | Spy |
python | astropy__astropy | astropy/units/tests/test_quantity_non_ufuncs.py | {
"start": 73948,
"end": 75179
} | class ____(InvariantUnitTestSetup):
tested_module = np.fft
# These are all trivial, just preserve the unit.
def setup_method(self):
# Use real input; gets turned into complex as needed.
self.q = np.arange(128.0).reshape(8, -1) * u.s
def test_fft(self):
self.check(np.fft.fft)
... | TestFFT |
python | getsentry__sentry | tests/sentry/notifications/notification_action/test_issue_alert_registry_handlers.py | {
"start": 21228,
"end": 21599
} | class ____(TestTicketingIssueAlertHandlerBase):
def setUp(self) -> None:
super().setUp()
self.handler = JiraServerIssueAlertHandler()
def test_build_rule_action_blob(self) -> None:
for expected in JIRA_SERVER_ACTION_DATA_BLOBS:
self._test_build_rule_action_blob(expected, Act... | TestJiraServerIssueAlertHandler |
python | sanic-org__sanic | sanic/exceptions.py | {
"start": 11422,
"end": 13297
} | class ____(NotFound):
"""404 Not Found
A specific form of :class:`.NotFound` that is specifically when looking
for a file on the file system at a known path.
Args:
message (Optional[Union[str, bytes]], optional): The message to be sent to the client. If `None`
then the HTTP status ... | FileNotFound |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran/managed/reconciliation.py | {
"start": 12663,
"end": 14630
} | class ____(ManagedElementReconciler):
def __init__(
self,
fivetran: ResourceDefinition,
connectors: Iterable[FivetranConnector],
delete_unmentioned_resources: bool = False,
):
"""Reconciles Python-specified Fivetran resources with an Fivetran instance.
Args:
... | FivetranManagedElementReconciler |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_exceptions.py | {
"start": 2499,
"end": 2673
} | class ____(Exception):
def __str__(self):
raise Exception("str() is broken")
# XXX This is not really enough, each *operation* should be tested!
| BrokenStrException |
python | pytorch__pytorch | torch/_numpy/_dtypes.py | {
"start": 2315,
"end": 2414
} | class ____(floating):
name = "float32"
typecode = "f"
torch_dtype = torch.float32
| float32 |
python | ray-project__ray | python/ray/autoscaler/v2/schema.py | {
"start": 4246,
"end": 4310
} | class ____(ResourceDemand):
pass
@dataclass
| RayTaskActorDemand |
python | pdm-project__pdm | src/pdm/models/serializers.py | {
"start": 188,
"end": 850
} | class ____(json.JSONEncoder):
"""Expand standard json encoder to support dumps bytes object."""
bytes_ident = "PDM_BYTES_OBJECT"
def default(self, o: Any) -> Any:
if isinstance(o, bytes):
base64_string = base64.b64encode(o).decode()
return {"type": self.bytes_ident, "val": ... | Encoder |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol3.py | {
"start": 301,
"end": 392
} | class ____(Protocol):
@property
def batch_shape(self) -> int:
return 0
| Class1 |
python | coleifer__peewee | playhouse/reflection.py | {
"start": 13754,
"end": 15780
} | class ____(Metadata):
column_map = {
'bigint': BigIntegerField,
'blob': BlobField,
'bool': BooleanField,
'boolean': BooleanField,
'char': CharField,
'date': DateField,
'datetime': DateTimeField,
'decimal': DecimalField,
'float': FloatField,
... | SqliteMetadata |
python | doocs__leetcode | solution/1600-1699/1690.Stone Game VII/Solution.py | {
"start": 0,
"end": 429
} | class ____:
def stoneGameVII(self, stones: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i > j:
return 0
a = s[j + 1] - s[i + 1] - dfs(i + 1, j)
b = s[j] - s[i] - dfs(i, j - 1)
return max(a, b)
s = list(accumulat... | Solution |
python | pytest-dev__pytest | src/_pytest/pytester.py | {
"start": 3195,
"end": 6015
} | class ____:
def get_open_files(self) -> list[tuple[str, str]]:
if sys.version_info >= (3, 11):
# New in Python 3.11, ignores utf-8 mode
encoding = locale.getencoding()
else:
encoding = locale.getpreferredencoding(False)
out = subprocess.run(
("... | LsofFdLeakChecker |
python | scrapy__scrapy | tests/test_loader.py | {
"start": 6314,
"end": 6430
} | class ____(ItemLoader):
title_in = MapCompose(str.upper)
title_out = TakeFirst()
| BaseNoInputReprocessingLoader |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 145615,
"end": 146717
} | class ____(nn.Module):
def __init__(self, ratio=2, kernel_size=None):
super().__init__()
self.ratio = ratio
self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
self.stride = ratio
self.pad = self.kernel_size // ratio - 1
self.pad_left = ... | UpSample1d |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/font.py | {
"start": 581,
"end": 1211
} | class ____(Parameter):
"""
Creates and controls a QFont value. Be careful when selecting options from the font dropdown. since not all
fonts are available on all systems
"""
itemClass = FontParameterItem
def _interpretValue(self, v):
if isinstance(v, str):
newVal = QtGui.QFo... | FontParameter |
python | walkccc__LeetCode | solutions/2786. Visit Array Positions to Maximize Score/2786.py | {
"start": 0,
"end": 607
} | class ____:
def maxScore(self, nums: list[int], x: int) -> int:
# Note that we always need to take nums[0], so the initial definition might
# not hold true.
# dp0 := the maximum score so far with `nums` ending in an even number
dp0 = nums[0] - (x if nums[0] % 2 == 1 else 0)
# dp0 := the maximum s... | Solution |
python | huggingface__transformers | tests/models/tvp/test_image_processing_tvp.py | {
"start": 1156,
"end": 4409
} | class ____:
def __init__(
self,
parent,
do_resize: bool = True,
size: dict[str, int] = {"longest_edge": 40},
do_center_crop: bool = False,
crop_size: dict[str, int] | None = None,
do_rescale: bool = False,
rescale_factor: int | float = 1 / 255,
... | TvpImageProcessingTester |
python | getsentry__sentry | src/sentry/testutils/silo.py | {
"start": 5899,
"end": 26576
} | class ____:
"""Encapsulate the set of changes made to a test class by a SiloModeTestDecorator."""
silo_modes: frozenset[SiloMode]
regions: tuple[Region, ...]
def __post_init__(self) -> None:
if not self.silo_modes:
raise ValueError("silo_modes must not be empty")
@contextmanag... | _SiloModeTestModification |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 61223,
"end": 62233
} | class ____(Response):
"""
Response of queues.get_num_entries endpoint.
:param num: Number of entries
:type num: int
"""
_service = "queues"
_action = "get_num_entries"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {"num": {"description": "Number of ... | GetNumEntriesResponse |
python | pennersr__django-allauth | tests/apps/headless/spec/internal/test_openapikit.py | {
"start": 342,
"end": 2232
} | class ____:
optional_integer: Optional[int]
integer: int
optional_string: Optional[str]
string: str
number: float = field(
metadata={
"description": "Some float",
"example": "3.14",
}
)
nested: Optional[NestedDataClass]
def test_spec_for_dataclass():... | ExampleDataclass |
python | langchain-ai__langchain | libs/core/langchain_core/documents/compressor.py | {
"start": 383,
"end": 2017
} | class ____(BaseModel, ABC):
"""Base class for document compressors.
This abstraction is primarily used for post-processing of retrieved documents.
`Document` objects matching a given query are first retrieved.
Then the list of documents can be further processed.
For example, one could re-rank th... | BaseDocumentCompressor |
python | qdrant__qdrant-client | qdrant_client/embed/type_inspector.py | {
"start": 325,
"end": 5426
} | class ____:
"""Inspector which tries to find at least one occurrence of an object requiring inference
Inspector is stateful and accumulates parsed model schemes in its parser.
Attributes:
parser: ModelSchemaParser instance to inspect model json schemas
"""
def __init__(self, parser: Optio... | Inspector |
python | google__jax | jax/experimental/array_serialization/serialization_test.py | {
"start": 28984,
"end": 29248
} | class ____:
def __init__(self, a):
self.a = a
# we're testing custom type registration which modifies the global registry
# so need to ensure we're not running multiple custom types tests in parallel
custom_types_threading_lock = threading.Lock()
| CustomStatic |
python | getsentry__sentry | tests/sentry/feedback/endpoints/test_organization_feedback_summary.py | {
"start": 2052,
"end": 10473
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-user-feedback-summary"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.org = self.create_organization(owner=self.user)
self.team = self.create_team(
organization=self.org, name... | OrganizationFeedbackSummaryTest |
python | astropy__astropy | astropy/constants/constant.py | {
"start": 3359,
"end": 8842
} | class ____(Quantity, metaclass=ConstantMeta):
"""A physical or astronomical constant.
These objects are quantities that are meant to represent physical
constants.
Parameters
----------
abbrev : str
A typical ASCII text abbreviation of the constant, generally
the same as the Pyt... | Constant |
python | getsentry__sentry | src/sentry/ingest/transaction_clusterer/rules.py | {
"start": 876,
"end": 2941
} | class ____:
"""Store rules in both project options and Redis.
Why Redis?
We want to update the rule lifetimes when a transaction has been sanitized
with that rule. That load is very high for the project options to handle,
but Redis is capable of doing so.
Then, why project options?
Redis ... | RedisRuleStore |
python | python__mypy | mypyc/codegen/literals.py | {
"start": 600,
"end": 10602
} | class ____:
"""Collection of literal values used in a compilation group and related helpers."""
def __init__(self) -> None:
# Each dict maps value to literal index (0, 1, ...)
self.str_literals: dict[str, int] = {}
self.bytes_literals: dict[bytes, int] = {}
self.int_literals: di... | Literals |
python | google__pytype | pytype/tests/test_closures.py | {
"start": 7542,
"end": 9970
} | class ____(test_base.BaseTest):
"""Tests for closures in Python 3."""
def test_if_split_delete_deref(self):
ty = self.Infer("""
def f(a: int):
x = "hello"
def g():
nonlocal x
x = 42
if a:
g()
else:
return x
""")
self.assertTy... | ClosuresTestPy3 |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataflow.py | {
"start": 27056,
"end": 30572
} | class ____:
@pytest.fixture
def run_operator(self):
"""
Create a DataflowDeletePipelineOperator instance with test data
"""
return DataflowDeletePipelineOperator(
task_id=TASK_ID,
pipeline_name=TEST_PIPELINE_NAME,
project_id=TEST_PROJECT,
... | TestDataflowDeletePipelineOperator |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 11860,
"end": 12162
} | class ____(Rule):
"""Rewrite integrand to another form that is easier to handle."""
rewritten: Expr
substep: Rule
def eval(self) -> Expr:
return self.substep.eval()
def contains_dont_know(self) -> bool:
return self.substep.contains_dont_know()
@dataclass
| RewriteRule |
python | getsentry__sentry | src/sentry/replays/usecases/query/fields.py | {
"start": 3642,
"end": 5818
} | class ____:
def __init__(self, query: type[SumOfTagAggregate] | type[TagScalar]) -> None:
self.parse = parse_str
self.query = query
def apply(self, search_filter: SearchFilter) -> Condition:
"""Apply a search operation against any named expression.
A named expression can be a c... | TagField |
python | mlflow__mlflow | mlflow/gateway/providers/mistral.py | {
"start": 295,
"end": 4928
} | class ____(ProviderAdapter):
@classmethod
def model_to_completions(cls, resp, config):
# Response example (https://docs.mistral.ai/api/#operation/createChatCompletion)
# ```
# {
# "id": "string",
# "object": "string",
# "created": "integer",
# "mod... | MistralAdapter |
python | django__django | docs/_ext/djangodocs.py | {
"start": 7633,
"end": 10049
} | class ____(nodes.literal_block):
"""
Custom node to override the visit/depart event handlers at registration
time. Wrap a literal_block object and defer to it.
"""
tagname = "ConsoleNode"
def __init__(self, litblk_obj):
self.wrapped = litblk_obj
def __getattr__(self, attr):
... | ConsoleNode |
python | pydata__xarray | xarray/coding/cftime_offsets.py | {
"start": 20718,
"end": 20917
} | class ____(Tick):
_freq = "min"
def as_timedelta(self) -> timedelta:
return timedelta(minutes=self.n)
def __apply__(self, other):
return other + self.as_timedelta()
| Minute |
python | tensorflow__tensorflow | third_party/xla/build_tools/lint/generate_compile_commands_test.py | {
"start": 814,
"end": 1770
} | class ____(absltest.TestCase):
def test_command_from_args_list(self):
arguments = [
"/usr/bin/gcc",
"-DTEST_DEFINE",
"-fstack-protector",
"-c",
"xla/compiler.cc",
"-o",
"bazel-out/k8-opt/bin/xla/_objs/compiler/compiler.pic.o",
]
command = CompileCo... | CompileCommandsTest |
python | sympy__sympy | sympy/functions/special/bessel.py | {
"start": 34488,
"end": 36589
} | class ____(SphericalBesselBase):
@assume_integer_order
def _eval_rewrite_as_besselj(self, nu, z, **kwargs):
# jn +- I*yn
# jn as beeselj: sqrt(pi/(2*z)) * besselj(nu + S.Half, z)
# yn as besselj: (-1)**(nu+1) * sqrt(pi/(2*z)) * besselj(-nu - S.Half, z)
hks = self._hankel_kind_si... | SphericalHankelBase |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.