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 | huggingface__transformers | src/transformers/data/processors/squad.py | {
"start": 23153,
"end": 25360
} | class ____:
"""
A single training/test example for the Squad dataset, as loaded from disk.
Args:
qas_id: The example's unique identifier
question_text: The question string
context_text: The context string
answer_text: The answer string
start_position_character: The c... | SquadExample |
python | huggingface__transformers | src/transformers/models/deepseek_vl_hybrid/modeling_deepseek_vl_hybrid.py | {
"start": 6338,
"end": 7243
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.conv1 = nn.Conv2d(config.hidden_size, config.output_channels, kernel_size=1, bias=False)
self.layer_norm1 = DeepseekVLHybridLayerNorm(config.output_channels, data_format="channels_first")... | DeepseekVLSamVisionNeck |
python | doocs__leetcode | solution/0500-0599/0532.K-diff Pairs in an Array/Solution.py | {
"start": 0,
"end": 299
} | class ____:
def findPairs(self, nums: List[int], k: int) -> int:
ans = set()
vis = set()
for x in nums:
if x - k in vis:
ans.add(x - k)
if x + k in vis:
ans.add(x)
vis.add(x)
return len(ans)
| Solution |
python | encode__django-rest-framework | tests/test_utils.py | {
"start": 686,
"end": 718
} | class ____(APIView):
pass
| Root |
python | openai__openai-python | src/openai/resources/fine_tuning/alpha/alpha.py | {
"start": 3004,
"end": 3274
} | class ____:
def __init__(self, alpha: AsyncAlpha) -> None:
self._alpha = alpha
@cached_property
def graders(self) -> AsyncGradersWithStreamingResponse:
return AsyncGradersWithStreamingResponse(self._alpha.graders)
| AsyncAlphaWithStreamingResponse |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 34836,
"end": 35424
} | class ____(graphene.Mutation):
"""Frees the concurrency slots occupied by a specific run."""
Output = graphene.NonNull(graphene.Boolean)
class Meta:
name = "FreeConcurrencySlotsForRunMutation"
class Arguments:
runId = graphene.Argument(graphene.NonNull(graphene.String))
@capture_... | GrapheneFreeConcurrencySlotsForRunMutation |
python | pypa__warehouse | tests/unit/macaroons/test_caveats.py | {
"start": 12758,
"end": 14925
} | class ____:
def test_verify_invalid_signature(self):
m = Macaroon(location="somewhere", identifier="something", key=b"a secure key")
status = verify(
m, b"a different key", pretend.stub(), pretend.stub(), pretend.stub()
)
assert not status
assert status.msg == "si... | TestVerification |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/dep_diamond_patch_mid1/package.py | {
"start": 217,
"end": 608
} | class ____(Package):
r"""Package that requires a patch on a dependency
W
/ \
X Y
\ /
Z
This is package X
"""
homepage = "http://www.example.com"
url = "http://www.example.com/patch-a-dependency-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
# single patch fil... | DepDiamondPatchMid1 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/system.py | {
"start": 54484,
"end": 55383
} | class ____(StepExecutionContext):
"""The context object provided to a :py:class:`@dagster_type_loader <dagster_type_loader>`-decorated function during execution.
Users should not construct this object directly.
"""
@public
@property
def resources(self) -> "Resources":
"""The resources ... | DagsterTypeLoaderContext |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_text.py | {
"start": 18007,
"end": 20811
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx=None):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = Data2VecTextAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
... | Data2VecTextLayer |
python | psf__black | tests/data/miscellaneous/force_pyi.py | {
"start": 487,
"end": 597
} | class ____:
def BMethod(self) -> None: ...
@overload
def BMethod(self, arg: List[str]) -> None: ...
| B |
python | pypa__pip | src/pip/_vendor/urllib3/_collections.py | {
"start": 641,
"end": 3017
} | class ____(MutableMapping):
"""
Provides a thread-safe dict-like container which maintains up to
``maxsize`` keys while throwing away the least-recently-used keys beyond
``maxsize``.
:param maxsize:
Maximum number of recent elements to retain.
:param dispose_func:
Every time an... | RecentlyUsedContainer |
python | ethereum__web3.py | tests/core/utilities/test_attach_modules.py | {
"start": 382,
"end": 453
} | class ____(Module):
def block_number(self):
return 42
| MockEth |
python | facebook__pyre-check | client/commands/report_any_expressions.py | {
"start": 2930,
"end": 6222
} | class ____(json_mixins.SnakeCaseAndExcludeJsonMixin):
path: str
expression_statistics: ExpressionStatistics
any_expressions: List[AnyExpression]
@staticmethod
def from_typed_backend_data(
data: Union[
expression_level_coverage.CoverageAtPathResponse,
expression_level... | ModuleExpressionData |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/task_instance_history.py | {
"start": 1316,
"end": 2454
} | class ____(BaseModel):
"""TaskInstanceHistory serializer for responses."""
task_id: str
dag_id: str
# todo: this should not be aliased; it's ambiguous with dag run's "id" - airflow 3.0
run_id: str = Field(alias="dag_run_id")
map_index: int
start_date: datetime | None
end_date: datetim... | TaskInstanceHistoryResponse |
python | facebook__pyre-check | client/tests/frontend_configuration_test.py | {
"start": 580,
"end": 8147
} | class ____(testslide.TestCase):
def test_dot_pyre_directory(self) -> None:
self.assertEqual(
frontend_configuration.OpenSource(
configuration_module.Configuration(
global_root=Path("foo"), dot_pyre_directory=Path(".pyre")
)
).get_do... | FrontendConfigurationTest |
python | getsentry__sentry | src/sentry/constants.py | {
"start": 18193,
"end": 19037
} | class ____:
PENDING = 0
INSTALLED = 1
PENDING_DELETION = 2
PENDING_STR = "pending"
INSTALLED_STR = "installed"
PENDING_DELETION_STR = "pending_deletion"
@classmethod
def as_choices(cls) -> Sequence[tuple[int, str]]:
return (
(cls.PENDING, cls.PENDING_STR),
... | SentryAppInstallationStatus |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 7052,
"end": 7153
} | class ____(NamedTuple):
type: EnvVarConsumerType
name: str
@whitelist_for_serdes
| EnvVarConsumer |
python | django__django | tests/model_inheritance/models.py | {
"start": 4775,
"end": 4830
} | class ____(FirstParent, SecondParent):
pass
| CommonChild |
python | scikit-learn__scikit-learn | sklearn/_loss/loss.py | {
"start": 19881,
"end": 21052
} | class ____(BaseLoss):
"""Absolute error with identity link, for regression.
Domain:
y_true and y_pred all real numbers
Link:
y_pred = raw_prediction
For a given sample x_i, the absolute error is defined as::
loss(x_i) = |y_true_i - raw_prediction_i|
Note that the exact hessian =... | AbsoluteError |
python | kamyu104__LeetCode-Solutions | Python/maximum-white-tiles-covered-by-a-carpet.py | {
"start": 76,
"end": 817
} | class ____(object):
def maximumWhiteTiles(self, tiles, carpetLen):
"""
:type tiles: List[List[int]]
:type carpetLen: int
:rtype: int
"""
tiles.sort()
result = right = gap = 0
for left, (l, _) in enumerate(tiles):
if left-1 >= 0:
... | Solution |
python | pytorch__pytorch | test/test_cuda.py | {
"start": 242125,
"end": 243773
} | class ____(TestCase):
def _get_tmp_dir_fs_type(self):
my_path = os.path.realpath("/tmp")
root_type = ""
for part in psutil.disk_partitions():
if part.mountpoint == "/":
root_type = part.fstype
continue
if part.mountpoint == my_path:
... | TestGDS |
python | weaviate__weaviate-python-client | weaviate/config.py | {
"start": 135,
"end": 1199
} | class ____:
session_pool_connections: int = 20
session_pool_maxsize: int = 100
session_pool_max_retries: int = 3
session_pool_timeout: int = 5
def __post_init__(self) -> None:
if not isinstance(self.session_pool_connections, int):
raise TypeError(
f"session_pool_... | ConnectionConfig |
python | walkccc__LeetCode | solutions/2117. Abbreviating the Product of a Range/2117.py | {
"start": 0,
"end": 662
} | class ____:
def abbreviateProduct(self, left: int, right: int) -> str:
prod = 1.0
suf = 1
countDigits = 0
countZeros = 0
for num in range(left, right + 1):
prod *= num
while prod >= 1.0:
prod /= 10
countDigits += 1
suf *= num
while suf % 10 == 0:
su... | Solution |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_generators.py | {
"start": 23311,
"end": 51469
} | class ____(__TestCase):
def test_generator_gi_yieldfrom(self):
def a():
self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_RUNNING)
self.assertIsNone(gen_b.gi_yieldfrom)
yield
self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_RUNNING)
... | YieldFromTests |
python | TheAlgorithms__Python | cellular_automata/wa_tor.py | {
"start": 3000,
"end": 20556
} | class ____:
"""
Represents the main Wa-Tor algorithm.
:attr time_passed: A function that is called every time
time passes (a chronon) in order to visually display
the new Wa-Tor planet. The `time_passed` function can block
using ``time.sleep`` to slow the algorithm progression.
... | WaTor |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/line/colorbar/title/_font.py | {
"start": 233,
"end": 9949
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d.line.colorbar.title"
_path_str = "scatter3d.line.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | streamlit__streamlit | lib/tests/streamlit/elements/chat_test.py | {
"start": 1473,
"end": 30111
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall ChatInput and ChatMessage protos."""
def test_label_required(self):
"""Test that label is required"""
with pytest.raises(TypeError):
st.chat_message()
def test_nesting_is_allowed(self):
"""Test that it is a... | ChatTest |
python | numpy__numpy | numpy/f2py/tests/test_kind.py | {
"start": 298,
"end": 1845
} | class ____(util.F2PyTest):
sources = [util.getpath("tests", "src", "kind", "foo.f90")]
@pytest.mark.skipif(sys.maxsize < 2 ** 31 + 1,
reason="Fails for 32 bit machines")
def test_int(self):
"""Test `int` kind_func for integers up to 10**40."""
selectedintkind = self.... | TestKind |
python | huggingface__transformers | src/transformers/models/dinov2/modeling_dinov2.py | {
"start": 22268,
"end": 25375
} | class ____(Dinov2PreTrainedModel, BackboneMixin):
def __init__(self, config):
super().__init__(config)
super()._init_backbone(config)
self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
self.embeddings = Dinov2Embeddings(config)
self.encoder... | Dinov2Backbone |
python | realpython__materials | django-diary/source_code_step_5/entries/views.py | {
"start": 677,
"end": 775
} | class ____(DeleteView):
model = Entry
success_url = reverse_lazy("entry-list")
| EntryDeleteView |
python | realpython__materials | python-built-in-exceptions/birds.py | {
"start": 22,
"end": 223
} | class ____(ABC):
def swim(self):
raise NotImplementedError("must be implemented in subclasses")
def fly(self):
raise NotImplementedError("must be implemented in subclasses")
| Bird |
python | getsentry__sentry | src/sentry/api/endpoints/organization_insights_tree.py | {
"start": 417,
"end": 2472
} | class ____(OrganizationEventsEndpoint):
"""
Endpoint for querying Next.js Insights data to display a tree view of files and components.
Currently, the component and path information is extracted from the span.description field using a regex.
In the future, this data will be properly structured through:... | OrganizationInsightsTreeEndpoint |
python | huggingface__transformers | tests/quantization/bnb/test_mixed_int8.py | {
"start": 36352,
"end": 37753
} | class ____(MixedInt8Test):
model_name = "openai-community/gpt2-xl"
EXPECTED_RELATIVE_DIFFERENCE = 1.8720077507258357
EXPECTED_OUTPUTS = set()
EXPECTED_OUTPUTS.add("Hello my name is John Doe, and I'm a big fan of")
EXPECTED_OUTPUTS.add("Hello my name is John Doe, and I'm a fan of the")
# Expected... | MixedInt8GPT2Test |
python | wandb__wandb | wandb/agents/pyagent.py | {
"start": 1618,
"end": 1749
} | class ____:
QUEUED = "QUEUED"
RUNNING = "RUNNING"
STOPPED = "STOPPED"
ERRORED = "ERRORED"
DONE = "DONE"
| RunStatus |
python | oauthlib__oauthlib | tests/openid/connect/core/endpoints/test_claims_handling.py | {
"start": 746,
"end": 4579
} | class ____(TestCase):
DEFAULT_REDIRECT_URI = 'http://i.b./path'
def set_scopes(self, scopes):
def set_request_scopes(client_id, code, client, request):
request.scopes = scopes
return True
return set_request_scopes
def set_user(self, request):
request.user =... | TestClaimsHandling |
python | tiangolo__fastapi | docs_src/security/tutorial005_an_py310.py | {
"start": 1475,
"end": 5426
} | class ____(User):
hashed_password: str
password_hash = PasswordHash.recommended()
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="token",
scopes={"me": "Read information about the current user.", "items": "Read items."},
)
app = FastAPI()
def verify_password(plain_password, hashed_password):
retur... | UserInDB |
python | kamyu104__LeetCode-Solutions | Python/find-time-required-to-eliminate-bacterial-strains.py | {
"start": 63,
"end": 444
} | class ____(object):
def minEliminationTime(self, timeReq, splitTime):
"""
:type timeReq: List[int]
:type splitTime: int
:rtype: int
"""
heapq.heapify(timeReq)
for _ in xrange(len(timeReq)-1):
heapq.heappush(timeReq, max(heapq.heappop(timeReq), heap... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/inputs.py | {
"start": 16268,
"end": 16902
} | class ____(
StepInputSource,
):
"""This input source is for direct python values to be passed as inputs to ops."""
input_name: str
def load_input_object(
self, step_context: "StepExecutionContext", input_def: InputDefinition
) -> Iterator[object]:
job_def = step_context.job_def
... | FromDirectInputValue |
python | numba__numba | numba/cuda/cudadrv/nvrtc.py | {
"start": 426,
"end": 970
} | class ____(IntEnum):
NVRTC_SUCCESS = 0
NVRTC_ERROR_OUT_OF_MEMORY = 1
NVRTC_ERROR_PROGRAM_CREATION_FAILURE = 2
NVRTC_ERROR_INVALID_INPUT = 3
NVRTC_ERROR_INVALID_PROGRAM = 4
NVRTC_ERROR_INVALID_OPTION = 5
NVRTC_ERROR_COMPILATION = 6
NVRTC_ERROR_BUILTIN_OPERATION_FAILURE = 7
NVRTC_ERROR... | NvrtcResult |
python | RaRe-Technologies__gensim | gensim/topic_coherence/text_analysis.py | {
"start": 14054,
"end": 19974
} | class ____(WindowedTextsAnalyzer):
"""Accumulate word occurrences in parallel.
Attributes
----------
processes : int
Number of processes to use; must be at least two.
args :
Should include `relevant_ids` and `dictionary` (see :class:`~UsesDictionary.__init__`).
kwargs :
... | ParallelWordOccurrenceAccumulator |
python | graphql-python__graphene | graphene/tests/issues/test_1394.py | {
"start": 59,
"end": 947
} | class ____(ObjectType):
hello = String(input=NonNull(String))
def resolve_hello(self, info, input):
if input == "nothing":
return None
return f"Hello {input}!"
schema = Schema(query=Query)
def test_required_input_provided():
"""
Test that a required argument works when p... | Query |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 881,
"end": 1087
} | class ____(RequestHandler):
def get(self):
name = self.get_argument("name", "world")
self.set_header("Content-Type", "text/plain")
self.finish("Hello %s!" % name)
| HelloWorldHandler |
python | pytorch__pytorch | torch/ao/quantization/fx/graph_module.py | {
"start": 3188,
"end": 4541
} | class ____(ObservedGraphModule):
def __init__(
self,
root: torch.nn.Module | dict[str, Any],
graph: Graph,
preserved_attr_names: set[str],
):
preserved_attr_names = preserved_attr_names.union(
{
"_standalone_module_input_quantized_idxs",
... | ObservedStandaloneGraphModule |
python | doocs__leetcode | solution/2400-2499/2441.Largest Positive Integer That Exists With Its Negative/Solution.py | {
"start": 0,
"end": 144
} | class ____:
def findMaxK(self, nums: List[int]) -> int:
s = set(nums)
return max((x for x in s if -x in s), default=-1)
| Solution |
python | bokeh__bokeh | src/bokeh/models/widgets/sliders.py | {
"start": 5124,
"end": 5869
} | class ____(NumericalSlider):
""" Slider-based number selection widget. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
start = Required(Float, help="""
The minimum allowable value.
""")
end... | Slider |
python | numba__numba | numba/core/generators.py | {
"start": 7985,
"end": 8909
} | class ____(BaseGeneratorLower):
"""
Support class for lowering nopython generators.
"""
def get_generator_type(self):
return self.fndesc.restype
def box_generator_struct(self, lower, gen_struct):
return gen_struct
def lower_finalize_func_body(self, builder, genptr):
""... | GeneratorLower |
python | walkccc__LeetCode | solutions/2941. Maximum GCD-Sum of a Subarray/2941.py | {
"start": 0,
"end": 829
} | class ____:
def maxGcdSum(self, nums: list[int], k: int) -> int:
ans = 0
# [(startIndex, gcd of subarray starting at startIndex)]
startIndexAndGcds = []
prefix = list(itertools.accumulate(nums, initial=0))
for i, num in enumerate(nums):
nextStartIndexAndGcds = []
for startIndex, gcd i... | Solution |
python | coleifer__peewee | tests/base_models.py | {
"start": 1442,
"end": 1523
} | class ____(TestModel):
a = ForeignKeyField(A, backref='bs')
b = TextField()
| B |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 66218,
"end": 66546
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('vgpuProcessCount', c_uint),
('lastSeenTimeStamp', c_ulonglong),
('vgpuProcUtilArray', POINTER(c_nvmlVgpuProcessUtilizationInfo_v1_t)),
]
VgpuProcessesUtilizationInfo_v1 = 0x01000018
| c_nvmlVgpuProcessesUtilizationInfo_v1_t |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor24.py | {
"start": 1158,
"end": 1801
} | class ____(Generic[U]):
def __init__(self) -> None:
self.containers: List[Container[U]] = []
def method1(self, a: U):
Container[U](a)
Container()
Container(123)
# This should generate an error if strictParameterNoneValue is true.
Container[U]()
# This s... | ContainerList |
python | coleifer__peewee | tests/cockroachdb.py | {
"start": 424,
"end": 517
} | class ____(TestModel):
title = TextField()
tags = ArrayField(TextField, index=False)
| Arr |
python | jazzband__django-oauth-toolkit | tests/test_scopes.py | {
"start": 1708,
"end": 2397
} | class ____(TestCase):
factory = RequestFactory()
@classmethod
def setUpTestData(cls):
cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456")
cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456")
cls.application = App... | BaseTest |
python | huggingface__transformers | tests/models/clipseg/test_modeling_clipseg.py | {
"start": 10507,
"end": 12092
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (CLIPSegTextModel,) if is_torch_available() else ()
model_split_percents = [0.5, 0.8, 0.9]
def setUp(self):
self.model_tester = CLIPSegTextModelTester(self)
self.config_tester = ConfigTester(self, config_class=CLIPSegText... | CLIPSegTextModelTest |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0076_add_detector_group_table.py | {
"start": 329,
"end": 2992
} | 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 | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataprep.py | {
"start": 4255,
"end": 4782
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dataprep.GoogleDataprepHook")
def test_execute(self, hook_mock):
op = DataprepRunJobGroupOperator(
dataprep_conn_id=DATAPREP_CONN_ID,
body_request=DATA,
task_id=TASK_ID,
)
op.execute(con... | TestDataprepRunJobGroupOperator |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 132482,
"end": 136799
} | class ____(_RelationshipErrors, fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table("a", metadata, Column("id", Integer, primary_key=True))
Table(
"b",
metadata,
Column("id", Integer, primary_key=True),
Column("aid_1", Intege... | AmbiguousFKResolutionTest |
python | keras-team__keras | keras/src/ops/math_test.py | {
"start": 10630,
"end": 16240
} | class ____(testing.TestCase):
@parameterized.parameters([(kmath.segment_sum,), (kmath.segment_max,)])
@pytest.mark.skipif(
backend.backend() == "jax",
reason="JAX does not support `num_segments=None`.",
)
def test_segment_reduce(self, segment_reduce_op):
# 1D case
data = ... | MathOpsStaticShapeTest |
python | readthedocs__readthedocs.org | readthedocs/search/documents.py | {
"start": 628,
"end": 1048
} | class ____:
def update(self, *args, **kwargs):
# Hack a fix to our broken connection pooling
# This creates a new connection on every request,
# but actually works :)
log.debug("Hacking Elastic indexing to fix connection pooling")
self.using = Elasticsearch(**settings.ELASTIC... | RTDDocTypeMixin |
python | ray-project__ray | python/ray/serve/tests/unit/test_proxy.py | {
"start": 5524,
"end": 6028
} | class ____:
def __init__(self):
self.messages = []
async def __call__(self, message):
self.messages.append(message)
async def _consume_proxy_generator(
gen: ResponseGenerator,
) -> Tuple[ResponseStatus, List]:
status = None
messages = []
async for message in gen:
if is... | FakeHttpSend |
python | great-expectations__great_expectations | great_expectations/metrics/metric.py | {
"start": 1487,
"end": 2524
} | class ____(ModelMetaclass):
"""Metaclass for Metric classes that maintains a registry of all concrete Metric types."""
_registry: dict[str, type["Metric"]] = {}
def __new__(cls, name, bases, attrs, **kwargs):
register_cls = super().__new__(cls, name, bases, attrs)
# Don't register the base... | MetaMetric |
python | tiangolo__fastapi | scripts/notify_translations.py | {
"start": 2906,
"end": 2998
} | class ____(BaseModel):
nodes: List[AllDiscussionsDiscussionNode]
| AllDiscussionsDiscussions |
python | scipy__scipy | scipy/optimize/_nonlin.py | {
"start": 19328,
"end": 26554
} | class ____:
r"""
A matrix represented as
.. math:: \alpha I + \sum_{n=0}^{n=M} c_n d_n^\dagger
However, if the rank of the matrix reaches the dimension of the vectors,
full matrix representation will be used thereon.
"""
# generic type compatibility with scipy-stubs
__class_getitem__... | LowRankMatrix |
python | spyder-ide__spyder | spyder/plugins/findinfiles/widgets/search_thread.py | {
"start": 816,
"end": 14874
} | class ____(QThread):
"""Find in files search thread."""
PYTHON_EXTENSIONS = ['.py', '.pyw', '.pyx', '.ipy', '.pyi', '.pyt']
USEFUL_EXTENSIONS = [
'.ipynb', '.md', '.c', '.cpp', '.h', '.cxx', '.f', '.f03', '.f90',
'.json', '.dat', '.csv', '.tsv', '.txt', '.md', '.rst', '.yml',
'.yam... | SearchThread |
python | pytorch__pytorch | benchmarks/transformer/score_mod.py | {
"start": 4901,
"end": 5677
} | class ____:
shape: tuple[int, ...] # [B, Hq, M, Hkv, N, D]
attn_type: str
dtype: torch.dtype
calculate_bwd_time: bool
cal_bandwidth: bool
backends: list[str]
max_autotune: bool
def __post_init__(self):
assert len(self.shape) == 6, (
"Shape must be of length 6"
... | ExperimentConfig |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/no_method_decorator.py | {
"start": 27,
"end": 493
} | class ____:
COLORS = []
def __init__(self, color):
self.color = color
def pick_colors(cls, *args): # [no-classmethod-decorator]
"""classmethod to pick fruit colors"""
cls.COLORS = args
pick_colors = classmethod(pick_colors)
def pick_one_color(): # [no-staticmethod-decor... | Fruit |
python | viewflow__viewflow | viewflow/workflow/managers.py | {
"start": 1950,
"end": 2476
} | class ____(ModelIterable):
def __iter__(self):
base_iterator = super().__iter__()
if getattr(self.queryset, "_coerced", False):
for process in base_iterator:
if isinstance(process, self.queryset.model):
process = coerce_to_related_instance(
... | ProcessIterable |
python | encode__django-rest-framework | rest_framework/templatetags/rest_framework.py | {
"start": 807,
"end": 9820
} | class ____(template.Node):
style = 'emacs'
def __init__(self, lang, code):
self.lang = lang
self.nodelist = code
def render(self, context):
text = self.nodelist.render(context)
return pygments_highlight(text, self.lang, self.style)
@register.filter()
def with_location(fie... | CodeNode |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/base.py | {
"start": 120013,
"end": 122283
} | class ____(log.Identified):
_sa_propagate_class_events = False
dispatch: dispatcher[ConnectionEventsTarget]
_compiled_cache: Optional[CompiledCacheType]
dialect: Dialect
pool: Pool
url: URL
hide_parameters: bool
echo: log.echo_property
def __init__(
self, proxied: Engine, e... | OptionEngineMixin |
python | openai__openai-python | tests/test_transform.py | {
"start": 8326,
"end": 8911
} | class ____(TypedDict, total=False):
required_prop: Required[Annotated[date, PropertyInfo(format="iso8601", alias="prop")]]
@parametrize
@pytest.mark.asyncio
async def test_datetime_with_alias(use_async: bool) -> None:
assert await transform({"required_prop": None}, DateDictWithRequiredAlias, use_async) == {"p... | DateDictWithRequiredAlias |
python | pytorch__pytorch | benchmarks/tensorexpr/broadcast.py | {
"start": 2021,
"end": 2251
} | class ____(BroadcastMulBench):
def __init__(self, mode, device, dtype, M, N, K):
super().__init__(mode, device, dtype, "row", M, N, K)
@staticmethod
def module():
return "broadcast_row"
| BroadcastRowBench |
python | tornadoweb__tornado | tornado/test/ioloop_test.py | {
"start": 20513,
"end": 22181
} | class ____(unittest.TestCase):
def setUp(self):
self.io_loop = IOLoop(make_current=False)
def tearDown(self):
self.io_loop.close()
def test_sync_result(self):
with self.assertRaises(gen.BadYieldError):
self.io_loop.run_sync(lambda: 42)
def test_sync_exception(self)... | TestIOLoopRunSync |
python | pandas-dev__pandas | pandas/io/parsers/readers.py | {
"start": 3722,
"end": 4025
} | class ____(TypedDict):
na_filter: Literal[True]
low_memory: Literal[True]
memory_map: Literal[False]
float_precision: None
_c_parser_defaults: _C_Parser_Defaults = {
"na_filter": True,
"low_memory": True,
"memory_map": False,
"float_precision": None,
}
| _C_Parser_Defaults |
python | Pylons__pyramid | tests/test_security.py | {
"start": 1906,
"end": 2507
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.security import Denied
return Denied
def _makeOne(self, *arg, **kw):
klass = self._getTargetClass()
return klass(*arg, **kw)
def test_it(self):
denied = self._makeOne('hello')
self.asser... | TestDenied |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/symly/package.py | {
"start": 240,
"end": 1250
} | class ____(Package):
"""A toy package full of symlinks."""
homepage = "https://www.example.com"
has_code = False
version("3.0.0")
def install(self, spec, prefix):
symly_c = """
#include <stdio.h>
int main() {
printf("I'm just here to give the build system something to do...");
ret... | Symly |
python | pandas-dev__pandas | pandas/tests/indexes/datetimes/methods/test_fillna.py | {
"start": 66,
"end": 2004
} | class ____:
@pytest.mark.parametrize("tz", ["US/Eastern", "Asia/Tokyo"])
def test_fillna_datetime64(self, tz):
# GH 11343
idx = pd.DatetimeIndex(["2011-01-01 09:00", pd.NaT, "2011-01-01 11:00"])
exp = pd.DatetimeIndex(
["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:... | TestDatetimeIndexFillNA |
python | kamyu104__LeetCode-Solutions | Python/find-subarrays-with-equal-sum.py | {
"start": 42,
"end": 372
} | class ____(object):
def findSubarrays(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
lookup = set()
for i in xrange(len(nums)-1):
if nums[i]+nums[i+1] in lookup:
return True
lookup.add(nums[i]+nums[i+1])
return ... | Solution |
python | getsentry__sentry | src/sentry/codecov/endpoints/repository_tokens/repository_tokens.py | {
"start": 976,
"end": 4375
} | class ____(CodecovEndpoint):
owner = ApiOwner.CODECOV
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
@extend_schema(
operation_id="Retrieves a paginated list of repository tokens for a given owner",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
PreventP... | RepositoryTokensEndpoint |
python | joke2k__faker | faker/providers/color/hr_HR/__init__.py | {
"start": 98,
"end": 6247
} | class ____(ColorProvider):
"""Implement color provider for ``hr_HR`` locale."""
all_colors = OrderedDict(
(
("Akvamarin", "#7FFFD4"),
("Antikna bijela", "#FAEBD7"),
("Azurna", "#F0FFFF"),
("Bež", "#F5F5DC"),
("Bijela", "#FFFFFF"),
... | Provider |
python | coleifer__peewee | tests/sqlite.py | {
"start": 2894,
"end": 2976
} | class ____(TestModel):
rowid = RowIDField()
data = IntegerField()
| RowIDModel |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_lib.py | {
"start": 42264,
"end": 87156
} | class ____(object):
"""A state & compute distribution policy on a list of devices.
See [the guide](https://www.tensorflow.org/guide/distributed_training)
for overview and examples. See `tf.distribute.StrategyExtended` and
[`tf.distribute`](https://www.tensorflow.org/api_docs/python/tf/distribute)
for a gloss... | StrategyBase |
python | openai__openai-python | src/openai/types/chat/chat_completion_custom_tool_param.py | {
"start": 529,
"end": 775
} | class ____(TypedDict, total=False):
definition: Required[str]
"""The grammar definition."""
syntax: Required[Literal["lark", "regex"]]
"""The syntax of the grammar definition. One of `lark` or `regex`."""
| CustomFormatGrammarGrammar |
python | great-expectations__great_expectations | great_expectations/data_context/store/configuration_store.py | {
"start": 1070,
"end": 5466
} | class ____(Store):
"""
Configuration Store provides a way to store any Marshmallow Schema compatible Configuration (using the YAML format).
""" # noqa: E501 # FIXME CoP
_key_class = ConfigurationIdentifier
_configuration_class = BaseYamlConfig
def __init__(
self,
store_name: ... | ConfigurationStore |
python | pypa__warehouse | tests/common/db/base.py | {
"start": 115,
"end": 546
} | class ____(SQLAlchemyModelFactory):
class Meta:
abstract = True
sqlalchemy_session = Session
@classmethod
def _setup_next_sequence(cls, *args, **kwargs):
return 0
@classmethod
def _create(cls, *args, **kwargs):
r = super()._create(*args, **kwargs)
session = ... | WarehouseFactory |
python | ZoranPandovski__al-go-rithms | data_structures/Tree/python/tree_utils.py | {
"start": 179,
"end": 1449
} | class ____(object):
def in_order_traversal(self, root):
if root:
self.in_order_traversal(root.left)
print(str(root.data))
self.in_order_traversal(root.right)
def pre_order_traversal(self, root):
if root:
print(str(root.data))
self.pre_order_traversal(root.left)
self.pre_order_traversal(root.ri... | Traversals |
python | doocs__leetcode | solution/1200-1299/1210.Minimum Moves to Reach Target with Rotations/Solution.py | {
"start": 0,
"end": 1364
} | class ____:
def minimumMoves(self, grid: List[List[int]]) -> int:
def move(i1, j1, i2, j2):
if 0 <= i1 < n and 0 <= j1 < n and 0 <= i2 < n and 0 <= j2 < n:
a, b = i1 * n + j1, i2 * n + j2
status = 0 if i1 == i2 else 1
if (a, status) not in vis and ... | Solution |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/errors.py | {
"start": 12227,
"end": 12934
} | class ____(OAuth2Error):
"""
This error is a placeholder for all custom errors not described by the RFC.
Some of the popular OAuth2 providers are using custom errors.
"""
def __init__(self, error, *args, **kwargs):
self.error = error
super().__init__(*args, **kwargs)
def raise_from... | CustomOAuth2Error |
python | astropy__astropy | astropy/timeseries/periodograms/lombscargle/core.py | {
"start": 664,
"end": 28092
} | class ____(BasePeriodogram):
"""Compute the Lomb-Scargle Periodogram.
This implementations here are based on code presented in [1]_ and [2]_;
if you use this functionality in an academic application, citation of
those works would be appreciated.
Parameters
----------
t : array-like or `~as... | LombScargle |
python | numba__numba | numba/tests/test_optimisation_pipelines.py | {
"start": 163,
"end": 1692
} | class ____(TestCase):
""" Tests that pass manager is not overriding the intended
optimization level.
"""
def _get_llvmir(self, fn, sig):
with override_config('OPT', 0):
fn.compile(sig)
return fn.inspect_llvm(sig)
def test_override_config(self):
@njit(debug=T... | TestPassManagerOptimization |
python | pytorch__pytorch | torch/_inductor/codegen/simd_kernel_features.py | {
"start": 22180,
"end": 22903
} | class ____:
"""Memory usage stats that are collected for both persistent and looped kernels"""
reads: StatsForReadsOrWrites
writes: StatsForReadsOrWrites
memory: StatsForReadsOrWrites
@classmethod
def compute(
cls, loops: list[MemoryEstimate], estimator: MemoryEstimator
) -> typing... | StatsForKernelType |
python | langchain-ai__langchain | libs/core/langchain_core/tools/base.py | {
"start": 8064,
"end": 12126
} | class ____:
"""Configuration for Pydantic models generated from function signatures."""
extra: str = "forbid"
"""Whether to allow extra fields in the model."""
arbitrary_types_allowed: bool = True
"""Whether to allow arbitrary types in the model."""
def create_schema_from_function(
model_name... | _SchemaConfig |
python | huggingface__transformers | tests/models/dbrx/test_modeling_dbrx.py | {
"start": 2645,
"end": 3560
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = DbrxModelTester
@slow
def test_model_from_pretrained(self):
model_name = "trl-internal-testing/tiny-DbrxForCausalLM"
model = DbrxModel.from_pretrained(model_name)
self.assertIsNotNone(model)
# Offload does n... | DbrxModelTest |
python | apache__airflow | airflow-core/src/airflow/serialization/definitions/param.py | {
"start": 2984,
"end": 5549
} | class ____(collections.abc.Mapping[str, Any]):
"""Server-side ParamsDict class for deserialization."""
__dict: dict[str, SerializedParam]
def __init__(self, d: Mapping[str, Any] | None = None) -> None:
self.__dict = dict(_collect_params(d))
def __eq__(self, other: Any) -> bool:
"""Com... | SerializedParamsDict |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 19071,
"end": 20008
} | class ____(ASTExpression):
def __init__(self, typ: ASTType) -> None:
self.typ = typ
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTAlignofExpr):
return NotImplemented
return self.typ == other.typ
def __hash__(self) -> int:
return hash(self.... | ASTAlignofExpr |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 25271,
"end": 26132
} | class ____(Response):
"""
Response of queues.create endpoint.
:param id: New queue ID
:type id: str
"""
_service = "queues"
_action = "create"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {"id": {"description": "New queue ID", "type": ["string", "n... | CreateResponse |
python | Lightning-AI__lightning | src/lightning/pytorch/_graveyard/tpu.py | {
"start": 2019,
"end": 2427
} | class ____(XLAAccelerator):
"""Legacy class.
Use :class:`~lightning.pytorch.accelerators.xla.XLAAccelerator` instead.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
rank_zero_deprecation(
"The `TPUAccelerator` class is deprecated. Use `lightning.pytorch.accelerators.XL... | TPUAccelerator |
python | pytorch__pytorch | test/distributed/test_c10d_nccl.py | {
"start": 181734,
"end": 197893
} | class ____(test_c10d_common.AbstractLargeCommTest, MultiProcessTestCase):
def setUp(self):
super().setUp()
# TORCH_NCCL_BLOCKING_WAIT overrides TORCH_NCCL_ASYNC_ERROR_HANDLING hence tests
# that use TORCH_NCCL_BLOCKING_WAIT will test it as expected.
os.environ["TORCH_NCCL_ASYNC_ERROR... | LargeCommTest |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_monitor.py | {
"start": 1262,
"end": 1434
} | class ____:
@pytest.fixture(autouse=True)
def setup(self) -> None:
clear_db_jobs()
def teardown_method(self):
clear_db_jobs()
| TestMonitorEndpoint |
python | encode__django-rest-framework | tests/schemas/views.py | {
"start": 5359,
"end": 5518
} | class ____(generics.GenericAPIView):
serializer_class = ExampleSerializerModel
def get(self, *args, **kwargs):
pass
| ExampleOperationIdDuplicate1 |
python | sympy__sympy | sympy/series/formal.py | {
"start": 42161,
"end": 44077
} | class ____(FiniteFormalPowerSeries):
"""Represents the product of two formal power series of two functions.
Explanation
===========
No computation is performed. Terms are calculated using a term by term logic,
instead of a point by point logic.
There are two differences between a :obj:`Formal... | FormalPowerSeriesProduct |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.