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 | scipy__scipy | scipy/integrate/tests/test_quadrature.py | {
"start": 19537,
"end": 28534
} | class ____:
x0 = np.arange(4)
y0 = x0**2
@pytest.mark.parametrize('use_dx', (False, True))
@pytest.mark.parametrize('use_initial', (False, True))
def test_1d(self, use_dx, use_initial, xp):
# Test for exact agreement with polynomial of highest
# possible order (3 if `dx` is constant... | TestCumulativeSimpson |
python | scipy__scipy | scipy/stats/_resampling.py | {
"start": 93735,
"end": 94568
} | class ____:
"""Configuration information for a statistical resampling method.
Instances of this class can be passed into the `method` parameter of some
hypothesis test functions to perform a resampling or Monte Carlo version
of the hypothesis test.
Attributes
----------
n_resamples : int
... | ResamplingMethod |
python | kamyu104__LeetCode-Solutions | Python/maximum-sum-of-two-non-overlapping-subarrays.py | {
"start": 29,
"end": 617
} | class ____(object):
def maxSumTwoNoOverlap(self, A, L, M):
"""
:type A: List[int]
:type L: int
:type M: int
:rtype: int
"""
for i in xrange(1, len(A)):
A[i] += A[i-1]
result, L_max, M_max = A[L+M-1], A[L-1], A[M-1]
for i in xrange(L... | Solution |
python | pytorch__pytorch | test/export/test_dynamic_shapes.py | {
"start": 158,
"end": 1373
} | class ____(TestCase):
def test_dimhint_repr(self):
hint = _DimHint(_DimHintType.DYNAMIC)
self.assertEqual(repr(hint), "DimHint(DYNAMIC)")
hint_with_bounds = _DimHint(_DimHintType.AUTO, min=1, max=64)
self.assertEqual(repr(hint_with_bounds), "DimHint(AUTO, min=1, max=64)")
n... | TestDimHint |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/convolutional.py | {
"start": 126087,
"end": 131584
} | class ____(Layer):
"""Cropping layer for 2D input (e.g. picture).
It crops along spatial dimensions, i.e. height and width.
Examples:
>>> input_shape = (2, 28, 28, 3)
>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)
>>> y = tf.keras.layers.Cropping2D(cropping=((2, 2), (4, 4)))(x)
>>> print(... | Cropping2D |
python | ansible__ansible | lib/ansible/playbook/play_context.py | {
"start": 1608,
"end": 13847
} | class ____(Base):
"""
This class is used to consolidate the connection information for
hosts in a play and child tasks, where the task may override some
connection/authentication information.
"""
_post_validate_object = True
# base
module_compression = FieldAttribute(isa='string', def... | PlayContext |
python | plotly__plotly.py | plotly/graph_objs/scattercarpet/_hoverlabel.py | {
"start": 233,
"end": 11283
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattercarpet"
_path_str = "scattercarpet.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namele... | Hoverlabel |
python | readthedocs__readthedocs.org | readthedocs/profiles/views.py | {
"start": 6068,
"end": 6612
} | class ____(PrivateViewMixin):
"""User token to access APIv3."""
model = Token
lookup_url_kwarg = "token_pk"
template_name = "profiles/private/token_list.html"
def get_queryset(self):
# NOTE: we are currently showing just one token since the DRF model has
# a OneToOneField relation ... | TokenMixin |
python | kubernetes-client__python | kubernetes/base/watch/watch_test.py | {
"start": 776,
"end": 25694
} | class ____(unittest.TestCase):
def setUp(self):
# counter for a test that needs test global state
self.callcount = 0
def test_watch_with_decode(self):
fake_resp = Mock()
fake_resp.close = Mock()
fake_resp.release_conn = Mock()
fake_resp.stream = Mock(
... | WatchTests |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 72196,
"end": 73534
} | class ____(Operation):
def __init__(self, axis=None, dtype=None, *, name=None):
super().__init__(name=name)
self.axis = axis
self.dtype = None if dtype is None else backend.standardize_dtype(dtype)
def call(self, x):
return backend.numpy.cumprod(x, axis=self.axis, dtype=self.dty... | Cumprod |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/models/batch_apis.py | {
"start": 1634,
"end": 1837
} | class ____(TypedDict, total=False):
"""Represent the parameters of ``is_authorized_pool`` API in the auth manager."""
method: ResourceMethod
details: PoolDetails | None
| IsAuthorizedPoolRequest |
python | google__flatbuffers | tests/MyGame/Example/NestedUnion/Vec3.py | {
"start": 280,
"end": 3847
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset: int = 0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Vec3()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsVec3(cls, buf, offset=0):
... | Vec3 |
python | sqlalchemy__sqlalchemy | test/sql/test_defaults.py | {
"start": 42312,
"end": 46806
} | class ____(fixtures.TestBase):
__sparse_driver_backend__ = True
@testing.provide_metadata
def test_string_default_none_on_insert(self, connection):
"""Test that without implicit returning, we return None for
a string server default.
That is, we don't want to attempt to pre-execute ... | ServerDefaultsOnPKTest |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 26553,
"end": 26714
} | class ____(strip_text_x, strip_text_y):
"""
Facet labels along both axes
Parameters
----------
theme_element : element_text
"""
| strip_text |
python | readthedocs__readthedocs.org | readthedocs/projects/tests/test_build_tasks.py | {
"start": 2541,
"end": 5326
} | class ____(BuildEnvironmentBase):
# Relative path to where a custom config file is assumed to exist in repo
config_file_name = "unique.yaml"
def _get_project(self):
return fixture.get(
Project,
slug="project",
readthedocs_yaml_path=self.config_file_name,
... | TestCustomConfigFile |
python | langchain-ai__langchain | libs/core/tests/unit_tests/stores/test_in_memory.py | {
"start": 245,
"end": 533
} | class ____(BaseStoreSyncTests):
@pytest.fixture
@override
def kv_store(self) -> InMemoryStore:
return InMemoryStore()
@pytest.fixture
@override
def three_values(self) -> tuple[str, str, str]:
return "value1", "value2", "value3"
| TestSyncInMemoryStore |
python | catalyst-team__catalyst | catalyst/contrib/datasets/imagewang.py | {
"start": 75,
"end": 469
} | class ____(ImageClassificationDataset):
"""
`Imagewang <https://github.com/fastai/imagenette#image%E7%BD%91>`_ Dataset.
.. note::
catalyst[cv] required for this dataset.
"""
name = "imagewang"
resources = [
(
"https://s3.amazonaws.com/fast-ai-imageclas/imagewang.tgz... | Imagewang |
python | lepture__authlib | authlib/jose/rfc7518/jwe_encs.py | {
"start": 3215,
"end": 5093
} | class ____(JWEEncAlgorithm):
# Use of an IV of size 96 bits is REQUIRED with this algorithm.
# https://tools.ietf.org/html/rfc7518#section-5.3
IV_SIZE = 96
def __init__(self, key_size):
self.name = f"A{key_size}GCM"
self.description = f"AES GCM using {key_size}-bit key"
self.key... | GCMEncAlgorithm |
python | numba__numba | numba/core/types/functions.py | {
"start": 24582,
"end": 25215
} | class ____(Callable, Opaque):
"""
Type class for namedtuple classes.
"""
def __init__(self, instance_class):
self.instance_class = instance_class
name = "class(%s)" % (instance_class)
super(NamedTupleClass, self).__init__(name)
def get_call_type(self, context, args, kws):
... | NamedTupleClass |
python | pytorch__pytorch | test/inductor/test_split_cat_fx_aten_passes.py | {
"start": 518,
"end": 1462
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, x: torch.Tensor, y: torch.Tensor, z: torch.Tensor):
cat = torch.ops.aten.cat.default([x, y], 1)
split = torch.ops.aten.split.Tensor(cat, 32, 1)
getitem = split[0]
getitem_1 = sp... | TestSplitCat |
python | tiangolo__fastapi | docs_src/schema_extra_example/tutorial005_an_py310.py | {
"start": 114,
"end": 1523
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(
*,
item_id: int,
item: Annotated[
Item,
Body(
openapi_examples={
"normal": {
... | Item |
python | doocs__leetcode | solution/2900-2999/2961.Double Modular Exponentiation/Solution.py | {
"start": 0,
"end": 247
} | class ____:
def getGoodIndices(self, variables: List[List[int]], target: int) -> List[int]:
return [
i
for i, (a, b, c, m) in enumerate(variables)
if pow(pow(a, b, 10), c, m) == target
]
| Solution |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 48587,
"end": 49195
} | class ____(system_info):
section = 'armpl'
dir_env_var = 'ARMPL_DIR'
_lib_armpl = ['armpl_lp64_mp']
def calc_info(self):
lib_dirs = self.get_lib_dirs()
incl_dirs = self.get_include_dirs()
armpl_libs = self.get_libs('armpl_libs', self._lib_armpl)
info = self.check_libs2(l... | armpl_info |
python | numba__numba | numba/cuda/codegen.py | {
"start": 1502,
"end": 11350
} | class ____(serialize.ReduceMixin, CodeLibrary):
"""
The CUDACodeLibrary generates PTX, SASS, cubins for multiple different
compute capabilities. It also loads cubins to multiple devices (via
get_cufunc), which may be of different compute capabilities.
"""
def __init__(self, codegen, name, entry... | CUDACodeLibrary |
python | networkx__networkx | networkx/algorithms/approximation/tests/test_traveling_salesman.py | {
"start": 9438,
"end": 32048
} | class ____(TestSimulatedAnnealingTSP):
tsp = staticmethod(nx_app.threshold_accepting_tsp)
def test_failure_of_costs_too_high_when_iterations_low(self):
# Threshold Version:
# set number of moves low and number of iterations low
cycle = self.tsp(
self.DG2,
"greedy... | TestThresholdAcceptingTSP |
python | ansible__ansible | lib/ansible/module_utils/errors.py | {
"start": 2416,
"end": 2501
} | class ____(AnsibleValidationError):
"""Error converting no_log values"""
| NoLogError |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py | {
"start": 6572,
"end": 7042
} | class ____(FileSystemEvent):
"""File system event representing directory deletion on the file system."""
event_type = EVENT_TYPE_DELETED
is_directory = True
def __init__(self, src_path):
super(DirDeletedEvent, self).__init__(src_path)
def __repr__(self):
return ("<%(class_name)s: ... | DirDeletedEvent |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 64847,
"end": 72931
} | class ____:
async def test_task_input_hash_within_flows(
self,
):
@task(
cache_key_fn=task_input_hash,
persist_result=True,
)
def foo(x):
return x
@flow
def bar():
return (
foo(1, return_state=True),... | TestCacheFunctionBuiltins |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/check/builder.py | {
"start": 674,
"end": 873
} | class ____(NamedTuple):
"""A pointer to where to lazily import from to resolve a ForwardRef.
Used with Annotated ie: Annotated['Foo', ImportFrom('baz.bar')]
"""
module: str
| ImportFrom |
python | optuna__optuna | optuna/_gp/acqf.py | {
"start": 11389,
"end": 13050
} | class ____(BaseAcquisitionFunc):
def __init__(
self,
gpr_list: list[GPRegressor],
search_space: SearchSpace,
Y_feasible: torch.Tensor | None,
n_qmc_samples: int,
qmc_seed: int | None,
constraints_gpr_list: list[GPRegressor],
constraints_threshold_list:... | ConstrainedLogEHVI |
python | great-expectations__great_expectations | contrib/great_expectations_ethical_ai_expectations/great_expectations_ethical_ai_expectations/expectations/expect_table_linear_feature_importances_to_be.py | {
"start": 1206,
"end": 2745
} | class ____(TableMetricProvider):
metric_name = "table.modeling.linear.feature_importances"
value_keys = ("y_column",)
@metric_value(engine=PandasExecutionEngine)
def _pandas(
cls,
execution_engine: PandasExecutionEngine,
metric_domain_kwargs: Dict,
metric_value_kwargs: D... | TableModelingRidgeFeatureImportances |
python | numba__numba | numba/tests/test_linalg.py | {
"start": 59972,
"end": 65269
} | class ____(TestLinalgSystems):
"""
Tests for np.linalg.solve.
"""
@needs_lapack
def test_linalg_solve(self):
"""
Test np.linalg.solve
"""
cfunc = jit(nopython=True)(solve_system)
def check(a, b, **kwargs):
expected = solve_system(a, b, **kwargs)
... | TestLinalgSolve |
python | django__django | django/db/migrations/autodetector.py | {
"start": 1153,
"end": 89926
} | class ____:
"""
Take a pair of ProjectStates and compare them to see what the first would
need doing to make it match the second (the second usually being the
project's current state).
Note that this naturally operates on entire projects at a time,
as it's likely that changes interact (for exam... | MigrationAutodetector |
python | huggingface__transformers | src/transformers/models/nougat/image_processing_nougat.py | {
"start": 1535,
"end": 2090
} | class ____(ImagesKwargs, total=False):
r"""
do_crop_margin (`bool`, *optional*, defaults to `True`):
Whether to crop the image margins.
do_thumbnail (`bool`, *optional*, defaults to `True`):
Whether to resize the image using thumbnail method.
do_align_long_axis (`bool`, *optional*, defau... | NougatImageProcessorKwargs |
python | pydata__xarray | xarray/computation/arithmetic.py | {
"start": 4155,
"end": 4263
} | class ____(
SupportsArithmetic,
DatasetGroupByOpsMixin,
):
__slots__ = ()
| DatasetGroupbyArithmetic |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/sparse/csr_sparse_matrix_sparse_mat_mul_grad_test.py | {
"start": 1817,
"end": 5045
} | class ____(test.TestCase):
@classmethod
def setUpClass(cls):
super(CSRSparseMatrixGradTest, cls).setUpClass()
cls._gpu_available = test_util.is_gpu_available()
# TODO(penporn): Make these tests runnable on eager mode.
# (tf.gradients and gradient_checker only run in graph mode.)
@test_util.run_depre... | CSRSparseMatrixGradTest |
python | ray-project__ray | python/ray/tune/tests/test_searchers.py | {
"start": 10914,
"end": 16523
} | class ____(unittest.TestCase):
"""
Test add_evaluated_point method in searchers that support it.
"""
def setUp(self):
self.param_name = "report"
self.valid_value = 1.0
self.space = {self.param_name: tune.uniform(0.0, 5.0)}
self.analysis = tune.run(
_dummy_ob... | AddEvaluatedPointTest |
python | huggingface__transformers | src/transformers/models/voxtral/processing_voxtral.py | {
"start": 1448,
"end": 1956
} | class ____(ProcessingKwargs, total=False):
_defaults = {
"text_kwargs": {
"padding": True,
},
"audio_kwargs": {
"sampling_rate": 16000,
"padding": True,
"truncation": False,
"pad_to_multiple_of": 480000,
"max_source_posi... | VoxtralProcessorKwargs |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_device_class_spec.py | {
"start": 383,
"end": 7302
} | 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... | V1beta1DeviceClassSpec |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_v2_utils_test.py | {
"start": 5811,
"end": 7336
} | class ____(test.TestCase):
def test_table_config_repr(self):
table = tpu_embedding_v2_utils.TableConfig(
vocabulary_size=2, dim=4,
combiner='sum', name='table')
self.assertEqual(
repr(table),
'TableConfig(vocabulary_size=2, dim=4, initializer=None, '
'optimizer=None, ... | ConfigTest |
python | rapidsai__cudf | python/cudf/cudf/core/udf/masked_typing.py | {
"start": 7061,
"end": 7456
} | class ____(models.StructModel):
def __init__(self, dmm, fe_type):
# This struct has two members, a value and a validity
# let the type of the `value` field be the same as the
# `value_type` and let `valid` be a boolean
members = [("value", fe_type.value_type), ("valid", types.bool_)]... | MaskedModel |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_doughnut05.py | {
"start": 315,
"end": 1237
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_doughnut05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.... | TestCompareXLSXFiles |
python | bokeh__bokeh | src/bokeh/models/dom.py | {
"start": 8542,
"end": 10265
} | class ____(DOMElement):
""" A parsed HTML fragment with optional references to DOM nodes and UI elements. """
def __init__(self, *html: str | DOMNode | UIElement, **kwargs: Any) -> None:
if html and "html" in kwargs:
raise TypeError("'html' argument specified multiple times")
proce... | HTML |
python | modin-project__modin | modin/core/execution/ray/implementations/pandas_on_ray/partitioning/partition.py | {
"start": 14303,
"end": 15533
} | class ____(MaterializationHook):
"""
Used by mask() for the slilced length computation.
Parameters
----------
ref : ObjectIDType
Non-materialized length to be sliced.
slc : slice
The slice to be applied.
"""
def __init__(self, ref: ObjectIDType, slc: slice):
sel... | SlicerHook |
python | openai__openai-python | examples/realtime/push_to_talk_app.py | {
"start": 2051,
"end": 9480
} | class ____(App[None]):
CSS = """
Screen {
background: #1a1b26; /* Dark blue-grey background */
}
Container {
border: double rgb(91, 164, 91);
}
Horizontal {
width: 100%;
}
#input-container {
height: 5; /* Ex... | RealtimeApp |
python | eventlet__eventlet | tests/isolated/patcher_existing_locks_preexisting.py | {
"start": 178,
"end": 1168
} | class ____:
lock = threading.RLock()
class NS2:
lock = threading.RLock()
dict = {1: 2, 12: threading.RLock()}
list = [0, threading.RLock()]
def ensure_upgraded(lock):
if not isinstance(lock, python_lock):
raise RuntimeError(lock)
if __name__ == '__main__':
# These extra pri... | NS |
python | ray-project__ray | python/ray/data/_internal/datasource/tfrecords_datasource.py | {
"start": 680,
"end": 1160
} | class ____:
"""
Specifies read options when reading TFRecord files with TFX.
"""
# An int representing the number of consecutive elements of
# this dataset to combine in a single batch when tfx-bsl is used to read
# the tfrecord files.
batch_size: int = 2048
# Toggles the schema infere... | TFXReadOptions |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 688122,
"end": 688577
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of LinkProjectV2ToTeam"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "team")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutat... | LinkProjectV2ToTeamPayload |
python | getsentry__sentry | tests/sentry/release_health/release_monitor/__init__.py | {
"start": 3205,
"end": 5297
} | class ____(TestCase, BaseMetricsTestCase):
__test__ = Abstract(__module__, __qualname__)
backend_class: type[BaseReleaseMonitorBackend]
def setUp(self) -> None:
self.project1 = self.create_project()
self.project2 = self.create_project()
self.environment1 = self.create_environment(p... | BaseFetchProjectReleaseHealthTotalsTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/_processors_cy.py | {
"start": 2104,
"end": 2498
} | class ____:
type_: type
format_: str
__slots__ = ("type_", "format_")
def __init__(self, type_: type, scale: int):
self.type_ = type_
self.format_ = f"%.{scale}f"
def __call__(self, value: Optional[Any]) -> object:
if value is None:
return None
else:
... | to_decimal_processor_factory |
python | marshmallow-code__apispec | tests/test_ext_marshmallow.py | {
"start": 50615,
"end": 51199
} | class ____:
def test_schema_with_default_values(self, spec):
spec.components.schema("DefaultValuesSchema", schema=DefaultValuesSchema)
definitions = get_schemas(spec)
props = definitions["DefaultValuesSchema"]["properties"]
assert props["number_auto_default"]["default"] == 12
... | TestSchemaWithDefaultValues |
python | dask__distributed | distributed/spill.py | {
"start": 10721,
"end": 13767
} | class ____(zict.Func[Key, object, bytes]):
max_weight: int | Literal[False]
weight_by_key: dict[Key, SpilledSize]
total_weight: SpilledSize
def __init__(self, spill_directory: str, max_weight: int | Literal[False] = False):
compression = get_compression_settings(
"distributed.worker... | Slow |
python | wandb__wandb | wandb/sdk/artifacts/_generated/link_artifact.py | {
"start": 333,
"end": 625
} | class ____(GQLResult):
version_index: Optional[int] = Field(alias="versionIndex")
artifact_membership: Optional[ArtifactMembershipFragment] = Field(
alias="artifactMembership", default=None
)
LinkArtifact.model_rebuild()
LinkArtifactResult.model_rebuild()
| LinkArtifactResult |
python | realpython__materials | python-async-iterators/large_file_iterator.py | {
"start": 34,
"end": 749
} | class ____:
def __init__(self, path, chunk_size=1024):
self.path = path
self.chunk_size = chunk_size
self.file = None
def __aiter__(self):
return self
async def __anext__(self):
if self.file is None:
self.file = await aiofiles.open(self.path, mode="rb")
... | AsyncFileIterator |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 403696,
"end": 409310
} | class ____(rv_continuous):
r"""A relativistic Breit-Wigner random variable.
%(before_notes)s
See Also
--------
cauchy: Cauchy distribution, also known as the Breit-Wigner distribution.
Notes
-----
The probability density function for `rel_breitwigner` is
.. math::
f(x, ... | rel_breitwigner_gen |
python | django__django | tests/model_fields/models.py | {
"start": 3506,
"end": 3586
} | class ____(models.Model):
value = models.SmallIntegerField()
| SmallIntegerModel |
python | huggingface__transformers | src/transformers/models/vitmatte/modeling_vitmatte.py | {
"start": 5896,
"end": 7560
} | class ____(nn.Module):
"""
Simple and lightweight Detail Capture Module for ViT Matting.
"""
def __init__(self, config):
super().__init__()
if len(config.fusion_hidden_sizes) != len(config.convstream_hidden_sizes) + 1:
raise ValueError(
"The length of fusion_... | VitMatteDetailCaptureModule |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 257275,
"end": 257510
} | class ____(Response):
"""
Response of tasks.ping endpoint.
"""
_service = "tasks"
_action = "ping"
_version = "2.9"
_schema = {"additionalProperties": False, "definitions": {}, "type": "object"}
| PingResponse |
python | jina-ai__jina | jina/proto/docarray_v1/pb/jina_pb2_grpc.py | {
"start": 26117,
"end": 27013
} | class ____(object):
"""*
jina gRPC service to trigger a snapshot at the Executor Runtime.
"""
@staticmethod
def restore_status(
request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
... | JinaExecutorRestoreProgress |
python | getsentry__sentry | src/sentry/issues/occurrence_consumer.py | {
"start": 1682,
"end": 19675
} | class ____(Exception):
pass
def create_rate_limit_key(project_id: int, fingerprint: str) -> str:
rate_limit_key = f"occurrence_rate_limit:{project_id}-{fingerprint}"
return rate_limit_key
def is_rate_limited(
project_id: int,
fingerprint: str,
) -> bool:
try:
rate_limit_enabled = opt... | EventLookupError |
python | numpy__numpy | numpy/distutils/fcompiler/vast.py | {
"start": 98,
"end": 1667
} | class ____(GnuFCompiler):
compiler_type = 'vast'
compiler_aliases = ()
description = 'Pacific-Sierra Research Fortran 90 Compiler'
version_pattern = (r'\s*Pacific-Sierra Research vf90 '
r'(Personal|Professional)\s+(?P<version>[^\s]*)')
# VAST f90 does not support -o with -c. ... | VastFCompiler |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 188386,
"end": 189624
} | class ____(GeneratedAirbyteSource):
class PATCredentials:
@public
def __init__(self, personal_access_token: str):
self.personal_access_token = check.str_param(
personal_access_token, "personal_access_token"
)
class OAuthCredentials:
@public
... | AsanaSource |
python | networkx__networkx | networkx/algorithms/isomorphism/vf2userfunc.py | {
"start": 3071,
"end": 4736
} | class ____(vf2.GraphMatcher):
"""VF2 isomorphism checker for undirected graphs."""
def __init__(self, G1, G2, node_match=None, edge_match=None):
"""Initialize graph matcher.
Parameters
----------
G1, G2: graph
The graphs to be tested.
node_match: callable
... | GraphMatcher |
python | ansible__ansible | lib/ansible/_internal/_yaml/_loader.py | {
"start": 1297,
"end": 1886
} | class ____(_YamlParser, AnsibleInstrumentedConstructor, Resolver):
"""Ansible YAML loader which supports Ansible custom behavior such as `Origin` tagging, but no Ansible-specific YAML tags."""
def __init__(self, stream: str | bytes | _io.IOBase) -> None:
_YamlParser.__init__(self, stream)
Ansi... | AnsibleInstrumentedLoader |
python | google__jax | jax/experimental/jax2tf/examples/mnist_lib.py | {
"start": 6576,
"end": 11512
} | class ____:
"""An MNIST model using Flax."""
name = "mnist_flax"
class Module(nn.Module):
"""A simple CNN model for MNIST.
There is an option for the model to skip the classifier layer, for
demonstrating reuse of the classifier-less model into a larger model.
See README.md.
"""
@nn.com... | FlaxMNIST |
python | apache__airflow | scripts/in_container/run_generate_openapi_spec_providers.py | {
"start": 1622,
"end": 3634
} | class ____(NamedTuple):
openapi_spec_file: Path
app: FastAPI | None
prefix: str
sys.path.insert(0, str(Path(__file__).parent.resolve()))
ProvidersManager().initialize_providers_configuration()
PROVIDERS_DEFS = {
"fab": ProviderDef(
openapi_spec_file=Path(FAB_AUTHMGR_API_PATH).parent
/... | ProviderDef |
python | doocs__leetcode | lcof2/剑指 Offer II 097. 子序列的数目/Solution.py | {
"start": 0,
"end": 414
} | class ____:
def numDistinct(self, s: str, t: str) -> int:
m, n = len(s), len(t)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
f[i][0] = 1
for i, a in enumerate(s, 1):
for j, b in enumerate(t, 1):
f[i][j] = f[i - 1][j]
... | Solution |
python | pytorch__pytorch | torch/distributed/tensor/placement_types.py | {
"start": 855,
"end": 17130
} | class ____(torch._C._distributed.Shard):
"""
The ``Shard(dim)`` placement describes the DTensor sharding on tensor dimension
``dim`` over a corresponding ``DeviceMesh`` dimension, where each rank on the
DeviceMesh dimension only holds a shard/piece of the global Tensor. The
``Shard(dim)`` placement ... | Shard |
python | getsentry__sentry | src/sentry/web/frontend/base.py | {
"start": 28693,
"end": 29062
} | class ____(AbstractOrganizationView):
"""A view which accesses organization objects over RPC.
Only endpoints on the control silo should use this class (but it works anywhere).
"""
def _get_organization(self) -> RpcOrganization | None:
return self.active_organization.organization if self.active... | ControlSiloOrganizationView |
python | jazzband__django-simple-history | simple_history/tests/view.py | {
"start": 518,
"end": 605
} | class ____(CreateView):
model = Poll
fields = ["question", "pub_date"]
| PollCreate |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 498776,
"end": 499992
} | class ____(VegaLiteSchema):
"""
JoinAggregateFieldDef schema wrapper.
Parameters
----------
op : :class:`AggregateOp`, Literal['argmax', 'argmin', 'average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'val... | JoinAggregateFieldDef |
python | ray-project__ray | rllib/algorithms/sac/sac.py | {
"start": 26844,
"end": 27795
} | class ____(DQN):
"""Soft Actor Critic (SAC) Algorithm class.
This file defines the distributed Algorithm class for the soft actor critic
algorithm.
See `sac_[tf|torch]_policy.py` for the definition of the policy loss.
Detailed documentation:
https://docs.ray.io/en/master/rllib-algorithms.html#... | SAC |
python | huggingface__transformers | tests/models/glm4_moe/test_modeling_glm4_moe.py | {
"start": 1706,
"end": 2091
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = Glm4MoeModelTester
# used in `test_torch_compile_for_training`. Skip as "Dynamic control flow in MoE"
_torch_compile_train_cls = None
model_split_percents = [0.5, 0.85, 0.9] # it tries to offload everything with the default value
... | Glm4MoeModelTest |
python | kamyu104__LeetCode-Solutions | Python/flip-equivalent-binary-trees.py | {
"start": 1110,
"end": 1967
} | class ____(object):
def flipEquiv(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
stk1, stk2 = [root1], [root2]
while stk1 and stk2:
node1, node2 = stk1.pop(), stk2.pop()
if not node1 and not node2:... | Solution2 |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 29170,
"end": 29619
} | class ____(DiagnosticPipError):
reference = "failed-wheel-build-for-install"
def __init__(self, failed: list[InstallRequirement]) -> None:
super().__init__(
message=(
"Failed to build installable wheels for some "
"pyproject.toml based projects"
)... | InstallWheelBuildError |
python | mahmoud__boltons | tests/test_strutils.py | {
"start": 3030,
"end": 5568
} | class ____(TestCase):
def test_simple_substitutions(self):
"""Test replacing multiple values."""
m = strutils.MultiReplace({r'cat': 'kedi', r'purple': 'mor', })
self.assertEqual(m.sub('The cat is purple'), 'The kedi is mor')
def test_shortcut_function(self):
"""Test replacing m... | TestMultiReplace |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1217201,
"end": 1229346
} | class ____(sgqlc.types.Type, Node):
"""A listing in the GitHub integration marketplace."""
__schema__ = github_schema
__field_names__ = (
"app",
"company_url",
"configuration_resource_path",
"configuration_url",
"documentation_url",
"extended_description",
... | MarketplaceListing |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-analytics-v4/source_google_analytics_v4/source.py | {
"start": 18198,
"end": 18949
} | class ____(GoogleAnalyticsV4Stream):
cursor_field = "ga_date"
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
return {self.cursor_field: max(latest_record.get(self.cursor_field, ""), current_stream_state.get(self.cursor... | GoogleAnalyticsV4IncrementalObjectsBase |
python | django__django | tests/model_forms/models.py | {
"start": 3415,
"end": 3644
} | class ____(models.Model):
writer = models.OneToOneField(Writer, models.CASCADE, primary_key=True)
age = models.PositiveIntegerField()
def __str__(self):
return "%s is %s" % (self.writer, self.age)
| WriterProfile |
python | wandb__wandb | tests/system_tests/test_api/conftest.py | {
"start": 867,
"end": 3267
} | class ____:
"""Simple HTTP server for serving parquet files over HTTP."""
def __init__(self):
self.port = self.get_free_port()
self.server = None
self.thread = None
def get_free_port(self) -> int:
"""Get a free port."""
with socket.socket(socket.AF_INET, socket.SOCK... | ParquetHTTPServer |
python | google__jax | jax/_src/pallas/mosaic/sc_core.py | {
"start": 7455,
"end": 11134
} | class ____:
core_axis_name: str
subcore_axis_name: str
num_cores: int = dataclasses.field(default_factory=_get_num_cores)
num_subcores: int = dataclasses.field(
default_factory=_get_num_subcores, init=False
)
def __post_init__(self):
sc_info = get_sparse_core_info()
if self.num_cores > (num_e... | VectorSubcoreMesh |
python | pypa__setuptools | setuptools/_vendor/packaging/_manylinux.py | {
"start": 2316,
"end": 9612
} | class ____(NamedTuple):
major: int
minor: int
def _glibc_version_string_confstr() -> str | None:
"""
Primary implementation of glibc_version_string using os.confstr.
"""
# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
# to be broken or missing. This strategy is us... | _GLibCVersion |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table03.py | {
"start": 315,
"end": 1003
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | django__django | tests/test_utils/tests.py | {
"start": 4827,
"end": 7181
} | class ____(TransactionTestCase):
available_apps = []
def test_skip_class_unless_db_feature(self):
@skipUnlessDBFeature("__class__")
class NotSkippedTests(TestCase):
def test_dummy(self):
return
@skipUnlessDBFeature("missing")
@skipIfDBFeature("__clas... | SkippingClassTestCase |
python | django__django | tests/postgres_tests/test_search.py | {
"start": 6377,
"end": 6726
} | class ____(PostgreSQLSimpleTestCase):
def test_from_parameter(self):
self.assertIsNone(SearchConfig.from_parameter(None))
self.assertEqual(SearchConfig.from_parameter("foo"), SearchConfig("foo"))
self.assertEqual(
SearchConfig.from_parameter(SearchConfig("bar")), SearchConfig("ba... | SearchConfigTests |
python | ansible__ansible | lib/ansible/_internal/_json/_profiles/_cache_persistence.py | {
"start": 1837,
"end": 1913
} | class ____(_profiles.AnsibleProfileJSONDecoder):
_profile = _Profile
| Decoder |
python | coleifer__peewee | playhouse/signals.py | {
"start": 1832,
"end": 2511
} | class ____(_Model):
def __init__(self, *args, **kwargs):
super(Model, self).__init__(*args, **kwargs)
pre_init.send(self)
def save(self, *args, **kwargs):
pk_value = self._pk if self._meta.primary_key else True
created = kwargs.get('force_insert', False) or not bool(pk_value)
... | Model |
python | walkccc__LeetCode | solutions/3375. Minimum Operations to Make Array Values Equal to K/3375.py | {
"start": 0,
"end": 218
} | class ____:
def minOperations(self, nums: list[int], k: int) -> int:
numsSet = set(nums)
mn = min(nums)
if mn < k:
return -1
if mn > k:
return len(numsSet)
return len(numsSet) - 1
| Solution |
python | django__django | tests/admin_views/admin.py | {
"start": 22056,
"end": 22254
} | class ____(admin.ModelAdmin):
list_filter = (("warm", CustomTemplateBooleanFieldListFilter),)
# For Selenium Prepopulated tests -------------------------------------
| CustomTemplateFilterColorAdmin |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_complex.py | {
"start": 3718,
"end": 41272
} | class ____(__TestCase):
def assertFloatIdentical(self, x, y):
"""Fail unless floats x and y are identical, in the sense that:
(1) both x and y are nans, or
(2) both x and y are infinities, with the same sign, or
(3) both x and y are zeros, with the same sign, or
(4) x and y ... | ComplexTest |
python | gevent__gevent | src/gevent/tests/test__ares_timeout.py | {
"start": 346,
"end": 1015
} | class ____(greentest.TestCase):
__timeout__ = 30
def test(self):
listener = self._close_on_teardown(udp_listener())
address = listener.getsockname()
def reader():
while True:
listener.recvfrom(10000)
greader = gevent.spawn(reader)
self._cl... | TestTimeout |
python | numba__numba | numba/tests/enum_usecases.py | {
"start": 33,
"end": 93
} | class ____(Enum):
red = 1
green = 2
blue = 3
| Color |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_sharding_test.py | {
"start": 875,
"end": 5177
} | class ____(test.TestCase):
def testFreeze(self):
"""Tests that freezing a policy applies default values."""
p1 = tpu_sharding.ShardingPolicy()
p1.freeze()
self.assertEqual(p1.number_of_shards,
tpu_sharding._DEFAULT_NUMBER_OF_SHARDS)
self.assertEqual(p1.shard_dimension, tpu_sh... | ShardingTest |
python | getsentry__sentry | tests/sentry/utils/test_event_frames.py | {
"start": 16794,
"end": 41572
} | class ____(TestCase):
def test_crashing_event_with_exception_interface_but_no_frame_should_waterfall_to_thread_frames(
self,
) -> None:
event = self.store_event(
data={
"platform": "cocoa",
"exception": {
"values": [
... | CocoaWaterFallTestCase |
python | Farama-Foundation__Gymnasium | gymnasium/vector/async_vector_env.py | {
"start": 1307,
"end": 34824
} | class ____(VectorEnv):
"""Vectorized environment that runs multiple environments in parallel.
It uses ``multiprocessing`` processes, and pipes for communication.
Example:
>>> import gymnasium as gym
>>> envs = gym.make_vec("Pendulum-v1", num_envs=2, vectorization_mode="async")
>>> ... | AsyncVectorEnv |
python | openai__openai-python | src/openai/types/container_create_params.py | {
"start": 591,
"end": 814
} | class ____(TypedDict, total=False):
anchor: Required[Literal["last_active_at"]]
"""Time anchor for the expiration time.
Currently only 'last_active_at' is supported.
"""
minutes: Required[int]
| ExpiresAfter |
python | ansible__ansible | lib/ansible/module_utils/six/__init__.py | {
"start": 15342,
"end": 18368
} | class ____(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_request"""
_urllib_request_moved_attributes = [
MovedAttribute("urlopen", "urllib2", "urllib.request"),
MovedAttribute("install_opener", "urllib2", "urllib.request"),
MovedAttribute("build_opener", "urllib2", "urllib.reques... | Module_six_moves_urllib_request |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 42940,
"end": 43169
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("NOT_RELEVANT", "PERSONAL_PREFERENCE", "TOO_GENERAL", "TOO_SPECIFIC")
| TopicSuggestionDeclineReason |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-bm25/llama_index/retrievers/bm25/base.py | {
"start": 1034,
"end": 9357
} | class ____(BaseRetriever):
r"""
A BM25 retriever that uses the BM25 algorithm to retrieve nodes.
Args:
nodes (List[BaseNode], optional):
The nodes to index. If not provided, an existing BM25 object must be passed.
stemmer (Stemmer.Stemmer, optional):
The stemmer to u... | BM25Retriever |
python | django__django | django/utils/autoreload.py | {
"start": 14771,
"end": 24804
} | class ____(BaseReloader):
def __init__(self):
self.roots = defaultdict(set)
self.processed_request = threading.Event()
self.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 5))
super().__init__()
@cached_property
def client(self):
return pywatchman.clie... | WatchmanReloader |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.