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 | optuna__optuna | optuna/storages/_rdb/alembic/versions/v3.0.0.a.py | {
"start": 1910,
"end": 2243
} | class ____(BaseModel):
__tablename__ = "trials"
trial_id = Column(Integer, primary_key=True)
number = Column(Integer)
study_id = Column(Integer, ForeignKey("studies.study_id"))
state = Column(Enum(TrialState), nullable=False)
datetime_start = Column(DateTime)
datetime_complete = Column(DateT... | TrialModel |
python | ray-project__ray | python/ray/dashboard/modules/job/tests/test_job_manager.py | {
"start": 20069,
"end": 23252
} | class ____:
async def test_submit_basic_echo(self, job_manager):
job_id = await job_manager.submit_job(entrypoint="echo hello")
await async_wait_for_condition(
check_job_succeeded, job_manager=job_manager, job_id=job_id
)
assert "hello\n" in job_manager.get_job_logs(job_... | TestShellScriptExecution |
python | spyder-ide__spyder | spyder/api/widgets/toolbars.py | {
"start": 3166,
"end": 10132
} | class ____(QToolBar):
"""
Spyder Toolbar.
This class provides toolbars with some predefined functionality.
"""
sig_is_rendered = Signal()
"""
This signal is emitted to let other objects know that the toolbar is now
rendered.
"""
def __init__(self, parent, title):
super... | SpyderToolbar |
python | great-expectations__great_expectations | great_expectations/metrics/column/mean.py | {
"start": 179,
"end": 292
} | class ____(ColumnMetric[ColumnMeanResult]):
"""Mean of values in a column"""
name = "column.mean"
| ColumnMean |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_organization_workflow_index.py | {
"start": 37529,
"end": 45985
} | class ____(OrganizationWorkflowAPITestCase):
method = "DELETE"
def assert_unaffected_workflows(self, workflows: Sequence[Workflow]) -> None:
for workflow in workflows:
workflow.refresh_from_db()
assert Workflow.objects.get(id=workflow.id).status != ObjectStatus.PENDING_DELETION
... | OrganizationWorkflowDeleteTest |
python | aio-libs__aiohttp | tests/test_web_exceptions.py | {
"start": 5184,
"end": 6846
} | class ____:
def test_ctor_all(self) -> None:
resp = web.HTTPOk(
headers={"X-Custom": "value"},
reason="Done",
text="text",
content_type="custom",
)
assert resp.text == "text"
compare: Mapping[str, str] = {"X-Custom": "value", "Content-T... | TestHTTPOk |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI059.py | {
"start": 1147,
"end": 1216
} | class ____(Generic[T], Generic[K, V]): ... # PYI059
# Negative cases
| C |
python | scrapy__scrapy | tests/test_utils_asyncio.py | {
"start": 730,
"end": 3379
} | class ____:
"""Test for scrapy.utils.asyncio.parallel_asyncio(), based on tests.test_utils_defer.TestParallelAsync."""
CONCURRENT_ITEMS = 50
@staticmethod
async def callable(o: int, results: list[int]) -> None:
if random.random() < 0.4:
# simulate async processing
await... | TestParallelAsyncio |
python | redis__redis-py | redis/commands/search/index_definition.py | {
"start": 131,
"end": 2489
} | class ____:
"""IndexDefinition is used to define a index definition for automatic
indexing on Hash or Json update."""
def __init__(
self,
prefix=[],
filter=None,
language_field=None,
language=None,
score_field=None,
score=1.0,
payload_field=No... | IndexDefinition |
python | tensorflow__tensorflow | tensorflow/python/saved_model/save_test.py | {
"start": 53271,
"end": 57796
} | class ____(test.TestCase):
def setUp(self):
super(AssetTests, self).setUp()
self._vocab_path = os.path.join(self.get_temp_dir(), "vocab.txt")
with open(self._vocab_path, "w") as f:
f.write("alpha\nbeta\ngamma\n")
def test_asset_path_returned(self):
root = autotrackable.AutoTrackable()
ro... | AssetTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor19.py | {
"start": 161,
"end": 252
} | class ____:
pass
a1 = A()
# This should generate an error
a2 = A(1)
a3 = A(*[], **{})
| A |
python | apache__airflow | airflow-core/src/airflow/ti_deps/deps/task_not_running_dep.py | {
"start": 1019,
"end": 1799
} | class ____(BaseTIDep):
"""Ensures that the task instance's state is not running."""
NAME = "Task Instance Not Running"
IGNORABLE = False
def __eq__(self, other: object) -> bool:
"""Check if two task instance dependencies are of the same type."""
return type(self) is type(other)
de... | TaskNotRunningDep |
python | huggingface__transformers | src/transformers/integrations/mxfp4.py | {
"start": 4824,
"end": 9492
} | class ____(ConversionOps):
def __init__(self, hf_quantizer):
self.hf_quantizer = hf_quantizer
def convert(
self,
input_dict: dict[str, torch.Tensor],
model: Optional[torch.nn.Module] = None,
full_layer_name: str | None = None,
missing_keys: Optional[list[str]] = ... | Mxfp4Deserialize |
python | allegroai__clearml | clearml/utilities/deferred.py | {
"start": 123,
"end": 1177
} | class ____(object):
@attr.s
class _DeferredAction(object):
method = attr.ib()
args = attr.ib()
kwargs = attr.ib()
def __init__(self, instance: Any) -> None:
self._instance = instance
self._pool = []
self._lock = threading.Lock()
def add(self, callable_: ... | DeferredExecutionPool |
python | google__jax | tests/state_test.py | {
"start": 2072,
"end": 24661
} | class ____(jtu.JaxTestCase):
def test_get_abstract_aval_must_take_in_refs(self):
ref_aval = core.ShapedArray((), jnp.float32)
def f(x_ref):
return [ref_get(x_ref, ())]
with self.assertRaises(ValueError):
pe.trace_to_jaxpr_dynamic(wrap_init(f, 1), [ref_aval])
@parameterized.named_parameters... | StatePrimitivesTest |
python | walkccc__LeetCode | solutions/1611. Minimum One Bit Operations to Make Integers Zero/1611.py | {
"start": 0,
"end": 1123
} | class ____:
def minimumOneBitOperations(self, n: int) -> int:
# Observation: e.g. n = 2^2
# 100 (2^2 needs 2^3 - 1 ops)
# op1 -> 101
# op2 -> 111
# op1 -> 110
# op2 -> 010 (2^1 needs 2^2 - 1 ops)
# op1 -> 011
# op2 -> 001 (2^0 needs 2^1 - 1 ops)
# op1 -> 000
#
# So 2... | Solution |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 28190,
"end": 28806
} | class ____(object):
def __init__(self,inst):
if isinstance(inst,TokenStream):
self.inst = inst
return
raise TypeError("TokenStreamIterator requires TokenStream object")
def next(self):
assert self.inst
item = self.inst.nextToken()
if not item or i... | TokenStreamIterator |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 605898,
"end": 606222
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("app", "context")
app = sgqlc.types.Field("App", graphql_name="app")
context = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="context")
| RequiredStatusCheckDescription |
python | huggingface__transformers | src/transformers/models/informer/modeling_informer.py | {
"start": 28468,
"end": 31781
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: InformerConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.dropout = config.dropout
self.activation_fn = ACT2FN[config.activation_function... | InformerEncoderLayer |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/shortcuts/progress_bar/base.py | {
"start": 8743,
"end": 9954
} | class ____(UIControl):
"""
User control for the progress bar.
"""
def __init__(
self,
progress_bar: ProgressBar,
formatter: Formatter,
cancel_callback: Callable[[], None] | None,
) -> None:
self.progress_bar = progress_bar
self.formatter = formatter
... | _ProgressControl |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/redshift_cluster.py | {
"start": 20777,
"end": 23231
} | class ____(AwsBaseOperator[RedshiftHook]):
"""
Deletes the specified manual snapshot.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:RedshiftDeleteClusterSnapshotOperator`
:param snapshot_identifier: A unique identifier for... | RedshiftDeleteClusterSnapshotOperator |
python | pydata__xarray | xarray/tests/test_coarsen.py | {
"start": 8607,
"end": 11877
} | class ____:
@pytest.mark.parametrize("dask", [True, False])
def test_coarsen_construct(self, dask: bool) -> None:
ds = Dataset(
{
"vart": ("time", np.arange(48), {"a": "b"}),
"varx": ("x", np.arange(10), {"a": "b"}),
"vartx": (("x", "time"), np... | TestCoarsenConstruct |
python | ray-project__ray | rllib/offline/d4rl_reader.py | {
"start": 387,
"end": 1596
} | class ____(InputReader):
"""Reader object that loads the dataset from the D4RL dataset."""
@PublicAPI
def __init__(self, inputs: str, ioctx: IOContext = None):
"""Initializes a D4RLReader instance.
Args:
inputs: String corresponding to the D4RL environment name.
ioc... | D4RLReader |
python | scipy__scipy | scipy/stats/tests/test_survival.py | {
"start": 18764,
"end": 21958
} | class ____:
@pytest.mark.parametrize(
"x, y, statistic, pvalue",
# Results validate with R
# library(survival)
# options(digits=16)
#
# futime_1 <- c(8, 12, 26, 14, 21, 27, 8, 32, 20, 40)
# fustat_1 <- c(1, 1, 1, 1, 1, 1, 0, 0, 0, 0)
# rx_1 <- c(0, 0,... | TestLogRank |
python | ipython__ipython | examples/utils/cwd_prompt.py | {
"start": 139,
"end": 584
} | class ____(Prompts):
def in_prompt_tokens(self):
return [(Token, os.getcwd()), (Token.Prompt, ">>>")]
def load_ipython_extension(shell):
new_prompts = MyPrompt(shell)
new_prompts.old_prompts = shell.prompts
shell.prompts = new_prompts
def unload_ipython_extension(shell):
if not hasattr(s... | MyPrompt |
python | readthedocs__readthedocs.org | readthedocs/gold/forms.py | {
"start": 227,
"end": 469
} | class ____(forms.ModelForm):
"""Gold subscription form."""
class Meta:
model = GoldUser
fields = ["level"]
level = forms.ChoiceField(
required=True,
choices=LEVEL_CHOICES,
)
| GoldSubscriptionForm |
python | redis__redis-py | tests/test_asyncio/test_scripting.py | {
"start": 521,
"end": 5444
} | class ____:
@pytest_asyncio.fixture
async def r(self, create_redis):
redis = await create_redis()
yield redis
await redis.script_flush()
@pytest.mark.asyncio()
async def test_eval(self, r):
await r.flushdb()
await r.set("a", 2)
# 2 * 3 == 6
assert... | TestScripting |
python | fastapi__sqlmodel | docs_src/tutorial/delete/tutorial002.py | {
"start": 100,
"end": 2907
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_u... | Hero |
python | run-llama__llama_index | llama-index-core/llama_index/core/readers/file/base.py | {
"start": 832,
"end": 5011
} | class ____(ABC):
@abstractmethod
def read_file_content(self, input_file: Path, **kwargs: Any) -> bytes:
"""
Read the bytes content of a file.
Args:
input_file (Path): Path to the file.
Returns:
bytes: File content.
"""
async def aread_file_... | FileSystemReaderMixin |
python | numpy__numpy | numpy/lib/_user_array_impl.py | {
"start": 791,
"end": 8026
} | class ____:
"""
container(data, dtype=None, copy=True)
Standard container-class for easy multiple-inheritance.
Methods
-------
copy
byteswap
astype
"""
def __init_subclass__(cls) -> None:
# Deprecated in NumPy 2.4, 2025-11-24
import warnings
warnings.w... | container |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 48125,
"end": 48368
} | class ____(Response):
"""
Response of events.download_task_log endpoint.
"""
_service = "events"
_action = "download_task_log"
_version = "2.9"
_schema = {"definitions": {}, "type": "string"}
| DownloadTaskLogResponse |
python | PrefectHQ__prefect | src/integrations/prefect-aws/prefect_aws/settings.py | {
"start": 665,
"end": 1086
} | class ____(PrefectBaseSettings):
model_config = build_settings_config(("integrations", "aws", "ecs", "observer"))
enabled: bool = Field(
default=True,
description="Whether to enable the ECS observer.",
)
sqs: EcsObserverSqsSettings = Field(
description="Settings for controlling... | EcsObserverSettings |
python | getsentry__sentry | tests/sentry/api/serializers/test_base.py | {
"start": 511,
"end": 893
} | class ____(Serializer):
def get_attrs(self, item_list, user, **kwargs):
return {item: {"child_data": Foo()} for item in item_list}
def serialize(self, obj, attrs, user, **kwargs):
return {
"parent": "something",
"child": serialize(attrs["child_data"], serializer=FailingC... | ParentSerializer |
python | simplejson__simplejson | simplejson/ordered_dict.py | {
"start": 154,
"end": 2945
} | class ____(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clear()
self.update(*args, **kwds)
def clear(sel... | OrderedDict |
python | walkccc__LeetCode | solutions/242. Valid Anagram/242.py | {
"start": 0,
"end": 239
} | class ____:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = collections.Counter(s)
count.subtract(collections.Counter(t))
return all(freq == 0 for freq in count.values())
| Solution |
python | numba__numba | numba/cpython/unicode_support.py | {
"start": 13957,
"end": 22215
} | class ____(IntEnum):
LOWER = 0x01
UPPER = 0x02
ALPHA = 0x01 | 0x02
DIGIT = 0x04
ALNUM = 0x01 | 0x02 | 0x04
SPACE = 0x08
XDIGIT = 0x10
# From the definition in CPython's Python/pyctype.c
# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Python/pyctype.c#L5 ... | _PY_CTF |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/links/test_comprehend.py | {
"start": 1236,
"end": 2191
} | class ____(BaseAwsLinksTestCase):
link_class = ComprehendPiiEntitiesDetectionLink
def test_extra_link(self, mock_supervisor_comms):
test_job_id = "123-345-678"
if AIRFLOW_V_3_0_PLUS and mock_supervisor_comms:
mock_supervisor_comms.send.return_value = XComResult(
key=... | TestComprehendPiiEntitiesDetectionLink |
python | streamlit__streamlit | lib/streamlit/vendor/pympler/asizeof.py | {
"start": 49007,
"end": 50203
} | class ____(object):
"""Internal largest object class."""
deep = 0 # recursion depth
id = 0 # id(obj)
key = None # Typedef
objref = None # obj or Weakref.ref(obj)
pid = 0 # id(parent obj)
size = 0 # size in bytes
weak = False # objref is Weakref.ref
def __init__(self, key, ob... | _Rank |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_modelresource/test_data_deletion.py | {
"start": 203,
"end": 6300
} | class ____(TestCase):
def setUp(self):
self.resource = BookResource()
self.book = Book.objects.create(name="Some book")
self.dataset = tablib.Dataset(headers=["id", "name", "author_email", "price"])
row = [self.book.pk, "Some book", "test@example.com", "10.25"]
self.dataset.a... | DataDeletionDryRunTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/bigquery.py | {
"start": 3321,
"end": 61920
} | class ____(GoogleBaseHook, DbApiHook):
"""
Interact with BigQuery.
This hook uses the Google Cloud connection.
:param gcp_conn_id: The Airflow connection used for GCP credentials.
:param use_legacy_sql: This specifies whether to use legacy SQL dialect.
:param location: The location of the BigQ... | BigQueryHook |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 665851,
"end": 667401
} | class ____(sgqlc.types.Type):
"""A file in a gist."""
__schema__ = github_schema
__field_names__ = ("encoded_name", "encoding", "extension", "is_image", "is_truncated", "language", "name", "size", "text")
encoded_name = sgqlc.types.Field(String, graphql_name="encodedName")
"""The file name encoded ... | GistFile |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeParams5.py | {
"start": 203,
"end": 305
} | class ____[R: int | str]:
...
# This should generate an error because 'dummy' is not declared.
| ClassB |
python | automl__auto-sklearn | autosklearn/pipeline/components/classification/qda.py | {
"start": 455,
"end": 2847
} | class ____(AutoSklearnClassificationAlgorithm):
def __init__(self, reg_param, random_state=None):
self.reg_param = float(reg_param)
self.estimator = None
def fit(self, X, Y):
import sklearn.discriminant_analysis
estimator = sklearn.discriminant_analysis.QuadraticDiscriminantAna... | QDA |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 138478,
"end": 141957
} | class ____(Response):
"""
Response of events.get_task_plots endpoint.
:param plots: Plots list
:type plots: Sequence[dict]
:param returned: Number of results returned
:type returned: int
:param total: Total number of results available for this query. In case there
are more than 1000... | GetTaskPlotsResponse |
python | numba__llvmlite | llvmlite/tests/test_ir.py | {
"start": 31012,
"end": 32499
} | class ____(TestBase):
def test_attributes(self):
func = self.function()
block = ir.Block(parent=func, name='start')
self.assertIs(block.parent, func)
self.assertFalse(block.is_terminated)
def test_descr(self):
block = self.block(name='my_block')
self.assertEqual... | TestBlock |
python | django__django | django/db/models/expressions.py | {
"start": 24062,
"end": 27280
} | class ____(SQLiteNumericMixin, Expression):
def __init__(self, lhs, connector, rhs, output_field=None):
super().__init__(output_field=output_field)
self.connector = connector
self.lhs = lhs
self.rhs = rhs
def __repr__(self):
return "<{}: {}>".format(self.__class__.__name... | CombinedExpression |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/retrieval_qa/base.py | {
"start": 9858,
"end": 11859
} | class ____(BaseRetrievalQA):
"""Chain for question-answering against a vector database."""
vectorstore: VectorStore = Field(exclude=True, alias="vectorstore")
"""Vector Database to connect to."""
k: int = 4
"""Number of documents to query for."""
search_type: str = "similarity"
"""Search ty... | VectorDBQA |
python | FactoryBoy__factory_boy | factory/declarations.py | {
"start": 20801,
"end": 21841
} | class ____(BaseDeclaration):
"""Declarations to be called once the model object has been generated."""
FACTORY_BUILDER_PHASE = enums.BuilderPhase.POST_INSTANTIATION
def evaluate_post(self, instance, step, overrides):
context = self.unroll_context(instance, step, overrides)
postgen_context ... | PostGenerationDeclaration |
python | aio-libs__aiohttp | aiohttp/http_parser.py | {
"start": 1883,
"end": 2140
} | class ____(NamedTuple):
method: str
path: str
version: HttpVersion
headers: CIMultiDictProxy[str]
raw_headers: RawHeaders
should_close: bool
compression: str | None
upgrade: bool
chunked: bool
url: URL
| RawRequestMessage |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/exceptions.py | {
"start": 161,
"end": 2532
} | class ____:
class BaseBulkException(AirbyteTracedException):
"""Base BULK Job Exception"""
failure_type: FailureType = FailureType.config_error
def __init__(self, message: str, **kwargs) -> None:
super().__init__(internal_message=message, failure_type=self.failure_type, **kwarg... | ShopifyBulkExceptions |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/activation.py | {
"start": 212,
"end": 1360
} | class ____(torch.nn.ReLU):
r"""Applies the element-wise function:
:math:`\text{ReLU6}(x) = \min(\max(x_0, x), q(6))`, where :math:`x_0` is the
zero_point, and :math:`q(6)` is the quantized representation of number 6.
Args:
inplace: can optionally do the operation in-place. Default: ``False``
... | ReLU6 |
python | spyder-ide__spyder | spyder/plugins/editor/utils/editor.py | {
"start": 5843,
"end": 23193
} | class ____(object):
"""
Text helper helps you manipulate the content of CodeEditor and extends the
Qt text api for an easier usage.
FIXME: Some of this methods are already implemented in CodeEditor, move
and unify redundant methods.
"""
@property
def _editor(self):
try:
... | TextHelper |
python | openai__openai-python | src/openai/resources/evals/runs/runs.py | {
"start": 22911,
"end": 23611
} | class ____:
def __init__(self, runs: Runs) -> None:
self._runs = runs
self.create = to_streamed_response_wrapper(
runs.create,
)
self.retrieve = to_streamed_response_wrapper(
runs.retrieve,
)
self.list = to_streamed_response_wrapper(
... | RunsWithStreamingResponse |
python | sanic-org__sanic | sanic/asgi.py | {
"start": 4069,
"end": 9402
} | class ____:
sanic_app: Sanic
request: Request
transport: MockTransport
lifespan: Lifespan
ws: Optional[WebSocketConnection]
stage: Stage
response: Optional[BaseHTTPResponse]
@classmethod
async def create(
cls,
sanic_app: Sanic,
scope: ASGIScope,
recei... | ASGIApp |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/tests/conftest.py | {
"start": 5690,
"end": 11217
} | class ____:
def __init__(self, credentials=None, project=None):
self.credentials = credentials
self.project = project
self._secrets = {}
def create_secret(self, request=None, parent=None, secret_id=None, **kwds):
response = MagicMock()
if request:
parent = re... | SecretManagerClient |
python | has2k1__plotnine | plotnine/geoms/geom_quantile.py | {
"start": 77,
"end": 898
} | class ____(geom_path):
"""
Quantile lines from a quantile regression
{usage}
Parameters
----------
{common_parameters}
lineend : Literal["butt", "round", "projecting"], default="butt"
Line end style. This option is applied for solid linetypes.
linejoin : Literal["round", "miter... | geom_quantile |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_pennsylvania_zip.py | {
"start": 767,
"end": 1783
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_pennsylvania_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _... | ColumnValuesToBeValidPennsylvaniaZip |
python | google__pytype | pytype/tests/test_typing_methods2.py | {
"start": 124,
"end": 2452
} | class ____(test_base.BaseTest):
"""Tests for typing.py."""
def test_mapping(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
from typing import Mapping
K = TypeVar("K")
V = TypeVar("V")
class MyDict(Mapping[K, V]): ...
def f(... | TypingMethodsTest |
python | celery__celery | t/integration/tasks.py | {
"start": 8879,
"end": 10054
} | class ____(Exception):
"""Exception that doesn't survive a pickling roundtrip (dump + load)."""
def __init__(self, foo, bar=None):
if bar is None:
# We define bar with a default value in the signature so that
# it's easier to add a break point here to find out when the
... | UnpickleableException |
python | readthedocs__readthedocs.org | readthedocs/core/migrations/0011_alter_historicaluser_first_name.py | {
"start": 148,
"end": 518
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("core", "0010_add_time_fields"),
]
operations = [
migrations.AlterField(
model_name="historicaluser",
name="first_name",
field=models.CharField(blank=True, max_length=150, ... | Migration |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py | {
"start": 55946,
"end": 59575
} | class ____(GoogleCloudBaseOperator):
"""
Gets the details of a specific Memcached instance.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudMemorystoreMemcachedGetInstanceOperator`
:param location: The location of the C... | CloudMemorystoreMemcachedGetInstanceOperator |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_tasks.py | {
"start": 7787,
"end": 8623
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.tasks.CloudTasksHook")
def test_resume_queue(self, mock_hook):
mock_hook.return_value.resume_queue.return_value = TEST_QUEUE
operator = CloudTasksQueueResumeOperator(location=LOCATION, queue_name=QUEUE_ID, task_id="id")
r... | TestCloudTasksQueueResume |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/interfaces.py | {
"start": 40198,
"end": 52993
} | class ____:
"""This represents a batch of data.
This is usually not the data itself but a hook to the data on an external datastore such as
a spark or a sql database. An exception exists for pandas or any in-memory datastore.
"""
def __init__( # noqa: PLR0913 # FIXME CoP
self,
dat... | Batch |
python | kubernetes-client__python | kubernetes/client/models/v1alpha1_storage_version_migration_spec.py | {
"start": 383,
"end": 5103
} | 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... | V1alpha1StorageVersionMigrationSpec |
python | PrefectHQ__prefect | tests/input/test_actions.py | {
"start": 3707,
"end": 4377
} | class ____:
async def test_implicit_flow_run(self, flow_run_context):
await create_flow_run_input(key="key", value="value")
await delete_flow_run_input(key="key")
assert (
await read_flow_run_input(
key="key", flow_run_id=flow_run_context.flow_run.id
)... | TestDeleteFlowRunInput |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/tiktok/tests.py | {
"start": 240,
"end": 875
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = TikTokProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"data": {
"user": {
"open_id": "44322889",
"username": "username123",
... | TikTokTests |
python | numba__numba | numba/core/typing/npdatetime.py | {
"start": 3983,
"end": 4107
} | class ____(TimedeltaUnaryOp):
key = operator.neg
@infer_global(operator.add)
@infer_global(operator.iadd)
| TimedeltaUnaryNeg |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 28545,
"end": 29954
} | class ____(BaseUserFunctionVariable):
_nonvar_fields = {
"allowed_types",
*BaseUserFunctionVariable._nonvar_fields,
}
def __init__(
self,
allowed_types: tuple[type, ...],
map_fn: VariableTracker,
**kwargs: Any,
) -> None:
super().__init__(**kwargs... | TreeMapOnlyFunctionVariable |
python | doocs__leetcode | solution/2300-2399/2357.Make Array Zero by Subtracting Equal Amounts/Solution.py | {
"start": 0,
"end": 116
} | class ____:
def minimumOperations(self, nums: List[int]) -> int:
return len({x for x in nums if x})
| Solution |
python | kamyu104__LeetCode-Solutions | Python/sum-of-subarray-ranges.py | {
"start": 29,
"end": 815
} | class ____(object):
def subArrayRanges(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
stk = []
for i in xrange(len(nums)+1):
x = nums[i] if i < len(nums) else float("inf")
while stk and nums[stk[-1]] <= x:
... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/sensors/dataplex.py | {
"start": 1698,
"end": 4930
} | class ____(BaseSensorOperator):
"""
Check the status of the Dataplex task.
:param project_id: Required. The ID of the Google Cloud project that the task belongs to.
:param region: Required. The ID of the Google Cloud region that the task belongs to.
:param lake_id: Required. The ID of the Google Cl... | DataplexTaskStateSensor |
python | huggingface__transformers | src/transformers/models/persimmon/modeling_persimmon.py | {
"start": 7352,
"end": 8685
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size)
self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size)
self.act = ACT2FN[config.hidden_act]
def forward(self, ... | PersimmonMLP |
python | huggingface__transformers | tests/models/clipseg/test_modeling_clipseg.py | {
"start": 15171,
"end": 20226
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (CLIPSegModel, CLIPSegForImageSegmentation) if is_torch_available() else ()
pipeline_model_mapping = {"feature-extraction": CLIPSegModel} if is_torch_available() else {}
test_resize_embeddings = False
test_attenti... | CLIPSegModelTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/document_summary/base.py | {
"start": 1507,
"end": 1648
} | class ____(str, Enum):
EMBEDDING = "embedding"
LLM = "llm"
_RetrieverMode = DocumentSummaryRetrieverMode
| DocumentSummaryRetrieverMode |
python | gevent__gevent | src/gevent/tests/test__selectors.py | {
"start": 3845,
"end": 5763
} | class ____(greentest.TestCase):
"""
Tests for the crashes and unexpected exceptions
that happen when we try to use or create (depending on
loop implementation) a IO watcher for a closed/invalid file descriptor.
See https://github.com/gevent/gevent/issues/2100
See test__select.py
"""
de... | TestPossibleCrashes |
python | realpython__materials | django-diary/source_code_final/entries/views.py | {
"start": 337,
"end": 407
} | class ____(LoginRequiredMixin):
login_url = "admin:login"
| LockedView |
python | google__pytype | pytype/pytd/visitors.py | {
"start": 32388,
"end": 32752
} | class ____(ExtractSuperClasses):
"""Visitor for extracting all superclasses (i.e., the class hierarchy).
This returns a mapping by name, e.g. {
"bool": ["int"],
"int": ["object"],
...
}.
"""
def _Key(self, node):
if isinstance(node, (pytd.GenericType, pytd.GENERIC_BASE_TYPE, pytd.Class)):
... | ExtractSuperClassesByName |
python | arrow-py__arrow | arrow/parser.py | {
"start": 31734,
"end": 33345
} | class ____:
"""
Parser for timezone information.
"""
_TZINFO_RE: ClassVar[Pattern[str]] = re.compile(
r"^(?:\(UTC)*([\+\-])?(\d{2})(?:\:?(\d{2}))?"
)
@classmethod
def parse(cls, tzinfo_string: str) -> dt_tzinfo:
"""
Parse a timezone string and return a datetime time... | TzinfoParser |
python | apache__airflow | airflow-core/tests/unit/dag_processing/bundles/test_base.py | {
"start": 4102,
"end": 4724
} | class ____:
def __init__(self, num, **kwargs):
super().__init__(**kwargs)
self.num = num
self.stop = None
self.did_lock = None
self.locker: BundleVersionLock
def lock_the_file(self):
self.locker = BundleVersionLock(
bundle_name="abc",
bund... | LockTestHelper |
python | joke2k__faker | tests/test_generator.py | {
"start": 159,
"end": 487
} | class ____:
def foo_formatter(self):
return "foobar"
def foo_formatter_with_arguments(self, param="", append=""):
return "baz" + str(param) + str(append)
@pytest.fixture(autouse=True)
def generator():
generator = Generator()
generator.add_provider(FooProvider())
return generator
... | FooProvider |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/experiment_service.py | {
"start": 12792,
"end": 15654
} | class ____(GoogleCloudBaseOperator):
"""
Use the Vertex AI SDK to update state of the experiment run.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param location: Required. The ID of the Google Cloud location that the service belongs to.
:param exper... | UpdateExperimentRunStateOperator |
python | jazzband__django-simple-history | simple_history/tests/tests/test_utils.py | {
"start": 11250,
"end": 14029
} | class ____(TransactionTestCase):
def setUp(self):
self.data = [
Poll(id=1, question="Question 1", pub_date=timezone.now()),
Poll(id=2, question="Question 2", pub_date=timezone.now()),
Poll(id=3, question="Question 3", pub_date=timezone.now()),
Poll(id=4, quest... | BulkCreateWithHistoryTransactionTestCase |
python | neetcode-gh__leetcode | python/0746-min-cost-climbing-stairs.py | {
"start": 0,
"end": 215
} | class ____:
def minCostClimbingStairs(self, cost: List[int]) -> int:
for i in range(len(cost) - 3, -1, -1):
cost[i] += min(cost[i + 1], cost[i + 2])
return min(cost[0], cost[1])
| Solution |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 26194,
"end": 26598
} | class ____(Sky2PixProjection, PseudoCylindrical):
r"""
Hammer-Aitoff projection - sky to pixel.
Corresponds to the ``AIT`` projection in FITS WCS.
.. math::
x &= 2 \gamma \cos \theta \sin \frac{\phi}{2} \\
y &= \gamma \sin \theta
where:
.. math::
\gamma = \frac{180^\c... | Sky2Pix_HammerAitoff |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/op_definition.py | {
"start": 2378,
"end": 24901
} | class ____(NodeDefinition, IHasInternalInit):
"""Defines an op, the functional unit of user-defined computation.
End users should prefer the :func:`@op <op>` decorator. OpDefinition is generally intended to be
used by framework authors or for programatically generated ops.
Args:
name (str): Na... | OpDefinition |
python | falconry__falcon | tests/test_middleware.py | {
"start": 4558,
"end": 4692
} | class ____:
def on_get(self, req, resp, **kwargs):
resp.status = falcon.HTTP_200
resp.text = 'Test'
| TestCorsResource |
python | ipython__ipython | examples/IPython Kernel/gui/gui-qt.py | {
"start": 286,
"end": 1009
} | class ____(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(300, 300, 200, 80)
self.setWindowTitle('Hello World')
quit = QtGui.QPushButton('Close', self)
quit.setGeometry(10, 10, 60, 35)
self.connect(quit, QtCor... | SimpleWindow |
python | wandb__wandb | wandb/filesync/stats.py | {
"start": 322,
"end": 427
} | class ____(NamedTuple):
artifact: int
wandb: int
media: int
other: int
| FileCountsByCategory |
python | walkccc__LeetCode | solutions/2933. High-Access Employees/2933.py | {
"start": 0,
"end": 425
} | class ____:
def findHighAccessEmployees(self, access_times: list[list[str]]) -> list[str]:
ans = set()
access_times.sort()
for i in range(len(access_times) - 2):
name = access_times[i][0]
if name in ans:
continue
if name != access_times[i + 2][0]:
continue
if int(... | Solution |
python | huggingface__transformers | src/transformers/models/pegasus/tokenization_pegasus.py | {
"start": 1013,
"end": 7244
} | class ____(TokenizersBackend):
r"""
Construct a PEGASUS 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 ... | PegasusTokenizer |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/merge.py | {
"start": 14024,
"end": 19608
} | class ____(_Merge):
"""Layer that concatenates a list of inputs.
It takes as input a list of tensors, all of the same shape except
for the concatenation axis, and returns a single tensor that is the
concatenation of all inputs.
>>> x = np.arange(20).reshape(2, 2, 5)
>>> print(x)
[[[ 0 1 2 3 4]
[... | Concatenate |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/xaxis/_tickformatstop.py | {
"start": 235,
"end": 8527
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.xaxis"
_path_str = "layout.scene.xaxis.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where "min", "max... | Tickformatstop |
python | ansible__ansible | test/units/module_utils/facts/test_facts.py | {
"start": 3185,
"end": 3379
} | class ____(BaseTestFactsPlatform):
platform_id = 'FreeBSD'
fact_class = hardware.freebsd.FreeBSDHardware
collector_class = hardware.freebsd.FreeBSDHardwareCollector
| TestFreeBSDHardware |
python | davidhalter__jedi | test/completion/comprehensions.py | {
"start": 2257,
"end": 3779
} | class ____():
def __init__(self, bar):
self.bar = bar
def foo(self):
x = [a for a in self.bar][0]
#? int()
x
return x
#? int()
X([1]).foo()
# -----------------
# dict comprehensions
# -----------------
#? int()
list({a - 1: 3 for a in [1]})[0]
d = {a - 1: b for a, b ... | X |
python | html5lib__html5lib-python | html5lib/html5parser.py | {
"start": 83142,
"end": 86414
} | class ____(Phase):
# http://www.whatwg.org/specs/web-apps/current-work/#in-row
__slots__ = tuple()
# helper methods (XXX unify this with other table helper methods)
def clearStackToTableRowContext(self):
while self.tree.openElements[-1].name not in ("tr", "html"):
self.parser.parseE... | InRowPhase |
python | ApeWorX__ape | src/ape_networks/config.py | {
"start": 962,
"end": 1116
} | class ____(PluginConfig):
custom: list[CustomNetwork] = []
model_config = SettingsConfigDict(extra="allow", env_prefix="APE_NETWORKS_")
| NetworksConfig |
python | wandb__wandb | tests/system_tests/test_artifacts/test_wandb_artifacts.py | {
"start": 15106,
"end": 66484
} | class ____:
@pytest.fixture
def run(self, user) -> Iterator[wandb.Run]:
with wandb.init() as run:
yield run
@pytest.fixture
def orig_data(self) -> str:
"""The contents of the original file."""
return "hello"
@pytest.fixture
def orig_fpath(self, tmp_path_fact... | TestAddReferenceLocalFileNoChecksumTwice |
python | langchain-ai__langchain | libs/core/langchain_core/retrievers.py | {
"start": 1536,
"end": 11125
} | class ____(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
"""Abstract base class for a document retrieval system.
A retrieval system is defined as something that can take string queries and return
the most 'relevant' documents from some source.
Usage:
A retriever follows the standar... | BaseRetriever |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numerictypes.py | {
"start": 1416,
"end": 4038
} | class ____(TestCase):
# scalar types can be promoted into dtypes
wrappers = [np.dtype, lambda x: x]
def test_both_abstract(self):
assert_(np.issubdtype(np.floating, np.inexact))
assert_(not np.issubdtype(np.inexact, np.floating))
def test_same(self):
for cls in (np.float32, np.... | TestIsSubDType |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py | {
"start": 2800,
"end": 3060
} | class ____(Protocol):
"""Callable that generates a description for a tool call."""
def __call__(self, tool_call: ToolCall, state: AgentState, runtime: Runtime) -> str:
"""Generate a description for a tool call."""
...
| _DescriptionFactory |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.