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 | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 58380,
"end": 60073
} | class ____(fixtures.MappedTest):
"""test a relationship based on a primary
join against a unique non-pk column"""
@classmethod
def define_tables(cls, metadata):
Table(
"table_a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_au... | UniqueColReferenceSwitchTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zoho-crm/source_zoho_crm/types.py | {
"start": 2739,
"end": 7968
} | class ____(FromDictMixin):
json_type: str
length: Optional[int]
api_name: str
data_type: str
decimal_place: Optional[int]
system_mandatory: bool
display_label: str
pick_list_values: Optional[List[ZohoPickListItem]]
auto_number: Optional[AutoNumberDict] = AutoNumberDict(prefix="", suf... | FieldMeta |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/transfers/test_dynamodb_to_s3.py | {
"start": 1480,
"end": 1919
} | class ____:
@pytest.mark.parametrize("value", ["102938.3043847474", 1.010001, 10, "100", "1E-128", 1e-128])
def test_jsonencoder_with_decimal(self, value):
"""Test JSONEncoder correctly encodes and decodes decimal values."""
org = Decimal(value)
encoded = json.dumps(org, cls=JSONEncoder... | TestJSONEncoder |
python | psf__requests | tests/test_utils.py | {
"start": 5531,
"end": 6032
} | class ____:
@pytest.mark.parametrize(
"value, expected",
(
(None, None),
("Test", "Test"),
('"Test"', "Test"),
('"Test\\\\"', "Test\\"),
('"\\\\Comp\\Res"', "\\Comp\\Res"),
),
)
def test_valid(self, value, expected):
... | TestUnquoteHeaderValue |
python | dagster-io__dagster | python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py | {
"start": 25012,
"end": 36201
} | class ____(MultiColumnConstraintWithMetadata):
"""This class is similar to multicolumn, but takes in functions that operate on the whole column at once
rather than ones that operate on each value --
consider this similar to the difference between apply-map and apply aggregate.
Args:
description... | MultiAggregateConstraintWithMetadata |
python | pandas-dev__pandas | pandas/tests/extension/base/groupby.py | {
"start": 305,
"end": 6247
} | class ____:
"""Groupby-specific tests."""
def test_grouping_grouper(self, data_for_grouping):
df = pd.DataFrame(
{
"A": pd.Series(
["B", "B", None, None, "A", "A", "B", "C"], dtype=object
),
"B": data_for_grouping,
... | BaseGroupbyTests |
python | huggingface__transformers | src/transformers/models/layoutlm/modeling_layoutlm.py | {
"start": 12678,
"end": 14345
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([LayoutLMLayer(config) for i in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
@can_return_tuple
def forward(
self,
hi... | LayoutLMEncoder |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_ordered_dict.py | {
"start": 31989,
"end": 35580
} | class ____:
def check_runtime_error_issue119004(self, dict1, dict2):
msg = re.escape("OrderedDict mutated during iteration")
self.assertRaisesRegex(RuntimeError, msg, operator.eq, dict1, dict2)
def test_issue119004_change_size_by_clear(self):
with torch._dynamo.error_on_graph_break(Fal... | CPythonOrderedDictSideEffects |
python | PrefectHQ__prefect | tests/server/utilities/test_text_search_parser.py | {
"start": 463,
"end": 2087
} | class ____:
"""Test basic query parsing functionality"""
def test_empty_string(self):
result = parse_text_search_query("")
assert result == TextSearchQuery(include=[], exclude=[], required=[])
def test_whitespace_only(self):
result = parse_text_search_query(" \t\n ")
ass... | TestBasicParsing |
python | plotly__plotly.py | plotly/graph_objs/carpet/baxis/_title.py | {
"start": 233,
"end": 3564
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "carpet.baxis"
_path_str = "carpet.baxis.title"
_valid_props = {"font", "offset", "text"}
@property
def font(self):
"""
Sets this axis' title font.
The 'font' property is an instance of Font
that may be specifi... | Title |
python | mlflow__mlflow | mlflow/store/artifact/databricks_logged_model_artifact_repo.py | {
"start": 127,
"end": 1453
} | class ____(DatabricksTrackingArtifactRepository):
"""
Artifact repository for interacting with logged model artifacts in a Databricks workspace.
If operations using the Databricks SDK fail for any reason, this repository automatically
falls back to using the `DatabricksArtifactRepository`, ensuring oper... | DatabricksLoggedModelArtifactRepository |
python | realpython__materials | python-maze-solver/source_code_final/src/maze_solver/models/role.py | {
"start": 33,
"end": 186
} | class ____(IntEnum):
NONE = 0
ENEMY = auto()
ENTRANCE = auto()
EXIT = auto()
EXTERIOR = auto()
REWARD = auto()
WALL = auto()
| Role |
python | pypa__warehouse | tests/common/db/ses.py | {
"start": 818,
"end": 1256
} | class ____(WarehouseFactory):
class Meta:
model = Event
created = factory.Faker(
"date_time_between_dates",
datetime_start=datetime.datetime.now(datetime.UTC)
- datetime.timedelta(days=14),
)
email = factory.SubFactory(EmailMessageFactory)
event_id = factory.Faker("p... | EventFactory |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 127390,
"end": 128609
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.gate = Qwen3OmniMoeTalkerTextTopKRouter(config)
self.experts = Qwen3OmniMoeTalkerTextExperts(config)
self.shared_expert = Qwen3OmniMoeTalkerTextMLP(
config, intermediate_size=config.shared_expert_i... | Qwen3OmniMoeTalkerTextSparseMoeBlock |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/test_component_scaffolding.py | {
"start": 662,
"end": 873
} | class ____(dg.Scaffolder[TestParamsModelWithDefaults]):
@classmethod
def get_scaffold_params(cls) -> type[TestParamsModelWithDefaults]:
return TestParamsModelWithDefaults
| TestScaffolderWithDefaults |
python | numpy__numpy | numpy/lib/tests/test_recfunctions.py | {
"start": 16876,
"end": 17869
} | class ____:
# Test recursive_fill_fields.
def test_simple_flexible(self):
# Test recursive_fill_fields on flexible-array
a = np.array([(1, 10.), (2, 20.)], dtype=[('A', int), ('B', float)])
b = np.zeros((3,), dtype=a.dtype)
test = recursive_fill_fields(a, b)
control = np.... | TestRecursiveFillFields |
python | redis__redis-py | tests/test_maint_notifications.py | {
"start": 31731,
"end": 37542
} | class ____:
"""Test MaintNotificationsConfig endpoint type functionality."""
def setup_method(self):
"""Set up common mock classes for all tests."""
class MockSocket:
def __init__(self, resolved_ip):
self.resolved_ip = resolved_ip
def getpeername(self):... | TestMaintNotificationsConfigEndpointType |
python | docker__docker-py | tests/unit/api_network_test.py | {
"start": 150,
"end": 5664
} | class ____(BaseAPIClientTest):
def test_list_networks(self):
networks = [
{
"name": "none",
"id": "8e4e55c6863ef424",
"type": "null",
"endpoints": []
},
{
"name": "host",
"id":... | NetworkTest |
python | apache__airflow | providers/dingding/src/airflow/providers/dingding/hooks/dingding.py | {
"start": 1010,
"end": 5046
} | class ____(HttpHook):
"""
Send message using a DingTalk Custom Robot API.
.. seealso::
`How to get webhook token <https://open.dingtalk.com/document/robots/custom-robot-access>`__
:param dingding_conn_id: Dingding connection id that has access token in the password field,
and optional ... | DingdingHook |
python | OmkarPathak__pygorithm | tests/test_sorting.py | {
"start": 287,
"end": 2278
} | class ____:
def test_test_setup(self):
self.assertIsNotNone(getattr(self, 'sort', None))
self.assertIsNotNone(getattr(self, 'inplace', None))
self.assertIsNotNone(getattr(self, 'alph_support', None))
def _check_sort_list(self, arr, expected):
cp_arr = list(arr)
sarr = se... | TestSortingAlgorithm |
python | jazzband__django-model-utils | model_utils/managers.py | {
"start": 2086,
"end": 7301
} | class ____(Generic[ModelT]):
model: type[ModelT]
subclasses: Sequence[str]
def __init__(self, *args: object, **kwargs: object):
super().__init__(*args, **kwargs)
self._iterable_class: type[BaseIterable[ModelT]] = InheritanceIterable
def select_subclasses(self, *subclasses: str | type[... | InheritanceQuerySetMixin |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/layout_test.py | {
"start": 12479,
"end": 16710
} | class ____(test_util.DTensorBaseTest, parameterized.TestCase):
def test_empty_sharding_spec_different_from_single_unsharded(self):
layout_str_single_unsharded = (
'sharding_specs:unsharded, mesh:' + _MESH_2D_STRING
)
layout_str_empty_sharding_spec = 'sharding_specs: mesh:' + _MESH_2D_STRING
... | LayoutTest |
python | pyparsing__pyparsing | examples/shapes.py | {
"start": 633,
"end": 1737
} | class ____(Shape):
def area(self):
return 3.14159 * self.radius ** 2
import pyparsing as pp
ppc = pp.pyparsing_common
# use pyparsing-defined numeric expression that converts all parsed
# numeric values as floats
number = ppc.fnumber()
# Shape expressions:
# square : S <centerx> <centery> <side>
# ... | Circle |
python | streamlit__streamlit | lib/tests/streamlit/elements/arrow_table_test.py | {
"start": 1310,
"end": 5228
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall arrow protos."""
def test_dataframe_data(self):
df = mock_data_frame()
st.table(df)
proto = self.get_delta_from_queue().new_element.arrow_table
pd.testing.assert_frame_equal(convert_arrow_bytes_to_pandas_df(proto.d... | ArrowTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/links/emr.py | {
"start": 1268,
"end": 1524
} | class ____(BaseAwsLink):
"""Helper class for constructing Amazon EMR Cluster Link."""
name = "EMR Cluster"
key = "emr_cluster"
format_str = BASE_AWS_CONSOLE_LINK + "/emr/home?region={region_name}#/clusterDetails/{job_flow_id}"
| EmrClusterLink |
python | django__django | tests/generic_views/test_base.py | {
"start": 1045,
"end": 1236
} | class ____(TemplateView):
def get(self, request):
return self.render_to_response({})
def get_template_names(self):
return ["generic_views/about.html"]
| AboutTemplateView |
python | scipy__scipy | scipy/interpolate/_bary_rational.py | {
"start": 8098,
"end": 25085
} | class ____(_BarycentricRational):
r"""
AAA real or complex rational approximation.
As described in [1]_, the AAA algorithm is a greedy algorithm for approximation by
rational functions on a real or complex set of points. The rational approximation is
represented in a barycentric form from which the... | AAA |
python | django__django | django/views/generic/list.py | {
"start": 7765,
"end": 8001
} | class ____(MultipleObjectTemplateResponseMixin, BaseListView):
"""
Render some list of objects, set by `self.model` or `self.queryset`.
`self.queryset` can actually be any iterable of items, not just a queryset.
"""
| ListView |
python | django__django | tests/migrations/test_migrations_squashed_complex/2_auto.py | {
"start": 35,
"end": 188
} | class ____(migrations.Migration):
dependencies = [("migrations", "1_auto")]
operations = [migrations.RunPython(migrations.RunPython.noop)]
| Migration |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/permissions.py | {
"start": 114,
"end": 748
} | class ____(graphene.ObjectType):
class Meta:
name = "Permission"
permission = graphene.NonNull(graphene.String)
value = graphene.NonNull(graphene.Boolean)
disabledReason = graphene.Field(graphene.String)
def __init__(self, permission: str, permission_result: PermissionResult):
chec... | GraphenePermission |
python | lazyprogrammer__machine_learning_examples | hmm_class/hmmd.py | {
"start": 597,
"end": 7291
} | class ____:
def __init__(self, M):
self.M = M # number of hidden states
def fit(self, X, max_iter=30):
t0 = datetime.now()
np.random.seed(123)
# train the HMM model using the Baum-Welch algorithm
# a specific instance of the expectation-maximization algorithm
... | HMM |
python | google__python-fire | fire/test_components.py | {
"start": 6752,
"end": 7054
} | class ____:
"""Test class for supporting callable."""
def __call__(self, **kwargs):
for key, value in kwargs.items():
print('{}: {}'.format(key, value))
def print_msg(self, msg):
print(msg)
CALLABLE_WITH_KEYWORD_ARGUMENT = CallableWithKeywordArgument()
| CallableWithKeywordArgument |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/utils.py | {
"start": 1299,
"end": 1401
} | class ____(Exception):
"""General class for Rate Limits errors"""
@dataclass
| GitHubAPILimitException |
python | great-expectations__great_expectations | tests/integration/cloud/rest_contracts/conftest.py | {
"start": 1322,
"end": 5156
} | class ____(str, enum.Enum):
DELETE = "DELETE"
GET = "GET"
PATCH = "PATCH"
POST = "POST"
PUT = "PUT"
@pytest.fixture
def cloud_base_url() -> str:
try:
return os.environ["GX_CLOUD_BASE_URL"]
except KeyError as e:
raise OSError("GX_CLOUD_BASE_URL is not set in this environment... | RequestMethods |
python | sympy__sympy | sympy/holonomic/holonomicerrors.py | {
"start": 173,
"end": 476
} | class ____(BaseHolonomicError):
def __init__(self, holonomic, x0):
self.holonomic = holonomic
self.x0 = x0
def __str__(self):
s = 'A Power Series does not exists for '
s += str(self.holonomic)
s += ' about %s.' %self.x0
return s
| NotPowerSeriesError |
python | marshmallow-code__apispec | src/apispec/ext/marshmallow/openapi.py | {
"start": 938,
"end": 11671
} | class ____(FieldConverterMixin):
"""Adds methods for generating OpenAPI specification from marshmallow schemas and fields.
:param Version|str openapi_version: The OpenAPI version to use.
Should be in the form '2.x' or '3.x.x' to comply with the OpenAPI standard.
:param callable schema_name_resolver... | OpenAPIConverter |
python | numba__numba | numba/parfors/parfor.py | {
"start": 64851,
"end": 70200
} | class ____:
"""Parfor subpass to convert setitem on Arrays
"""
def __init__(self, pass_states):
"""
Parameters
----------
pass_states : ParforPassStates
"""
self.pass_states = pass_states
self.rewritten = []
def run(self, blocks):
pass_sta... | ConvertInplaceBinop |
python | neetcode-gh__leetcode | python/0424-longest-repeating-character-replacement.py | {
"start": 0,
"end": 381
} | class ____:
def characterReplacement(self, s: str, k: int) -> int:
count = {}
l = 0
maxf = 0
for r in range(len(s)):
count[s[r]] = 1 + count.get(s[r], 0)
maxf = max(maxf, count[s[r]])
if (r - l + 1) - maxf > k:
count[s[l]]... | Solution |
python | scrapy__scrapy | scrapy/mail.py | {
"start": 1250,
"end": 7062
} | class ____:
def __init__(
self,
smtphost: str = "localhost",
mailfrom: str = "scrapy@localhost",
smtpuser: str | None = None,
smtppass: str | None = None,
smtpport: int = 25,
smtptls: bool = False,
smtpssl: bool = False,
debug: bool = False,
... | MailSender |
python | scikit-learn__scikit-learn | sklearn/manifold/_spectral_embedding.py | {
"start": 18481,
"end": 29959
} | class ____(BaseEstimator):
"""Spectral embedding for non-linear dimensionality reduction.
Forms an affinity matrix given by the specified function and
applies spectral decomposition to the corresponding graph laplacian.
The resulting transformation is given by the value of the
eigenvectors for each... | SpectralEmbedding |
python | ray-project__ray | python/ray/client_builder.py | {
"start": 798,
"end": 2693
} | class ____(BaseContext):
"""
Basic context manager for a ClientBuilder connection.
"""
dashboard_url: Optional[str]
python_version: str
ray_version: str
ray_commit: str
_num_clients: int
_context_to_restore: Optional[ray.util.client.RayAPIStub]
def __enter__(self) -> "ClientCo... | ClientContext |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/test_kubernetes_helper_functions.py | {
"start": 3002,
"end": 6549
} | class ____:
@pytest.mark.parametrize(
("val", "expected"),
[
("task-id", "task-id"), # no problem
("task_id", "task-id"), # underscores
("---task.id---", "task-id"), # dots
(".task.id", "task-id"), # leading dot invalid
("**task.id", "t... | TestCreateUniqueId |
python | allegroai__clearml | clearml/backend_api/services/v2_9/queues.py | {
"start": 61834,
"end": 63235
} | class ____(Request):
"""
Removes a task entry from the queue.
:param queue: Queue id
:type queue: str
:param task: Task id
:type task: str
"""
_service = "queues"
_action = "remove_task"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
... | RemoveTaskRequest |
python | plotly__plotly.py | plotly/graph_objs/layout/mapbox/_center.py | {
"start": 235,
"end": 2815
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.mapbox"
_path_str = "layout.mapbox.center"
_valid_props = {"lat", "lon"}
@property
def lat(self):
"""
Sets the latitude of the center of the map (in degrees North).
The 'lat' property is a number and may be sp... | Center |
python | getsentry__sentry | fixtures/safe_migrations_apps/safe_run_sql_app/migrations/0003_add_col.py | {
"start": 155,
"end": 383
} | class ____(CheckedMigration):
dependencies = [
("safe_run_sql_app", "0002_run_sql"),
]
operations = [
migrations.AlterField("testtable", "field", BoundedPositiveIntegerField(null=True)),
]
| Migration |
python | explosion__spaCy | spacy/schemas.py | {
"start": 18311,
"end": 19381
} | class ____(BaseModel):
# fmt: off
vocab_data: Optional[StrictStr] = Field(..., title="Path to JSON-formatted vocabulary file")
lookups: Optional[Lookups] = Field(..., title="Vocabulary lookups, e.g. lexeme normalization")
vectors: Optional[StrictStr] = Field(..., title="Path to vectors")
init_tok2ve... | ConfigSchemaInit |
python | huggingface__transformers | src/transformers/trainer_pt_utils.py | {
"start": 18196,
"end": 19826
} | class ____(Sampler):
r"""
Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
keeping a bit of randomness.
"""
def __init__(
self,
batch_size: int,
dataset: Dataset | None = None,
lengths: list[int] | No... | LengthGroupedSampler |
python | sdispater__pendulum | src/pendulum/formatting/difference_formatter.py | {
"start": 495,
"end": 4813
} | class ____:
"""
Handles formatting differences in text.
"""
def __init__(self, locale: str = "en") -> None:
self._locale = Locale.load(locale)
def format(
self,
diff: Duration,
is_now: bool = True,
absolute: bool = False,
locale: str | Locale | None ... | DifferenceFormatter |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 136040,
"end": 144264
} | class ____(Request):
"""
Update a model
:param model: Model id
:type model: str
:param name: Model name Unique within the company.
:type name: str
:param comment: Model comment
:type comment: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tag... | UpdateRequest |
python | ansible__ansible | lib/ansible/modules/dnf.py | {
"start": 14066,
"end": 51642
} | class ____(YumDnf):
"""
DNF Ansible module back-end implementation
"""
def __init__(self, module):
# This populates instance vars for all argument spec params
super(DnfModule, self).__init__(module)
self._ensure_dnf()
self.pkg_mgr_name = "dnf"
self.with_modules ... | DnfModule |
python | pypa__virtualenv | src/virtualenv/activation/python/__init__.py | {
"start": 153,
"end": 830
} | class ____(ViaTemplateActivator):
def templates(self):
yield "activate_this.py"
@staticmethod
def quote(string):
return repr(string)
def replacements(self, creator, dest_folder):
replacements = super().replacements(creator, dest_folder)
lib_folders = OrderedDict((os.pat... | PythonActivator |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/workflow/multi_agent_workflow.py | {
"start": 2918,
"end": 28032
} | class ____(Workflow, PromptMixin, metaclass=AgentWorkflowMeta):
"""A workflow for managing multiple agents with handoffs."""
def __init__(
self,
agents: List[BaseWorkflowAgent],
initial_state: Optional[Dict] = None,
root_agent: Optional[str] = None,
handoff_prompt: Optio... | AgentWorkflow |
python | scipy__scipy | scipy/spatial/tests/test__plotutils.py | {
"start": 486,
"end": 3814
} | class ____:
points = [(0,0), (0,1), (1,0), (1,1)]
def test_delaunay(self):
# Smoke test
fig = plt.figure()
obj = Delaunay(self.points)
s_before = obj.simplices.copy()
r = delaunay_plot_2d(obj, ax=fig.gca())
assert_array_equal(obj.simplices, s_before) # shouldn't... | TestPlotting |
python | pytorch__pytorch | test/inductor/test_graph_transform_observer.py | {
"start": 598,
"end": 2280
} | class ____(TestCase):
def test_sdpa_rewriter(self):
if not (
HAS_CUDA_AND_TRITON
and PLATFORM_SUPPORTS_FUSED_ATTENTION
and HAS_PYDOT
and HAS_DOT
):
return
def dot_prod_attention(
query: torch.Tensor, key: torch.Tensor, ... | TestGraphTransformObserver |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 96840,
"end": 96973
} | class ____(Structure):
_fields_ = [("start", c_uint),
("size", c_uint)
]
| c_nvmlGpuInstancePlacement_t |
python | scipy__scipy | scipy/io/tests/test_idl.py | {
"start": 18972,
"end": 20531
} | class ____:
'''Test that sav files with description tag read at all'''
def test_description(self):
s = readsav(path.join(DATA_PATH, 'scalar_byte_descr.sav'), verbose=False)
assert_identical(s.i8u, np.uint8(234))
def test_null_pointer():
# Regression test for null pointers.
s = readsav... | TestTags |
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/subscribers/ray_stopper.py | {
"start": 654,
"end": 5263
} | class ____(InstanceUpdatedSubscriber):
"""RayStopper is responsible for stopping ray on instances.
It will drain the ray node if it's for idle termination.
For other terminations, it will stop the ray node. (e.g. scale down, etc.)
If any failures happen when stopping/draining the node, we will not ret... | RayStopper |
python | bokeh__bokeh | src/bokeh/core/property/string.py | {
"start": 1366,
"end": 2663
} | class ____(String):
""" Accept strings that match a given regular expression.
Args:
default (string, optional) :
A default value for attributes created from this property to have.
help (str or None, optional) :
A documentation string for this property. (default: None)
... | Regex |
python | doocs__leetcode | solution/1400-1499/1403.Minimum Subsequence in Non-Increasing Order/Solution.py | {
"start": 0,
"end": 278
} | class ____:
def minSubsequence(self, nums: List[int]) -> List[int]:
ans = []
s, t = sum(nums), 0
for x in sorted(nums, reverse=True):
t += x
ans.append(x)
if t > s - t:
break
return ans
| Solution |
python | aio-libs__aiohttp | tests/test_loop.py | {
"start": 550,
"end": 1629
} | class ____(AioHTTPTestCase):
on_startup_called: bool
async def get_application(self) -> web.Application:
app = web.Application()
app.on_startup.append(self.on_startup_hook)
return app
async def on_startup_hook(self, app: web.Application) -> None:
self.on_startup_called = Tr... | TestCase |
python | skorch-dev__skorch | skorch/callbacks/training.py | {
"start": 23307,
"end": 23894
} | class ____(ParamMapper):
"""Apply any function on matching parameters in the first epoch.
Examples
--------
Use ``Initializer`` to initialize all dense layer weights with
values sampled from an uniform distribution on the beginning of
the first epoch:
>>> init_fn = partial(torch.nn.init.u... | Initializer |
python | wandb__wandb | wandb/vendor/pygments/lexers/data.py | {
"start": 18269,
"end": 18771
} | class ____(JsonLexer):
"""
For `JSON-LD <http://json-ld.org/>`_ linked data.
.. versionadded:: 2.0
"""
name = 'JSON-LD'
aliases = ['jsonld', 'json-ld']
filenames = ['*.jsonld']
mimetypes = ['application/ld+json']
tokens = {
'objectvalue': [
(r'"@(context|id|val... | JsonLdLexer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor1.py | {
"start": 386,
"end": 657
} | class ____(Generic[S]):
def __init__(self, value: S) -> None:
self._value: Final = value
Result = A[T] | B[S]
def return_ok_none() -> Result[int | None, Exception]:
return A(None)
def return_ok_one() -> Result[int | None, Exception]:
return A(1)
| B |
python | tensorflow__tensorflow | third_party/xla/build_tools/ci/build.py | {
"start": 3201,
"end": 4992
} | class ____(enum.Enum):
"""Enum representing all types of builds.
Should be named as `REPO,OS,HOST_TYPE,BACKEND,GPU_TYPE,CI_TYPE`.
"""
XLA_LINUX_X86_CPU_GITHUB_ACTIONS = enum.auto()
XLA_LINUX_X86_CPU_BZLMOD_GITHUB_ACTIONS = enum.auto()
XLA_LINUX_ARM64_CPU_GITHUB_ACTIONS = enum.auto()
XLA_LINUX_X86_GPU_L4... | BuildType |
python | doocs__leetcode | solution/2600-2699/2652.Sum Multiples/Solution2.py | {
"start": 0,
"end": 237
} | class ____:
def sumOfMultiples(self, n: int) -> int:
def f(x: int) -> int:
m = n // x
return (x + m * x) * m // 2
return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7)
| Solution |
python | weaviate__weaviate-python-client | weaviate/collections/classes/filters.py | {
"start": 3779,
"end": 4109
} | class ____(GeoCoordinate):
distance: float
FilterValuesList = Union[
Sequence[str],
Sequence[bool],
Sequence[int],
Sequence[float],
Sequence[datetime],
Sequence[UUID],
]
FilterValues = Union[
int, float, str, bool, datetime, UUID, _GeoCoordinateFilter, None, FilterValuesList
]
| _GeoCoordinateFilter |
python | django__django | tests/gis_tests/relatedapp/models.py | {
"start": 695,
"end": 1094
} | class ____(SimpleModel):
name = models.CharField(max_length=30)
city = models.ForeignKey(City, models.CASCADE)
center1 = models.PointField()
# Throwing a curveball w/`db_column` here.
center2 = models.PointField(srid=2276, db_column="mycenter")
border1 = models.PolygonField()
border2 = model... | Parcel |
python | apache__airflow | airflow-core/src/airflow/exceptions.py | {
"start": 9887,
"end": 10019
} | class ____(ValueError):
"""Raised when an attempt is made to load an executor which is not configured."""
| UnknownExecutorException |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_highlight.py | {
"start": 17781,
"end": 20373
} | class ____(util.MdCase):
"""Test extended language cases."""
extension = ['pymdownx.highlight', 'pymdownx.superfences', 'pymdownx.inlinehilite']
extension_configs = {
'pymdownx.highlight': {
'extend_pygments_lang': [
{'name': 'php-inline', 'lang': 'php', 'options': {'sta... | TestExtendedLang |
python | bottlepy__bottle | bottle.py | {
"start": 143209,
"end": 150183
} | class ____(ServerAdapter):
""" Untested. """
adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer,
CherootServer, WSGIRefServer]
def run(self, handler):
for sa in self.adapters:
try:
return sa(self.host, self.port, **self.options).run(ha... | AutoServer |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/trt_convert_test.py | {
"start": 2888,
"end": 50244
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
"""Class to test Tensorflow-TensorRT integration python API."""
# Use a small max_workspace_size for tests so they don't consume too much GPU
# memory.
_TRT_MAX_WORKSPACE_SIZE_BYTES = (
trt_convert.DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES)
... | TrtConvertTest |
python | Pylons__pyramid | src/pyramid/response.py | {
"start": 307,
"end": 2197
} | class ____(Response):
"""
A Response object that can be used to serve a static file from disk
simply.
``path`` is a file path on disk.
``request`` must be a Pyramid :term:`request` object. Note
that a request *must* be passed if the response is meant to attempt to
use the ``wsgi.file_wrap... | FileResponse |
python | nedbat__coveragepy | tests/test_files.py | {
"start": 13356,
"end": 13499
} | class ____(Protocol):
"""The shape all Matchers have."""
def match(self, s: str) -> bool:
"""Does this string match?"""
| TMatcher |
python | encode__django-rest-framework | tests/test_generics.py | {
"start": 19117,
"end": 19546
} | class ____(TestCase):
def test_guarded_queryset(self):
class QuerysetAccessError(generics.ListAPIView):
queryset = BasicModel.objects.all()
def get(self, request):
return Response(list(self.queryset))
view = QuerysetAccessError.as_view()
request = fa... | TestGuardedQueryset |
python | huggingface__transformers | tests/utils/test_core_model_loading.py | {
"start": 6452,
"end": 6678
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.q_proj = DummyParamModule((1, 2))
self.k_proj = DummyParamModule((1, 2))
self.v_proj = DummyParamModule((1, 2))
| DummySelfAttn |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 282254,
"end": 282750
} | class ____(sgqlc.types.Input):
"""Ordering options for repository migrations."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(RepositoryMigrationOrderField), graphql_name="field")
"""The field to order repository migrations by.""... | RepositoryMigrationOrder |
python | openai__openai-python | src/openai/types/evals/create_eval_completions_run_data_source.py | {
"start": 4453,
"end": 4783
} | class ____(BaseModel):
template: List[InputMessagesTemplateTemplate]
"""A list of chat messages forming the prompt or context.
May include variable references to the `item` namespace, ie {{item.name}}.
"""
type: Literal["template"]
"""The type of input messages. Always `template`."""
| InputMessagesTemplate |
python | huggingface__transformers | src/transformers/models/swiftformer/modeling_swiftformer.py | {
"start": 1188,
"end": 2760
} | class ____(nn.Module):
"""
Patch Embedding Layer constructed of two 2D convolutional layers.
Input: tensor of shape `[batch_size, in_channels, height, width]`
Output: tensor of shape `[batch_size, out_channels, height/4, width/4]`
"""
def __init__(self, config: SwiftFormerConfig):
sup... | SwiftFormerPatchEmbedding |
python | encode__django-rest-framework | tests/schemas/test_openapi.py | {
"start": 1111,
"end": 1656
} | class ____(TestCase):
def dummy_view(request):
pass
def test_filters(self):
classes = [filters.SearchFilter, filters.OrderingFilter]
for c in classes:
f = c()
assert f.get_schema_operation_parameters(self.dummy_view)
def test_pagination(self):
classe... | TestBasics |
python | crytic__slither | slither/solc_parsing/declarations/caller_context.py | {
"start": 228,
"end": 913
} | class ____(metaclass=abc.ABCMeta):
"""
This class is inherited by all the declarations class that can be used in the expression/type parsing
As a source of context/scope
It is used by any declaration class that can be top-level and require complex parsing
"""
@property
@abc.abstractmethod... | CallerContextExpression |
python | mamba-org__mamba | micromamba/tests/test_config.py | {
"start": 2875,
"end": 3153
} | class ____:
def test_config_empty(self, tmp_home):
assert "Configuration of micromamba" in config()
@pytest.mark.parametrize("quiet_flag", ["-q", "--quiet"])
def test_config_quiet(self, quiet_flag, tmp_home):
assert config(quiet_flag) == ""
| TestConfig |
python | spyder-ide__spyder | spyder/plugins/plots/widgets/figurebrowser.py | {
"start": 11111,
"end": 23154
} | class ____(QScrollArea, SpyderWidgetMixin):
"""
A scrollarea that displays a single FigureCanvas with zooming and panning
capability with CTRL + Mouse_wheel and Left-press mouse button event.
"""
sig_zoom_changed = Signal(int)
"""
This signal is emitted when zoom has changed.
Parameter... | FigureViewer |
python | apache__airflow | providers/discord/src/airflow/providers/discord/notifications/discord.py | {
"start": 1234,
"end": 3815
} | class ____(BaseNotifier):
"""
Discord BaseNotifier.
:param discord_conn_id: Http connection ID with host as "https://discord.com/api/" and
default webhook endpoint in the extra field in the form of
{"webhook_endpoint": "webhooks/{webhook.id}/{webhook.token}... | DiscordNotifier |
python | django__django | django/contrib/postgres/lookups.py | {
"start": 1733,
"end": 1856
} | class ____(PostgresOperatorLookup):
lookup_name = "trigram_word_similar"
postgres_operator = "%%>"
| TrigramWordSimilar |
python | sphinx-doc__sphinx | sphinx/domains/cpp/__init__.py | {
"start": 19373,
"end": 20559
} | class ____(SphinxDirective):
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec: ClassVar[OptionSpec] = {}
def run(self) -> list[Node]:
if self.arguments[0].strip() in {'NULL', '0', 'nullptr'}:
return []
par... | CPPNamespacePushObject |
python | cython__cython | Cython/Compiler/Buffer.py | {
"start": 6615,
"end": 26954
} | class ____:
def __init__(self, entry):
self.entry = entry
self.type = entry.type
self.cname = entry.buffer_aux.buflocal_nd_var.cname
self.buf_ptr = "%s.rcbuffer->pybuffer.buf" % self.cname
self.buf_ptr_type = entry.type.buffer_ptr_type
self.init_attributes()
def ... | BufferEntry |
python | scipy__scipy | scipy/ndimage/tests/test_interpolation.py | {
"start": 661,
"end": 3737
} | class ____:
@make_xp_test_case(ndimage.geometric_transform)
@pytest.mark.parametrize(
'mode, expected_value',
[('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]),
('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]),
('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]),
('mirror', [1.5,... | TestBoundaries |
python | kamyu104__LeetCode-Solutions | Python/assign-elements-to-groups-with-constraints.py | {
"start": 121,
"end": 632
} | class ____(object):
def assignElements(self, groups, elements):
"""
:type groups: List[int]
:type elements: List[int]
:rtype: List[int]
"""
mx = max(groups)
lookup = [-1]*mx
for i, x in enumerate(elements):
if x > mx or lookup[x-1] != -1:
... | Solution |
python | encode__django-rest-framework | tests/generic_relations/models.py | {
"start": 562,
"end": 792
} | class ____(models.Model):
"""
A URL bookmark that may have multiple tags attached.
"""
url = models.URLField()
tags = GenericRelation(Tag)
def __str__(self):
return 'Bookmark: %s' % self.url
| Bookmark |
python | PrefectHQ__prefect | tests/server/models/test_block_schemas.py | {
"start": 34234,
"end": 36458
} | class ____:
async def test_delete_block_schema(self, session, block_schema):
block_schema_id = block_schema.id
assert await models.block_schemas.delete_block_schema(
session=session, block_schema_id=block_schema_id
)
assert not await models.block_schemas.read_block_schema... | TestDeleteBlockSchema |
python | pytorch__pytorch | torch/_inductor/metrics.py | {
"start": 2790,
"end": 3674
} | class ____:
"""
A helper class to help calculate and apply counter deltas for those
metrics we want to save with cache entries (e.g., FxGraphCache) and
apply on a cache hit.
"""
def __init__(self) -> None:
self.cached_metrics = {}
for metric in get_metric_fields():
s... | CachedMetricsHelper |
python | kamyu104__LeetCode-Solutions | Python/count-number-of-trapezoids-i.py | {
"start": 78,
"end": 548
} | class ____(object):
def countTrapezoids(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
MOD = 10**9+7
cnt = collections.defaultdict(int)
for _, y in points:
cnt[y] += 1
result = total = 0
for c in cnt.itervalues():
... | Solution |
python | skorch-dev__skorch | skorch/tests/test_history.py | {
"start": 251,
"end": 14041
} | class ____:
test_epochs = 3
test_batches = 4
@pytest.fixture(scope='class', params=['single', 'distributed'])
def history_cls(self, request):
# run tests once with default History, once with DistributedHistory
from skorch.history import DistributedHistory, History
from skorch._... | TestHistory |
python | chroma-core__chroma | sample_apps/generative_benchmarking/functions/types.py | {
"start": 725,
"end": 791
} | class ____:
results: Dict[str, Dict[str, float]]
| ResultMetricsDict |
python | PrefectHQ__prefect | tests/server/models/test_block_types.py | {
"start": 2636,
"end": 8885
} | class ____:
@pytest.fixture
async def block_types_with_associated_capabilities(self, session):
class CanRun(Block):
_block_schema_capabilities = ["run"]
def run(self):
pass
class CanFly(Block):
_block_schema_capabilities = ["fly"]
... | TestReadBlockTypes |
python | getsentry__sentry | tests/sentry/web/frontend/test_cli.py | {
"start": 150,
"end": 760
} | class ____(TestCase):
def test_cli(self) -> None:
resp = self.client.get(reverse("get_cli_script"))
assert b"https://release-registry.services.sentry.io/apps/sentry-cli" in resp.content
def test_valid_platform_arch(self) -> None:
resp = self.client.get(reverse("get_cli_download_url", ar... | GetCliDownloadUrlTestCase |
python | getsentry__sentry | src/sentry/integrations/jira_server/integration.py | {
"start": 4560,
"end": 4667
} | class ____(TypedDict):
emptyMessage: str
noResultsMessage: str
items: list[_Project]
| _AddDropDown |
python | airbytehq__airbyte | airbyte-ci/connectors/live-tests/src/live_tests/commons/connector_runner.py | {
"start": 413,
"end": 9469
} | class ____:
DATA_DIR = "/airbyte/data"
IN_CONTAINER_CONFIG_PATH = f"{DATA_DIR}/config.json"
IN_CONTAINER_CONFIGURED_CATALOG_PATH = f"{DATA_DIR}/catalog.json"
IN_CONTAINER_STATE_PATH = f"{DATA_DIR}/state.json"
IN_CONTAINER_OUTPUT_PATH = f"{DATA_DIR}/output.txt"
IN_CONTAINER_OBFUSCATOR_PATH = "/us... | ConnectorRunner |
python | kubernetes-client__python | kubernetes/client/models/v1_typed_local_object_reference.py | {
"start": 383,
"end": 5769
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1TypedLocalObjectReference |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 342606,
"end": 351216
} | class ____:
""" Tests for wasserstein_distance_nd() output values.
"""
def test_published_values(self):
# Compare against published values and manually computed results.
# The values and computed result are posted at James D. McCaffrey's blog,
# https://jamesmccaffrey.wordpress.com/... | TestWassersteinDistanceND |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.