language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | pytorch__pytorch | torch/distributed/checkpoint/_async_thread_executor.py | {
"start": 1333,
"end": 2476
} | class ____(_AsyncCheckpointExecutor):
def __init__(self) -> None:
self._executor = ThreadPoolExecutor(
max_workers=1, thread_name_prefix="AsyncCheckpointExecutor"
)
def execute_save(
self,
staging_future_or_state_dict: Union[Future[STATE_DICT_TYPE], STATE_DICT_TYPE],... | _ThreadBasedAsyncCheckpointExecutor |
python | tornadoweb__tornado | tornado/httputil.py | {
"start": 23387,
"end": 23518
} | class ____(Exception):
"""Exception class for errors in HTTP output.
.. versionadded:: 4.0
"""
pass
| HTTPOutputError |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_variable_test.py | {
"start": 3166,
"end": 26313
} | class ____(test.TestCase):
"""Base class that tests mirrored variable creator.
Currently it assumes all strategy objects have two replicas.
"""
@classmethod
def setUpClass(cls):
_mimic_two_cpus()
def assertAllDifferent(self, objs):
for i in range(len(objs)):
for j in range(len(objs)):
... | MirroredVariableCreationTest |
python | google__pytype | pytype/tools/xref/indexer.py | {
"start": 14411,
"end": 28600
} | class ____(ScopedVisitor, traces.MatchAstVisitor):
"""Visitor that generates indexes."""
def __init__(self, ast, src, module_name):
super().__init__(ast=ast, src_code=src, module_name=module_name)
self.defs = {}
self.locs = collections.defaultdict(list)
self.refs = []
self.modules = {}
self... | IndexVisitor |
python | django__django | django/core/exceptions.py | {
"start": 1936,
"end": 2037
} | class ____(Exception):
"""The user did not have permission to do that"""
pass
| PermissionDenied |
python | tensorflow__tensorflow | tensorflow/python/ops/sparse_bincount_ops_test.py | {
"start": 24240,
"end": 27303
} | class ____(test_util.TensorFlowTestCase):
def test_dense_input_sparse_weights_fails(self):
x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32)
weights = sparse_ops.from_dense(
np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))
with self.assertRaisesRegex(ValueError, "must be a... | TestSparseCountFailureModes |
python | patrick-kidger__equinox | equinox/_vmap_pmap.py | {
"start": 1538,
"end": 3423
} | class ____:
"""Returns a callable that returns the specified integer if evaluated on an array.
Otherwise, it returns `None`.
!!! Example
```python
fn = if_array(1)
# Evaluate on an array, return the integer.
fn(jax.numpy.array([0, 1, 2])) # 1
# Evaluate on not-an-a... | if_array |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 55876,
"end": 58751
} | class ____:
def test_log_values(self):
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for dt in ['f', 'd', 'g']:
log2_ = 0.69314718055994530943
xf = np.array(x, dtype=dt)
yf = np.array(y, dtype=dt) * log2_
... | TestLog |
python | great-expectations__great_expectations | tests/execution_engine/test_sqlalchemy_execution_engine.py | {
"start": 47399,
"end": 59826
} | class ____:
"""Tests for SQLAlchemy condition_to_filter_clause methods."""
@pytest.mark.sqlite
@pytest.mark.parametrize(
"condition,expected_sql",
[
pytest.param(
ComparisonCondition(column=Column("age"), operator=Operator.EQUAL, parameter=5),
"ag... | TestConditionToFilterClauseSqlAlchemy |
python | pytest-dev__pytest | testing/test_reports.py | {
"start": 20076,
"end": 22651
} | class ____:
"""Test that the hooks are working correctly for plugins"""
def test_test_report(self, pytester: Pytester, pytestconfig: Config) -> None:
pytester.makepyfile(
"""
def test_a(): assert False
def test_b(): pass
"""
)
reprec = pyteste... | TestHooks |
python | tensorflow__tensorflow | tensorflow/python/tpu/tests/tpu_embedding_v2_correctness_dense_lookup_test.py | {
"start": 1078,
"end": 3789
} | class ____(
tpu_embedding_v2_correctness_base_test.TPUEmbeddingCorrectnessBaseTest):
@parameterized.parameters([True, False])
def test_dense_lookup(self, is_high_dimensional):
strategy, mid_level_api, _ = self._create_strategy_and_mid_level('sgd')
if is_high_dimensional:
dataset = self._create_h... | TPUEmbeddingCorrectnessTest |
python | huggingface__transformers | src/transformers/models/megatron_bert/modeling_megatron_bert.py | {
"start": 21558,
"end": 21984
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = MegatronBertLMPredictionHead(config)
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
prediction_scores = self.predictions(sequence_output)
return prediction_scores
# Copi... | MegatronBertOnlyMLMHead |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox32.py | {
"start": 315,
"end": 972
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox32.xlsx")
self.ignore_elements = {"xl/drawings/drawing1.xml": ["<a:fld"]}
def test_create_file(self):
"""Test the creation ... | TestCompareXLSXFiles |
python | langchain-ai__langchain | libs/standard-tests/tests/unit_tests/test_basic_retriever.py | {
"start": 198,
"end": 475
} | class ____(BaseRetriever):
parrot_name: str
k: int = 3
def _get_relevant_documents(self, query: str, **kwargs: Any) -> list[Document]:
k = kwargs.get("k", self.k)
return [Document(page_content=f"{self.parrot_name} says: {query}")] * k
| ParrotRetriever |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 34159,
"end": 34289
} | class ____(_DropBase["Sequence"]):
"""Represent a DROP SEQUENCE statement."""
__visit_name__ = "drop_sequence"
| DropSequence |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-google-sheets/destination_google_sheets/spreadsheet.py | {
"start": 250,
"end": 3521
} | class ____:
def __init__(self, client: pygsheets_client, spreadsheet_id: str):
self.client = client
self.spreadsheet_id = spreadsheet_id
@property
def spreadsheet(self) -> Spreadsheet:
"""
Returns pygsheets.Spreadsheet with opened target spreadsheet by key.
"""
... | GoogleSheets |
python | apache__airflow | helm-tests/tests/helm_tests/other/test_keda.py | {
"start": 914,
"end": 14377
} | class ____:
"""Tests keda."""
def test_keda_disabled_by_default(self):
"""Disabled by default."""
docs = render_chart(
values={},
show_only=["templates/workers/worker-kedaautoscaler.yaml"],
)
assert docs == []
@pytest.mark.parametrize(
("exec... | TestKeda |
python | pypa__warehouse | warehouse/filters.py | {
"start": 491,
"end": 5409
} | class ____(enum.Enum):
bdist_dmg = "OSX Disk Image"
bdist_dumb = "Dumb Binary"
bdist_egg = "Egg"
bdist_msi = "Windows MSI Installer"
bdist_rpm = "RPM"
bdist_wheel = "Wheel"
bdist_wininst = "Windows Installer"
sdist = "Source"
def format_package_type(value):
try:
return Pack... | PackageType |
python | bokeh__bokeh | src/bokeh/models/glyph.py | {
"start": 3317,
"end": 3553
} | class ____(HasProps):
''' Glyphs with line properties
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@abstract
| LineGlyph |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/optimization/optimization_test.py | {
"start": 3569,
"end": 12095
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(test_base.default_test_combinations())
def testOptimizationStatefulFunction(self):
dataset = dataset_ops.Dataset.range(
10).map(lambda _: random_ops.random_uniform([])).batch(10)
options = options_lib.Options()
... | OptimizationTest |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 12368,
"end": 12516
} | class ____(_Test_random_ball):
def setup_method(self):
super().setup_method()
self.eps = 0.1
@KDTreeTest
| _Test_random_ball_approx |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_trends.py | {
"start": 30325,
"end": 34192
} | class ____(APITestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.url = reverse(
"sentry-api-0-organization-events-trends-stats",
kwargs={"organization_id_or_slug": self.project.organization.slug},
)
s... | OrganizationEventsTrendsPagingTest |
python | keras-team__keras | keras/src/optimizers/schedules/learning_rate_schedule_test.py | {
"start": 1358,
"end": 2999
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
schedules.ExponentialDecay(
initial_learning_rate=0.05,
decay_steps=10,
decay_rate=0.96,
staircase=True,
name="my_ed",
... | ExponentialDecayTest |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 43036,
"end": 43151
} | class ____(BaseModel, extra="forbid"):
geo_distance: "GeoDistanceParams" = Field(..., description="")
| GeoDistance |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 42327,
"end": 42461
} | class ____(GroupByCumulative):
chunk = M.cumcount
aggregate = staticmethod(_cumcount_aggregate)
initial = -1
| GroupByCumcount |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_write_row_breaks.py | {
"start": 301,
"end": 1327
} | class ____(unittest.TestCase):
"""
Test the Worksheet _write_row_breaks() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_row_breaks_1(self):
"""Test the _write_row_breaks() metho... | TestWriteRowBreaks |
python | pypa__hatch | src/hatch/project/env.py | {
"start": 16072,
"end": 17790
} | class ____:
def __init__(self, data_dir: Path, project_path: Path):
self.__data_dir = data_dir
self.__project_path = project_path
def dependency_hash(self, environment: EnvironmentInterface) -> str:
return self._read(environment).get("dependency_hash", "")
def update_dependency_has... | EnvironmentMetadata |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 118441,
"end": 118561
} | class ____(BaseModel, extra="forbid"):
searches: List["SearchRequest"] = Field(..., description="")
| SearchRequestBatch |
python | ray-project__ray | python/ray/tune/search/search_generator.py | {
"start": 914,
"end": 8185
} | class ____(SearchAlgorithm):
"""Generates trials to be passed to the TrialRunner.
Uses the provided ``searcher`` object to generate trials. This class
transparently handles repeating trials with score aggregation
without embedding logic into the Searcher.
Args:
searcher: Search object that... | SearchGenerator |
python | psf__black | tests/test_black.py | {
"start": 85333,
"end": 100819
} | class ____:
def test_get_cache_dir(
self,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
# Create multiple cache directories
workspace1 = tmp_path / "ws1"
workspace1.mkdir()
workspace2 = tmp_path / "ws2"
workspace2.mkdir()
# F... | TestCaching |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 89575,
"end": 93926
} | class ____(Request):
"""
Get a list of distinct values for the chosen hyperparameter
:param projects: Project IDs
:type projects: Sequence[str]
:param section: Hyperparameter section name
:type section: str
:param name: Hyperparameter name
:type name: str
:param allow_public: If set... | GetHyperparamValuesRequest |
python | getsentry__sentry | src/sentry/models/organizationonboardingtask.py | {
"start": 3344,
"end": 4636
} | class ____(Model):
"""
An abstract onboarding task that can be subclassed. This abstract model exists so that the Sandbox can create a subclass
which allows for the creation of tasks that are unique to users instead of organizations.
"""
__relocation_scope__ = RelocationScope.Excluded
STATUS_C... | AbstractOnboardingTask |
python | scrapy__scrapy | tests/test_downloadermiddleware_retry.py | {
"start": 793,
"end": 4934
} | class ____:
def setup_method(self):
self.crawler = get_crawler(DefaultSpider)
self.crawler.spider = self.crawler._create_spider()
self.mw = RetryMiddleware.from_crawler(self.crawler)
self.mw.max_retry_times = 2
def test_priority_adjust(self):
req = Request("http://www.sc... | TestRetry |
python | pytorch__pytorch | torch/distributed/_tools/fsdp2_mem_tracker.py | {
"start": 1027,
"end": 2360
} | class ____(_RefType):
"""
Enumerates categories of memory usage in FSDP modules, including parameters, gradients, activations,
and optimizer states.
Attributes:
SHARDED_PARAM (str): Memory usage of sharded parameters.
UNSHARDED_PARAM (str): Memory usage of unsharded parameters.
... | _FSDPRefType |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_memorystore.py | {
"start": 14135,
"end": 15891
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.cloud_memorystore.CloudMemorystoreHook")
def test_assert_valid_hook_call(self, mock_hook):
task = CloudMemorystoreCreateInstanceAndImportOperator(
task_id=TEST_TASK_ID,
location=TEST_LOCATION,
instance_... | TestCloudMemorystoreCreateInstanceAndImportOperatorOperator |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/in_airflow/materialize_assets_operator.py | {
"start": 261,
"end": 2040
} | class ____(BaseDagsterAssetsOperator):
"""An operator base class that proxies execution to a user-provided list of Dagster assets.
Will throw an error at runtime if not all assets can be found on the corresponding Dagster instance.
Args:
asset_key_paths (Sequence[Union[str, Sequence[str]]]): A sequ... | BaseMaterializeAssetsOperator |
python | doocs__leetcode | solution/0400-0499/0404.Sum of Left Leaves/Solution.py | {
"start": 192,
"end": 566
} | class ____:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
ans = self.sumOfLeftLeaves(root.right)
if root.left:
if root.left.left == root.left.right:
ans += root.left.val
else:
ans += s... | Solution |
python | pytorch__pytorch | torch/utils/data/datapipes/_typing.py | {
"start": 12268,
"end": 16437
} | class ____(_DataPipeMeta):
r"""
Metaclass for `IterDataPipe` and inherits from `_DataPipeMeta`.
Add various functions for behaviors specific to `IterDataPipe`.
"""
def __new__(cls, name, bases, namespace, **kwargs):
if "reset" in namespace:
reset_func = namespace["reset"]
... | _IterDataPipeMeta |
python | jd__tenacity | tenacity/retry.py | {
"start": 8440,
"end": 8738
} | class ____(retry_base):
"""Retries if any of the retries condition is valid."""
def __init__(self, *retries: retry_base) -> None:
self.retries = retries
def __call__(self, retry_state: "RetryCallState") -> bool:
return any(r(retry_state) for r in self.retries)
| retry_any |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/constant_op_eager_test.py | {
"start": 20083,
"end": 22114
} | class ____(test.TestCase):
def _compare(self, dims, val, np_ans, use_gpu):
ctx = context.context()
device = "GPU:0" if (use_gpu and ctx.num_gpus()) else "CPU:0"
with ops.device(device):
tf_ans = array_ops.fill(dims, val, name="fill")
out = tf_ans.numpy()
self.assertAllClose(np_ans, out)
... | FillTest |
python | pytorch__pytorch | torch/multiprocessing/spawn.py | {
"start": 973,
"end": 1274
} | class ____(ProcessException):
"""Exception raised when a process failed due to an exception raised by the code."""
def __init__(
self,
msg: str,
error_index: int,
error_pid: int,
):
super().__init__(msg, error_index, error_pid)
| ProcessRaisedException |
python | tensorflow__tensorflow | tensorflow/python/tools/api/generator2/shared/exported_api.py | {
"start": 848,
"end": 1244
} | class ____(NamedTuple):
"""Information about a single tf_export instance."""
file_name: str
line_no: int
symbol_name: str
v1_apis: tuple[str, ...]
v2_apis: tuple[str, ...]
@classmethod
def create(
cls, *, v1_apis: Sequence[str], v2_apis: Sequence[str], **kwargs
) -> "ExportedSymbol":
retur... | ExportedSymbol |
python | urllib3__urllib3 | test/contrib/test_pyopenssl_dependencies.py | {
"start": 611,
"end": 1988
} | class ____:
"""
Tests for error handling in pyopenssl's 'inject_into urllib3'
"""
def test_inject_validate_fail_cryptography(self) -> None:
"""
Injection should not be supported if cryptography is too old.
"""
try:
with patch("cryptography.x509.extensions.Ext... | TestPyOpenSSLInjection |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/path_registry.py | {
"start": 24423,
"end": 24580
} | class ____(_AbstractEntityRegistry):
# for aliased class, return lightweight, no-cycles created
# version
inherit_cache = True
| _SlotsEntityRegistry |
python | sqlalchemy__sqlalchemy | test/orm/test_naturalpks.py | {
"start": 50349,
"end": 52468
} | class ____(fixtures.MappedTest):
"""Test integration with TypeEngine.sort_key_function"""
class HashableDict(dict):
def __hash__(self):
return hash((self["x"], self["y"]))
@classmethod
def define_tables(cls, metadata):
class MyUnsortable(TypeDecorator):
impl = S... | UnsortablePKTest |
python | getsentry__sentry | tests/sentry/data_export/processors/test_discover.py | {
"start": 5832,
"end": 6590
} | class ____(TestCase, PerformanceIssueTestCase):
def test_handle_dataset(self) -> None:
query = {
"statsPeriod": "14d",
"project": [self.project.id],
"field": ["count(id)", "fake(field)", "issue"],
"query": "",
}
query["field"] = ["title", "coun... | DiscoverIssuesProcessorTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 80520,
"end": 85391
} | class ____(AwsBaseOperator[SageMakerHook]):
"""
Create a SageMaker notebook.
More information regarding parameters of this operator can be found here
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker/client/create_notebook_instance.html.
.. seealso:
For m... | SageMakerCreateNotebookOperator |
python | ray-project__ray | rllib/models/torch/misc.py | {
"start": 10924,
"end": 11397
} | class ____(nn.Module):
"""Simple bias appending layer for free_log_std."""
def __init__(self, num_bias_vars: int):
super().__init__()
self.log_std = torch.nn.Parameter(torch.as_tensor([0.0] * num_bias_vars))
self.register_parameter("log_std", self.log_std)
def forward(self, x: Tens... | AppendBiasLayer |
python | doocs__leetcode | solution/0600-0699/0639.Decode Ways II/Solution.py | {
"start": 0,
"end": 1182
} | class ____:
def numDecodings(self, s: str) -> int:
mod = int(1e9 + 7)
n = len(s)
# dp[i - 2], dp[i - 1], dp[i]
a, b, c = 0, 1, 0
for i in range(1, n + 1):
# 1 digit
if s[i - 1] == "*":
c = 9 * b % mod
elif s[i - 1] != "0":
... | Solution |
python | ray-project__ray | python/ray/util/scheduling_strategies.py | {
"start": 4768,
"end": 4944
} | class ____:
def __init__(self, *values):
_validate_label_match_operator_values(values, "NotIn")
self.values = list(values)
@PublicAPI(stability="alpha")
| NotIn |
python | davidhalter__jedi | test/completion/pep0484_typing.py | {
"start": 5903,
"end": 8684
} | class ____(typing.Generic[TYPE_VARX]):
def lala(self) -> TYPE_VARX:
...
def maaan(p: WithTypeVar[int]):
#? int()
p.lala()
def in_out1(x: TYPE_VARX) -> TYPE_VARX: ...
#? int()
in_out1(1)
#? str()
in_out1("")
#? str()
in_out1(str())
#?
in_out1()
def type_in_out1(x: typing.Type[TYPE_VARX]) -> TYPE... | WithTypeVar |
python | dask__distributed | distributed/tests/test_core.py | {
"start": 40230,
"end": 43644
} | class ____(TCPBackend):
_listener_class = AsyncStopTCPListener
@gen_test()
async def test_async_listener_stop(monkeypatch):
monkeypatch.setitem(backends, "tcp", TCPAsyncListenerBackend())
with pytest.warns(DeprecationWarning):
async with Server({}) as s:
await s.listen(0)
a... | TCPAsyncListenerBackend |
python | rapidsai__cudf | python/cudf/cudf/tests/general_functions/test_register_accessor.py | {
"start": 1597,
"end": 2247
} | class ____:
def __init__(self, obj):
self._obj = obj
def __getitem__(self, i):
return self._obj[2 * i - 1]
@pytest.mark.parametrize("klass", [cudf.Index, cudf.Series])
def test_index_series_accessor(klass):
obj = klass([1, 2, 3])
pobj = obj.to_pandas()
assert_eq(obj.odd[1], pobj.o... | OddRowAccessor |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1060760,
"end": 1060986
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (ProjectV2Field, ProjectV2IterationField, ProjectV2SingleSelectField)
| ProjectV2FieldConfiguration |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 59046,
"end": 63222
} | class ____:
def makegen(self):
return (x**2 for x in range(24))
def test_types(self):
ai32 = np.fromiter(self.makegen(), np.int32)
ai64 = np.fromiter(self.makegen(), np.int64)
af = np.fromiter(self.makegen(), float)
assert_(ai32.dtype == np.dtype(np.int32))
asser... | TestFromiter |
python | facelessuser__pymdown-extensions | pymdownx/smartsymbols.py | {
"start": 3960,
"end": 5427
} | class ____(Extension):
"""Smart Symbols extension."""
def __init__(self, *args, **kwargs):
"""Setup config of which symbols are enabled."""
self.config = {
'trademark': [True, 'Trademark'],
'copyright': [True, 'Copyright'],
'registered': [True, 'Registered']... | SmartSymbolsExtension |
python | getsentry__sentry | src/sentry/issues/endpoints/project_user_issue.py | {
"start": 2477,
"end": 5253
} | class ____(BaseUserIssueFormatter):
def get_issue_type(self) -> type[GroupType]:
return WebVitalsGroup
def get_issue_title(self) -> str:
vital = self.data.get("vital", "")
return f"{vital.upper()} score needs improvement"
def get_issue_subtitle(self) -> str:
vital = self.da... | WebVitalsUserIssueFormatter |
python | getsentry__sentry | tests/tools/test_flake8_plugin.py | {
"start": 1683,
"end": 5145
} | class ____(unittest.TestCase):
def test(self) -> None:
with self.assertRaises(ValueError):
func()
"""
errors = _run(S004_py)
assert errors == [
"t.py:7:13: S004 Use `pytest.raises` instead for better debuggability.",
]
def test_S005() -> None:
S005_py = """\
from sentry... | Test |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/biases/boost_low_volume_transactions_bias.py | {
"start": 320,
"end": 3916
} | class ____(Bias):
def generate_rules(self, project: Project, base_sample_rate: float) -> list[PolymorphicRule]:
proj_id = project.id
org_id = project.organization.id
transaction_map, base_implicit_rate = get_transactions_resampling_rates(
org_id=org_id, proj_id=proj_id, default_... | BoostLowVolumeTransactionsBias |
python | pytest-dev__pytest | src/_pytest/fixtures.py | {
"start": 36293,
"end": 43827
} | class ____(Generic[FixtureValue]):
"""A container for a fixture definition.
Note: At this time, only explicitly documented fields and methods are
considered public stable API.
"""
def __init__(
self,
config: Config,
baseid: str | None,
argname: str,
func: _F... | FixtureDef |
python | PrefectHQ__prefect | src/integrations/prefect-aws/prefect_aws/credentials.py | {
"start": 494,
"end": 1437
} | class ____(Enum):
"""The supported boto3 clients."""
S3 = "s3"
ECS = "ecs"
BATCH = "batch"
SECRETS_MANAGER = "secretsmanager"
@lru_cache(maxsize=8, typed=True)
def _get_client_cached(ctx, client_type: Union[str, ClientType]) -> Any:
"""
Helper method to cache and dynamically get a client ... | ClientType |
python | doocs__leetcode | solution/2100-2199/2106.Maximum Fruits Harvested After at Most K Steps/Solution.py | {
"start": 0,
"end": 511
} | class ____:
def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:
ans = i = s = 0
for j, (pj, fj) in enumerate(fruits):
s += fj
while (
i <= j
and pj
- fruits[i][0]
+ min(abs(startPos -... | Solution |
python | patrick-kidger__equinox | equinox/_tree.py | {
"start": 407,
"end": 685
} | class ____:
def __init__(self, value: Any):
self.value = value
def _remove_leaf_wrapper(x: _LeafWrapper) -> Any:
if not isinstance(x, _LeafWrapper):
raise TypeError(f"Operation undefined, {x} is not a leaf of the pytree.")
return x.value
| _LeafWrapper |
python | django__django | tests/model_fields/test_autofield.py | {
"start": 602,
"end": 1359
} | class ____(SimpleTestCase):
def test_isinstance_of_autofield(self):
for field in (models.BigAutoField, models.SmallAutoField):
with self.subTest(field.__name__):
self.assertIsInstance(field(), models.AutoField)
def test_issubclass_of_autofield(self):
class MyBigAutoF... | AutoFieldInheritanceTests |
python | ray-project__ray | python/ray/serve/tests/test_target_capacity.py | {
"start": 30955,
"end": 31688
} | class ____:
async def __call__(self, *args):
await asyncio.sleep(10000)
def create_hang_app(config: Dict) -> Application:
name: str = config["name"]
min_replicas: int = config["min_replicas"]
initial_replicas: int = config["initial_replicas"]
max_replicas: int = config["max_replicas"]
... | HangDeployment |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_legacy_tests.py | {
"start": 3788,
"end": 5647
} | class ____(TestCase):
def test_required(self):
class Schema:
option = c.Choice(('python', 'node'), required=True)
conf = self.get_config(Schema, {'option': 'python'})
self.assertEqual(conf['option'], 'python')
def test_optional(self):
class Schema:
optio... | ChoiceTest |
python | pypa__pipenv | pipenv/patched/pip/_internal/index/collector.py | {
"start": 12821,
"end": 12953
} | class ____(NamedTuple):
find_links: Sequence[Optional[LinkSource]]
index_urls: Sequence[Optional[LinkSource]]
| CollectedSources |
python | huggingface__transformers | src/transformers/models/mt5/modeling_mt5.py | {
"start": 23058,
"end": 23882
} | class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config: MT5Config):
super().__init__()
self.dense = nn.Linear(config.d_model, config.d_model)
self.dropout = nn.Dropout(p=config.classifier_dropout)
self.out_proj = nn.Linear(config.d_m... | MT5ClassificationHead |
python | sympy__sympy | sympy/tensor/array/dense_ndim_array.py | {
"start": 390,
"end": 3658
} | class ____(NDimArray):
_array: List[Basic]
def __new__(self, *args, **kwargs):
return ImmutableDenseNDimArray(*args, **kwargs)
@property
def kind(self) -> ArrayKind:
return ArrayKind._union(self._array)
def __getitem__(self, index):
"""
Allows to get items from N-... | DenseNDimArray |
python | uqfoundation__dill | dill/_dill.py | {
"start": 12208,
"end": 12261
} | class ____(Warning, PickleError):
pass
| PickleWarning |
python | huggingface__transformers | src/transformers/pipelines/base.py | {
"start": 21636,
"end": 23212
} | class ____(PipelineDataFormat):
"""
Read data from piped input to the python process. For multi columns data, columns should separated by \t
If columns are provided, then the output will be a dictionary with {column_x: value_x}
Args:
output_path (`str`): Where to save the outgoing data.
... | PipedPipelineDataFormat |
python | mwaskom__seaborn | tests/_stats/test_aggregation.py | {
"start": 194,
"end": 661
} | class ____:
@pytest.fixture
def df(self, rng):
n = 30
return pd.DataFrame(dict(
x=rng.uniform(0, 7, n).round(),
y=rng.normal(size=n),
color=rng.choice(["a", "b", "c"], n),
group=rng.choice(["x", "y"], n),
))
def get_groupby(self, df,... | AggregationFixtures |
python | miyuchina__mistletoe | test/test_contrib/test_toc_renderer.py | {
"start": 173,
"end": 2520
} | class ____(TestCase):
def test_parse_rendered_heading(self):
rendered_heading = '<h3>some <em>text</em></h3>'
content = TocRenderer.parse_rendered_heading(rendered_heading)
self.assertEqual(content, 'some text')
def test_render_heading(self):
renderer = TocRenderer()
Hea... | TestTocRenderer |
python | PyCQA__pylint | tests/functional/a/attribute_defined_outside_init.py | {
"start": 774,
"end": 1014
} | class ____:
def test_mixin(self):
"""Don't emit attribute-defined-outside-init for mixin classes."""
if self.defined_already: # pylint: disable=access-member-before-definition
self.defined_already = None
| Mixin |
python | walkccc__LeetCode | solutions/2808. Minimum Seconds to Equalize a Circular Array/2808.py | {
"start": 0,
"end": 622
} | class ____:
def minimumSeconds(self, nums: list[int]) -> int:
n = len(nums)
ans = n
numToIndices = collections.defaultdict(list)
for i, num in enumerate(nums):
numToIndices[num].append(i)
def getSeconds(i: int, j: int) -> int:
"""Returns the number of seconds required to make nums[i.... | Solution |
python | lepture__authlib | authlib/oauth1/client.py | {
"start": 300,
"end": 6737
} | class ____:
auth_class = ClientAuth
def __init__(
self,
session,
client_id,
client_secret=None,
token=None,
token_secret=None,
redirect_uri=None,
rsa_key=None,
verifier=None,
signature_method=SIGNATURE_HMAC_SHA1,
signature_... | OAuth1Client |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 126755,
"end": 130128
} | class ____(UnaryExpression[_T]):
"""Forms the basis for right-hand collection operator modifiers
ANY and ALL.
The ANY and ALL keywords are available in different ways on different
backends. On PostgreSQL, they only work for an ARRAY type. On
MySQL, they only work for subqueries.
"""
inh... | CollectionAggregate |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 96057,
"end": 97220
} | class ____:
def test_format_timeframe(self):
assert self.locale._format_timeframe("now", 0) == "nunc"
assert self.locale._format_timeframe("second", 1) == "secundum"
assert self.locale._format_timeframe("seconds", 3) == "3 secundis"
assert self.locale._format_timeframe("minute", 1) =... | TestLatinLocale |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 857902,
"end": 858098
} | class ____(VegaLiteSchema):
"""Padding schema wrapper."""
_schema = {"$ref": "#/definitions/Padding"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| Padding |
python | kamyu104__LeetCode-Solutions | Python/find-the-maximum-sequence-value-of-array.py | {
"start": 66,
"end": 1244
} | class ____(object):
def maxValue(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
INF = float("inf")
MAX_MASK = 127
def is_submask(a, b):
return (a|b) == b
def dp(direction, npos):
result = [npos]*... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_types04.py | {
"start": 315,
"end": 1892
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("types04.xlsx")
def test_write_url_default(self):
"""Test writing hyperlinks with strings_to_urls on."""
workbook = Workbook(self.g... | TestCompareXLSXFiles |
python | django__django | tests/admin_docs/test_views.py | {
"start": 23893,
"end": 24907
} | class ____(unittest.TestCase):
def test_field_name(self):
with self.assertRaises(AttributeError):
views.get_readable_field_data_type("NotAField")
def test_builtin_fields(self):
self.assertEqual(
views.get_readable_field_data_type(fields.BooleanField()),
"Bool... | TestFieldType |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 91551,
"end": 92576
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("batch_prediction_job.BatchPredictionJobHook"))
def test_execute(self, mock_hook):
op = DeleteBatchPredictionJobOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
regio... | TestVertexAIDeleteBatchPredictionJobOperator |
python | encode__starlette | tests/test_formparsers.py | {
"start": 747,
"end": 11142
} | class ____(dict[Any, Any]):
def __bool__(self) -> bool:
return True
# FORCE_MULTIPART is an empty dict that boolean-evaluates as `True`.
FORCE_MULTIPART = ForceMultipartDict()
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive)
data = await reques... | ForceMultipartDict |
python | pytorch__pytorch | torch/_inductor/codegen/rocm/rocm_kernel.py | {
"start": 1028,
"end": 1166
} | class ____(Kernel):
"""
Baseclass for ROCm based Kernels
"""
overrides = OpOverrides # type: ignore[assignment]
| ROCmKernel |
python | tensorflow__tensorflow | tensorflow/python/keras/distribute/worker_training_state.py | {
"start": 1463,
"end": 6091
} | class ____(object):
"""Training state management class.
This class provides apis for backing up and restoring the training state.
This allows model and epoch information to be saved periodically and restore
for fault-tolerance, also known as preemption-recovery purpose.
"""
def __init__(self, model, check... | WorkerTrainingState |
python | huggingface__transformers | tests/models/m2m_100/test_modeling_m2m_100.py | {
"start": 8735,
"end": 13251
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
M2M100Model,
M2M100ForConditionalGeneration,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{
"feat... | M2M100ModelTest |
python | ray-project__ray | release/train_tests/benchmark/config.py | {
"start": 428,
"end": 497
} | class ____(BaseModel):
TASK_NAME: ClassVar[str] = "base"
| TaskConfig |
python | django__django | django/views/generic/dates.py | {
"start": 20423,
"end": 20594
} | class ____(MultipleObjectTemplateResponseMixin, BaseTodayArchiveView):
"""List of objects published today."""
template_name_suffix = "_archive_day"
| TodayArchiveView |
python | scrapy__scrapy | tests/test_command_parse.py | {
"start": 2130,
"end": 2432
} | class ____(BaseSpider):
name = "asyncdef_asyncio_gen_exc"
async def parse(self, response):
for i in range(10):
await asyncio.sleep(0.1)
yield {{'foo': i}}
if i > 5:
raise ValueError("Stopping the processing")
| AsyncDefAsyncioGenExcSpider |
python | pandas-dev__pandas | asv_bench/benchmarks/sparse.py | {
"start": 2626,
"end": 2962
} | class ____:
def setup(self):
N = 10000
k = 10
arr = np.zeros((N, k), dtype=float)
arr[0, 0] = 3.0
arr[12, 7] = -1.0
arr[0, 9] = 11.2
self.df = pd.DataFrame(arr, dtype=pd.SparseDtype("float", fill_value=0.0))
def time_to_coo(self):
self.df.sparse.t... | ToCooFrame |
python | kubernetes-client__python | kubernetes/client/api/apis_api.py | {
"start": 543,
"end": 5205
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | ApisApi |
python | jina-ai__jina | tests/unit/serve/runtimes/worker/test_worker_request_handler.py | {
"start": 309,
"end": 455
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
return DocumentArray([Document(text='new document')])
| NewDocsExecutor |
python | PyCQA__pylint | pylint/config/callback_actions.py | {
"start": 8731,
"end": 9767
} | class ____(_CallbackAction):
"""Action that has access to the Linter object."""
def __init__(
self,
option_strings: Sequence[str],
dest: str,
nargs: None = None,
const: None = None,
default: None = None,
type: None = None,
choices: None = None,
... | _AccessLinterObjectAction |
python | getsentry__sentry | src/sentry/migrations/0992_latestrepoerelease_indexes.py | {
"start": 186,
"end": 1987
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | django-haystack__django-haystack | test_haystack/elasticsearch5_tests/test_backend.py | {
"start": 26547,
"end": 28777
} | class ____(TestCase):
fixtures = ["base_data.json"]
def setUp(self):
super().setUp()
# Wipe it clean.
clear_elasticsearch_index()
# Stow.
self.old_ui = connections["elasticsearch"].get_unified_index()
self.ui = UnifiedIndex()
self.smmi = Elasticsearch5M... | LiveElasticsearch5SearchQueryTestCase |
python | ray-project__ray | python/ray/util/client/server/proxier.py | {
"start": 1894,
"end": 3749
} | class ____:
port: int
process_handle_future: futures.Future
channel: "grpc._channel.Channel"
def is_ready(self) -> bool:
"""Check if the server is ready or not (doesn't block)."""
return self.process_handle_future.done()
def wait_ready(self, timeout: Optional[float] = None) -> None... | SpecificServer |
python | PrefectHQ__prefect | tests/runner/test_runner.py | {
"start": 3435,
"end": 3765
} | class ____:
@flow(on_cancellation=[instance_on_cancellation], log_prints=True)
def cancellable_flow(self, sleep_time: int = 100):
sleep(sleep_time)
def instance_on_crashed(flow, flow_run, state):
logger = flow_run_logger(flow_run, flow)
logger.info("Instance method flow crashed!")
| ClassWithCancellableFlow |
python | huggingface__transformers | src/transformers/models/emu3/modular_emu3.py | {
"start": 1504,
"end": 1612
} | class ____(LlamaAttention):
pass
# Has extra dropout which no other model in the library has
| Emu3Attention |
python | facebookresearch__faiss | tests/test_rowwise_minmax.py | {
"start": 277,
"end": 1545
} | class ____(unittest.TestCase):
def compare_train_vs_train_inplace(self, factory_key):
d = 96
nb = 1000
nq = 0
nt = 2000
xt, x, _ = get_dataset_2(d, nt, nb, nq)
assert x.size > 0
codec = faiss.index_factory(d, factory_key)
# use the regular .train()... | TestIndexRowwiseMinmax |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.