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 | django__django | django/db/models/deletion.py | {
"start": 2354,
"end": 3406
} | class ____:
def __init__(self, operation, name, forced_collector=None):
self.operation = operation
self.forced_collector = forced_collector
self.__name__ = name
__call__ = DO_NOTHING
def on_delete_sql(self, schema_editor):
return schema_editor.connection.ops.fk_on_delete_sq... | DatabaseOnDelete |
python | bottlepy__bottle | bottle.py | {
"start": 142330,
"end": 143008
} | class ____(AsyncioServerAdapter):
""" Asynchronous HTTP client/server framework for asyncio
https://pypi.python.org/pypi/aiohttp/
https://pypi.org/project/aiohttp-wsgi/
"""
def get_event_loop(self):
import asyncio
return asyncio.new_event_loop()
def run(self, handler):
... | AiohttpServer |
python | python-poetry__poetry | tests/helpers.py | {
"start": 5341,
"end": 6285
} | class ____(Locker):
# class name begins 'Test': tell pytest that it does not contain testcases.
__test__ = False
def __init__(self, lock: Path, pyproject_data: dict[str, Any]) -> None:
super().__init__(lock, pyproject_data)
self._locked = False
self._write = False
def write(sel... | TestLocker |
python | huggingface__transformers | src/transformers/pipelines/image_to_image.py | {
"start": 1171,
"end": 5261
} | class ____(Pipeline):
"""
Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous
image input.
Example:
```python
>>> from PIL import Image
>>> import httpx
>>> import io
>>> from transformers import pipeline
>>> upsc... | ImageToImagePipeline |
python | ray-project__ray | python/ray/_private/runtime_env/plugin.py | {
"start": 3191,
"end": 3509
} | class ____:
def __init__(
self,
name: str,
class_instance: RuntimeEnvPlugin,
priority: int,
uri_cache: URICache,
):
self.name = name
self.class_instance = class_instance
self.priority = priority
self.uri_cache = uri_cache
| PluginSetupContext |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py | {
"start": 10056,
"end": 12276
} | class ____(Qwen3VLConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen3VLMoeModel`]. It is used to instantiate a
Qwen3-VL-MOE model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar ... | Qwen3VLMoeConfig |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 1848,
"end": 2105
} | class ____(RequestHandler):
@gen.coroutine
def get(self):
self.write("asdf")
self.flush()
# Wait a bit to ensure the chunks are sent and received separately.
yield gen.sleep(0.01)
self.write("qwer")
| ChunkHandler |
python | ansible__ansible | lib/ansible/plugins/filter/__init__.py | {
"start": 222,
"end": 528
} | class ____(AnsibleJinja2Plugin):
@property
def plugin_type(self) -> str:
return "filter"
def _no_options(self, *args, **kwargs) -> t.NoReturn:
raise NotImplementedError("Jinja2 filter plugins do not support option functions, they use direct arguments instead.")
| AnsibleJinja2Filter |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 149317,
"end": 155915
} | class ____:
def test_noniterable_hook_raises(self):
def running_hook():
pass
with pytest.raises(
TypeError,
match=re.escape(
"Expected iterable for 'on_running'; got function instead. Please"
" provide a list of hooks to 'on_runnin... | TestTaskHooksOnRunning |
python | ray-project__ray | release/train_tests/benchmark/config.py | {
"start": 497,
"end": 809
} | class ____(TaskConfig):
TASK_NAME: ClassVar[str] = "image_classification"
class ImageFormat(enum.Enum):
JPEG = "jpeg"
PARQUET = "parquet"
image_classification_local_dataset: bool = False
image_classification_data_format: ImageFormat = ImageFormat.PARQUET
| ImageClassificationConfig |
python | allegroai__clearml | examples/reporting/hyper_parameters.py | {
"start": 1103,
"end": 1158
} | class ____(Enum):
A = 'a'
B = 'b'
| StringEnumClass |
python | ray-project__ray | rllib/env/tests/test_multi_agent_env.py | {
"start": 949,
"end": 2930
} | class ____(MultiAgentEnv):
"""Env of N independent agents, each of which exits after 25 steps."""
metadata = {
"render.modes": ["rgb_array"],
}
render_mode = "rgb_array"
def __init__(self, num):
super().__init__()
self.envs = [MockEnv(25) for _ in range(num)]
self.a... | BasicMultiAgent |
python | jazzband__django-oauth-toolkit | oauth2_provider/exceptions.py | {
"start": 1560,
"end": 1676
} | class ____(OIDCError):
error = "logout_denied"
description = "Logout has been refused by the user."
| LogoutDenied |
python | huggingface__transformers | src/transformers/models/udop/modeling_udop.py | {
"start": 1995,
"end": 9480
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model. If `past_key_values` is used only
the last hidden-state of the sequences of shape `(batch_size, 1, ... | BaseModelOutputWithAttentionMask |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 138191,
"end": 139421
} | class ____(Set):
"""
A helper class, useful to compare two lists without reference to the order
of elements.
FrozenMultiset represents a hashable set that allows duplicate elements.
"""
def __init__(self, iterable):
self._collection = frozenset(Counter(iterable).items())
def __con... | _FrozenMultiset |
python | django__django | tests/cache/tests.py | {
"start": 10495,
"end": 46129
} | class ____:
# A common set of tests to apply to all cache backends
factory = RequestFactory()
# Some clients raise custom exceptions when .incr() or .decr() are called
# with a non-integer value.
incr_decr_type_error = TypeError
def tearDown(self):
cache.clear()
def test_simple(se... | BaseCacheTests |
python | doocs__leetcode | solution/2900-2999/2944.Minimum Number of Coins for Fruits/Solution.py | {
"start": 0,
"end": 294
} | class ____:
def minimumCoins(self, prices: List[int]) -> int:
@cache
def dfs(i: int) -> int:
if i * 2 >= len(prices):
return prices[i - 1]
return prices[i - 1] + min(dfs(j) for j in range(i + 1, i * 2 + 2))
return dfs(1)
| Solution |
python | getsentry__sentry | src/sentry/mail/forms/member_team.py | {
"start": 327,
"end": 3214
} | class ____(forms.Form, Generic[T]):
targetType = forms.ChoiceField()
targetIdentifier = forms.CharField(
required=False, help_text="Only required if 'Member' or 'Team' is selected"
)
teamValue: T
memberValue: T
targetTypeEnum: type[T]
def __init__(self, project: Project, *args: Any,... | MemberTeamForm |
python | django__django | django/core/files/uploadhandler.py | {
"start": 1245,
"end": 1397
} | class ____(UploadFileException):
"""
This exception is raised by an upload handler that wants to skip a given
file.
"""
pass
| SkipFile |
python | numba__numba | numba/testing/main.py | {
"start": 22728,
"end": 23362
} | class ____(runner.TextTestResult):
"""
A TestResult able to inject results from other results.
"""
def add_results(self, result):
"""
Add the results from the other *result* to this result.
"""
self.stream.write(result.stream.getvalue())
self.stream.flush()
... | ParallelTestResult |
python | openai__openai-python | src/openai/resources/realtime/realtime.py | {
"start": 7629,
"end": 8062
} | class ____:
def __init__(self, realtime: Realtime) -> None:
self._realtime = realtime
@cached_property
def client_secrets(self) -> ClientSecretsWithStreamingResponse:
return ClientSecretsWithStreamingResponse(self._realtime.client_secrets)
@cached_property
def calls(self) -> CallsW... | RealtimeWithStreamingResponse |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/transfers/facebook_ads_to_gcs.py | {
"start": 1566,
"end": 10362
} | class ____(BaseOperator):
"""
Fetch from Facebook Ads API.
This converts and saves the data as a temporary JSON file, and uploads the
JSON to Google Cloud Storage.
.. seealso::
For more information on the Facebook Ads API, take a look at the API docs:
https://developers.facebook.co... | FacebookAdsReportToGcsOperator |
python | django__django | django/core/signing.py | {
"start": 1920,
"end": 3292
} | class ____(BadSignature):
"""Signature timestamp is older than required max_age."""
pass
def b62_encode(s):
if s == 0:
return "0"
sign = "-" if s < 0 else ""
s = abs(s)
encoded = ""
while s > 0:
s, remainder = divmod(s, 62)
encoded = BASE62_ALPHABET[remainder] + en... | SignatureExpired |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 15861,
"end": 17002
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
pause_status: Optional[Literal["PAUSED", "UNPAUSED"]] = Field(
None,
description="Indicate whether this schedule is paused or not.",
examples=["... | CronSchedule |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/s3.py | {
"start": 3287,
"end": 5212
} | class ____(AwsBaseOperator[S3Hook]):
"""
This operator deletes an S3 bucket.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:S3DeleteBucketOperator`
:param bucket_name: This is bucket name you want to delete
:param force... | S3DeleteBucketOperator |
python | django__django | django/contrib/gis/db/models/functions.py | {
"start": 19502,
"end": 20265
} | class ____(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc):
def __init__(self, expression, *args, **extra):
nargs = len(args)
expressions = [expression]
if nargs in (1, 2):
expressions.extend(
[self._handle_param(arg, "", NUMERIC_TYPES) for arg in args]
... | SnapToGrid |
python | huggingface__transformers | src/transformers/models/detr/modeling_detr.py | {
"start": 76276,
"end": 77807
} | class ____(nn.Module):
"""This is a 2D attention module, which only returns the attention softmax (no multiplication by value)"""
def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True, std=None):
super().__init__()
self.num_heads = num_heads
self.hidden_dim = hidde... | DetrMHAttentionMap |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-localai/llama_index/llms/localai/base.py | {
"start": 1063,
"end": 4466
} | class ____(OpenAI):
"""
LocalAI LLM class.
Examples:
`pip install llama-index-llms-localai`
```python
from llama_index.llms.localai import LocalAI
llm = LocalAI(api_base="http://localhost:8080/v1")
response = llm.complete("Hello!")
print(str(response))
... | LocalAI |
python | PrefectHQ__prefect | src/prefect/concurrency/v1/services.py | {
"start": 715,
"end": 2958
} | class ____(
FutureQueueService[Unpack[tuple[UUID, Optional[float]]], httpx.Response]
):
def __init__(self, concurrency_limit_names: frozenset[str]) -> None:
super().__init__(concurrency_limit_names)
self._client: PrefectClient
self.concurrency_limit_names: list[str] = sorted(list(concurr... | ConcurrencySlotAcquisitionService |
python | PrefectHQ__prefect | tests/utilities/test_callables.py | {
"start": 19529,
"end": 21882
} | class ____:
def test_flow_with_args_docstring(self):
def f(x):
"""Function f.
Args:
x: required argument x
"""
schema = callables.parameter_schema(f)
assert schema.model_dump_for_openapi() == {
"title": "Parameters",
... | TestParseFlowDescriptionToSchema |
python | viewflow__viewflow | viewflow/utils.py | {
"start": 4558,
"end": 5308
} | class ____(Generic[T]):
"""
Descriptor class that creates a lazy singleton instance.
This descriptor can be used as a class attribute, and the first time the
attribute is accessed, it creates an instance of the class. Subsequent
accesses return the same instance, effectively making the class a sing... | LazySingletonDescriptor |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py | {
"start": 23445,
"end": 26800
} | class ____(nn.Module):
def __init__(self, config: Qwen3VLMoeVisionConfig) -> None:
super().__init__()
self.dim = config.hidden_size
self.num_heads = config.num_heads
self.head_dim = self.dim // self.num_heads
self.num_key_value_groups = 1 # needed for eager attention
... | Qwen3VLMoeVisionAttention |
python | jschneier__django-storages | tests/test_dropbox.py | {
"start": 1644,
"end": 5839
} | class ____(TestCase):
def setUp(self, *args):
self.storage = dropbox.DropboxStorage("foo")
def test_no_access_token(self, *args):
with self.assertRaises(ImproperlyConfigured):
dropbox.DropboxStorage(None)
def test_setting_access_token(self):
with override_settings(DROPB... | DropboxTest |
python | doocs__leetcode | solution/1500-1599/1559.Detect Cycles in 2D Grid/Solution2.py | {
"start": 0,
"end": 850
} | class ____:
def containsCycle(self, grid: List[List[str]]) -> bool:
def dfs(x: int, y: int, px: int, py: int) -> bool:
vis[x][y] = True
for dx, dy in pairwise(dirs):
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n:
if grid[nx... | Solution |
python | coleifer__peewee | examples/blog/app.py | {
"start": 1961,
"end": 4857
} | class ____(flask_db.Model):
title = CharField()
slug = CharField(unique=True)
content = TextField()
published = BooleanField(index=True)
timestamp = DateTimeField(default=datetime.datetime.now, index=True)
@property
def html_content(self):
"""
Generate HTML representation of... | Entry |
python | PyCQA__pylint | pylint/testutils/output_line.py | {
"start": 936,
"end": 3994
} | class ____(NamedTuple):
symbol: str
lineno: int
column: int
end_lineno: int | None
end_column: int | None
object: str
msg: str
confidence: str
@classmethod
def from_msg(cls, msg: Message, check_endline: bool = True) -> OutputLine:
"""Create an OutputLine from a Pylint Me... | OutputLine |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/host_config_parsers.py | {
"start": 4329,
"end": 6260
} | class ____(PairParser):
"""Composite argument parser for a POSIX remote host."""
def __init__(self, controller: bool) -> None:
self.controller = controller
def create_namespace(self) -> t.Any:
"""Create and return a namespace."""
return PosixRemoteConfig()
def get_left_parser(... | PosixRemoteParser |
python | huggingface__transformers | src/transformers/models/pix2struct/modeling_pix2struct.py | {
"start": 10188,
"end": 11881
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: Pix2StructConfig) -> None:
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = Pix2StructVisionAttention(config)
self.mlp = Pix2StructVisionMl... | Pix2StructVisionLayer |
python | spack__spack | lib/spack/spack/cmd/create.py | {
"start": 18808,
"end": 19168
} | class ____(PerlmakePackageTemplate):
"""Provides appropriate overrides for Perl extensions
that come with a Build.PL instead of a Makefile.PL"""
dependencies = """\
depends_on("perl-module-build", type="build")
# FIXME: Add additional dependencies if required:
# depends_on("perl-foo", type=("b... | PerlbuildPackageTemplate |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/_etcd_stub.py | {
"start": 1555,
"end": 1998
} | class ____:
def __init__(self, *args: Any, **kwargs: Any) -> None:
raise EtcdStubError
def read(self, key: str) -> None:
raise EtcdStubError
def write(
self, key: str, value: Any, ttl: int | None = None, **kwargs: Any
) -> None:
raise EtcdStubError
def test_and_set... | Client |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/transfers/test_mongo_to_s3.py | {
"start": 1786,
"end": 6484
} | class ____:
def setup_method(self):
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
self.dag = DAG("test_dag_id", schedule=None, default_args=args)
self.mock_operator = MongoToS3Operator(
task_id=TASK_ID,
mongo_conn_id=MONGO_CONN_ID,
aws_conn_id=... | TestMongoToS3Operator |
python | numpy__numpy | numpy/_core/tests/test_numerictypes.py | {
"start": 4775,
"end": 4913
} | class ____(CreateZeros):
"""Check the creation of heterogeneous arrays zero-valued (nested)"""
_descr = Ndescr
| TestCreateZerosNested |
python | huggingface__transformers | src/transformers/models/fnet/modeling_fnet.py | {
"start": 15748,
"end": 19902
} | class ____(FNetPreTrainedModel):
"""
The model can behave as an encoder, following the architecture described in [FNet: Mixing Tokens with Fourier
Transforms](https://huggingface.co/papers/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
"""
def __init__(self, conf... | FNetModel |
python | chroma-core__chroma | chromadb/auth/__init__.py | {
"start": 868,
"end": 1611
} | class ____:
"""
UserIdentity represents the identity of a user. In general, not all fields
will be populated, and the fields that are populated will depend on the
authentication provider.
The idea is that the AuthenticationProvider is responsible for populating
_all_ information known about the... | UserIdentity |
python | walkccc__LeetCode | solutions/74. Search a 2D Matrix/74.py | {
"start": 0,
"end": 425
} | class ____:
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
if not matrix:
return False
m = len(matrix)
n = len(matrix[0])
l = 0
r = m * n
while l < r:
mid = (l + r) // 2
i = mid // n
j = mid % n
if matrix[i][j] == target:
return Tr... | Solution |
python | davidhalter__jedi | jedi/plugins/stdlib.py | {
"start": 25216,
"end": 29997
} | class ____(ValueWrapper, FunctionMixin):
def __init__(self, func, original_function):
super().__init__(func)
self._original_function = original_function
@property
def name(self):
return self._original_function.name
def get_signature_functions(self):
return [self]
@arg... | Wrapped |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/tasks.py | {
"start": 1500,
"end": 26340
} | class ____(GoogleBaseHook):
"""
Hook for Google Cloud Tasks APIs.
Cloud Tasks allows developers to manage the execution of background work in their applications.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
:param gcp_conn_... | CloudTasksHook |
python | getsentry__sentry | src/sentry/integrations/api/serializers/rest_framework/data_forwarder.py | {
"start": 9796,
"end": 12410
} | class ____(Serializer):
data_forwarder_id = serializers.IntegerField()
project = ProjectField(scope="project:write", id_allowed=True)
overrides = serializers.JSONField(default=dict)
is_enabled = serializers.BooleanField(default=True)
def __init__(self, *args, **kwargs):
super().__init__(*ar... | DataForwarderProjectSerializer |
python | pyca__cryptography | src/cryptography/hazmat/primitives/asymmetric/ec.py | {
"start": 7507,
"end": 7720
} | class ____(EllipticCurve):
name = "sect409k1"
key_size = 407
group_order = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF # noqa: E501
| SECT409K1 |
python | dask__distributed | distributed/multi_lock.py | {
"start": 4844,
"end": 8044
} | class ____:
"""Distributed Centralized Lock
Parameters
----------
names
Names of the locks to acquire. Choosing the same name allows two
disconnected processes to coordinate a lock.
client
Client to use for communication with the scheduler. If not given, the
default... | MultiLock |
python | huggingface__transformers | tests/models/deformable_detr/test_modeling_deformable_detr.py | {
"start": 1448,
"end": 7118
} | class ____:
def __init__(
self,
parent,
batch_size=8,
is_training=True,
use_labels=True,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=8,
intermediate_size=4,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attent... | DeformableDetrModelTester |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_glue_catalog.py | {
"start": 1411,
"end": 7145
} | class ____:
def setup_method(self, method):
self.client = boto3.client("glue", region_name="us-east-1")
self.hook = GlueCatalogHook(region_name="us-east-1")
def test_get_conn_returns_a_boto3_connection(self):
hook = GlueCatalogHook(region_name="us-east-1")
assert hook.get_conn()... | TestGlueCatalogHook |
python | cython__cython | Demos/benchmarks/bm_richards_cclass.py | {
"start": 6916,
"end": 7866
} | class ____(Task):
def __init__(self,i,p,w,s,r):
Task.__init__(self,i,p,w,s,r)
def fn(self, pkt: Packet | None, r: WorkerTaskRec):
w = r
if pkt is None:
return self.waitTask()
if w.destination == I_HANDLERA:
dest = I_HANDLERB
else:
des... | WorkTask |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-google-sheets/destination_google_sheets/client.py | {
"start": 613,
"end": 2539
} | class ____:
logger = AirbyteLogger()
def __init__(self, config: Dict):
self.config = config
self.retries = 100 # max number of backoff retries
def authorize(self) -> pygsheets_client:
credentials = self.config.get("credentials", {})
auth_type = credentials.get("auth_type")... | GoogleSheetsClient |
python | django__django | tests/test_utils/tests.py | {
"start": 83536,
"end": 85509
} | class ____(SimpleTestCase):
databases = {"default"}
def test_allowed_database_queries(self):
Car.objects.first()
def test_allowed_database_chunked_cursor_queries(self):
next(Car.objects.iterator(), None)
def test_allowed_threaded_database_queries(self):
connections_dict = {}
... | AllowedDatabaseQueriesTests |
python | getsentry__sentry | src/sentry/api/serializers/release_details_types.py | {
"start": 66,
"end": 140
} | class ____(TypedDict, total=False):
description: str
| VersionInfoOptional |
python | getsentry__sentry | tests/sentry/relocation/api/endpoints/artifacts/test_details.py | {
"start": 1953,
"end": 6491
} | class ____(GetRelocationArtifactDetailsTest):
def setUp(self) -> None:
super().setUp()
dir = f"runs/{self.relocation.uuid}"
self.relocation_storage = get_relocation_storage()
# These files are unencrypted, so just save the file name as the content for testing
# purposes.
... | GetRelocationArtifactDetailsGoodTest |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 40512,
"end": 41283
} | class ____(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
action: Annotated[
Literal["update"], Field(description="The action to be performed on the entities.", title="Action")
]
entities: Annotated[
list[VariableBody], Field(description="A list of entities to be up... | BulkUpdateActionVariableBody |
python | huggingface__transformers | src/transformers/models/idefics3/modeling_idefics3.py | {
"start": 17799,
"end": 18370
} | class ____(PreTrainedModel):
config: Idefics3Config
base_model_prefix = "model"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["Idefics3VisionAttention", "Idefics3DecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_... | Idefics3PreTrainedModel |
python | ray-project__ray | python/ray/data/_internal/logical/rules/limit_pushdown.py | {
"start": 427,
"end": 8102
} | class ____(Rule):
"""Rule for pushing down the limit operator.
When a limit operator is present, we apply the limit on the
most upstream operator that supports it. We are conservative and only
push through operators that we know for certain do not modify row counts:
- Project operations (column sel... | LimitPushdownRule |
python | django__django | tests/migrations/test_multidb.py | {
"start": 368,
"end": 532
} | class ____:
"""
A router that doesn't allow migrating.
"""
def allow_migrate(self, db, app_label, **hints):
return False
| MigrateNothingRouter |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 59888,
"end": 63121
} | class ____:
def test_allclose(self, xp):
"""Test for false positive on allclose in normalize() in
filter_design.py"""
# Test to make sure the allclose call within signal.normalize does not
# choose false positives. Then check against a known output from MATLAB
# to make sure... | TestNormalize |
python | simonw__datasette | datasette/database.py | {
"start": 25460,
"end": 26192
} | class ____:
def __init__(self, rows, truncated, description):
self.rows = rows
self.truncated = truncated
self.description = description
@property
def columns(self):
return [d[0] for d in self.description]
def first(self):
if self.rows:
return self.r... | Results |
python | ipython__ipython | tests/test_ipunittest.py | {
"start": 2764,
"end": 3365
} | class ____(object):
"""For methods, the normal decorator doesn't work.
But rewriting the docstring with ip2py does, *but only if using nose
--with-doctest*. Do we want to have that as a dependency?
"""
@ipdocstring
def ipdt_method(self):
"""
In [20]: print(1)
1
... | Foo |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_state_dict.py | {
"start": 4280,
"end": 4838
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
torch.manual_seed(0)
self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU())
self.net2 = nn.Sequential(nn.Linear(16, 16), nn.ReLU())
self.net3 = self.net2
self.random_parameter = nn.Parameter(t... | TestDummyModel |
python | ray-project__ray | python/ray/tune/tests/_test_trial_runner_callbacks.py | {
"start": 649,
"end": 1765
} | class ____(Callback):
def __init__(self):
self.state = OrderedDict()
def setup(self, **info):
self.state["setup"] = info
def on_step_begin(self, **info):
self.state["step_begin"] = info
def on_step_end(self, **info):
self.state["step_end"] = info
def on_trial_star... | TestCallback |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 169538,
"end": 174341
} | class ____:
@pytest.mark.parametrize(
"args, kwargs",
[
((42, 42), {}),
([42, 42], {}),
((), {"x": 42, "y": 42}),
([42], {"y": 42}),
],
)
async def test_with_args_kwargs(self, args, kwargs):
@task
def multiply(x, y):
... | TestApplyAsync |
python | ray-project__ray | python/ray/data/aggregate.py | {
"start": 11229,
"end": 13328
} | class ____(AggregateFnV2[int, int]):
"""Defines count aggregation.
Example:
.. testcode::
import ray
from ray.data.aggregate import Count
ds = ray.data.range(100)
# Schema: {'id': int64}
ds = ds.add_column("group_key", lambda x: x % 3)
... | Count |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 28806,
"end": 30306
} | class ____(TokenStream):
def __init__(self):
self._input = None
self._stmap = {}
self._stack = []
def addInputStream(self,stream,key):
self._stmap[key] = stream
def getCurrentStream(self):
return self._input
def getStream(self,sname):
try:
... | TokenStreamSelector |
python | django__django | django/db/models/functions/text.py | {
"start": 9711,
"end": 9842
} | class ____(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform):
function = "SHA384"
lookup_name = "sha384"
| SHA384 |
python | rapidsai__cudf | python/cudf/cudf/core/buffer/spill_manager.py | {
"start": 1403,
"end": 6059
} | class ____:
"""Gather spill statistics
Levels of information gathered:
0 - disabled (no overhead).
1+ - duration and number of bytes spilled (very low overhead).
2+ - a traceback for each time a spillable buffer is exposed
permanently (potential high overhead).
The statistics... | SpillStatistics |
python | donnemartin__interactive-coding-challenges | stacks_queues/stack/stack.py | {
"start": 114,
"end": 559
} | class ____(object):
def __init__(self, top=None):
self.top = top
def push(self, data):
self.top = Node(data, self.top)
def pop(self):
if self.top is None:
return None
data = self.top.data
self.top = self.top.next
return data
def peek(self):... | Stack |
python | zarr-developers__zarr-python | tests/test_store/test_fsspec.py | {
"start": 4351,
"end": 15905
} | class ____(StoreTests[FsspecStore, cpu.Buffer]):
store_cls = FsspecStore
buffer_cls = cpu.Buffer
@pytest.fixture
def store_kwargs(self) -> dict[str, str | bool]:
try:
from fsspec import url_to_fs
except ImportError:
# before fsspec==2024.3.1
from fssp... | TestFsspecStoreS3 |
python | huggingface__transformers | src/transformers/models/t5/modeling_t5.py | {
"start": 1616,
"end": 3078
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
Construct a layernorm module in the T5 style. No bias and no subtraction of mean.
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forw... | T5LayerNorm |
python | weaviate__weaviate-python-client | weaviate/collections/batch/batch_wrapper.py | {
"start": 4943,
"end": 8224
} | class ____(Protocol):
def add_object(
self,
collection: str,
properties: Optional[WeaviateProperties] = None,
references: Optional[ReferenceInputs] = None,
uuid: Optional[UUID] = None,
vector: Optional[VECTORS] = None,
tenant: Optional[Union[str, Tenant]] = No... | BatchClientProtocol |
python | openai__openai-python | src/openai/types/image_generate_params.py | {
"start": 362,
"end": 4517
} | class ____(TypedDict, total=False):
prompt: Required[str]
"""A text description of the desired image(s).
The maximum length is 32000 characters for `gpt-image-1`, 1000 characters for
`dall-e-2` and 4000 characters for `dall-e-3`.
"""
background: Optional[Literal["transparent", "opaque", "auto"... | ImageGenerateParamsBase |
python | getsentry__sentry | tests/snuba/api/endpoints/test_discover_key_transactions.py | {
"start": 1103,
"end": 25334
} | class ____(TeamKeyTransactionTestBase):
def setUp(self) -> None:
super().setUp()
self.url = reverse("sentry-api-0-organization-key-transactions", args=[self.org.slug])
def test_key_transaction_without_feature(self) -> None:
project = self.create_project(name="qux", organization=self.org... | TeamKeyTransactionTest |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/unsupervised_learning/autoencoder.py | {
"start": 507,
"end": 4017
} | class ____():
"""An Autoencoder with deep fully-connected neural nets.
Training Data: MNIST Handwritten Digits (28x28 images)
"""
def __init__(self):
self.img_rows = 28
self.img_cols = 28
self.img_dim = self.img_rows * self.img_cols
self.latent_dim = 128 # The dimension ... | Autoencoder |
python | doocs__leetcode | solution/3100-3199/3123.Find Edges in Shortest Paths/Solution.py | {
"start": 0,
"end": 901
} | class ____:
def findAnswer(self, n: int, edges: List[List[int]]) -> List[bool]:
g = defaultdict(list)
for i, (a, b, w) in enumerate(edges):
g[a].append((b, w, i))
g[b].append((a, w, i))
dist = [inf] * n
dist[0] = 0
q = [(0, 0)]
while q:
... | Solution |
python | huggingface__transformers | tests/models/deformable_detr/test_image_processing_deformable_detr.py | {
"start": 4801,
"end": 35510
} | class ____(AnnotationFormatTestMixin, ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = DeformableDetrImageProcessor if is_vision_available() else None
fast_image_processing_class = DeformableDetrImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super(... | DeformableDetrImageProcessingTest |
python | pyca__cryptography | tests/hazmat/primitives/test_ciphers.py | {
"start": 1319,
"end": 1876
} | class ____:
@pytest.mark.parametrize(
("key", "keysize"),
[(b"0" * 32, 128), (b"0" * 48, 192), (b"0" * 64, 256)],
)
def test_key_size(self, key, keysize):
cipher = AES(binascii.unhexlify(key))
assert cipher.key_size == keysize
def test_invalid_key_size(self):
wit... | TestAES |
python | wandb__wandb | wandb/vendor/pygments/lexers/jvm.py | {
"start": 48582,
"end": 51009
} | class ____(RegexLexer):
"""
For `Pig Latin <https://pig.apache.org/>`_ source code.
.. versionadded:: 2.0
"""
name = 'Pig'
aliases = ['pig']
filenames = ['*.pig']
mimetypes = ['text/x-pig']
flags = re.MULTILINE | re.IGNORECASE
tokens = {
'root': [
(r'\s+',... | PigLexer |
python | ethereum__web3.py | web3/types.py | {
"start": 3442,
"end": 4507
} | class ____(TypedDict):
chainId: int
address: Address | ChecksumAddress | str
nonce: Nonce
y_parity: int
r: int
s: int
# syntax b/c "from" keyword not allowed w/ class construction
TxParams = TypedDict(
"TxParams",
{
"accessList": AccessList,
"authorizationList": Sequenc... | SetCodeAuthorizationParams |
python | sympy__sympy | sympy/plotting/series.py | {
"start": 4153,
"end": 38452
} | class ____:
"""Base class for the data objects containing stuff to be plotted.
Notes
=====
The backend should check if it supports the data series that is given.
(e.g. TextBackend supports only LineOver1DRangeSeries).
It is the backend responsibility to know how to use the class of
data se... | BaseSeries |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 101086,
"end": 101308
} | class ____(Structure):
_fields_ = [("bIsPresent", c_uint, 1),
("percentage", c_uint),
("incThreshold", c_uint),
("decThreshold", c_uint)]
| c_nvmlGpuDynamicPstatesUtilization_t |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-llama-dataset-metadata/llama_index/packs/llama_dataset_metadata/base.py | {
"start": 1543,
"end": 1746
} | class ____(BaseModel):
"""Base Metadata class."""
class Config:
alias_generator = to_camel
allow_population_by_field_name = True
arbitrary_types_allowed = True
| BaseMetadata |
python | urllib3__urllib3 | src/urllib3/exceptions.py | {
"start": 7423,
"end": 8053
} | class ____(HTTPError, httplib_IncompleteRead):
"""
Response length doesn't match expected Content-Length
Subclass of :class:`http.client.IncompleteRead` to allow int value
for ``partial`` to avoid creating large objects on streamed reads.
"""
partial: int # type: ignore[assignment]
expect... | IncompleteRead |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/graph.py | {
"start": 1410,
"end": 2271
} | class ____(NamedTuple):
"""Edge in a graph."""
source: str
"""The source node id."""
target: str
"""The target node id."""
data: Stringifiable | None = None
"""Optional data associated with the edge. """
conditional: bool = False
"""Whether the edge is conditional."""
def copy(... | Edge |
python | fluentpython__example-code-2e | 17-it-generator/aritprog_v0.py | {
"start": 129,
"end": 563
} | class ____:
def __init__(self, begin, step, end=None):
self.begin = begin
self.step = step
self.end = end # None -> "infinite" series
def __iter__(self):
result_type = type(self.begin + self.step)
result = result_type(self.begin)
forever = self.end is None
... | ArithmeticProgression |
python | huggingface__transformers | tests/models/detr/test_image_processing_detr.py | {
"start": 1267,
"end": 4853
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_rescale=True,
rescale_factor=1 / 255,
do_normalize=True,
image_mean=[0.5, 0.5, 0.... | DetrImageProcessingTester |
python | mlflow__mlflow | mlflow/genai/judges/tools/get_span.py | {
"start": 583,
"end": 5387
} | class ____(JudgeTool):
"""
Tool for retrieving a specific span by its ID.
Returns the complete span data including inputs, outputs, attributes, and events.
"""
@property
def name(self) -> str:
return ToolNames.GET_SPAN
def get_definition(self) -> ToolDefinition:
return Too... | GetSpanTool |
python | getsentry__sentry | tests/sentry/search/events/builder/test_metrics.py | {
"start": 5671,
"end": 61876
} | class ____(MetricBuilderBaseTest):
@pytest.mark.querybuilder
def test_default_conditions(self) -> None:
query = MetricsQueryBuilder(
self.params, query="", dataset=Dataset.PerformanceMetrics, selected_columns=[]
)
self.assertCountEqual(query.where, self.default_conditions)
... | MetricQueryBuilderTest |
python | ansible__ansible | lib/ansible/_internal/_ssh/_ssh_agent.py | {
"start": 11018,
"end": 11364
} | class ____(PrivateKeyMsg):
type: KeyAlgo
ecdsa_curve_name: unicode_string
Q: binary_string
d: mpint
comments: unicode_string = dataclasses.field(default=unicode_string(''), compare=False)
constraints: constraints = dataclasses.field(default=constraints(b''))
@dataclasses.dataclass(order=True, ... | EcdsaPrivateKeyMsg |
python | sympy__sympy | sympy/physics/quantum/pauli.py | {
"start": 2963,
"end": 4797
} | class ____(SigmaOpBase):
"""Pauli sigma y operator
Parameters
==========
name : str
An optional string that labels the operator. Pauli operators with
different names commute.
Examples
========
>>> from sympy.physics.quantum import represent
>>> from sympy.physics.quan... | SigmaY |
python | PrefectHQ__prefect | tests/cli/test_work_queues.py | {
"start": 13532,
"end": 16042
} | class ____:
def test_inspect(self, work_queue):
invoke_and_assert(
command=f"work-queue inspect {work_queue.name}",
expected_output_contains=[
f"id='{work_queue.id}'",
f"name={work_queue.name!r}",
],
expected_code=0,
)
... | TestInspectWorkQueue |
python | networkx__networkx | networkx/algorithms/shortest_paths/tests/test_generic.py | {
"start": 19930,
"end": 20609
} | class ____:
@classmethod
def setup_class(cls):
global np
import pytest
np = pytest.importorskip("numpy")
def test_specified_methods_numpy(self):
G = nx.Graph()
nx.add_cycle(G, range(7), weight=2)
ans = nx.average_shortest_path_length(
G, weight="... | TestAverageShortestPathLengthNumpy |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0108_migrate_language_code.py | {
"start": 610,
"end": 831
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0107_alter_project_language"),
]
operations = [
migrations.RunPython(forwards_func),
]
| Migration |
python | PrefectHQ__prefect | tests/runner/test_runner.py | {
"start": 2885,
"end": 2992
} | class ____:
@flow
@staticmethod
def dummy_flow_staticmethod():
pass
| ClassNameStaticmethod |
python | python-markdown__markdown | tests/test_apis.py | {
"start": 4888,
"end": 6170
} | class ____(unittest.TestCase):
""" Tests of the State class for `BlockParser`. """
def setUp(self):
self.state = markdown.blockparser.State()
def testBlankState(self):
""" Test State when empty. """
self.assertEqual(self.state, [])
def testSetSate(self):
""" Test State... | TestBlockParserState |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/mixins.py | {
"start": 424,
"end": 7217
} | class ____:
"""
This mixin decouples Django OAuth Toolkit from OAuthLib.
Users can configure the Server, Validator and OAuthlibCore
classes used by this mixin by setting the following class
variables:
* server_class
* validator_class
* oauthlib_backend_class
If these class v... | OAuthLibMixin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.