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 | sympy__sympy | sympy/codegen/ast.py | {
"start": 14990,
"end": 16185
} | class ____(AssignmentBase):
"""
Represents variable assignment for code generation.
Parameters
==========
lhs : Expr
SymPy object representing the lhs of the expression. These should be
singular objects, such as one would use in writing code. Notable types
include Symbol, M... | Assignment |
python | takluyver__flit | flit_core/flit_core/config.py | {
"start": 597,
"end": 1580
} | class ____(ValueError):
pass
metadata_list_fields = {
'classifiers',
'requires',
'dev-requires'
}
pep621_allowed_fields = {
'name',
'version',
'description',
'readme',
'requires-python',
'license',
'license-files',
'authors',
'maintainers',
'keywords',
'clas... | ConfigError |
python | getsentry__sentry | tests/sentry/releases/endpoints/test_project_release_details.py | {
"start": 9630,
"end": 11177
} | class ____(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
self.commits = [{"id": "a" * 40}, {"id": "b" * 40}]
self.ref = "master"
self.url = "https://example.com"
self.dateReleased = "1000-10-10T06:06"
def test_simple(self) -> None:
serializer = Rel... | ReleaseSerializerTest |
python | pytorch__pytorch | torch/_inductor/codegen/halide.py | {
"start": 6985,
"end": 16245
} | class ____(OpOverrides):
@staticmethod
def to_dtype(
x,
dtype: torch.dtype,
src_dtype: Optional[torch.dtype] = None,
use_compute_types=True,
):
if dtype == torch.bool:
return f"({x} != 0)"
return f"hl.cast({halide_type(dtype)}, {x})"
@staticme... | HalideOverrides |
python | getsentry__sentry | src/sentry/core/endpoints/scim/utils.py | {
"start": 4598,
"end": 4875
} | class ____(OrganizationSCIMPermission):
scope_map = {
"GET": ["team:read", "team:write", "team:admin"],
"POST": ["team:write", "team:admin"],
"PATCH": ["team:write", "team:admin"],
"DELETE": ["team:admin"],
}
| OrganizationSCIMTeamPermission |
python | pandas-dev__pandas | pandas/tests/tseries/offsets/test_offsets.py | {
"start": 20596,
"end": 26683
} | class ____:
def setup_method(self):
_offset_map.clear()
def test_repr(self):
repr(DateOffset())
repr(DateOffset(2))
repr(2 * DateOffset())
repr(2 * DateOffset(months=2))
def test_mul(self):
assert DateOffset(2) == 2 * DateOffset(1)
assert DateOffset(... | TestDateOffset |
python | joblib__joblib | joblib/externals/loky/backend/context.py | {
"start": 13200,
"end": 14280
} | class ____(LokyContext):
"""Extra context with LokyProcess, which does load the main module
This context is used for compatibility in the case ``cloudpickle`` is not
present on the running system. This permits to load functions defined in
the ``main`` module, using proper safeguards. The declaration of... | LokyInitMainContext |
python | ray-project__ray | python/ray/autoscaler/_private/prom_metrics.py | {
"start": 30,
"end": 11817
} | class ____:
"""Mock metric class to be used in case of prometheus_client import error."""
def set(self, *args, **kwargs):
pass
def observe(self, *args, **kwargs):
pass
def inc(self, *args, **kwargs):
pass
def labels(self, *args, **kwargs):
return self
def cle... | NullMetric |
python | pypa__warehouse | warehouse/admin/views/organizations.py | {
"start": 1627,
"end": 2081
} | class ____(wtforms.Form):
username = wtforms.StringField(
validators=[
wtforms.validators.InputRequired(message="Specify username"),
]
)
role_name = wtforms.SelectField(
choices=[(role.value, role.value) for role in OrganizationRoleType],
coerce=OrganizationRoleTy... | AddOrganizationRoleForm |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/functional_utils.py | {
"start": 14217,
"end": 15696
} | class ____:
"""
This should be equal whenever has_same_metadata would return True
"""
size: tuple[SymIntEqByExpr, ...]
layout: torch.layout
is_sparse: bool
# these are empty when is_sparse
stride: tuple[SymIntEqByExpr, ...] | None
storage_offset: SymIntEqByExpr | None
is_conj: b... | MetadataKey |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/vertex_ai.py | {
"start": 1667,
"end": 4403
} | class ____(BaseTrigger):
"""
Base class for Vertex AI job triggers.
This trigger polls the Vertex AI job and checks its status.
In order to use it properly, you must:
- implement the following methods `_wait_job()`.
- override required `job_type_verbose_name` attribute to provide meaningful me... | BaseVertexAIJobTrigger |
python | huggingface__transformers | src/transformers/models/dinov3_convnext/modeling_dinov3_convnext.py | {
"start": 10115,
"end": 11753
} | class ____(DINOv3ConvNextPreTrainedModel, BackboneMixin):
config: DINOv3ConvNextConfig
def __init__(self, config: DINOv3ConvNextConfig):
super().__init__(config)
super()._init_backbone(config)
self.num_features = [config.num_channels] + list(config.hidden_sizes)
self.stages = ... | DINOv3ConvNextBackbone |
python | great-expectations__great_expectations | docs/docusaurus/docs/reference/learn/data_quality_use_cases/freshness_resources/freshness_workflow.py | {
"start": 1328,
"end": 2183
} | class ____(gxe.ExpectColumnMaxToBeBetween):
"""Custom Expectation class to validate the freshness of sensor readings in the database."""
column: str = "created_at"
min_value: datetime.datetime = datetime.datetime.now() - datetime.timedelta(
minutes=5
)
description: str = "New sensor reading... | ExpectSensorDataToBeFresh |
python | django__django | tests/queries/tests.py | {
"start": 119649,
"end": 120477
} | class ____(TestCase):
def test_primary_key(self):
custom = CustomPk.objects.create(name="pk")
null = Related.objects.create()
notnull = Related.objects.create(custom=custom)
self.assertSequenceEqual(
Related.objects.filter(custom__isnull=False), [notnull]
)
... | IsNullTests |
python | numpy__numpy | numpy/f2py/tests/test_data.py | {
"start": 2523,
"end": 2895
} | class ____(util.F2PyTest):
sources = [util.getpath("tests", "src", "crackfortran", "data_with_comments.f")]
# For gh-23276
def test_data_stmts(self):
assert len(self.module.mycom.mytab) == 3
assert self.module.mycom.mytab[0] == 0
assert self.module.mycom.mytab[1] == 4
assert... | TestDataWithCommentsF77 |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/take_while_test.py | {
"start": 5194,
"end": 6270
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_dataset(self, num_elements, upper_bound, options=None):
dataset = dataset_ops.Dataset.range(num_elements)
dataset = dataset.take_while(predicate=lambda x: x < upper_bound)
if options:
... | TakeWhileCheckpointTest |
python | huggingface__transformers | src/transformers/models/esm/modeling_esmfold.py | {
"start": 39170,
"end": 40215
} | class ____(nn.Module):
def __init__(self, sequence_state_dim, inner_dim, pairwise_state_dim):
super().__init__()
self.layernorm = nn.LayerNorm(sequence_state_dim)
self.proj = nn.Linear(sequence_state_dim, inner_dim * 2, bias=True)
self.o_proj = nn.Linear(2 * inner_dim, pairwise_stat... | EsmFoldSequenceToPair |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/config.py | {
"start": 4089,
"end": 7303
} | class ____(graphene.Interface):
message = graphene.NonNull(graphene.String)
path = non_null_list(graphene.String)
stack = graphene.NonNull(GrapheneEvaluationStack)
reason = graphene.NonNull(GrapheneEvaluationErrorReason)
class Meta:
name = "PipelineConfigValidationError" # back-compat
... | GrapheneConfigValidationError |
python | huggingface__transformers | src/transformers/models/pvt_v2/modeling_pvt_v2.py | {
"start": 2546,
"end": 3671
} | class ____(nn.Module):
"""Image to Patch Embedding"""
def __init__(self, config: PvtV2Config, layer_idx: int):
super().__init__()
patch_size = config.patch_sizes[layer_idx]
patch_size = (patch_size, patch_size) if isinstance(patch_size, int) else patch_size
stride = config.strid... | PvtV2OverlapPatchEmbeddings |
python | huggingface__transformers | tests/models/prophetnet/test_tokenization_prophetnet.py | {
"start": 1084,
"end": 7893
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "microsoft/prophetnet-large-uncased"
tokenizer_class = ProphetNetTokenizer
test_rust_tokenizer = False
@classmethod
def setUpClass(cls):
super().setUpClass()
vocab_tokens = [
"[UNK]",
... | ProphetNetTokenizationTest |
python | jupyterlab__jupyterlab | jupyterlab/labapp.py | {
"start": 7679,
"end": 8983
} | class ____(JupyterApp):
version = version
description = """
Clean the JupyterLab application
This will clean the app directory by removing the `staging` directories.
Optionally, the `extensions`, `settings`, and/or `static` directories,
or the entire contents of the app directory, can also be r... | LabCleanApp |
python | automl__auto-sklearn | autosklearn/pipeline/components/regression/gaussian_process.py | {
"start": 370,
"end": 2850
} | class ____(AutoSklearnRegressionAlgorithm):
def __init__(self, alpha, thetaL, thetaU, random_state=None):
self.alpha = alpha
self.thetaL = thetaL
self.thetaU = thetaU
self.random_state = random_state
self.estimator = None
def fit(self, X, y):
import sklearn.gauss... | GaussianProcess |
python | weaviate__weaviate-python-client | weaviate/proto/v1/v4216/v1/file_replication_pb2_grpc.py | {
"start": 2198,
"end": 5815
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def PauseFileActivity(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')... | FileReplicationServiceServicer |
python | huggingface__transformers | tests/cli/test_serve.py | {
"start": 30722,
"end": 32788
} | class ____:
"""
Mixin class for the Completions API tests, to seamlessly replicate tests across the two versions of the API
(`generate` and `continuous_batching`).
"""
@retry
def run_server(self, request):
client = OpenAI(base_url=f"http://localhost:{self.port}/v1", api_key="<KEY>")
... | ServeResponsesMixin |
python | getsentry__sentry | src/sentry/issue_detection/detectors/io_main_thread_detector.py | {
"start": 829,
"end": 4321
} | class ____(PerformanceDetector):
SPAN_PREFIX: str # abstract
group_type: type[GroupType] # abstract
def _is_io_on_main_thread(self, span: Span) -> bool:
raise NotImplementedError
def _fingerprint(self, span_list: list[Span]) -> str:
raise NotImplementedError
def __init__(self, s... | BaseIOMainThreadDetector |
python | astropy__astropy | astropy/io/fits/tests/conftest.py | {
"start": 1883,
"end": 6139
} | class ____:
def setup_method(self):
self.data_dir = os.path.join(os.path.dirname(__file__), "data")
self.temp_dir = tempfile.mkdtemp(prefix="fits-test-")
self.home_is_data = False
self.home_is_temp = False
self.temp_files_used = set()
self.use_pathlib = False
... | FitsTestCase |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/orm_config_constructs.py | {
"start": 350,
"end": 1037
} | class ____(Base):
__tablename__ = "User"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
@validates("name", include_removes=True)
def validate_name(self, name: str) -> str:
"""test #8577"""
return name + "hi"
# test #9536
_password: Mapped[str] = mapped... | User |
python | huggingface__transformers | src/transformers/models/siglip2/modular_siglip2.py | {
"start": 9443,
"end": 11550
} | class ____(SiglipVisionTransformer):
def __init__(self, config: Siglip2VisionConfig):
super().__init__(config)
# Update: add `spatial_shapes` and `attention_mask`
def forward(
self,
pixel_values: torch.FloatTensor,
attention_mask: torch.Tensor,
spatial_shapes: torch.... | Siglip2VisionTransformer |
python | pypa__setuptools | setuptools/_distutils/errors.py | {
"start": 2130,
"end": 2309
} | class ____(DistutilsError):
"""For errors that can be definitely blamed on the setup script,
such as invalid keyword arguments to 'setup()'."""
pass
| DistutilsSetupError |
python | huggingface__transformers | src/transformers/models/rwkv/modeling_rwkv.py | {
"start": 18826,
"end": 19793
} | 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... | RwkvCausalLMOutput |
python | cython__cython | tests/run/py3k_super.py | {
"start": 3073,
"end": 3239
} | class ____:
"""
>>> obj = E()
>>> obj.method()().__name__
'E'
"""
def method(self):
def inner(): return __class__
return inner
| E |
python | jazzband__django-waffle | waffle/models.py | {
"start": 699,
"end": 3683
} | class ____(models.Model):
SINGLE_CACHE_KEY = ''
ALL_CACHE_KEY = ''
class Meta:
abstract = True
def __str__(self) -> str:
return self.name
def natural_key(self) -> tuple[str]:
return (self.name,)
@classmethod
def _cache_key(cls, name: str) -> str:
return ke... | BaseModel |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_pretty.py | {
"start": 3519,
"end": 3604
} | class ____:
def _repr_pretty_(self, p, cycle):
p.text("Dummy1(...)")
| Dummy1 |
python | tensorflow__tensorflow | tensorflow/core/function/polymorphism/function_type_test.py | {
"start": 19900,
"end": 24500
} | class ____(test.TestCase):
def test_same_type(self):
foo_type = function_type.FunctionType([
function_type.Parameter("x", function_type.Parameter.POSITIONAL_ONLY,
False, trace_type.from_value(1))
])
self.assertEqual(foo_type, foo_type)
self.assertTrue(foo_type.... | TypeHierarchyTest |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_grid.py | {
"start": 9772,
"end": 28347
} | class ____:
def test_should_response_200(self, test_client):
with assert_queries_count(5):
response = test_client.get(f"/grid/runs/{DAG_ID}")
assert response.status_code == 200
assert response.json() == [
GRID_RUN_1,
GRID_RUN_2,
]
@pytest.mark... | TestGetGridDataEndpoint |
python | pandas-dev__pandas | pandas/core/indexers/objects.py | {
"start": 17065,
"end": 21787
} | class ____(BaseIndexer):
"""Calculate bounds to compute groupby rolling, mimicking df.groupby().rolling()"""
def __init__(
self,
index_array: np.ndarray | None = None,
window_size: int | BaseIndexer = 0,
groupby_indices: dict | None = None,
window_indexer: type[BaseIndex... | GroupbyIndexer |
python | django__django | tests/model_forms/models.py | {
"start": 12621,
"end": 13153
} | class ____(models.Model):
title = models.CharField(max_length=30)
image = models.FileField(storage=temp_storage, upload_to="tests")
# Support code for the tests; this keeps track of how many times save()
# gets called on each instance.
def __init__(self, *args, **kwargs):
super().__init__(*... | Photo |
python | dateutil__dateutil | src/dateutil/parser/_parser.py | {
"start": 8649,
"end": 13451
} | class ____(object):
"""
Class which handles what inputs are accepted. Subclass this to customize
the language and acceptable values for each parameter.
:param dayfirst:
Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the day (``True``) or month (``... | parserinfo |
python | Lightning-AI__lightning | src/lightning/pytorch/loops/fit_loop.py | {
"start": 2120,
"end": 2370
} | class ____:
NONE = "none"
RESTARTED_ON_EPOCH_START = "restarted_on_epoch_start"
RESTARTED_MID_EPOCH = "restarted_mid_epoch"
RESTARTED_ON_EPOCH_END = "restarted_on_epoch_end"
RESUMED_ON_EPOCH_END = "resumed_on_epoch_end"
| RestartStage |
python | jazzband__django-oauth-toolkit | oauth2_provider/contrib/rest_framework/permissions.py | {
"start": 2558,
"end": 3174
} | class ____(TokenHasScope):
"""
The request is authenticated as a user and the token used has the right scope
"""
def get_scopes(self, request, view):
try:
view_scopes = super().get_scopes(request, view)
except ImproperlyConfigured:
view_scopes = []
if re... | TokenHasResourceScope |
python | nedbat__coveragepy | tests/test_process.py | {
"start": 57622,
"end": 59958
} | class ____(CoverageTest):
"""Test that we can measure coverage in subprocesses."""
@pytest.mark.parametrize(
"fname",
[
base + suffix
for base, suffix in itertools.product(
["exec", "spawn"],
["l", "le", "lp", "lpe", "v", "ve", "vp", "vpe"... | ExecvTest |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 37284,
"end": 43539
} | class ____:
result_type = namedtuple('result_type',
['nocast', 'casted'])
helper_lambdas = {
'zero': lambda dtype: 0,
'min': lambda dtype: np.iinfo(dtype).min,
'neg_min': lambda dtype: -np.iinfo(dtype).min,
'min-zero': lambda dtype: (np.iinfo(dtype).min, 0),
'... | TestDivisionIntegerOverflowsAndDivideByZero |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0138_remove_old_fields.py | {
"start": 121,
"end": 1367
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0137_use_generic_root_selector"),
]
operations = [
migrations.RemoveField(
model_name="addonsconfig",
name="doc_diff_root_selector",
),
migrations.RemoveF... | Migration |
python | apache__airflow | providers/apprise/src/airflow/providers/apprise/notifications/apprise.py | {
"start": 1163,
"end": 4137
} | class ____(BaseNotifier):
r"""
Apprise BaseNotifier.
:param body: Specify the message body
:param title: Specify the message title. This field is complete optional
:param notify_type: Specify the message type (default=info). Possible values are "info",
"success", "failure", and "warning"
... | AppriseNotifier |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-elasticsearch/llama_index/vector_stores/elasticsearch/base.py | {
"start": 3799,
"end": 21867
} | class ____(BasePydanticVectorStore):
"""
Elasticsearch vector store.
Args:
index_name: Name of the Elasticsearch index.
es_client: Optional. Pre-existing AsyncElasticsearch client.
es_url: Optional. Elasticsearch URL.
es_cloud_id: Optional. Elasticsearch cloud ID.
es... | ElasticsearchStore |
python | django__django | tests/queries/models.py | {
"start": 13860,
"end": 13985
} | class ____(models.Model):
title = models.TextField()
paragraph = models.ForeignKey("Paragraph", models.CASCADE)
| Chapter |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_legend.py | {
"start": 15781,
"end": 65035
} | class ____:
# Tests the legend function for figure
def test_legend_handle_label(self):
fig, ax = plt.subplots()
lines = ax.plot(range(10))
with mock.patch('matplotlib.legend.Legend') as Legend:
fig.legend(lines, ['hello world'])
Legend.assert_called_with(fig, lines, [... | TestLegendFigureFunction |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 239657,
"end": 239921
} | class ____(TestCase):
def test_arrays_not_hashable(self):
x = np.ones(3)
assert_raises(TypeError, hash, x)
def test_collections_hashable(self):
x = np.array([])
assert_(not isinstance(x, collections.abc.Hashable))
| TestHashing |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_managed_kafka.py | {
"start": 5429,
"end": 6488
} | class ____:
@mock.patch(MANAGED_KAFKA_PATH.format("types.Cluster.to_dict"))
@mock.patch(MANAGED_KAFKA_PATH.format("ManagedKafkaHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = ManagedKafkaGetClusterOperator(
task_id=TASK_ID,
cluster_id=TEST_CLUSTER_ID,
... | TestManagedKafkaGetClusterOperator |
python | ZoranPandovski__al-go-rithms | sort/radix_sort/python/radixsort.py | {
"start": 78,
"end": 1845
} | class ____:
def __init__(self,a):
self.a = a
def result(self):
maxElement = max(self.a)
exp = 1
while int(maxElement/exp) > 0:
self.countingsort(exp)
exp *= 10
return self.a
def countingsort(self,exp):
position = [0]*(10)
b =... | RadixSort |
python | plotly__plotly.py | plotly/graph_objs/histogram2dcontour/contours/_labelfont.py | {
"start": 233,
"end": 10116
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram2dcontour.contours"
_path_str = "histogram2dcontour.contours.labelfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Labelfont |
python | langchain-ai__langchain | libs/partners/prompty/langchain_prompty/core.py | {
"start": 1347,
"end": 5650
} | class ____(BaseModel):
"""Base Prompty model."""
# Metadata
name: str = Field(default="")
description: str = Field(default="")
authors: list[str] = Field(default=[])
tags: list[str] = Field(default=[])
version: str = Field(default="")
base: str = Field(default="")
basePrompty: Promp... | Prompty |
python | joke2k__faker | faker/providers/internet/fi_FI/__init__.py | {
"start": 46,
"end": 332
} | class ____(InternetProvider):
free_email_domains = (
"gmail.com",
"googlemail.com",
"hotmail.com",
"suomi24.fi",
"kolumbus.fi",
"luukku.com",
"surffi.net",
)
tlds = ("com", "com", "com", "fi", "fi", "net", "org")
| Provider |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/struct_store/sql_query.py | {
"start": 23030,
"end": 25039
} | class ____(BaseSQLTableQueryEngine):
"""SQL Table retriever query engine."""
def __init__(
self,
sql_database: SQLDatabase,
table_retriever: ObjectRetriever[SQLTableSchema],
rows_retrievers: Optional[dict[str, BaseRetriever]] = None,
cols_retrievers: Optional[dict[str, d... | SQLTableRetrieverQueryEngine |
python | ethereum__web3.py | web3/geth.py | {
"start": 708,
"end": 1202
} | class ____(Module):
"""
https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-txpool
"""
is_async = False
content: Method[Callable[[], TxPoolContent]] = Method(
RPC.txpool_content,
is_property=True,
)
inspect: Method[Callable[[], TxPoolInspect]] = Method(
RPC... | GethTxPool |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ViewBox/ViewBox.py | {
"start": 377,
"end": 875
} | class ____(object):
def __init__(self):
self._items = []
def append(self, obj):
#Add backwards to iterate backwards (to make iterating more efficient on removal).
self._items.insert(0, weakref.ref(obj))
def __iter__(self):
i = len(self._items)-1
while i >= 0:
... | WeakList |
python | doocs__leetcode | solution/1400-1499/1469.Find All The Lonely Nodes/Solution.py | {
"start": 192,
"end": 663
} | class ____:
def getLonelyNodes(self, root: Optional[TreeNode]) -> List[int]:
def dfs(root: Optional[TreeNode]):
if root is None or root.left == root.right:
return
if root.left is None:
ans.append(root.right.val)
if root.right is None:
... | Solution |
python | PyCQA__pylint | tests/functional/r/redefined/redefined_slots.py | {
"start": 193,
"end": 313
} | class ____:
"""Class defining the `a`, `b` & `deque.__name__` slots"""
__slots__ = ("a", "b", deque.__name__)
| Base |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 2197,
"end": 2727
} | class ____(BaseClass):
def with_comments(self):
super(
# super helpful comment
ClassForCommentEnthusiasts,
self
).f()
super(
ClassForCommentEnthusiasts,
# even more helpful comment
self
).f()
super(
... | ClassForCommentEnthusiasts |
python | kubernetes-client__python | kubernetes/client/models/v1alpha1_group_version_resource.py | {
"start": 383,
"end": 5118
} | 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... | V1alpha1GroupVersionResource |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_gtin_variable_measure_trade_item.py | {
"start": 2075,
"end": 4799
} | class ____(ColumnMapExpectation):
"""Expect column values to be GTIN variable measure trade item."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_variable_measure_... | ExpectColumnValuesToBeGtinVariableMeasureTradeItem |
python | jazzband__django-waffle | test_app/models.py | {
"start": 720,
"end": 809
} | class ____(AbstractBaseSample):
"""Demonstrates custom switch behavior."""
| CustomSample |
python | pypa__warehouse | tests/unit/metrics/test_event_handlers.py | {
"start": 3930,
"end": 7283
} | class ____:
def test_without_timings(self, pyramid_request, metrics):
on_new_response(pretend.stub(request=pyramid_request))
assert metrics.timing.calls == []
def test_without_route(self, pyramid_request, metrics):
response = pretend.stub(status_code="200")
new_request = datet... | TestOnNewResponse |
python | doocs__leetcode | solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution.py | {
"start": 0,
"end": 135
} | class ____:
def missingNumber(self, arr: List[int]) -> int:
return (arr[0] + arr[-1]) * (len(arr) + 1) // 2 - sum(arr)
| Solution |
python | cherrypy__cherrypy | cherrypy/test/test_core.py | {
"start": 28903,
"end": 30247
} | class ____(helper.CPWebCase):
@staticmethod
def setup_server():
def break_header():
# Add a header after finalize that is invalid
cherrypy.serving.response.header_list.append((2, 3))
cherrypy.tools.break_header = cherrypy.Tool(
'on_end_resource',
... | ErrorTests |
python | Lightning-AI__lightning | src/lightning/fabric/wrappers.py | {
"start": 1790,
"end": 3762
} | class ____:
def __init__(self, optimizer: Optimizer, strategy: Strategy, callbacks: Optional[list[Callable]] = None) -> None:
"""FabricOptimizer is a thin wrapper around the :class:`~torch.optim.Optimizer` that delegates the optimizer
step calls to the strategy.
The underlying wrapped optim... | _FabricOptimizer |
python | ray-project__ray | rllib/core/models/tests/test_cnn_encoders.py | {
"start": 337,
"end": 3939
} | class ____(unittest.TestCase):
def test_cnn_encoders(self):
"""Tests building CNN encoders properly and checks for correct architecture."""
# Loop through permutations of hyperparameters.
inputs_dimss = [
[96, 96, 3],
[96, 96, 1],
[84, 84, 3],
... | TestCNNEncoders |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1570276,
"end": 1570929
} | class ____(OffsetDef):
"""
ValueDefnumber schema wrapper.
Definition object for a constant value (primitive value or gradient definition) of an
encoding channel.
Parameters
----------
value : float
A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient
... | ValueDefnumber |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/multiple_sources.py | {
"start": 207,
"end": 2597
} | class ____:
def __init__(self, id) -> None:
self.id = id
def send(self, vc) -> None: ...
@classmethod
def get(cls, id) -> "Node":
return cls(id)
def user_controlled_input():
return "evil"
def permissive_context():
return 0
def combine_tainted_user_and_dangerous_vc():
... | Node |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-database/llama_index/tools/database/base.py | {
"start": 449,
"end": 4829
} | class ____(BaseToolSpec, BaseReader):
"""
Simple Database tool.
Concatenates each row into Document used by LlamaIndex.
Args:
sql_database (Optional[SQLDatabase]): SQL database to use,
including table names to specify.
See :ref:`Ref-Struct-Store` for more details.
... | DatabaseToolSpec |
python | getsentry__sentry | tests/sentry/sentry_apps/api/endpoints/test_sentry_app_installation_external_requests.py | {
"start": 205,
"end": 3432
} | class ____(APITestCase):
def setUp(self) -> None:
self.user = self.create_user(email="boop@example.com")
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(organization=self.org)
self.sentry_app = self.create_sentry_app(
name="Testin"... | SentryAppInstallationExternalRequestsEndpointTest |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/sensor_tests/test_business_logic.py | {
"start": 11202,
"end": 15734
} | class ____:
"""Test processing of sensor data structures.
This class tests pure functions and domain model functionality
without requiring external dependencies.
"""
def test_sensor_creation_with_all_fields(self, snapshot):
"""Test creating sensor with all possible fields."""
senso... | TestSensorDataProcessing |
python | numpy__numpy | numpy/f2py/tests/test_block_docstring.py | {
"start": 101,
"end": 584
} | class ____(util.F2PyTest):
sources = [util.getpath("tests", "src", "block_docstring", "foo.f")]
@pytest.mark.skipif(sys.platform == "win32",
reason="Fails with MinGW64 Gfortran (Issue #9673)")
@pytest.mark.xfail(IS_PYPY,
reason="PyPy cannot modify tp_doc after... | TestBlockDocString |
python | bokeh__bokeh | src/bokeh/core/property/container.py | {
"start": 10571,
"end": 10991
} | class ____(Dict):
""" Accept RelativeDelta dicts for time delta values.
"""
def __init__(self, default={}, *, help: str | None = None) -> None:
keys = Enum("years", "months", "days", "hours", "minutes", "seconds", "microseconds")
values = Int
super().__init__(keys, values, default=... | RelativeDelta |
python | ipython__ipython | IPython/core/formatters.py | {
"start": 30278,
"end": 30841
} | class ____(BaseFormatter):
"""A Javascript formatter.
To define the callables that compute the Javascript representation of
your objects, define a :meth:`_repr_javascript_` method or use the
:meth:`for_type` or :meth:`for_type_by_name` methods to register functions
that handle this.
The return... | JavascriptFormatter |
python | mwaskom__seaborn | seaborn/regression.py | {
"start": 2070,
"end": 34326
} | class ____(_LinearPlotter):
"""Plotter for numeric independent variables with regression model.
This does the computations and drawing for the `regplot` function, and
is thus also used indirectly by `lmplot`.
"""
def __init__(self, x, y, data=None, x_estimator=None, x_bins=None,
x_... | _RegressionPlotter |
python | cython__cython | Cython/Compiler/Tests/TestBuffer.py | {
"start": 1574,
"end": 4144
} | class ____(CythonTest):
# Tests the full parsing of the options within the brackets
def nonfatal_error(self, error):
# We're passing self as context to transform to trap this
self.error = error
self.assertTrue(self.expect_error)
def parse_opts(self, opts, expect_error=False):
... | TestBufferOptions |
python | kamyu104__LeetCode-Solutions | Python/maximum-score-of-a-good-subarray.py | {
"start": 744,
"end": 1423
} | class ____(object):
def maximumScore(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def score(nums, k):
prefix = [nums[k]]*(k+1)
for i in reversed(xrange(k)):
prefix[i] = min(prefix[i+1], nums[i])
... | Solution2 |
python | django-debug-toolbar__django-debug-toolbar | tests/forms.py | {
"start": 71,
"end": 220
} | class ____(forms.Form):
user = forms.ModelChoiceField(queryset=User.objects.all())
def __repr__(self):
return str(self)
| TemplateReprForm |
python | django__django | tests/admin_custom_urls/models.py | {
"start": 1451,
"end": 1524
} | class ____(models.Model):
name = models.CharField(max_length=20)
| Person |
python | python-openxml__python-docx | src/docx/oxml/text/run.py | {
"start": 793,
"end": 6010
} | class ____(BaseOxmlElement):
"""`<w:r>` element, containing the properties and text for a run."""
add_br: Callable[[], CT_Br]
add_tab: Callable[[], CT_TabStop]
get_or_add_rPr: Callable[[], CT_RPr]
_add_drawing: Callable[[], CT_Drawing]
_add_t: Callable[..., CT_Text]
rPr: CT_RPr | None = Ze... | CT_R |
python | mamba-org__mamba | micromamba/tests/test_update.py | {
"start": 8661,
"end": 19741
} | class ____:
current_root_prefix = os.environ["MAMBA_ROOT_PREFIX"]
current_prefix = os.environ["CONDA_PREFIX"]
env_name = helpers.random_string()
root_prefix = os.path.expanduser(os.path.join("~", "tmproot" + helpers.random_string()))
prefix = os.path.join(root_prefix, "envs", env_name)
@static... | TestUpdateConfig |
python | tensorflow__tensorflow | tensorflow/compiler/tests/image_ops_test.py | {
"start": 11041,
"end": 14495
} | class ____(xla_test.XLATestCase):
def _adjust_saturation(self, image, saturation_factor):
image = ops.convert_to_tensor(image, name="image")
orig_dtype = image.dtype
flt_image = image_ops.convert_image_dtype(image, dtypes.float32)
with self.test_scope():
saturation_adjusted_image = gen_image_op... | AdjustSaturationTest |
python | keras-team__keras | keras/src/distribution/distribution_lib.py | {
"start": 20028,
"end": 28832
} | class ____(Distribution):
"""Distribution that shards model variables.
Compare to `DataParallel` which replicates the variables across all devices,
`ModelParallel` allows you to shard variables in addition to the input data.
To construct a `ModelParallel` distribution, you need to provide a
`Devic... | ModelParallel |
python | charliermarsh__ruff | python/ruff-ecosystem/ruff_ecosystem/projects.py | {
"start": 5071,
"end": 5164
} | class ____(Enum):
check = "check"
format = "format"
@dataclass(frozen=True)
| RuffCommand |
python | ray-project__ray | python/ray/tests/test_placement_group.py | {
"start": 19691,
"end": 23179
} | class ____:
def test_strategy_validation(self):
"""Test strategy validation when creating a placement group."""
# Valid strategies should not raise an exception.
for strategy in VALID_PLACEMENT_GROUP_STRATEGIES:
validate_placement_group(bundles=[{"CPU": 1}], strategy=strategy)
... | TestPlacementGroupValidation |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 348728,
"end": 349395
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("avatar_url", "date", "email", "name", "user")
avatar_url = sgqlc.types.Field(
sgqlc.types.non_null(URI),
graphql_name="avatarUrl",
args=sgqlc.types.ArgDic... | GitActor |
python | huggingface__transformers | src/transformers/models/internvl/video_processing_internvl.py | {
"start": 1144,
"end": 1256
} | class ____(VideosKwargs, total=False):
initial_shift: Union[bool, float, int]
| InternVLVideoProcessorInitKwargs |
python | python-visualization__folium | folium/features.py | {
"start": 40869,
"end": 45938
} | class ____(MacroElement):
"""Base class for GeoJsonTooltip and GeoJsonPopup.
:meta private:
"""
base_template = """
function(layer){
let div = L.DomUtil.create('div');
{% if this.fields %}
let handleObject = feature => {
if (feature === null) {
return '';
} ... | GeoJsonDetail |
python | mlflow__mlflow | mlflow/data/spark_dataset.py | {
"start": 867,
"end": 16626
} | class ____(Dataset, PyFuncConvertibleDatasetMixin):
"""
Represents a Spark dataset (e.g. data derived from a Spark Table / file directory or Delta
Table) for use with MLflow Tracking.
"""
def __init__(
self,
df: "pyspark.sql.DataFrame",
source: DatasetSource,
targets... | SparkDataset |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/overrides.py | {
"start": 890,
"end": 1092
} | class ____(B):
q: str = "q"
def __init__(self, arg):
super(B, self).__init__(arg)
def methodA(self, arg):
pass
@classmethod
def classMethod(cls, arg):
pass
| C |
python | django-import-export__django-import-export | tests/core/tests/test_widgets.py | {
"start": 3406,
"end": 3684
} | class ____(TestCase):
date = date(10, 8, 2)
target_dt = "02.08.0010"
format = "%d.%m.%Y"
def test_format_datetime_gte_django4(self):
self.assertEqual(
self.target_dt, widgets.format_datetime(self.date, self.format)
)
| FormatDatetimeTest |
python | pypa__pip | src/pip/_internal/commands/install.py | {
"start": 2180,
"end": 30545
} | class ____(RequirementCommand):
"""
Install packages from:
- PyPI (and other indexes) using requirement specifiers.
- VCS project urls.
- Local project directories.
- Local or remote source archives.
pip also supports installing from "requirements files", which provide
an easy way to s... | InstallCommand |
python | spack__spack | lib/spack/spack/repo.py | {
"start": 10127,
"end": 10870
} | class ____(types.ModuleType):
"""Allow lazy loading of modules."""
def __init__(self, namespace):
super().__init__(namespace)
self.__file__ = "(spack namespace)"
self.__path__ = []
self.__name__ = namespace
self.__package__ = namespace
self.__modules = {}
de... | SpackNamespace |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/tests/unit_tests/test_checks/test_packaging.py | {
"start": 5036,
"end": 5792
} | class ____:
def test_fail_when_license_is_missing(self, mocker):
# Arrange
connector = mocker.MagicMock(metadata={})
# Act
result = packaging.CheckConnectorLicense()._run(connector)
# Assert
assert result.status == CheckStatus.FAILED
assert "License is missi... | TestCheckConnectorLicense |
python | django__django | tests/contenttypes_tests/test_views.py | {
"start": 5087,
"end": 8767
} | class ____(TestCase):
def setUp(self):
Site.objects.clear_cache()
@classmethod
def setUpTestData(cls):
cls.site_2 = Site.objects.create(domain="example2.com", name="example2.com")
cls.site_3 = Site.objects.create(domain="example3.com", name="example3.com")
@mock.patch("django.a... | ContentTypesViewsSiteRelTests |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 93617,
"end": 95903
} | class ____(test.TestCase):
# AddN special-cases adding the first M inputs to make (N - M) divisible by 8,
# after which it adds the remaining (N - M) tensors 8 at a time in a loop.
# Test N in [1, 10] so we check each special-case from 1 to 9 and one
# iteration of the loop.
_MAX_N = 10
def _supported_type... | AddNTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassConverter3.py | {
"start": 286,
"end": 462
} | class ____[T](ModelBase):
data: set[T] = model_field(converter=set)
x = DC1([1, 2])
reveal_type(x, expected_text="DC1[int]")
reveal_type(x.data, expected_text="set[int]")
| DC1 |
python | pandas-dev__pandas | pandas/io/sql.py | {
"start": 32785,
"end": 52006
} | class ____(PandasObject):
"""
For mapping Pandas tables to SQL tables.
Uses fact that table is reflected by SQLAlchemy to
do better type conversions.
Also holds various flags needed to avoid having to
pass them between functions all the time.
"""
# TODO: support for multiIndex
def ... | SQLTable |
python | scikit-learn__scikit-learn | sklearn/utils/_testing.py | {
"start": 42609,
"end": 43860
} | class ____:
"""Minimal regressor implementation without inheriting from BaseEstimator.
This estimator should be tested with:
* `check_estimator` in `test_estimator_checks.py`;
* within a `Pipeline` in `test_pipeline.py`;
* within a `SearchCV` in `test_search.py`.
"""
def __init__(self, pa... | MinimalRegressor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.