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 | pypa__warehouse | tests/unit/manage/test_forms.py | {
"start": 36691,
"end": 37311
} | class ____:
def test_validate(self):
organization_service = pretend.stub()
user_service = pretend.stub(find_userid=pretend.call_recorder(lambda userid: 1))
form = forms.CreateOrganizationRoleForm(
MultiDict({"username": "user", "role_name": "Owner"}),
orgtype="Compan... | TestCreateOrganizationRoleForm |
python | run-llama__llama_index | llama-index-finetuning/llama_index/finetuning/types.py | {
"start": 1305,
"end": 1618
} | class ____(ABC):
"""Base Cohere Reranker Finetuning Engine."""
@abstractmethod
def finetune(self) -> None:
"""Goes off and does stuff."""
@abstractmethod
def get_finetuned_model(self, top_n: int = 5) -> CohereRerank:
"""Gets finetuned model."""
| BaseCohereRerankerFinetuningEngine |
python | ray-project__ray | python/ray/llm/_internal/serve/utils/batcher.py | {
"start": 301,
"end": 3662
} | class ____(Generic[T]):
"""This class batches multiple responses from a generator into a list of
single responses, at some time interval.
Args:
generator: the async generator that this class pulls responses
from.
interval_ms: the interval at which this class yields the current b... | Batcher |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategy_options.py | {
"start": 63002,
"end": 71898
} | class ____(_LoadElement):
"""Loader strategies against specific relationship or column paths.
e.g.::
joinedload(User.addresses)
defer(Order.name)
selectinload(User.orders).lazyload(Order.items)
"""
__slots__ = ("_of_type", "_path_with_polymorphic_path")
__visit_name__ = ... | _AttributeStrategyLoad |
python | kennethreitz__tablib | src/tablib/formats/_rst.py | {
"start": 633,
"end": 9210
} | class ____:
title = 'rst'
extensions = ('rst',)
MAX_TABLE_WIDTH = 80 # Roughly. It may be wider to avoid breaking words.
@classmethod
def _get_column_string_lengths(cls, dataset):
"""
Returns a list of string lengths of each column, and a list of
maximum word lengths.
... | ReSTFormat |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed3.py | {
"start": 1851,
"end": 1952
} | class ____(TypedDict, extra_items=int | None):
name: str
# This should generate an error.
| MovieBase |
python | plotly__plotly.py | plotly/graph_objs/box/_selected.py | {
"start": 233,
"end": 2366
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "box"
_path_str = "box.selected"
_valid_props = {"marker"}
@property
def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.bo... | Selected |
python | coleifer__peewee | tests/model_sql.py | {
"start": 40130,
"end": 40210
} | class ____(Model):
class Meta:
database = compound_db
| CompoundTestModel |
python | automl__auto-sklearn | test/test_evaluation/test_test_evaluator.py | {
"start": 2978,
"end": 7609
} | class ____(unittest.TestCase):
def setUp(self):
self.queue = multiprocessing.Queue()
self.configuration = get_configuration_space(
DummyDatamanager()
).get_default_configuration()
self.data = get_multiclass_classification_datamanager()
self.tmp_dir = os.path.join(... | FunctionsTest |
python | wandb__wandb | wandb/apis/public/runs.py | {
"start": 16474,
"end": 52618
} | class ____(Attrs):
"""A single run associated with an entity and project.
Args:
client: The W&B API client.
entity: The entity associated with the run.
project: The project associated with the run.
run_id: The unique identifier for the run.
attrs: The attributes of the r... | Run |
python | pytorch__pytorch | torch/ao/quantization/quantizer/quantizer.py | {
"start": 2188,
"end": 2857
} | class ____(QuantizationSpecBase):
dtype: torch.dtype
scale: float
zero_point: int
quant_min: int | None = None
quant_max: int | None = None
qscheme: torch.qscheme | None = None
is_dynamic: bool = False
"""
The way we refer to other points of quantization in the graph will be either
an inpu... | FixedQParamsQuantizationSpec |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/key_value_parsers.py | {
"start": 1776,
"end": 3067
} | class ____(KeyValueParser):
"""Composite argument parser for controller key/value pairs."""
def get_parsers(self, state: ParserState) -> dict[str, Parser]:
"""Return a dictionary of key names and value parsers."""
versions = get_controller_pythons(state.root_namespace.controller, False)
... | ControllerKeyValueParser |
python | scipy__scipy | scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py | {
"start": 1031,
"end": 3990
} | class ____(TestCase):
def test_2d_sphere_constraints(self):
# Interior initial point
ta, tb, intersect = sphere_intersections([0, 0],
[1, 0], 0.5)
assert_array_almost_equal([ta, tb], [0, 0.5])
assert_equal(intersect, True)
# ... | TestSphericalBoundariesIntersections |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-cassandra/tests/test_cassandra.py | {
"start": 415,
"end": 3672
} | class ____(unittest.TestCase):
@pytest.mark.skipif(not has_cassio, reason="cassio not installed")
def test_cassandra_create_and_crud(self) -> None:
mock_db_session = MagicMock()
try:
import cassio # noqa
except ModuleNotFoundError:
# mock `cassio` if not installe... | TestCassandraVectorStore |
python | numpy__numpy | numpy/distutils/tests/test_misc_util.py | {
"start": 292,
"end": 1459
} | class ____:
def test_1(self):
assert_equal(appendpath('prefix', 'name'), join('prefix', 'name'))
assert_equal(appendpath('/prefix', 'name'), ajoin('prefix', 'name'))
assert_equal(appendpath('/prefix', '/name'), ajoin('prefix', 'name'))
assert_equal(appendpath('prefix', '/name'), joi... | TestAppendpath |
python | pypa__setuptools | setuptools/_distutils/filelist.py | {
"start": 408,
"end": 11942
} | class ____:
"""A list of files built by on exploring the filesystem and filtered by
applying various patterns to what we find there.
Instance attributes:
dir
directory from which files will be taken -- only used if
'allfiles' not supplied to constructor
files
list of fil... | FileList |
python | plotly__plotly.py | plotly/graph_objs/surface/_lightposition.py | {
"start": 233,
"end": 3494
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "surface"
_path_str = "surface.lightposition"
_valid_props = {"x", "y", "z"}
@property
def x(self):
"""
Numeric vector, representing the X coordinate for each vertex.
The 'x' property is a number and may be specified a... | Lightposition |
python | mlflow__mlflow | mlflow/entities/multipart_upload.py | {
"start": 295,
"end": 727
} | class ____:
part_number: int
etag: str
url: str | None = None
@classmethod
def from_proto(cls, proto):
return cls(
proto.part_number,
proto.etag or None,
proto.url or None,
)
def to_dict(self):
return {
"part_number": self... | MultipartUploadPart |
python | django__django | tests/utils_tests/test_choices.py | {
"start": 3380,
"end": 14017
} | class ____(SimpleTestCase):
expected = [
("C", _("Club")),
("D", _("Diamond")),
("H", _("Heart")),
("S", _("Spade")),
]
expected_nested = [
("Audio", [("vinyl", _("Vinyl")), ("cd", _("CD"))]),
("Video", [("vhs", _("VHS Tape")), ("dvd", _("DVD"))]),
("u... | NormalizeFieldChoicesTests |
python | scikit-learn__scikit-learn | sklearn/exceptions.py | {
"start": 6176,
"end": 7703
} | class ____(UserWarning):
"""Warning raised when an estimator check from the common tests fails.
Parameters
----------
estimator : estimator object
Estimator instance for which the test failed.
check_name : str
Name of the check that failed.
exception : Exception
Except... | EstimatorCheckFailedWarning |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 153627,
"end": 158319
} | class ____(Request):
"""
Get the image for the next variant for the same iteration or for the next iteration
:param task: Task ID
:type task: str
:param scroll_id: Scroll ID from the previous call to get_debug_image_sample
:type scroll_id: str
:param navigate_earlier: If set then get the ei... | NextDebugImageSampleRequest |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/sentry_app_authorizations.py | {
"start": 1198,
"end": 1489
} | class ____(serializers.Serializer):
client_id = serializers.CharField(required=True, allow_null=False)
refresh_token = serializers.CharField(required=True, allow_null=False)
grant_type = serializers.CharField(required=True, allow_null=False)
| SentryAppRefreshAuthorizationSerializer |
python | getsentry__sentry | src/sentry/sentry_metrics/consumers/indexer/tags_validator.py | {
"start": 113,
"end": 810
} | class ____:
"""
This class is used to enforce the limits on tags that are received by the indexer.
"""
MAX_TAG_KEY_LENGTH = MAX_INDEXED_COLUMN_LENGTH
MAX_TAG_VALUE_LENGTH = MAX_INDEXED_COLUMN_LENGTH
def is_allowed(self, tags: Mapping[str, str] | None) -> bool:
"""
Returns True ... | TagsValidator |
python | scrapy__scrapy | tests/CrawlerProcess/twisted_reactor_custom_settings_conflict.py | {
"start": 267,
"end": 626
} | class ____(scrapy.Spider):
name = "asyncio_reactor"
custom_settings = {
"TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor",
}
process = CrawlerProcess()
d1 = process.crawl(SelectReactorSpider)
d1.addErrback(log.err)
d2 = process.crawl(AsyncioReactorSpider)
d2.addErrback(lo... | AsyncioReactorSpider |
python | huggingface__transformers | src/transformers/models/cohere2_vision/modular_cohere2_vision.py | {
"start": 13737,
"end": 14460
} | class ____(GotOcr2ImageProcessorFast):
size = {"height": 512, "width": 512}
min_patches = 1
max_patches = 12
crop_to_patches = True
patch_size = 16
valid_kwargs = Cohere2VisionFastImageProcessorKwargs
def __init__(self, **kwargs: Unpack[Cohere2VisionFastImageProcessorKwargs]):
super... | Cohere2VisionImageProcessorFast |
python | getsentry__sentry | src/sentry/models/activity.py | {
"start": 3507,
"end": 7793
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
project = FlexibleForeignKey("sentry.Project")
group = FlexibleForeignKey("sentry.Group", null=True)
# index on (type, ident)
type: models.Field[int | ActivityType, int] = BoundedPositiveIntegerField(choices=CHOICES)
ident = mod... | Activity |
python | langchain-ai__langchain | libs/partners/openai/langchain_openai/chat_models/base.py | {
"start": 87169,
"end": 137907
} | class ____(BaseChatOpenAI): # type: ignore[override]
r"""Interface to OpenAI chat model APIs.
???+ info "Setup"
Install `langchain-openai` and set environment variable `OPENAI_API_KEY`.
```bash
pip install -U langchain-openai
# or using uv
uv add langchain-openai
... | ChatOpenAI |
python | getsentry__sentry | tests/integration/test_api.py | {
"start": 531,
"end": 5323
} | class ____(AuthProviderTestCase):
def setUp(self) -> None:
self.organization = self.create_organization(name="foo")
self.user = self.create_user("foobar@example.com", is_superuser=False)
team = self.create_team(name="bar", organization=self.organization)
self.project = self.create_p... | AuthenticationTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/composition.py | {
"start": 2377,
"end": 2493
} | class ____:
"""Marker for holding places in fan-in lists where input mappings will feed."""
| MappedInputPlaceholder |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/backfills.py | {
"start": 2009,
"end": 2141
} | class ____(BaseModel):
"""Backfill serializer for responses in dry-run mode."""
logical_date: datetime
| DryRunBackfillResponse |
python | wandb__wandb | wandb/automations/_filters/operators.py | {
"start": 6120,
"end": 6421
} | class ____(BaseOp):
val: TupleOf[Scalar] = Field(default=(), alias="$nin")
@override
def __invert__(self) -> In:
"""Implements `~NotIn(a) -> In(a)`."""
return In(val=self.val)
# Element operator(s)
# https://www.mongodb.com/docs/manual/reference/operator/query/exists/
| NotIn |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 27779,
"end": 28119
} | class ____(ByOfImpl, RoleImpl):
__slots__ = ()
def _post_coercion(self, resolved, **kw):
if (
isinstance(resolved, self._role_class)
and resolved._order_by_label_element is not None
):
return elements._label_reference(resolved)
else:
retur... | OrderByImpl |
python | django__django | tests/generic_views/views.py | {
"start": 4828,
"end": 4924
} | class ____(generic.DeleteView):
model = Author
success_url = "/list/authors/"
| AuthorDelete |
python | astropy__astropy | astropy/modeling/tests/test_bounding_box.py | {
"start": 66313,
"end": 71522
} | class ____:
def test_create(self):
index = mk.MagicMock()
ignore = mk.MagicMock()
argument = _SelectorArgument(index, ignore)
assert isinstance(argument, _BaseSelectorArgument)
assert argument.index == index
assert argument.ignore == ignore
assert argument ==... | Test_SelectorArgument |
python | numba__numba | numba/tests/test_builtins.py | {
"start": 34449,
"end": 35626
} | class ____(TestCase):
def test_eq_ne(self):
for opstr in ('eq', 'ne'):
op = getattr(operator, opstr)
@njit
def func(a, b):
return op(a, b)
# all these things should evaluate to being equal or not, all should
# survive typing.
... | TestOperatorMixedTypes |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/mpich2/package.py | {
"start": 217,
"end": 1067
} | class ____(Package):
homepage = "http://www.mpich.org"
url = "http://www.mpich.org/static/downloads/1.5/mpich2-1.5.tar.gz"
list_url = "http://www.mpich.org/static/downloads/"
list_depth = 2
tags = ["tag1", "tag3"]
version("1.5", md5="9c5d5d4fe1e17dd12153f40bc5b6dbc0")
version("1.4", md5="0... | Mpich2 |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_captured_logs.py | {
"start": 1176,
"end": 7566
} | class ____(ExecutingGraphQLContextTestMatrix):
def test_get_captured_logs_over_graphql(self, graphql_context):
selector = infer_job_selector(graphql_context, "spew_job")
payload = sync_execute_get_run_log_data(
context=graphql_context,
variables={"executionParams": {"selector... | TestCapturedLogs |
python | tornadoweb__tornado | tornado/httputil.py | {
"start": 13859,
"end": 23218
} | class ____:
"""A single HTTP request.
All attributes are type `str` unless otherwise noted.
.. attribute:: method
HTTP request method, e.g. "GET" or "POST"
.. attribute:: uri
The requested uri.
.. attribute:: path
The path portion of `uri`
.. attribute:: query
... | HTTPServerRequest |
python | pytorch__pytorch | test/mobile/lightweight_dispatch/tests_setup.py | {
"start": 827,
"end": 1129
} | class ____(torch.nn.Module):
def forward(self, x: int):
a = torch.ones(
size=[3, x],
dtype=torch.int64,
layout=torch.strided,
device="cpu",
pin_memory=False,
)
return a
@save_model
| ModelWithDTypeDeviceLayoutPinMemory |
python | sqlalchemy__sqlalchemy | test/perf/orm2010.py | {
"start": 883,
"end": 5645
} | class ____(Employee):
__tablename__ = "grunt"
id = Column(Integer, ForeignKey("employee.id"), primary_key=True)
savings = Column(Numeric)
employer_id = Column(Integer, ForeignKey("boss.id"))
employer = relationship(
"Boss", backref="employees", primaryjoin=Boss.id == employer_id
)
... | Grunt |
python | apache__airflow | providers/grpc/src/airflow/providers/grpc/operators/grpc.py | {
"start": 1254,
"end": 4010
} | class ____(BaseOperator):
"""
Calls a gRPC endpoint to execute an action.
:param stub_class: The stub client to use for this gRPC call
:param call_func: The client function name to call the gRPC endpoint
:param grpc_conn_id: The connection to run the operator against
:param data: The data to pa... | GrpcOperator |
python | huggingface__transformers | src/transformers/models/llava_next_video/modular_llava_next_video.py | {
"start": 25913,
"end": 34787
} | class ____(LlavaNextForConditionalGeneration):
def get_video_features(
self,
pixel_values: torch.FloatTensor,
vision_feature_layer: Optional[Union[int, list[int]]] = None,
vision_feature_select_strategy: Optional[str] = None,
):
return self.model.get_video_features(
... | LlavaNextVideoForConditionalGeneration |
python | django__django | tests/staticfiles_tests/test_management.py | {
"start": 17262,
"end": 17349
} | class ____(TestCollectionDryRun):
pass
| TestCollectionDryRunManifestStaticFilesStorage |
python | zostera__django-bootstrap4 | src/bootstrap4/templatetags/bootstrap4.py | {
"start": 17227,
"end": 23533
} | class ____(template.Node):
def __init__(self, nodelist, args, kwargs, asvar, **kwargs2):
self.nodelist = nodelist
self.args = args
self.kwargs = kwargs
self.asvar = asvar
def render(self, context):
output_kwargs = {}
for key in self.kwargs:
output_kwa... | ButtonsNode |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 58272,
"end": 58835
} | class ____(CBaseTypeNode):
# components [CBaseTypeNode]
child_attrs = ["components"]
def analyse(self, env, could_be_name=False):
component_types = []
for c in self.components:
type = c.analyse(env)
if type.is_pyobject:
error(c.pos, "Tuple types can'... | CTupleBaseTypeNode |
python | realpython__materials | python-textual/vertical_layout_tcss.py | {
"start": 120,
"end": 413
} | class ____(App):
CSS_PATH = "vertical_layout.tcss"
def compose(self):
with Vertical():
for i in range(NUM_BOXES):
yield Static(f"Static {i + 1}")
if __name__ == "__main__":
app = VerticalLayoutAppWithTCSS()
app.run()
| VerticalLayoutAppWithTCSS |
python | spack__spack | var/spack/test_repos/spack_repo/builder_test/packages/gnuconfig/package.py | {
"start": 216,
"end": 525
} | class ____(Package):
"""This package is needed to allow mocking AutotoolsPackage objects"""
homepage = "http://www.example.com"
url = "http://www.example.com/a-1.0.tar.gz"
version("2.0", md5="abcdef0123456789abcdef0123456789")
version("1.0", md5="0123456789abcdef0123456789abcdef")
| Gnuconfig |
python | run-llama__llama_index | llama-index-experimental/llama_index/experimental/param_tuner/base.py | {
"start": 1529,
"end": 2171
} | class ____(BaseModel):
"""Base param tuner."""
param_dict: Dict[str, Any] = Field(
..., description="A dictionary of parameters to iterate over."
)
fixed_param_dict: Dict[str, Any] = Field(
default_factory=dict,
description="A dictionary of fixed parameters passed to each job.",... | BaseParamTuner |
python | huggingface__transformers | src/transformers/models/clip/modeling_clip.py | {
"start": 41744,
"end": 43815
} | class ____(CLIPPreTrainedModel):
main_input_name = "pixel_values"
input_modalities = ("image",)
def __init__(self, config: CLIPConfig) -> None:
super().__init__(config)
self.num_labels = config.num_labels
vision_model = CLIPVisionModel._from_config(config.vision_config)
sel... | CLIPForImageClassification |
python | plotly__plotly.py | plotly/graph_objs/waterfall/totals/marker/_line.py | {
"start": 233,
"end": 3176
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "waterfall.totals.marker"
_path_str = "waterfall.totals.marker.line"
_valid_props = {"color", "width"}
@property
def color(self):
"""
Sets the line color of all intermediate sums and total values.
The 'color' property ... | Line |
python | tensorflow__tensorflow | tensorflow/python/ops/lookup_ops.py | {
"start": 29783,
"end": 31938
} | class ____(TextFileInitializer):
"""Table initializer for `int64` IDs to string tables from a text file."""
def __init__(self,
filename,
key_column_index=TextFileIndex.LINE_NUMBER,
value_column_index=TextFileIndex.WHOLE_LINE,
vocab_size=None,
... | TextFileStringTableInitializer |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 64836,
"end": 65305
} | class ____(themeable):
def apply_figure(self, figure: Figure, targets: ThemeTargets):
warn(
"You no longer need to use subplots_adjust to make space for "
"the legend or text around the panels. This parameter will be "
"removed in a future version. You can still use 'plot... | subplots_adjust |
python | doocs__leetcode | solution/1800-1899/1820.Maximum Number of Accepted Invitations/Solution.py | {
"start": 0,
"end": 548
} | class ____:
def maximumInvitations(self, grid: List[List[int]]) -> int:
def find(i):
for j, v in enumerate(grid[i]):
if v and j not in vis:
vis.add(j)
if match[j] == -1 or find(match[j]):
match[j] = i
... | Solution |
python | pytorch__pytorch | torch/_dynamo/device_interface.py | {
"start": 14439,
"end": 17758
} | class ____(DeviceInterface):
device = torch.xpu.device # type: ignore[assignment]
Event = torch.xpu.Event # type: ignore[assignment]
Stream = torch.xpu.Stream # type: ignore[assignment]
# pyrefly: ignore [bad-override]
class Worker:
@staticmethod
def set_device(device: int) -> No... | XpuInterface |
python | django-extensions__django-extensions | django_extensions/management/commands/sqldsn.py | {
"start": 2679,
"end": 6608
} | class ____(BaseCommand):
help = "Prints DSN on stdout, as specified in settings.py"
requires_system_checks: List[str] = []
can_import_settings = True
def add_arguments(self, parser):
super().add_arguments(parser)
dbspec = parser.add_mutually_exclusive_group()
dbspec.add_argument... | Command |
python | google__jax | jax/_src/test_util.py | {
"start": 42985,
"end": 54286
} | class ____(parameterized.TestCase):
"""Base class for JAX tests including numerical checks and boilerplate."""
_default_global_config: dict[str, Any] = {}
_default_thread_local_config = {
'jax_enable_checks': True,
'jax_numpy_dtype_promotion': 'strict',
'jax_numpy_rank_promotion': 'raise',
'jax_tr... | JaxTestCase |
python | getsentry__sentry | tests/sentry/integrations/web/test_organization_integration_setup.py | {
"start": 211,
"end": 768
} | class ____(PermissionTestCase):
def setUp(self) -> None:
super().setUp()
self.path = f"/organizations/{self.organization.slug}/integrations/example/setup/"
# this currently redirects the user
@pytest.mark.xfail
def test_manager_can_load(self) -> None:
self.assert_role_can_access... | OrganizationIntegrationSetupPermissionTest |
python | getsentry__sentry | src/sentry/rules/conditions/event_attribute.py | {
"start": 13357,
"end": 13819
} | class ____(AttributeHandler):
minimum_path_length = 2
@classmethod
def _handle(cls, path: list[str], event: GroupEvent) -> list[str]:
if path[1] in ("in_foreground"):
contexts = event.data.get("contexts", {})
response = contexts.get("app")
if response is None:
... | AppAttributeHandler |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/__init__.py | {
"start": 4230,
"end": 6269
} | class ____ implements the rendezvous mechanism described above. It is a backend-
agnostic type that expects a particular :py:class:`.RendezvousBackend` instance
to be specified during construction.
Torch distributed users can either implement their own backend type or use one
of the following implementations that come... | that |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_ignore_error01.py | {
"start": 315,
"end": 813
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("ignore_error01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.go... | TestCompareXLSXFiles |
python | PyCQA__pylint | tests/functional/r/raising/raising_self.py | {
"start": 37,
"end": 213
} | class ____(Exception):
def __init__(self):
Exception.__init__(self)
def return_self(self):
return self
raise MultiException().return_self()
| MultiException |
python | huggingface__transformers | tests/tensor_parallel/test_tensor_parallel.py | {
"start": 19027,
"end": 19155
} | class ____(TestTensorParallelBase):
"""Test tensor parallel with 4 processes."""
nproc_per_node = 4
| TestTensorParallel4Proc |
python | django__django | django/db/models/fields/__init__.py | {
"start": 99184,
"end": 99419
} | class ____(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta):
def get_internal_type(self):
return "AutoField"
def rel_db_type(self, connection):
return IntegerField().db_type(connection=connection)
| AutoField |
python | google__jax | jax/_src/pallas/core.py | {
"start": 4209,
"end": 4801
} | class ____:
"""Specifies how a block should be buffered for a pipeline.
Attributes:
buffer_count: The number of buffers to use for multiple buffering.
use_lookahead: optional bool, indicates whether to use lookahead on the
buffer. Enabling lookahead allows the pipeline to begin fetching the next
... | Buffered |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 117659,
"end": 135009
} | class ____(Response):
"""
Response of dataviews.get_by_id endpoint.
:param dataview: Dataview information
:type dataview: Dataview
"""
_service = "dataviews"
_action = "get_by_id"
_version = "2.23"
_schema = {
"definitions": {
"augmentation": {
... | GetByIdResponse |
python | oauthlib__oauthlib | oauthlib/openid/connect/core/exceptions.py | {
"start": 824,
"end": 1223
} | class ____(OpenIDClientError):
"""
The Authorization Server requires End-User authentication.
This error MAY be returned when the prompt parameter value in the
Authentication Request is none, but the Authentication Request cannot be
completed without displaying a user interface for End-User authent... | LoginRequired |
python | tensorflow__tensorflow | tensorflow/python/keras/losses.py | {
"start": 12765,
"end": 14743
} | class ____(LossFunctionWrapper):
"""Computes the mean of absolute difference between labels and predictions.
`loss = abs(y_true - y_pred)`
Standalone usage:
>>> y_true = [[0., 1.], [0., 0.]]
>>> y_pred = [[1., 1.], [1., 0.]]
>>> # Using 'auto'/'sum_over_batch_size' reduction type.
>>> mae = tf.keras.lo... | MeanAbsoluteError |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 34637,
"end": 34756
} | class ____(Operator):
__slots__ = ()
_description = "bitwise xor"
_pretty = "^"
_op = operator.xor
| BitXor |
python | jazzband__django-oauth-toolkit | oauth2_provider/contrib/rest_framework/authentication.py | {
"start": 205,
"end": 1789
} | class ____(BaseAuthentication):
"""
OAuth 2 authentication backend using `django-oauth-toolkit`
"""
www_authenticate_realm = "api"
def _dict_to_string(self, my_dict):
"""
Return a string of comma-separated key-value pairs (e.g. k="v",k2="v2").
"""
return ",".join(['... | OAuth2Authentication |
python | pyca__cryptography | tests/hazmat/primitives/test_dsa.py | {
"start": 28724,
"end": 37358
} | class ____:
@pytest.mark.parametrize(
("fmt", "password"),
itertools.product(
[
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.PrivateFormat.PKCS8,
],
[
b"s",
b"longerpassword",
... | TestDSASerialization |
python | sympy__sympy | sympy/physics/mechanics/method.py | {
"start": 37,
"end": 660
} | class ____(ABC):
"""Abstract Base Class for all methods."""
@abstractmethod
def q(self):
pass
@abstractmethod
def u(self):
pass
@abstractmethod
def bodies(self):
pass
@abstractmethod
def loads(self):
pass
@abstractmethod
def mass_matrix(se... | _Methods |
python | has2k1__plotnine | plotnine/scales/scale_color.py | {
"start": 9064,
"end": 9202
} | class ____(scale_color_gradientn):
"""
Create a n color gradient
"""
_aesthetics = ["fill"]
@dataclass
| scale_fill_gradientn |
python | huggingface__transformers | src/transformers/models/ernie/modeling_ernie.py | {
"start": 22868,
"end": 24357
} | class ____(PreTrainedModel):
config_class = ErnieConfig
base_model_prefix = "ernie"
supports_gradient_checkpointing = True
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": Erni... | ErniePreTrainedModel |
python | getsentry__sentry | src/sentry/models/groupresolution.py | {
"start": 688,
"end": 7806
} | class ____(Model):
"""
Describes when a group was marked as resolved.
"""
__relocation_scope__ = RelocationScope.Excluded
class Type:
in_release = 0
in_next_release = 1
class Status:
pending = 0
resolved = 1
group = FlexibleForeignKey("sentry.Group", uniqu... | GroupResolution |
python | fastai__fastai | fastai/metrics.py | {
"start": 22473,
"end": 23194
} | class ____(AvgMetric):
"Create a metric from `loss_func.attr` named `nm`"
def __init__(self, attr, nm=None): store_attr('attr,nm')
def accumulate(self, learn):
bs = find_bs(learn.yb)
self.total += learn.to_detach(getattr(learn.loss_func, self.attr, 0))*bs
self.count += bs
@prope... | LossMetric |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py | {
"start": 27842,
"end": 36029
} | class ____(Qwen3VLMoePreTrainedModel):
config: Qwen3VLMoeVisionConfig
_no_split_modules = ["Qwen3VLMoeVisionBlock"]
def __init__(self, config, *inputs, **kwargs) -> None:
super().__init__(config, *inputs, **kwargs)
self.spatial_merge_size = config.spatial_merge_size
self.patch_size ... | Qwen3VLMoeVisionModel |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_types.py | {
"start": 23633,
"end": 23980
} | class ____(_DateFixture, fixtures.TablesTest):
__requires__ = ("date",)
__backend__ = True
datatype = Date
data = datetime.date(2012, 10, 15)
@testing.requires.date_implicit_bound
def test_select_direct(self, connection):
result = connection.scalar(select(literal(self.data)))
eq... | DateTest |
python | getsentry__sentry | src/sentry/incidents/logic.py | {
"start": 10854,
"end": 11011
} | class ____(BaseMetricIssueQueryParams):
start_arg: datetime | None = None
end_arg: datetime | None = None
@dataclass
| CalculateOpenPeriodTimeRangeParams |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 81118,
"end": 83000
} | class ____(StatelessSymbolicContext):
"""
Create symbols in ``create_symbolic_sizes_strides_storage_offset`` via
a symbolic_context determination as given by a cache of Source:Symbol. A cache hit
will reuse a stored symbol, and a cache miss will write to this cache.
This behaves like StatelessSymbo... | StatefulSymbolicContext |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/fixtures/base.py | {
"start": 729,
"end": 12127
} | class ____:
# A sequence of requirement names matching testing.requires decorators
__requires__ = ()
# A sequence of dialect names to exclude from the test class.
__unsupported_on__ = ()
# If present, test class is only runnable for the *single* specified
# dialect. If you need multiple, use ... | TestBase |
python | django__django | django/db/models/functions/text.py | {
"start": 7898,
"end": 8086
} | class ____(Func):
function = "REPLACE"
def __init__(self, expression, text, replacement=Value(""), **extra):
super().__init__(expression, text, replacement, **extra)
| Replace |
python | huggingface__transformers | tests/models/hiera/test_modeling_hiera.py | {
"start": 22106,
"end": 26112
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return AutoImageProcessor.from_pretrained("facebook/hiera-tiny-224-in1k-hf") if is_vision_available() else None
def test_inference_image_classification_head(self):
model = HieraForImageClassification.from_pre... | HieraModelIntegrationTest |
python | django__django | django/contrib/gis/db/backends/mysql/operations.py | {
"start": 541,
"end": 5174
} | class ____(BaseSpatialOperations, DatabaseOperations):
name = "mysql"
geom_func_prefix = "ST_"
Adapter = WKTAdapter
@cached_property
def mariadb(self):
return self.connection.mysql_is_mariadb
@cached_property
def mysql(self):
return not self.connection.mysql_is_mariadb
... | MySQLOperations |
python | kamyu104__LeetCode-Solutions | Python/count-zero-request-servers.py | {
"start": 66,
"end": 1016
} | class ____(object):
def countServers(self, n, logs, x, queries):
"""
:type n: int
:type logs: List[List[int]]
:type x: int
:type queries: List[int]
:rtype: List[int]
"""
logs.sort(key=lambda x:x[1])
result = [0]*len(queries)
cnt = [0]*n... | Solution |
python | numba__numba | numba/cuda/simulator/kernel.py | {
"start": 991,
"end": 1305
} | class ____:
'''
Used only to provide the max_cooperative_grid_blocks method
'''
def max_cooperative_grid_blocks(self, blockdim):
# We can only run one block in a cooperative grid because we have no
# mechanism for synchronization between different blocks
return 1
| FakeOverload |
python | astropy__astropy | astropy/utils/masked/tests/test_function_helpers.py | {
"start": 1860,
"end": 2079
} | class ____(MaskedArraySetup):
def check(self, func, *args, **kwargs):
o = func(self.ma, *args, **kwargs)
expected = func(self.a, *args, **kwargs)
assert_array_equal(o, expected)
| NoMaskTestSetup |
python | ApeWorX__ape | tests/conftest.py | {
"start": 14151,
"end": 15131
} | class ____(SubprocessRunner):
"""
Subprocess runner for Ape-specific commands.
"""
def __init__(
self,
root_cmd: Optional[Union[str, Sequence[str]]] = None,
data_folder: Optional[Path] = None,
):
ape_path = Path(sys.executable).parent / "ape"
root = root_cmd... | ApeSubprocessRunner |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/schemas/role_and_permission_schema.py | {
"start": 1637,
"end": 1907
} | class ____(SQLAlchemySchema):
"""Action View Schema."""
class Meta:
"""Meta."""
model = Permission
action = fields.Nested(ActionSchema, data_key="action")
resource = fields.Nested(ResourceSchema, data_key="resource")
| ActionResourceSchema |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/bedrock.py | {
"start": 2533,
"end": 3964
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger when a Bedrock Knowledge Base reaches the ACTIVE state.
:param knowledge_base_id: The unique identifier of the knowledge base for which to get information.
:param waiter_delay: The amount of time in seconds to wait between attempts. (default: 5)
:param... | BedrockKnowledgeBaseActiveTrigger |
python | scikit-learn__scikit-learn | sklearn/compose/tests/test_target.py | {
"start": 10907,
"end": 11722
} | class ____(TransformerMixin, BaseEstimator):
"""Dummy transformer which count how many time fit was called."""
def __init__(self, fit_counter=0):
self.fit_counter = fit_counter
def fit(self, X, y=None):
self.fit_counter += 1
return self
def transform(self, X):
return X... | DummyTransformer |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/keyword_table/retrievers.py | {
"start": 4539,
"end": 6207
} | class ____(BaseKeywordTableRetriever):
"""
Keyword Table Index GPT Retriever.
Extracts keywords using GPT. Set when using `retriever_mode="default"`.
See BaseGPTKeywordTableQuery for arguments.
"""
def __init__(
self,
index: BaseKeywordTableIndex,
keyword_extract_temp... | KeywordTableGPTRetriever |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/autograd_cache.py | {
"start": 20541,
"end": 20784
} | class ____(CacheArtifact):
@override
def populate_cache(self):
AOTAutogradCache._write_to_local_cache(self.key, self.content)
@override
@staticmethod
def type():
return "aot_autograd"
| AOTAutogradCacheArtifact |
python | readthedocs__readthedocs.org | readthedocs/integrations/models.py | {
"start": 11979,
"end": 14023
} | class ____(Integration):
"""
Dummy integration for GitHub App projects.
This is a proxy model for the Integration model, which is used to
represent GitHub App integrations in the UI.
This integration is automatically created when a project is linked to a
remote repository from a GitHub App ins... | GitHubAppIntegration |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/communicator.py | {
"start": 379,
"end": 1887
} | class ____:
def __init__(self, worker_id=0, base_port=5005):
"""
Python side of the communication. Must be used in pair with the right Unity Communicator equivalent.
:int worker_id: Offset from base_port. Used for training multiple environments simultaneously.
:int base_port: Baseli... | Communicator |
python | scrapy__scrapy | tests/test_command_crawl.py | {
"start": 3178,
"end": 3650
} | class ____(scrapy.Spider):
name = 'myspider'
async def start(self):
self.logger.debug('It works!')
return
yield
"""
log = self.get_log(spider_code, proj_path, args=("-s", "TWISTED_REACTOR="))
assert "[myspider] DEBUG: It works!" in log
assert (
"Using... | MySpider |
python | pypa__warehouse | warehouse/config.py | {
"start": 1580,
"end": 36143
} | class ____:
__parent__ = None
__name__ = None
__acl__ = [
(
Allow,
"group:admins",
(
Permissions.AdminBannerRead,
Permissions.AdminBannerWrite,
Permissions.AdminDashboardRead,
Permissions.AdminDashbo... | RootFactory |
python | doocs__leetcode | solution/3600-3699/3688.Bitwise OR of Even Numbers in an Array/Solution.py | {
"start": 0,
"end": 139
} | class ____:
def evenNumberBitwiseORs(self, nums: List[int]) -> int:
return reduce(or_, (x for x in nums if x % 2 == 0), 0)
| Solution |
python | Pylons__pyramid | tests/test_session.py | {
"start": 19396,
"end": 19868
} | class ____(unittest.TestCase):
def _makeOne(self, wrapped):
from pyramid.session import manage_changed
return manage_changed(wrapped)
def test_it(self):
request = testing.DummyRequest()
session = DummySessionFactory(request)
wrapper = self._makeOne(session.__class__.__s... | Test_manage_changed |
python | pydantic__pydantic | pydantic/types.py | {
"start": 36376,
"end": 36673
} | class ____(BaseModel):
uuid6: UUID6
Model(uuid6=uuid.UUID('1efea953-c2d6-6790-aa0a-69db8c87df97'))
```
"""
UUID7 = Annotated[UUID, UuidVersion(7)]
"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 7.
```python
import uuid
from pydantic import UUID7, BaseModel
| Model |
python | keon__algorithms | tests/test_maths.py | {
"start": 2927,
"end": 3242
} | class ____(unittest.TestCase):
"""[summary]
Test for the file extended_gcd.py
Arguments:
unittest {[type]} -- [description]
"""
def test_extended_gcd(self):
self.assertEqual((0, 1, 2), extended_gcd(8, 2))
self.assertEqual((0, 1, 17), extended_gcd(13, 17))
| TestExtendedGcd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.