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 | sqlalchemy__sqlalchemy | test/sql/test_delete.py | {
"start": 1126,
"end": 4497
} | class ____(_DeleteTestBase, fixtures.TablesTest, AssertsCompiledSQL):
__dialect__ = "default"
def test_delete_literal_binds(self):
table1 = self.tables.mytable
stmt = table1.delete().where(table1.c.name == "jill")
self.assert_compile(
stmt,
"DELETE FROM mytable... | DeleteTest |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0068_migrate_anomaly_detection_alerts.py | {
"start": 5111,
"end": 31794
} | class ____:
"""
OnCallDataBlob is a specific type that represents the data blob for a PagerDuty or Opsgenie notification action.
"""
priority: str = ""
action_schema_mapping: dict[str, ActionSchemas] = {
ActionType.EMAIL: ActionSchemas(
config_schema={
"$schema": "https://json... | OnCallDataBlob |
python | getsentry__sentry | src/sentry/grouping/enhancer/matchers.py | {
"start": 11403,
"end": 11825
} | class ____(FrameMatch):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._ref_val = bool_from_string(self.pattern)
def _positive_frame_match(
self, match_frame: MatchFrame, exception_data: dict[str, Any], cache: ReturnValueCache
) -> bool:
ref_val ... | InAppMatch |
python | getsentry__sentry | src/sentry/remote_subscriptions/consumers/result_consumer.py | {
"start": 3765,
"end": 12065
} | class ____(ProcessingStrategyFactory[KafkaPayload], Generic[T, U]):
parallel_executor: ThreadPoolExecutor | None = None
batched_parallel = False
"""
Does the consumer process unrelated messages in parallel?
"""
max_batch_size = 500
"""
How many messages will be batched at once when in ... | ResultsStrategyFactory |
python | streamlit__streamlit | lib/tests/streamlit/elements/vega_charts_test.py | {
"start": 19606,
"end": 29352
} | class ____(DeltaGeneratorTestCase):
"""Test altair_chart width parameter functionality."""
@parameterized.expand(
[
# width, expected_width_spec, expected_width_value
("stretch", "use_stretch", True),
("content", "use_content", True),
(500, "pixel_width",... | AltairChartWidthTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 20567,
"end": 29136
} | class ____(SageMakerBaseOperator):
"""
When you create a serverless endpoint, SageMaker provisions and manages the compute resources for you.
Then, you can make inference requests to the endpoint and receive model predictions
in response. SageMaker scales the compute resources up and down as needed to ... | SageMakerEndpointOperator |
python | ipython__ipython | IPython/core/oinspect.py | {
"start": 4299,
"end": 10943
} | class ____:
"""Data passed to the mime hook"""
obj: Any
info: Optional[OInfo]
info_dict: InfoDict
detail_level: int
omit_sections: list[str]
@undoc
def object_info(
*,
name: str,
found: bool,
isclass: bool = False,
isalias: bool = False,
ismagic: bool = False,
**kw... | InspectorHookData |
python | explosion__spaCy | spacy/lang/ga/__init__.py | {
"start": 237,
"end": 350
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
stop_words = STOP_WORDS
| IrishDefaults |
python | pytorch__pytorch | test/package/package_d/imports_directly.py | {
"start": 75,
"end": 218
} | class ____(torch.nn.Module):
key = important_string
def forward(self, inp):
return torch.sum(inp)
| ImportsDirectlyFromSubSubPackage |
python | huggingface__transformers | src/transformers/models/blip_2/modeling_blip_2.py | {
"start": 6848,
"end": 11087
} | class ____(nn.Module):
def __init__(self, config: Blip2VisionConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.image_size = config.image_size
self.patch_size = config.patch_size
self.class_embedding = nn.Parameter(torch.randn(1... | Blip2VisionEmbeddings |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/bigtable.py | {
"start": 1458,
"end": 1660
} | class ____(BaseGoogleLink):
"""Helper class for constructing Bigtable Cluster link."""
name = "Bigtable Cluster"
key = "cluster_key"
format_str = BIGTABLE_CLUSTER_LINK
| BigtableClusterLink |
python | jazzband__django-oauth-toolkit | tests/models.py | {
"start": 1567,
"end": 1731
} | class ____(AbstractIDToken):
"""Exists to be improperly configured for multiple databases."""
# The other token types will be in 'alpha' database.
| LocalIDToken |
python | getsentry__sentry | src/sentry/notifications/types.py | {
"start": 6022,
"end": 7435
} | class ____:
implicit = -1 # not for use as a persisted field value
committed = -2 # not for use as a persisted field value
processing_issue = -3 # not for use as a persisted field value
unknown = 0
comment = 1
assigned = 2
bookmark = 3
status_change = 4
deploy_setting = 5
men... | GroupSubscriptionReason |
python | django__django | tests/model_forms/models.py | {
"start": 711,
"end": 855
} | class ____(models.Manager):
def get_queryset(self):
qs = super().get_queryset()
return qs.filter(archived=False)
| WriterManager |
python | spack__spack | lib/spack/spack/modules/common.py | {
"start": 16885,
"end": 18932
} | class ____:
"""Provides information on the layout of module files. Needs to be
sub-classed for specific module types.
"""
#: This needs to be redefined
extension: Optional[str] = None
def __init__(self, configuration):
self.conf = configuration
@property
def spec(self):
... | BaseFileLayout |
python | ray-project__ray | rllib/env/tests/test_multi_agent_episode.py | {
"start": 4928,
"end": 159285
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_init(self):
# Create an empty episode.
episode = MultiAgentEpisode()
# Empty episode should have a start ... | TestMultiAgentEpisode |
python | pyparsing__pyparsing | tests/test_simple_unit.py | {
"start": 7036,
"end": 10381
} | class ____(PyparsingExpressionTestCase):
tests = [
PyparsingTest(
desc="Match several words",
expr=(pp.Word("x") | pp.Word("y"))[...],
text="xxyxxyyxxyxyxxxy",
expected_list=["xx", "y", "xx", "yy", "xx", "y", "x", "y", "xxx", "y"],
),
Pyparsing... | TestRepetition |
python | falconry__falcon | falcon/routing/compiled.py | {
"start": 45130,
"end": 45443
} | class ____(_CxChild):
def __init__(self, dict_value_name: str) -> None:
self._dict_value_name = dict_value_name
def src(self, indentation: int) -> str:
return '{0}params.update({1})'.format(
_TAB_STR * indentation,
self._dict_value_name,
)
| _CxSetParamsFromDict |
python | explosion__spaCy | spacy/training/pretrain.py | {
"start": 8051,
"end": 9710
} | class ____:
def __init__(self, frequency=1000000):
self.loss = 0.0
self.prev_loss = 0.0
self.nr_word = 0
self.words_per_epoch = Counter()
self.frequency = frequency
self.last_time = time.time()
self.last_update = 0
self.epoch_loss = 0.0
def update... | ProgressTracker |
python | walkccc__LeetCode | solutions/3336. Find the Number of Subsequences With Equal GCD/3336-2.py | {
"start": 0,
"end": 1006
} | class ____:
def subsequencePairCount(self, nums: list[int]) -> int:
MOD = 1_000_000_007
maxNum = max(nums)
# dp[i][x][y] := number of disjoint pairs `seq1` and `seq2` of
# nums[0..i - 1], where GCD(seq1) == x and GCD(seq2) == y
dp = [[[0] * (maxNum + 1)
for _ in range(maxNum + 1)]
... | Solution |
python | huggingface__transformers | src/transformers/models/marian/modeling_marian.py | {
"start": 26264,
"end": 37432
} | class ____(MarianPreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`MarianDecoderLayer`]
Args:
config: MarianConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(self, config: MarianConfig):
super().__i... | MarianDecoder |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/associationproxy.py | {
"start": 11584,
"end": 11738
} | class ____(Protocol):
def __call__(
self, proxy: _AssociationCollection[Any], collection: Iterable[Any]
) -> None: ...
| _ProxyBulkSetProtocol |
python | ansible__ansible | lib/ansible/playbook/conditional.py | {
"start": 869,
"end": 1317
} | class ____:
"""
This is a mix-in class, to be used with Base to allow the object
to be run conditionally when a condition is met or skipped.
"""
when = FieldAttribute(isa='list', default=list, extend=True, prepend=True)
def __init__(self, *args, **kwargs):
super().__init__()
def _... | Conditional |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 867535,
"end": 868313
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for PullRequestChangedFile."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PullRequestChangedFileEdge"), graphql_name="edges")
"""A list of... | PullRequestChangedFileConnection |
python | pyparsing__pyparsing | examples/TAP.py | {
"start": 2540,
"end": 7553
} | class ____:
def __init__(self, results):
self.passedTests = []
self.failedTests = []
self.skippedTests = []
self.todoTests = []
self.bonusTests = []
self.bail = False
if results.plan:
expected = list(range(1, int(results.plan.ubound) + 1))
... | TAPSummary |
python | PyCQA__pylint | tests/checkers/unittest_typecheck.py | {
"start": 5797,
"end": 7465
} | class ____:
"""Tests for the _string_distance helper in pylint.checkers.typecheck."""
def test_string_distance_identical_strings(self) -> None:
seq1 = "hi"
seq2 = "hi"
assert typecheck._string_distance(seq1, seq2, len(seq1), len(seq2)) == 0
seq1, seq2 = seq2, seq1
asser... | TestTypeCheckerStringDistance |
python | pallets__werkzeug | src/werkzeug/middleware/lint.py | {
"start": 817,
"end": 890
} | class ____(Warning):
"""Warning class for WSGI warnings."""
| WSGIWarning |
python | getsentry__sentry | tests/sentry/options/test_store.py | {
"start": 519,
"end": 6428
} | class ____(TestCase):
@cached_property
def store(self):
c = LocMemCache("test", settings.CACHES["default"])
c.clear()
return OptionsStore(cache=c)
@cached_property
def manager(self):
return OptionsManager(store=self.store)
@cached_property
def key(self):
... | OptionsStoreTest |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofwork.py | {
"start": 2630,
"end": 4696
} | class ____(fixtures.MappedTest):
__requires__ = ("unicode_connections",)
@classmethod
def define_tables(cls, metadata):
uni_type = sa.Unicode(50).with_variant(
sa.Unicode(50, collation="utf8_unicode_ci"), "mysql"
)
Table(
"uni_t1",
metadata,
... | UnicodeTest |
python | wandb__wandb | landfill/functional_tests/artifacts/public-link-model.py | {
"start": 126,
"end": 1475
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10... | Net |
python | fluentpython__example-code-2e | 10-dp-1class-func/strategy_param.py | {
"start": 1247,
"end": 1487
} | class ____:
def __init__(self, product: str, quantity: int, price: float):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
| LineItem |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar20.py | {
"start": 315,
"end": 1421
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar20.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | streamlit__streamlit | lib/streamlit/elements/widgets/file_uploader.py | {
"start": 5035,
"end": 21218
} | class ____:
# Multiple overloads are defined on `file_uploader()` below to represent
# the different return types of `file_uploader()`.
# These return types differ according to the value of the `accept_multiple_files` argument.
# There must be 2x2=4 overloads to cover all the possible arguments,
# a... | FileUploaderMixin |
python | wandb__wandb | wandb/sdk/data_types/html.py | {
"start": 4900,
"end": 5019
} | class ____(_dtypes.Type):
name = "html-file"
types = [Html]
_dtypes.TypeRegistry.add(_HtmlFileType)
| _HtmlFileType |
python | pytest-dev__pytest | src/_pytest/warning_types.py | {
"start": 2272,
"end": 2595
} | class ____(PytestWarning):
"""An unraisable exception was reported.
Unraisable exceptions are exceptions raised in :meth:`__del__ <object.__del__>`
implementations and similar situations when the exception cannot be raised
as normal.
"""
__module__ = "pytest"
@final
| PytestUnraisableExceptionWarning |
python | keras-team__keras | guides/custom_train_step_in_tensorflow.py | {
"start": 12117,
"end": 16172
} | class ____(keras.Model):
def __init__(self, discriminator, generator, latent_dim):
super().__init__()
self.discriminator = discriminator
self.generator = generator
self.latent_dim = latent_dim
self.d_loss_tracker = keras.metrics.Mean(name="d_loss")
self.g_loss_tracker... | GAN |
python | ray-project__ray | rllib/examples/envs/classes/cartpole_with_dict_observation_space.py | {
"start": 100,
"end": 2923
} | class ____(CartPoleEnv):
"""CartPole gym environment that has a dict observation space.
However, otherwise, the information content in each observation remains the same.
https://github.com/Farama-Foundation/Gymnasium/blob/main/gymnasium/envs/classic_control/cartpole.py # noqa
The new observation spa... | CartPoleWithDictObservationSpace |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 15360,
"end": 15539
} | class ____(AbstractTemplate):
def generic(self, args, kws):
[lhs, rhs] = args
return signature(types.boolean, lhs, rhs)
@infer_global(operator.is_)
| CmpOpIdentity |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 577615,
"end": 578235
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("ReleaseAssetEdge"), graphql_name="edges"
)
nodes = sgqlc.... | ReleaseAssetConnection |
python | numpy__numpy | numpy/lib/tests/test_mixins.py | {
"start": 230,
"end": 2895
} | class ____(np.lib.mixins.NDArrayOperatorsMixin):
def __init__(self, value):
self.value = np.asarray(value)
# One might also consider adding the built-in list type to this
# list, to support operations like np.add(array_like, list)
_HANDLED_TYPES = (np.ndarray, numbers.Number)
def __array_u... | ArrayLike |
python | django__django | tests/template_tests/filter_tests/test_capfirst.py | {
"start": 166,
"end": 879
} | class ____(SimpleTestCase):
@setup(
{
"capfirst01": (
"{% autoescape off %}{{ a|capfirst }} {{ b|capfirst }}"
"{% endautoescape %}"
)
}
)
def test_capfirst01(self):
output = self.engine.render_to_string(
"capfirst01"... | CapfirstTests |
python | getsentry__sentry | src/sentry/projects/project_rules/updater.py | {
"start": 445,
"end": 2662
} | class ____:
rule: Rule
project: Project
name: str | None = None
owner: Actor | None = None
environment: int | None = None
action_match: str | None = None
filter_match: str | None = None
actions: Sequence[dict[str, str]] | None = None
conditions: Sequence[dict[str, str]] | None = None... | ProjectRuleUpdater |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/ProgressDialog.py | {
"start": 105,
"end": 8791
} | class ____(QtWidgets.QProgressDialog):
"""
Extends QProgressDialog:
* Adds context management so the dialog may be used in `with` statements
* Allows nesting multiple progress dialogs
Example::
with ProgressDialog("Processing..", minVal, maxVal) as dlg:
# do stuff
... | ProgressDialog |
python | kubernetes-client__python | kubernetes/client/models/v1_local_volume_source.py | {
"start": 383,
"end": 4972
} | 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... | V1LocalVolumeSource |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/auto_materialize_rule_impls.py | {
"start": 33648,
"end": 45048
} | class ____(
AutoMaterializeRule,
NamedTuple(
"_SkipOnNotAllParentsUpdatedSinceCronRule",
[("cron_schedule", str), ("timezone", str)],
),
):
@property
def decision_type(self) -> AutoMaterializeDecisionType:
return AutoMaterializeDecisionType.SKIP
@property
def descrip... | SkipOnNotAllParentsUpdatedSinceCronRule |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/np_logic_test.py | {
"start": 1056,
"end": 3628
} | class ____(test.TestCase):
def setUp(self):
super(LogicTest, self).setUp()
self.array_transforms = [
lambda x: x, # Identity,
ops.convert_to_tensor,
np.array,
lambda x: np.array(x, dtype=np.int32),
lambda x: np.array(x, dtype=np.int64),
lambda x: np.array(x, d... | LogicTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/assets.py | {
"start": 983,
"end": 1133
} | class ____(graphene.Union):
class Meta:
types = (GrapheneAsset, GrapheneAssetNotFoundError)
name = "AssetOrError"
| GrapheneAssetOrError |
python | pypa__hatch | src/hatch/errors/__init__.py | {
"start": 40,
"end": 101
} | class ____(HatchError):
pass
| PythonDistributionUnknownError |
python | EpistasisLab__tpot | tpot/search_spaces/nodes/genetic_feature_selection.py | {
"start": 7085,
"end": 9438
} | class ____(SearchSpace):
def __init__(self,
n_features,
start_p=0.2,
mutation_rate = 0.1,
crossover_rate = 0.1,
mutation_rate_rate = 0, # These are still experimental but seem to help. Theory is ... | GeneticFeatureSelectorNode |
python | huggingface__transformers | src/transformers/models/metaclip_2/modular_metaclip_2.py | {
"start": 20619,
"end": 27423
} | class ____(CLIPModel):
"""
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a PyTorch [torch.nn.Modu... | MetaClip2Model |
python | apache__airflow | task-sdk/tests/task_sdk/bases/test_sensor.py | {
"start": 2034,
"end": 2316
} | class ____(BaseSensorOperator):
def __init__(self, return_value=False, **kwargs):
super().__init__(**kwargs)
self.return_value = return_value
def execute_complete(self, context, event=None):
raise AirflowException("Should be skipped")
| DummyAsyncSensor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadImpl2.py | {
"start": 504,
"end": 554
} | class ____(Protocol[T_co]):
_target_: str
| ClassA |
python | getsentry__sentry | tests/sentry/ratelimits/test_cardinality.py | {
"start": 288,
"end": 8550
} | class ____:
"""
Wrapper interface around the rate limiter, with specialized, stateful and
primitive interface for more readable tests.
"""
def __init__(self, limiter: RedisCardinalityLimiter):
self.limiter = limiter
self.quota = Quota(window_seconds=3600, granularity_seconds=60, lim... | LimiterHelper |
python | huggingface__transformers | tests/models/gpt_oss/test_modeling_gpt_oss.py | {
"start": 1437,
"end": 6699
} | class ____(CausalLMModelTest, unittest.TestCase):
_is_stateful = True
model_split_percents = [0.5, 0.6]
model_tester_class = GptOssModelTester
@unittest.skip("GptOss's forcefully disables sdpa due to Sink")
def test_sdpa_can_dispatch_non_composite_models(self):
pass
@unittest.skip("Gpt... | GptOssModelTest |
python | pytorch__pytorch | torch/distributed/tensor/experimental/_context_parallel/_attention.py | {
"start": 1557,
"end": 1712
} | class ____(Enum):
MONKEY_PATCH = auto()
MODULE_WRAPPER = auto()
_dispatch_mode: _DispatchMode = _DispatchMode.MONKEY_PATCH
@dataclass
| _DispatchMode |
python | sympy__sympy | sympy/integrals/transforms.py | {
"start": 49441,
"end": 51750
} | class ____(HankelTypeTransform):
"""
Class representing unevaluated inverse Hankel transforms.
For usage of this class, see the :class:`IntegralTransform` docstring.
For how to compute inverse Hankel transforms, see the
:func:`inverse_hankel_transform` docstring.
"""
_name = 'Inverse Hank... | InverseHankelTransform |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/extension.py | {
"start": 15003,
"end": 16585
} | class ____:
def __init__(self, config_file_path: str | None = None) -> None:
self.config_file_path = config_file_path
def makeExtension( # noqa: N802
*,
default_handler: str | None = None,
inventory_project: str | None = None,
inventory_version: str | None = None,
handlers: dict[str, ... | _ToolConfig |
python | kamyu104__LeetCode-Solutions | Python/grid-game.py | {
"start": 48,
"end": 422
} | class ____(object):
def gridGame(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
result = float("inf")
left, right = 0, sum(grid[0])
for a, b in itertools.izip(grid[0], grid[1]):
right -= a
result = min(result, max(left, ri... | Solution |
python | vyperlang__vyper | vyper/venom/check_venom.py | {
"start": 547,
"end": 845
} | class ____(VenomError):
message: str = "variable is used before definition"
def __init__(self, var, inst):
self.var = var
self.inst = inst
def __str__(self):
bb = self.inst.parent
return f"var {self.var} not defined:\n {self.inst}\n\n{bb}"
| VarNotDefined |
python | google__pytype | pytype/pytd/visitors.py | {
"start": 71162,
"end": 71687
} | class ____(_RemoveTypeParametersFromGenericAny):
"""Replace all references to modules in a list with AnythingType."""
def __init__(self, module_list: list[str]):
super().__init__()
self._any_modules = module_list
def VisitNamedType(self, n):
if any(n.name.startswith(module) for module in self._any_m... | ReplaceModulesWithAny |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/pythonic_config/typing_utils.py | {
"start": 1226,
"end": 2604
} | class ____:
_TResValue = TypeVar("_TResValue")
class _Temp(Generic[_TResValue]):
pass
_ResourceDep: type = _Temp
_Resource: type = _Temp
_PartialResource: type = _Temp
@staticmethod
def get_resource_rep_type() -> type:
return LateBoundTypesForResourceTypeChecking._Resource... | LateBoundTypesForResourceTypeChecking |
python | pypa__hatch | tests/index/test_core.py | {
"start": 312,
"end": 1447
} | class ____:
@pytest.mark.parametrize(
("repo_url", "expected_url"),
[
pytest.param("https://upload.pypi.org/legacy/", "https://pypi.org/simple/", id="PyPI main"),
pytest.param("https://test.pypi.org/legacy/", "https://test.pypi.org/simple/", id="PyPI test"),
pytes... | TestURLs |
python | numpy__numpy | numpy/polynomial/tests/test_legendre.py | {
"start": 3447,
"end": 6100
} | class ____:
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([2., 2., 2.])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
# some random values in [-1, 1)
x = np.random.random((3, 5)) * 2 - 1
y = polyval(x, [1., 2., 3.])
def test_legval(self):
... | TestEvaluation |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 1058,
"end": 1417
} | class ____(Event):
name: str = "start_trace"
@classmethod
def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None:
# Capture the set of currently imported packages at trace start time to
# understand the flavor of the trace.
return {"imports": [pkg for pkg in GENAI_MODULE... | StartTraceEvent |
python | huggingface__transformers | src/transformers/data/processors/glue.py | {
"start": 8444,
"end": 10150
} | class ____(DataProcessor):
"""Processor for the CoLA data set (GLUE version)."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning)
def get_example_from_tensor_dict(self, tensor_dict):
"""See ... | ColaProcessor |
python | wandb__wandb | wandb/apis/public/projects.py | {
"start": 1308,
"end": 4596
} | class ____(Paginator["Project"]):
"""An lazy iterator of `Project` objects.
An iterable interface to access projects created and saved by the entity.
Args:
client (`wandb.apis.internal.Api`): The API client instance to use.
entity (str): The entity name (username or team) to fetch projects... | Projects |
python | getsentry__sentry | src/sentry/core/endpoints/team_release_count.py | {
"start": 673,
"end": 2870
} | class ____(TeamEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request, team) -> Response:
"""
Returns a dict of team projects, and a time-series list of release counts for each.
"""
if not features.has("organizations:team-insi... | TeamReleaseCountEndpoint |
python | django-extensions__django-extensions | tests/test_runscript.py | {
"start": 5434,
"end": 6771
} | class ____(RunScriptTests):
def test_prints_error_message_for_script_without_run(self):
cmd = self.get_command()
with self.assertRaises(CommandError):
call_command(cmd, "script_no_run_function")
self.assertIn(
"No (valid) module for script 'script_no_run_function' fou... | RunFunctionTests |
python | wandb__wandb | wandb/sdk/artifacts/_generated/artifact_used_by.py | {
"start": 336,
"end": 445
} | class ____(GQLResult):
used_by: ArtifactUsedByArtifactUsedBy = Field(alias="usedBy")
| ArtifactUsedByArtifact |
python | keras-team__keras | keras/src/layers/reshaping/permute_test.py | {
"start": 190,
"end": 2712
} | class ____(testing.TestCase):
@parameterized.named_parameters(
[
{"testcase_name": "dense", "sparse": False},
{"testcase_name": "sparse", "sparse": True},
]
)
@pytest.mark.requires_trainable_backend
def test_permute(self, sparse):
if sparse and not backend... | PermuteTest |
python | django__django | tests/auth_tests/test_management.py | {
"start": 11147,
"end": 47933
} | class ____(TestCase):
def test_no_email_argument(self):
new_io = StringIO()
with self.assertRaisesMessage(
CommandError, "You must use --email with --noinput."
):
call_command(
"createsuperuser", interactive=False, username="joe", stdout=new_io
... | CreatesuperuserManagementCommandTestCase |
python | getsentry__sentry | src/sentry/data_export/base.py | {
"start": 215,
"end": 393
} | class ____(Exception):
def __init__(self, message: str, recoverable: bool = False) -> None:
super().__init__(message)
self.recoverable = recoverable
| ExportError |
python | kamyu104__LeetCode-Solutions | Python/find-elements-in-a-contaminated-binary-tree.py | {
"start": 191,
"end": 732
} | class ____(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
def dfs(node, v, lookup):
if not node:
return
node.val = v
lookup.add(v)
dfs(node.left, 2*v+1, lookup)
dfs(node.right, 2*v+2, lo... | FindElements |
python | pytorch__pytorch | torch/_inductor/config.py | {
"start": 53889,
"end": 66124
} | class ____:
"""
Config specific to codegen/triton.py
"""
# Use cudagraphs on output code
cudagraphs = os.environ.get("TORCHINDUCTOR_CUDAGRAPHS") == "1"
# Use cudagraph trees for memory pooling if `cudagraphs` is True
cudagraph_trees = True
# Should we skip cudagraphing graphs with dyn... | triton |
python | optuna__optuna | optuna/exceptions.py | {
"start": 1614,
"end": 1765
} | class ____(OptunaError):
"""Exception for CLI.
CLI raises this exception when it receives invalid configuration.
"""
pass
| CLIUsageError |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 61635,
"end": 64677
} | class ____(TestCase):
def test_8420_set_merge(self):
# This used to segfault
global be_bad, set2, dict2
be_bad = False
set1 = {bad_eq()}
set2 = {bad_eq() for i in range(75)}
be_bad = True
self.assertRaises(ZeroDivisionError, set1.update, set2)
be_bad ... | TestWeirdBugs |
python | dagster-io__dagster | python_modules/libraries/dagster-sigma/dagster_sigma/translator.py | {
"start": 3630,
"end": 4137
} | class ____:
"""A record representing a Sigma dataset and the Sigma organization data."""
dataset: "SigmaDataset"
organization_data: "SigmaOrganizationData"
@property
def properties(self) -> dict[str, Any]:
return self.dataset.properties
@property
def columns(self) -> AbstractSet[s... | SigmaDatasetTranslatorData |
python | pytorch__pytorch | torchgen/dest/lazy_ir.py | {
"start": 5871,
"end": 12516
} | class ____(ABC):
backend_index: BackendIndex
backend_name: str
node_base: str
use_lazy_shape: bool
@method_with_native_function
def __call__(self, f: NativeFunctionsGroup | NativeFunction) -> list[str]:
func = f.functional.func if isinstance(f, NativeFunctionsGroup) else f.func
... | GenLazyIR |
python | mlflow__mlflow | mlflow/models/resources.py | {
"start": 537,
"end": 1623
} | class ____(ABC):
"""
Base class for defining the resources needed to serve a model.
Args:
type (ResourceType): The resource type.
target_uri (str): The target URI where these resources are hosted.
"""
@property
@abstractmethod
def type(self) -> ResourceType:
"""
... | Resource |
python | ray-project__ray | release/microbenchmark/experimental/compiled_graph_gpu_microbenchmark.py | {
"start": 1498,
"end": 2021
} | class ____:
def __init__(self):
self.device = torch_utils.get_devices()[0]
def send(self, shape, dtype, _):
t = torch.ones(shape, dtype=dtype, device=self.device) * 1
return t
def recv(self, tensor):
# This benchmark tests the overhead of sending a tensor between
# ... | TorchTensorWorker |
python | allegroai__clearml | clearml/automation/hpbandster/bandster.py | {
"start": 4638,
"end": 18321
} | class ____(SearchStrategy, RandomSeed):
def __init__(
self,
base_task_id: str,
hyper_parameters: Sequence[Parameter],
objective_metric: Objective,
execution_queue: str,
num_concurrent_workers: int,
min_iteration_per_job: Optional[int],
max_iteration_pe... | OptimizerBOHB |
python | doocs__leetcode | solution/3100-3199/3165.Maximum Sum of Subsequence With Non-adjacent Elements/Solution.py | {
"start": 263,
"end": 1721
} | class ____:
__slots__ = "tr"
def __init__(self, n: int):
self.tr: List[Node | None] = [None] * (n << 2)
self.build(1, 1, n)
def build(self, u: int, l: int, r: int):
self.tr[u] = Node(l, r)
if l == r:
return
mid = (l + r) >> 1
self.build(u << 1, l... | SegmentTree |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 11878,
"end": 11984
} | class ____(PrefectException):
"""
Raised when a configuration is invalid.
"""
| ConfigurationError |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/syntax.py | {
"start": 7705,
"end": 35896
} | class ____(JupyterMixin):
"""Construct a Syntax object to render syntax highlighted code.
Args:
code (str): Code to highlight.
lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)
theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/... | Syntax |
python | donnemartin__interactive-coding-challenges | stacks_queues/set_of_stacks/test_set_of_stacks.py | {
"start": 18,
"end": 853
} | class ____(unittest.TestCase):
def test_set_of_stacks(self):
print('Test: Push on an empty stack')
stacks = SetOfStacks(indiv_stack_capacity=2)
stacks.push(3)
print('Test: Push on a non-empty stack')
stacks.push(5)
print('Test: Push on a capacity stack to create a ... | TestSetOfStacks |
python | jina-ai__jina | tests/unit/jaml/test_type_parse.py | {
"start": 281,
"end": 347
} | class ____(BaseExecutor):
pass
@dataclasses.dataclass
| MyExecutor |
python | Netflix__metaflow | test/core/metaflow_test/metadata_check.py | {
"start": 225,
"end": 8077
} | class ____(MetaflowCheck):
def __init__(self, flow):
from metaflow.client import Flow, get_namespace
self.flow = flow
self.run = Flow(flow.name)[self.run_id]
expected_steps = set(step.name for step in flow)
actual_steps = set(step.id for step in self.run)
assert actu... | MetadataCheck |
python | graphql-python__graphene | graphene/types/tests/test_definition.py | {
"start": 1214,
"end": 1252
} | class ____(Enum):
foo = "foo"
| MyEnum |
python | pytorch__pytorch | torch/_dynamo/exc.py | {
"start": 9731,
"end": 9917
} | class ____(ObservedException):
# An AttributeError exception to be raised from inside Dynamo tracing. This can happen on user defined object __getattr__
pass
| ObservedAttributeError |
python | simplejson__simplejson | simplejson/tests/test_tuple.py | {
"start": 83,
"end": 1831
} | class ____(unittest.TestCase):
def test_tuple_array_dumps(self):
t = (1, 2, 3)
expect = json.dumps(list(t))
# Default is True
self.assertEqual(expect, json.dumps(t))
self.assertEqual(expect, json.dumps(t, tuple_as_array=True))
self.assertRaises(TypeError, json.dumps, ... | TestTuples |
python | rq__rq | rq/worker_pool.py | {
"start": 770,
"end": 850
} | class ____(NamedTuple):
name: str
pid: int
process: Process
| WorkerData |
python | langchain-ai__langchain | libs/langchain/langchain_classic/indexes/_sql_record_manager.py | {
"start": 1363,
"end": 2479
} | class ____(Base): # type: ignore[valid-type,misc]
"""Table used to keep track of when a key was last updated."""
# ATTENTION:
# Prior to modifying this table, please determine whether
# we should create migrations for this table to make sure
# users do not experience data loss.
__tablename__ =... | UpsertionRecord |
python | ray-project__ray | release/train_tests/benchmark/recsys/recsys_factory.py | {
"start": 2151,
"end": 8779
} | class ____(BenchmarkFactory):
def __init__(self, benchmark_config: BenchmarkConfig):
super().__init__(benchmark_config)
self.torchrec_config = TorchRecConfig()
def get_dataloader_factory(self) -> BaseDataLoaderFactory:
data_factory_cls = {
DataloaderType.MOCK: RecsysMockDat... | RecsysFactory |
python | numpy__numpy | numpy/_core/tests/test_indexing.py | {
"start": 48051,
"end": 49672
} | class ____:
"""
These test that ``TypeError`` is raised when you try to use
non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]``
and ``a[0.5]``, or other functions like ``array.reshape(1., -1)``.
"""
def test_valid_indexing(self):
# These should raise no errors.
... | TestFloatNonIntegerArgument |
python | PyCQA__pylint | doc/data/messages/m/multiple-class-sub-patterns/bad.py | {
"start": 0,
"end": 359
} | class ____:
__match_args__ = ("title", "year")
def __init__(self, title, year):
self.title = title
self.year = year
def func(item: Book):
match item:
case Book("abc", title="abc"): # [multiple-class-sub-patterns]
...
case Book(year=2000, year=2001): # [multip... | Book |
python | yaml__pyyaml | tests/legacy_tests/canonical.py | {
"start": 11071,
"end": 12371
} | class ____(CanonicalScanner, CanonicalParser,
yaml.composer.Composer, yaml.constructor.Constructor, yaml.resolver.Resolver):
def __init__(self, stream):
if hasattr(stream, 'read'):
stream = stream.read()
CanonicalScanner.__init__(self, stream)
CanonicalParser.__init__(se... | CanonicalLoader |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/interfaces.py | {
"start": 4517,
"end": 4658
} | class ____(roles.FromClauseRole):
__slots__ = ()
_role_name = "ORM mapped entity, aliased entity, or FROM expression"
| ORMFromClauseRole |
python | donnemartin__system-design-primer | solutions/object_oriented_design/online_chat/online_chat.py | {
"start": 504,
"end": 1441
} | class ____(object):
def __init__(self, user_id, name, pass_hash):
self.user_id = user_id
self.name = name
self.pass_hash = pass_hash
self.friends_by_id = {} # key: friend id, value: User
self.friend_ids_to_private_chats = {} # key: friend id, value: private chats
s... | User |
python | apache__thrift | lib/py/src/transport/TTwisted.py | {
"start": 8691,
"end": 9098
} | class ____(ServerFactory):
protocol = ThriftServerProtocol
def __init__(self, processor, iprot_factory, oprot_factory=None):
self.processor = processor
self.iprot_factory = iprot_factory
if oprot_factory is None:
self.oprot_factory = iprot_factory
else:
... | ThriftServerFactory |
python | getsentry__sentry | src/sentry/api/serializers/models/group_stream.py | {
"start": 9506,
"end": 9670
} | class ____(TypedDict):
count: str
userCount: int
firstSeen: datetime | None
lastSeen: datetime | None
stats: NotRequired[dict[str, Any]]
| _Filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.