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 | django__django | tests/forms_tests/tests/tests.py | {
"start": 2230,
"end": 9344
} | class ____(TestCase):
def test_no_empty_option(self):
"""
If a model's ForeignKey has blank=False and a default, no empty option
is created.
"""
option = ChoiceOptionModel.objects.create(name="default")
choices = list(ChoiceFieldForm().fields["choice"].choices)
... | ModelFormCallableModelDefault |
python | pandas-dev__pandas | pandas/tests/frame/test_reductions.py | {
"start": 5891,
"end": 55177
} | class ____:
# ---------------------------------------------------------------------
# Reductions
@pytest.mark.parametrize("axis", [0, 1])
@pytest.mark.parametrize(
"opname",
[
"count",
"sum",
"mean",
"product",
"median",
... | TestDataFrameAnalytics |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/tokens.py | {
"start": 8147,
"end": 11015
} | class ____(TokenBase):
__slots__ = (
'request_validator', 'token_generator',
'refresh_token_generator', 'expires_in'
)
def __init__(self, request_validator=None, token_generator=None,
expires_in=None, refresh_token_generator=None):
self.request_validator = request_v... | BearerToken |
python | huggingface__transformers | src/transformers/models/conditional_detr/configuration_conditional_detr.py | {
"start": 908,
"end": 12713
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ConditionalDetrModel`]. It is used to instantiate
a Conditional DETR model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yiel... | ConditionalDetrConfig |
python | readthedocs__readthedocs.org | readthedocs/projects/models.py | {
"start": 56923,
"end": 57351
} | class ____(ImportedFile):
"""
Imported HTML file Proxy model.
This tracks only the HTML files for indexing to search.
"""
class Meta:
proxy = True
objects = HTMLFileManager()
def get_processed_json(self):
parser = GenericParser(self.version)
return parser.parse(se... | HTMLFile |
python | astropy__astropy | astropy/coordinates/tests/test_transformations.py | {
"start": 2020,
"end": 2050
} | class ____(ICRS):
pass
| TCoo1 |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py | {
"start": 61130,
"end": 77508
} | class ____:
def _dags_for_trigger_tests(self, session=None):
inactive_dag = DagModel(
dag_id="inactive",
bundle_name="testing",
fileloc="/tmp/dag_del_1.py",
timetable_summary="2 2 * * *",
is_stale=True,
is_paused=True,
owner... | TestTriggerDagRun |
python | pytorch__pytorch | test/quantization/fx/test_model_report_fx.py | {
"start": 50792,
"end": 62605
} | class ____(QuantizationTestCase):
class SimpleConv(torch.nn.Module):
def __init__(self, con_dims):
super().__init__()
self.relu = torch.nn.ReLU()
self.conv = torch.nn.Conv2d(con_dims[0], con_dims[1], kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
... | TestFxDetectInputWeightEqualization |
python | doocs__leetcode | solution/0600-0699/0642.Design Search Autocomplete System/Solution.py | {
"start": 659,
"end": 1647
} | class ____:
def __init__(self, sentences: List[str], times: List[int]):
self.trie = Trie()
for a, b in zip(sentences, times):
self.trie.insert(a, b)
self.t = []
def input(self, c: str) -> List[str]:
def dfs(node):
if node is None:
return
... | AutocompleteSystem |
python | great-expectations__great_expectations | great_expectations/data_context/types/base.py | {
"start": 50799,
"end": 52566
} | class ____(DictDot):
"""
Define base defaults for platform specific StoreBackendDefaults.
StoreBackendDefaults define defaults for specific cases of often used configurations.
For example, if you plan to store expectations, validations, and data_docs in s3 use the S3StoreBackendDefaults and you may be a... | BaseStoreBackendDefaults |
python | doocs__leetcode | lcof2/剑指 Offer II 066. 单词之和/Solution.py | {
"start": 0,
"end": 570
} | class ____:
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = defaultdict(int)
self.t = defaultdict(int)
def insert(self, key: str, val: int) -> None:
old = self.t[key]
self.t[key] = val
for i in range(1, len(key) + 1):
... | MapSum |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 113147,
"end": 113533
} | class ____(CReferenceBaseType):
is_rvalue_reference = 1
def __str__(self):
return "%s &&" % self.ref_base_type
def declaration_code(self, entity_code,
for_display = 0, dll_linkage = None, pyrex = 0):
return self.ref_base_type.declaration_code(
"&&%s" % entity_code,... | CppRvalueReferenceType |
python | kamyu104__LeetCode-Solutions | Python/missing-number-in-arithmetic-progression.py | {
"start": 32,
"end": 554
} | class ____(object):
def missingNumber(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
def check(arr, d, x):
return arr[x] != arr[0] + d*x
d = (arr[-1]-arr[0])//len(arr)
left, right = 0, len(arr)-1
while left <= right:
mid ... | Solution |
python | django__django | tests/generic_views/views.py | {
"start": 6231,
"end": 6469
} | class ____(generic.list.MultipleObjectMixin, generic.View):
queryset = [
{"name": "John"},
{"name": "Yoko"},
]
def get(self, request):
self.object_list = self.get_queryset()
| CustomMultipleObjectMixinView |
python | pytorch__pytorch | .ci/lumen_cli/tests/test_cli_helper.py | {
"start": 244,
"end": 378
} | class ____(BaseRunner):
"""Foo description from docstring."""
def run(self) -> None: # replaced by mock
pass
| FooRunner |
python | pypa__setuptools | setuptools/_distutils/tests/support.py | {
"start": 300,
"end": 1370
} | class ____:
"""
Mix-in class that handles temporary directories for test cases.
"""
def mkdtemp(self):
"""Create a temporary directory that will be cleaned up.
Returns the path of the directory.
"""
d = tempfile.mkdtemp()
self.tempdirs.append(d)
return d... | TempdirManager |
python | getsentry__sentry-python | tests/conftest.py | {
"start": 16739,
"end": 18873
} | class ____(BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
# Process an HTTP GET request and return a response.
# If the path ends with /status/<number>, return status code <number>.
# Otherwise return a 200 response.
code = 200
if "/status/" in self.path:
... | MockServerRequestHandler |
python | qdrant__qdrant-client | qdrant_client/http/api/collections_api.py | {
"start": 7616,
"end": 9691
} | class ____(_CollectionsApi):
def collection_exists(
self,
collection_name: str,
) -> m.InlineResponse2006:
"""
Returns \"true\" if the given collection name exists, and \"false\" otherwise
"""
return self._build_for_collection_exists(
collection_name=c... | SyncCollectionsApi |
python | networkx__networkx | networkx/generators/tests/test_geometric.py | {
"start": 11030,
"end": 18087
} | class ____:
"""Unit tests for :func:`~networkx.thresholded_random_geometric_graph`"""
def test_number_of_nodes(self):
G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1, seed=42)
assert len(G) == 50
G = nx.thresholded_random_geometric_graph(range(50), 0.2, 0.1, seed=42)
asse... | TestThresholdedRandomGeometricGraph |
python | huggingface__transformers | src/transformers/models/mgp_str/processing_mgp_str.py | {
"start": 940,
"end": 1167
} | class ____(ExplicitEnum):
CHARACTER = "char"
BPE = "bpe"
WORDPIECE = "wp"
SUPPORTED_ANNOTATION_FORMATS = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)
@requires(backends=("sentencepiece",))
| DecodeType |
python | joke2k__faker | faker/providers/person/tr_TR/__init__.py | {
"start": 44,
"end": 30455
} | class ____(PersonProvider):
formats_female = (
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{first_name_female}} {{last_name}}",
"{{first_name_female}} {{last_name}}",
"{{first_name_female}} {{first_name_female}} {{last_name}} {{last_name}}",
"{{first_name_f... | Provider |
python | kamyu104__LeetCode-Solutions | Python/count-of-range-sum.py | {
"start": 1528,
"end": 3020
} | class ____(object):
def countRangeSum(self, nums, lower, upper):
"""
:type nums: List[int]
:type lower: int
:type upper: int
:rtype: int
"""
def countAndMergeSort(sums, start, end, lower, upper):
if end - start <= 0: # The size of range [start, en... | Solution2 |
python | keras-team__keras | keras/src/trainers/trainer_test.py | {
"start": 99954,
"end": 101746
} | class ____(test_case.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
("single_device", False),
("distributed", True),
)
def test_jit_fit_with_out_shardings_logic(self, distributed):
if keras.backend.backend() != "jax":
self.skipTest("This test requires... | JAXTrainerCorrectnessTest |
python | getsentry__sentry | src/sentry/lang/native/applecrashreport.py | {
"start": 467,
"end": 11956
} | class ____:
def __init__(
self, threads=None, context=None, debug_images=None, symbolicated=False, exceptions=None
):
"""
Create an Apple crash report from the provided data.
This constructor can modify the passed structures in place.
"""
self.threads = threads i... | AppleCrashReport |
python | pytorch__pytorch | torch/fx/experimental/accelerator_partitioner.py | {
"start": 569,
"end": 1261
} | class ____:
"""DAGNode class maintains useful information for a partition (submodule),
and its input submodules and output submodules.
"""
def __init__(
self,
submodule_node: Node,
input_nodes: list[Node],
output_nodes: list[Node],
logical_device_ids: list[int],
... | DAGNode |
python | django__django | tests/admin_default_site/sites.py | {
"start": 35,
"end": 84
} | class ____(admin.AdminSite):
pass
| CustomAdminSite |
python | ray-project__ray | python/ray/_private/prometheus_exporter.py | {
"start": 633,
"end": 2001
} | class ____(object):
"""Options contains options for configuring the exporter.
The address can be empty as the prometheus client will
assume it's localhost
:type namespace: str
:param namespace: The prometheus namespace to be used. Defaults to ''.
:type port: int
:param port: The Prometheus p... | Options |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess21.py | {
"start": 667,
"end": 923
} | class ____:
field1: ClassVar = Descriptor[str]()
field2: ClassVar = ""
def reset(self) -> None:
self.field1 = ""
# This should generate an error because field2 isn't
# a descriptor object.
self.field2 = ""
| Example |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/models.py | {
"start": 971,
"end": 1065
} | class ____(models.Field):
def db_type(self, connection):
return "char(1)"
| CharmField |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-that-sum-of-the-prices-is-less-than-or-equal-to-k.py | {
"start": 3190,
"end": 4078
} | class ____(object):
def findMaximumNumber(self, k, x):
"""
:type k: int
:type x: int
:rtype: int
"""
def binary_search_right(left, right, check):
while left <= right:
mid = left+(right-left)//2
if not check(mid):
... | Solution4 |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-nomic/llama_index/embeddings/nomic/base.py | {
"start": 5021,
"end": 8699
} | class ____(HuggingFaceEmbedding):
tokenizer_name: str = Field(description="Tokenizer name from HuggingFace.")
max_length: int = Field(
default=DEFAULT_HUGGINGFACE_LENGTH, description="Maximum length of input.", gt=0
)
pooling: Pooling = Field(default=Pooling.MEAN, description="Pooling strategy."... | NomicHFEmbedding |
python | ipython__ipython | IPython/core/interactiveshell.py | {
"start": 10612,
"end": 159736
} | class ____(SingletonConfigurable):
"""An enhanced, interactive shell for Python."""
_instance = None
_user_ns: dict
_sys_modules_keys: set[str]
inspector: oinspect.Inspector
ast_transformers: List[ast.NodeTransformer] = List(
[],
help="""
A list of ast.NodeTransformer ... | InteractiveShell |
python | gevent__gevent | src/gevent/tests/test__makefile_ref.py | {
"start": 4821,
"end": 8653
} | class ____(Test):
def test_simple_close(self):
with Closing() as closer:
s = closer(self.make_open_socket())
fileno = s.fileno()
s.close()
self.assert_closed(s, fileno)
def test_makefile1(self):
with Closing() as closer:
s = closer(self.m... | TestSocket |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_base64.py | {
"start": 1647,
"end": 3893
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid base64 codes."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_base64": [
... | ExpectColumnValuesToBeValidBase64 |
python | pypa__pip | src/pip/_internal/models/link.py | {
"start": 3012,
"end": 6634
} | class ____:
"""Information about a core metadata file associated with a distribution."""
hashes: dict[str, str] | None
def __post_init__(self) -> None:
if self.hashes is not None:
assert all(name in _SUPPORTED_HASHES for name in self.hashes)
def supported_hashes(hashes: dict[str, str... | MetadataFile |
python | spack__spack | lib/spack/spack/error.py | {
"start": 2946,
"end": 3122
} | class ____(SpackError):
"""Raised by packages when a platform is not supported"""
def __init__(self, message):
super().__init__(message)
| UnsupportedPlatformError |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 2093,
"end": 2420
} | class ____(BaseModel):
x: str = Field(alias='x_alias')
y: str = Field(validation_alias='y_alias')
z: str = Field(validation_alias='z_alias', alias='unused')
alias_model = AliasModel(x_alias='a', y_alias='a', z_alias='a')
assert alias_model.x == 'a'
assert alias_model.y == 'a'
assert alias_model.z == 'a'
... | AliasModel |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 30199,
"end": 30379
} | class ____(torch.nn.Module):
torchdynamo_force_dynamic = True # forced to be a UnspecializedNNModule
def forward(self, x):
return torch.sin(x)
| UnspecInlinableModule |
python | apache__airflow | providers/atlassian/jira/src/airflow/providers/atlassian/jira/sensors/jira.py | {
"start": 1122,
"end": 2392
} | class ____(BaseSensorOperator):
"""
Monitors a jira ticket for any change.
:param jira_conn_id: reference to a pre-defined Jira Connection
:param method_name: method name from atlassian-python-api JIRA sdk to execute
:param method_params: parameters for the method method_name
:param result_proc... | JiraSensor |
python | pydantic__pydantic | tests/test_json_schema.py | {
"start": 94531,
"end": 94638
} | class ____(BaseModel):
class NestedModel(BaseModel):
b: Decimal
nested: NestedModel
| ModelTwo |
python | django-haystack__django-haystack | test_haystack/test_fields.py | {
"start": 21980,
"end": 22691
} | class ____(TestCase):
def test_init(self):
try:
foo = FacetDateTimeField(model_attr="foo")
foo_exact = FacetDateTimeField(facet_for="bar")
except:
self.fail()
self.assertEqual(foo.facet_for, None)
self.assertEqual(foo_exact.null, True)
sel... | FacetDateTimeFieldTestCase |
python | ray-project__ray | python/ray/tests/accelerators/mock_dpctl_1.py | {
"start": 0,
"end": 124
} | class ____:
def __init__(self, info):
pass
@property
def device_count(self):
return 6
| SyclContext |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py | {
"start": 8639,
"end": 9525
} | class ____:
def test_serialization(self):
application_id = "test_application_id"
waiter_delay = 30
waiter_max_attempts = 60
job_id = "job_id"
aws_conn_id = "aws_default"
trigger = EmrServerlessStartJobTrigger(
application_id=application_id,
wa... | TestEmrServerlessStartJobTrigger |
python | pypa__warehouse | tests/unit/manage/views/test_oidc_publishers.py | {
"start": 782,
"end": 79297
} | class ____:
def test_initializes(self, metrics):
project = pretend.stub(organization=None)
request = pretend.stub(
find_service=pretend.call_recorder(lambda *a, **kw: metrics),
registry=pretend.stub(
settings={
"github.token": "fake-api-tok... | TestManageOIDCPublisherViews |
python | weaviate__weaviate-python-client | integration/test_batch_v4.py | {
"start": 1677,
"end": 27828
} | class ____(Protocol):
"""Typing for fixture."""
def __call__(
self, name: str = "", ports: Tuple[int, int] = (8080, 50051), multi_tenant: bool = False
) -> Tuple[weaviate.WeaviateClient, str]:
"""Typing for fixture."""
...
@pytest.fixture
def client_factory(
request: SubReques... | ClientFactory |
python | getsentry__sentry | tests/acceptance/test_organization_dashboards.py | {
"start": 26995,
"end": 29720
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.team = self.create_team(organization=self.organization, name="Mariachi Band")
self.project = self.create_project(
organization=self.organization, teams=[self.team], name="Bengal"
)
self.... | OrganizationDashboardsManageAcceptanceTest |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_algorithms.py | {
"start": 6169,
"end": 6641
} | class ____:
test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "CAST5"),
["cast5-cbc.txt"],
lambda key, **kwargs: CAST5(binascii.unhexlify(key)),
lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)),
)
@pytest.mark.supported(
only_if=lamb... | TestCAST5ModeCBC |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 15457,
"end": 15778
} | class ____(HTTPException):
"""*415* `Unsupported Media Type`
The status code returned if the server is unable to handle the media type
the client transmitted.
"""
code = 415
description = (
"The server does not support the media type transmitted in the request."
)
| UnsupportedMediaType |
python | getsentry__sentry | tests/sentry/tasks/test_update_code_owners_schema.py | {
"start": 407,
"end": 2322
} | class ____(TestCase):
def setUp(self) -> None:
self.organization = self.create_organization()
self.project = self.create_project(organization=self.organization)
self.project_codeowner = self.create_codeowners(project=self.project)
with assume_test_silo_mode(SiloMode.CONTROL):
... | UpdateCodeOwnersSchemaTest |
python | facebookresearch__faiss | tests/test_io.py | {
"start": 14060,
"end": 15809
} | class ____(unittest.TestCase):
@unittest.skipIf(
platform.system() not in ["Windows", "Linux"],
"supported OSes only"
)
def test_mmap(self):
xt, xb, xq = get_dataset_2(32, 0, 100, 50)
index = faiss.index_factory(32, "SQfp16", faiss.METRIC_L2)
# does not need training... | TestIOFlatMMap |
python | django__django | tests/forms_tests/tests/test_input_formats.py | {
"start": 30439,
"end": 35033
} | class ____(SimpleTestCase):
@classmethod
def setUpClass(cls):
cls.enterClassContext(translation.override(None))
super().setUpClass()
def test_dateTimeField(self):
"DateTimeFields can parse dates in the default format"
f = forms.DateTimeField()
# Parse a date in an un... | CustomDateTimeInputFormatsTests |
python | huggingface__transformers | src/transformers/models/vilt/image_processing_vilt.py | {
"start": 4206,
"end": 22291
} | class ____(BaseImageProcessor):
r"""
Constructs a ViLT image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
`do_resize` parameter in the `preproce... | ViltImageProcessor |
python | plotly__plotly.py | plotly/graph_objs/pie/_domain.py | {
"start": 233,
"end": 4925
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "pie"
_path_str = "pie.domain"
_valid_props = {"column", "row", "x", "y"}
@property
def column(self):
"""
If there is a layout grid, use the domain for this column in
the grid for this pie trace .
The 'column' ... | Domain |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol6.py | {
"start": 228,
"end": 373
} | class ____(Protocol):
def __call__(self, path: str = ...) -> str: ...
# Callback with positional parameter without default arg value.
| Callback1 |
python | langchain-ai__langchain | libs/core/tests/unit_tests/output_parsers/test_pydantic_parser.py | {
"start": 2994,
"end": 6535
} | class ____(BaseModel):
action: Actions = Field(description="Action to be performed")
action_input: str = Field(description="Input to be used in the action")
additional_fields: str | None = Field(description="Additional fields", default=None)
for_new_lines: str = Field(description="To be used to test new... | TestModel |
python | doocs__leetcode | solution/3400-3499/3459.Length of Longest V-Shaped Diagonal Segment/Solution.py | {
"start": 0,
"end": 817
} | class ____:
def lenOfVDiagonal(self, grid: List[List[int]]) -> int:
@cache
def dfs(i: int, j: int, k: int, cnt: int) -> int:
x, y = i + dirs[k], j + dirs[k + 1]
target = 2 if grid[i][j] == 1 else (2 - grid[i][j])
if not 0 <= x < m or not 0 <= y < n or grid[x][y] !... | Solution |
python | sqlalchemy__sqlalchemy | test/base/test_events.py | {
"start": 22387,
"end": 23296
} | class ____(TearDownLocalEventsFixture, fixtures.TestBase):
"""Test custom target acceptance."""
def setup_test(self):
class TargetEvents(event.Events):
@classmethod
def _accept_with(cls, target, identifier):
if target == "one":
return Target
... | CustomTargetsTest |
python | kamyu104__LeetCode-Solutions | Python/neighboring-bitwise-xor.py | {
"start": 37,
"end": 248
} | class ____(object):
def doesValidArrayExist(self, derived):
"""
:type derived: List[int]
:rtype: bool
"""
return reduce(lambda total, x: total^x, derived, 0) == 0
| Solution |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0006_add_config_field.py | {
"start": 145,
"end": 555
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0005_remove-version-alias"),
]
operations = [
migrations.AddField(
model_name="build",
name="_config",
field=jsonfield.fields.JSONField(
default=... | Migration |
python | getsentry__sentry | tests/sentry/sentry_apps/api/endpoints/test_sentry_app_stats.py | {
"start": 153,
"end": 4730
} | class ____(APITestCase):
def setUp(self) -> None:
self.superuser = self.create_user(email="superuser@example.com", is_superuser=True)
self.user = self.create_user(email="user@example.com")
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(organiz... | GetSentryAppStatsTest |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/integrations/duckdb/reference/multiple_dataframe_types.py | {
"start": 438,
"end": 1623
} | class ____(DuckDBIOManager):
@staticmethod
def type_handlers():
"""type_handlers should return a list of the TypeHandlers that the I/O manager can use.
Here we return the DuckDBPandasTypeHandler, DuckDBPySparkTypeHandler, and DuckDBPolarsTypeHandler so that the I/O
manager can store Pand... | DuckDBPandasPySparkPolarsIOManager |
python | pytorch__pytorch | torch/_inductor/output_code.py | {
"start": 35867,
"end": 39326
} | class ____(OutputCode):
"""
OutputCode for regional inductor compilation results.
Regional inductor returns a torch.fx.GraphModule that contains both
compiled regions (via standalone_compile) and eager regions. This needs
special serialization using GraphPickler instead of standard pickle.
The... | RegionalOutputCode |
python | getsentry__sentry | src/sentry/replays/usecases/query/conditions/selector.py | {
"start": 7720,
"end": 8135
} | class ____(ComputedBase):
"""Streaming dead click selector composite condition class."""
@staticmethod
def visit_eq(value: list[QueryType]) -> Condition:
return contains(DeadClickSelectorComposite.visit_eq(value))
@staticmethod
def visit_neq(value: list[QueryType]) -> Condition:
re... | SumOfDeadClickSelectorComposite |
python | neetcode-gh__leetcode | python/0213-house-robber-ii.py | {
"start": 0,
"end": 324
} | class ____:
def rob(self, nums: List[int]) -> int:
return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self, nums):
rob1, rob2 = 0, 0
for n in nums:
newRob = max(rob1 + n, rob2)
rob1 = rob2
rob2 = newRob
return rob2
| Solution |
python | sympy__sympy | sympy/matrices/common.py | {
"start": 24287,
"end": 37957
} | class ____(MatrixRequired):
"""Construction of special matrices"""
@classmethod
def _eval_diag(cls, rows, cols, diag_dict):
"""diag_dict is a defaultdict containing
all the entries of the diagonal matrix."""
def entry(i, j):
return diag_dict[(i, j)]
return cls._n... | MatrixSpecial |
python | gevent__gevent | src/greentest/3.11/test_wsgiref.py | {
"start": 1140,
"end": 2856
} | class ____(WSGIRequestHandler):
"""Non-socket HTTP handler"""
def setup(self):
self.connection = self.request
self.rfile, self.wfile = self.connection
def finish(self):
pass
def hello_app(environ,start_response):
start_response("200 OK", [
('Content-Type','text/plain')... | MockHandler |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 28717,
"end": 29331
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layer0 = torch.nn.Linear(10, 10)
self.layer1 = torch.nn.Linear(10, 10)
self.layer2 = torch.nn.Linear(10, 10)
@property
def encoder_layers(self):
return [self.layer0, self.layer1, self.la... | ModuleComparison |
python | walkccc__LeetCode | solutions/231. Power of Two/231.py | {
"start": 0,
"end": 99
} | class ____:
def isPowerOfTwo(self, n: int) -> bool:
return n >= 0 and n.bit_count() == 1
| Solution |
python | django-import-export__django-import-export | import_export/widgets.py | {
"start": 857,
"end": 2024
} | class ____:
"""Internal Mixin for shared logic with date and datetime conversions."""
def __init__(
self,
format=None,
input_formats=None,
default_format="%Y-%m-%d",
coerce_to_string=True,
):
super().__init__(coerce_to_string=coerce_to_string)
self.fo... | _ParseDateTimeMixin |
python | apache__thrift | lib/py/src/protocol/TBinaryProtocol.py | {
"start": 903,
"end": 6451
} | class ____(TProtocolBase):
"""Binary implementation of the Thrift protocol driver."""
# NastyHaxx. Python 2.4+ on 32-bit machines forces hex constants to be
# positive, converting this into a long. If we hardcode the int value
# instead it'll stay in 32 bit-land.
# VERSION_MASK = 0xffff0000
VE... | TBinaryProtocol |
python | networkx__networkx | networkx/utils/misc.py | {
"start": 8650,
"end": 11045
} | class ____(random.Random):
"""Provide the random.random algorithms using a numpy.random bit generator
The intent is to allow people to contribute code that uses Python's random
library, but still allow users to provide a single easily controlled random
bit-stream for all work with NetworkX. This implem... | PythonRandomViaNumpyBits |
python | getsentry__sentry | tests/sentry/tasks/test_post_process.py | {
"start": 133088,
"end": 136398
} | class ____(
TestCase,
SnubaTestCase,
CorePostProcessGroupTestMixin,
InboxTestMixin,
RuleProcessorTestMixin,
SnoozeTestMixin,
SnoozeTestSkipSnoozeMixin,
PerformanceIssueTestCase,
KickOffSeerAutomationTestMixin,
TriageSignalsV0TestMixin,
):
def create_event(self, data, project_... | PostProcessGroupPerformanceTest |
python | PrefectHQ__prefect | tests/workers/test_utilities.py | {
"start": 2384,
"end": 3152
} | class ____:
async def test_get_default_base_job_template_for_local_registry(self):
result = await get_default_base_job_template_for_infrastructure_type("process")
assert result == ProcessWorker.get_default_base_job_template()
async def test_get_default_base_job_template_for_collection_registry(... | TestGetDefaultBaseJobTemplateForInfrastructureType |
python | keras-team__keras | keras/src/callbacks/csv_logger_test.py | {
"start": 361,
"end": 5831
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_CSVLogger(self):
OUTPUT_DIM = 1
np.random.seed(1337)
temp_dir = tempfile.TemporaryDirectory()
filepath = os.path.join(temp_dir.name, "log.tsv")
sep = "\t"
x_train = np.random.random((T... | CSVLoggerTest |
python | openai__openai-python | src/openai/types/fine_tuning/alpha/grader_validate_response.py | {
"start": 645,
"end": 773
} | class ____(BaseModel):
grader: Optional[Grader] = None
"""The grader used for the fine-tuning job."""
| GraderValidateResponse |
python | pytorch__pytorch | test/torch_np/test_basic.py | {
"start": 3209,
"end": 4640
} | class ____(TestCase):
@parametrize("func", [w.transpose])
@parametrize("axes", [(0, 2, 1), (1, 2, 0), None])
def test_andtuple_tensor(self, func, axes):
t = torch.ones((1, 2, 3))
ta = func(t, axes=axes)
assert isinstance(ta, w.ndarray)
# a np.transpose -specific test
... | TestOneArrAndAxesTuple |
python | gevent__gevent | src/gevent/_patcher.py | {
"start": 7337,
"end": 9020
} | class ____(object):
"""
Context manager that caches ``platform.architecture``.
Some things that load shared libraries (like Cryptodome, via
dnspython) invoke ``platform.architecture()`` for each one. That
in turn wants to fork and run commands , which in turn wants to
call ``threading._after_fo... | cached_platform_architecture |
python | neetcode-gh__leetcode | python/1838-frequency-of-the-most-frequent-element.py | {
"start": 0,
"end": 405
} | class ____:
def maxFrequency(self, nums: List[int], k: int) -> int:
nums.sort()
l, r = 0, 0
res, total = 0, 0
while r < len(nums):
total += nums[r]
while nums[r] * (r - l + 1) > total + k:
total -= nums[l]
l += 1
r... | Solution |
python | google__pytype | pytype/pytd/pytd.py | {
"start": 13296,
"end": 13448
} | class ____(Type):
"""A type specified by name and, optionally, the module it is in."""
name: str
def __str__(self):
return self.name
| NamedType |
python | cython__cython | pyximport/pyximport.py | {
"start": 9552,
"end": 11579
} | class ____(MetaPathFinder):
def __init__(self, extension=PY_EXT, pyxbuild_dir=None, inplace=False, language_level=None):
self.pyxbuild_dir = pyxbuild_dir
self.inplace = inplace
self.language_level = language_level
self.extension = extension
self.uncompilable_modules = {}
... | PyImportMetaFinder |
python | pytorch__pytorch | torch/testing/_internal/common_dist_composable.py | {
"start": 1878,
"end": 2313
} | class ____(nn.Module):
# Define this class to achieve a desired nested wrapping using the module
# wrap policy with `nn.Sequential`
def __init__(self, *modules: tuple[nn.Module, ...]) -> None:
super().__init__()
self._module_sequence = list(modules)
def forward(self, x: torch.Tensor) ->... | FakeSequential |
python | Textualize__textual | docs/examples/widgets/progress_bar.py | {
"start": 169,
"end": 1169
} | class ____(App[None]):
CSS_PATH = "progress_bar.tcss"
TITLE = "Funding tracking"
def compose(self) -> ComposeResult:
yield Header()
with Center():
yield Label("Funding: ")
yield ProgressBar(total=100, show_eta=False) # (1)!
with Center():
yield ... | FundingProgressApp |
python | sympy__sympy | sympy/physics/mechanics/joint.py | {
"start": 31429,
"end": 41230
} | class ____(Joint):
"""Prismatic (Sliding) Joint.
.. image:: PrismaticJoint.svg
Explanation
===========
It is defined such that the child body translates with respect to the parent
body along the body-fixed joint axis. The location of the joint is defined
by two points, one in each body, w... | PrismaticJoint |
python | automl__auto-sklearn | test/test_pipeline/components/data_preprocessing/test_data_preprocessing_numerical.py | {
"start": 190,
"end": 2906
} | class ____(unittest.TestCase):
def test_data_type_consistency(self):
X = np.random.rand(3, 4)
Y = NumericalPreprocessingPipeline(
feat_type={0: "numerical", 1: "numerical", 2: "numerical"}
).fit_transform(X)
self.assertFalse(sparse.issparse(Y))
X = sparse.csc_mat... | NumericalPreprocessingPipelineTest |
python | django__django | tests/field_defaults/models.py | {
"start": 2074,
"end": 2217
} | class ____(models.Model):
language_code = models.ForeignKey(
DBDefaultsPK, db_default="fr", on_delete=models.CASCADE
)
| DBDefaultsFK |
python | apache__airflow | airflow-core/src/airflow/executors/local_executor.py | {
"start": 4892,
"end": 9383
} | class ____(BaseExecutor):
"""
LocalExecutor executes tasks locally in parallel.
It uses the multiprocessing Python library and queues to parallelize the execution of tasks.
:param parallelism: how many parallel processes are run in the executor, must be > 0
"""
is_local: bool = True
serv... | LocalExecutor |
python | PyCQA__pylint | tests/functional/m/missing/missing_class_docstring.py | {
"start": 83,
"end": 134
} | class ____: # [missing-class-docstring]
pass
| Klass |
python | allegroai__clearml | clearml/backend_api/services/v2_13/workers.py | {
"start": 9632,
"end": 11478
} | class ____(NonStrictDataModel):
"""
:param worker: ID of the worker
:type worker: str
:param metrics: List of the metrics statistics for the worker
:type metrics: Sequence[MetricStats]
"""
_schema = {
"properties": {
"metrics": {
"description": "List of t... | WorkerStats |
python | tensorflow__tensorflow | tensorflow/python/distribute/values.py | {
"start": 17086,
"end": 18002
} | class ____(trace.TraceType):
"""TraceType of DistributedVariable objects."""
def __init__(self, distributed_variable):
self.distributed_variable = distributed_variable
self.components = (tuple(distributed_variable.shape.as_list()),
distributed_variable.dtype)
def is_subtype_of(sel... | DistributedVariableTraceType |
python | sqlalchemy__sqlalchemy | test/ext/test_orderinglist.py | {
"start": 1480,
"end": 13733
} | class ____(fixtures.MappedTest):
def setup_test(self):
global metadata, slides_table, bullets_table, Slide, Bullet
slides_table, bullets_table = None, None
Slide, Bullet = None, None
metadata = MetaData()
def _setup(self, test_collection_class):
"""Build a relationship s... | OrderingListTest |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_tabbed_alternate.py | {
"start": 106,
"end": 18015
} | class ____(util.MdCase):
"""Test tab cases."""
extension = ['pymdownx.tabbed', 'pymdownx.superfences', 'markdown.extensions.def_list', 'pymdownx.details']
extension_configs = {'pymdownx.tabbed': {'alternate_style': True}}
def test_with_preceding_text(self):
"""Test content directly before tabs... | TestTab |
python | huggingface__transformers | src/transformers/models/mbart/modeling_mbart.py | {
"start": 27325,
"end": 38764
} | class ____(MBartPreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`MBartDecoderLayer`]
Args:
config: MBartConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(self, config: MBartConfig):
super().__init_... | MBartDecoder |
python | getsentry__sentry | tests/sentry/api/serializers/test_release.py | {
"start": 37633,
"end": 40475
} | class ____(TestCase, SnubaTestCase):
def test_simple(self) -> None:
user = self.create_user()
project = self.create_project()
project2 = self.create_project(organization=project.organization)
release_version = uuid4().hex
release = Release.objects.create(
organiz... | GroupEventReleaseSerializerTest |
python | pydantic__pydantic | tests/test_json_schema.py | {
"start": 197824,
"end": 203897
} | class ____(BaseModel):
x: int
""",
module_name_prefix='C:\\',
)
foo_model = module.Foo
_, v_schema = models_json_schema([(foo_model, 'validation')])
assert v_schema == {
'$defs': {
'Foo': {
'properties': {'x': {'title': 'X', 'type': 'integer'}},
... | Foo |
python | apache__airflow | devel-common/src/tests_common/test_utils/mock_operators.py | {
"start": 1383,
"end": 1722
} | class ____(BaseOperator):
"""Operator for testing purposes."""
template_fields: Sequence[str] = ("arg1", "arg2")
def __init__(self, arg1: str = "", arg2: str = "", **kwargs):
super().__init__(**kwargs)
self.arg1 = arg1
self.arg2 = arg2
def execute(self, context: Context):
... | MockOperator |
python | Textualize__textual | tests/notifications/test_all_levels_notifications.py | {
"start": 387,
"end": 743
} | class ____(App[None]):
def on_mount(self) -> None:
self.notify("test", timeout=60)
self.push_screen(NotifyScreen())
async def test_all_levels_of_notification() -> None:
"""All levels within the DOM should be able to notify."""
async with NotifyApp().run_test() as pilot:
assert len(... | NotifyApp |
python | pydantic__pydantic | pydantic/v1/networks.py | {
"start": 11978,
"end": 12331
} | class ____(AnyHttpUrl):
tld_required = True
# https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
max_length = 2083
hidden_parts = {'port'}
@staticmethod
def get_default_parts(parts: 'Parts') -> 'Parts':
return {'port': '80' if parts['sch... | HttpUrl |
python | ethereum__web3.py | web3/contract/base_contract.py | {
"start": 13550,
"end": 17083
} | class ____(Generic[TContractEvent]):
"""
Class containing contract event objects
This is available via:
.. code-block:: python
>>> mycontract.events
<web3.contract.ContractEvents object at 0x108afde10>
To get list of all supported events in the contract ABI.
This allows you t... | BaseContractEvents |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/cwise_ops_binary_test.py | {
"start": 34850,
"end": 41497
} | class ____(test.TestCase):
def _compareScalar(self, func, x, y, dtype):
with test_util.use_gpu():
out = func(
ops.convert_to_tensor(np.array([x]).astype(dtype)),
ops.convert_to_tensor(np.array([y]).astype(dtype)))
ret = self.evaluate(out)
return ret[0]
def testScalarCompare... | ComparisonOpTest |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/run_launcher.py | {
"start": 2920,
"end": 3144
} | class ____(BaseModel):
celeryK8sRunLauncher: Optional[CeleryK8sRunLauncherConfig] = None
k8sRunLauncher: Optional[K8sRunLauncherConfig] = None
customRunLauncher: Optional[ConfigurableClass] = None
| RunLauncherConfig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.