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 | graphql-python__graphene | examples/starwars/schema.py | {
"start": 83,
"end": 159
} | class ____(graphene.Enum):
NEWHOPE = 4
EMPIRE = 5
JEDI = 6
| Episode |
python | huggingface__transformers | src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py | {
"start": 15358,
"end": 16999
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
super().__init__()
self.is_cross_attention = is_cross_attention
attention_class = RobertaPreLayerNormCrossAttention if is_cross_attention else RobertaPreLayerNormSelfAttention
... | RobertaPreLayerNormAttention |
python | ray-project__ray | python/ray/serve/tests/test_config_files/grpc_deployment.py | {
"start": 1779,
"end": 2901
} | class ____:
def __init__(
self,
_orange_stand: DeploymentHandle,
_apple_stand: DeploymentHandle,
):
self.directory = {
"ORANGE": _orange_stand,
"APPLE": _apple_stand,
}
async def FruitStand(self, fruit_amounts_proto):
fruit_amounts = {... | FruitMarket |
python | apache__airflow | providers/fab/src/airflow/providers/fab/www/api_connexion/exceptions.py | {
"start": 3700,
"end": 4193
} | class ____(ProblemException):
"""Raise when the user is not authenticated."""
def __init__(
self,
title: str = "Unauthorized",
detail: str | None = None,
headers: dict | None = None,
**kwargs: Any,
):
super().__init__(
status=HTTPStatus.UNAUTHORIZ... | Unauthenticated |
python | kamyu104__LeetCode-Solutions | Python/palindrome-partitioning.py | {
"start": 39,
"end": 933
} | class ____(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
is_palindrome = [[False] * len(s) for i in xrange(len(s))]
for i in reversed(xrange(len(s))):
for j in xrange(i, len(s)):
is_palindrome[i][j] = s[i] ==... | Solution |
python | scipy__scipy | scipy/optimize/tests/test__shgo.py | {
"start": 10297,
"end": 12054
} | class ____:
"""
Global optimisation tests with Sobol sampling:
"""
# Sobol algorithm
def test_f1_1_sobol(self):
"""Multivariate test function 1:
x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]"""
run_test(test1_1)
def test_f1_2_sobol(self):
"""Multivariate test... | TestShgoSobolTestFunctions |
python | tiangolo__fastapi | docs_src/cookie_param_models/tutorial001.py | {
"start": 112,
"end": 341
} | class ____(BaseModel):
session_id: str
fatebook_tracker: Union[str, None] = None
googall_tracker: Union[str, None] = None
@app.get("/items/")
async def read_items(cookies: Cookies = Cookie()):
return cookies
| Cookies |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 5966,
"end": 6489
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layers = torch.nn.ModuleList([])
for _ in range(3):
self.layers.append(
torch.nn.ModuleList(
[
torch.nn.Linear(10, 10),
... | NestedModuleList |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/repeat_test.py | {
"start": 3568,
"end": 6656
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_repeat_dataset(self,
num_elements,
num_epochs,
num_outputs=None,
options=None):
... | RepeatDatasetCheckpointTest |
python | huggingface__transformers | src/transformers/models/ovis2/modeling_ovis2.py | {
"start": 17807,
"end": 20360
} | class ____(Ovis2PreTrainedModel):
config: Ovis2VisionConfig
def __init__(self, config: Ovis2VisionConfig):
super().__init__(config)
self.config = config
self.transformer = Ovis2VisionTransformer(config)
self.num_visual_indicator_tokens = config.num_visual_indicator_tokens
... | Ovis2VisionModel |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyflakes/F821_27.py | {
"start": 1492,
"end": 1533
} | class ____: ...
# More circular references
| D |
python | doocs__leetcode | solution/2500-2599/2577.Minimum Time to Visit a Cell In a Grid/Solution.py | {
"start": 0,
"end": 807
} | class ____:
def minimumTime(self, grid: List[List[int]]) -> int:
if grid[0][1] > 1 and grid[1][0] > 1:
return -1
m, n = len(grid), len(grid[0])
dist = [[inf] * n for _ in range(m)]
dist[0][0] = 0
q = [(0, 0, 0)]
dirs = (-1, 0, 1, 0, -1)
while 1:
... | Solution |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 95997,
"end": 96313
} | class ____:
xlConsolidation = 3 # from enum XlPivotTableSourceType
xlDatabase = 1 # from enum XlPivotTableSourceType
xlExternal = 2 # from enum XlPivotTableSourceType
xlPivotTable = -4148 # from enum XlPivotTableSourceType
xlScenario = 4 # from enum XlPivotTableSourceType
| PivotTableSourceType |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 212920,
"end": 214560
} | class ____(Operation):
def call(self, condition, x1=None, x2=None):
return backend.numpy.where(condition, x1, x2)
def compute_output_spec(self, condition, x1, x2):
condition_shape = getattr(condition, "shape", [])
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape... | Where |
python | getsentry__sentry | src/sentry/replays/validators.py | {
"start": 581,
"end": 3014
} | class ____(serializers.Serializer):
statsPeriod = serializers.CharField(
help_text="""
This defines the range of the time series, relative to now. The range is given in a
`<number><unit>` format. For example `1d` for a one day range. Possible units are `m` for
minutes, `h` for hours, `d` for days and `w` fo... | ReplayValidator |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/git_test_commit/package.py | {
"start": 217,
"end": 1286
} | class ____(Package):
"""Mock package that tests installing specific commit"""
homepage = "http://www.git-fetch-example.com"
# git='to-be-filled-in-by-test'
# ----------------------------
# -- mock_git_repository, or mock_git_version_info
version("main", branch="main")
# ------------------... | GitTestCommit |
python | django-mptt__django-mptt | tests/myapp/models.py | {
"start": 514,
"end": 962
} | class ____(MPTTModel):
name = models.CharField(max_length=50)
visible = models.BooleanField(default=True)
parent = TreeForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
category_uuid = models.CharField(max_length=50, unique=True, null=True)
d... | Category |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_pretty.py | {
"start": 20035,
"end": 20375
} | class ____:
x: int
y: int = field(init=False)
def test_does_not_include_no_init_fields_in_dataclass_printing():
record = DataClassWithNoInitField(x=1)
assert pretty.pretty(record) == "DataClassWithNoInitField(x=1)"
record.y = 1
assert pretty.pretty(record) == "DataClassWithNoInitField(x=1)"
| DataClassWithNoInitField |
python | pypa__warehouse | tests/unit/admin/views/test_users.py | {
"start": 3775,
"end": 3953
} | class ____:
def test_validate(self):
form = views.EmailForm(formdata=MultiDict({"email": "foo@bar.net"}))
assert form.validate(), str(form.errors)
| TestEmailForm |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 144254,
"end": 144378
} | class ____(BaseModel, extra="forbid"):
update_vectors: "UpdateVectors" = Field(..., description="")
| UpdateVectorsOperation |
python | wandb__wandb | wandb/vendor/pygments/lexers/modula2.py | {
"start": 524,
"end": 52551
} | class ____(RegexLexer):
"""
For `Modula-2 <http://www.modula2.org/>`_ source code.
The Modula-2 lexer supports several dialects. By default, it operates in
fallback mode, recognising the *combined* literals, punctuation symbols
and operators of all supported dialects, and the *combined* reserved w... | Modula2Lexer |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 13148,
"end": 13415
} | class ____(str, Enum):
"""
Enum for DAG warning types.
This is the set of allowable values for the ``warning_type`` field
in the DagWarning model.
"""
ASSET_CONFLICT = "asset conflict"
NON_EXISTENT_POOL = "non-existent pool"
| DagWarningType |
python | joerick__pyinstrument | examples/falcon_hello.py | {
"start": 633,
"end": 854
} | class ____:
def on_get(self, req, resp):
time.sleep(1)
resp.media = "hello"
app = falcon.App()
if PROFILING:
app.add_middleware(ProfilerMiddleware())
app.add_route("/", HelloResource())
| HelloResource |
python | getsentry__sentry | src/sentry/uptime/grouptype.py | {
"start": 3379,
"end": 8148
} | class ____(StatefulDetectorHandler[UptimePacketValue, CheckStatus]):
@override
@property
def thresholds(self) -> DetectorThresholds:
recovery_threshold = self.detector.config["recovery_threshold"]
downtime_threshold = self.detector.config["downtime_threshold"]
return {
D... | UptimeDetectorHandler |
python | django-crispy-forms__django-crispy-forms | tests/forms.py | {
"start": 1565,
"end": 2497
} | class ____(BaseForm):
checkboxes = forms.MultipleChoiceField(
choices=((1, "Option one"), (2, "Option two"), (3, "Option three")),
initial=(1,),
widget=forms.CheckboxSelectMultiple,
)
alphacheckboxes = forms.MultipleChoiceField(
choices=(("option_one", "Option one"), ("optio... | CheckboxesSampleForm |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_dc_transforms.py | {
"start": 72506,
"end": 77278
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
"""tests for #8718"""
__dialect__ = "default"
@testing.fixture
def model(self):
def go(use_mixin, use_inherits, mad_setup, dataclass_kw):
if use_mixin:
if mad_setup == "dc, mad":
class B... | MixinColumnTest |
python | plotly__plotly.py | plotly/graph_objs/layout/slider/_currentvalue.py | {
"start": 235,
"end": 6059
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.slider"
_path_str = "layout.slider.currentvalue"
_valid_props = {"font", "offset", "prefix", "suffix", "visible", "xanchor"}
@property
def font(self):
"""
Sets the font of the current value label text.
The 'fo... | Currentvalue |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/resnet.py | {
"start": 2341,
"end": 4562
} | class ____(nn.Module):
"""ResNetV1."""
stage_sizes: Sequence[int]
block_cls: ModuleDef
num_classes: int
num_filters: int = 64
dtype: Any = jnp.float32
act: Callable = nn.relu
conv: ModuleDef = nn.Conv
@nn.compact
def __call__(self, x, train: bool = True):
conv = partial(self.conv, use_bias=Fals... | ResNet |
python | encode__django-rest-framework | tests/test_middleware.py | {
"start": 789,
"end": 985
} | class ____(APIView):
def get(self, request):
return Response(data="OK", status=200)
@api_view(['GET'])
def get_func_view(request):
return Response(data="OK", status=200)
| GetAPIView |
python | pytorch__pytorch | torch/fx/passes/infra/pass_base.py | {
"start": 324,
"end": 729
} | class ____(namedtuple("PassResult", ["graph_module", "modified"])):
"""
Result of a pass:
graph_module: The modified graph module
modified: A flag for if the pass has modified the graph module
"""
__slots__ = ()
def __new__(cls, graph_module, modified):
return super().__new... | PassResult |
python | pytorch__pytorch | torch/distributed/flight_recorder/components/types.py | {
"start": 4117,
"end": 5310
} | class ____(NamedTuple):
groups: list[Group]
memberships: list[Membership]
tracebacks: list[Traceback]
collectives: list[Collective]
ncclcalls: list[NCCLCall]
# TODO: We need to add a schema for the following
types = [
TypeInfo.from_type(t) # type: ignore[type-var]
for t in [Database, NCCL... | Database |
python | django__django | tests/get_or_create/models.py | {
"start": 525,
"end": 629
} | class ____(models.Model):
person = models.ForeignKey(Person, models.CASCADE, primary_key=True)
| Profile |
python | ray-project__ray | rllib/connectors/module_to_env/module_to_env_pipeline.py | {
"start": 150,
"end": 207
} | class ____(ConnectorPipelineV2):
pass
| ModuleToEnvPipeline |
python | getsentry__sentry | src/sentry/objectstore/endpoints/organization.py | {
"start": 394,
"end": 1513
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
"PUT": ApiPublishStatus.EXPERIMENTAL,
"DELETE": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.FOUNDATIONAL_STORAGE
def get(self, request: Request, organization: Organization) -> Respon... | OrganizationObjectstoreEndpoint |
python | pytorch__pytorch | torch/distributed/algorithms/_comm_hooks/default_hooks.py | {
"start": 1353,
"end": 7616
} | class ____(DefaultState):
r"""
Stores state needed to perform gradient communication in a lower precision within a communication hook.
Communication hook will cast gradients back to the original
parameter precision specified by ``parameter_type`` (default: torch.float32).
Builds on top of the :clas... | LowPrecisionState |
python | kamyu104__LeetCode-Solutions | Python/minimize-result-by-adding-parentheses-to-expression.py | {
"start": 64,
"end": 1352
} | class ____(object):
def minimizeResult(self, expression):
"""
:type expression: str
:rtype: str
"""
def stoi(s, i, j):
result = 0
for k in xrange(i, j):
result = result*10+(ord(s[k])-ord('0'))
return result
best = N... | Solution |
python | plotly__plotly.py | plotly/graph_objs/sankey/_link.py | {
"start": 233,
"end": 28100
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sankey"
_path_str = "sankey.link"
_valid_props = {
"arrowlen",
"color",
"colorscaledefaults",
"colorscales",
"colorsrc",
"customdata",
"customdatasrc",
"hovercolor",
"hovercolorsr... | Link |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/redshift/resources.py | {
"start": 9056,
"end": 9169
} | class ____(RedshiftClient):
"""This class was used by the function-style Redshift resource."""
| RedshiftResource |
python | joke2k__faker | tests/providers/test_bank.py | {
"start": 7434,
"end": 7900
} | class ____:
"""Test pt_PT bank provider"""
def test_bban(self, faker, num_samples):
for _ in range(num_samples):
assert re.fullmatch(r"\d{21}", faker.bban())
def test_iban(self, faker, num_samples):
for _ in range(num_samples):
iban = faker.iban()
assert... | TestPtPt |
python | crytic__slither | slither/core/expressions/unary_operation.py | {
"start": 3209,
"end": 4357
} | class ____(Expression):
def __init__(
self,
expression: Union[Literal, Identifier, IndexAccess, TupleExpression],
expression_type: UnaryOperationType,
) -> None:
assert isinstance(expression, Expression)
super().__init__()
self._expression: Expression = expression... | UnaryOperation |
python | getsentry__sentry | src/sentry/rules/conditions/event_attribute.py | {
"start": 12316,
"end": 12901
} | class ____(AttributeHandler):
minimum_path_length = 2
@classmethod
def _handle(cls, path: list[str], event: GroupEvent) -> list[str]:
if path[1] in (
"screen_density",
"screen_dpi",
"screen_height_pixels",
"screen_width_pixels",
):
... | DeviceAttributeHandler |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 1448,
"end": 1570
} | class ____:
def analyze(self, laparams):
"""Perform the layout analysis."""
return
## LTText
##
| LTItem |
python | google__jax | jax/_src/pallas/pipelining/internal.py | {
"start": 1440,
"end": 1739
} | class ____:
max_in_flight: int
is_async_start: bool
is_async_done: bool
def __post_init__(self):
if self.is_async_start and self.is_async_done:
raise ValueError(
"Async start and async done are mutually exclusive.")
@dataclasses.dataclass(frozen=True)
| SchedulingProperties |
python | ansible__ansible | lib/ansible/utils/encrypt.py | {
"start": 3478,
"end": 7879
} | class ____(BaseHash):
algorithms = {
**BaseHash.algorithms,
'yescrypt': _Algo(crypt_id='y', salt_size=16, implicit_rounds=5, rounds_format='cost', requires_gensalt=True, salt_exact=True),
}
def __init__(self, algorithm: str) -> None:
super(CryptHash, self).__init__(algorithm)
... | CryptHash |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/xent_op_test.py | {
"start": 1271,
"end": 3221
} | class ____(xent_op_test_base.XentOpTestBase):
@test_util.run_deprecated_v1
def testRankTooLarge(self):
for dtype in np.float16, np.float32:
np_features = np.array([[[1., 1., 1., 1.]], [[1., 2., 3.,
4.]]]).astype(dtype)
np_labels = np.array([[[0., ... | XentOpTest |
python | apache__airflow | providers/slack/tests/unit/slack/notifications/test_slack.py | {
"start": 1064,
"end": 6611
} | class ____:
@mock.patch("airflow.providers.slack.notifications.slack.SlackHook")
@pytest.mark.parametrize(
("extra_kwargs", "hook_extra_kwargs"),
[
pytest.param({}, DEFAULT_HOOKS_PARAMETERS, id="default-hook-parameters"),
pytest.param(
{
... | TestSlackNotifier |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/serializer.py | {
"start": 786,
"end": 8557
} | class ____:
# 'id' and 3+ numbers, but not 000
ANCHOR_TEMPLATE = 'id%03d'
ANCHOR_RE = RegExp('id(?!000$)\\d{3,}')
def __init__(
self,
encoding=None,
explicit_start=None,
explicit_end=None,
version=None,
tags=None,
dumper=None,
):
# ty... | Serializer |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/routers/test_builder_ingress.py | {
"start": 6273,
"end": 12640
} | class ____:
@pytest.fixture
def llm_config(self):
"""Basic LLMConfig for testing."""
return LLMConfig(
model_loading_config=ModelLoadingConfig(
model_id="test-model", model_source="test-source"
)
)
def test_build_openai_app(
self, get_... | TestBuildOpenaiApp |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/rpc_test.py | {
"start": 4485,
"end": 9608
} | class ____:
def __init__(self, a, delay=False):
self.a = a
# delay initialization to simulate errors if specified
if delay:
time.sleep(2)
def my_instance_method(self, b):
return self.a + b
@classmethod
def my_class_method(cls, d, e):
return d + e
... | MyClass |
python | huggingface__transformers | src/transformers/models/roberta/modular_roberta.py | {
"start": 5846,
"end": 5904
} | class ____(BertLayer):
pass
@auto_docstring
| RobertaLayer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/self2.py | {
"start": 3331,
"end": 4006
} | class ____:
scale: float = 1.0
def set_scale(self, scale: float) -> ReturnConcreteShape:
return ReturnConcreteShape()
def accepts_shape(shape: ShapeProtocol) -> None:
y = shape.set_scale(0.5)
reveal_type(y)
def main(
return_self_shape: ReturnSelf,
return_concrete_shape: ReturnConcre... | ReturnDifferentClass |
python | joke2k__faker | faker/providers/bank/es_MX/__init__.py | {
"start": 767,
"end": 7785
} | class ____(BankProvider):
"""Bank provider for ``es_MX`` locale."""
banks: Tuple[str, ...] = (
"ABC Capital, S.A. I.B.M.",
"Acciones y Valores Banamex, S.A. de C.V., Casa de Bolsa",
"Actinver Casa de Bolsa, S.A. de C.V.",
"Akala, S.A. de C.V., Sociedad Financiera Popular",
... | Provider |
python | ansible__ansible | lib/ansible/plugins/strategy/__init__.py | {
"start": 2464,
"end": 8355
} | class ____:
pass
_sentinel = StrategySentinel()
if t.TYPE_CHECKING:
from ansible.inventory.host import Host
def _get_item_vars(result, task):
item_vars = {}
if task.loop or task.loop_with:
loop_var = result.get('ansible_loop_var', 'item')
index_var = result.get('ansible_index_var')
... | StrategySentinel |
python | PrefectHQ__prefect | src/prefect/client/orchestration/_automations/client.py | {
"start": 351,
"end": 5561
} | class ____(BaseClient):
def create_automation(self, automation: "AutomationCore") -> "UUID":
"""Creates an automation in Prefect Cloud."""
response = self.request(
"POST",
"/automations/",
json=automation.model_dump(mode="json"),
)
from uuid import... | AutomationClient |
python | PyCQA__pylint | pylint/extensions/mccabe.py | {
"start": 1285,
"end": 1490
} | class ____(Mccabe_PathGraph): # type: ignore[misc]
def __init__(self, node: _SubGraphNodes | nodes.FunctionDef):
super().__init__(name="", entity="", lineno=1)
self.root = node
| PathGraph |
python | gevent__gevent | src/gevent/tests/known_failures.py | {
"start": 4454,
"end": 4498
} | class ____(_Action):
__slots__ = ()
| Failing |
python | kamyu104__LeetCode-Solutions | Python/time-taken-to-mark-all-nodes.py | {
"start": 1717,
"end": 2778
} | class ____(object):
def timeTaken(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
def dfs1(u, p):
for v in adj[u]:
if v == p:
continue
dfs1(v, u)
curr = [(1+int(v%2 == 0))+dp[... | Solution2 |
python | getsentry__sentry | src/sentry/replays/usecases/query/conditions/tags.py | {
"start": 1529,
"end": 2642
} | class ____(GenericBase):
"""Tag aggregate condition class."""
@staticmethod
def visit_eq(expression_name: str, value: str) -> Condition:
return Condition(_match_key_value_exact(expression_name, value), Op.EQ, 1)
@staticmethod
def visit_neq(expression_name: str, value: str) -> Condition:
... | TagAggregate |
python | gevent__gevent | src/gevent/_waiter.py | {
"start": 6109,
"end": 7387
} | class ____(Waiter):
"""
An internal extension of Waiter that can be used if multiple objects
must be waited on, and there is a chance that in between waits greenlets
might be switched out. All greenlets that switch to this waiter
will have their value returned.
This does not handle exceptions o... | MultipleWaiter |
python | wandb__wandb | wandb/vendor/pygments/lexers/hdl.py | {
"start": 6497,
"end": 14692
} | class ____(RegexLexer):
"""
Extends verilog lexer to recognise all SystemVerilog keywords from IEEE
1800-2009 standard.
.. versionadded:: 1.5
"""
name = 'systemverilog'
aliases = ['systemverilog', 'sv']
filenames = ['*.sv', '*.svh']
mimetypes = ['text/x-systemverilog']
#: optio... | SystemVerilogLexer |
python | weaviate__weaviate-python-client | weaviate/collections/classes/tenants.py | {
"start": 3906,
"end": 4476
} | class ____(str, Enum):
"""TenantActivityStatus class used to describe the activity status of a tenant to create in Weaviate.
Attributes:
ACTIVE: The tenant is fully active and can be used.
INACTIVE: The tenant is not active, files stored locally.
HOT: DEPRECATED, please use ACTIVE. The ... | TenantCreateActivityStatus |
python | doocs__leetcode | lcp/LCP 11. 期望个数统计/Solution.py | {
"start": 0,
"end": 102
} | class ____:
def expectNumber(self, scores: List[int]) -> int:
return len(set(scores))
| Solution |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 14496,
"end": 14637
} | class ____(_TestDSTIBase):
def setup_method(self):
self.rdt = np.float64
self.dec = 12
self.type = 1
| TestDSTIDouble |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 28366,
"end": 29170
} | class ____(DiagnosticPipError):
"""Raised when the dependency resolver exceeds the maximum recursion depth."""
reference = "resolution-too-deep"
def __init__(self) -> None:
super().__init__(
message="Dependency resolution exceeded maximum depth",
context=(
"... | ResolutionTooDeepError |
python | donnemartin__system-design-primer | solutions/system_design/social_graph/social_graph_snippets.py | {
"start": 729,
"end": 863
} | class ____(object):
def __init__(self, id, name):
self.id = id
self.name = name
self.friend_ids = []
| Person |
python | PrefectHQ__prefect | src/integrations/prefect-aws/tests/test_secrets_manager.py | {
"start": 4561,
"end": 9419
} | class ____:
"""Test asynchronous AwsSecret methods"""
async def test_read_secret(self, secret_under_test, aws_credentials):
expected_value = secret_under_test.pop("expected_value")
secret_name = secret_under_test.pop(
"secret_name"
) # Remove secret_name from kwargs
... | TestAwsSecretAsync |
python | doocs__leetcode | solution/0600-0699/0680.Valid Palindrome II/Solution.py | {
"start": 0,
"end": 429
} | class ____:
def validPalindrome(self, s: str) -> bool:
def check(i, j):
while i < j:
if s[i] != s[j]:
return False
i, j = i + 1, j - 1
return True
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
... | Solution |
python | joke2k__faker | tests/providers/test_date_time.py | {
"start": 30564,
"end": 31280
} | class ____(unittest.TestCase):
num_sample_runs = 50
def setUp(self):
self.setup_constants()
self.setup_faker()
def setup_faker(self):
self.fake = Faker("fil_PH")
Faker.seed(0)
def setup_constants(self):
from faker.providers.date_time.fil_PH import Provider
... | TestFilPh |
python | django__django | django/db/migrations/migration.py | {
"start": 9310,
"end": 9765
} | class ____(tuple):
"""
Subclass of tuple so Django can tell this was originally a swappable
dependency when it reads the migration file.
"""
def __new__(cls, value, setting):
self = tuple.__new__(cls, value)
self.setting = setting
return self
def swappable_dependency(value... | SwappableTuple |
python | dask__distributed | distributed/deploy/tests/test_adaptive.py | {
"start": 16411,
"end": 22639
} | class ____(Adaptive):
def __init__(self, *args, interval=None, **kwargs):
super().__init__(*args, interval=interval, **kwargs)
self._target = 0
self._log = []
self._observed = set()
self._plan = set()
self._requested = set()
@property
def observed(self):
... | MyAdaptive |
python | realpython__materials | typer-cli-python/source_code_final/rptodo/database.py | {
"start": 794,
"end": 877
} | class ____(NamedTuple):
todo_list: List[Dict[str, Any]]
error: int
| DBResponse |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py | {
"start": 4018,
"end": 5662
} | class ____(TestCase):
def test_encoded_size_is_within_expected_limit(self) -> None:
state = _RendezvousState()
state.round = 1
state.complete = True
state.deadline = datetime.now(timezone.utc)
state.closed = True
# fmt: off
expected_max_sizes = (
... | RendezvousStateTest |
python | huggingface__transformers | tests/models/pvt_v2/test_modeling_pvt_v2.py | {
"start": 12365,
"end": 14971
} | class ____(BackboneTesterMixin, unittest.TestCase):
all_model_classes = (PvtV2Backbone,) if is_torch_available() else ()
has_attentions = False
config_class = PvtV2Config
def test_config(self):
config_class = self.config_class
# test default config
config = config_class()
... | PvtV2BackboneTest |
python | neetcode-gh__leetcode | python/0040-combination-sum-ii.py | {
"start": 0,
"end": 693
} | class ____:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
res = []
def backtrack(cur, pos, target):
if target == 0:
res.append(cur.copy())
return
if target <= 0:
re... | Solution |
python | wandb__wandb | wandb/cli/beta_sync.py | {
"start": 2856,
"end": 6960
} | class ____:
"""Displays a sync operation's status until it completes."""
def __init__(
self,
id: str,
service: ServiceConnection,
printer: Printer,
) -> None:
self._id = id
self._service = service
self._printer = printer
self._rate_limit_last... | _SyncStatusLoop |
python | chroma-core__chroma | chromadb/api/types.py | {
"start": 28316,
"end": 46383
} | class ____(Protocol[L]):
def __call__(self, uris: URIs) -> L:
...
def validate_ids(ids: IDs) -> IDs:
"""Validates ids to ensure it is a list of strings"""
if not isinstance(ids, list):
raise ValueError(f"Expected IDs to be a list, got {type(ids).__name__} as IDs")
if len(ids) == 0:
... | DataLoader |
python | ray-project__ray | python/ray/util/state/common.py | {
"start": 40600,
"end": 55228
} | class ____:
#: Group key -> summary.
#: Right now, we only have func_class_name as a key.
# TODO(sang): Support the task group abstraction.
summary: Union[Dict[str, TaskSummaryPerFuncOrClassName], List[NestedTaskSummary]]
#: Total Ray tasks.
total_tasks: int
#: Total actor tasks.
total_a... | TaskSummaries |
python | sqlalchemy__sqlalchemy | test/orm/test_cascade.py | {
"start": 122822,
"end": 129487
} | class ____(fixtures.MappedTest):
"""Test that cascades are trimmed accordingly when viewonly is set.
Originally #4993 and #4994 this was raising an error for invalid
cascades. in 2.0 this is simplified to just remove the write
cascades, allows the default cascade to be reasonable.
"""
@class... | ViewonlyCascadeUpdate |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess7.py | {
"start": 458,
"end": 640
} | class ____(metaclass=MetaClass):
pass
v1 = ClassB.some_function(3)
reveal_type(v1, expected_text="int")
v2 = ClassB.some_function("hi")
reveal_type(v2, expected_text="str")
| ClassB |
python | bokeh__bokeh | src/bokeh/core/property/any.py | {
"start": 1379,
"end": 2347
} | class ____(Property[typing.Any]):
""" Accept all values.
The ``Any`` property does not do any validation or transformation.
Args:
default (obj or None, optional) :
A default value for attributes created from this property to
have (default: None)
help (str or None, ... | Any |
python | pytest-dev__pytest-cov | src/pytest_cov/__init__.py | {
"start": 194,
"end": 323
} | class ____(pytest.PytestWarning):
"""
The base for all pytest-cov warnings, never raised directly.
"""
| PytestCovWarning |
python | django__django | tests/sessions_tests/tests.py | {
"start": 33522,
"end": 33593
} | class ____(CacheDBSessionTests):
pass
| CacheDBSessionWithTimeZoneTests |
python | ray-project__ray | python/ray/util/actor_group.py | {
"start": 377,
"end": 516
} | class ____:
"""Class containing an actor and its metadata."""
actor: ActorHandle
metadata: ActorMetadata
@dataclass
| ActorWrapper |
python | getsentry__sentry | src/sentry/types/region.py | {
"start": 3929,
"end": 4042
} | class ____(Exception):
"""Indicate that the server is not in a state to resolve a region."""
| RegionContextError |
python | bokeh__bokeh | src/bokeh/models/annotations/geometry.py | {
"start": 17354,
"end": 19325
} | class ____(DataAnnotation):
''' Render a whisker along a dimension.
See :ref:`ug_basic_annotations_whiskers` for information on plotting whiskers.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
... | Whisker |
python | great-expectations__great_expectations | tests/expectations/metrics/query_metrics/test_query_metrics.py | {
"start": 6011,
"end": 7610
} | class ____(QueryRowCount):
metric_name = "my_query.row_count"
value_keys = ("my_query",)
query_param_name: ClassVar[str] = "my_query"
@pytest.mark.unit
@mock.patch.object(sa, "text")
@mock.patch.object(
QueryMetricProvider, "_get_substituted_batch_subquery_from_query_and_batch_selectable"
)
def test_... | MyQueryRowCount |
python | kamyu104__LeetCode-Solutions | Python/minimum-impossible-or.py | {
"start": 64,
"end": 294
} | class ____(object):
def minImpossibleOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lookup = set(nums)
return next(1<<i for i in xrange(31) if 1<<i not in lookup)
| Solution |
python | viewflow__viewflow | viewflow/workflow/flow/views/detail.py | {
"start": 453,
"end": 1387
} | class ____(generic.RedirectView):
"""Redirect for a flow.View node."""
def get_redirect_url(self, *args, **kwargs):
activation = self.request.activation
task = activation.task
flow_task = activation.flow_task
if activation.start.can_proceed() and flow_task.can_execute(
... | UserIndexTaskView |
python | django__django | tests/m2m_multiple/models.py | {
"start": 301,
"end": 471
} | class ____(models.Model):
name = models.CharField(max_length=20)
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
| Category |
python | kamyu104__LeetCode-Solutions | Python/minimize-the-difference-between-target-and-chosen-elements.py | {
"start": 50,
"end": 540
} | class ____(object):
def minimizeTheDifference(self, mat, target):
"""
:type mat: List[List[int]]
:type target: int
:rtype: int
"""
chosen_min = sum(min(row) for row in mat)
if chosen_min >= target:
return chosen_min-target
dp = {0}
... | Solution |
python | scikit-image__scikit-image | benchmarks/benchmark_rank.py | {
"start": 225,
"end": 612
} | class ____:
param_names = ["filter_func", "shape"]
params = [sorted(all_rank_filters), [(32, 32), (256, 256)]]
def setup(self, filter_func, shape):
self.image = np.random.randint(0, 255, size=shape, dtype=np.uint8)
self.footprint = disk(1)
def time_filter(self, filter_func, shape):
... | RankSuite |
python | Netflix__metaflow | metaflow/_vendor/click/exceptions.py | {
"start": 6930,
"end": 7282
} | class ____(UsageError):
"""Raised if an argument is generally supplied but the use of the argument
was incorrect. This is for instance raised if the number of values
for an argument is not correct.
.. versionadded:: 6.0
"""
def __init__(self, message, ctx=None):
UsageError.__init__(se... | BadArgumentUsage |
python | scrapy__scrapy | scrapy/spidermiddlewares/urllength.py | {
"start": 510,
"end": 1494
} | class ____(BaseSpiderMiddleware):
crawler: Crawler
def __init__(self, maxlength: int): # pylint: disable=super-init-not-called
self.maxlength: int = maxlength
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
maxlength = crawler.settings.getint("URLLENGTH_LIMIT")
i... | UrlLengthMiddleware |
python | django-guardian__django-guardian | guardian/testapp/migrations/0008_fix_project_timezone.py | {
"start": 121,
"end": 453
} | class ____(migrations.Migration):
dependencies = [
("testapp", "0007_genericgroupobjectpermission"),
]
operations = [
migrations.AlterField(
model_name="project",
name="created_at",
field=models.DateTimeField(default=django.utils.timezone.now),
),... | Migration |
python | chroma-core__chroma | chromadb/utils/embedding_functions/roboflow_embedding_function.py | {
"start": 396,
"end": 5182
} | class ____(EmbeddingFunction[Embeddable]):
"""
This class is used to generate embeddings for a list of texts or images using the Roboflow API.
"""
def __init__(
self,
api_key: Optional[str] = None,
api_url: str = "https://infer.roboflow.com",
api_key_env_var: str = "CHRO... | RoboflowEmbeddingFunction |
python | pennersr__django-allauth | allauth/mfa/recovery_codes/views.py | {
"start": 3030,
"end": 3644
} | class ____(TemplateView):
template_name = "mfa/recovery_codes/index." + account_settings.TEMPLATE_EXTENSION
def get_context_data(self, **kwargs):
ret = super().get_context_data(**kwargs)
authenticator = flows.view_recovery_codes(self.request)
if not authenticator:
raise Http... | ViewRecoveryCodesView |
python | pypa__setuptools | pkg_resources/__init__.py | {
"start": 64390,
"end": 65056
} | class ____(NullProvider):
"""Provider based on a virtual filesystem"""
def __init__(self, module: _ModuleLike) -> None:
super().__init__(module)
self._setup_prefix()
def _setup_prefix(self):
# Assume that metadata may be nested inside a "basket"
# of multiple eggs and use m... | EggProvider |
python | doocs__leetcode | solution/2600-2699/2603.Collect Coins in a Tree/Solution.py | {
"start": 0,
"end": 787
} | class ____:
def collectTheCoins(self, coins: List[int], edges: List[List[int]]) -> int:
g = defaultdict(set)
for a, b in edges:
g[a].add(b)
g[b].add(a)
n = len(coins)
q = deque(i for i in range(n) if len(g[i]) == 1 and coins[i] == 0)
while q:
... | Solution |
python | pytorch__pytorch | torch/export/dynamic_shapes.py | {
"start": 26508,
"end": 29875
} | class ____:
"""
Builder for dynamic_shapes.
Used to assign dynamic shape specifications to tensors that appear in inputs.
This is useful particularly when :func:`args` is a nested input structure, and it's
easier to index the input tensors, than to replicate the structure of :func:`args` in
the... | ShapesCollection |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_to_be_polygon_area_between.py | {
"start": 1115,
"end": 2867
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
# Please see {some doc} for information on how to choose an id string for your Metric.
condition_metric_name = "column_values.polygon_area"
condition_value_keys = (
"min_area",
"max_a... | ColumnValuesPolygonArea |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.