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 | tensorflow__tensorflow | tensorflow/python/training/saver_test.py | {
"start": 54248,
"end": 70147
} | class ____(test.TestCase):
def _get_test_dir(self, dirname):
test_dir = os.path.join(self.get_temp_dir(), dirname)
gfile.MakeDirs(test_dir)
return test_dir
def assertCheckpointState(self, model_checkpoint_path,
all_model_checkpoint_paths, save_dir):
checkpoint_state = c... | MaxToKeepTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor22.py | {
"start": 243,
"end": 373
} | class ____(Protocol[T]):
def a(self) -> "A[Tuple[T]]": ...
def b(self) -> "A[Tuple[T]]": ...
def c(self) -> "T": ...
| A |
python | Farama-Foundation__Gymnasium | tests/test_core.py | {
"start": 582,
"end": 1599
} | class ____(Env):
"""Example testing environment."""
def __init__(self):
"""Constructor for example environment."""
self.observation_space = Box(0, 1)
self.action_space = Box(0, 1)
def step(
self, action: ActType
) -> tuple[ObsType, float, bool, bool, dict[str, Any]]:
... | ExampleEnv |
python | spyder-ide__spyder | spyder/plugins/history/plugin.py | {
"start": 667,
"end": 4221
} | class ____(SpyderDockablePlugin):
"""
History log plugin.
"""
NAME = 'historylog'
REQUIRES = [Plugins.Preferences, Plugins.Console]
OPTIONAL = [Plugins.IPythonConsole]
TABIFY = Plugins.IPythonConsole
WIDGET_CLASS = HistoryWidget
CONF_SECTION = NAME
CONF_WIDGET_CLASS = HistoryCon... | HistoryLog |
python | has2k1__plotnine | plotnine/geoms/geom_count.py | {
"start": 79,
"end": 598
} | class ____(geom_point):
"""
Plot overlapping points
{usage}
This is a variant [](`~plotnine.geoms.geom_point`) that counts the number
of observations at each location, then maps the count to point
area. It useful when you have discrete data and overplotting.
Parameters
----------
... | geom_count |
python | lepture__authlib | authlib/oauth2/auth.py | {
"start": 1284,
"end": 2392
} | class ____:
"""Attaches OAuth Client Information to HTTP requests.
:param client_id: Client ID, which you get from client registration.
:param client_secret: Client Secret, which you get from registration.
:param auth_method: Client auth method for token endpoint. The supported
methods for now:... | ClientAuth |
python | getsentry__sentry | src/sentry/workflow_engine/models/workflow_action_group_status.py | {
"start": 187,
"end": 832
} | class ____(DefaultFieldsModel):
"""
Stores when a workflow action last fired for a Group.
"""
__relocation_scope__ = RelocationScope.Excluded
workflow = FlexibleForeignKey("workflow_engine.Workflow", on_delete=models.CASCADE)
action = FlexibleForeignKey("workflow_engine.Action", on_delete=mode... | WorkflowActionGroupStatus |
python | sympy__sympy | sympy/functions/special/polynomials.py | {
"start": 32927,
"end": 36041
} | class ____(OrthogonalPolynomial):
r"""
``hermite(n, x)`` gives the $n$th Hermite polynomial in $x$, $H_n(x)$.
Explanation
===========
The Hermite polynomials are orthogonal on $(-\infty, \infty)$
with respect to the weight $\exp\left(-x^2\right)$.
Examples
========
>>> from sympy... | hermite |
python | tox-dev__tox | src/tox/tox_env/python/virtual_env/package/pyproject.py | {
"start": 2148,
"end": 2257
} | class ____(RuntimeError):
"""raised when build editable is not supported."""
| BuildEditableNotSupportedError |
python | keras-team__keras | keras/src/layers/convolutional/base_conv.py | {
"start": 561,
"end": 17978
} | class ____(Layer):
"""Abstract N-D convolution layer (private, used as implementation base).
This layer creates a convolution kernel that is convolved (actually
cross-correlated) with the layer input to produce a tensor of outputs. If
`use_bias` is True (and a `bias_initializer` is provided), a bias ve... | BaseConv |
python | apache__airflow | airflow-core/src/airflow/timetables/_cron.py | {
"start": 2685,
"end": 7689
} | class ____:
"""Mixin to provide interface to work with croniter."""
def __init__(self, cron: str, timezone: str | Timezone | FixedTimezone) -> None:
self._expression = cron_presets.get(cron, cron)
if isinstance(timezone, str):
timezone = parse_timezone(timezone)
self._timez... | CronMixin |
python | django__django | django/db/migrations/serializer.py | {
"start": 5816,
"end": 5934
} | class ____(BaseUnorderedSequenceSerializer):
def _format(self):
return "frozenset([%s])"
| FrozensetSerializer |
python | doocs__leetcode | lcci/10.05.Sparse Array Search/Solution.py | {
"start": 0,
"end": 408
} | class ____:
def findString(self, words: List[str], s: str) -> int:
def dfs(i: int, j: int) -> int:
if i > j:
return -1
mid = (i + j) >> 1
l = dfs(i, mid - 1)
if l != -1:
return l
if words[mid] == s:
r... | Solution |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-days-to-disconnect-island.py | {
"start": 5042,
"end": 7630
} | class ____(object):
def minDays(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def floodfill(grid, i, j, lookup):
stk = [(i, j)]
lookup[i][j] = 1
while stk:
... | Solution2 |
python | pytorch__pytorch | torch/distributed/tensor/_op_schema.py | {
"start": 8051,
"end": 10073
} | class ____(StrategyType):
"""
TupleStrategy is a special case for operators that are fundamentally compound or batched such that some subset
of the inputs and outputs are completely unrelated to some other subset.
Generally, foreach_* ops are the most common use-case for TupleStrategy, because they acc... | TupleStrategy |
python | pydata__xarray | xarray/tests/test_indexing.py | {
"start": 36164,
"end": 41175
} | class ____:
def __array_namespace__(self, version=None):
pass
def __array_function__(self, func, types, args, kwargs):
pass
def as_dask_array(arr, chunks):
try:
import dask.array as da
except ImportError:
return None
return da.from_array(arr, chunks=chunks)
@pyt... | ArrayWithNamespaceAndArrayFunction |
python | PrefectHQ__prefect | src/integrations/prefect-sqlalchemy/tests/test_database.py | {
"start": 1569,
"end": 2646
} | class ____:
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def execute(self, query, params):
cursor_result = MagicMock()
cursor_result.fetchall.side_effect = lambda: [
(query, params),
]
cursor_result.fetchmany.side_effec... | SQLAlchemyConnectionMock |
python | getsentry__sentry | src/sentry/deletions/defaults/rule.py | {
"start": 261,
"end": 1797
} | class ____(ModelDeletionTask[Rule]):
def get_child_relations(self, instance: Rule) -> list[BaseRelation]:
from sentry.models.grouprulestatus import GroupRuleStatus
from sentry.models.rule import RuleActivity
from sentry.models.rulefirehistory import RuleFireHistory
from sentry.workfl... | RuleDeletionTask |
python | keras-team__keras | guides/making_new_layers_and_models_via_subclassing.py | {
"start": 11644,
"end": 13297
} | class ____(keras.layers.Layer):
def __init__(self, units=32, **kwargs):
super().__init__(**kwargs)
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=T... | Linear |
python | pytorch__pytorch | test/test_utils.py | {
"start": 33374,
"end": 33670
} | class ____(TestCase):
def test_cpp_compiler_is_ok(self):
self.assertTrue(torch.utils.cpp_extension.check_compiler_ok_for_platform("c++"))
def test_cc_compiler_is_ok(self):
self.assertTrue(torch.utils.cpp_extension.check_compiler_ok_for_platform("cc"))
| TestCppExtensionUtils |
python | ashishps1__awesome-system-design-resources | implementations/python/rate_limiting/token_bucket.py | {
"start": 13,
"end": 1219
} | class ____:
def __init__(self, capacity, fill_rate):
self.capacity = capacity # Maximum number of tokens the bucket can hold
self.fill_rate = fill_rate # Rate at which tokens are added (tokens/second)
self.tokens = capacity # Current token count, start with a full bucket
self.last... | TokenBucket |
python | falconry__falcon | tests/test_typing.py | {
"start": 806,
"end": 2182
} | class ____(falcon.asgi.Response):
context_type = RichContext
# NOTE(vytas): the `type: ignore` exemption is currently required if it is
# desirable to actually check typing of context attributes. See also:
# https://falcon.readthedocs.io/en/latest/api/typing.html#known-limitations
context: Rich... | FancyAsyncResponse |
python | Lightning-AI__lightning | src/lightning/pytorch/strategies/launchers/multiprocessing.py | {
"start": 12575,
"end": 12775
} | class ____(NamedTuple):
best_model_path: Optional[_PATH]
weights_path: Optional[_PATH]
trainer_state: TrainerState
trainer_results: Any
extra: dict[str, Any]
@dataclass
| _WorkerOutput |
python | google__jax | jax/_src/pallas/mosaic_gpu/pipeline.py | {
"start": 5806,
"end": 16265
} | class ____:
start: int | jax.Array
size: int | jax.Array
def __eq__(self, other: _Slice) -> jax.Array: # type: ignore
return lax.bitwise_and(self.start == other.start, self.size == other.size)
jax.tree_util.register_dataclass(
_Slice, data_fields=["start", "size"], meta_fields=[]
)
def _downcast_spe... | _Slice |
python | getsentry__sentry | src/sentry/integrations/utils/codecov.py | {
"start": 882,
"end": 4703
} | class ____(Enum):
MISSING_TOKEN = "Internal Error"
MISSING_GH = "Codecov access can only be enabled if the organization has a GitHub integration."
MISSING_CODECOV = (
"Codecov access can only be enabled if the organization has a Codecov integration."
)
def codecov_enabled(organization: Organiz... | CodecovIntegrationError |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_allocation_result.py | {
"start": 383,
"end": 5868
} | 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... | V1beta2AllocationResult |
python | keras-team__keras | keras/src/backend/jax/layer.py | {
"start": 272,
"end": 308
} | class ____(BaseLayer):
pass
| JaxLayer |
python | joke2k__faker | faker/providers/person/zh_CN/__init__.py | {
"start": 81,
"end": 15274
} | class ____(PersonProvider):
formats = ["{{last_name}}{{first_name}}"]
first_names_male = [
"伟",
"强",
"磊",
"洋",
"勇",
"军",
"杰",
"涛",
"超",
"明",
"刚",
"平",
"辉",
"鹏",
"华",
"飞",
"鑫",... | Provider |
python | apache__airflow | airflow-core/src/airflow/api/client/local_client.py | {
"start": 1073,
"end": 3930
} | class ____:
"""Local API client implementation."""
def __init__(self, auth=None, session: httpx.Client | None = None):
self._session: httpx.Client = session or httpx.Client()
if auth:
self._session.auth = auth
def trigger_dag(
self,
dag_id,
run_id=None,
... | Client |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 8290,
"end": 9279
} | class ____(FunctionPass):
_name = "with_lifting"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
Extract with-contexts
"""
main, withs = transforms.with_lifting(
func_ir=state.func_ir,
typingctx=state.typingctx,... | WithLifting |
python | ray-project__ray | python/ray/tests/test_runtime_env_plugin.py | {
"start": 672,
"end": 3100
} | class ____(RuntimeEnvPlugin):
name = MY_PLUGIN_NAME
env_key = "MY_PLUGIN_TEST_ENVIRONMENT_KEY"
@staticmethod
def validate(runtime_env: RuntimeEnv) -> str:
value = runtime_env[MY_PLUGIN_NAME]
if value == "fail":
raise ValueError("not allowed")
return value
def mo... | MyPlugin |
python | doocs__leetcode | solution/0600-0699/0634.Find the Derangement of An Array/Solution.py | {
"start": 0,
"end": 223
} | class ____:
def findDerangement(self, n: int) -> int:
mod = 10**9 + 7
f = [1] + [0] * n
for i in range(2, n + 1):
f[i] = (i - 1) * (f[i - 1] + f[i - 2]) % mod
return f[n]
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-sftp-bulk/source_sftp_bulk/source.py | {
"start": 526,
"end": 959
} | class ____(FileBasedSource):
def __init__(self, catalog: Optional[ConfiguredAirbyteCatalog], config: Optional[Mapping[str, Any]], state: Optional[TState]):
super().__init__(
stream_reader=SourceSFTPBulkStreamReader(),
spec_class=SourceSFTPBulkSpec,
catalog=catalog,
... | SourceSFTPBulk |
python | fluentpython__example-code | attic/objects/attr_list.py | {
"start": 65,
"end": 1517
} | class ____():
pass
# int, str,
sample_types = [object, list, Class, type(Class), type(fn)]
if '-' in sys.argv:
del sample_types[0] # exlude `object`
sample_objs = [type_() for type_ in sample_types[:-2]] + [Class, fn]
sample_oids = [id(obj) for obj in sample_objs]
fmt = '{attr:17}' + '|{:8}' * len(sample_typ... | Class |
python | huggingface__transformers | src/transformers/models/dpr/tokenization_dpr_fast.py | {
"start": 1140,
"end": 1660
} | class ____(BertTokenizer):
r"""
Construct a "fast" DPRContextEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
[`DPRContextEncoderTokenizerFast`] is identical to [`BertTokenizer`] and runs end-to-end tokenization:
punctuation splitting and wordpiece.
Refer to superclass [`BertToken... | DPRContextEncoderTokenizerFast |
python | kamyu104__LeetCode-Solutions | Python/final-prices-with-a-special-discount-in-a-shop.py | {
"start": 29,
"end": 361
} | class ____(object):
def finalPrices(self, prices):
"""
:type prices: List[int]
:rtype: List[int]
"""
stk = []
for i, p in enumerate(prices):
while stk and prices[stk[-1]] >= p:
prices[stk.pop()] -= p
stk.append(i)
return... | Solution |
python | django-haystack__django-haystack | test_haystack/elasticsearch7_tests/test_backend.py | {
"start": 47619,
"end": 49493
} | class ____(TestCase):
"""Used to test actual implementation details of the SearchQuerySet."""
fixtures = ["bulk_data.json"]
def setUp(self):
super().setUp()
# Wipe it clean.
clear_elasticsearch_index()
# Reboot the schema.
self.sb = connections["elasticsearch"].ge... | LiveElasticsearch7SpellingTestCase |
python | pallets__flask | tests/test_helpers.py | {
"start": 6970,
"end": 9596
} | class ____:
def test_streaming_with_context(self, app, client):
@app.route("/")
def index():
def generate():
yield "Hello "
yield flask.request.args["name"]
yield "!"
return flask.Response(flask.stream_with_context(generate()))... | TestStreaming |
python | numba__numba | numba/core/ir.py | {
"start": 21555,
"end": 21956
} | class ____(Stmt):
def __init__(self, dct, key, value, loc):
assert isinstance(dct, Var)
assert isinstance(key, Var)
assert isinstance(value, Var)
assert isinstance(loc, Loc)
self.dct = dct
self.key = key
self.value = value
self.loc = loc
def __rep... | StoreMap |
python | getsentry__sentry | src/sentry_plugins/github/webhooks/events/push.py | {
"start": 953,
"end": 9210
} | class ____(Webhook):
def _handle(self, event, organization_id, is_apps):
authors = {}
gh_username_cache: dict[str, str | None] = {}
try:
repo = Repository.objects.get(
organization_id=organization_id,
provider="github_apps" if is_apps else "githu... | PushEventWebhook |
python | huggingface__transformers | src/transformers/utils/quantization_config.py | {
"start": 84378,
"end": 87204
} | class ____(QuantizationConfigMixin):
"""
Configuration class for applying BitNet quantization.
Args:
modules_to_not_convert (`Optional[List]`, *optional*):
Optionally, provides a list of full paths of `nn.Linear` weight parameters
that shall not be quantized. Defaults to Non... | BitNetQuantConfig |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/combine_documents/map_reduce.py | {
"start": 995,
"end": 11858
} | class ____(BaseCombineDocumentsChain):
"""Combining documents by mapping a chain over them, then combining results.
We first call `llm_chain` on each document individually, passing in the
`page_content` and any other kwargs. This is the `map` step.
We then process the results of that `map` step in a `... | MapReduceDocumentsChain |
python | django__django | tests/i18n/forms.py | {
"start": 56,
"end": 396
} | class ____(forms.Form):
decimal_field = forms.DecimalField(localize=True)
float_field = forms.FloatField(localize=True)
date_field = forms.DateField(localize=True)
datetime_field = forms.DateTimeField(localize=True)
time_field = forms.TimeField(localize=True)
integer_field = forms.IntegerField(l... | I18nForm |
python | kubernetes-client__python | kubernetes/client/models/v1_api_resource_list.py | {
"start": 383,
"end": 7505
} | 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... | V1APIResourceList |
python | explosion__spaCy | spacy/lang/zh/__init__.py | {
"start": 1303,
"end": 11154
} | class ____(DummyTokenizer):
def __init__(self, vocab: Vocab, segmenter: Segmenter = Segmenter.char):
self.vocab = vocab
self.segmenter = (
segmenter.value if isinstance(segmenter, Segmenter) else segmenter
)
self.pkuseg_seg = None
self.jieba_seg = None
if ... | ChineseTokenizer |
python | spyder-ide__spyder | spyder/plugins/workingdirectory/container.py | {
"start": 1074,
"end": 1223
} | class ____:
Previous = 'previous_action'
Next = "next_action"
Browse = "browse_action"
Parent = "parent_action"
| WorkingDirectoryActions |
python | sympy__sympy | sympy/geometry/line.py | {
"start": 75378,
"end": 79437
} | class ____(LinearEntity3D, Ray):
"""
A Ray is a semi-line in the space with a source point and a direction.
Parameters
==========
p1 : Point3D
The source of the Ray
p2 : Point or a direction vector
direction_ratio: Determines the direction in which the Ray propagates.
Attribu... | Ray3D |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-milvus/unit_tests/destination_test.py | {
"start": 319,
"end": 3831
} | class ____(unittest.TestCase):
def setUp(self):
self.config = {
"processing": {"text_fields": ["str_col"], "metadata_fields": [], "chunk_size": 1000},
"embedding": {"mode": "openai", "openai_key": "mykey"},
"indexing": {
"host": "https://notmilvus.com",
... | TestDestinationMilvus |
python | pytorch__pytorch | torch/library.py | {
"start": 1776,
"end": 67668
} | class ____:
"""
A class to create libraries that can be used to register new operators or
override operators in existing libraries from Python.
A user can optionally pass in a dispatch keyname if they only want to register
kernels corresponding to only one specific dispatch key.
To create a lib... | Library |
python | apache__airflow | airflow-core/src/airflow/cli/cli_parser.py | {
"start": 3563,
"end": 4577
} | class ____(RichHelpFormatter):
"""
Custom help formatter to display help message.
It displays simple commands and groups of commands in separate sections.
"""
def _iter_indented_subactions(self, action: Action):
if isinstance(action, argparse._SubParsersAction):
self._indent()
... | AirflowHelpFormatter |
python | coleifer__peewee | tests/regressions.py | {
"start": 9348,
"end": 9408
} | class ____(TestModel):
id = IntegerField(primary_key=True)
| A |
python | spack__spack | .github/workflows/bin/format-rst.py | {
"start": 2257,
"end": 2521
} | class ____(Warning):
def __init__(self, path: str, line: int, message: str, diff: str):
super().__init__(path, line, f"{message}\n{diff}")
def __str__(self) -> str:
return _warning(f"{self.path}:{self.line}: {self.message}")
| CodeBlockWarning |
python | pytorch__pytorch | test/higher_order_ops/test_invoke_quant.py | {
"start": 3769,
"end": 3838
} | class ____(TestInvokeQuant):
backend = "eager"
| TestInvokeQuantEager |
python | dask__distributed | distributed/comm/tcp.py | {
"start": 25492,
"end": 26285
} | class ____(Backend):
# I/O
def get_connector(self):
return self._connector_class()
def get_listener(self, loc, handle_comm, deserialize, **connection_args):
return self._listener_class(loc, handle_comm, deserialize, **connection_args)
# Address handling
def get_address_host(self,... | BaseTCPBackend |
python | gevent__gevent | benchmarks/bench_local.py | {
"start": 266,
"end": 301
} | class ____(glocal):
pass
| GLocalSub |
python | tensorflow__tensorflow | tensorflow/python/training/evaluation.py | {
"start": 2677,
"end": 4664
} | class ____(session_run_hook.SessionRunHook):
"""Run hook used by the evaluation routines to run the `eval_ops` N times."""
def __init__(self, num_evals, steps_per_run=1):
"""Constructs the run hook.
Args:
num_evals: The number of evaluations to run for. if set to None, will
iterate the datas... | _MultiStepStopAfterNEvalsHook |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_ps.py | {
"start": 31557,
"end": 31727
} | class ____(Enum):
portrait, landscape = range(2)
def swap_if_landscape(self, shape):
return shape[::-1] if self.name == "landscape" else shape
| _Orientation |
python | numba__numba | numba/cuda/cudadecl.py | {
"start": 1879,
"end": 1961
} | class ____(Cuda_array_decl):
key = cuda.shared.array
@register
| Cuda_shared_array |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple10.py | {
"start": 492,
"end": 1674
} | class ____(Generic[DType, Unpack[Shape]]):
def __abs__(self) -> Array[DType, Unpack[Shape]]: ...
def __add__(
self, other: Array[DType, Unpack[Shape]]
) -> Array[DType, Unpack[Shape]]: ...
def process_batch_channels(
x: Array[Batch, Unpack[tuple[Any, ...]], Channels],
) -> None: ...
def exp... | Array |
python | django__django | tests/generic_views/test_edit.py | {
"start": 8964,
"end": 14887
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.author = Author.objects.create(
pk=1, # Required for OneAuthorUpdate.
name="Randall Munroe",
slug="randall-munroe",
)
def test_update_post(self):
res = self.client.get("/edit/author/%... | UpdateViewTests |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/pg8000.py | {
"start": 4620,
"end": 4685
} | class ____(_PGNumericCommon, sqltypes.Numeric):
pass
| _PGNumeric |
python | allegroai__clearml | clearml/backend_interface/task/repo/detectors.py | {
"start": 898,
"end": 7527
} | class ____(object):
"""Base class for repository detection"""
"""
Commands are represented using the result class, where each attribute contains
the command used to obtain the value of the same attribute in the actual result.
"""
_fallback = "_fallback"
_remote = "_remote"
@classmetho... | Detector |
python | ray-project__ray | python/ray/tests/test_actor_out_of_order.py | {
"start": 1023,
"end": 2430
} | class ____:
@pytest.fixture(scope="class", autouse=True)
def start_ray_cluster(self):
ray.init()
yield
ray.shutdown()
def test_options_with_in_order_async_actor_raises_error(self):
@ray.remote
class Actor:
async def method(self):
pass
... | TestAllowOutOfOrderExecutionValidation |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/event/base.py | {
"start": 2303,
"end": 2727
} | class ____(Generic[_ET]):
__slots__ = ()
_instance_cls: Optional[Type[_ET]]
def _join(self, other: _DispatchCommon[_ET]) -> _JoinedDispatcher[_ET]:
raise NotImplementedError()
def __getattr__(self, name: str) -> _InstanceLevelDispatch[_ET]:
raise NotImplementedError()
@property
... | _DispatchCommon |
python | sphinx-doc__sphinx | sphinx/transforms/references.py | {
"start": 366,
"end": 886
} | class ____(DanglingReferences):
"""DanglingReferences transform which does not output info messages."""
def apply(self, **kwargs: Any) -> None:
try:
reporter = self.document.reporter
report_level = reporter.report_level
# suppress INFO level messages for a while
... | SphinxDanglingReferences |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_block_documents.py | {
"start": 29204,
"end": 45962
} | class ____:
async def test_update_block_document_data(self, session, client, block_schemas):
block_document = await models.block_documents.create_block_document(
session,
block_document=schemas.actions.BlockDocumentCreate(
name="test-update-data",
data... | TestUpdateBlockDocument |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_reload_repository_location.py | {
"start": 8438,
"end": 8977
} | class ____(ReadonlyGraphQLContextTestMatrix):
def test_reload_repository_permission_failure(self, graphql_context):
result = execute_dagster_graphql(
graphql_context,
RELOAD_REPOSITORY_LOCATION_QUERY,
{"repositoryLocationName": main_repo_location_name()},
)
... | TestReloadRepositoriesReadOnly |
python | Netflix__metaflow | metaflow/plugins/argo/exit_hooks.py | {
"start": 3751,
"end": 4892
} | class ____(Hook):
# Warning: terrible hack to workaround a bug in Argo Workflow where the
# templates listed above do not execute unless there is an
# explicit exit hook. as and when this bug is patched, we should
# remove this effectively no-op template.
# Note: We use th... | ExitHookHack |
python | readthedocs__readthedocs.org | readthedocs/telemetry/models.py | {
"start": 3447,
"end": 3735
} | class ____(TimeStampedModel):
class Meta:
verbose_name_plural = "Build data"
indexes = [
# Speeds up `delete_old_build_data` task.
models.Index(fields=["created"]),
]
data = models.JSONField()
objects = BuildDataManager()
| BuildData |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/test_response_format.py | {
"start": 1833,
"end": 2930
} | class ____(TypedDict):
city: str
country: str
location_json_schema = {
"type": "object",
"properties": {
"city": {"type": "string", "description": "The city name"},
"country": {"type": "string", "description": "The country name"},
},
"title": "location_schema",
"required": ... | LocationTypedDict |
python | lepture__authlib | authlib/integrations/requests_client/oauth2_session.py | {
"start": 464,
"end": 1133
} | class ____(AuthBase, TokenAuth):
"""Sign requests for OAuth 2.0, currently only bearer token is supported."""
def ensure_active_token(self):
if self.client and not self.client.ensure_active_token(self.token):
raise InvalidTokenError()
def __call__(self, req):
self.ensure_active... | OAuth2Auth |
python | dagster-io__dagster | python_modules/libraries/dagster-postgres/dagster_postgres/run_storage/run_storage.py | {
"start": 1267,
"end": 9757
} | class ____(SqlRunStorage, ConfigurableClass):
"""Postgres-backed run storage.
Users should not directly instantiate this class; it is instantiated by internal machinery when
``dagster-webserver`` and ``dagster-graphql`` load, based on the values in the ``dagster.yaml`` file in
``$DAGSTER_HOME``. Config... | PostgresRunStorage |
python | mlflow__mlflow | mlflow/genai/labeling/labeling.py | {
"start": 1097,
"end": 7931
} | class ____:
"""A session for labeling items in the review app.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
"""
def __init__(
self,
*,
name: str,
assigned_users: list[str],
a... | LabelingSession |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_dev_tests/test_bk_build_status.py | {
"start": 745,
"end": 9619
} | class ____:
"""Test cases for the bk-build-status command."""
def test_successful_build_status_with_build_number(self):
"""Test successful build status retrieval with explicit build number."""
# Mock job data
jobs = [
create_mock_job("Unit Tests", "passed"),
crea... | TestBkBuildStatus |
python | huggingface__transformers | tests/models/audio_spectrogram_transformer/test_modeling_audio_spectrogram_transformer.py | {
"start": 1440,
"end": 5167
} | class ____:
def __init__(
self,
parent,
batch_size=13,
patch_size=2,
max_length=24,
num_mel_bins=16,
is_training=True,
use_labels=True,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
... | ASTModelTester |
python | numba__numba | numba/tests/test_debug.py | {
"start": 3636,
"end": 4986
} | class ____(FunctionDebugTestBase):
def test_dump_bytecode(self):
with override_config('DUMP_BYTECODE', True):
out = self.compile_simple_nopython()
self.check_debug_output(out, ['bytecode'])
def test_dump_ir(self):
with override_config('DUMP_IR', True):
out = sel... | TestFunctionDebugOutput |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_cond_format13.py | {
"start": 315,
"end": 1428
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("cond_format04.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with conditional formatting."""
workbo... | TestCompareXLSXFiles |
python | docker__docker-py | docker/models/configs.py | {
"start": 537,
"end": 1845
} | class ____(Collection):
"""Configs on the Docker server."""
model = Config
def create(self, **kwargs):
obj = self.client.api.create_config(**kwargs)
obj.setdefault("Spec", {})["Name"] = kwargs.get("name")
return self.prepare_model(obj)
create.__doc__ = APIClient.create_config.__... | ConfigCollection |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py | {
"start": 6050,
"end": 13316
} | class ____(Qwen2_5_VLPreTrainedModel):
config: Qwen2_5_VLVisionConfig
_no_split_modules = ["Qwen2_5_VLVisionBlock"]
def __init__(self, config, *inputs, **kwargs) -> None:
super().__init__(config, *inputs, **kwargs)
self.spatial_merge_size = config.spatial_merge_size
self.patch_size ... | Qwen2_5_VisionTransformerPretrainedModel |
python | mahmoud__boltons | boltons/urlutils.py | {
"start": 14740,
"end": 15588
} | class ____:
"""The ``cachedproperty`` is used similar to :class:`property`, except
that the wrapped method is only called once. This is commonly used
to implement lazy attributes.
After the property has been accessed, the value is stored on the
instance itself, using the same name as the cachedprop... | cachedproperty |
python | tiangolo__fastapi | docs_src/header_param_models/tutorial003_an_py310.py | {
"start": 116,
"end": 424
} | class ____(BaseModel):
host: str
save_data: bool
if_modified_since: str | None = None
traceparent: str | None = None
x_tag: list[str] = []
@app.get("/items/")
async def read_items(
headers: Annotated[CommonHeaders, Header(convert_underscores=False)],
):
return headers
| CommonHeaders |
python | PrefectHQ__prefect | src/prefect/server/schemas/responses.py | {
"start": 5284,
"end": 11575
} | class ____(ORMBaseModel):
name: str = Field(
default_factory=lambda: generate_slug(2),
description=(
"The name of the flow run. Defaults to a random slug if not specified."
),
examples=["my-flow-run"],
)
flow_id: UUID = Field(default=..., description="The id of th... | FlowRunResponse |
python | pydata__xarray | xarray/tests/test_dask.py | {
"start": 11573,
"end": 29756
} | class ____(DaskTestCase):
def assertLazyAndIdentical(self, expected, actual):
self.assertLazyAnd(expected, actual, assert_identical)
def assertLazyAndAllClose(self, expected, actual):
self.assertLazyAnd(expected, actual, assert_allclose)
def assertLazyAndEqual(self, expected, actual):
... | TestDataArrayAndDataset |
python | huggingface__transformers | src/transformers/models/dpr/tokenization_dpr_fast.py | {
"start": 1660,
"end": 7064
} | class ____(BertTokenizer):
r"""
Constructs a "fast" DPRQuestionEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
[`DPRQuestionEncoderTokenizerFast`] is identical to [`BertTokenizer`] and runs end-to-end tokenization:
punctuation splitting and wordpiece.
Refer to superclass [`BertTo... | DPRQuestionEncoderTokenizerFast |
python | walkccc__LeetCode | solutions/1101. The Earliest Moment When Everyone Become Friends/1101.py | {
"start": 609,
"end": 907
} | class ____:
def earliestAcq(self, logs: list[list[int]], n: int) -> int:
uf = UnionFind(n)
# Sort `logs` by timestamp.
logs.sort(key=lambda x: x[0])
for timestamp, x, y in logs:
uf.unionByRank(x, y)
if uf.getCount() == 1:
return timestamp
return -1
| Solution |
python | pyca__cryptography | tests/x509/test_x509.py | {
"start": 242035,
"end": 243941
} | class ____:
def test_eq(self):
oid1 = x509.ObjectIdentifier("2.999.1")
oid2 = x509.ObjectIdentifier("2.999.1")
assert oid1 == oid2
def test_ne(self):
oid1 = x509.ObjectIdentifier("2.999.1")
assert oid1 != x509.ObjectIdentifier("2.999.2")
assert oid1 != object()
... | TestObjectIdentifier |
python | getsentry__sentry | src/sentry/integrations/source_code_management/repo_trees.py | {
"start": 705,
"end": 1019
} | class ____(NamedTuple):
repo: RepoAndBranch
files: Sequence[str]
# Tasks which hit the API multiple connection errors should give up.
MAX_CONNECTION_ERRORS = 10
# When the number of remaining API requests is less than this value, it will
# fall back to the cache.
MINIMUM_REQUESTS_REMAINING = 200
| RepoTree |
python | huggingface__transformers | tests/test_image_processing_common.py | {
"start": 33561,
"end": 37055
} | class ____:
# this mixin adds a test to assert that usages of the
# to-be-deprecated `AnnotionFormat` continue to be
# supported for the time being
def test_processor_can_use_legacy_annotation_format(self):
image_processor_dict = self.image_processor_tester.prepare_image_processor_dict()
... | AnnotationFormatTestMixin |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 35460,
"end": 37859
} | class ____:
"""Descriptor for getting and set style flag properties (e.g. ``bold italic underline``)."""
def __set_name__(self, owner: StylesBase, name: str) -> None:
self.name = name
def __get__(
self, obj: StylesBase, objtype: type[StylesBase] | None = None
) -> Style:
"""Get... | StyleFlagsProperty |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/overrides.py | {
"start": 3011,
"end": 3109
} | class ____(AnalyzeAllOverrides):
def return_source(self):
pass
| AnalyzeAllOverridesChild1 |
python | pydata__xarray | xarray/coding/cftime_offsets.py | {
"start": 19407,
"end": 20168
} | class ____(YearOffset):
_freq = "YE"
_day_option = "end"
_default_month = 12
def onOffset(self, date) -> bool:
"""Check if the given date is in the set of possible dates created
using a length-one version of this offset class."""
return date.day == date.daysinmonth and date.mont... | YearEnd |
python | marshmallow-code__marshmallow | src/marshmallow/validate.py | {
"start": 12652,
"end": 15054
} | class ____(Validator):
"""Validator which succeeds if the value passed to it has a
length between a minimum and maximum. Uses len(), so it
can work for strings, lists, or anything with length.
:param min: The minimum length. If not provided, minimum length
will not be checked.
:param max: T... | Length |
python | PrefectHQ__prefect | src/prefect/events/schemas/automations.py | {
"start": 7864,
"end": 9592
} | class ____(PrefectBaseModel):
"""Defines a subset of the Trigger subclass, which is specific
to Metric automations, that specify the query configurations
and breaching conditions for the Automation"""
name: PrefectMetric = Field(
...,
description="The name of the metric to query.",
... | MetricTriggerQuery |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_aux/test_configmap.py | {
"start": 914,
"end": 10873
} | class ____:
"""Tests configmaps."""
def test_single_annotation(self):
docs = render_chart(
values={
"airflowConfigAnnotations": {"key": "value"},
},
show_only=["templates/configmaps/configmap.yaml"],
)
annotations = jmespath.search("m... | TestConfigmap |
python | getsentry__sentry | src/sentry/utils/locking/backends/migration.py | {
"start": 559,
"end": 3688
} | class ____(LockBackend):
"""
Backend class intended for controlled migrations of locks from one backend to another.
Example use in combination with runtime option:
def selector_func(key, routing_key, backend_new, backend_old):
if int(hashlib.md5("{key}{routing_key}".encode("utf8")).hex... | MigrationLockBackend |
python | dask__distributed | distributed/worker_memory.py | {
"start": 20601,
"end": 21214
} | class ____:
name: str
def __set_name__(self, owner: type, name: str) -> None:
self.name = name
def __get__(self, instance: Nanny | Worker | None, owner: type) -> Any:
if instance is None:
# This is triggered by Sphinx
return None # pragma: nocover
_warn_dep... | DeprecatedMemoryManagerAttribute |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_class.py | {
"start": 383,
"end": 6580
} | 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... | V1IngressClass |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/rpc_test.py | {
"start": 2752,
"end": 3680
} | class ____:
def __init__(self, world_size):
self.world_size = world_size
def get_worker_infos(self):
return {
WorkerInfo(name=worker_name(rank), id=rank)
for rank in range(self.world_size)
}
def _stub_construct_rpc_backend_options_handler(**kwargs):
return ... | StubRpcAgent |
python | pennersr__django-allauth | allauth/mfa/recovery_codes/internal/auth.py | {
"start": 218,
"end": 3684
} | class ____:
def __init__(self, instance: Authenticator) -> None:
self.instance = instance
@classmethod
def activate(cls, user) -> "RecoveryCodes":
instance = Authenticator.objects.filter(
user=user, type=Authenticator.Type.RECOVERY_CODES
).first()
if instance:
... | RecoveryCodes |
python | huggingface__transformers | src/transformers/models/univnet/modeling_univnet.py | {
"start": 1698,
"end": 3581
} | class ____(nn.Module):
"""
Implementation of the residual block for the kernel predictor network inside each location variable convolution
block (LVCBlock).
Parameters:
config: (`UnivNetConfig`):
Config for the `UnivNetModel` model.
"""
def __init__(
self,
c... | UnivNetKernelPredictorResidualBlock |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.