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 | huggingface__transformers | src/transformers/models/speecht5/modeling_speecht5.py | {
"start": 57999,
"end": 59317
} | class ____(SpeechT5PreTrainedModel):
"""
Wrapper around SpeechT5Encoder that applies SpeechT5TextEncoderPrenet to convert the input_ids to hidden features.
"""
def __init__(self, config: SpeechT5Config):
super().__init__(config)
self.prenet = SpeechT5TextEncoderPrenet(config)
se... | SpeechT5EncoderWithTextPrenet |
python | tensorflow__tensorflow | tensorflow/lite/python/lite_test.py | {
"start": 2667,
"end": 3109
} | class ____(LiteTest):
def assertValidDebugInfo(self, debug_info):
"""Verify the DebugInfo is valid."""
file_names = set()
for file_path in debug_info.files:
file_names.add(os.path.basename(file_path))
# To make the test independent on how the nodes are created, we only assert
# the name of ... | TestModels |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 49568,
"end": 49812
} | class ____(Response):
"""
Response of events.download_task_log endpoint.
"""
_service = "events"
_action = "download_task_log"
_version = "2.13"
_schema = {"definitions": {}, "type": "string"}
| DownloadTaskLogResponse |
python | ansible__ansible | packaging/release.py | {
"start": 11527,
"end": 48273
} | class ____(enum.Enum):
"""How to handle the ansible-core version."""
DEFAULT = enum.auto()
"""Do not allow development versions. Do not allow post release versions."""
STRIP_POST = enum.auto()
"""Do not allow development versions. Strip the post release from the version if present."""
REQUIRE_P... | VersionMode |
python | tensorflow__tensorflow | tensorflow/lite/tools/flatbuffer_utils_test.py | {
"start": 11100,
"end": 12419
} | class ____(test_util.TensorFlowTestCase):
op: schema.Operator
op_t: schema.OperatorT
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.op = test_utils.build_operator_with_options()
cls.op_t = schema.OperatorT.InitFromObj(cls.op)
def test_get_options(self):
ty = schema.StableHLOComp... | GetOptionsTest |
python | pytorch__pytorch | test/distributed/_tools/test_mod_tracker.py | {
"start": 270,
"end": 7020
} | class ____(TestCase):
# "https://github.com/pytorch/pytorch/issues/127112
@xfailIfTorchDynamo
def test_module_hierarchy(self):
seen_fw = []
seen_bw = []
class Foo(torch.nn.Module):
def forward(self, x):
x = x["a"].relu_()
seen_fw.append((c... | TestModTracker |
python | pytorch__pytorch | test/inductor/test_select_algorithm.py | {
"start": 2288,
"end": 18272
} | class ____(TestCase):
def setUp(self):
super().setUp()
if not is_big_gpu():
return self.skipTest("Need a big GPU to run max_autotune=True")
# Clear preprocessing functions to ensure clean state
select_algorithm.clear_preprocessing_fns()
@patches
def test_linear_r... | TestSelectAlgorithm |
python | openai__openai-python | tests/test_client.py | {
"start": 1110,
"end": 1734
} | class ____(Protocol):
request: httpx.Request
def _get_params(client: BaseClient[Any, Any]) -> dict[str, str]:
request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
url = httpx.URL(request.url)
return dict(url.params)
def _low_retry_timeout(*_args: Any, **_kwargs: Any) -> flo... | MockRequestCall |
python | cython__cython | Cython/Compiler/TypeSlots.py | {
"start": 16351,
"end": 16544
} | class ____(GCDependentSlot):
def slot_code(self, scope):
if scope.needs_tp_clear():
return GCDependentSlot.slot_code(self, scope)
return "0"
| GCClearReferencesSlot |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 943310,
"end": 946758
} | class ____(Predicate):
"""
FieldEqualPredicate schema wrapper.
Parameters
----------
equal : str, bool, dict, float, :class:`ExprRef`, :class:`DateTime`
The value that the field should be equal to.
field : str, :class:`FieldName`
Field to be tested.
timeUnit : dict, :class:`... | FieldEqualPredicate |
python | mitmproxy__pdoc | pdoc/__init__.py | {
"start": 659,
"end": 5080
} | class ____:
"""🐕"""
name: str
"""The name of our dog."""
friends: list["Dog"]
"""The friends of our dog."""
def __init__(self, name: str):
"""Make a Dog without any friends (yet)."""
self.name = name
self.friends = []
def bark(self, loud: bool = True):
"""*... | Dog |
python | apache__airflow | dev/airflow_perf/dags/elastic_dag.py | {
"start": 4004,
"end": 6122
} | class ____(Enum):
"""
Define shape of the Dag that will be used for testing.
"""
NO_STRUCTURE = "no_structure"
LINEAR = "linear"
BINARY_TREE = "binary_tree"
STAR = "star"
GRID = "grid"
DAG_PREFIX = os.environ.get("PERF_DAG_PREFIX", "perf_scheduler")
DAG_COUNT = int(os.environ["PERF_DA... | DagShape |
python | getlogbook__logbook | src/logbook/more.py | {
"start": 14822,
"end": 16786
} | class ____(Handler):
"""A handler that deduplicates log messages.
It emits each unique log record once, along with the number of times it was
emitted.
Example:::
with logbook.more.DedupHandler():
logbook.error("foo")
logbook.error("bar")
logbook.error("foo")... | DedupHandler |
python | huggingface__transformers | tests/models/pvt/test_image_processing_pvt.py | {
"start": 1005,
"end": 2709
} | 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,
do_normalize=True,
image_mean=[0.485, 0.456, 0.406],
image_std=[0.229... | PvtImageProcessingTester |
python | qdrant__qdrant-client | qdrant_client/grpc/collections_service_pb2_grpc.py | {
"start": 211,
"end": 4422
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Get = channel.unary_unary(
'/qdrant.Collections/Get',
request_seri... | CollectionsStub |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/control_flow/py_func_test.py | {
"start": 18805,
"end": 31569
} | class ____(PyFuncTestBase):
"""Encapsulates tests for eager_py_func only."""
@test_util.run_in_graph_and_eager_modes
def testEagerSingleOutputInt32(self):
a = array_ops.ones((3, 3), dtype=dtypes.int32)
x = array_ops.ones((3, 1), dtype=dtypes.int32)
output = script_ops.eager_py_func(matmul, inp=[a, x]... | EagerPyFuncTest |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 14090,
"end": 14896
} | class ____(Operation):
def call(self, x):
return backend.nn.selu(x)
def compute_output_spec(self, x):
return KerasTensor(x.shape, dtype=x.dtype)
@keras_export(["keras.ops.selu", "keras.ops.nn.selu"])
def selu(x):
"""Scaled Exponential Linear Unit (SELU) activation function.
It is def... | Selu |
python | davidhalter__jedi | test/completion/goto.py | {
"start": 1353,
"end": 1404
} | class ____:
def foo(self):
print("foo")
| Foo |
python | apache__airflow | airflow-core/tests/unit/models/test_xcom.py | {
"start": 6907,
"end": 13803
} | class ____:
@pytest.fixture
def setup_for_xcom_get_one(self, task_instance, push_simple_json_xcom):
push_simple_json_xcom(ti=task_instance, key="xcom_1", value={"key": "value"})
@pytest.mark.usefixtures("setup_for_xcom_get_one")
def test_xcom_get_one(self, session, task_instance):
store... | TestXComGet |
python | optuna__optuna | optuna/visualization/_slice.py | {
"start": 1235,
"end": 1330
} | class ____(NamedTuple):
target_name: str
subplots: list[_SliceSubplotInfo]
| _SlicePlotInfo |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_tool_param.py | {
"start": 661,
"end": 1911
} | class ____(TypedDict, total=False):
input_schema: Required[InputSchema]
"""[JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.
This defines the shape of the `input` that your tool accepts and that the model
will produce.
"""
name: Required[str]
"""Name of the tool.
... | BetaToolParam |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_workflows.py | {
"start": 10729,
"end": 11935
} | class ____:
@mock.patch(BASE_PATH.format("Execution"))
@mock.patch(BASE_PATH.format("WorkflowsHook"))
def test_execute(self, mock_hook, mock_object):
op = WorkflowsCancelExecutionOperator(
task_id="test_task",
workflow_id=WORKFLOW_ID,
execution_id=EXECUTION_ID,
... | TestWorkflowExecutionsCancelExecutionOperator |
python | mlflow__mlflow | mlflow/catboost/__init__.py | {
"start": 12662,
"end": 13236
} | class ____:
def __init__(self, cb_model):
self.cb_model = cb_model
def get_raw_model(self):
"""
Returns the underlying model.
"""
return self.cb_model
def predict(self, dataframe, params: dict[str, Any] | None = None):
"""
Args:
dataframe... | _CatboostModelWrapper |
python | django__django | django/test/html.py | {
"start": 6278,
"end": 6511
} | class ____(Element):
def __init__(self):
super().__init__(None, ())
def __str__(self):
return "".join(
[html.escape(c) if isinstance(c, str) else str(c) for c in self.children]
)
| RootElement |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py | {
"start": 109,
"end": 752
} | class ____:
# Errors
no_annotation = r"foo"
missing = MISSING
field = field()
# No errors
__slots__ = ("foo", "bar")
__radd__ = __add__
_private_attr = 100
with_annotation: str
with_annotation_and_default: int = 42
with_annotation_and_field_specifier: bytes = field()
c... | C |
python | davidhalter__jedi | jedi/plugins/django.py | {
"start": 10289,
"end": 10656
} | class ____(ValueWrapper):
def __init__(self, method, model_cls):
super().__init__(method)
self._model_cls = model_cls
def py__get__(self, instance, class_value):
return ValueSet({QuerySetBoundMethodWrapper(v, self._model_cls)
for v in self._wrapped_value.py__get... | QuerySetMethodWrapper |
python | chroma-core__chroma | chromadb/utils/embedding_functions/schemas/bm25_tokenizer.py | {
"start": 2569,
"end": 3277
} | class ____:
"""Adapter that provides the uniform `stem` API used across languages."""
def __init__(self) -> None:
try:
import snowballstemmer
except ImportError:
raise ValueError(
"The snowballstemmer python package is not installed. Please install it wit... | _SnowballStemmerAdapter |
python | getsentry__sentry | tests/sentry/seer/fetch_issues/test_by_function_name.py | {
"start": 3056,
"end": 9860
} | class ____(CreateEventTestCase):
def setUp(self):
super().setUp()
self.event_timestamp_start = datetime.now(UTC) - timedelta(days=NUM_DAYS_AGO)
self.event_timestamp_end = datetime.now(UTC)
def test_empty_projects_list(self):
result = _get_issues_for_file(
projects=[]... | TestGetIssuesForFile |
python | plotly__plotly.py | plotly/graph_objs/scatterpolar/marker/colorbar/title/_font.py | {
"start": 233,
"end": 9974
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolar.marker.colorbar.title"
_path_str = "scatterpolar.marker.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"varia... | Font |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0015_add_project_allow_promos.py | {
"start": 100,
"end": 604
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0014_add-state-tracking"),
]
operations = [
migrations.AddField(
model_name="project",
name="allow_promos",
field=models.BooleanField(
default=... | Migration |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/multicolumn_map_metrics/multicolumn_sum_equal.py | {
"start": 521,
"end": 1722
} | class ____(MulticolumnMapMetricProvider):
condition_metric_name = "multicolumn_sum.equal"
condition_domain_keys = (
"batch_id",
"table",
"column_list",
"row_condition",
"condition_parser",
"ignore_row_if",
)
condition_value_keys = ("sum_total",)
@mult... | MulticolumnSumEqual |
python | great-expectations__great_expectations | tests/experimental/metric_repository/test_column_filter.py | {
"start": 1094,
"end": 12814
} | class ____:
"""Test cases for ColumnFilter class."""
@pytest.mark.unit
def test_init_with_defaults(self):
"""Test initialization with default parameters."""
column_filter = ColumnFilter()
assert column_filter._include_column_names == []
assert column_filter._exclude_column_n... | TestColumnFilter |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 21789,
"end": 22199
} | class ____(LocalizableStreamlitException):
"""Exception raised when a value is not valid for a parameter."""
def __init__(self, parameter: str, valid_values: list[str]) -> None:
super().__init__(
"Invalid `{parameter}` value. Supported values: {valid_values}.",
parameter=paramet... | StreamlitValueError |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_slots/SLOT002.py | {
"start": 89,
"end": 157
} | class ____(namedtuple("foo", ["str", "int"])): # SLOT002
pass
| Bad |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 24450,
"end": 24737
} | class ____(ProjectAdminMixin, PrivateViewMixin):
model = WebHook
lookup_url_kwarg = "webhook_pk"
form_class = WebHookForm
def get_success_url(self):
return reverse(
"projects_webhooks",
args=[self.get_project().slug],
)
| WebHookMixin |
python | spyder-ide__spyder | spyder/plugins/outlineexplorer/widgets.py | {
"start": 7585,
"end": 32728
} | class ____(OneColumnTree):
# Used only for debug purposes
sig_tree_updated = Signal()
sig_display_spinner = Signal()
sig_hide_spinner = Signal()
sig_update_configuration = Signal()
CONF_SECTION = 'outline_explorer'
def __init__(self, parent):
if hasattr(parent, 'CONTEXT_NAME'):
... | OutlineExplorerTreeWidget |
python | has2k1__plotnine | plotnine/composition/_wrap.py | {
"start": 96,
"end": 1447
} | class ____(Compose):
"""
Wrap plots or compositions into a grid
**Usage**
plot + plot
plot + composition
composition + plot
composition + composition
Typically, you will use this class through the `+` operator.
Parameters
----------
items:
The obje... | Wrap |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py | {
"start": 2508,
"end": 2562
} | class ____(ABC): # error
foo
| abc_set_class_variable_4 |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/data_structures/dynamic_stitch_op_test.py | {
"start": 9180,
"end": 13559
} | class ____(DynamicStitchTestBase, test.TestCase):
def __init__(self, *test_case_args):
test.TestCase.__init__(self, *test_case_args)
DynamicStitchTestBase.__init__(self, data_flow_ops.parallel_dynamic_stitch)
def testScalar(self):
with test_util.use_gpu():
indices = [constant_op.constant(0), con... | ParallelDynamicStitchTest |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 68855,
"end": 69504
} | class ____(BaseValidator):
"""
Validator for readonly literal values
"""
def __init__(self, plotly_name, parent_name, val, **kwargs):
super(LiteralValidator, self).__init__(
plotly_name=plotly_name, parent_name=parent_name, **kwargs
)
self.val = val
def validate... | LiteralValidator |
python | apache__airflow | airflow-core/tests/unit/executors/test_executor_utils.py | {
"start": 1243,
"end": 5608
} | class ____:
@pytest.fixture
def core_executor(self):
return ExecutorName(alias=CORE_EXEC_ALIAS, module_path=CORE_EXEC_MODULE_PATH)
@pytest.fixture
def core_executor_team_name(self):
return ExecutorName(
alias=CORE_EXEC_ALIAS, module_path=CORE_EXEC_MODULE_PATH, team_name=CORE... | TestExecutorName |
python | django__django | tests/admin_views/admin.py | {
"start": 8435,
"end": 8538
} | class ____(admin.ModelAdmin):
raw_id_fields = ("inquisition", "defendant0", "defendant1")
| SketchAdmin |
python | langchain-ai__langchain | libs/partners/anthropic/tests/unit_tests/middleware/test_file_search.py | {
"start": 5813,
"end": 8068
} | class ____:
"""Test Grep content search."""
def test_grep_files_with_matches_mode(self) -> None:
"""Test grep with files_with_matches output mode."""
middleware = StateFileSearchMiddleware()
state: AnthropicToolsState = {
"messages": [],
"text_editor_files": {
... | TestGrepSearch |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/io_manager.py | {
"start": 9524,
"end": 10947
} | class ____:
def __init__(
self,
config_schema: CoercableToConfigSchema = None,
description: Optional[str] = None,
output_config_schema: CoercableToConfigSchema = None,
input_config_schema: CoercableToConfigSchema = None,
required_resource_keys: Optional[set[str]] = No... | _IOManagerDecoratorCallable |
python | google__pytype | pytype/metrics.py | {
"start": 4159,
"end": 5102
} | class ____(metaclass=_RegistryMeta):
"""Abstract base class for metrics."""
def __init__(self, name):
"""Initialize the metric and register it under the specified name."""
if name is None:
# We do not want to register this metric (e.g. we are deserializing a
# metric from file and need to merge... | Metric |
python | pytest-dev__pytest-django | tests/test_unittest.py | {
"start": 2356,
"end": 4262
} | class ____:
"""Django test tags are only converted to Pytest markers if actually
Django tests. Use pytest markers directly for pytest tests."""
@pytest.fixture(autouse=True)
def gimme_my_markers(self, request: pytest.FixtureRequest) -> None:
self.markers = {m.name for m in request.node.iter_mar... | TestNonDjangoClassWithTags |
python | Pylons__pyramid | tests/test_traversal.py | {
"start": 44051,
"end": 45565
} | class ____(unittest.TestCase):
def _callFUT(self, tup):
from pyramid.traversal import _join_path_tuple
return _join_path_tuple(tup)
def test_empty_tuple(self):
# tests "or '/'" case
result = self._callFUT(())
self.assertEqual(result, '/')
def test_nonempty_tuple(se... | Test__join_path_tuple |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/stateful.py | {
"start": 20702,
"end": 22473
} | class ____:
targets: Any
function: Any
arguments: Any
preconditions: Any
bundles: tuple["Bundle", ...] = field(init=False)
_cached_hash: int | None = field(init=False, default=None)
_cached_repr: str | None = field(init=False, default=None)
arguments_strategies: dict[Any, Any] = field(in... | Rule |
python | viewflow__viewflow | viewflow/workflow/nodes/end.py | {
"start": 283,
"end": 1921
} | class ____(Activation):
"""Activation that finishes the flow process."""
@Activation.status.transition(
source=STATUS.DONE,
target=STATUS.CANCELED,
conditions=[process_not_cancelled],
permission=has_manage_permission,
)
def undo(self):
self.process.finished = Non... | EndActivation |
python | getsentry__sentry | src/sentry/auth/authenticators/base.py | {
"start": 1079,
"end": 1241
} | class ____(ActivationResult):
type = "challenge"
def __init__(self, challenge: bytes) -> None:
self.challenge = challenge
| ActivationChallengeResult |
python | wandb__wandb | wandb/docker/__init__.py | {
"start": 193,
"end": 8663
} | class ____(Error):
"""Raised when attempting to execute a docker command."""
def __init__(
self,
command_launched: List[str],
return_code: int,
stdout: Optional[bytes] = None,
stderr: Optional[bytes] = None,
) -> None:
command_launched_str = " ".join(command_... | DockerError |
python | great-expectations__great_expectations | great_expectations/metrics/column/values_non_null.py | {
"start": 283,
"end": 424
} | class ____(ColumnMetric[ColumnValuesNonNullResult]):
name = f"column_values.nonnull.{MetricNameSuffix.CONDITION.value}"
| ColumnValuesNonNull |
python | kamyu104__LeetCode-Solutions | Python/circular-permutation-in-binary-representation.py | {
"start": 31,
"end": 254
} | class ____(object):
def circularPermutation(self, n, start):
"""
:type n: int
:type start: int
:rtype: List[int]
"""
return [start ^ (i>>1) ^ i for i in xrange(1<<n)]
| Solution |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/saved_model/model_serialization.py | {
"start": 1029,
"end": 2504
} | class ____(layer_serialization.LayerSavedModelSaver):
"""Model SavedModel serialization."""
@property
def object_identifier(self):
return constants.MODEL_IDENTIFIER
def _python_properties_internal(self):
metadata = super(ModelSavedModelSaver, self)._python_properties_internal()
# Network stateful ... | ModelSavedModelSaver |
python | pandas-dev__pandas | setup.py | {
"start": 2831,
"end": 5388
} | class ____(Command):
"""Custom command to clean the .so and .pyc files."""
user_options = [("all", "a", "")]
def initialize_options(self) -> None:
self.all = True
self._clean_me = []
self._clean_trees = []
base = pjoin("pandas", "_libs", "src")
parser = pjoin(base,... | CleanCommand |
python | astropy__astropy | astropy/convolution/kernels.py | {
"start": 764,
"end": 2778
} | class ____(Kernel1D):
"""
1D Gaussian filter kernel.
The Gaussian filter is a filter with great smoothing properties. It is
isotropic and does not produce artifacts.
The generated kernel is normalized so that it integrates to 1.
Parameters
----------
stddev : number
Standard d... | Gaussian1DKernel |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_service_cidr_status.py | {
"start": 383,
"end": 3794
} | 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... | V1beta1ServiceCIDRStatus |
python | pikepdf__pikepdf | tests/test_pdf.py | {
"start": 3190,
"end": 4440
} | class ____:
def test_some_permissions_missing(self, resources):
with Pdf.open(resources / 'graph-encrypted.pdf', password='owner') as pdf:
assert not pdf.allow.print_highres
assert not pdf.allow.modify_annotation
assert pdf.allow.print_lowres
def test_all_true_not_en... | TestPermissions |
python | getsentry__sentry | tests/acceptance/test_explore_spans.py | {
"start": 409,
"end": 2900
} | class ____(AcceptanceTestCase, SpanTestCase, SnubaTestCase):
viewname = "sentry-api-0-organization-events"
def setUp(self) -> None:
super().setUp()
self.start = self.day_ago = before_now(days=1).replace(
hour=10, minute=0, second=0, microsecond=0
)
self.start_minus_... | ExploreSpansTest |
python | huggingface__transformers | src/transformers/models/emu3/modular_emu3.py | {
"start": 1612,
"end": 3075
} | class ____(LlamaDecoderLayer):
def __init__(self, config: Emu3Config, layer_idx: int):
super().__init__(config, layer_idx)
self.dropout = nn.Dropout(config.attention_dropout)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
... | Emu3DecoderLayer |
python | psf__black | tests/test_black.py | {
"start": 119288,
"end": 124034
} | class ____(BlackBaseTestCase):
def check_ast_equivalence(
self, source: str, dest: str, *, should_fail: bool = False
) -> None:
# If we get a failure, make sure it's not because the code itself
# is invalid, since that will also cause assert_equivalent() to throw
# ASTSafetyError... | TestASTSafety |
python | apache__airflow | airflow-core/tests/unit/models/test_deadline.py | {
"start": 7525,
"end": 18687
} | class ____:
@staticmethod
def setup_method():
_clean_db()
@staticmethod
def teardown_method():
_clean_db()
@pytest.mark.parametrize(
("column", "conditions", "expected_query"),
[
pytest.param(
DagRun.logical_date,
{"dag_id... | TestCalculatedDeadlineDatabaseCalls |
python | gevent__gevent | src/gevent/testing/flaky.py | {
"start": 1931,
"end": 4104
} | class ____(FlakyTest):
"""
Use this when the test sometimes crashes.
"""
def reraiseFlakyTestRaceCondition():
six.reraise(FlakyAssertionError,
FlakyAssertionError(sys.exc_info()[1]),
sys.exc_info()[2])
reraiseFlakyTestTimeout = reraiseFlakyTestRaceCondition
reraiseFlaky... | FlakyTestCrashes |
python | crytic__slither | slither/detectors/functions/permit_domain_signature_collision.py | {
"start": 489,
"end": 3483
} | class ____(AbstractDetector):
"""
Domain separator collision
"""
ARGUMENT = "domain-separator-collision"
HELP = "Detects ERC20 tokens that have a function whose signature collides with EIP-2612's DOMAIN_SEPARATOR()"
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.... | DomainSeparatorCollision |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1010252,
"end": 1010845
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UnlinkRepositoryFromProject"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "project", "repository")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the cl... | UnlinkRepositoryFromProjectPayload |
python | scipy__scipy | scipy/optimize/tests/test_lsq_linear.py | {
"start": 9507,
"end": 11000
} | class ____:
def test_option_lsmr_tol(self):
# Should work with a positive float, string equal to 'auto', or None
_ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=1e-2)
_ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol='auto')
_ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=None)
... | TestErrorChecking |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 15666,
"end": 16388
} | class ____(PGExecutionContext):
def handle_dbapi_exception(self, e):
if isinstance(
e,
(
self.dialect.dbapi.InvalidCachedStatementError,
self.dialect.dbapi.InternalServerError,
),
):
self.dialect._invalidate_schema_cache... | PGExecutionContext_asyncpg |
python | gevent__gevent | src/greentest/3.10/test_context.py | {
"start": 12429,
"end": 12534
} | class ____(Exception):
pass
@unittest.skipIf(hamt is None, '_testcapi lacks "hamt()" function')
| EqError |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 40894,
"end": 41120
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("ERROR", "EXPECTED", "FAILURE", "PENDING", "SUCCESS")
String = sgqlc.types.String
| StatusState |
python | gevent__gevent | src/gevent/testing/patched_tests_setup.py | {
"start": 22012,
"end": 69384
} | class ____(object):
def __init__(self, test_fqn):
self._patcher = wrapped_tests[test_fqn]
def __call__(self, orig_test_fn):
@functools.wraps(orig_test_fn)
def test(*args, **kwargs):
with self._patcher():
return orig_test_fn(*args, **kwargs)
return te... | _PatchedTest |
python | sqlalchemy__sqlalchemy | test/engine/test_ddlevents.py | {
"start": 14779,
"end": 16821
} | class ____(DDLEventHarness):
requires_table_to_exist = True
def test_straight_create_drop(
self,
metadata,
connection,
produce_subject,
produce_table_integrated_subject,
produce_event_target,
):
subject = produce_subject
assert_subject = produ... | DDLEventWCreateHarness |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/pool/base.py | {
"start": 39028,
"end": 40872
} | class ____(PoolProxiedConnection):
"""provides the :class:`.PoolProxiedConnection` interface for cases where
the DBAPI connection is not actually proxied.
This is used by the engine internals to pass a consistent
:class:`.PoolProxiedConnection` object to consuming dialects in response to
pool event... | _AdhocProxiedConnection |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-seller-partner/components.py | {
"start": 13302,
"end": 13951
} | class ____(TypeTransformer):
def __init__(self, *args, **kwargs):
config = TransformConfig.DefaultSchemaNormalization | TransformConfig.CustomSchemaNormalization
super().__init__(config)
self.registerCustomTransform(self.get_transform_function())
@staticmethod
def get_transform_func... | FlatFileSettlementV2ReportsTypeTransformer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol9.py | {
"start": 192,
"end": 222
} | class ____:
__call__ = A()
| B |
python | pytorch__pytorch | torch/export/pt2_archive/_package.py | {
"start": 2415,
"end": 6077
} | class ____:
"""
Context manager for writing a PT2 archive.
"""
def __init__(self, archive_path_or_buffer: FileLike):
if isinstance(archive_path_or_buffer, str):
archive_path_or_buffer = normalize_path_separator(archive_path_or_buffer)
self.archive_file = torch._C.PyTorchFile... | PT2ArchiveWriter |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/dynamic_rel.py | {
"start": 471,
"end": 673
} | class ____(Base):
__tablename__ = "address"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("user.id"))
email_address: Mapped[str]
| Address |
python | pytorch__pytorch | torch/distributed/elastic/multiprocessing/api.py | {
"start": 15102,
"end": 25451
} | class ____(abc.ABC):
"""
The base class that standardizes operations over a set of processes that are launched via different mechanisms.
The name ``PContext`` is intentional to disambiguate with ``torch.multiprocessing.ProcessContext``.
.. warning:: stdouts and stderrs should ALWAYS be a superset of
... | PContext |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-duckdb-retriever/llama_index/retrievers/duckdb_retriever/base.py | {
"start": 1229,
"end": 4326
} | class ____(BaseRetriever):
def __init__(
self,
database_name: str = ":memory:",
table_name: str = "documents",
text_search_config: dict = {
"stemmer": "english",
"stopwords": "english",
"ignore": r"(\\.|[^a-z])+",
"strip_accents": True,... | DuckDBRetriever |
python | scrapy__scrapy | tests/test_downloadermiddleware_httpproxy.py | {
"start": 251,
"end": 18694
} | class ____:
failureException = AssertionError # type: ignore[assignment]
def setup_method(self):
self._oldenv = os.environ.copy()
def teardown_method(self):
os.environ = self._oldenv
def test_not_enabled(self):
crawler = get_crawler(Spider, {"HTTPPROXY_ENABLED": False})
... | TestHttpProxyMiddleware |
python | google__jax | jax/_src/error_check.py | {
"start": 8774,
"end": 12960
} | class ____:
"""A class to store error information for AOT compilation.
This class is used internally by the wrapper functions `wrap_for_export` and
`unwrap_from_import` to encapsulate error-related data within an exported
function.
Attributes:
error_code (jax.Array): A JAX array representing the final e... | _ErrorClass |
python | bokeh__bokeh | src/bokeh/models/scales.py | {
"start": 3510,
"end": 4530
} | class ____(Scale):
''' Represent a composition of two scales, which useful for defining
sub-coordinate systems.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
source_scale = Required(Instance(... | CompositeScale |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_diff_less_than_or_equal_to_threshold.py | {
"start": 936,
"end": 5605
} | class ____(
DataProfilerProfileMetricProvider
):
metric_name = "data_profiler.profile_numeric_columns_diff_less_than_or_equal_to_threshold"
value_keys = (
"profile_path",
"limit_check_report_keys",
"numerical_diff_statistics",
)
@metric_value(engine=PandasExecutionEngine)
... | DataProfilerProfileNumericColumnsDiffLessThanOrEqualToThreshold |
python | pypa__setuptools | setuptools/_scripts.py | {
"start": 547,
"end": 3075
} | class ____(list):
"""
A command spec for a #! header, specified as a list of arguments akin to
those passed to Popen.
"""
options: list[str] = []
split_args = _SplitArgs()
@classmethod
def best(cls):
"""
Choose the best CommandSpec class based on environmental condition... | CommandSpec |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/panels/sql/tracking.py | {
"start": 1007,
"end": 3773
} | class ____(Exception):
"""Thrown when template panel triggers a query"""
def wrap_cursor(connection):
# When running a SimpleTestCase, Django monkey patches some DatabaseWrapper
# methods, including .cursor() and .chunked_cursor(), to raise an exception
# if the test code tries to access the database,... | SQLQueryTriggered |
python | jazzband__django-formtools | formtools/wizard/storage/session.py | {
"start": 32,
"end": 523
} | class ____(BaseStorage):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.prefix not in self.request.session:
self.init_data()
def _get_data(self):
self.request.session.modified = True
return self.request.session[self.prefix]
def _... | SessionStorage |
python | django__django | django/contrib/gis/db/models/lookups.py | {
"start": 440,
"end": 3654
} | class ____(Lookup):
sql_template = None
transform_func = None
distance = False
band_rhs = None
band_lhs = None
def __init__(self, lhs, rhs):
rhs, *self.rhs_params = rhs if isinstance(rhs, (list, tuple)) else (rhs,)
super().__init__(lhs, rhs)
self.template_params = {}
... | GISLookup |
python | pytorch__pytorch | test/inductor/test_cache.py | {
"start": 12307,
"end": 21057
} | class ____(TestMixin, TestCase):
@parametrize("async_cache_type", TestMixin.async_cache_types())
@parametrize("key_type", TestMixin.key_types())
@parametrize("value_type", TestMixin.value_types())
def test_get_async(
self: Self,
async_cache_type: type[icache.AsyncCache],
key_type... | AsyncCacheTest |
python | django__django | django/db/backends/postgresql/compiler.py | {
"start": 336,
"end": 581
} | class ____(list):
"""
Sentinel value to signal DatabaseOperations.bulk_insert_sql() that the
UNNEST strategy should be used for the bulk insert.
"""
def __str__(self):
return "UNNEST(%s)" % ", ".join(self)
| InsertUnnest |
python | dagster-io__dagster | python_modules/libraries/dagstermill/dagstermill/manager.py | {
"start": 2299,
"end": 2789
} | class ____(EventGenerationManager):
"""Utility class to explicitly manage setup/teardown of resource events. Overrides the default
`generate_teardown_events` method so that teardown is deferred until explicitly called by the
dagstermill Manager.
"""
def generate_teardown_events(self):
retur... | DagstermillResourceEventGenerationManager |
python | Textualize__textual | docs/examples/styles/link_color.py | {
"start": 64,
"end": 747
} | class ____(App):
CSS_PATH = "link_color.tcss"
def compose(self):
yield Label(
"Visit the [link='https://textualize.io']Textualize[/link] website.",
id="lbl1", # (1)!
)
yield Label(
"Click [@click=app.bell]here[/] for the bell sound.",
id=... | LinkColorApp |
python | scrapy__scrapy | tests/test_loader.py | {
"start": 5950,
"end": 6033
} | class ____(InitializationTestMixin):
item_class = dict
| TestInitializationFromDict |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py | {
"start": 66838,
"end": 71832
} | class ____(Wav2Vec2ConformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, "add_adapter") and config.add_adapter:
raise ValueError(
"Sequence classification does not support the use of Wav2Vec2Conformer adapters (config.add_adap... | Wav2Vec2ConformerForSequenceClassification |
python | numba__numba | numba/core/caching.py | {
"start": 3732,
"end": 4671
} | class ____(object):
"""
A cache locator mixin for functions which are backed by a well-known
Python source file.
"""
def get_source_stamp(self):
if getattr(sys, 'frozen', False):
st = os.stat(sys.executable)
else:
st = os.stat(self._py_file)
# We use ... | _SourceFileBackedLocatorMixin |
python | django__django | tests/delete/models.py | {
"start": 5587,
"end": 5658
} | class ____(models.Model):
m2m = models.ManyToManyField(M2MTo)
| M2MFrom |
python | walkccc__LeetCode | solutions/1002. Find Common Characters/1002.py | {
"start": 0,
"end": 192
} | class ____:
def commonChars(self, words: list[str]) -> list[str]:
return functools.reduce(lambda a, b: a & b,
map(collections.Counter, words)).elements()
| Solution |
python | google__pytype | pytype/tools/xref/indexer.py | {
"start": 39234,
"end": 41268
} | class ____(source.AbstractTrace):
def __repr__(self):
types_repr = tuple(
t and [node_utils.typename(x) for x in t]
for t in self.types)
return f"{super().__repr__()} {types_repr}"
def process_file(options, source_text=None, generate_callgraphs=False,
preserve_pytype_vm=Fal... | VmTrace |
python | cherrypy__cherrypy | cherrypy/process/win32.py | {
"start": 2464,
"end": 4380
} | class ____(wspbus.Bus):
"""A Web Site Process Bus implementation for Win32.
Instead of time.sleep, this bus blocks using native win32event
objects.
"""
def __init__(self):
"""Initialize a Win32 bus implementation."""
self.events = {}
wspbus.Bus.__init__(self)
def _get_... | Win32Bus |
python | django__django | tests/forms_tests/field_tests/test_jsonfield.py | {
"start": 244,
"end": 4844
} | class ____(SimpleTestCase):
def test_valid(self):
field = JSONField()
value = field.clean('{"a": "b"}')
self.assertEqual(value, {"a": "b"})
def test_valid_empty(self):
field = JSONField(required=False)
self.assertIsNone(field.clean(""))
self.assertIsNone(field.cl... | JSONFieldTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/base/llms/types.py | {
"start": 732,
"end": 973
} | class ____(str, Enum):
"""Message role."""
SYSTEM = "system"
DEVELOPER = "developer"
USER = "user"
ASSISTANT = "assistant"
FUNCTION = "function"
TOOL = "tool"
CHATBOT = "chatbot"
MODEL = "model"
| MessageRole |
python | doocs__leetcode | solution/3700-3799/3751.Total Waviness of Numbers in Range I/Solution.py | {
"start": 0,
"end": 607
} | class ____:
def totalWaviness(self, num1: int, num2: int) -> int:
def f(x: int) -> int:
nums = []
while x:
nums.append(x % 10)
x //= 10
m = len(nums)
if m < 3:
return 0
s = 0
for i in rang... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.