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__pipenv | pipenv/patched/pip/_internal/resolution/resolvelib/base.py | {
"start": 2359,
"end": 3572
} | class ____:
@property
def project_name(self) -> NormalizedName:
"""The "project name" of a requirement.
This is different from ``name`` if this requirement contains extras,
in which case ``name`` would contain the ``[...]`` part, while this
refers to the name of the project.
... | Requirement |
python | scikit-learn__scikit-learn | sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py | {
"start": 23217,
"end": 30032
} | class ____(BaseDistancesReductionDispatcher):
"""Compute radius-based class modes of row vectors of X using the
those of Y.
For each row-vector X[i] of the queries X, find all the indices j of
row-vectors in Y such that:
dist(X[i], Y[j]) <= radius
RadiusNeighborsClassMode ... | RadiusNeighborsClassMode |
python | agronholm__apscheduler | src/apscheduler/_events.py | {
"start": 999,
"end": 1134
} | class ____(Event):
"""Base class for events originating from a data store."""
@attrs.define(kw_only=True, frozen=True)
| DataStoreEvent |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/cursor_shapes.py | {
"start": 497,
"end": 1340
} | class ____(Enum):
# Default value that should tell the output implementation to never send
# cursor shape escape sequences. This is the default right now, because
# before this `CursorShape` functionality was introduced into
# prompt_toolkit itself, people had workarounds to send cursor shapes
# esc... | CursorShape |
python | Netflix__metaflow | metaflow/_vendor/click/exceptions.py | {
"start": 7846,
"end": 8118
} | class ____(RuntimeError):
"""An exception that indicates that the application should exit with some
status code.
:param code: the status code to exit with.
"""
__slots__ = ("exit_code",)
def __init__(self, code=0):
self.exit_code = code
| Exit |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 13538,
"end": 13932
} | class ____(DagsterUserCodeExecutionError):
"""Indicates an error occurred while handling an output for a step."""
def __init__(self, *args, **kwargs):
self.step_key = check.str_param(kwargs.pop("step_key"), "step_key")
self.output_name = check.str_param(kwargs.pop("output_name"), "output_name")... | DagsterExecutionHandleOutputError |
python | pyca__cryptography | src/cryptography/hazmat/primitives/serialization/ssh.py | {
"start": 27447,
"end": 27512
} | class ____(enum.Enum):
USER = 1
HOST = 2
| SSHCertificateType |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/pymssql.py | {
"start": 1075,
"end": 1371
} | class ____(MSIdentifierPreparer):
def __init__(self, dialect):
super().__init__(dialect)
# pymssql has the very unusual behavior that it uses pyformat
# yet does not require that percent signs be doubled
self._double_percents = False
| MSIdentifierPreparer_pymssql |
python | allegroai__clearml | clearml/backend_interface/task/repo/detectors.py | {
"start": 13553,
"end": 13674
} | class ____(EnvDetector):
def __init__(self) -> None:
super(GitEnvDetector, self).__init__("git")
| GitEnvDetector |
python | huggingface__transformers | tests/models/musicgen_melody/test_modeling_musicgen_melody.py | {
"start": 53169,
"end": 56092
} | class ____(unittest.TestCase):
@cached_property
def model(self):
return MusicgenMelodyForConditionalGeneration.from_pretrained("ylacombe/musicgen-stereo-melody").to(
torch_device
)
@cached_property
def processor(self):
return MusicgenMelodyProcessor.from_pretrained("... | MusicgenMelodyStereoIntegrationTests |
python | huggingface__transformers | src/transformers/models/glm4_moe/modular_glm4_moe.py | {
"start": 10454,
"end": 11838
} | class ____(CohereAttention):
def __init__(self, config: Glm4MoeConfig, layer_idx: Optional[int] = None):
nn.Module.__init__(self)
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self... | Glm4MoeAttention |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 25679,
"end": 26881
} | class ____:
@pytest.mark.parametrize("error", [ValueError("Hello"), None])
async def test_final_state_reflects_exceptions_during_run(self, error):
@task
def bar():
if error:
raise error
@flow(version="test")
def foo():
return quote(bar(ret... | TestTaskStates |
python | jmcnamara__XlsxWriter | xlsxwriter/test/vml/test_write_textbox.py | {
"start": 289,
"end": 831
} | class ____(unittest.TestCase):
"""
Test the Vml _write_textbox() method.
"""
def setUp(self):
self.fh = StringIO()
self.vml = Vml()
self.vml._set_filehandle(self.fh)
def test_write_comment_textbox(self):
"""Test the _write_comment_textbox() method"""
self.... | TestWriteVtextbox |
python | django__django | django/template/context.py | {
"start": 598,
"end": 3763
} | class ____:
def __init__(self, dict_=None):
self._reset_dicts(dict_)
def _reset_dicts(self, value=None):
builtins = {"True": True, "False": False, "None": None}
self.dicts = [builtins]
if isinstance(value, BaseContext):
self.dicts += value.dicts[1:]
elif valu... | BaseContext |
python | PrefectHQ__prefect | src/prefect/server/services/scheduler.py | {
"start": 1088,
"end": 1199
} | class ____(Exception):
"""Internal control-flow exception used to retry the Scheduler's main loop"""
| TryAgain |
python | getsentry__sentry | src/sentry/integrations/discord/message_builder/base/component/action_row.py | {
"start": 176,
"end": 330
} | class ____(TypedDict):
type: int
components: list[DiscordMessageComponentDict] # Components can be buttons, select menus, etc.
| DiscordActionRowDict |
python | kubernetes-client__python | kubernetes/client/models/v1_custom_resource_definition.py | {
"start": 383,
"end": 7770
} | 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... | V1CustomResourceDefinition |
python | coleifer__peewee | examples/hexastore.py | {
"start": 3104,
"end": 5022
} | class ____(object):
__slots__ = ('name',)
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(self.name)
def __repr__(self):
return '<Variable: %s>' % self.name
if __name__ == '__main__':
h = Hexastore()
data = (
('charlie', 'likes', '... | Variable |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 93290,
"end": 93603
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('engineId', c_uint),
('schedulerPolicy', c_uint),
('enableARRMode', c_uint),
('schedulerParams', c_nvmlVgpuSchedulerSetParams_t),
]
nvmlVgpuSchedulerState_v1 = 0x1000018
| c_nvmlVgpuSchedulerState_v1_t |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/option_list_long.py | {
"start": 131,
"end": 346
} | class ____(App[None]):
def compose(self) -> ComposeResult:
yield OptionList(*[Option(f"This is option #{n}") for n in range(100)])
if __name__ == "__main__":
LongOptionListApp().run()
| LongOptionListApp |
python | google__jax | tests/pallas/ops_test.py | {
"start": 91532,
"end": 94675
} | class ____(PallasBaseTest):
@parameterized.parameters(*[
(lambda: (pl.dslice(0, 4), slice(None), slice(None)), "<- a[:,:,:]"),
(lambda: (pl.dslice(0, 3), slice(None), slice(None)), "<- a[:3,:,:]"),
(lambda: (pl.dslice(1, 3), slice(None), pl.dslice(0, 4)), "<- a[1:,:,:4]"),
(lambda: (jnp.arange(5), sl... | PallasPrimitivesTest |
python | apache__airflow | providers/apache/spark/tests/unit/apache/spark/operators/test_spark_sql.py | {
"start": 1057,
"end": 3371
} | class ____:
_config = {
"sql": "SELECT 22",
"conn_id": "spark_special_conn_id",
"total_executor_cores": 4,
"executor_cores": 4,
"executor_memory": "22g",
"keytab": "privileged_user.keytab",
"principal": "user/spark@airflow.org",
"master": "yarn-client"... | TestSparkSqlOperator |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_file_search.py | {
"start": 4762,
"end": 7327
} | class ____:
"""Tests for filesystem-backed glob search."""
def test_glob_basic_pattern(self, tmp_path: Path) -> None:
"""Test basic glob pattern matching."""
(tmp_path / "file1.py").write_text("content", encoding="utf-8")
(tmp_path / "file2.py").write_text("content", encoding="utf-8")
... | TestFilesystemGlobSearch |
python | plotly__plotly.py | plotly/graph_objs/densitymap/_hoverlabel.py | {
"start": 233,
"end": 11262
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "densitymap"
_path_str = "densitymap.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsr... | Hoverlabel |
python | django__django | django/db/models/functions/text.py | {
"start": 8086,
"end": 8869
} | class ____(Transform):
function = "REVERSE"
lookup_name = "reverse"
def as_oracle(self, compiler, connection, **extra_context):
# REVERSE in Oracle is undocumented and doesn't support multi-byte
# strings. Use a special subquery instead.
suffix = connection.features.bare_select_suff... | Reverse |
python | scrapy__scrapy | tests/test_scheduler_base.py | {
"start": 1937,
"end": 2511
} | class ____(InterfaceCheckMixin):
def setup_method(self):
self.scheduler = BaseScheduler()
def test_methods(self):
assert self.scheduler.open(Spider("foo")) is None
assert self.scheduler.close("finished") is None
with pytest.raises(NotImplementedError):
self.scheduler... | TestBaseScheduler |
python | tensorflow__tensorflow | tensorflow/python/saved_model/utils_test.py | {
"start": 1527,
"end": 8187
} | class ____(test.TestCase):
@test_util.run_v1_only(
"b/120545219: `build_tensor_info` is only available in graph mode.")
def testBuildTensorInfoOp(self):
x = constant_op.constant(1, name="x")
y = constant_op.constant(2, name="y")
z = control_flow_ops.group([x, y], name="op_z")
z_op_info = util... | UtilsTest |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 42812,
"end": 45892
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
... | EvollaMLP |
python | huggingface__transformers | src/transformers/models/mra/modeling_mra.py | {
"start": 8016,
"end": 9088
} | class ____(torch.autograd.Function):
@staticmethod
def forward(ctx, sparse_query, indices, dense_key, query_num_block):
sparse_qk_prod = sparse_dense_mm(sparse_query, indices, dense_key, query_num_block)
ctx.save_for_backward(sparse_query, indices, dense_key)
ctx.query_num_block = query_... | MraSparseDenseMatMul |
python | pytorch__pytorch | torch/_inductor/fx_passes/group_batch_fusion.py | {
"start": 25307,
"end": 31074
} | class ____(BatchFusion):
"""
Batch linear fusion in pre grad pass.
Fuse linear with same size with torch.baddmm
"""
def _getitem_args(self, getitem_node: torch.fx.Node):
if getitem_node.target != operator.__getitem__ or (
getitem_node.op != "call_function"
):
... | PreGradBatchLinearFusion |
python | huggingface__transformers | src/transformers/models/instructblipvideo/modeling_instructblipvideo.py | {
"start": 7804,
"end": 10591
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim /... | InstructBlipVideoAttention |
python | getsentry__sentry | tests/sentry/sentry_metrics/test_snuba.py | {
"start": 404,
"end": 552
} | class ____(BaseMetricsLayerTestCase, TestCase, GenericMetricsTestMixIn):
def setUp(self) -> None:
super().setUp()
| MetricsInterfaceTestCase |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/variable_scope_shim.py | {
"start": 4548,
"end": 22590
} | class ____(object):
"""TF2-compatible VariableStore that avoids collections & tracks regularizers.
New variable names and new variables can be created; all stored
variables are initialized with the initializer passed to __init__.
All variables get created in `tf.init_scope.` to avoid a bad
interaction betwe... | _EagerVariableStore |
python | Lightning-AI__lightning | examples/pytorch/domain_templates/computer_vision_fine_tuning.py | {
"start": 3851,
"end": 6046
} | class ____(LightningDataModule):
def __init__(self, dl_path: Union[str, Path] = "data", num_workers: int = 0, batch_size: int = 8):
"""CatDogImageDataModule.
Args:
dl_path: root directory where to download the data
num_workers: number of CPU workers
batch_size: n... | CatDogImageDataModule |
python | huggingface__transformers | tests/models/yolos/test_modeling_yolos.py | {
"start": 1331,
"end": 6320
} | class ____:
def __init__(
self,
parent,
batch_size=13,
image_size=[30, 30],
patch_size=2,
num_channels=3,
is_training=True,
use_labels=True,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=3... | YolosModelTester |
python | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 61871,
"end": 65623
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.attention_type = config.attention_type
self.layer = nn.ModuleList(
[BigBirdLayer(config, seed=layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
se... | BigBirdEncoder |
python | run-llama__llama_index | llama-index-core/llama_index/core/prompts/base.py | {
"start": 11323,
"end": 13943
} | class ____(BasePromptTemplate): # type: ignore[no-redef]
default_template: SerializeAsAny[BasePromptTemplate]
conditionals: Optional[
Sequence[Tuple[Callable[[BaseLLM], bool], BasePromptTemplate]]
] = None
def __init__(
self,
default_template: BasePromptTemplate,
condit... | SelectorPromptTemplate |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/base.py | {
"start": 873,
"end": 8870
} | class ____(BaseDocumentTransformer, ABC):
"""Interface for splitting text into chunks."""
def __init__(
self,
chunk_size: int = 4000,
chunk_overlap: int = 200,
length_function: Callable[[str], int] = len,
keep_separator: bool | Literal["start", "end"] = False, # noqa: F... | TextSplitter |
python | keras-team__keras | keras/src/metrics/regression_metrics_test.py | {
"start": 3332,
"end": 4741
} | class ____(testing.TestCase):
def test_config(self):
mae_obj = metrics.MeanAbsoluteError(name="my_mae", dtype="int32")
self.assertEqual(mae_obj.name, "my_mae")
self.assertEqual(mae_obj._dtype, "int32")
# Check save and restore config
mae_obj2 = metrics.MeanAbsoluteError.from... | MeanAbsoluteErrorTest |
python | plotly__plotly.py | plotly/graph_objs/layout/xaxis/_rangeselector.py | {
"start": 235,
"end": 13093
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.xaxis"
_path_str = "layout.xaxis.rangeselector"
_valid_props = {
"activecolor",
"bgcolor",
"bordercolor",
"borderwidth",
"buttondefaults",
"buttons",
"font",
"visible",
"x... | Rangeselector |
python | openai__openai-python | src/openai/resources/vector_stores/files.py | {
"start": 38377,
"end": 39018
} | class ____:
def __init__(self, files: Files) -> None:
self._files = files
self.create = to_streamed_response_wrapper(
files.create,
)
self.retrieve = to_streamed_response_wrapper(
files.retrieve,
)
self.update = to_streamed_response_wrapper(
... | FilesWithStreamingResponse |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/triggers/message_bus.py | {
"start": 1431,
"end": 3496
} | class ____(BaseEventTrigger):
"""
Base trigger for Azure Service Bus message processing.
This trigger provides common functionality for listening to Azure Service Bus
queues and topics/subscriptions. It handles connection management and
async message processing.
:param poll_interval: Time inte... | BaseAzureServiceBusTrigger |
python | viewflow__viewflow | viewflow/forms/__init__.py | {
"start": 485,
"end": 753
} | class ____:
pass
__all__ = (
"Caption",
"Column",
"Layout",
"LayoutNode",
"Row",
"Span",
"FieldSet",
"FormLayout",
"FormSet",
"ModelForm",
"FormAjaxCompleteMixin",
"FormDependentSelectMixin",
)
| FormDependentSelectMixin |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-changes-to-make-binary-string-beautiful.py | {
"start": 38,
"end": 221
} | class ____(object):
def minChanges(self, s):
"""
:type s: str
:rtype: int
"""
return sum(s[i] != s[i+1] for i in xrange(0, len(s), 2))
| Solution |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/vcs/git.py | {
"start": 1495,
"end": 18177
} | class ____(VersionControl):
name = "git"
dirname = ".git"
repo_name = "clone"
schemes = (
"git+http",
"git+https",
"git+ssh",
"git+git",
"git+file",
)
# Prevent the user's environment variables from interfering with pip:
# https://github.com/pypa/pip/i... | Git |
python | sanic-org__sanic | sanic/worker/multiplexer.py | {
"start": 253,
"end": 5467
} | class ____:
"""Multiplexer for Sanic workers.
This is instantiated inside of worker porocesses only. It is used to
communicate with the monitor process.
Args:
monitor_publisher (Connection): The connection to the monitor.
worker_state (Dict[str, Any]): The state of the worker.
"""
... | WorkerMultiplexer |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/biases/boost_latest_releases_bias.py | {
"start": 454,
"end": 2808
} | class ____(Bias):
datetime_format = "%Y-%m-%dT%H:%M:%SZ"
def generate_rules(self, project: Project, base_sample_rate: float) -> list[PolymorphicRule]:
factor = apply_dynamic_factor(base_sample_rate, LATEST_RELEASES_BOOST_FACTOR)
boosted_releases = ProjectBoostedReleases(project.id).get_extende... | BoostLatestReleasesBias |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/autoVariance3.py | {
"start": 3804,
"end": 3961
} | class ____[T]:
x: T
# This should generate an error based on variance.
vinv4_1: ShouldBeInvariant4[float] = ShouldBeInvariant4[int](1)
| ShouldBeInvariant4 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault5.py | {
"start": 355,
"end": 560
} | class ____: ...
@overload
def func1(x: ClassA) -> ClassA: ...
@overload
def func1[T1 = str](x: ClassC | T1) -> T1: ...
def func1(x: Any) -> Any: ...
reveal_type(func1(ClassC()), expected_text="str")
| ClassC |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/actions/test_ticketing.py | {
"start": 176,
"end": 993
} | class ____(TestCase):
__test__ = False
provider: str
def setUp(self) -> None:
super().setUp()
self.integration, self.org_integration = self.create_provider_integration_for(
provider=self.provider,
organization=self.organization,
user=self.user,
... | BaseTicketingActionValidatorTest |
python | getsentry__sentry | tests/sentry/hybridcloud/test_tombstone.py | {
"start": 301,
"end": 1486
} | class ____(TransactionTestCase):
def test_writing_control_models(self) -> None:
with assume_test_silo_mode(SiloMode.REGION):
assert RegionTombstone.objects.count() == 0
user_id = self.user.id
self.organization
with outbox_runner(), assume_test_silo_mode(SiloMode.CONTROL... | TombstoneTest |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 1899,
"end": 2087
} | class ____(str, Enum):
"""
Bulk Action to be taken if the entity already exists or not.
"""
FAIL = "fail"
SKIP = "skip"
OVERWRITE = "overwrite"
| BulkActionOnExistence |
python | huggingface__transformers | src/transformers/cli/serve.py | {
"start": 9789,
"end": 11574
} | class ____:
"""
A class that holds a PreTrainedModel instance and its associated processor.
Automatically deletes the instances after a specified timeout.
"""
def __init__(
self,
model: "PreTrainedModel",
timeout_seconds: int,
processor: Union["ProcessorMixin", "PreT... | TimedModel |
python | pytransitions__transitions | transitions/extensions/states.py | {
"start": 382,
"end": 1012
} | class ____(State):
"""Allows states to be tagged.
Attributes:
tags (list): A list of tag strings. `State.is_<tag>` may be used
to check if <tag> is in the list.
"""
def __init__(self, *args, **kwargs):
"""
Args:
**kwargs: If kwargs contains `ta... | Tags |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/basic.py | {
"start": 20966,
"end": 21751
} | class ____(MetaflowCard):
type = "default_json"
def __init__(
self,
options=dict(only_repr=True),
components=[],
graph=None,
flow=None,
**kwargs
):
self._only_repr = True
self._graph = None if graph is None else transform_flow_graph(graph)
... | DefaultCardJSON |
python | PyCQA__pylint | pylint/pyreverse/inspector.py | {
"start": 10831,
"end": 11161
} | class ____(ABC):
@abstractmethod
def set_next(
self, handler: RelationshipHandlerInterface
) -> RelationshipHandlerInterface:
pass
@abstractmethod
def handle(
self, node: nodes.AssignAttr | nodes.AssignName, parent: nodes.ClassDef
) -> None:
pass
| RelationshipHandlerInterface |
python | Textualize__textual | tests/tree/test_tree_clearing.py | {
"start": 370,
"end": 3558
} | class ____(App[None]):
"""Tree clearing test app."""
def compose(self) -> ComposeResult:
yield VerseTree("White Sun", data=VerseStar())
def on_mount(self) -> None:
tree = self.query_one(VerseTree)
node = tree.root.add("Londinium", VersePlanet())
node.add_leaf("Balkerne", Ve... | TreeClearApp |
python | pytorch__pytorch | test/distributed/elastic/agent/server/test/api_test.py | {
"start": 1240,
"end": 1573
} | class ____(unittest.TestCase):
def test_is_running(self):
for state in WorkerState:
if state == WorkerState.HEALTHY or state == WorkerState.UNHEALTHY:
self.assertTrue(WorkerState.is_running(state))
else:
self.assertFalse(WorkerState.is_running(state))
... | WorkerStateTest |
python | urllib3__urllib3 | test/test_proxymanager.py | {
"start": 295,
"end": 3657
} | class ____:
@pytest.mark.parametrize("proxy_scheme", ["http", "https"])
def test_proxy_headers(self, proxy_scheme: str) -> None:
url = "http://pypi.org/project/urllib3/"
proxy_url = f"{proxy_scheme}://something:1234"
with ProxyManager(proxy_url) as p:
# Verify default headers... | TestProxyManager |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 61148,
"end": 65877
} | class ____(ASTBaseBase):
def __init__(
self,
objectType: str,
directiveType: str | None,
declaration: DeclarationType | ASTFunctionParameter,
semicolon: bool = False,
) -> None:
self.objectType = objectType
self.directiveType = directiveType
self.d... | ASTDeclaration |
python | kubernetes-client__python | kubernetes/client/models/core_v1_endpoint_port.py | {
"start": 383,
"end": 7954
} | 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... | CoreV1EndpointPort |
python | python__mypy | mypy/plugin.py | {
"start": 7011,
"end": 8476
} | class ____:
"""Interface for accessing semantic analyzer functionality in plugins.
Methods docstrings contain only basic info. Look for corresponding implementation
docstrings in typeanal.py for more details.
"""
# An options object. Note: these are the cloned options for the current file.
# T... | TypeAnalyzerPluginInterface |
python | SmileyChris__easy-thumbnails | easy_thumbnails/tests/test_models.py | {
"start": 174,
"end": 2124
} | class ____(test.BaseTest):
"""Test for FileManager"""
def setUp(self):
super().setUp()
self.storage = test.TemporaryStorage()
self.storage_hash = utils.get_storage_hash(self.storage)
self.source = Source.objects.create(
name='Test source',
storage_hash=s... | FileManagerTest |
python | google__jax | jax/_src/sharding_impls.py | {
"start": 6379,
"end": 12330
} | class ____(jsharding.Sharding):
"""Describes a sharding used by :func:`jax.pmap`."""
devices: np.ndarray
sharding_spec: sharding_specs.ShardingSpec
_internal_device_list: xc.DeviceList
@use_cpp_method()
def __init__(self, devices: Sequence[Device] | np.ndarray,
sharding_spec: sharding_specs.... | PmapSharding |
python | mlflow__mlflow | mlflow/exceptions.py | {
"start": 6279,
"end": 6671
} | class ____(MlflowException):
"""
Exception thrown from tracing logic
Tracing logic should not block the main execution flow in general, hence this exception
is used to distinguish tracing related errors and handle them properly.
"""
def __init__(self, message, error_code=INTERNAL_ERROR):
... | MlflowTracingException |
python | django__django | tests/admin_changelist/admin.py | {
"start": 4046,
"end": 4235
} | class ____(admin.ModelAdmin):
list_display = ["name", "file", "url"]
list_display_links = ["file", "url"]
site.register(Genre, ListDisplayLinksGenreAdmin)
| ListDisplayLinksGenreAdmin |
python | huggingface__transformers | src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py | {
"start": 48854,
"end": 51792
} | class ____(XLMRobertaXLPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
self.post_i... | XLMRobertaXLForQuestionAnswering |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_type_lookup.py | {
"start": 12048,
"end": 12189
} | class ____(abc.ABC):
def __init__(self, x): # noqa: B027
pass
@abc.abstractmethod
def qux(self):
pass
| AbstractFoo |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 64129,
"end": 65643
} | class ____:
"""A CSEVariable is just a name for an expression but it is useful to be able to annotate them on a backend dependent basis.
To do so, the backends can simply overload `Kernel.create_cse_var`
The "CSEVariable.update_on_args" method gives you a hook for annotations
See example of TritonCSEVar... | CSEVariable |
python | huggingface__transformers | src/transformers/models/doge/modular_doge.py | {
"start": 1985,
"end": 11487
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DogeModel`]. It is used to instantiate an Doge
model according to the specified arguments, defining the model architecture like [SmallDoge/Doge-320M](https://huggingface.co/SmallDoge/Doge-320M).
Configu... | DogeConfig |
python | django-guardian__django-guardian | guardian/testapp/models.py | {
"start": 3002,
"end": 3243
} | class ____(models.Model):
"""
Model for testing whether get_objects_for_user will work when the objects to
be returned have varchar primary keys.
"""
char_pk = models.CharField(primary_key=True, max_length=128)
| CharPKModel |
python | ZoranPandovski__al-go-rithms | data_structures/Graphs/graph/Python/chromatic_number.py | {
"start": 87,
"end": 3225
} | class ____:
"""
Implementation of a graph with Adjacency Matrix
"""
def __init__(self,size,directed = False):
self.size = size
self.matrix = [[0 for i in range(self.size)] for j in range(self.size)]
self.directed = directed
self.Time = 0
self.color = {i:"white" fo... | Graph |
python | python-pillow__Pillow | setup.py | {
"start": 3154,
"end": 8117
} | class ____(Exception):
pass
PLATFORM_MINGW = os.name == "nt" and "GCC" in sys.version
def _dbg(s: str, tp: str | tuple[str, ...] | None = None) -> None:
if DEBUG:
if tp:
print(s % tp)
return
print(s)
def _find_library_dirs_ldconfig() -> list[str]:
# Based on cty... | RequiredDependencyException |
python | scipy__scipy | scipy/differentiate/tests/test_differentiate.py | {
"start": 25257,
"end": 27724
} | class ____(JacobianHessianTest):
jh_func = hessian
@pytest.mark.parametrize('shape', [(), (4,), (2, 4)])
def test_example(self, shape, xp):
rng = np.random.default_rng(458912319542)
m = 3
x = xp.asarray(rng.random((m,) + shape), dtype=xp.float64)
res = hessian(optimize.rosen... | TestHessian |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/collective_ops_test.py | {
"start": 1726,
"end": 2388
} | class ____(object):
@staticmethod
def all_reduce(t, group_size, group_key, instance_key, *args, **kwargs):
kwargs.pop('ordering_token', None)
return _collective_ops.all_reduce(t, group_size, group_key, instance_key,
*args, **kwargs)
@staticmethod
def all_gather(t,... | CollectiveOpsV1 |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 339891,
"end": 341026
} | class ____(Response):
"""
Response of tasks.make_private endpoint.
:param updated: Number of tasks updated
:type updated: int
"""
_service = "tasks"
_action = "make_private"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"updated": {
... | MakePrivateResponse |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/error.py | {
"start": 6625,
"end": 7135
} | class ____(YAMLWarning):
text = """
The default 'Loader' for 'load(stream)' without further arguments can be unsafe.
Use 'load(stream, Loader=spack.vendor.ruamel.yaml.Loader)' explicitly if that is OK.
Alternatively include the following in your code:
import warnings
warnings.simplefilter('ignore', spack.vendo... | UnsafeLoaderWarning |
python | allegroai__clearml | clearml/backend_api/services/v2_23/auth.py | {
"start": 21271,
"end": 22785
} | class ____(Response):
"""
Response of auth.revoke_credentials endpoint.
:param revoked: Number of credentials revoked
:type revoked: int
"""
_service = "auth"
_action = "revoke_credentials"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
... | RevokeCredentialsResponse |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI012.py | {
"start": 1041,
"end": 1144
} | class ____:
value: int = 0
def __init__():
pass
def function():
pass
pass
| WithInit |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-make-arrays-identical.py | {
"start": 67,
"end": 464
} | class ____(object):
def minCost(self, arr, brr, k):
"""
:type arr: List[int]
:type brr: List[int]
:type k: int
:rtype: int
"""
def cost():
return sum(abs(x-y) for x, y in itertools.izip(arr, brr))
result = cost()
arr.sort()
... | Solution |
python | facebookresearch__faiss | benchs/bench_fw/utils.py | {
"start": 3389,
"end": 3741
} | class ____:
def __init__(self, values):
self.values = values
def __le__(self, other):
return all(
v1 <= v2 for v1, v2 in zip(self.values, other.values, strict=True)
)
def __lt__(self, other):
return all(
v1 < v2 for v1, v2 in zip(self.values, other.v... | Cost |
python | PyCQA__pydocstyle | src/tests/test_cases/sections.py | {
"start": 12420,
"end": 12885
} | class ____: # noqa: D203
"""Test class."""
@expect("D417: Missing argument descriptions in the docstring "
"(argument(s) y are missing descriptions in "
"'test_incorrect_indent' docstring)", arg_count=3)
def test_incorrect_indent(self, x=1, y=2): # noqa: D207, D213, D407
"... | TestIncorrectIndent |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 170390,
"end": 172176
} | class ____(TestCase):
def test_r_less_than_n(self):
iterable = 'abcdefg'
r = 4
first_index = {}
for index, element in enumerate(combinations(iterable, r)):
actual = mi.combination_index(element, iterable)
expected = first_index.setdefault(element, index)
... | CombinationIndexTests |
python | sympy__sympy | sympy/matrices/expressions/special.py | {
"start": 5175,
"end": 8021
} | class ____(MatrixExpr):
"""
Matrix whose all entries are ones.
Also called "matrix of ones" or "all-ones matrix".
https://en.wikipedia.org/wiki/Matrix_of_ones
Examples
========
>>> from sympy.matrices.expressions import OneMatrix
>>> O = OneMatrix(3, 4)
>>> O.shape
(3, 4)
... | OneMatrix |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 62405,
"end": 70960
} | class ____(nn.Module):
def __init__(self, config: OneFormerConfig, feature_channels):
super().__init__()
self.config = config
# positional encoding
self.position_embedding = OneFormerSinePositionEmbedding(num_pos_feats=config.conv_dim // 2, normalize=True)
self.num_feature... | OneFormerPixelDecoder |
python | huggingface__transformers | tests/models/lightglue/test_modeling_lightglue.py | {
"start": 11984,
"end": 27196
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return AutoImageProcessor.from_pretrained("ETH-CVG/lightglue_superpoint") if is_vision_available() else None
@slow
def test_inference(self):
model = LightGlueForKeypointMatching.from_pretrained(
... | LightGlueModelIntegrationTest |
python | langchain-ai__langchain | libs/core/langchain_core/messages/function.py | {
"start": 874,
"end": 2094
} | class ____(FunctionMessage, BaseMessageChunk):
"""Function Message chunk."""
# Ignoring mypy re-assignment here since we're overriding the value
# to make sure that the chunk variant can be discriminated from the
# non-chunk variant.
type: Literal["FunctionMessageChunk"] = "FunctionMessageChunk" #... | FunctionMessageChunk |
python | huggingface__transformers | src/transformers/models/idefics/processing_idefics.py | {
"start": 4449,
"end": 17959
} | class ____(ProcessorMixin):
r"""
Constructs a IDEFICS processor which wraps a LLama tokenizer and IDEFICS image processor into a single processor.
[`IdeficsProcessor`] offers all the functionalities of [`IdeficsImageProcessor`] and [`LlamaTokenizerFast`]. See
the docstring of [`~IdeficsProcessor.__call... | IdeficsProcessor |
python | apache__airflow | providers/google/tests/unit/google/cloud/transfers/test_cassandra_to_gcs.py | {
"start": 1148,
"end": 5495
} | class ____:
@pytest.mark.db_test
def test_execute(self):
test_bucket = TEST_BUCKET
schema = SCHEMA
filename = FILENAME
gzip = True
query_timeout = 20
try:
from airflow.providers.google.cloud.transfers.cassandra_to_gcs import CassandraToGCSOperator
... | TestCassandraToGCS |
python | getsentry__sentry-python | sentry_sdk/consts.py | {
"start": 24547,
"end": 27523
} | class ____:
ANTHROPIC_MESSAGES_CREATE = "ai.messages.create.anthropic"
CACHE_GET = "cache.get"
CACHE_PUT = "cache.put"
COHERE_CHAT_COMPLETIONS_CREATE = "ai.chat_completions.create.cohere"
COHERE_EMBEDDINGS_CREATE = "ai.embeddings.create.cohere"
DB = "db"
DB_REDIS = "db.redis"
EVENT_DJANG... | OP |
python | PrefectHQ__prefect | tests/server/models/deprecated/test_work_queues.py | {
"start": 17571,
"end": 28145
} | class ____:
async def setup_work_queues_and_deployment(
self, session, flow, flow_function, tags=[]
):
"""
Create combinations of work queues, and a deployment to make sure that query is working correctly.
Returns the ID of the deployment that was created and a random ID that wa... | TestCheckWorkQueuesForDeployment |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 69636,
"end": 70692
} | class ____(Response):
"""
Response of events.delete_for_model endpoint.
:param deleted: Number of deleted events
:type deleted: bool
"""
_service = "events"
_action = "delete_for_model"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"de... | DeleteForModelResponse |
python | huggingface__transformers | src/transformers/cache_utils.py | {
"start": 62500,
"end": 62919
} | class ____(StaticCache):
def __init__(self, config: PreTrainedConfig, max_cache_len: int, *args, **kwargs):
logger.warning_once(
"`HybridChunkedCache` is deprecated and will be removed in version v4.59 "
"Use `StaticCache(...)` instead which will correctly infer the type of each laye... | HybridChunkedCache |
python | huggingface__transformers | src/transformers/models/deepseek_vl_hybrid/modular_deepseek_vl_hybrid.py | {
"start": 5927,
"end": 5985
} | class ____(SamLayerNorm):
pass
| DeepseekVLHybridLayerNorm |
python | scikit-learn__scikit-learn | sklearn/utils/_available_if.py | {
"start": 155,
"end": 2945
} | class ____:
"""Implements a conditional property using the descriptor protocol.
Using this class to create a decorator will raise an ``AttributeError``
if check(self) returns a falsey value. Note that if check raises an error
this will also result in hasattr returning false.
See https://docs.pytho... | _AvailableIfDescriptor |
python | realpython__materials | build-a-blog-from-scratch-django/django-blog/blog/apps.py | {
"start": 36,
"end": 140
} | class ____(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "blog"
| BlogConfig |
python | python__mypy | mypy/test/testsubtypes.py | {
"start": 316,
"end": 12426
} | class ____(Suite):
def setUp(self) -> None:
self.fx = TypeFixture(INVARIANT)
self.fx_contra = TypeFixture(CONTRAVARIANT)
self.fx_co = TypeFixture(COVARIANT)
def test_trivial_cases(self) -> None:
for simple in self.fx_co.a, self.fx_co.o, self.fx_co.b:
self.assert_subt... | SubtypingSuite |
python | doocs__leetcode | solution/2600-2699/2614.Prime In Diagonal/Solution.py | {
"start": 0,
"end": 487
} | class ____:
def diagonalPrime(self, nums: List[List[int]]) -> int:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(sqrt(x)) + 1))
n = len(nums)
ans = 0
for i, row in enumerate(nums):
if i... | Solution |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 148565,
"end": 149638
} | class ____(multi_rv_frozen):
__class_getitem__ = None
def __init__(self, dim=None, seed=None):
"""Create a frozen O(N) distribution.
Parameters
----------
dim : scalar
Dimension of matrices
seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomSta... | ortho_group_frozen |
python | pytorch__pytorch | test/distributed/optim/test_zero_redundancy_optimizer.py | {
"start": 1823,
"end": 11298
} | class ____(TestZeroRedundancyOptimizer):
def test_state_dict(self):
"""Check that ZeroRedundancyOptimizer exposes the expected state dict
interface, irrespective of the sharding."""
self.create_pg(self.device)
LR1 = 0.1
LR2 = 0.01
MOMENTUM = 0.9
RECIPIENT_RANK... | TestZeroRedundancyOptimizerSingleRank |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.