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 | pytorch__pytorch | test/dynamo/cpython/3_13/seq_tests.py | {
"start": 2528,
"end": 2810
} | class ____:
'Missing __getitem__ and __iter__'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __next__(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
| IterNextOnly |
python | sympy__sympy | sympy/matrices/common.py | {
"start": 6493,
"end": 24287
} | class ____(MatrixRequired):
"""Provides basic matrix shaping and extracting of submatrices"""
def _eval_col_del(self, col):
def entry(i, j):
return self[i, j] if j < col else self[i, j + 1]
return self._new(self.rows, self.cols - 1, entry)
def _eval_col_insert(self, pos, other)... | MatrixShaping |
python | chroma-core__chroma | chromadb/telemetry/opentelemetry/__init__.py | {
"start": 1404,
"end": 6021
} | class ____(Component):
def __init__(self, system: System):
super().__init__(system)
otel_init(
system.settings.chroma_otel_service_name,
system.settings.chroma_otel_collection_endpoint,
system.settings.chroma_otel_collection_headers,
OpenTelemetryGranu... | OpenTelemetryClient |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/rds.py | {
"start": 4019,
"end": 5788
} | class ____(RdsBaseSensor):
"""
Waits for RDS export task with a specific status.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:RdsExportTaskExistenceSensor`
:param export_task_identifier: A unique identifier for the snapshot e... | RdsExportTaskExistenceSensor |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/tests/unit_tests/test_models.py | {
"start": 237,
"end": 3340
} | class ____:
def test_fail_when_requires_metadata_and_metata_is_missing(self, mocker):
# Arrange
connector = mocker.MagicMock(metadata={}, is_released=False)
# Act
results = []
for check in ENABLED_CHECKS:
if check.requires_metadata:
results.append... | TestCheck |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 51878,
"end": 53109
} | class ____(BaseModel):
"""
Task processor config. You can use it to configure the task processor for your Serve application.
"""
queue_name: str = Field(
..., description="The name of the queue to use for task processing."
)
adapter: Union[str, Callable] = Field(
default="ray.se... | TaskProcessorConfig |
python | keras-team__keras | keras/src/ops/operation_test.py | {
"start": 1210,
"end": 1553
} | class ____(operation.Operation):
def __init__(self, alpha, beta=1.0):
super().__init__()
self.alpha = alpha
self.beta = beta
def call(self, x):
return self.alpha * x + self.beta
def compute_output_spec(self, x):
return keras_tensor.KerasTensor(x.shape, x.dtype)
| OpWithCustomConstructorNoName |
python | kamyu104__LeetCode-Solutions | Python/remove-duplicates-from-sorted-list-ii.py | {
"start": 280,
"end": 826
} | class ____(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
pre, cur = dummy, head
while cur:
if cur.next and cur.next.val == cur.val:
val = cur.val
while c... | Solution |
python | redis__redis-py | redis/commands/bf/__init__.py | {
"start": 3612,
"end": 4600
} | class ____(TOPKCommands, AbstractBloom):
def __init__(self, client, **kwargs):
"""Create a new RedisBloom client."""
# Set the module commands' callbacks
_MODULE_CALLBACKS = {
TOPK_RESERVE: bool_ok,
# TOPK_QUERY: spaceHolder,
# TOPK_COUNT: spaceHolder,
... | TOPKBloom |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 30653,
"end": 30873
} | class ____(BaseModel):
dag_id: str
logical_dates: list[AwareDatetime] | None = None
run_ids: list[str] | None = None
states: list[str] | None = None
type: Literal["GetDRCount"] = "GetDRCount"
| GetDRCount |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Filters.py | {
"start": 4556,
"end": 5024
} | class ____(CtrlNode):
"""Filters data by taking the median of a sliding window"""
nodeName = 'MedianFilter'
uiTemplate = [
('n', 'intSpin', {'min': 1, 'max': 1000000})
]
def processData(self, data):
try:
import scipy.ndimage
except ImportError:
ra... | Median |
python | django__django | tests/inspectdb/models.py | {
"start": 3053,
"end": 3436
} | class ____(models.Model):
json_field = models.JSONField()
null_json_field = models.JSONField(blank=True, null=True)
class Meta:
required_db_features = {
"can_introspect_json_field",
"supports_json_field",
}
test_collation = SimpleLazyObject(
lambda: connection.... | JSONFieldColumnType |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/workflows.py | {
"start": 17403,
"end": 20324
} | class ____(GoogleCloudBaseOperator):
"""
Creates a new execution using the latest revision of the given workflow.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:WorkflowsCreateExecutionOperator`
:param execution: Required. ... | WorkflowsCreateExecutionOperator |
python | django__django | django/forms/widgets.py | {
"start": 12537,
"end": 12944
} | class ____(Input):
input_type = "password"
template_name = "django/forms/widgets/password.html"
def __init__(self, attrs=None, render_value=False):
super().__init__(attrs)
self.render_value = render_value
def get_context(self, name, value, attrs):
if not self.render_value:
... | PasswordInput |
python | allegroai__clearml | clearml/backend_api/api_proxy.py | {
"start": 164,
"end": 2041
} | class ____(object):
_main_services_module = "clearml.backend_api.services"
_available_versions = None
def __init__(self, module: str) -> None:
self.__wrapped_name__ = module
self.__wrapped_version__ = Session.api_version
def __getattr__(self, attr: str) -> Any:
if attr in ["__w... | ApiServiceProxy |
python | Netflix__metaflow | metaflow/_vendor/yaml/__init__.py | {
"start": 865,
"end": 11776
} | class ____(RuntimeWarning):
pass
def load_warning(method):
if _warnings_enabled['YAMLLoadWarning'] is False:
return
import warnings
message = (
"calling yaml.%s() without Loader=... is deprecated, as the "
"default Loader is unsafe. Please read "
"https://msg.pyyaml.or... | YAMLLoadWarning |
python | PyCQA__pylint | tests/functional/m/misplaced_bare_raise.py | {
"start": 1044,
"end": 1433
} | class ____:
try:
pass
except Exception:
raise
raise # [misplaced-bare-raise]
# This works in Python 2, but the intent is nevertheless
# unclear. It will also not work on Python 3, so it's best
# not to rely on it.
exc = None
try:
1/0
except ZeroDivisionError as exc:
pass
if exc:
... | A |
python | vyperlang__vyper | tests/functional/builtins/codegen/test_convert.py | {
"start": 5828,
"end": 20857
} | class ____(enum.Enum):
Left = enum.auto()
Right = enum.auto()
def _padding_direction(typ):
if isinstance(typ, (BytesM_T, StringT, BytesT)):
return _PadDirection.Right
return _PadDirection.Left
# TODO this could be a function in vyper.builtins._convert
# which implements literal folding and a... | _PadDirection |
python | google__jax | tests/memories_test.py | {
"start": 28448,
"end": 62038
} | class ____(jtu.BufferDonationTestCase):
def setUp(self):
if not jtu.test_device_matches(["tpu", "gpu"]):
self.skipTest("Memories do not work on CPU backends yet.")
super().setUp()
def _check_mem_kind(self, executable_kind, out_sharding, expected_kind):
out_kind = out_sharding.memory_kind
sel... | ComputeOffload |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/metrics/data_profiler_metrics/data_profiler_profile_report.py | {
"start": 394,
"end": 1521
} | class ____(DataProfilerProfileMetricProvider):
metric_name = "data_profiler.profile_report"
value_keys = ("profile_path",)
@metric_value(engine=PandasExecutionEngine)
def _pandas(
cls,
execution_engine,
metric_domain_kwargs,
metric_value_kwargs,
metrics,
... | DataProfilerProfileReport |
python | cython__cython | Cython/Coverage.py | {
"start": 15605,
"end": 16907
} | class ____(FileTracer):
"""
Find the Python/Cython source file for a Cython module.
"""
def __init__(self, module_file, py_file, c_file, c_files_map, file_path_map):
super().__init__()
self.module_file = module_file
self.py_file = py_file
self.c_file = c_file
self... | CythonModuleTracer |
python | pyinstaller__pyinstaller | PyInstaller/utils/hooks/gi.py | {
"start": 950,
"end": 19112
} | class ____:
def __init__(self, module, version, hook_api=None):
self.name = module
self.version = version
self.available = False
self.sharedlibs = []
self.typelib = None
self.dependencies = []
# If hook API is available, use it to override the version from ho... | GiModuleInfo |
python | huggingface__transformers | src/transformers/models/aria/modeling_aria.py | {
"start": 34696,
"end": 36276
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the lan... | AriaCausalLMOutputWithPast |
python | pytest-dev__pytest | testing/test_assertrewrite.py | {
"start": 70563,
"end": 72560
} | class ____:
@pytest.mark.parametrize(
"prefix, source, expected",
[
("c:/tmp/pycs", "d:/projects/src/foo.py", "c:/tmp/pycs/projects/src"),
(None, "d:/projects/src/foo.py", "d:/projects/src/__pycache__"),
("/tmp/pycs", "/home/projects/src/foo.py", "/tmp/pycs/home/p... | TestPyCacheDir |
python | pandas-dev__pandas | pandas/tests/tseries/offsets/test_halfyear.py | {
"start": 981,
"end": 7346
} | class ____:
def test_repr(self):
expected = "<HalfYearBegin: startingMonth=1>"
assert repr(HalfYearBegin()) == expected
expected = "<HalfYearBegin: startingMonth=3>"
assert repr(HalfYearBegin(startingMonth=3)) == expected
expected = "<HalfYearBegin: startingMonth=1>"
... | TestHalfYearBegin |
python | dagster-io__dagster | python_modules/libraries/dagster-tableau/dagster_tableau/translator.py | {
"start": 1727,
"end": 1961
} | class ____(Enum):
"""Enum representing each object in Tableau's ontology."""
WORKBOOK = "workbook"
SHEET = "sheet"
DASHBOARD = "dashboard"
DATA_SOURCE = "data_source"
@whitelist_for_serdes
@record
| TableauContentType |
python | getsentry__sentry-python | sentry_sdk/integrations/dramatiq.py | {
"start": 2716,
"end": 6564
} | class ____(Middleware): # type: ignore[misc]
"""
A Dramatiq middleware that automatically captures and sends
exceptions to Sentry.
This is automatically added to every instantiated broker via the
DramatiqIntegration.
"""
SENTRY_HEADERS_NAME = "_sentry_headers"
def before_enqueue(self... | SentryMiddleware |
python | huggingface__transformers | tests/models/bridgetower/test_modeling_bridgetower.py | {
"start": 3435,
"end": 5251
} | class ____:
def __init__(
self,
parent,
hidden_size=64,
initializer_factor=1,
layer_norm_eps=1e-05,
num_hidden_layers=2,
init_layernorm_from_vision_encoder=False,
output_hidden_states=False,
image_size=64,
):
self.parent = parent
... | BridgeTowerImageModelTester |
python | mahmoud__boltons | boltons/socketutils.py | {
"start": 28230,
"end": 28346
} | class ____(Error):
"Base class for all of socketutils' Netstring exception types."
pass
| NetstringProtocolError |
python | fluentpython__example-code-2e | 10-dp-1class-func/untyped/strategy_param2.py | {
"start": 1854,
"end": 2068
} | class ____:
"""compute discount for order"""
def __init__(self, percent):
self.percent = percent
def __call__(self, order):
raise NotImplementedError("Subclass responsibility")
| Promotion |
python | astropy__astropy | astropy/io/votable/tree.py | {
"start": 12888,
"end": 14506
} | class ____:
"""
A base class for all classes that represent XML elements in the
VOTABLE file.
"""
_element_name = ""
_attr_list = []
def _add_unknown_tag(self, iterator, tag, data, config, pos):
warn_or_raise(W10, W10, tag, config, pos)
def _ignore_add(self, iterator, tag, dat... | Element |
python | sympy__sympy | sympy/core/tests/test_constructor_postprocessor.py | {
"start": 1015,
"end": 2441
} | class ____(SymbolRemovesOtherSymbols):
pass
def test_constructor_postprocessors1():
x = SymbolInMulOnce("x")
y = SymbolInMulOnce("y")
assert isinstance(3*x, Mul)
assert (3*x).args == (3, x)
assert x*x == x
assert 3*x*x == 3*x
assert 2*x*x + x == 3*x
assert x**3*y*y == x*y
asser... | SubclassSymbolRemovesOtherSymbols |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py | {
"start": 23528,
"end": 24137
} | class ____(
LegacyNamedTupleMixin,
MetadataValue["PythonArtifactMetadataValue"],
):
"""Container class for python artifact metadata entry data.
Args:
module (str): The module where the python artifact can be found
name (str): The name of the python artifact
"""
module: PublicAt... | PythonArtifactMetadataValue |
python | getsentry__sentry | src/sentry/plugins/base/v2.py | {
"start": 548,
"end": 680
} | class ____(Protocol):
def __call__(self, data: MutableMapping[str, Any]) -> MutableMapping[str, Any] | None: ...
| EventPreprocessor |
python | scrapy__scrapy | scrapy/downloadermiddlewares/httpproxy.py | {
"start": 644,
"end": 3966
} | class ____:
def __init__(self, auth_encoding: str | None = "latin-1"):
self.auth_encoding: str | None = auth_encoding
self.proxies: dict[str, tuple[bytes | None, str]] = {}
for type_, url in getproxies().items():
try:
self.proxies[type_] = self._get_proxy(url, typ... | HttpProxyMiddleware |
python | apache__airflow | providers/opsgenie/src/airflow/providers/opsgenie/notifications/opsgenie.py | {
"start": 1229,
"end": 2673
} | class ____(BaseNotifier):
"""
This notifier allows you to post alerts to Opsgenie.
Accepts a connection that has an Opsgenie API key as the connection's password.
This notifier sets the domain to conn_id.host, and if not set will default
to ``https://api.opsgenie.com``.
Each Opsgenie API key c... | OpsgenieNotifier |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py | {
"start": 658,
"end": 785
} | class ____:
def __post_init__(self, bar: int = 11, baz: Something[Whatever | None] = 11) -> None: ...
# RUF033
@dataclass
| Foo |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_compute.py | {
"start": 25848,
"end": 38615
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
new=mock_base_gcp_hook_default_project_id,
):
self.gce_hook = ComputeEngineHook(gcp_conn_id="test")
@mock.patch(
"airflow... | TestGcpComputeHookDefaultProjectId |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 19822,
"end": 20227
} | class ____(Literal):
"""Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
:class:`Pair` nodes.
"""
fields = ("items",)
items: t.List["Pair"]
def as_const(
self, eval_ctx: t.Optional[EvalContext] = None
) -> t.Dict[t.Any, t.Any]:
eval_ctx = get_eval_con... | Dict |
python | bokeh__bokeh | src/bokeh/models/ui/menus.py | {
"start": 4396,
"end": 5521
} | class ____(UIElement):
""" An implicitly positioned panel containing a collection of items.
These items can include commands, checked items, dividers, etc.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kw... | Menu |
python | great-expectations__great_expectations | tests/integration/metrics/column/test_distinct_values_count.py | {
"start": 508,
"end": 990
} | class ____:
@parameterize_batch_for_data_sources(
data_source_configs=ALL_DATA_SOURCES,
data=DATA_FRAME,
)
def test_distinct_values_count(self, batch_for_datasource: Batch) -> None:
metric = ColumnDistinctValuesCount(column=COLUMN_NAME)
metric_result = batch_for_datasource.co... | TestColumnDistinctValuesCount |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/kinesis.py | {
"start": 1108,
"end": 2126
} | class ____(_FirehoseHook):
"""
Interact with Amazon Kinesis Firehose.
Provide thick wrapper around :external+boto3:py:class:`boto3.client("firehose") <Firehose.Client>`.
:param delivery_stream: Name of the delivery stream
Additional arguments (such as ``aws_conn_id``) may be specified and
are... | FirehoseHook |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/sentry_app_requests.py | {
"start": 1486,
"end": 4230
} | class ____(RegionSentryAppBaseEndpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
permission_classes = (SentryAppStatsPermission,)
def get(self, request: Request, sentry_app) -> Response:
"""
:qparam string eventType: Optionally spe... | SentryAppRequestsEndpoint |
python | sphinx-doc__sphinx | sphinx/util/logging.py | {
"start": 11073,
"end": 11345
} | class ____:
def __init__(self) -> None:
self.logs: list[logging.LogRecord] = []
@contextmanager
def collect(self) -> Iterator[None]:
with pending_logging() as memhandler:
yield
self.logs = memhandler.clear()
| LogCollector |
python | realpython__materials | python-314/linked_list.py | {
"start": 126,
"end": 185
} | class ____:
value: Any
next: Optional[Node] = None
| Node |
python | getsentry__sentry | src/sentry/auth/password_validation.py | {
"start": 3762,
"end": 5209
} | class ____:
"""
Validate whether a password has previously appeared in a data breach.
"""
def __init__(self, threshold: int = 1, timeout: float = 0.200) -> None:
self.threshold = threshold
self.timeout = timeout
def validate(self, password: str, user: User | None = None) -> None:
... | PwnedPasswordsValidator |
python | hynek__structlog | src/structlog/threadlocal.py | {
"start": 4209,
"end": 9212
} | class ____:
"""
Wrap a dict-like class and keep the state *global* but *thread-local*.
Attempts to re-initialize only updates the wrapped dictionary.
Useful for short-lived threaded applications like requests in web app.
Use :func:`wrap` to instantiate and use
:func:`structlog.BoundLogger.new... | _ThreadLocalDictWrapper |
python | pyca__cryptography | tests/hazmat/asn1/test_serialization.py | {
"start": 2366,
"end": 2753
} | class ____:
def test_bytes(self) -> None:
assert_roundtrips(
[
(b"", b"\x04\x00"),
(b"hello", b"\x04\x05hello"),
(b"\x01\x02\x03", b"\x04\x03\x01\x02\x03"),
(
b"\x00\xff\x80\x7f",
b"\x04\x04\x... | TestBytes |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/workflows.py | {
"start": 23105,
"end": 26429
} | class ____(GoogleCloudBaseOperator):
"""
Returns a list of executions which belong to the workflow with the given name.
The method returns executions of all workflow revisions. Returned
executions are ordered by their start time (newest first).
.. seealso::
For more information on how to u... | WorkflowsListExecutionsOperator |
python | spyder-ide__spyder | spyder/widgets/onecolumntree.py | {
"start": 949,
"end": 10491
} | class ____(QTreeWidget, SpyderWidgetMixin):
"""
One-column tree widget with context menu.
"""
def __init__(self, parent):
if not PYSIDE2:
super().__init__(parent, class_parent=parent)
else:
QTreeWidget.__init__(self, parent)
SpyderWidgetMixin.__init__... | OneColumnTree |
python | astropy__astropy | astropy/convolution/utils.py | {
"start": 433,
"end": 12151
} | class ____(KernelError):
"""Called when doing invalid arithmetic with a kernel."""
def has_even_axis(array):
if isinstance(array, (list, tuple)):
return not len(array) % 2
return any(not axes_size % 2 for axes_size in array.shape)
def add_kernel_arrays_1D(array_1, array_2):
"""
Add two 1... | KernelArithmeticError |
python | google__jax | jax/_src/lax/linalg.py | {
"start": 17268,
"end": 107125
} | class ____(enum.Enum):
"""Enum for SVD algorithm."""
DEFAULT = "default"
QR = "QR"
JACOBI = "Jacobi"
POLAR = "polar"
@overload
def svd(
x: ArrayLike,
*,
full_matrices: bool = True,
compute_uv: Literal[True],
subset_by_index: tuple[int, int] | None = None,
algorithm: SvdAlgorithm | No... | SvdAlgorithm |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/pythonic_config/resource.py | {
"start": 27379,
"end": 30324
} | class ____(
MakeConfigCacheable,
Generic[TResValue],
):
data: dict[str, Any]
resource_cls: type[Any]
def __init__(
self,
resource_cls: type[ConfigurableResourceFactory[TResValue]],
data: dict[str, Any],
):
resource_pointers, _data_without_resources = separate_res... | PartialResource |
python | scipy__scipy | benchmarks/benchmarks/interpolate.py | {
"start": 8483,
"end": 9860
} | class ____(Benchmark):
"""
Benchmark RegularGridInterpolator with method="linear".
"""
param_names = ['ndim', 'max_coord_size', 'n_samples', 'flipped']
params = [
[2, 3, 4],
[10, 40, 200],
[10, 100, 1000, 10000],
[1, -1]
]
def setup(self, ndim, max_coord_size... | RegularGridInterpolator |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dlp.py | {
"start": 80186,
"end": 83631
} | class ____(GoogleCloudBaseOperator):
"""
Returns a list of the sensitive information types that the DLP API supports.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDLPListInfoTypesOperator`
:param language_code: (Opti... | CloudDLPListInfoTypesOperator |
python | langchain-ai__langchain | libs/core/langchain_core/messages/content.py | {
"start": 4933,
"end": 6778
} | class ____(TypedDict):
"""Annotation for citing data from a document.
!!! note
`start`/`end` indices refer to the **response text**,
not the source text. This means that the indices are relative to the model's
response, not the original document (as specified in the `url`).
!!! not... | Citation |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/metadata.py | {
"start": 2319,
"end": 2528
} | class ____(graphene.ObjectType):
md_str = graphene.NonNull(graphene.String)
class Meta:
interfaces = (GrapheneMetadataEntry,)
name = "MarkdownMetadataEntry"
| GrapheneMarkdownMetadataEntry |
python | django-extensions__django-extensions | tests/collisions/models.py | {
"start": 777,
"end": 1043
} | class ____(models.Model):
# no conflicts but FK to conflicting models.
name = models.ForeignKey(Name, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
global_id = models.CharField(unique=True, max_length=32)
| SystemUser |
python | pdm-project__pdm | src/pdm/formats/flit.py | {
"start": 2128,
"end": 5824
} | class ____(MetaConverter):
def warn_against_dynamic_version_or_docstring(self, source: Path, version: str, description: str) -> None:
if not self._ui:
return
dynamic_fields = []
if not version:
dynamic_fields.append("version")
if not description:
d... | FlitMetaConverter |
python | huggingface__transformers | src/transformers/models/llava/modeling_llava.py | {
"start": 13395,
"end": 19953
} | class ____(LlavaPreTrainedModel, GenerationMixin):
_checkpoint_conversion_mapping = {
r"^language_model.model": "model.language_model",
r"^vision_tower": "model.vision_tower",
r"^multi_modal_projector": "model.multi_modal_projector",
r"^language_model.lm_head": "lm_head",
}
_... | LlavaForConditionalGeneration |
python | python-visualization__folium | folium/features.py | {
"start": 34470,
"end": 40869
} | class ____(JSCSSMixin, Layer):
"""
Creates a TopoJson object for plotting into a Map.
Parameters
----------
data: file, dict or str.
The TopoJSON data you want to plot.
* If file, then data will be read in the file and fully
embedded in Leaflet's JavaScript.
* If dic... | TopoJson |
python | python-pillow__Pillow | src/PIL/FitsImagePlugin.py | {
"start": 3699,
"end": 4644
} | class ____(ImageFile.PyDecoder):
_pulls_fd = True
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
assert self.fd is not None
value = gzip.decompress(self.fd.read())
rows = []
offset = 0
number_of_bits = min(self.args[0] // 8, 4)
... | FitsGzipDecoder |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 261662,
"end": 262005
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("CreatedIssueContribution", graphql_name="node")
| CreatedIssueContributionEdge |
python | spack__spack | lib/spack/spack/cmd/common/arguments.py | {
"start": 5869,
"end": 7703
} | class ____(argparse.Action):
"""Pick the currently configured config scopes."""
def __init__(self, *args, **kwargs) -> None:
kwargs.setdefault("metavar", spack.config.SCOPES_METAVAR)
super().__init__(*args, **kwargs)
@property
def default(self):
return self._default() if callab... | ConfigScope |
python | django__django | tests/test_utils/tests.py | {
"start": 68364,
"end": 69109
} | class ____(SimpleTestCase):
def test_setup_test_environment_calling_more_than_once(self):
with self.assertRaisesMessage(
RuntimeError, "setup_test_environment() was already called"
):
setup_test_environment()
def test_allowed_hosts(self):
for type_ in (list, tupl... | SetupTestEnvironmentTests |
python | PrefectHQ__prefect | src/prefect/utilities/schema_tools/hydration.py | {
"start": 2559,
"end": 2833
} | class ____(HydrationError):
@property
def message(self) -> str:
return f"Missing '{self.key}' key in __prefect object"
@property
@abstractmethod
def key(self) -> str:
raise NotImplementedError("Must be implemented by subclass")
| KeyNotFound |
python | PrefectHQ__prefect | src/prefect/client/schemas/actions.py | {
"start": 27631,
"end": 28598
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to create a work pool."""
name: NonEmptyishName = Field(
description="The name of the work pool.",
)
description: Optional[str] = Field(default=None)
type: str = Field(
description="The work pool type.", default="pref... | WorkPoolCreate |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_name/invalid_name_module_level.py | {
"start": 252,
"end": 1286
} | class ____:
pass
ClassB = ClassA
def A(): # [invalid-name]
return 1, 2, 3
CONSTA, CONSTB, CONSTC = A()
CONSTD = A()
CONST = "12 34 ".rstrip().split()
ASSIGNMENT_THAT_CRASHED_PYLINT = type(float.__new__.__code__)
# Exclusive assignment: uses const regex
if CONST:
OTHER_CONST = 1
elif CONSTA:
... | ClassA |
python | kamyu104__LeetCode-Solutions | Python/min-cost-to-connect-all-points.py | {
"start": 1618,
"end": 2205
} | class ____(object):
def minCostConnectPoints(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
edges = []
for u in xrange(len(points)):
for v in xrange(u+1, len(points)):
edges.append((u, v, abs(points[v][0]-points[u][0]) + a... | Solution2 |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 154188,
"end": 162176
} | class ____:
if has_zarr_v3:
methods = [
"get",
"set",
"list_dir",
"list_prefix",
]
else:
methods = [
"__iter__",
"__contains__",
"__setitem__",
"__getitem__",
"listdir",
... | TestInstrumentedZarrStore |
python | huggingface__transformers | tests/models/deepseek_vl_hybrid/test_image_processing_deepseek_vl_hybrid.py | {
"start": 1259,
"end": 3740
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
high_res_size=None,
do_normalize=True,
image_mean=[0.5, 0.5, 0.5],
... | DeepseekVLHybridImageProcessingTester |
python | PyCQA__bandit | bandit/core/context.py | {
"start": 145,
"end": 10667
} | class ____:
def __init__(self, context_object=None):
"""Initialize the class with a context, empty dict otherwise
:param context_object: The context object to create class from
:return: -
"""
if context_object is not None:
self._context = context_object
e... | Context |
python | sympy__sympy | sympy/polys/matrices/exceptions.py | {
"start": 398,
"end": 492
} | class ____(DMError):
"""list of lists is inconsistent with shape"""
pass
| DMBadInputError |
python | sympy__sympy | sympy/codegen/cfunctions.py | {
"start": 10829,
"end": 11874
} | class ____(Function):
"""
Represents the hypotenuse function.
Explanation
===========
The hypotenuse function is provided by e.g. the math library
in the C99 standard, hence one may want to represent the function
symbolically when doing code-generation.
Examples
========
>>> ... | hypot |
python | streamlit__streamlit | lib/streamlit/elements/widgets/select_slider.py | {
"start": 2310,
"end": 3428
} | class ____(Generic[T]):
options: Sequence[T]
value: list[int]
is_range_value: bool
def serialize(self, v: object) -> list[int]:
return self._as_index_list(v)
def deserialize(self, ui_value: list[int] | None) -> T | tuple[T, T]:
if not ui_value:
# Widget has not been use... | SelectSliderSerde |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/configuration_phi4_multimodal.py | {
"start": 5238,
"end": 11733
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Phi4MultimodalAudioModel`]. It is used to instantiate a
Phi4Multimodal audio encoder according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults... | Phi4MultimodalAudioConfig |
python | sqlalchemy__sqlalchemy | test/sql/test_metadata.py | {
"start": 157703,
"end": 162139
} | class ____(fixtures.TestBase):
"""test assignment of default fixures to columns"""
def _fixture(self, *arg, **kw):
return Column("x", Integer, *arg, **kw)
def test_server_default_positional(self):
target = schema.DefaultClause("y")
c = self._fixture(target)
assert c.server_... | ColumnDefaultsTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictReadOnly2.py | {
"start": 1052,
"end": 1147
} | class ____(TypedDict, total=True):
a: str
b: NotRequired[str]
c: NotRequired[str]
| TD3 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 128869,
"end": 132316
} | class ____(GroupedElement, SelectBase, Generic[_SB]):
"""Represent a grouping of a :class:`_expression.SelectBase`.
This differs from :class:`.Subquery` in that we are still
an "inner" SELECT statement, this is strictly for grouping inside of
compound selects.
"""
__visit_name__ = "select_sta... | SelectStatementGrouping |
python | encode__django-rest-framework | tests/test_relations_hyperlink.py | {
"start": 1214,
"end": 1383
} | class ____(serializers.HyperlinkedModelSerializer):
class Meta:
model = ManyToManyTarget
fields = ('url', 'name', 'sources')
| ManyToManyTargetSerializer |
python | pypa__warehouse | warehouse/manage/forms.py | {
"start": 12481,
"end": 12956
} | class ____:
role_name = wtforms.SelectField(
"Select role",
choices=[
("", "Select role"),
("Member", "Member"),
("Manager", "Manager"),
("Owner", "Owner"),
("Billing Manager", "Billing Manager"),
],
coerce=lambda string: Or... | OrganizationRoleNameMixin |
python | falconry__falcon | falcon/testing/helpers.py | {
"start": 10142,
"end": 14081
} | class ____:
"""Collects and validates ASGI events returned by an app.
Raises:
TypeError: An event field emitted by the app was of an unexpected type.
ValueError: Invalid event name or field value.
"""
_LIFESPAN_EVENT_TYPES = frozenset(
[
'lifespan.startup.complete',... | ASGIResponseEventCollector |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-chroma/destination_chroma/config.py | {
"start": 2793,
"end": 3292
} | class ____(VectorDBConfigModel):
indexing: ChromaIndexingConfigModel
embedding: Union[
AzureOpenAIEmbeddingConfigModel,
OpenAIEmbeddingConfigModel,
CohereEmbeddingConfigModel,
FromFieldEmbeddingConfigModel,
FakeEmbeddingConfigModel,
OpenAICompatibleEmbeddingConfig... | ConfigModel |
python | doocs__leetcode | solution/2200-2299/2262.Total Appeal of A String/Solution.py | {
"start": 0,
"end": 259
} | class ____:
def appealSum(self, s: str) -> int:
ans = t = 0
pos = [-1] * 26
for i, c in enumerate(s):
c = ord(c) - ord('a')
t += i - pos[c]
ans += t
pos[c] = i
return ans
| Solution |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 1288,
"end": 2146
} | class ____(App[None]):
"""An app with zero bindings."""
async def test_just_app_no_bindings() -> None:
"""An app with no bindings should have no bindings, other than the app's hard-coded ones."""
async with NoBindings().run_test() as pilot:
assert list(pilot.app._bindings.key_to_bindings.keys()) =... | NoBindings |
python | walkccc__LeetCode | solutions/3300. Minimum Element After Replacement With Digit Sum/3300.py | {
"start": 0,
"end": 120
} | class ____:
def minElement(self, nums: list[int]) -> int:
return min(sum(map(int, str(num))) for num in nums)
| Solution |
python | getsentry__sentry | src/sentry/plugins/sentry_useragents/models.py | {
"start": 2099,
"end": 2397
} | class ____(UserAgentPlugin):
"""
Automatically adds the 'device' tag from events containing interface data
from ``request``.
"""
slug = "device"
title = "Auto Tag: Device"
tag = "device"
def get_tag_from_ua(self, ua):
return ua["device"]["family"]
| DevicePlugin |
python | conda__conda | tests/plugins/test_manager.py | {
"start": 1247,
"end": 1442
} | class ____:
@plugins.hookimpl
def conda_solvers(*args):
yield VerboseCondaSolver
DummyVirtualPackage = plugins.CondaVirtualPackage("dummy", "version", "build")
| VerboseSolverPlugin |
python | pypa__hatch | backend/src/hatchling/metadata/core.py | {
"start": 58289,
"end": 62187
} | class ____(Generic[PluginManagerBound]):
def __init__(self, root: str, config: dict[str, Any], plugin_manager: PluginManagerBound) -> None:
self.root = root
self.config = config
self.plugin_manager = plugin_manager
self._allow_direct_references: bool | None = None
self._allo... | HatchMetadataSettings |
python | marshmallow-code__marshmallow | tests/base.py | {
"start": 6914,
"end": 7039
} | class ____(BlogSchema):
user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species"))
| BlogSchemaOnlyExclude |
python | great-expectations__great_expectations | tests/metrics/test_metric.py | {
"start": 711,
"end": 768
} | class ____(MetricResult[bool]): ...
| ColumnValuesAboveResult |
python | fsspec__filesystem_spec | fsspec/implementations/reference.py | {
"start": 20376,
"end": 47349
} | class ____(AsyncFileSystem):
"""View byte ranges of some other file as a file system
Initial version: single file system target, which must support
async, and must allow start and end args in _cat_file. Later versions
may allow multiple arbitrary URLs for the targets.
This FileSystem is read-only. I... | ReferenceFileSystem |
python | getsentry__sentry | src/sentry/utils/math.py | {
"start": 725,
"end": 872
} | class ____(ABC):
@abstractmethod
def update(self, n: int, avg: float, value: float) -> float:
raise NotImplementedError
| MovingAverage |
python | openai__openai-python | src/openai/types/beta/assistant_update_params.py | {
"start": 610,
"end": 6289
} | class ____(TypedDict, total=False):
description: Optional[str]
"""The description of the assistant. The maximum length is 512 characters."""
instructions: Optional[str]
"""The system instructions that the assistant uses.
The maximum length is 256,000 characters.
"""
metadata: Optional[Met... | AssistantUpdateParams |
python | pytorch__pytorch | torch/_dynamo/code_context.py | {
"start": 1084,
"end": 1818
} | class ____:
def __init__(self) -> None:
self.code_context: ExactWeakKeyDictionary = ExactWeakKeyDictionary()
def has_context(self, code: types.CodeType) -> bool:
return code in self.code_context
def get_context(self, code: types.CodeType) -> dict[str, Any]:
ctx = self.code_context.... | CodeContextDict |
python | facebookresearch__faiss | benchs/bench_hybrid_cpu_gpu.py | {
"start": 2507,
"end": 4180
} | class ____:
"""
Separately manage the coarse quantizer and the IVF index.
"""
def __init__(self, quantizer, index, bs=-1, seq_tiling=False):
self.index = index
self.index_ivf = extract_index_ivf(index)
if isinstance(self.index_ivf, faiss.IndexIVF):
self.index_ivf.par... | SeparateCoarseQuantizationIndex |
python | pytorch__pytorch | torch/distributed/tensor/experimental/_context_parallel/_attention.py | {
"start": 44094,
"end": 59932
} | class ____(ParallelStyle):
class AttentionType(Enum):
FLEX = "flex_attention"
SDPA = "scaled_dot_product_attention"
def __init__(
self,
seq_dim: int,
attention_type: AttentionType,
) -> None:
super().__init__()
self.seq_dim = seq_dim
self.atte... | _ContextParallel |
python | walkccc__LeetCode | solutions/2785. Sort Vowels in a String/2785.py | {
"start": 0,
"end": 315
} | class ____:
def sortVowels(self, s: str) -> str:
VOWELS = 'aeiouAEIOU'
ans = []
vowels = sorted([c for c in s if c in VOWELS])
i = 0 # vowels' index
for c in s:
if c in VOWELS:
ans.append(vowels[i])
i += 1
else:
ans.append(c)
return ''.join(ans)
| Solution |
python | spack__spack | lib/spack/spack/solver/core.py | {
"start": 7129,
"end": 9057
} | class ____(NamedTuple):
flag_type: str
flag: str
flag_group: str
source: str
def intermediate_repr(sym):
"""Returns an intermediate representation of clingo models for Spack's spec builder.
Currently, transforms symbols from clingo models either to strings or to NodeArgument objects.
Ret... | NodeFlag |
python | FactoryBoy__factory_boy | tests/test_transformer.py | {
"start": 433,
"end": 572
} | class ____(factory.Factory):
name = factory.Transformer("value", transform=transform)
class Meta:
model = Upper
| UpperFactory |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.