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 | dagster-io__dagster | python_modules/libraries/dagster-deltalake/dagster_deltalake/config.py | {
"start": 533,
"end": 2052
} | class ____(Config):
"""Storage configuration for Microsoft Azure Blob or ADLS Gen 2 object store."""
provider: Literal["azure"] = "azure"
account_name: str
"""Storage account name"""
client_id: Optional[str] = None
"""Client ID for ID / secret based authentication."""
client_secret: Opti... | AzureConfig |
python | spack__spack | lib/spack/spack/vendor/jsonschema/validators.py | {
"start": 758,
"end": 3383
} | class ____(Exception):
"""
Raised when a Validators with non-default type checker is misused.
Asking one for DEFAULT_TYPES doesn't make sense, since type checkers
exist for the unrepresentable cases where DEFAULT_TYPES can't
represent the type relationship.
"""
def __str__(self):
r... | _DontDoThat |
python | kamyu104__LeetCode-Solutions | Python/maximum-xor-after-operations.py | {
"start": 48,
"end": 224
} | class ____(object):
def maximumXOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x, y: x|y, nums)
| Solution |
python | geekcomputers__Python | insta_monitering/insta_api.py | {
"start": 390,
"end": 1522
} | class ____(tornado.web.RequestHandler):
executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)
@run_on_executor
def background_task(self, user, tags, type, productId):
try:
instasubprocess(user=user, tags=tags, type=type, productId=productId)
except:
print("error::ba... | StartHandlerinsta |
python | python__mypy | mypy/suggestions.py | {
"start": 34297,
"end": 39110
} | class ____(TypeTranslator):
def visit_any(self, t: AnyType) -> Type:
if not t.missing_import_name:
return t.copy_modified(type_of_any=TypeOfAny.suggestion_engine)
else:
return t
def visit_type_alias_type(self, t: TypeAliasType) -> Type:
return t.copy_modified(arg... | MakeSuggestionAny |
python | pytorch__pytorch | torch/_dynamo/output_graph.py | {
"start": 18064,
"end": 117138
} | class ____(OutputGraphCommon):
"""
Wrapper class to hold outputs of InstructionTranslator. Mainly the
generated fx.Graph.
OutputGraph is 1:1 with a frame being processed. Each frame is associated
with some root InstructionTranslator. When user code calls a function,
we construct a InliningInst... | OutputGraph |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 41116,
"end": 41502
} | class ____(NLargest):
_parameters = ["frame", "n", "_columns", "ascending", "split_every"]
_defaults = {"n": 5, "_columns": None, "ascending": None, "split_every": None}
reduction_chunk = staticmethod(_nfirst)
reduction_aggregate = staticmethod(_nfirst)
@property
def chunk_kwargs(self):
... | NFirst |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 281829,
"end": 282156
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("DeploymentStatus", graphql_name="node")
| DeploymentStatusEdge |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass5.py | {
"start": 839,
"end": 1122
} | class ____:
x: int
def __eq__(self, x: "E") -> float:
return 1.23
def __lt__(self, x: "E") -> str:
return ""
foo1 = E(3) == E(3)
reveal_type(foo1, expected_text="float")
foo2 = E(3) < E(3)
reveal_type(foo2, expected_text="str")
@dataclass(order=True)
| E |
python | ZoranPandovski__al-go-rithms | data_structures/binarySearch_tree/Python/binary_search_tree.py | {
"start": 1124,
"end": 3705
} | class ____():
def __init__(self, key, value=None):
self.key = key
self.value = value
self.left = None
self.right = None
self.parent = None
# creating a function to visualize a tree easily
def display_keys(node, space='\t', level=0):
# print(node.key if node else... | BSTNode |
python | paramiko__paramiko | paramiko/kex_gex.py | {
"start": 10219,
"end": 10320
} | class ____(KexGex):
name = "diffie-hellman-group-exchange-sha256"
hash_algo = sha256
| KexGexSHA256 |
python | django__django | tests/backends/mysql/test_introspection.py | {
"start": 1399,
"end": 2727
} | class ____(TestCase):
databases = {"default", "other"}
def test_get_storage_engine(self):
table_name = "test_storage_engine"
create_sql = "CREATE TABLE %s (id INTEGER) ENGINE = %%s" % table_name
drop_sql = "DROP TABLE %s" % table_name
default_connection = connections["default"]
... | StorageEngineTests |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/utils_v1/export_output.py | {
"start": 7136,
"end": 8127
} | class ____(ExportOutput):
"""Represents the output of a generic prediction head.
A generic prediction need not be either a classification or a regression.
Named outputs must be provided as a dict from string to `Tensor`,
"""
_SINGLE_OUTPUT_DEFAULT_NAME = 'output'
def __init__(self, outputs):
"""Const... | PredictOutput |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/manager.py | {
"start": 321,
"end": 747
} | class ____(KernelRestarter, QtKernelRestarterMixin):
def start(self):
if self._timer is None:
self._timer = QtCore.QTimer()
self._timer.timeout.connect(self.poll)
self._timer.start(round(self.time_to_dead * 1000))
def stop(self):
self._timer.stop()
def poll... | QtKernelRestarter |
python | kamyu104__LeetCode-Solutions | Python/apple-redistribution-into-boxes.py | {
"start": 48,
"end": 434
} | class ____(object):
def minimumBoxes(self, apple, capacity):
"""
:type apple: List[int]
:type capacity: List[int]
:rtype: int
"""
capacity.sort(reverse=True)
total = sum(apple)
for i in xrange(len(capacity)):
total -= capacity[i]
... | Solution |
python | explosion__spaCy | spacy/lang/am/__init__.py | {
"start": 734,
"end": 830
} | class ____(Language):
lang = "am"
Defaults = AmharicDefaults
__all__ = ["Amharic"]
| Amharic |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/dagster_run.py | {
"start": 4812,
"end": 8635
} | class ____(NamedTupleSerializer["DagsterRun"]):
# serdes log
# * removed reexecution_config - serdes logic expected to strip unknown keys so no need to preserve
# * added pipeline_snapshot_id
# * renamed previous_run_id -> parent_run_id, added root_run_id
# * added execution_plan_snapshot_id
# *... | DagsterRunSerializer |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-orchestrate/test_flow_complex_topology.py | {
"start": 1386,
"end": 1768
} | class ____(Executor):
@requests
def bar(self, docs, **kwargs):
for doc in docs:
doc.text += 'bar'
def test_flow_to_flow():
with Flow().add(uses=FooExec) as external_flow:
with Flow().add(external=True, port=external_flow.port).add(uses=BarExec) as f:
docs = f.search... | BarExec |
python | django__django | tests/generic_views/test_base.py | {
"start": 10966,
"end": 15540
} | class ____(SimpleTestCase):
rf = RequestFactory()
def _assert_about(self, response):
response.render()
self.assertContains(response, "<h1>About</h1>")
def test_get(self):
"""
Test a view that simply renders a template on GET
"""
self._assert_about(AboutTempl... | TemplateViewTest |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/tests/llama_index/test_vectorstore.py | {
"start": 3326,
"end": 13278
} | class ____:
"""Integration tests for the AzurePGVectorStore implementation.
Covers table creation, initialization via parameters, CRUD operations,
and similarity queries against seeded data in the test database.
"""
def test_table_creation_success(
self, vectorstore: AzurePGVectorStore, ta... | TestAzurePGVectorStore |
python | ray-project__ray | python/ray/util/client/server/proxier.py | {
"start": 25728,
"end": 32810
} | class ____(ray_client_pb2_grpc.RayletDataStreamerServicer):
def __init__(self, proxy_manager: ProxyManager):
self.num_clients = 0
# dictionary mapping client_id's to the last time they connected
self.clients_last_seen: Dict[str, float] = {}
self.reconnect_grace_periods: Dict[str, flo... | DataServicerProxy |
python | django-haystack__django-haystack | haystack/query.py | {
"start": 350,
"end": 21870
} | class ____:
"""
Provides a way to specify search parameters and lazily load results.
Supports chaining (a la QuerySet) to narrow the search.
"""
def __init__(self, using=None, query=None):
# ``_using`` should only ever be a value other than ``None`` if it's
# been forced with the `... | SearchQuerySet |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-that-sum-of-the-prices-is-less-than-or-equal-to-k.py | {
"start": 1487,
"end": 2360
} | class ____(object):
def findMaximumNumber(self, k, x):
"""
:type k: int
:type x: int
:rtype: int
"""
def floor_log2(x):
return x.bit_length()-1
result = prefix_cnt = 0
while k >= prefix_cnt:
# l = result.bit_length()
... | Solution2 |
python | huggingface__transformers | src/transformers/models/fnet/tokenization_fnet.py | {
"start": 777,
"end": 3241
} | class ____(AlbertTokenizer):
"""
Construct an FNet tokenizer. Based on [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
This tokenizer inherits from [`AlbertTokenizer`] which contains most of the main methods. Users should refer to
this superclas... | FNetTokenizer |
python | ray-project__ray | python/ray/train/v2/xgboost/xgboost_trainer.py | {
"start": 461,
"end": 6853
} | class ____(DataParallelTrainer):
"""A Trainer for distributed data-parallel XGBoost training.
Example
-------
.. testcode::
import xgboost
import ray.data
import ray.train
from ray.train.xgboost import RayTrainReportCallback
from ray.train.xgboost import XGBoo... | XGBoostTrainer |
python | pypa__warehouse | tests/unit/oidc/models/test_core.py | {
"start": 1037,
"end": 6328
} | class ____:
def test_lookup_by_claims_raises(self):
with pytest.raises(NotImplementedError):
_core.OIDCPublisher.lookup_by_claims(pretend.stub(), pretend.stub())
def test_oidc_publisher_not_default_verifiable(self):
publisher = _core.OIDCPublisher(projects=[])
with pytest.r... | TestOIDCPublisher |
python | cython__cython | tests/run/methodmangling_unknown_names.py | {
"start": 58,
"end": 700
} | class ____(object):
def run(self):
"""
>>> Test().run()
NameError1
NameError2
found mangled
"""
try:
print(__something)
except NameError:
print("NameError1") # correct - shouldn't exist
globals()['__something'] = 'found... | Test |
python | spack__spack | lib/spack/spack/cmd/common/arguments.py | {
"start": 3733,
"end": 4442
} | class ____(argparse.Action):
"""Sets the value for maximum number of concurrent package builds
The value is set in the command line configuration scope so that
it can be retrieved using the spack.config API.
"""
def __call__(self, parser, namespace, concurrent_packages, option_string):
if ... | SetConcurrentPackages |
python | huggingface__transformers | tests/pipelines/test_pipelines_common.py | {
"start": 2446,
"end": 9150
} | class ____(unittest.TestCase):
@require_torch
def test_pipeline_iteration(self):
from torch.utils.data import Dataset
class MyDataset(Dataset):
data = [
"This is a test",
"This restaurant is great",
"This restaurant is awful",
... | CommonPipelineTest |
python | gevent__gevent | src/gevent/tests/test__greenlet.py | {
"start": 1731,
"end": 1781
} | class ____(ExpectedError):
pass
| ExpectedJoinError |
python | getsentry__sentry | src/sentry/rules/conditions/tagged_event.py | {
"start": 1198,
"end": 4003
} | class ____(EventCondition):
id = "sentry.rules.conditions.tagged_event.TaggedEventCondition"
label = "The event's tags match {key} {match} {value}"
form_fields = {
"key": {"type": "string", "placeholder": "key"},
"match": {"type": "choice", "choices": list(MATCH_CHOICES.items())},
"... | TaggedEventCondition |
python | aimacode__aima-python | csp.py | {
"start": 34977,
"end": 37146
} | class ____:
"""
A Constraint consists of:
scope : a tuple of variables
condition: a function that can applied to a tuple of values
for the variables.
"""
def __init__(self, scope, condition):
self.scope = scope
self.condition = condition
def __repr__(self):
r... | Constraint |
python | doocs__leetcode | solution/2200-2299/2239.Find Closest Number to Zero/Solution.py | {
"start": 0,
"end": 227
} | class ____:
def findClosestNumber(self, nums: List[int]) -> int:
ans, d = 0, inf
for x in nums:
if (y := abs(x)) < d or (y == d and x > ans):
ans, d = x, y
return ans
| Solution |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-legacy-office/llama_index/readers/legacy_office/reader.py | {
"start": 340,
"end": 8027
} | class ____(BaseReader):
"""
Legacy Office Reader for parsing old Office documents (.doc, etc.) using Apache Tika.
This reader uses Apache Tika to parse legacy Office documents like Word 97 (.doc) files.
It can use either a local Tika server or connect to a remote one.
Args:
tika_server_jar... | LegacyOfficeReader |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py | {
"start": 36029,
"end": 40428
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Qwen3VLMoeTextConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
... | Qwen3VLMoeTextRotaryEmbedding |
python | tensorflow__tensorflow | tensorflow/python/debug/wrappers/framework.py | {
"start": 8174,
"end": 9882
} | class ____:
"""Request from an on-run-start callback.
The caller of the callback can use this response object to specify what
action the debug-wrapper session actually takes on the run() call.
"""
def __init__(self,
action,
debug_urls,
debug_ops="DebugIdentity",
... | OnRunStartResponse |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 31522,
"end": 31637
} | class ____(Interface):
"""Interface representing a PEP 282 logger"""
ILogger = IDebugLogger # b/c
| IDebugLogger |
python | openai__openai-python | src/openai/types/evals/runs/output_item_list_response.py | {
"start": 1457,
"end": 1633
} | class ____(BaseModel):
content: str
"""The content of the message."""
role: str
"""The role of the message sender (e.g., system, user, developer)."""
| SampleInput |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 12467,
"end": 12582
} | class ____(VyperInternalException):
"""Constant folding logic cannot be applied to an AST node."""
| UnfoldableNode |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 9171,
"end": 9515
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layers = torch.nn.ModuleDict(
{
"0": torch.nn.Linear(10, 10),
}
)
def forward(self, x):
# TODO(future PR): handle more logic
x = self.layers["0"](x)
... | ModuleDict |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 55310,
"end": 55505
} | class ____(VegaLiteSchema):
"""AutosizeType schema wrapper."""
_schema = {"$ref": "#/definitions/AutosizeType"}
def __init__(self, *args):
super().__init__(*args)
| AutosizeType |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/representer.py | {
"start": 19408,
"end": 44563
} | class ____(SafeRepresenter):
# need to add type here and write out the .comment
# in serializer and emitter
def __init__(self, default_style=None, default_flow_style=None, dumper=None):
# type: (Any, Any, Any) -> None
if not hasattr(dumper, 'typ') and default_flow_style is None:
... | RoundTripRepresenter |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 6693,
"end": 6957
} | class ____(B):
def f(self):
C = B # Local variable C shadows the class name
return super(C, self).f() # Should NOT trigger UP008
# See: https://github.com/astral-sh/ruff/issues/20491
# UP008 should not apply when __class__ is a local variable
| C |
python | pytorch__pytorch | torch/_decomp/decompositions.py | {
"start": 1211,
"end": 181968
} | class ____(Enum):
NONE = 0
MEAN = 1
SUM = 2
# This wraps a decomposition and performs various type promotion logic within it, depending on the strategy provided
# We're currently reusing ELEMENTWISE_TYPE_PROMOTION_KIND, although some of the usages are on non-elementwise ops
# Will need to validate the non... | Reduction |
python | python__mypy | mypy/fastparse.py | {
"start": 73215,
"end": 84921
} | class ____:
def __init__(
self,
errors: Errors | None,
line: int = -1,
override_column: int = -1,
is_evaluated: bool = True,
) -> None:
self.errors = errors
self.line = line
self.override_column = override_column
self.node_stack: list[AST] ... | TypeConverter |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/integration_test/benchmarks/micro_benchmarks.py | {
"start": 1502,
"end": 5477
} | class ____(tf.test.Benchmark):
"""Main micro benchmark class."""
def _benchmark_and_report(
self,
name,
fn,
repeat=None,
number=None):
"""Run fn repeat * number times, report time, and return fastest time."""
# Can't make these default above since the flags may not have been p... | MicroBenchmarks |
python | ray-project__ray | release/ray_release/test.py | {
"start": 1730,
"end": 1946
} | class ____(enum.Enum):
"""
Overall state of the test
"""
JAILED = "jailed"
FAILING = "failing"
FLAKY = "flaky"
CONSITENTLY_FAILING = "consistently_failing"
PASSING = "passing"
| TestState |
python | encode__django-rest-framework | tests/authentication/migrations/0001_initial.py | {
"start": 76,
"end": 563
} | class ____(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CustomToken',
fields=[
('key', models.CharField(max_length=40, primary_ke... | Migration |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_length/invalid_length_returned.py | {
"start": 204,
"end": 306
} | class ____:
"""__len__ returns <type 'int'>"""
def __len__(self):
return 0
| FirstGoodLen |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink52.py | {
"start": 304,
"end": 857
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink52.xlsx")
def test_create_file(self):
"""
Test the creation of a simple XlsxWriter file with hyperlinks.
"""
... | TestCompareXLSXFiles |
python | pydantic__pydantic | tests/benchmarks/test_discriminated_unions.py | {
"start": 239,
"end": 324
} | class ____(BaseModel):
state_type: Literal['loop']
substate: AnyState
| LoopState |
python | allegroai__clearml | examples/hyperdatasets/create_qa_entries.py | {
"start": 1574,
"end": 12048
} | class ____(DataEntry):
def __init__(
self,
question: str,
answer: str,
*,
reference: Optional[str] = None,
tags: Optional[Iterable[str]] = None,
):
metadata = {
"question": question,
"answer": answer,
}
if reference:... | QADataEntry |
python | kamyu104__LeetCode-Solutions | Python/check-if-an-original-string-exists-given-two-encoded-strings.py | {
"start": 152,
"end": 3233
} | class ____(object):
def possiblyEquals(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
def general_possible_numbers(s): # Time: O(2^l), Space: O(2^l), l is the length of consecutive digits, and l is at most 3
dp = [set() for _ in xrange(le... | Solution |
python | walkccc__LeetCode | solutions/858. Mirror Reflection/858.py | {
"start": 0,
"end": 216
} | class ____:
def mirrorReflection(self, p: int, q: int) -> int:
while p % 2 == 0 and q % 2 == 0:
p //= 2
q //= 2
if p % 2 == 0:
return 2
if q % 2 == 0:
return 0
return 1
| Solution |
python | dask__distributed | distributed/http/worker/prometheus/core.py | {
"start": 505,
"end": 9538
} | class ____(PrometheusCollector):
server: Worker
def __init__(self, server: Worker):
super().__init__(server)
self.subsystem = "worker"
self.crick_available = True
try:
import crick # noqa: F401
except ImportError:
self.crick_available = False
... | WorkerMetricCollector |
python | falconry__falcon | e2e-tests/server/hub.py | {
"start": 2305,
"end": 2482
} | class ____:
def __init__(self, hub: Hub):
self._hub = hub
async def on_get(self, req: Request, resp: Response) -> None:
resp.sse = self._hub.events()
| Events |
python | docker__docker-py | tests/unit/api_test.py | {
"start": 2208,
"end": 3092
} | class ____(unittest.TestCase):
def setUp(self):
self.patcher = mock.patch.multiple(
'docker.api.client.APIClient',
get=fake_get,
post=fake_post,
put=fake_put,
delete=fake_delete,
_read_from_socket=fake_read_from_socket
)
... | BaseAPIClientTest |
python | astropy__astropy | astropy/units/tests/test_quantity_annotations.py | {
"start": 586,
"end": 9880
} | class ____:
"""Test Quantity[Unit] type annotation."""
def test_simple_annotation(self):
@u.quantity_input
def func(x: Quantity[u.m], y: str):
return x, y
i_q, i_str = 2 * u.m, "cool string"
o_q, o_str = func(i_q, i_str)
assert i_q == o_q
assert i_st... | TestQuantityUnitAnnotations |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_responses/ticket_metrics_response_builder.py | {
"start": 310,
"end": 1057
} | class ____(HttpResponseBuilder):
@classmethod
def stateful_ticket_metrics_response(cls) -> "TicketMetricsResponseBuilder":
return cls(find_template("stateful_ticket_metrics", __file__), FieldPath("ticket_metric"), CursorBasedPaginationStrategy())
@classmethod
def stateless_ticket_metrics_respon... | TicketMetricsResponseBuilder |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 125393,
"end": 127712
} | class ____:
def test_gamma(self):
gam = special.gamma(5)
assert_equal(gam,24.0)
def test_gammaln(self):
gamln = special.gammaln(3)
lngam = log(special.gamma(3))
assert_allclose(gamln, lngam, atol=1.5e-8, rtol=0)
def test_gammainccinv(self):
gccinv = special.... | TestGamma |
python | doocs__leetcode | solution/0600-0699/0600.Non-negative Integers without Consecutive Ones/Solution.py | {
"start": 0,
"end": 465
} | class ____:
def findIntegers(self, n: int) -> int:
@cache
def dfs(i: int, pre: int, limit: bool) -> int:
if i < 0:
return 1
up = (n >> i & 1) if limit else 1
ans = 0
for j in range(up + 1):
if pre and j:
... | Solution |
python | astropy__astropy | astropy/coordinates/tests/test_separation.py | {
"start": 666,
"end": 13309
} | class ____(NamedTuple):
"""
The coordinates the position angle and separations are relative to
are different for different tests.
"""
coord: BaseCoordinateFrame | SkyCoord
pytest_id: str
position_angle: u.Quantity
separation: u.Quantity
separation_3d: u.Quantity
reversed_positio... | SeparationExpectation |
python | PyCQA__pycodestyle | tests/test_blank_lines.py | {
"start": 2709,
"end": 3219
} | class ____(object):
pass
""")
self.assertEqual([
'E302:7:1', # another_function
'E302:14:1', # SomeCloseClass
], result)
def test_top_level_more_blank_lines(self):
"""
It will trigger an error when more 2 blank lines are found
before top level d... | AFarEnoughClass |
python | django-guardian__django-guardian | guardian/testapp/tests/test_mixins.py | {
"start": 965,
"end": 1080
} | class ____(PermissionRequiredMixin, RemoveDatabaseView):
permission_required = "testapp.change_post"
| NoObjectView |
python | hynek__structlog | tests/processors/test_processors.py | {
"start": 1009,
"end": 1727
} | class ____:
def test_encodes(self):
"""
Unicode strings get encoded (as UTF-8 by default).
"""
e = UnicodeEncoder()
assert {"foo": b"b\xc3\xa4r"} == e(None, None, {"foo": "b\xe4r"})
def test_passes_arguments(self):
"""
Encoding options are passed into th... | TestUnicodeEncoder |
python | django__django | tests/many_to_many/models.py | {
"start": 1838,
"end": 1891
} | class ____(AbstractArticle):
pass
| InheritedArticleA |
python | django__django | tests/sessions_tests/models.py | {
"start": 640,
"end": 1242
} | class ____(DBStore):
"""
A database session store, that handles updating the account ID column
inside the custom session model.
"""
@classmethod
def get_model_class(cls):
return CustomSession
def create_model_instance(self, data):
obj = super().create_model_instance(data)
... | SessionStore |
python | pytorch__pytorch | benchmarks/operator_benchmark/common/tests/pt_cpu_gpu_forward_backward_test.py | {
"start": 168,
"end": 714
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device):
self.input_one = torch.rand(M, N, K, device=device, requires_grad=True)
self.input_two = torch.rand(M, N, K, device=device, requires_grad=True)
self.set_module_name("add")
def forward(self):
return torch.a... | AddBenchmark |
python | doocs__leetcode | solution/2500-2599/2583.Kth Largest Sum in a Binary Tree/Solution.py | {
"start": 192,
"end": 690
} | class ____:
def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
arr = []
q = deque([root])
while q:
t = 0
for _ in range(len(q)):
root = q.popleft()
t += root.val
if root.left:
q.ap... | Solution |
python | getsentry__sentry | src/sentry/preprod/migrations/0013_binary_uuid.py | {
"start": 155,
"end": 1487
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | getsentry__sentry | tests/sentry/ratelimits/utils/test_enforce_rate_limit.py | {
"start": 463,
"end": 738
} | class ____(Endpoint):
permission_classes = (AllowAny,)
rate_limits = RateLimitConfig(
limit_overrides={"GET": {RateLimitCategory.IP: RateLimit(limit=1, window=100)}}
)
def get(self, request):
return Response({"ok": True})
| RateLimitTestEndpoint |
python | streamlit__streamlit | lib/tests/streamlit/runtime/caching/cache_data_api_test.py | {
"start": 9020,
"end": 18282
} | class ____(DeltaGeneratorTestCase):
"""st.cache_data disk persistence tests"""
def setUp(self) -> None:
super().setUp()
mock_runtime = MagicMock(spec=Runtime)
mock_runtime.cache_storage_manager = LocalDiskCacheStorageManager()
Runtime._instance = mock_runtime
def tearDown(s... | CacheDataPersistTest |
python | python__mypy | mypyc/ir/ops.py | {
"start": 6120,
"end": 7208
} | class ____(Value):
"""Short integer literal.
Integer literals are treated as constant values and are generally
not included in data flow analyses and such, unlike Register and
Op subclasses.
Integer can represent multiple types:
* Short tagged integers (short_int_primitive type; the tag bit ... | Integer |
python | kubernetes-client__python | kubernetes/client/models/v1_custom_resource_definition_status.py | {
"start": 383,
"end": 6600
} | 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... | V1CustomResourceDefinitionStatus |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 16035,
"end": 16226
} | class ____(DagsterError):
"""Indicates that an error has occurred when an op has been invoked, but before the actual
core compute has been reached.
"""
| DagsterInvalidInvocationError |
python | google__jax | tests/custom_partitioning_test.py | {
"start": 1065,
"end": 16330
} | class ____(jtu.JaxTestCase):
def skip_if_custom_partitioning_not_supported(self):
if jtu.is_cloud_tpu():
raise unittest.SkipTest("Custom partitioning is not supported on libtpu.")
@jtu.skip_on_devices('cpu') # Collectives don't seem to work on CPU.
def test_custom_partitioner(self):
self.skip_if_... | CustomPartitionerTest |
python | huggingface__transformers | src/transformers/models/edgetam/modeling_edgetam.py | {
"start": 8531,
"end": 11619
} | class ____(nn.Module):
def __init__(self, config: EdgeTamMaskDecoderConfig, skip_first_layer_pe: bool = False):
"""
A transformer block with four layers:
(1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on
sparse inputs (4... | EdgeTamTwoWayAttentionBlock |
python | walkccc__LeetCode | solutions/2025. Maximum Number of Ways to Partition an Array/2025.py | {
"start": 0,
"end": 662
} | class ____:
def waysToPartition(self, nums: list[int], k: int) -> int:
n = len(nums)
summ = sum(nums)
prefix = 0
# Count of sum(A[0..k)) - sum(A[k..n)) for k in [0..i)
l = collections.Counter()
# Count of sum(A[0..k)) - sum(A[k..n)) for k in [i..n)
r = collections.Counter()
for pivot ... | Solution |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/key_value_parsers.py | {
"start": 3067,
"end": 4811
} | class ____(KeyValueParser):
"""Composite argument parser for docker key/value pairs."""
def __init__(self, image: str, controller: bool) -> None:
self.controller = controller
self.versions = get_docker_pythons(image, controller, False)
self.allow_default = bool(get_docker_pythons(image,... | DockerKeyValueParser |
python | readthedocs__readthedocs.org | readthedocs/projects/tests/test_build_tasks.py | {
"start": 106003,
"end": 108529
} | class ____(BuildEnvironmentBase):
def _trigger_sync_repository_task(self):
sync_repository_task.delay(self.version.pk, build_api_key="1234")
@mock.patch("readthedocs.projects.tasks.builds.clean_build")
def test_clean_build_after_sync_repository(self, clean_build):
self._trigger_sync_reposit... | TestSyncRepositoryTask |
python | python__mypy | mypy/test/meta/test_parse_data.py | {
"start": 416,
"end": 1983
} | class ____(Suite):
def test_parse_invalid_case(self) -> None:
# Act
result = _run_pytest(
"""
[case abc]
s: str
[case foo-XFAIL]
s: str
"""
)
# Assert
assert "Invalid testcase id 'foo-XFAIL'" in result.s... | ParseTestDataSuite |
python | Textualize__textual | src/textual/_animator.py | {
"start": 7272,
"end": 20530
} | class ____:
"""An object to manage updates to a given attribute over a period of time."""
def __init__(self, app: App, frames_per_second: int = 60) -> None:
"""Initialise the animator object.
Args:
app: The application that owns the animator.
frames_per_second: The numb... | Animator |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 185212,
"end": 187450
} | class ____(Request):
"""
Delete models from task
:param task: ID of the task
:type task: str
:param models: The list of models to delete
:type models: Sequence[dict]
"""
_service = "tasks"
_action = "delete_models"
_version = "2.13"
_schema = {
"definitions": {"mode... | DeleteModelsRequest |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/utils/pod_manager.py | {
"start": 11629,
"end": 11808
} | class ____:
"""Return the status of the pod and last log time when exiting from `fetch_container_logs`."""
running: bool
last_log_time: DateTime | None
| PodLoggingStatus |
python | huggingface__transformers | src/transformers/models/diffllama/modeling_diffllama.py | {
"start": 25198,
"end": 26085
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
DiffLlamaRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
in... | DiffLlamaRMSNorm |
python | spyder-ide__spyder | spyder/plugins/help/widgets.py | {
"start": 2629,
"end": 4928
} | class ____(EditableComboBox):
"""
QComboBox handling object names
"""
# Signals
valid = Signal(bool, bool)
def __init__(self, parent, id_=None):
EditableComboBox.__init__(self, parent)
self.help = parent
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
... | ObjectComboBox |
python | huggingface__transformers | src/transformers/utils/auto_docstring.py | {
"start": 20106,
"end": 29657
} | class ____:
last_hidden_state = {
"description": """
Sequence of hidden-states at the output of the last layer of the model.
""",
"shape": "of shape `(batch_size, sequence_length, hidden_size)`",
}
past_key_values = {
"description": """
It is a [`~cache_utils.Cache`] ins... | ModelOutputArgs |
python | sympy__sympy | sympy/assumptions/predicates/calculus.py | {
"start": 87,
"end": 1058
} | class ____(Predicate):
"""
Finite number predicate.
Explanation
===========
``Q.finite(x)`` is true if ``x`` is a number but neither an infinity
nor a ``NaN``. In other words, ``ask(Q.finite(x))`` is true for all
numerical ``x`` having a bounded absolute value.
Examples
========
... | FinitePredicate |
python | facebookresearch__faiss | tests/test_index.py | {
"start": 12813,
"end": 13603
} | class ____(unittest.TestCase):
def test_range_search(self):
d = 4
nt = 100
nq = 10
nb = 50
(xt, xb, xq) = get_dataset(d, nb, nt, nq)
index = faiss.IndexFlatL2(d)
index.add(xb)
Dref, Iref = index.search(xq, 5)
thresh = 0.1 # *squared* dis... | TestRangeSearch |
python | apache__airflow | dev/breeze/src/airflow_breeze/global_constants.py | {
"start": 26345,
"end": 26771
} | class ____(Enum):
PULL_REQUEST = "pull_request"
PULL_REQUEST_REVIEW = "pull_request_review"
PULL_REQUEST_TARGET = "pull_request_target"
PULL_REQUEST_WORKFLOW = "pull_request_workflow"
PUSH = "push"
SCHEDULE = "schedule"
WORKFLOW_DISPATCH = "workflow_dispatch"
WORKFLOW_RUN = "workflow_run... | GithubEvents |
python | sympy__sympy | sympy/functions/special/error_functions.py | {
"start": 55328,
"end": 59306
} | class ____(TrigonometricIntegral):
r"""
Cosine integral.
Explanation
===========
This function is defined for positive $x$ by
.. math:: \operatorname{Ci}(x) = \gamma + \log{x}
+ \int_0^x \frac{\cos{t} - 1}{t} \mathrm{d}t
= -\int_x^\infty \frac{\cos{t}}{t} \... | Ci |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/checkpoint_metrics_test.py | {
"start": 1112,
"end": 4369
} | class ____(test.TestCase):
def _get_write_histogram_proto(self, api_label):
proto_bytes = metrics.GetCheckpointWriteDurations(api_label=api_label)
histogram_proto = summary_pb2.HistogramProto()
histogram_proto.ParseFromString(proto_bytes)
return histogram_proto
def _get_read_histogram_proto(self, ... | CheckpointMetricTests |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 2703,
"end": 2793
} | class ____(BaseModel):
__type_alias_attribute__ = Union[str, bytes]
| TypeAliasAsAttribute |
python | huggingface__transformers | tests/utils/test_deprecation.py | {
"start": 968,
"end": 8820
} | class ____(unittest.TestCase):
def test_rename_kwarg(self):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
@deprecate_kwarg("deprecated_name", new_name="new_name", version=INFINITE_VERSION)
def dummy_function(new_name=None, other_name=None):
... | DeprecationDecoratorTester |
python | PyCQA__pylint | pylint/typing.py | {
"start": 1821,
"end": 2576
} | class ____(NamedTuple):
"""Tuple with information about a managed message of the linter."""
name: str | None
msgid: str
symbol: str
line: int | None
is_disabled: bool
MessageTypesFullName = Literal[
"convention", "error", "fatal", "info", "refactor", "statement", "warning"
]
"""All possib... | ManagedMessage |
python | mitmproxy__pdoc | test/testdata/enums.py | {
"start": 339,
"end": 414
} | class ____(enum.IntEnum):
FOO = enum.auto()
BAR = enum.auto()
| IntEnum |
python | joke2k__faker | faker/providers/person/gu_IN/__init__.py | {
"start": 44,
"end": 2991
} | class ____(PersonProvider):
formats_male = (
"{{first_name_male}} {{last_name}}",
"{{prefix_male}} {{first_name_male}} {{last_name}}",
)
formats_female = (
"{{first_name_female}} {{last_name}}",
"{{prefix_female}} {{first_name_female}} {{last_name}}",
)
formats = (... | Provider |
python | lxml__lxml | src/lxml/html/__init__.py | {
"start": 7686,
"end": 23266
} | class ____:
def set(self, key, value=None):
"""set(self, key, value=None)
Sets an element attribute. If no value is provided, or if the value is None,
creates a 'boolean' attribute without value, e.g. "<form novalidate></form>"
for ``form.set('novalidate')``.
"""
s... | HtmlMixin |
python | bokeh__bokeh | tests/unit/bokeh/document/_util_document.py | {
"start": 1467,
"end": 2043
} | class ____(Model):
foo = DistanceSpec(2)
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------... | ModelWithSpecInTestDocument |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 5692,
"end": 11245
} | class ____(Static):
"""The base class for a Markdown Element."""
COMPONENT_CLASSES = {"em", "strong", "s", "code_inline"}
"""
These component classes target standard inline markdown styles.
Changing these will potentially break the standard markdown formatting.
| Class | Description |
| :-... | MarkdownBlock |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.