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 | apache__airflow | providers/smtp/tests/unit/smtp/hooks/test_smtp.py | {
"start": 2404,
"end": 17914
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=CONN_ID_DEFAULT,
conn_type=CONN_TYPE,
host=SMTP_HOST,
login=SMTP_LOGIN,
... | TestSmtpHook |
python | kamyu104__LeetCode-Solutions | Python/maximize-profit-from-task-assignment.py | {
"start": 85,
"end": 642
} | class ____(object):
def maxProfit(self, workers, tasks):
"""
:type workers: List[int]
:type tasks: List[List[int]]
:rtype: int
"""
cnt = collections.defaultdict(int)
for x in workers:
cnt[x] += 1
tasks.sort(key=lambda x: x[1], reverse=True)... | Solution |
python | walkccc__LeetCode | solutions/3378. Count Connected Components in LCM Graph/3378.py | {
"start": 554,
"end": 829
} | class ____:
def countComponents(self, nums: list[int], threshold: int) -> int:
uf = UnionFind()
for num in nums:
for multiple in range(2 * num, threshold + 1, num):
uf.unionByRank(num, multiple)
return len(set(uf.find(num) for num in nums))
| Solution |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/query_metrics/query_table/query_table.py | {
"start": 610,
"end": 2553
} | class ____(QueryMetricProvider):
metric_name = "query.table"
value_keys = ("query",)
@metric_value(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(
cls,
execution_engine: SqlAlchemyExecutionEngine,
metric_domain_kwargs: dict,
metric_value_kwargs: dict,
metrics:... | QueryTable |
python | getsentry__sentry | src/sentry/grouping/enhancer/actions.py | {
"start": 6138,
"end": 7805
} | class ____(EnhancementAction):
_VALUE_PARSERS: dict[str, Callable[[Any], Any]] = {
"max-frames": int,
"min-frames": int,
"category": lambda x: x,
}
_FRAME_VARIABLES = {"category"}
def __init__(self, var: str, value: str) -> None:
self.var = var
self.is_classifie... | VarAction |
python | scikit-learn__scikit-learn | sklearn/tree/_classes.py | {
"start": 55420,
"end": 67361
} | class ____(DecisionTreeClassifier):
"""An extremely randomized tree classifier.
Extra-trees differ from classic decision trees in the way they are built.
When looking for the best split to separate the samples of a node into two
groups, random splits are drawn for each of the `max_features` randomly
... | ExtraTreeClassifier |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 86428,
"end": 86520
} | class ____(openblas_lapack_info):
_lib_names = ['openblas', 'lapack']
| openblas_clapack_info |
python | joke2k__faker | faker/providers/person/ja_JP/__init__.py | {
"start": 138,
"end": 9763
} | class ____(PersonProvider):
# link: http://dic.nicovideo.jp/a/日本人の名前一覧
# link: http://www.meijiyasuda.co.jp/enjoy/ranking/
first_name_female_pairs = (
("明美", "アケミ", "Akemi"),
("あすか", "アスカ", "Asuka"),
("香織", "カオリ", "Kaori"),
("加奈", "カナ", "Kana"),
("くみ子", "クミコ", "Kumiko... | Provider |
python | pola-rs__polars | py-polars/src/polars/datatypes/classes.py | {
"start": 9174,
"end": 9252
} | class ____(DataType):
"""Base class for temporal data types."""
| TemporalType |
python | bokeh__bokeh | src/bokeh/models/tickers.py | {
"start": 5648,
"end": 6179
} | class ____(ContinuousTicker):
''' Generate ticks at fixed, explicitly supplied locations.
.. note::
The ``desired_num_ticks`` property is ignored by this Ticker.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__ini... | FixedTicker |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/codemods/test_codemods.py | {
"start": 5399,
"end": 6193
} | class ____(CodemodTest):
TRANSFORM = codemods.HypothesisFixCharactersArguments
def test_substitution(self) -> None:
for in_, out in codemods.HypothesisFixCharactersArguments._replacements.items():
before = f"""
import hypothesis.strategies as st
st.characters... | TestFixCharactersArguments |
python | lepture__mistune | tests/test_hooks.py | {
"start": 131,
"end": 888
} | class ____(BaseTestCase):
@staticmethod
def parse(text):
md = create_markdown(escape=False)
add_toc_hook(md)
html, state = md.parse(text)
result = html + render_toc_ul(state.env["toc_items"])
return result
def test_customize_heading_id_func(self):
def heading... | TestTocHook |
python | pytest-dev__pytest | testing/test_pluginmanager.py | {
"start": 14846,
"end": 17294
} | class ____:
def test_preparse_args(self, pytestpm: PytestPluginManager) -> None:
pytest.raises(
ImportError, lambda: pytestpm.consider_preparse(["xyz", "-p", "hello123"])
)
# Handles -p without space (#3532).
with pytest.raises(ImportError) as excinfo:
pytest... | TestPytestPluginManagerBootstrapping |
python | numba__numba | numba/tests/test_sets.py | {
"start": 20450,
"end": 22692
} | class ____(BaseTest):
"""
Test reflection of native Numba sets on Python set objects.
"""
def check_reflection(self, pyfunc):
cfunc = jit(nopython=True)(pyfunc)
samples = [(set([1., 2., 3., 4.]), set([0.])),
(set([1., 2., 3., 4.]), set([5., 6., 7., 8., 9.])),
... | TestSetReflection |
python | apache__airflow | task-sdk/src/airflow/sdk/api/client.py | {
"start": 29374,
"end": 31405
} | class ____(httpx.Auth):
def __init__(self, token: str):
self.token: str = token
def auth_flow(self, request: httpx.Request):
if self.token:
request.headers["Authorization"] = "Bearer " + self.token
yield request
# This exists as an aid for debugging or local running via th... | BearerAuth |
python | great-expectations__great_expectations | great_expectations/types/fonts.py | {
"start": 188,
"end": 440
} | class ____(Enum):
MONTSERRAT = "https://fonts.googleapis.com/css2?family=Montserrat"
ROBOTO_MONO = "https://fonts.googleapis.com/css2?family=Roboto+Mono"
SOURCE_SANS_PRO = "https://fonts.googleapis.com/css2?family=Source+Sans+Pro"
| FontFamilyURL |
python | sqlalchemy__sqlalchemy | test/orm/test_eager_relations.py | {
"start": 137637,
"end": 144530
} | class ____(_fixtures.FixtureTest):
"""test that loaders from a base Query fully populate."""
run_inserts = "once"
run_deletes = None
def _collection_to_scalar_fixture(self):
User, Address, Dingaling = (
self.classes.User,
self.classes.Address,
self.classes.D... | LoadOnExistingTest |
python | django__django | django/db/models/fields/related_descriptors.py | {
"start": 40322,
"end": 66942
} | class ____(ReverseManyToOneDescriptor):
"""
Accessor to the related objects manager on the forward and reverse sides of
a many-to-many relation.
In the example::
class Pizza(Model):
toppings = ManyToManyField(Topping, related_name='pizzas')
``Pizza.toppings`` and ``Topping.piz... | ManyToManyDescriptor |
python | run-llama__llama_index | llama-index-integrations/postprocessor/llama-index-postprocessor-alibabacloud-aisearch-rerank/llama_index/postprocessor/alibabacloud_aisearch_rerank/base.py | {
"start": 1544,
"end": 5234
} | class ____(BaseNodePostprocessor):
"""
For further details, please visit `https://help.aliyun.com/zh/open-search/search-platform/developer-reference/ranker-api-details`.
"""
_client: Client = PrivateAttr()
aisearch_api_key: str = Field(default=None, exclude=True)
endpoint: str = None
serv... | AlibabaCloudAISearchRerank |
python | google__jax | tests/fused_attention_stablehlo_test.py | {
"start": 35703,
"end": 41228
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
try:
cudnn_version = check_cudnn_version()
except RuntimeError as e:
self.skipTest(str(e))
return
if cudnn_version == 91000:
self.skipTest("cuDNN 9.10.0 does not support SDPA FP8")
if not jtu.is_cuda_compute_cap... | DotProductAttentionF8Test |
python | tox-dev__tox | src/tox/session/cmd/run/common.py | {
"start": 948,
"end": 1473
} | class ____(Action):
def __call__(
self,
parser: ArgumentParser, # noqa: ARG002
namespace: Namespace,
values: str | Sequence[Any] | None,
option_string: str | None = None, # noqa: ARG002
) -> None:
value = "true" if values is None else values
if value not... | SkipMissingInterpreterAction |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/limit_and_offset/tutorial001_py310.py | {
"start": 392,
"end": 1618
} | class ____(HeroBase):
id: int
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
app = FastAPI()... | HeroPublic |
python | getsentry__sentry | src/sentry/explore/endpoints/serializers.py | {
"start": 568,
"end": 657
} | class ____(serializers.Serializer):
groupBy = serializers.CharField()
| GroupBySerializer |
python | numba__numba | numba/core/types/containers.py | {
"start": 15956,
"end": 16073
} | class ____(BaseContainerIterator):
"""
Type class for set iterators.
"""
container_class = Set
| SetIter |
python | mlflow__mlflow | tests/resources/mlflow-test-plugin/mlflow_test_plugin/request_auth_provider.py | {
"start": 94,
"end": 356
} | class ____(RequestAuthProvider):
"""RequestAuthProvider provided through plugin system"""
def get_name(self):
return "test_auth_provider_name"
def get_auth(self):
return {"auth_name": "test_auth_provider_name"}
| PluginRequestAuthProvider |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/output_parsers/tools.py | {
"start": 3053,
"end": 4034
} | class ____(MultiActionAgentOutputParser):
"""Parses a message into agent actions/finish.
If a tool_calls parameter is passed, then that is used to get
the tool names and tool inputs.
If one is not passed, then the AIMessage is assumed to be the final output.
"""
@property
def _type(self) ... | ToolsAgentOutputParser |
python | ray-project__ray | rllib/algorithms/iql/torch/iql_torch_learner.py | {
"start": 788,
"end": 9268
} | class ____(TorchLearner, IQLLearner):
"""Implements the IQL loss on top of `IQLLearner`.
This Learner implements configure_optimizers_for_module to define
separate optimizers for the policy, Q-, and value networks. When
using a twin-Q network architecture, each Q-network is assigned its
own optimiz... | IQLTorchLearner |
python | openai__openai-python | src/openai/types/image_gen_completed_event.py | {
"start": 871,
"end": 1745
} | class ____(BaseModel):
b64_json: str
"""Base64-encoded image data, suitable for rendering as an image."""
background: Literal["transparent", "opaque", "auto"]
"""The background setting for the generated image."""
created_at: int
"""The Unix timestamp when the event was created."""
output_... | ImageGenCompletedEvent |
python | mlflow__mlflow | dev/set_matrix.py | {
"start": 3957,
"end": 4410
} | class ____(BaseModel):
model_config = ConfigDict(extra="forbid")
package_info: PackageInfo
models: TestConfig | None = None
autologging: TestConfig | None = None
@property
def categories(self) -> list[tuple[str, TestConfig]]:
cs = []
if self.models:
cs.append(("mode... | FlavorConfig |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 3406,
"end": 3634
} | class ____(ConvConfig):
"""
ROCm subclass for Conv, with AMD backend specific tuneable kernargs
"""
matrix_instr_nonkdim: int = 16
waves_per_eu: int = 0
kpack: int = 2
@dataclasses.dataclass
| ROCmConvConfig |
python | scikit-learn__scikit-learn | sklearn/utils/_metadata_requests.py | {
"start": 19381,
"end": 26465
} | class ____:
"""Contains the metadata request info of a consumer.
Instances of `MethodMetadataRequest` are used in this class for each
available method under `metadatarequest.{method}`.
Consumer-only classes such as simple estimators return a serialized
version of this class as the output of `get_m... | MetadataRequest |
python | PrefectHQ__prefect | src/prefect/blocks/core.py | {
"start": 11388,
"end": 67055
} | class ____(BaseModel, ABC):
"""
A base class for implementing a block that wraps an external service.
This class can be defined with an arbitrary set of fields and methods, and
couples business logic with data contained in an block document.
`_block_document_name`, `_block_document_id`, `_block_sch... | Block |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 191318,
"end": 191752
} | class ____:
def test_sf_isf(self):
# reference values were computed via the reference distribution, e.g.
# mp.dps = 50; TruncExpon(b=b).sf(x)
b = [20, 100]
x = [19.999999, 99.999999]
ref = [2.0611546593828472e-15, 3.7200778266671455e-50]
assert_allclose(stats.truncex... | TestTruncexpon |
python | django__django | tests/serializers/models/data.py | {
"start": 7293,
"end": 7456
} | class ____(BaseModel):
parent = models.OneToOneField(BaseModel, models.CASCADE, parent_link=True)
child_data = models.IntegerField()
| ExplicitInheritBaseModel |
python | pytorch__pytorch | test/distributed/test_overlap_bucketing_unit.py | {
"start": 3690,
"end": 25750
} | class ____(InductorTestCase):
"""
Unit tests for overlap-preserving bucketing pass.
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
from torch.testing._internal.distributed.fake_pg import FakeStore
store = FakeStore()
dist.init_process_group(backend="fake... | TestOverlapPreservingBucketing |
python | pennersr__django-allauth | allauth/headless/account/inputs.py | {
"start": 7054,
"end": 7114
} | class ____(AddEmailForm, inputs.Input):
pass
| AddEmailInput |
python | huggingface__transformers | src/transformers/models/wavlm/modeling_wavlm.py | {
"start": 52018,
"end": 56900
} | class ____(WavLMPreTrainedModel):
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 WavLM adapters (config.add_adapter=True)"
)... | WavLMForSequenceClassification |
python | numba__numba | numba/tests/test_datamodel.py | {
"start": 450,
"end": 511
} | class ____(test_factory()):
fe_type = types.int16
| TestInt16 |
python | doocs__leetcode | solution/1500-1599/1508.Range Sum of Sorted Subarray Sums/Solution.py | {
"start": 0,
"end": 341
} | class ____:
def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:
arr = []
for i in range(n):
s = 0
for j in range(i, n):
s += nums[j]
arr.append(s)
arr.sort()
mod = 10**9 + 7
return sum(arr[left - 1... | Solution |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 12741,
"end": 12822
} | class ____(Super):
def __init__(self, a, b):
super().__init__(a, b)
| Sub |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 15822,
"end": 16399
} | class ____(BaseExtensionApp):
description = "Lock labextension(s) by name"
aliases = lock_aliases
level = Unicode("sys_prefix", help="Level at which to lock: sys_prefix, user, system").tag(
config=True
)
def run_task(self):
app_options = AppOptions(
app_dir=self.app_dir... | LockLabExtensionsApp |
python | celery__celery | t/unit/tasks/test_trace.py | {
"start": 1705,
"end": 19969
} | class ____(TraceCase):
def test_trace_successful(self):
retval, info = self.trace(self.add, (2, 2), {})
assert info is None
assert retval == 4
def test_trace_before_start(self):
@self.app.task(shared=False, before_start=Mock())
def add_with_before_start(x, y):
... | test_trace |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 542048,
"end": 542507
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CreateRepository"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "repository")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mu... | CreateRepositoryPayload |
python | run-llama__llama_index | llama-index-core/llama_index/core/storage/kvstore/types.py | {
"start": 2193,
"end": 2686
} | class ____(BaseKVStore):
"""Base in-memory key-value store."""
@abstractmethod
def persist(
self, persist_path: str, fs: Optional[fsspec.AbstractFileSystem] = None
) -> None:
pass
@classmethod
@abstractmethod
def from_persist_path(cls, persist_path: str) -> "BaseInMemoryKVS... | BaseInMemoryKVStore |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/errors.py | {
"start": 10639,
"end": 11237
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneError,)
name = "NoModeProvidedError"
pipeline_name = graphene.NonNull(graphene.String)
def __init__(self, pipeline_name, mode_list):
super().__init__()
mode_list = check.list_param(mode_list, "mode_list", of... | GrapheneNoModeProvidedError |
python | tensorflow__tensorflow | tensorflow/python/ops/init_ops.py | {
"start": 56939,
"end": 58634
} | class ____(Initializer):
"""Initializer that generates the identity matrix.
Only use for 2D matrices.
Args:
gain: Multiplicative factor to apply to the identity matrix.
dtype: Default data type, used if no `dtype` argument is provided when
calling the initializer. Only floating point types are sup... | Identity |
python | great-expectations__great_expectations | tests/datasource/fluent/test_config_str.py | {
"start": 595,
"end": 6545
} | class ____(FluentBaseModel):
normal_field: str
secret_field: SecretStr
config_field: ConfigStr
config_field_w_default: ConfigStr = r"hey-${MY_SECRET}" # type: ignore[assignment] # FIXME CoP
@pytest.fixture
def env_config_provider() -> _ConfigurationProvider:
config_provider = _ConfigurationProvid... | MyClass |
python | coleifer__peewee | tests/libs/mock.py | {
"start": 51663,
"end": 59275
} | class ____(object):
"""
Patch a dictionary, or dictionary like object, and restore the dictionary
to its original state after the test.
`in_dict` can be a dictionary or a mapping like container. If it is a
mapping then it must at least support getting, setting and deleting items
plus iterating ... | _patch_dict |
python | pytorch__pytorch | torch/distributed/_tools/sac_estimator.py | {
"start": 5879,
"end": 6594
} | class ____:
"""
Stores metadata for Greedy-order SAC.
Attributes:
recomputed_ops (set[int]): Set of operator indices to be recomputed.
stored_ops (set[int]): Set of operator indices to be stored.
inplace_op_groups (dict[int, set[int]]): Dictionary of inplace operator groups from gro... | SACGreedyOrderMeta |
python | celery__celery | t/integration/tasks.py | {
"start": 12241,
"end": 13623
} | class ____(BaseModel):
result: int
@shared_task(pydantic=True)
def add_pydantic(data: AddParameterModel) -> AddResultModel:
"""Add two numbers, but with parameters and results using Pydantic model serialization."""
value = data.x + data.y
return AddResultModel(result=value)
@shared_task(pydantic=Tru... | AddResultModel |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 4795,
"end": 4881
} | class ____:
def func(self, user_input: Dict[str, int]) -> None:
pass
| ParentT1 |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/grid_helper_curvelinear.py | {
"start": 3402,
"end": 4975
} | class ____(_FixedAxisArtistHelperBase):
"""
Helper class for a fixed axis.
"""
def __init__(self, grid_helper, side, nth_coord_ticks=None):
"""
nth_coord = along which coordinate value varies.
nth_coord = 0 -> x axis, nth_coord = 1 -> y axis
"""
super().__init... | FixedAxisArtistHelper |
python | mlflow__mlflow | mlflow/genai/agent_server/server.py | {
"start": 2253,
"end": 9605
} | class ____:
"""FastAPI-based server for hosting agents.
Args:
agent_type: An optional parameter to specify the type of agent to serve. If provided,
input/output validation and streaming tracing aggregation will be done automatically.
Currently only "ResponsesAgent" is supported.
... | AgentServer |
python | wandb__wandb | wandb/old/settings.py | {
"start": 240,
"end": 6620
} | class ____:
"""Global W&B settings stored under $WANDB_CONFIG_DIR/settings."""
DEFAULT_SECTION = "default"
_UNSET = object()
def __init__(
self, load_settings: bool = True, root_dir: Optional[str] = None
) -> None:
self._global_settings = Settings._settings()
self._local_s... | Settings |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_pdf.py | {
"start": 16181,
"end": 21733
} | class ____:
"""
PDF stream object.
This has no pdfRepr method. Instead, call begin(), then output the
contents of the stream by calling write(), and finally call end().
"""
__slots__ = ('id', 'len', 'pdfFile', 'file', 'compressobj', 'extra', 'pos')
def __init__(self, id, len, file, extra=N... | Stream |
python | matplotlib__matplotlib | lib/matplotlib/testing/jpl_units/EpochConverter.py | {
"start": 169,
"end": 2944
} | class ____(units.ConversionInterface):
"""
Provides Matplotlib conversion functionality for Monte Epoch and Duration
classes.
"""
jdRef = 1721425.5
@staticmethod
def axisinfo(unit, axis):
# docstring inherited
majloc = date_ticker.AutoDateLocator()
majfmt = date_tic... | EpochConverter |
python | python-pillow__Pillow | Tests/helper.py | {
"start": 10124,
"end": 10406
} | class ____:
def __init__(self, func: Callable[[Any], Any]) -> None:
self.func = func
def __get__(self, instance: Any, cls: type[Any] | None = None) -> Any:
result = instance.__dict__[self.func.__name__] = self.func(instance)
return result
| CachedProperty |
python | networkx__networkx | networkx/algorithms/tests/test_cycles.py | {
"start": 33821,
"end": 34851
} | class ____:
@pytest.mark.parametrize(
("G", "expected"),
(
(nx.chvatal_graph(), 4),
(nx.tutte_graph(), 4),
(nx.petersen_graph(), 5),
(nx.heawood_graph(), 6),
(nx.pappus_graph(), 6),
(nx.random_labeled_tree(10, seed=42), inf),
... | TestGirth |
python | getsentry__sentry | src/sentry/auth/providers/saml2/auth0/apps.py | {
"start": 36,
"end": 267
} | class ____(AppConfig):
name = "sentry.auth.providers.saml2.auth0"
def ready(self) -> None:
from sentry.auth import register
from .provider import Auth0SAML2Provider
register(Auth0SAML2Provider)
| Config |
python | kamyu104__LeetCode-Solutions | Python/html-entity-parser.py | {
"start": 3255,
"end": 4063
} | class ____(object):
def entityParser(self, text):
"""
:type text: str
:rtype: str
"""
patterns = [""", "'", "&", ">", "<", "⁄"]
chars = ["\"", "'", "&", ">", "<", "/"]
result = []
i, j = 0, 0
while i != len(text):
... | Solution2 |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_modelresource/test_m2m.py | {
"start": 196,
"end": 5052
} | class ____(TestCase):
def setUp(self):
self.resource = BookResource()
self.book = Book.objects.create(name="Some book")
self.dataset = tablib.Dataset(headers=["id", "name", "author_email", "price"])
row = [self.book.pk, "Some book", "test@example.com", "10.25"]
self.dataset.a... | ForeignKeyM2MTest |
python | html5lib__html5lib-python | html5lib/tests/test_serializer.py | {
"start": 580,
"end": 8357
} | class ____(TreeWalker):
def __iter__(self):
for token in self.tree:
type = token[0]
if type == "StartTag":
if len(token) == 4:
namespace, name, attrib = token[1:4]
else:
namespace = default_namespace
... | JsonWalker |
python | pytorch__pytorch | torch/_dynamo/output_graph.py | {
"start": 7342,
"end": 7954
} | class ____:
"""Stores why a given output graph was compiled; i.e. what caused the graph break."""
reason: str
user_stack: list[traceback.FrameSummary]
# Indicates if this was a graph break reason due to graph break.
graph_break: bool = True
def __post_init__(self) -> None:
if self.gra... | GraphCompileReason |
python | scikit-learn__scikit-learn | sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py | {
"start": 16559,
"end": 23217
} | class ____(BaseDistancesReductionDispatcher):
"""Compute the argkmin of row vectors of X on the ones of Y with labels.
For each row vector of X, computes the indices of k first the rows
vectors of Y with the smallest distances. Computes weighted mode of labels.
ArgKminClassMode is typically used to pe... | ArgKminClassMode |
python | kubernetes-client__python | kubernetes/client/models/discovery_v1_endpoint_port.py | {
"start": 383,
"end": 8898
} | 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... | DiscoveryV1EndpointPort |
python | python__mypy | mypy/build.py | {
"start": 12452,
"end": 19280
} | class ____(TypedDict):
path: str
mtime: int
# Priorities used for imports. (Here, top-level includes inside a class.)
# These are used to determine a more predictable order in which the
# nodes in an import cycle are processed.
PRI_HIGH: Final = 5 # top-level "from X import blah"
PRI_MED: Final = 10 # top-... | FgDepMeta |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-llama-guard-moderator/llama_index/packs/llama_guard_moderator/base.py | {
"start": 3442,
"end": 6445
} | class ____(BaseLlamaPack):
def __init__(
self,
custom_taxonomy: str = DEFAULT_TAXONOMY,
) -> None:
"""Init params."""
try:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
except ImportError:
raise ImportError(
... | LlamaGuardModeratorPack |
python | pytorch__pytorch | torch/utils/data/datapipes/dataframe/dataframes.py | {
"start": 940,
"end": 1667
} | class ____(DFIterDataPipe):
def __init__(self, source_datapipe, output_var) -> None:
self.source_datapipe = source_datapipe
self.output_var = output_var
def __iter__(self):
for item in self.source_datapipe:
yield self.output_var.apply_ops(item)
# TODO(VitalyFedyunin): Ext... | DataFrameTracedOps |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_einsum.py | {
"start": 728,
"end": 46617
} | class ____(TestCase):
def test_einsum_errors(self):
for do_opt in [True, False]:
# Need enough arguments
assert_raises(
(TypeError, IndexError, ValueError), np.einsum, optimize=do_opt
)
assert_raises((IndexError, ValueError), np.einsum, "", opt... | TestEinsum |
python | pytorch__pytorch | torch/_vendor/packaging/version.py | {
"start": 4491,
"end": 16236
} | class ____(_BaseVersion):
"""This class abstracts handling of a project's versions.
A :class:`Version` instance is comparison aware and can be compared and
sorted using the standard Python interfaces.
>>> v1 = Version("1.0a5")
>>> v2 = Version("1.0")
>>> v1
<Version('1.0a5')>
>>> v2
... | Version |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_embed_image05.py | {
"start": 315,
"end": 930
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("embed_image05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Wo... | TestCompareXLSXFiles |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 167434,
"end": 168473
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
created_time: Optional[int] = Field(
None,
description=(
"The time at which this job was created in epoch milliseconds (milliseconds"
... | Job |
python | pypa__warehouse | tests/unit/organizations/test_tasks.py | {
"start": 3496,
"end": 5375
} | class ____:
def test_delete_declined_organization_applications(self, db_request):
# Create an organization_application that's ready for cleanup
organization_application = OrganizationApplicationFactory.create()
organization_application.is_active = False
organization_application.statu... | TestDeleteOrganizationApplications |
python | getsentry__sentry | tests/sentry/deletions/tasks/test_scheduled.py | {
"start": 8333,
"end": 9300
} | class ____(RegionalRunScheduleDeletionTest):
@property
def ScheduledDeletion(self) -> type[BaseScheduledDeletion]:
return ScheduledDeletion
def run_scheduled_deletions(self) -> None:
return run_scheduled_deletions_control()
def reattempt_deletions(self) -> None:
return reattemp... | RunControlScheduledDeletionTest |
python | run-llama__llama_index | llama-index-integrations/postprocessor/llama-index-postprocessor-bedrock-rerank/tests/test_postprocessor_bedrock_rerank.py | {
"start": 263,
"end": 3084
} | class ____(TestCase):
def test_class(self):
names_of_base_classes = [b.__name__ for b in BedrockRerank.__mro__]
self.assertIn(BaseNodePostprocessor.__name__, names_of_base_classes)
def test_bedrock_rerank(self):
exp_rerank_response = {
"results": [
{
... | TestBedrockRerank |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 5795,
"end": 7852
} | class ____(DagsterError):
"""Indicates that you have attempted to construct a config with an invalid value.
Acceptable values for config types are any of:
1. A Python primitive type that resolves to a Dagster config type
(:py:class:`~python:int`, :py:class:`~python:float`, :py:class:`~pytho... | DagsterInvalidConfigDefinitionError |
python | sqlalchemy__sqlalchemy | examples/inheritance/joined.py | {
"start": 957,
"end": 1399
} | class ____(Base):
__tablename__ = "person"
id: Mapped[intpk]
company_id: Mapped[int] = mapped_column(ForeignKey("company.id"))
name: Mapped[str50]
type: Mapped[str50]
company: Mapped[Company] = relationship(back_populates="employees")
__mapper_args__ = {
"polymorphic_identity": "pe... | Person |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py | {
"start": 16771,
"end": 18349
} | class ____:
"""Test _recursive_flatten_dict function."""
def test_flat_dict(self):
"""Test flattening a flat dictionary."""
input_dict = {"a": "value1", "b": "value2"}
expected = {"a": "value1", "b": "value2"}
assert _recursive_flatten_dict(input_dict) == expected
def test_... | TestRecursiveFlattenDict |
python | huggingface__transformers | src/transformers/models/informer/modeling_informer.py | {
"start": 10382,
"end": 10684
} | class ____(nn.Module):
def __init__(self, feature_size, d_model):
super().__init__()
self.value_projection = nn.Linear(in_features=feature_size, out_features=d_model, bias=False)
def forward(self, x):
return self.value_projection(x)
@auto_docstring
| InformerValueEmbedding |
python | scrapy__scrapy | tests/mockserver/http_resources.py | {
"start": 5344,
"end": 5669
} | class ____(LeafResource):
def render_GET(self, request):
request.setHeader(b"Content-Length", b"1024")
self.deferRequest(request, 0, self._delayedRender, request)
return NOT_DONE_YET
def _delayedRender(self, request):
request.write(b"partial content\n")
request.finish()
... | Partial |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/special_math_test.py | {
"start": 13374,
"end": 17571
} | class ____(test.TestCase):
# Note that scipy.stats.laplace does not have a stable Log CDF, so we cannot
# rely on scipy to cross check the extreme values.
# Test will be done differently over different ranges. These are the values
# such that when exceeded by x, produce output that causes the naive (scipy)
... | LogCDFLaplaceTest |
python | pytorch__pytorch | torch/_inductor/autoheuristic/autoheuristic_utils.py | {
"start": 2899,
"end": 11308
} | class ____:
def __init__(
self,
shared_memory: Any,
device_capa: tuple[int, int],
choices: list[Choice],
name: str,
) -> None:
# use amount of shared_memory and device_capability to identify GPU
# TODO(AlnisM): there might be a better way to do this
... | AHMetadata |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 10982,
"end": 13444
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column("id", Integer, primary_key=True),
Column("bid", ForeignKey("b.id")),
)
Table("b", metadata, Column("id", Integer, primary_key=True)... | M2ODontOverwriteFKTest |
python | tensorflow__tensorflow | third_party/xla/xla/codegen/testlib/kernel_runner_test.py | {
"start": 1728,
"end": 1955
} | class ____(absltest.TestCase):
def test_output_same_as_input(self):
array = np.array([1, 2, 3, 4], dtype=np.int32)
got = create_literal(array)
np.testing.assert_array_equal(np.asarray(got), array)
| LiteralFromNpTest |
python | mlflow__mlflow | mlflow/models/evaluation/artifacts.py | {
"start": 3568,
"end": 6763
} | class ____(NamedTuple):
from_path: bool
type: type[EvaluationArtifact]
ext: str
def _infer_artifact_type_and_ext(artifact_name, raw_artifact, custom_metric_tuple):
"""
This function performs type and file extension inference on the provided artifact
Args:
artifact_name: The name of th... | _InferredArtifactProperties |
python | google__pytype | pytype/tools/environment_test.py | {
"start": 200,
"end": 2092
} | class ____(unittest.TestCase):
"""Tests for environment.compute_pythonpath."""
def test_script_path(self):
with test_utils.Tempdir() as d:
f = d.create_file('foo.py')
self.assertSequenceEqual(environment.compute_pythonpath([f]), [d.path])
def test_module_path(self):
with test_utils.Tempdir()... | TestComputePythonPath |
python | langchain-ai__langchain | libs/core/langchain_core/messages/content.py | {
"start": 9712,
"end": 11061
} | class ____(TypedDict):
"""A chunk of a tool call (yielded when streaming).
When merging `ToolCallChunks` (e.g., via `AIMessageChunk.__add__`),
all string attributes are concatenated. Chunks are only merged if their
values of `index` are equal and not `None`.
Example:
```python
left_chunks ... | ToolCallChunk |
python | kevin1024__vcrpy | vcr/stubs/boto3_stubs.py | {
"start": 230,
"end": 332
} | class ____(VCRHTTPConnection, HTTPConnection):
_baseclass = HTTPConnection
| VCRRequestsHTTPConnection |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_tool_reference_block_param.py | {
"start": 335,
"end": 598
} | class ____(TypedDict, total=False):
tool_name: Required[str]
type: Required[Literal["tool_reference"]]
cache_control: Optional[BetaCacheControlEphemeralParam]
"""Create a cache control breakpoint at this content block."""
| BetaToolReferenceBlockParam |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance21.py | {
"start": 871,
"end": 1337
} | class ____:
pass
def guard3(t: type[Any]) -> TypeIs[type[A]]:
return True
def func3(t: type[B]):
if guard3(t):
reveal_type(t, expected_text="type[<subclass of B and A>]")
else:
reveal_type(t, expected_text="type[B]")
def guard4(t: Any) -> TypeIs[type[A]]:
return True
def func... | B |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modeling_glm4v_moe.py | {
"start": 40459,
"end": 41509
} | class ____(GradientCheckpointingLayer):
def __init__(self, config) -> None:
super().__init__()
self.norm1 = Glm4vMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.norm2 = Glm4vMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.attn = Glm4vMoeVisionAttention(confi... | Glm4vMoeVisionBlock |
python | django__django | tests/aggregation_regress/models.py | {
"start": 2602,
"end": 2796
} | class ____(models.Model):
name = models.CharField(max_length=50)
parent = models.ForeignKey(
"self", models.SET_NULL, null=True, blank=True, related_name="children"
)
| SelfRefFK |
python | pytest-dev__pytest | testing/test_collection.py | {
"start": 10902,
"end": 13197
} | class ____:
def test_custom_repr_failure(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import not_exists
"""
)
pytester.makeconftest(
"""
import pytest
def pytest_collect_file(file_path, parent):
... | TestPrunetraceback |
python | django__django | django/contrib/postgres/fields/ranges.py | {
"start": 10291,
"end": 10507
} | class ____(models.Transform):
lookup_name = "startswith"
function = "lower"
@property
def output_field(self):
return self.lhs.output_field.base_field
@RangeField.register_lookup
| RangeStartsWith |
python | streamlit__streamlit | e2e_playwright/conftest.py | {
"start": 21387,
"end": 41123
} | class ____(Protocol):
def __call__(
self,
element: ElementHandle | Locator | Page,
*,
image_threshold: float = 0.002,
pixel_threshold: float = 0.05,
name: str | None = None,
fail_fast: bool = False,
style: str | None = None,
) -> None:
"""C... | ImageCompareFunction |
python | ray-project__ray | python/ray/experimental/channel/shared_memory_channel.py | {
"start": 5180,
"end": 20624
} | class ____(ChannelInterface):
"""
A wrapper type for ray.ObjectRef. Currently supports ray.get but not
ray.wait.
"""
def __init__(
self,
writer: Optional[ray.actor.ActorHandle],
reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]],
typ: Optional[Union[int,... | Channel |
python | redis__redis-py | tests/test_scenario/maint_notifications_helpers.py | {
"start": 279,
"end": 2004
} | class ____:
@staticmethod
def wait_push_notification(
redis_client: Redis,
timeout: int = 120,
fail_on_timeout: bool = True,
connection: Optional[Connection] = None,
):
"""Wait for a push notification to be received."""
start_time = time.time()
check_i... | ClientValidations |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 315915,
"end": 318642
} | class ____(Response):
"""
Response of tasks.get_hyper_params endpoint.
:param params: Hyper parameters (keyed by task ID)
:type params: Sequence[dict]
"""
_service = "tasks"
_action = "get_hyper_params"
_version = "2.13"
_schema = {
"definitions": {
"params_item... | GetHyperParamsResponse |
python | huggingface__transformers | tests/models/instructblipvideo/test_modeling_instructblipvideo.py | {
"start": 18253,
"end": 25930
} | class ____(
ModelTesterMixin, GenerationTesterMixin, unittest.TestCase
):
all_model_classes = (
(InstructBlipVideoForConditionalGeneration, InstructBlipVideoModel) if is_torch_available() else ()
)
additional_model_inputs = ["qformer_input_ids", "input_ids"]
test_resize_embeddings = True
... | InstructBlipVideoForConditionalGenerationDecoderOnlyTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec32.py | {
"start": 391,
"end": 894
} | class ____(Generic[P, T2]):
def __init__(self, fn: Callable[P, T2], *args: P.args, **kwargs: P.kwargs) -> None:
self.fn = fn
self.args = args
self.kwargs = kwargs
def __call__(self) -> T2:
return self.fn(*self.args, **self.kwargs)
# This should generate an error because argume... | Class1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.