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 | mkdocs__mkdocs | mkdocs/livereload/__init__.py | {
"start": 12888,
"end": 13530
} | class ____(wsgiref.simple_server.WSGIRequestHandler):
def log_request(self, code="-", size="-"):
level = logging.DEBUG if str(code) == "200" else logging.WARNING
log.log(level, f'"{self.requestline}" code {code}')
def log_message(self, format, *args):
log.debug(format, *args)
def _tim... | _Handler |
python | bokeh__bokeh | src/bokeh/sphinxext/_internal/bokeh_sampledata_xref.py | {
"start": 1958,
"end": 2149
} | class ____(nodes.General, nodes.Element):
def __init__(self, *args, **kwargs):
self.subfolder = kwargs.pop("subfolder", None)
super().__init__(*args, **kwargs)
| gallery_xrefs |
python | getsentry__sentry | src/sentry/api/serializers/models/dashboard.py | {
"start": 21664,
"end": 21842
} | class ____(TypedDict, total=False):
environment: list[str]
period: str
utc: str
expired: bool
start: datetime
end: datetime
| DashboardDetailsResponseOptional |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/side_channel/stats_side_channel.py | {
"start": 274,
"end": 736
} | class ____(Enum):
# Values within the summary period are averaged before reporting.
AVERAGE = 0
# Only the most recent value is reported.
MOST_RECENT = 1
# Values within the summary period are summed up before reporting.
SUM = 2
# All values within a summary period are reported as a histo... | StatsAggregationMethod |
python | python__mypy | mypyc/transform/lower.py | {
"start": 915,
"end": 1344
} | class ____(IRTransform):
def visit_primitive_op(self, op: PrimitiveOp) -> Value | None:
# The lowering implementation functions of various primitive ops are stored
# in a registry, which is populated using function decorators. The name
# of op (such as "int_eq") is used as the key.
l... | LoweringVisitor |
python | crytic__slither | slither/detectors/functions/unimplemented.py | {
"start": 864,
"end": 4452
} | class ____(AbstractDetector):
"""
Unimplemented functions detector
"""
ARGUMENT = "unimplemented-functions"
HELP = "Unimplemented functions"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Do... | UnimplementedFunctionDetection |
python | doocs__leetcode | solution/0100-0199/0122.Best Time to Buy and Sell Stock II/Solution2.py | {
"start": 0,
"end": 345
} | class ____:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
f = [[0] * 2 for _ in range(n)]
f[0][0] = -prices[0]
for i in range(1, n):
f[i][0] = max(f[i - 1][0], f[i - 1][1] - prices[i])
f[i][1] = max(f[i - 1][1], f[i - 1][0] + prices[i])
... | Solution |
python | mlflow__mlflow | mlflow/genai/judges/tools/get_trace_info.py | {
"start": 568,
"end": 1952
} | class ____(JudgeTool):
"""
Tool for retrieving high-level metadata about a trace.
This provides trace metadata like ID, timing, state, and location without
the detailed span data.
"""
@property
def name(self) -> str:
return ToolNames.GET_TRACE_INFO
def get_definition(self) -> ... | GetTraceInfoTool |
python | coleifer__peewee | tests/keys.py | {
"start": 294,
"end": 423
} | class ____(TestModel):
title = CharField()
package = ForeignKeyField(Package, Package.barcode, backref='items')
| PackageItem |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 79040,
"end": 80117
} | class ____(SocketDummyServerTestCase):
def test_chunked_head_response_does_not_hang(self) -> None:
self.start_response_handler(
b"HTTP/1.1 200 OK\r\n"
b"Transfer-Encoding: chunked\r\n"
b"Content-type: text/plain\r\n"
b"\r\n"
)
with HTTPConnecti... | TestHEAD |
python | joke2k__faker | faker/providers/credit_card/ru_RU/__init__.py | {
"start": 210,
"end": 3174
} | class ____(CreditCardProvider):
"""Implement credit card provider for ``ru_RU`` locale.
For all methods that take ``card_type`` as an argument, a random card type
will be used if the supplied value is ``None``. The list of valid card types
includes ``'amex'``, ``'maestro'``, ``'mastercard'``, ``'mir'``... | Provider |
python | simonw__datasette | datasette/views/special.py | {
"start": 27054,
"end": 33170
} | class ____(BaseView):
name = "api_explorer"
has_json_alternate = False
async def example_links(self, request):
databases = []
for name, db in self.ds.databases.items():
database_visible, _ = await self.ds.check_visibility(
request.actor,
action="v... | ApiExplorerView |
python | huggingface__transformers | tests/utils/test_cache_utils.py | {
"start": 25314,
"end": 37562
} | class ____(unittest.TestCase):
"""Cache tests that rely on `torch.export()` and model loading"""
@pytest.mark.torch_export_test
def test_dynamic_cache_exportability(self):
model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM")
model = model.eval()... | CacheExportIntegrationTest |
python | scikit-learn__scikit-learn | sklearn/feature_extraction/text.py | {
"start": 17918,
"end": 31900
} | class ____(
TransformerMixin, _VectorizerMixin, BaseEstimator, auto_wrap_output_keys=None
):
r"""Convert a collection of text documents to a matrix of token occurrences.
It turns a collection of text documents into a scipy.sparse matrix holding
token occurrence counts (or binary occurrence information)... | HashingVectorizer |
python | kamyu104__LeetCode-Solutions | Python/check-for-contradictions-in-equations.py | {
"start": 1513,
"end": 1967
} | class ____(object):
def checkContradictions(self, equations, values):
"""
:type equations: List[List[str]]
:type values: List[float]
:rtype: bool
"""
EPS = 1e-5
uf = UnionFind()
return any(not uf.union_set(a, b, k) and abs(uf.query_set(a, b)-k) >= EPS ... | Solution |
python | getsentry__sentry | src/sentry/integrations/source_code_management/repository.py | {
"start": 11275,
"end": 11804
} | class ____(ABC):
base_url: str
@abstractmethod
def check_file(self, repo: Repository, path: str, version: str | None) -> object | None:
"""Check if the file exists. Currently used for stacktrace linking and CODEOWNERS."""
raise NotImplementedError
@abstractmethod
def get_file(
... | RepositoryClient |
python | run-llama__llama_index | llama-index-utils/llama-index-utils-qianfan/llama_index/utils/qianfan/apis.py | {
"start": 716,
"end": 925
} | class ____(BaseModel):
"""
All model service items.
"""
common: List[ServiceItem]
"""built-in model service"""
custom: List[ServiceItem]
"""custom model service"""
| ServiceListResult |
python | kamyu104__LeetCode-Solutions | Python/validate-stack-sequences.py | {
"start": 29,
"end": 437
} | class ____(object):
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
i = 0
s = []
for v in pushed:
s.append(v)
while s and i < len(popped) and s[-1] == popped... | Solution |
python | ray-project__ray | python/ray/serve/tests/unit/test_proxy.py | {
"start": 26906,
"end": 32807
} | class ____:
"""Test ProxyRouter.match_route_pattern functionality."""
@pytest.fixture
def mock_get_handle(self):
def _get_handle(endpoint: DeploymentID, info: EndpointInfo):
return MockDeploymentHandle(deployment_name=endpoint.name)
return _get_handle
def test_match_route_... | TestProxyRouterMatchRoutePattern |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/typing_extensions/test_backported_types.py | {
"start": 6800,
"end": 7770
} | class ____(Book):
genre: Required[str]
rating: NotRequired[str]
@pytest.mark.parametrize(
"check,condition",
[
pytest.param(
assert_all_examples,
lambda novel: "author" in novel,
id="author-is-required",
),
pytest.param(
assert_al... | Novel |
python | getsentry__sentry | tests/sentry/rules/filters/test_issue_occurrences.py | {
"start": 205,
"end": 1371
} | class ____(RuleTestCase):
rule_cls = IssueOccurrencesFilter
def setUp(self) -> None:
super().setUp()
self.event.group.times_seen_pending = 0
def test_compares_correctly(self) -> None:
event = self.get_event()
value = 10
data = {"value": str(value)}
rule = s... | IssueOccurrencesTest |
python | catalyst-team__catalyst | tests/catalyst/callbacks/test_profiler.py | {
"start": 1105,
"end": 1475
} | class ____(nn.Module):
"""Docs."""
def __init__(self, in_features, out_features):
"""Docs."""
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.layers = nn.Linear(in_features, out_features)
def forward(self, batch):
"""D... | DummyModel |
python | python-poetry__poetry | src/poetry/console/commands/update.py | {
"start": 352,
"end": 1788
} | class ____(InstallerCommand):
name = "update"
description = (
"Update the dependencies as according to the <comment>pyproject.toml</> file."
)
arguments: ClassVar[list[Argument]] = [
argument("packages", "The packages to update", optional=True, multiple=True)
]
options: ClassVar... | UpdateCommand |
python | redis__redis-py | tests/test_pubsub.py | {
"start": 29434,
"end": 29656
} | class ____:
def test_channel_subscribe(self, r):
r = redis.Redis(host="localhost", port=6390)
p = r.pubsub()
with pytest.raises(ConnectionError):
p.subscribe("foo")
| TestPubSubRedisDown |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_details.py | {
"start": 28589,
"end": 64782
} | class ____(OrganizationDetailsTestBase):
method = "put"
def test_simple(self) -> None:
self.get_success_response(self.organization.slug, name="hello world", slug="foobar")
org = Organization.objects.get(id=self.organization.id)
assert org.name == "hello world"
assert org.slug =... | OrganizationUpdateTest |
python | huggingface__transformers | src/transformers/models/vit_msn/modeling_vit_msn.py | {
"start": 14724,
"end": 15266
} | class ____(nn.Module):
def __init__(self, config: ViTMSNConfig):
super().__init__()
self.config = config
self.layer = nn.ModuleList([ViTMSNLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(self, hidden_states: torch.Tensor) ... | ViTMSNEncoder |
python | ray-project__ray | python/ray/data/_internal/execution/progress_manager.py | {
"start": 1220,
"end": 2768
} | class ____(str, Enum):
NONE = "NONE" # no-op
GLOBAL_ONLY = "GLOBAL_ONLY" # global progress
ALL = "ALL" # show everything
def show_op(self) -> bool:
return self == self.ALL
def is_enabled(self) -> bool:
return self != self.NONE
@classmethod
def get_mode(cls) -> "_Manager... | _ManagerMode |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 34794,
"end": 35340
} | class ____(TestCase):
def test_constructor(self):
inner = frozenset([1])
outer = OrderedSet([inner])
element = outer.pop()
self.assertEqual(type(element), frozenset)
outer.add(inner) # Rebuild OrderedSet of sets with .add method
outer.remove(inner)
self.asser... | TestSetOfSets |
python | automl__auto-sklearn | autosklearn/ensemble_building/manager.py | {
"start": 799,
"end": 15177
} | class ____(IncorporateRunResultCallback):
def __init__(
self,
backend: Backend,
dataset_name: str,
task: int,
metrics: Sequence[Scorer],
time_left_for_ensembles: float = np.inf,
max_iterations: int | None = None,
pynisher_context: str = "fork",
... | EnsembleBuilderManager |
python | huggingface__transformers | src/transformers/models/qwen2_moe/modeling_qwen2_moe.py | {
"start": 3357,
"end": 6363
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Qwen2MoeConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
sel... | Qwen2MoeRotaryEmbedding |
python | ansible__ansible | test/lib/ansible_test/_internal/provider/layout/__init__.py | {
"start": 2379,
"end": 5140
} | class ____(Layout):
"""Information about the current Ansible content being tested."""
def __init__(
self,
root: str,
paths: list[str],
plugin_paths: dict[str, str],
collection: t.Optional[CollectionDetail],
test_path: str,
results_path: str,
sanit... | ContentLayout |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 2169,
"end": 2276
} | class ____(SQLRole):
"""mixin indicating a role that results in strings"""
__slots__ = ()
| StringRole |
python | apache__airflow | providers/celery/src/airflow/providers/celery/executors/celery_executor_utils.py | {
"start": 9333,
"end": 11692
} | class ____:
"""
Wrapper class used to propagate exceptions to parent processes from subprocesses.
:param exception: The exception to wrap
:param exception_traceback: The stacktrace to wrap
"""
def __init__(self, exception: BaseException, exception_traceback: str):
self.exception = exce... | ExceptionWithTraceback |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 15089,
"end": 15791
} | class ____(Sky2PixProjection, Zenithal):
r"""
Slant orthographic projection - sky to pixel.
Corresponds to the ``SIN`` projection in FITS WCS.
See `Zenithal` for a definition of the full transformation.
The following transformation applies when :math:`\xi` and
:math:`\eta` are both zero.
... | Sky2Pix_SlantOrthographic |
python | tensorflow__tensorflow | tensorflow/python/tools/api/generator2/generator/generator.py | {
"start": 3961,
"end": 4643
} | class ____(Exception):
"""Exception for when two docstrings are registered to a single module."""
def _get_import_path(
file: str, file_prefixes_to_strip: Sequence[str], module_prefix: str
) -> str:
module_import_path = file
for prefix in file_prefixes_to_strip:
module_import_path = module_import_path.r... | DocExportedTwiceError |
python | Lightning-AI__lightning | tests/tests_pytorch/test_cli.py | {
"start": 24092,
"end": 26153
} | class ____(BoringDataModule):
def __init__(self, batch_size: int = 8):
super().__init__()
self.batch_size = batch_size
self.num_classes = 5 # only available after instantiation
def test_lightning_cli_link_arguments(cleandir):
class MyLightningCLI(LightningCLI):
def add_argumen... | BoringDataModuleBatchSizeAndClasses |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 4063,
"end": 4239
} | class ____(PostWithUniqFieldCompat):
new_field = models.CharField(max_length=10)
class Meta:
app_label = "django_extensions"
| InheritedFromPostWithUniqFieldCompat |
python | lepture__authlib | authlib/jose/rfc7517/jwk.py | {
"start": 122,
"end": 2029
} | class ____:
JWK_KEY_CLS = {}
@classmethod
def generate_key(cls, kty, crv_or_size, options=None, is_private=False):
"""Generate a Key with the given key type, curve name or bit size.
:param kty: string of ``oct``, ``RSA``, ``EC``, ``OKP``
:param crv_or_size: curve name or bit size
... | JsonWebKey |
python | pandas-dev__pandas | asv_bench/benchmarks/groupby.py | {
"start": 16435,
"end": 17340
} | class ____:
"""
Benchmarks specifically targeting our cython aggregation algorithms
(using a big enough dataframe with simple key, so a large part of the
time is actually spent in the grouped aggregation).
"""
param_names = ["dtype", "method"]
params = [
["float64"],
[
... | GroupByCythonAgg |
python | kubernetes-client__python | kubernetes/client/models/v1alpha1_named_rule_with_operations.py | {
"start": 383,
"end": 10860
} | 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... | V1alpha1NamedRuleWithOperations |
python | optuna__optuna | optuna/storages/journal/_file.py | {
"start": 12279,
"end": 12589
} | class ____(JournalFileOpenLock):
pass
@deprecated_class(
deprecated_version="4.0.0",
removed_version="6.0.0",
name="The import path :class:`~optuna.storages.JournalFileSymlinkLock`",
text="Use :class:`~optuna.storages.journal.JournalFileSymlinkLock` instead.",
)
| DeprecatedJournalFileOpenLock |
python | huggingface__transformers | src/transformers/models/starcoder2/modeling_starcoder2.py | {
"start": 22072,
"end": 22363
} | class ____(GenericForTokenClassification, Starcoder2PreTrainedModel):
pass
__all__ = [
"Starcoder2ForCausalLM",
"Starcoder2Model",
"Starcoder2PreTrainedModel",
"Starcoder2ForSequenceClassification",
"Starcoder2ForTokenClassification",
]
| Starcoder2ForTokenClassification |
python | django__django | django/contrib/auth/forms.py | {
"start": 9497,
"end": 10492
} | class ____(forms.ModelForm):
password = ReadOnlyPasswordHashField(
label=_("Password"),
help_text=_(
"Raw passwords are not stored, so there is no way to see "
"the user’s password."
),
)
class Meta:
model = User
fields = "__all__"
fie... | UserChangeForm |
python | google__pytype | pytype/tools/traces/source_test.py | {
"start": 267,
"end": 608
} | class ____(unittest.TestCase):
def test_instantiate(self):
with self.assertRaises(TypeError):
source.AbstractTrace(None, None, None)
self.assertIsInstance(_FakeTrace(None, None, None), _FakeTrace)
def test_repr(self):
trace = _FakeTrace("LOAD_NAME", "x", (["t"],))
print(repr(trace)) # smoke... | AbstractTraceTest |
python | facebook__pyre-check | tools/upgrade/commands/tests/fixme_test.py | {
"start": 429,
"end": 1561
} | class ____(unittest.TestCase):
def test_run(self) -> None:
arguments = MagicMock()
arguments.error_source = ErrorSource.STDIN
mock_errors = MagicMock()
arguments.fixme_threshold = None
with patch.object(
errors.Errors, "from_stdin", return_value=mock_errors
... | FixmeTest |
python | bokeh__bokeh | src/bokeh/util/compiler.py | {
"start": 4195,
"end": 4519
} | class ____(Inline):
''' An implementation for a Bokeh custom model in TypeScript
Example:
.. code-block:: python
class MyExt(Model):
__implementation__ = TypeScript(""" <TypeScript code> """)
'''
@property
def lang(self) -> str:
return "typescript"
| TypeScript |
python | google__python-fire | fire/docstrings_fuzz_test.py | {
"start": 817,
"end": 1100
} | class ____(testutils.BaseTestCase):
@settings(max_examples=1000, deadline=1000)
@given(st.text(min_size=1))
@example('This is a one-line docstring.')
def test_fuzz_parse(self, value):
docstrings.parse(value)
if __name__ == '__main__':
testutils.main()
| DocstringsFuzzTest |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 30793,
"end": 43617
} | class ____(TestCase):
"""
Test the np.array constructor
"""
def test_from_attribute(self):
class x:
def __array__(self, dtype=None):
pass
assert_raises(ValueError, np.array, x())
def test_from_string(self):
types = np.typecodes["AllInteger"] + n... | TestCreation |
python | PyCQA__pycodestyle | testing/data/E30not.py | {
"start": 1489,
"end": 2452
} | class ____(object):
pass
if __name__ == '__main__':
foo()
#: Okay
classification_errors = None
#: Okay
defined_properly = True
#: Okay
defaults = {}
defaults.update({})
#: Okay
def foo(x):
classification = x
definitely = not classification
#: E704:3:1 E704:4:1
# This emits the (ignored-by-default) E70... | Bar |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vector_index.py | {
"start": 2978,
"end": 3167
} | class ____(_VectorIndexConfigCreate):
skip: bool = True
@staticmethod
def vector_index_type() -> VectorIndexType:
return VectorIndexType.HNSW
| _VectorIndexConfigSkipCreate |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 130092,
"end": 130884
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("ray.RayHook"))
def test_execute(self, mock_hook):
op = GetRayClusterOperator(
task_id=TASK_ID,
cluster_id=TEST_CLUSTER_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
location... | TestVertexAIGetRayClusterOperator |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/run_event.py | {
"start": 743,
"end": 1076
} | class ____(BaseModel):
"""Single run event model."""
run_id: str
message: str
timestamp: str # ISO 8601 timestamp
level: RunEventLevel
step_key: Optional[str] = None
event_type: Optional[str] = None
error: Optional[DgApiErrorInfo] = None
class Config:
from_attributes = Tru... | DgApiRunEvent |
python | django__django | django/db/models/functions/datetime.py | {
"start": 4323,
"end": 4378
} | class ____(Extract):
lookup_name = "year"
| ExtractYear |
python | cython__cython | tests/run/ext_auto_richcmp.py | {
"start": 7108,
"end": 7951
} | class ____(X):
"""
>>> a = ClassLtGtInherited(1)
>>> b = ClassLtGtInherited(2)
>>> c = ClassLtGtInherited(1)
>>> a < b
True
>>> b > a
True
>>> b < a
False
>>> a > b
False
>>> a < c
False
>>> c > a
False
>>> c < a
False
>>> a > c
False
... | ClassLtGtInherited |
python | encode__django-rest-framework | rest_framework/throttling.py | {
"start": 5757,
"end": 6370
} | class ____(SimpleRateThrottle):
"""
Limits the rate of API calls that may be made by a given user.
The user id will be used as a unique cache key if the user is
authenticated. For anonymous requests, the IP address of the request will
be used.
"""
scope = 'user'
def get_cache_key(self... | UserRateThrottle |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess1.py | {
"start": 1930,
"end": 2448
} | class ____(Generic[_T, _P, _R]):
def __init__(self, func: Callable[Concatenate[_T, _P], Awaitable[_R]]) -> None:
self.func = func
@overload
def __get__(self, obj: None, objtype: type[_T]) -> "Decorator[_T, _P, _R]": ...
@overload
def __get__(
self, obj: _T, objtype: type[_T] | None... | Decorator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_data_bar06.py | {
"start": 345,
"end": 7437
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with conditional formatting."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle... | TestAssembleWorksheet |
python | huggingface__transformers | src/transformers/models/evolla/modular_evolla.py | {
"start": 5816,
"end": 5876
} | class ____(EsmIntermediate):
pass
| EvollaSaProtIntermediate |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass3.py | {
"start": 387,
"end": 499
} | class ____(MixinA, MixinB, MixinC):
pass
# This should not generate an error
trainer = Trainer_1a()
| Trainer_1a |
python | skorch-dev__skorch | skorch/tests/callbacks/test_training.py | {
"start": 39935,
"end": 48286
} | class ____:
@pytest.fixture(params=['torch', 'safetensors'])
def use_safetensors(self, request):
return request.param == 'safetensors'
@pytest.fixture
def trainendcheckpoint_cls(self):
from skorch.callbacks import TrainEndCheckpoint
return TrainEndCheckpoint
@pytest.fixture... | TestTrainEndCheckpoint |
python | miyuchina__mistletoe | test/test_block_token.py | {
"start": 161,
"end": 893
} | class ____(unittest.TestCase):
def setUp(self):
self.addCleanup(lambda: span_token._token_types.__setitem__(-1, span_token.RawText))
patcher = patch('mistletoe.span_token.RawText')
self.mock = patcher.start()
span_token._token_types[-1] = self.mock
self.addCleanup(patcher.sto... | TestToken |
python | apache__airflow | providers/alibaba/tests/unit/alibaba/cloud/operators/test_oss.py | {
"start": 1340,
"end": 1868
} | class ____:
@mock.patch("airflow.providers.alibaba.cloud.operators.oss.OSSHook")
def test_execute(self, mock_hook):
operator = OSSCreateBucketOperator(
task_id=MOCK_TASK_ID, region=MOCK_REGION, bucket_name=MOCK_BUCKET, oss_conn_id=MOCK_OSS_CONN_ID
)
operator.execute(None)
... | TestOSSCreateBucketOperator |
python | pallets__quart | src/quart/logging.py | {
"start": 641,
"end": 2197
} | class ____(QueueHandler):
"""Custom QueueHandler that skips record preparation.
There is no need to prepare records that go into a local, in-process queue,
we can skip that process and minimise the cost of logging further.
"""
def prepare(self, record: LogRecord) -> LogRecord:
return recor... | LocalQueueHandler |
python | ray-project__ray | release/nightly_tests/multimodal_inference_benchmarks/large_image_embedding/daft_main.py | {
"start": 1421,
"end": 2692
} | class ____:
def __init__(self):
self._device = "cuda" if torch.cuda.is_available() else "cpu"
self._model = ViTForImageClassification.from_pretrained(
"google/vit-base-patch16-224"
).to(self._device)
def __call__(self, image_column) -> np.ndarray:
image_ndarray = np.... | Infer |
python | sanic-org__sanic | tests/typing/samples/app_fully_custom.py | {
"start": 58,
"end": 97
} | class ____(Config):
pass
| CustomConfig |
python | readthedocs__readthedocs.org | readthedocs/embed/v3/views.py | {
"start": 918,
"end": 1353
} | class ____(IsAuthorizedToViewVersion):
"""
Checks if the user from the request has permissions to get content from the version.
If the URL is from an external site, we return ``True``,
since we don't have a project to check for.
"""
def has_permission(self, request, view):
if view.exte... | IsAuthorizedToGetContenFromVersion |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/spark/parquet_asset.py | {
"start": 540,
"end": 1800
} | class ____(_SparkGenericFilePathAssetMixin):
# The options below are available as of spark v3.4.0
# See https://spark.apache.org/docs/latest/sql-data-sources-parquet.html for more info.
merge_schema: Optional[Union[bool, str]] = Field(None, alias="mergeSchema")
datetime_rebase_mode: Optional[Literal["EX... | ParquetAssetBase |
python | apache__airflow | providers/google/src/airflow/providers/google/suite/sensors/drive.py | {
"start": 1163,
"end": 3334
} | class ____(BaseSensorOperator):
"""
Checks for the existence of a file in Google Cloud Storage.
:param folder_id: The Google drive folder where the file is.
:param file_name: The name of the file to check in Google Drive
:param drive_id: Optional. The id of the shared Google Drive in which the file... | GoogleDriveFileExistenceSensor |
python | python-openxml__python-docx | src/docx/oxml/section.py | {
"start": 15307,
"end": 20395
} | class ____:
"""Generates the block-item XML elements in a section.
A block-item element is a `CT_P` (paragraph) or a `CT_Tbl` (table).
"""
_compiled_blocks_xpath: etree.XPath | None = None
_compiled_count_xpath: etree.XPath | None = None
def __init__(self, sectPr: CT_SectPr):
self._se... | _SectBlockElementIterator |
python | getsentry__sentry | src/sentry/flags/endpoints/logs.py | {
"start": 997,
"end": 1254
} | class ____(TypedDict):
id: int
action: str
createdAt: datetime
createdBy: str | None
createdByType: str | None
flag: str
provider: str | None
tags: dict[str, Any]
@register(FlagAuditLogModel)
| FlagAuditLogModelSerializerResponse |
python | oauthlib__oauthlib | examples/device_code_flow.py | {
"start": 2923,
"end": 7364
} | class ____:
@staticmethod
def create_device_authorization_response(request):
server = DeviceApplicationServer(interval=5, verification_uri="https://example.com/device")
return server.create_device_authorization_response(request)
def post(self, request):
headers, data, status = self.... | DeviceAuthorizationEndpoint |
python | django__django | tests/custom_pk/tests.py | {
"start": 4724,
"end": 7425
} | class ____(TestCase):
def test_custom_pk_create(self):
"""
New objects can be created both with pk and the custom name
"""
Employee.objects.create(employee_code=1234, first_name="Foo", last_name="Bar")
Employee.objects.create(pk=1235, first_name="Foo", last_name="Baz")
... | CustomPKTests |
python | astropy__astropy | astropy/table/tests/test_table.py | {
"start": 10439,
"end": 12161
} | class ____:
def test_simple(self, table_types):
cols = [
table_types.Column(name="a", data=[1, 2, 3]),
table_types.Column(name="b", data=[4, 5, 6], dtype=np.float32),
]
t = table_types.Table(cols)
assert np.all(t["a"].data == np.array([1, 2, 3]))
asser... | TestNewFromColumns |
python | ansible__ansible | test/lib/ansible_test/_internal/host_configs.py | {
"start": 2941,
"end": 4264
} | class ____(metaclass=abc.ABCMeta):
"""Configuration for Python."""
version: t.Optional[str] = None
path: t.Optional[str] = None
@property
def tuple(self) -> tuple[int, ...]:
"""Return the Python version as a tuple."""
return str_to_version(self.version)
@property
def major... | PythonConfig |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 54379,
"end": 55626
} | class ____(Response):
"""
Response of events.get_debug_image_sample endpoint.
"""
_service = "events"
_action = "get_debug_image_sample"
_version = "2.13"
_schema = {
"$ref": "#/definitions/debug_image_sample_reposnse",
"definitions": {
"debug_image_sample_repos... | GetDebugImageSampleResponse |
python | pytorch__pytorch | test/distributed/checkpoint/test_checkpoint.py | {
"start": 2298,
"end": 4693
} | class ____(ShardedTensorTestBase):
@property
def world_size(self) -> int:
return 2
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(2)
@requires_accelerator_dist_backend()
def test_tensor_metadata_with_missing_rank_spec(self) -> None:
spec = ChunkShardingSpec(
dim=0,
... | TestDistributedCheckpointing |
python | sphinx-doc__sphinx | sphinx/theming.py | {
"start": 4889,
"end": 15394
} | class ____:
"""A factory class for HTML Themes."""
def __init__(
self,
*,
confdir: Path,
app: Sphinx,
config: Config,
registry: SphinxComponentRegistry,
) -> None:
self._app = app
self._confdir = confdir
self._themes = registry.html_th... | HTMLThemeFactory |
python | plotly__plotly.py | plotly/graph_objs/funnel/marker/colorbar/title/_font.py | {
"start": 233,
"end": 9944
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "funnel.marker.colorbar.title"
_path_str = "funnel.marker.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 13013,
"end": 13722
} | class ____(Stmt):
"""A node that represents the from import tag. It's important to not
pass unsafe names to the name attribute. The compiler translates the
attribute lookups directly into getattr calls and does *not* use the
subscript callback of the interface. As exported variables may not
start... | FromImport |
python | tensorflow__tensorflow | tensorflow/python/util/decorator_utils_test.py | {
"start": 4083,
"end": 5567
} | class ____(test.TestCase):
def testCachedClassProperty(self):
log = [] # log all calls to `MyClass.value`.
class MyClass(object):
@decorator_utils.cached_classproperty
def value(cls): # pylint: disable=no-self-argument
log.append(cls)
return cls.__name__
class MySubclass(... | CachedClassPropertyTest |
python | pallets__werkzeug | src/werkzeug/routing/map.py | {
"start": 14732,
"end": 36516
} | class ____:
"""Returned by :meth:`Map.bind` or :meth:`Map.bind_to_environ` and does
the URL matching and building based on runtime information.
"""
def __init__(
self,
map: Map,
server_name: str,
script_name: str,
subdomain: str | None,
url_scheme: str,
... | MapAdapter |
python | getsentry__sentry | src/sentry/api/endpoints/project_transaction_threshold_override.py | {
"start": 2179,
"end": 5880
} | class ____(OrganizationEventsV2EndpointBase):
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
"GET": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
permission_classes = (ProjectTransactionThresholdOverridePermission,)
def get_project(self, request: Request,... | ProjectTransactionThresholdOverrideEndpoint |
python | numba__llvmlite | llvmlite/ir/types.py | {
"start": 6282,
"end": 7676
} | class ____(Type):
"""
The type for functions.
"""
def __init__(self, return_type, args, var_arg=False):
self.return_type = return_type
self.args = tuple(args)
self.var_arg = var_arg
def _to_string(self):
if self.args:
strargs = ', '.join([str(a) for a in... | FunctionType |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/job/asset_layer.py | {
"start": 790,
"end": 987
} | class ____:
"""Data that relates asset-level information to a node in the execution graph."""
node_handle: NodeHandle
assets_def: "AssetsDefinition"
@record(checked=False)
| AssetLayerData |
python | huggingface__transformers | src/transformers/models/mlcd/modular_mlcd.py | {
"start": 7317,
"end": 8032
} | class ____(CLIPVisionEmbeddings):
def __init__(self, config: MLCDVisionConfig):
super().__init__(config)
del self.position_embedding
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
batch_size = pixel_values.shape[0]
target_dtype = self.patch_embedding.weight.... | MLCDVisionEmbeddings |
python | google__pytype | pytype/pytd/codegen/function.py | {
"start": 665,
"end": 1354
} | class ____:
"""Internal representation of function parameters."""
name: str
type: pytd.Type | None = None
default: Any = None
kind: pytd.ParameterKind = pytd.ParameterKind.REGULAR
def to_pytd(self) -> pytd.Parameter:
"""Return a pytd.Parameter object for a normal argument."""
if self.default is no... | Param |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/base.py | {
"start": 44330,
"end": 45531
} | class ____(sqltypes.VARBINARY, sqltypes.LargeBinary):
"""The MSSQL VARBINARY type.
This type adds additional features to the core :class:`_types.VARBINARY`
type, including "deprecate_large_types" mode where
either ``VARBINARY(max)`` or IMAGE is rendered, as well as the SQL
Server ``FILESTREAM`` opt... | VARBINARY |
python | tensorflow__tensorflow | third_party/xla/build_tools/ci/build.py | {
"start": 4992,
"end": 27776
} | class ____:
"""Class representing a build of XLA."""
_builds: ClassVar[Dict[BuildType, "Build"]] = {}
type_: BuildType
repo: str
target_patterns: Tuple[str, ...]
subcommand: str = "test"
configs: Tuple[str, ...] = ()
build_tag_filters: Tuple[str, ...] = ()
test_tag_filters: Tuple[str, ...] = ()
ac... | Build |
python | ethereum__web3.py | web3/types.py | {
"start": 6530,
"end": 6881
} | class ____(SubscriptionResponse):
result: GethSyncingSubscriptionResult
EthSubscriptionParams = Union[
BlockTypeSubscriptionResponse,
TransactionTypeSubscriptionResponse,
LogsSubscriptionResponse,
SyncingSubscriptionResponse,
GethSyncingSubscriptionResponse,
]
RPCId = Optional[Union[int, str]... | GethSyncingSubscriptionResponse |
python | apache__airflow | airflow-core/tests/unit/utils/test_retries.py | {
"start": 1090,
"end": 3951
} | class ____:
def test_retry_db_transaction_with_passing_retries(self):
"""Test that retries can be passed to decorator"""
mock_obj = mock.MagicMock()
mock_session = mock.MagicMock()
op_error = OperationalError(statement=mock.ANY, params=mock.ANY, orig=mock.ANY)
@retry_db_tran... | TestRetries |
python | crytic__slither | slither/solc_parsing/variables/top_level_variable.py | {
"start": 468,
"end": 1446
} | class ____(VariableDeclarationSolc, CallerContextExpression):
def __init__(
self,
variable: TopLevelVariable,
variable_data: Dict,
slither_parser: "SlitherCompilationUnitSolc",
) -> None:
super().__init__(variable, variable_data)
self._slither_parser = slither_par... | TopLevelVariableSolc |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_quantile.py | {
"start": 375,
"end": 26936
} | class ____:
@pytest.mark.parametrize(
"df,expected",
[
[
DataFrame(
{
0: Series(pd.arrays.SparseArray([1, 2])),
1: Series(pd.arrays.SparseArray([3, 4])),
}
),
... | TestDataFrameQuantile |
python | django__django | tests/check_framework/test_security.py | {
"start": 4779,
"end": 5243
} | class ____(SimpleTestCase):
@override_settings(MIDDLEWARE=[])
def test_no_csrf_middleware(self):
"""
Warn if CsrfViewMiddleware isn't in MIDDLEWARE.
"""
self.assertEqual(csrf.check_csrf_middleware(None), [csrf.W003])
@override_settings(MIDDLEWARE=["django.middleware.csrf.Csr... | CheckCSRFMiddlewareTest |
python | ijl__orjson | test/test_non_str_keys.py | {
"start": 256,
"end": 9173
} | class ____:
def test_dict_keys_duplicate(self):
"""
OPT_NON_STR_KEYS serializes duplicate keys
"""
assert (
orjson.dumps({"1": True, 1: False}, option=orjson.OPT_NON_STR_KEYS)
== b'{"1":true,"1":false}'
)
def test_dict_keys_int(self):
asse... | TestNonStrKeyTests |
python | pypa__pip | src/pip/_vendor/packaging/version.py | {
"start": 1012,
"end": 1503
} | class ____(NamedTuple):
epoch: int
release: tuple[int, ...]
dev: tuple[str, int] | None
pre: tuple[str, int] | None
post: tuple[str, int] | None
local: LocalType | None
def parse(version: str) -> Version:
"""Parse the given version string.
>>> parse('1.0.dev1')
<Version('1.0.dev1'... | _Version |
python | django__django | django/core/signing.py | {
"start": 4983,
"end": 7869
} | class ____:
def __init__(
self, *, key=None, sep=":", salt=None, algorithm=None, fallback_keys=None
):
self.key = key or settings.SECRET_KEY
self.fallback_keys = (
fallback_keys
if fallback_keys is not None
else settings.SECRET_KEY_FALLBACKS
)
... | Signer |
python | great-expectations__great_expectations | tests/data_context/conftest.py | {
"start": 12034,
"end": 16743
} | class ____:
# TODO: GG 08232022 update signature to accept arbitrary content types
def __init__(
self,
json_data: JSONData,
status_code: int,
headers: Optional[Dict[str, str]] = None,
exc_to_raise: Optional[RequestError] = None,
) -> None:
self._json_data = js... | MockResponse |
python | fluentpython__example-code | 21-class-metaprog/evaltime.py | {
"start": 527,
"end": 992
} | class ____(ClassThree):
print('<[9]> ClassFour body')
def method_y(self):
print('<[10]> ClassFour.method_y')
if __name__ == '__main__':
print('<[11]> ClassOne tests', 30 * '.')
one = ClassOne()
one.method_x()
print('<[12]> ClassThree tests', 30 * '.')
three = ClassThree()
thre... | ClassFour |
python | python-openxml__python-docx | tests/parts/test_numbering.py | {
"start": 1768,
"end": 2566
} | class ____:
def it_knows_how_many_numbering_definitions_it_contains(self, len_fixture):
numbering_definitions, numbering_definition_count = len_fixture
assert len(numbering_definitions) == numbering_definition_count
# fixtures -------------------------------------------------------
@pytest... | Describe_NumberingDefinitions |
python | pola-rs__polars | py-polars/tests/unit/io/test_scan.py | {
"start": 2634,
"end": 33717
} | class ____:
path: Path
df: pl.DataFrame
def df_with_chunk_size_limit(df: pl.DataFrame, limit: int) -> pl.DataFrame:
return pl.concat(
(
df.slice(i * limit, min(limit, df.height - i * limit))
for i in range(ceil(df.height / limit))
),
rechunk=False,
)
@... | _DataFile |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.