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 | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 30629,
"end": 36421
} | class ____:
"""
Represents the information needed to make a query to Snuba.
`start` and `end`: The beginning and end of the query time window (required)
`groupby`: A list of column names to group by.
`conditions`: A list of (column, operator, literal) conditions to be passed
to the query. Con... | SnubaQueryParams |
python | great-expectations__great_expectations | great_expectations/core/freshness_diagnostics.py | {
"start": 1767,
"end": 1854
} | class ____(FreshnessDiagnostics):
pass
@dataclass
| BatchDefinitionFreshnessDiagnostics |
python | getsentry__sentry | tests/sentry/issues/test_ingest.py | {
"start": 40512,
"end": 42268
} | class ____(OccurrenceTestMixin, TestCase):
def test(self) -> None:
create_default_projects()
event_data = load_data("generic-event-profiling")
project_id = event_data["event"].pop("project_id")
event_data["event"]["timestamp"] = timezone.now().isoformat()
event = self.store_e... | SaveIssueOccurrenceToEventstreamTest |
python | sympy__sympy | sympy/assumptions/handlers/common.py | {
"start": 560,
"end": 1063
} | class ____:
"""Base class that all Ask Handlers must inherit."""
def __new__(cls, *args, **kwargs):
sympy_deprecation_warning(
"""
The AskHandler system is deprecated. The AskHandler class should
be replaced with the multipledispatch handler of Predicate
"... | AskHandler |
python | Pylons__pyramid | src/pyramid/testing.py | {
"start": 4640,
"end": 7938
} | class ____:
"""A dummy :app:`Pyramid` :term:`resource` object."""
def __init__(
self, __name__=None, __parent__=None, __provides__=None, **kw
):
"""The resource's ``__name__`` attribute will be set to the
value of the ``__name__`` argument, and the resource's
``__parent__`` ... | DummyResource |
python | kamyu104__LeetCode-Solutions | Python/find-array-given-subset-sums.py | {
"start": 1281,
"end": 2575
} | class ____(object):
def recoverArray(self, n, sums):
"""
:type n: int
:type sums: List[int]
:rtype: List[int]
"""
sums.sort() # Time: O(2^n * log(2^n)) = O(n * 2^n)
shift, l = 0, len(sums)
result = []
for _ in xrange(n): # log(2^n) times, eac... | Solution |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_vf2userfunc.py | {
"start": 2240,
"end": 3850
} | class ____:
def setup_method(self):
self.g1 = nx.Graph()
self.g2 = nx.Graph()
self.build()
def build(self):
self.nm = iso.categorical_node_match("color", "")
self.em = iso.numerical_edge_match("weight", 1)
self.g1.add_node("A", color="red")
self.g2.add_n... | TestNodeMatch_Graph |
python | plotly__plotly.py | tests/test_core/test_graph_objs/test_layout_subplots.py | {
"start": 102,
"end": 9312
} | class ____(TestCase):
def setUp(self):
# Construct initial scatter object
self.layout = go.Layout()
pio.templates.default = None
def tearDown(self):
pio.templates.default = "plotly"
def test_initial_access_subplots(self):
# It should be possible to access base subp... | TestLayoutSubplots |
python | numpy__numpy | benchmarks/benchmarks/bench_manipulate.py | {
"start": 1097,
"end": 1993
} | class ____(Benchmark):
params = [[(16, 32), (32, 64)],
[2, 5],
TYPES1]
param_names = ['shape', 'narrays', 'ndtype']
timeout = 10
def setup(self, shape, narrays, ndtype):
self.xarg = [np.random.ranf(shape[0] * shape[1]).reshape(shape)
for x in ran... | ConcatenateStackArrays |
python | jazzband__django-pipeline | pipeline/compilers/__init__.py | {
"start": 3176,
"end": 6340
} | class ____(CompilerBase):
def execute_command(self, command, cwd=None, stdout_captured=None):
"""Execute a command at cwd, saving its normal output at
stdout_captured. Errors, defined as nonzero return code or a failure
to start execution, will raise a CompilerError exception with a
... | SubProcessCompiler |
python | marshmallow-code__marshmallow | tests/test_deserialization.py | {
"start": 60074,
"end": 60254
} | class ____(Schema):
email = fields.Email()
colors = fields.Str(validate=validate.OneOf(["red", "blue"]))
age = fields.Integer(validate=[validate.Range(1, 99)])
| Validators |
python | django__django | django/contrib/postgres/search.py | {
"start": 12473,
"end": 12541
} | class ____(TrigramBase):
function = "SIMILARITY"
| TrigramSimilarity |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 150283,
"end": 151375
} | class ____(sgqlc.types.Input):
"""Information from a check run analysis to specific lines of code."""
__schema__ = github_schema
__field_names__ = ("path", "location", "annotation_level", "message", "title", "raw_details")
path = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="path")
... | CheckAnnotationData |
python | huggingface__transformers | src/transformers/models/dab_detr/modeling_dab_detr.py | {
"start": 64462,
"end": 66081
} | class ____(nn.Module):
"""This is a 2D attention module, which only returns the attention softmax (no multiplication by value)"""
def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True, std=None):
super().__init__()
self.num_heads = num_heads
self.hidden_dim = hidde... | DabDetrMHAttentionMap |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 194101,
"end": 199391
} | class ____:
"""
Tests kstest and ks_samp 1-samples with K-S various sizes, alternatives, modes.
"""
def _testOne(self, x, alternative, expected_statistic, expected_prob, *,
mode='auto', dtype, xp):
rtol = 5e-14 if dtype == xp.float64 else 1e-5
res = stats.ks_1samp(x, sp... | TestKSOneSample |
python | apache__airflow | airflow-core/src/airflow/models/dagcode.py | {
"start": 1739,
"end": 7174
} | class ____(Base):
"""
A table for DAGs code.
dag_code table contains code of DAG files synchronized by scheduler.
For details on dag serialization see SerializedDagModel
"""
__tablename__ = "dag_code"
id: Mapped[str] = mapped_column(UUIDType(binary=False), primary_key=True, default=uuid6.... | DagCode |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/spark/spark_generic.py | {
"start": 310,
"end": 1669
} | class ____(PathDataAsset):
# vvv Docs <> Source Code mismatch
# ignoreCorruptFiles and ignoreMissingFiles appear in the docs https://spark.apache.org/docs/latest/sql-data-sources-generic-options.html
# but not in any reader method signatures (e.g. https://github.com/apache/spark/blob/v3.4.0/python/pyspark/s... | _SparkGenericFilePathAssetMixin |
python | lxml__lxml | src/lxml/tests/test_incremental_xmlfile.py | {
"start": 13770,
"end": 14087
} | class ____(_XmlFileTestCaseBase):
def setUp(self):
self._file = BytesIO()
def test_filelike_close(self):
with etree.xmlfile(self._file, close=True) as xf:
with xf.element('test'):
pass
self.assertRaises(ValueError, self._file.getvalue)
| BytesIOXmlFileTestCase |
python | django__django | django/core/cache/backends/memcached.py | {
"start": 236,
"end": 5311
} | class ____(BaseCache):
def __init__(self, server, params, library, value_not_found_exception):
super().__init__(params)
if isinstance(server, str):
self._servers = re.split("[;,]", server)
else:
self._servers = server
# Exception type raised by the underlying... | BaseMemcachedCache |
python | pytorch__pytorch | test/functorch/test_control_flow.py | {
"start": 208803,
"end": 223167
} | class ____(torch.nn.Module):
def forward(self, L_ctx_saved_tensors_0_: "f32[4]", L_ctx_pred: "b8[]", L_args_1_: "f32[4]"):
l_ctx_saved_tensors_0_ = L_ctx_saved_tensors_0_
l_ctx_pred = L_ctx_pred
l_args_1_ = L_args_1_
cond_true_0 = self.cond_true_0
cond_false_0 = self.cond_fa... | GraphModule |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 46584,
"end": 47572
} | class ____(PipesBlobStoreMessageWriter):
"""Message writer that writes messages by periodically writing message chunks to an
AzureBlobStorage container.
Args:
client (Any): An azure.storage.blob.BlobServiceClient object.
interval (float): interval in seconds between upload chunk uploads... | PipesAzureBlobStorageMessageWriter |
python | sqlalchemy__sqlalchemy | test/dialect/mssql/test_query.py | {
"start": 14395,
"end": 20867
} | class ____(AssertsCompiledSQL, fixtures.TablesTest):
__only_on__ = "mssql"
__skip_if__ = (full_text_search_missing,)
__backend__ = True
run_setup_tables = "once"
run_inserts = run_deletes = "once"
@classmethod
def define_tables(cls, metadata):
Table(
"cattable",
... | MatchTest |
python | ray-project__ray | release/train_tests/benchmark/s3_parquet_reader.py | {
"start": 1707,
"end": 5401
} | class ____(S3Reader):
"""Extended S3Reader class for Parquet-specific functionality.
Provides specialized methods for:
1. Collecting Parquet file metadata (row counts) from S3
2. Distributing files among workers based on row counts
3. Managing parallel S3 operations with Ray tasks
"""
def ... | S3ParquetReader |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 37489,
"end": 38385
} | class ____(BaseModel):
type: Literal["WaitTimeFromHeader"]
header: str = Field(
...,
description="The name of the response header defining how long to wait before retrying.",
examples=["Retry-After"],
title="Response Header Name",
)
regex: Optional[str] = Field(
N... | WaitTimeFromHeader |
python | ionelmc__pytest-benchmark | src/pytest_benchmark/logger.py | {
"start": 150,
"end": 206
} | class ____(PytestWarning):
pass
| PytestBenchmarkWarning |
python | python-openxml__python-docx | tests/image/test_jpeg.py | {
"start": 8550,
"end": 10014
} | class ____:
def it_can_construct_from_a_stream_and_offset(self, _App0Marker__init_):
bytes_ = b"\x00\x10JFIF\x00\x01\x01\x01\x00\x2a\x00\x18"
marker_code, offset, length = JPEG_MARKER_CODE.APP0, 0, 16
density_units, x_density, y_density = 1, 42, 24
stream = StreamReader(io.BytesIO(by... | Describe_App0Marker |
python | pytorch__pytorch | torch/_inductor/virtualized.py | {
"start": 4592,
"end": 6350
} | class ____(Generic[T]):
"""
Implements a global variable that redirects via thread local variable
(NB: construct this class to create the global variable; this is not
a singleton class!)
This allows us to swap in different op implementations in codegen.
NB: Despite the fact that we typically c... | Virtualized |
python | huggingface__transformers | src/transformers/cache_utils.py | {
"start": 60978,
"end": 61270
} | class ____(DynamicCache):
def __init__(self) -> None:
logger.warning_once(
"`OffloadedCache` is deprecated and will be removed in version v4.59 "
"Use `DynamicCache(offloading=True)` instead"
)
super().__init__(offloading=True)
| OffloadedCache |
python | pytest-dev__pytest | doc/en/example/fixtures/test_fixtures_order_autouse_multiple_scopes.py | {
"start": 453,
"end": 560
} | class ____:
def test_order(self, order, c2):
assert order == ["c1", "c2"]
| TestClassWithoutC1Request |
python | getsentry__sentry | tests/sentry/issues/test_issue_search.py | {
"start": 6637,
"end": 8830
} | class ____(TestCase):
def test_valid_assign_me_converter(self) -> None:
raw_value = "me"
filters = [SearchFilter(SearchKey("assigned_to"), "=", SearchValue(raw_value))]
expected = value_converters["assigned_to"]([raw_value], [self.project], self.user, None)
filters = convert_query_va... | ConvertQueryValuesTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 946938,
"end": 947358
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("RepositoryVulnerabilityAl... | RepositoryVulnerabilityAlertEdge |
python | Lightning-AI__lightning | src/lightning/fabric/utilities/distributed.py | {
"start": 12284,
"end": 14273
} | class ____(Dataset):
"""Dataset to create indexes from `Sampler` or `Iterable`"""
def __init__(self, sampler: Union[Sampler, Iterable]) -> None:
if not isinstance(sampler, Sized):
raise TypeError(
"You seem to have configured a sampler in your DataLoader which"
... | _DatasetSamplerWrapper |
python | huggingface__transformers | src/transformers/models/siglip2/modeling_siglip2.py | {
"start": 18315,
"end": 19307
} | class ____(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`Siglip2EncoderLayer`].
Args:
config: Siglip2Config
"""
def __init__(self, config: Siglip2Config):
super().__init__()
self.config = config
... | Siglip2Encoder |
python | django__django | django/db/migrations/serializer.py | {
"start": 10378,
"end": 10475
} | class ____(BaseSequenceSerializer):
def _format(self):
return "[%s]"
| SequenceSerializer |
python | getsentry__sentry | tests/sentry/web/frontend/test_setup_wizard.py | {
"start": 378,
"end": 12834
} | class ____(PermissionTestCase):
def test_redirect(self) -> None:
user = self.create_user("foo@example.com", is_active=False)
url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"})
resp = self.client.get(url)
self.login_as(user)
assert resp.status_code ... | SetupWizard |
python | walkccc__LeetCode | solutions/1980. Find Unique Binary String/1980.py | {
"start": 0,
"end": 273
} | class ____:
def findDifferentBinaryString(self, nums: list[str]) -> str:
bitSize = len(nums[0])
maxNum = 1 << bitSize
numsSet = {int(num, 2) for num in nums}
for num in range(maxNum):
if num not in numsSet:
return f'{num:0>{bitSize}b}'
| Solution |
python | ipython__ipython | IPython/core/guarded_eval.py | {
"start": 47131,
"end": 57474
} | class ____(dict):
"""A dict subclass that always returns the factory instance and claims to have any item."""
def __init__(self, factory, *args, **kwargs):
super().__init__(*args, **kwargs)
self._factory = factory
def __getitem__(self, key):
return self._factory()
def __contai... | _GetItemDuck |
python | pytorch__pytorch | torch/testing/_internal/common_modules.py | {
"start": 6713,
"end": 6936
} | class ____:
""" Contains args and kwargs to pass as input to a function. """
__slots__ = ['args', 'kwargs']
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
| FunctionInput |
python | modin-project__modin | modin/core/execution/dispatching/factories/dispatcher.py | {
"start": 2855,
"end": 14312
} | class ____(object):
"""
Class that routes IO-work to the factories.
This class is responsible for keeping selected factory up-to-date and dispatching
calls of IO-functions to its actual execution-specific implementations.
"""
__factory: factories.BaseFactory = None
@classmethod
def ge... | FactoryDispatcher |
python | pandas-dev__pandas | asv_bench/benchmarks/hash_functions.py | {
"start": 930,
"end": 1359
} | class ____:
params = ["Int64", "Float64"]
param_names = ["dtype"]
def setup(self, dtype):
self.ser = pd.Series(([1, pd.NA, 2] + list(range(100_000))) * 3, dtype=dtype)
self.ser_unique = pd.Series(list(range(300_000)) + [pd.NA], dtype=dtype)
def time_unique_with_duplicates(self, exponen... | Unique |
python | getsentry__sentry | src/sentry/auth/providers/saml2/activedirectory/apps.py | {
"start": 89,
"end": 350
} | class ____(AppConfig):
name = "sentry.auth.providers.saml2.activedirectory"
def ready(self) -> None:
from sentry.auth import register
from .provider import ActiveDirectorySAML2Provider
register(ActiveDirectorySAML2Provider)
| Config |
python | huggingface__transformers | tests/models/edgetam/test_modeling_edgetam.py | {
"start": 17710,
"end": 29162
} | class ____(unittest.TestCase):
def setUp(self):
super().setUp()
self.model = EdgeTamModel.from_pretrained("yonigozlan/EdgeTAM-hf").to(torch.float32)
self.processor = Sam2Processor.from_pretrained("yonigozlan/EdgeTAM-hf")
self.model.to(torch_device)
self.model.eval()
def ... | EdgeTamModelIntegrationTest |
python | getsentry__sentry | src/sentry/api/endpoints/organization_traces.py | {
"start": 36537,
"end": 40751
} | class ____:
project: int | None = None
name: str | None = None
duration: float | None = None
def format_trace_result(
trace: GetTracesResponse.Trace,
projects_map: dict[int, str],
) -> TraceResult:
result: TraceResult = {
"trace": "",
"numErrors": 0,
"numOccurrences": 0... | TraceInfo |
python | walkccc__LeetCode | solutions/555. Split Concatenated Strings/555.py | {
"start": 0,
"end": 380
} | class ____:
def splitLoopedString(self, strs: list[str]) -> str:
ans = ''
sortedStrs = [max(s, s[::-1]) for s in strs]
for i, sortedStr in enumerate(sortedStrs):
for s in (sortedStr, sortedStr[::-1]):
for j in range(len(s) + 1):
ans = max(
ans, s[j:] + ''.join(sorted... | Solution |
python | miyuchina__mistletoe | mistletoe/span_token.py | {
"start": 7079,
"end": 7527
} | class ____(SpanToken):
"""
Line break token: hard or soft.
This is an inline token without children.
Attributes:
soft (bool): true if this is a soft line break.
"""
repr_attributes = ("soft",)
pattern = re.compile(r'( *|\\)\n')
parse_inner = False
parse_group = 0
def __... | LineBreak |
python | great-expectations__great_expectations | great_expectations/render/renderer/site_builder.py | {
"start": 1304,
"end": 13703
} | class ____:
"""SiteBuilder builds data documentation for the project defined by a
DataContext.
A data documentation site consists of HTML pages for expectation suites,
profiling and validation results, and
an index.html page that links to all the pages.
The exact behavior of SiteBuilder is con... | SiteBuilder |
python | readthedocs__readthedocs.org | readthedocs/projects/views/mixins.py | {
"start": 406,
"end": 1648
} | class ____:
"""
Mixin class for constructing model views for project dashboard.
This mixin class is used for model views on models that have a relation
to the :py:class:`Project` model.
:cvar project_lookup_url_kwarg: URL kwarg to use in project lookup
:cvar project_lookup_field: Query field f... | ProjectRelationMixin |
python | FactoryBoy__factory_boy | factory/base.py | {
"start": 23298,
"end": 23936
} | class ____(Factory):
"""Factory for list-like classes."""
class Meta:
abstract = True
@classmethod
def _build(cls, model_class, *args, **kwargs):
if args:
raise ValueError(
"ListFactory %r does not support Meta.inline_args." % cls)
# kwargs are const... | BaseListFactory |
python | python__mypy | mypy/visitor.py | {
"start": 8009,
"end": 8972
} | class ____(Generic[T]):
@abstractmethod
def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T:
pass
@abstractmethod
def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T:
pass
@abstractmethod
def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T... | PatternVisitor |
python | realpython__materials | python-protocol/adder_v1.py | {
"start": 148,
"end": 366
} | class ____:
def add(self, x, y):
return x + y
def add(adder: Adder) -> None:
print(adder.add(2, 3))
add(IntAdder())
add(FloatAdder())
for adder in [IntAdder(), FloatAdder()]:
add(adder)
| FloatAdder |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 17960,
"end": 18038
} | class ____(RootModel[int]):
root: Annotated[int, Field(ge=0, title="Id")]
| Id |
python | lxml__lxml | doc/s5/ep2008/atom.py | {
"start": 13211,
"end": 13435
} | class ____(_EntryElement):
"""
Represents authors and contributors
"""
email = _text_element_property('email')
uri = _text_element_property('uri')
name = _text_element_property('name')
| PersonElement |
python | viewflow__viewflow | viewflow/forms/renderers.py | {
"start": 24594,
"end": 25283
} | class ____(Column):
def __init__(self, title, *elements, **kwargs):
self.title = title
super().__init__(*elements, **kwargs)
def append(self, layout: FormLayout, form: forms.Form, root: ElementTree.Element):
wrapper = ElementTree.SubElement(
root,
"div",
... | FieldSet |
python | google__jax | jax/_src/state/types.py | {
"start": 8746,
"end": 12014
} | class ____:
ref: Any
transforms: tuple[Transform, ...]
@property
def is_dynamic_size(self):
return any(not isinstance(i, int) for i in self.shape)
@property
def shape(self) -> tuple[int | Array, ...]:
unprocessed, shape = 0, None
# We first go backwards to find the first transform that knows i... | TransformedRef |
python | zarr-developers__zarr-python | src/zarr/core/metadata/v3.py | {
"start": 6717,
"end": 17249
} | class ____(Metadata):
shape: tuple[int, ...]
data_type: ZDType[TBaseDType, TBaseScalar]
chunk_grid: ChunkGrid
chunk_key_encoding: ChunkKeyEncoding
fill_value: Any
codecs: tuple[Codec, ...]
attributes: dict[str, Any] = field(default_factory=dict)
dimension_names: tuple[str | None, ...] | ... | ArrayV3Metadata |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/from_tensors_test.py | {
"start": 16549,
"end": 17564
} | class ____(
test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
repetitions=[1, 3],
seed=[None, 19],
reshuffle_each_iteration=[True, False])... | FromTensorsGlobalShuffleTest |
python | allegroai__clearml | clearml/backend_interface/task/repo/detectors.py | {
"start": 8249,
"end": 12036
} | class ____(Detector):
def __init__(self) -> None:
super(GitDetector, self).__init__("git")
def _get_commands(self) -> "GitDetector.Commands":
return self.Commands(
url=["git", "ls-remote", "--get-url"],
branch=["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", ... | GitDetector |
python | PyCQA__pylint | tests/functional/p/protected_access.py | {
"start": 1042,
"end": 1076
} | class ____:
_sauce = 42
| BaseTomato |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/discord/tests.py | {
"start": 452,
"end": 2015
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = DiscordProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""{
"id": "80351110224678912",
"username": "nelly",
"discriminator": "0",
"global_name":... | DiscordTests |
python | xlwings__xlwings | xlwings/pro/_xlremote.py | {
"start": 8996,
"end": 11022
} | class ____(base_classes.Sheets):
def __init__(self, api, book):
self._api = api
self.book = book
@property
def active(self):
ix = self.book.api["book"]["active_sheet_index"]
return Sheet(api=self.api[ix], sheets=self, index=ix + 1)
@property
def api(self):
r... | Sheets |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/retrieval_qa/base.py | {
"start": 7145,
"end": 9858
} | class ____(BaseRetrievalQA):
"""Chain for question-answering against an index.
This class is deprecated. See below for an example implementation using
`create_retrieval_chain`:
```python
from langchain_classic.chains import create_retrieval_chain
from langchain_classic.chains.combi... | RetrievalQA |
python | ApeWorX__ape | src/ape_test/config.py | {
"start": 4462,
"end": 6552
} | class ____(PluginConfig):
balance: int = DEFAULT_TEST_ACCOUNT_BALANCE
"""
The starting-balance of every test account in Wei (NOT Ether).
"""
coverage: CoverageConfig = CoverageConfig()
"""
Configuration related to coverage reporting.
"""
enable_fixture_rebasing: bool = True
"""... | ApeTestConfig |
python | google__jax | tests/pallas/tpu_splash_attention_kernel_test.py | {
"start": 3774,
"end": 4466
} | class ____(Mask):
q_seq_len: int
kv_seq_len: int
sparsity: float
seed: int
def get_mask(self) -> mask_lib.Mask:
mask = mask_lib.make_random_mask(
(self.q_seq_len, self.kv_seq_len), self.sparsity, self.seed
)
# Make sure that no row is full of zeros as this is leads to undefined
# soft... | RandomMask |
python | ansible__ansible | test/units/module_utils/basic/test_tmpdir.py | {
"start": 377,
"end": 3843
} | class ____:
DATA = (
(
{
"_ansible_tmpdir": "/path/to/dir",
"_ansible_remote_tmp": "/path/tmpdir",
"_ansible_keep_remote_files": False,
},
True,
"/path/to/dir"
),
(
{
... | TestAnsibleModuleTmpDir |
python | Lightning-AI__lightning | tests/tests_pytorch/tuner/test_scale_batch_size.py | {
"start": 24465,
"end": 25700
} | class ____(BoringModel):
"""A BoringModel that fails when batch size reaches a certain threshold."""
def __init__(self, batch_size=2, fail_at=16):
super().__init__()
self.batch_size = batch_size
self.fail_at = fail_at
def training_step(self, batch, batch_idx):
# Simulate OO... | FailsAtBatchSizeBoringModel |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/remote_explorer.py | {
"start": 2864,
"end": 38887
} | class ____(QWidget, SpyderWidgetMixin):
sig_dir_opened = Signal(str, str)
sig_start_spinner_requested = Signal()
sig_stop_spinner_requested = Signal()
def __init__(self, parent=None, class_parent=None, files=None):
super().__init__(parent=parent, class_parent=parent)
# General attribut... | RemoteExplorer |
python | getsentry__sentry | src/sentry/api/invite_helper.py | {
"start": 1319,
"end": 1821
} | class ____:
invite_token: str | None
invite_member_id: int | None
invite_organization_id: int | None
def get_invite_details(request: HttpRequest) -> InviteDetails:
"""Returns tuple of (token, member_id) from request session"""
return InviteDetails(
invite_token=request.session.get("invite_... | InviteDetails |
python | python-pillow__Pillow | Tests/test_imagefile.py | {
"start": 8396,
"end": 8575
} | class ____:
@classmethod
def setup_class(cls) -> None:
Image.register_decoder("MOCK", MockPyDecoder)
Image.register_encoder("MOCK", MockPyEncoder)
| CodecsTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/cloud_formation.py | {
"start": 1271,
"end": 3111
} | class ____(AwsBaseOperator[CloudFormationHook]):
"""
An operator that creates an AWS CloudFormation stack.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudFormationCreateStackOperator`
:param stack_name: stack name (tem... | CloudFormationCreateStackOperator |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/project_key.py | {
"start": 357,
"end": 894
} | class ____(serializers.Serializer):
"""
Applies a rate limit to cap the number of errors accepted during a given time window. To
disable entirely set `rateLimit` to null.
```json
{
"rateLimit": {
"window": 7200, // time in seconds
"count": 1000 // error cap
}
... | RateLimitSerializer |
python | doocs__leetcode | solution/2200-2299/2276.Count Integers in Intervals/Solution.py | {
"start": 1721,
"end": 2085
} | class ____:
def __init__(self):
self.tree = SegmentTree()
def add(self, left, right):
self.tree.modify(left, right, 1)
def count(self):
return self.tree.query(1, int(1e9))
# Your CountIntervals object will be instantiated and called as such:
# obj = CountIntervals()
# obj.add(lef... | CountIntervals |
python | walkccc__LeetCode | solutions/670. Maximum Swap/670.py | {
"start": 0,
"end": 378
} | class ____:
def maximumSwap(self, num: int) -> int:
s = list(str(num))
dict = {c: i for i, c in enumerate(s)}
for i, c in enumerate(s):
for digit in reversed(string.digits):
if digit <= c:
break
if digit in dict and dict[digit] > i:
s[i], s[dict[digit]] = digit, ... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 40186,
"end": 40876
} | class ____(sgqlc.types.Enum):
"""The GitHub Enterprise Importer (GEI) migration state.
Enumeration Choices:
* `FAILED`: The migration has failed.
* `FAILED_VALIDATION`: The migration has invalid credentials.
* `IN_PROGRESS`: The migration is in progress.
* `NOT_STARTED`: The migration has not ... | MigrationState |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol17.py | {
"start": 393,
"end": 657
} | class ____(Protocol[_T1, _T2, _T3]):
def m1(self, p0: _T1, p1: _T2, p2: _T3) -> _T1 | _T2: ...
def m2(self) -> _T1: ...
def m3(self) -> _T2: ...
def m4(self) -> _T3: ...
# This should generate an error because _T3 should be contravariant
| Protocol1 |
python | apache__airflow | helm-tests/tests/chart_utils/helm_template_generator.py | {
"start": 5544,
"end": 7754
} | class ____(subprocess.CalledProcessError):
def __str__(self):
return f"Helm command failed. Args: {self.args}\nStderr: \n{self.stderr.decode('utf-8')}"
def render_chart(
name="release-name",
values=None,
show_only=None,
chart_dir=None,
kubernetes_version=DEFAULT_KUBERNETES_VERSION,
... | HelmFailedError |
python | ansible__ansible | test/integration/targets/plugin_config_for_inventory/cache_plugins/none.py | {
"start": 738,
"end": 1453
} | class ____(BaseCacheModule):
def __init__(self, *args, **kwargs):
super(CacheModule, self).__init__(*args, **kwargs)
self.empty = {}
self._timeout = self.get_option('_timeout')
def get(self, key):
return self.empty.get(key)
def set(self, key, value):
return value
... | CacheModule |
python | readthedocs__readthedocs.org | readthedocs/core/unresolver.py | {
"start": 2211,
"end": 2489
} | class ____(UnresolverError):
def __init__(self, project, version_slug, external_version_slug):
self.project = project
self.version_slug = version_slug
self.external_version_slug = external_version_slug
@dataclass(slots=True)
| InvalidExternalVersionError |
python | apache__airflow | airflow-core/tests/unit/core/test_stats.py | {
"start": 6433,
"end": 10682
} | class ____:
def setup_method(self):
pytest.importorskip("datadog")
from datadog import DogStatsd
self.dogstatsd_client = Mock(spec=DogStatsd)
self.dogstatsd = SafeDogStatsdLogger(self.dogstatsd_client)
def test_increment_counter_with_valid_name_with_dogstatsd(self):
sel... | TestDogStats |
python | sqlalchemy__sqlalchemy | test/orm/test_froms.py | {
"start": 1762,
"end": 4680
} | class ____(_fixtures.FixtureTest):
run_setup_mappers = "once"
run_inserts = "once"
run_deletes = None
@classmethod
def setup_mappers(cls):
(
Node,
composite_pk_table,
users,
Keyword,
items,
Dingaling,
order_... | QueryTest |
python | astropy__astropy | astropy/modeling/tests/test_parameters.py | {
"start": 1495,
"end": 4561
} | class ____(FittableModel):
alpha = Parameter(name="alpha", default=42)
@staticmethod
def evaluate(*args):
pass
def test__tofloat():
# iterable
value = _tofloat([1, 2, 3])
assert isinstance(value, np.ndarray)
assert (value == np.array([1, 2, 3])).all()
assert np.all([isinstance... | MockModel |
python | numba__numba | numba/core/typing/cmathdecl.py | {
"start": 728,
"end": 896
} | class ____(ConcreteTemplate):
cases = [signature(types.boolean, tp) for tp in
sorted(types.complex_domain)]
@infer_global(cmath.isfinite)
| CMath_predicate |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 72400,
"end": 73452
} | class ____(Response):
"""
Response of events.delete_for_task endpoint.
:param deleted: Number of deleted events
:type deleted: bool
"""
_service = "events"
_action = "delete_for_task"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"dele... | DeleteForTaskResponse |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_gen_ai.py | {
"start": 3187,
"end": 6948
} | class ____:
def dummy_get_credentials(self):
pass
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id
):
self.hook = GenAIGenerativeModelHook(gcp_conn_id=TEST_GCP_CONN_ID)
s... | TestGenAIGenerativeModelHookWithDefaultProjectId |
python | scikit-learn__scikit-learn | sklearn/compose/_target.py | {
"start": 728,
"end": 14636
} | class ____(RegressorMixin, BaseEstimator):
"""Meta-estimator to regress on a transformed target.
Useful for applying a non-linear transformation to the target `y` in
regression problems. This transformation can be given as a Transformer
such as the :class:`~sklearn.preprocessing.QuantileTransformer` or... | TransformedTargetRegressor |
python | cython__cython | docs/examples/userguide/language_basics/optional_subclassing.py | {
"start": 15,
"end": 96
} | class ____:
@cython.cfunc
def foo(self):
print("A")
@cython.cclass
| A |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/buffer.py | {
"start": 1523,
"end": 4035
} | class ____:
"""
Immutable class that contains a completion state.
"""
def __init__(
self,
original_document: Document,
completions: list[Completion] | None = None,
complete_index: int | None = None,
) -> None:
#: Document as it was when the completion started... | CompletionState |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/ranges.py | {
"start": 28860,
"end": 30171
} | class ____(AbstractRange[Sequence[Range[_T]]]):
"""Base for PostgreSQL MULTIRANGE types.
these are types that return a sequence of :class:`_postgresql.Range`
objects.
"""
__abstract__ = True
def _resolve_for_literal(self, value: Sequence[Range[Any]]) -> Any:
if not value:
... | AbstractMultiRange |
python | ray-project__ray | python/ray/util/collective/tests/util.py | {
"start": 285,
"end": 4251
} | class ____:
def __init__(self):
self.buffer = None
self.list_buffer = None
def init_tensors(self):
self.buffer = cp.ones((10,), dtype=cp.float32)
self.list_buffer = [cp.ones((10,), dtype=cp.float32) for _ in range(2)]
cp.cuda.Stream.null.synchronize()
return True... | Worker |
python | walkccc__LeetCode | solutions/2983. Palindrome Rearrangement Queries/2983.py | {
"start": 0,
"end": 2864
} | class ____:
def canMakePalindromeQueries(
self,
s: str,
queries: list[list[int]],
) -> list[bool]:
n = len(s)
# mirroredDiffs[i] := the number of different letters between the first i
# letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1]
mirroredDiffs = self._getMir... | Solution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/executors/ecs/utils.py | {
"start": 5201,
"end": 9759
} | class ____:
"""A five-way dictionary between Airflow task ids, Airflow cmds, ECS ARNs, and ECS task objects."""
def __init__(self):
self.key_to_arn: dict[TaskInstanceKey, str] = {}
self.arn_to_key: dict[str, TaskInstanceKey] = {}
self.tasks: dict[str, EcsExecutorTask] = {}
self.... | EcsTaskCollection |
python | django__django | tests/template_tests/syntax_tests/test_basic.py | {
"start": 14810,
"end": 15833
} | class ____(SimpleTestCase):
template_error_msg = (
"Invalid block tag on line 1: 'endfor'. Did you forget to register or "
"load this tag?"
)
def test_template_name_in_error_message(self):
msg = f"Template: test.html, {self.template_error_msg}"
with self.assertRaisesMessage(... | TemplateNameInExceptionTests |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/schedule_tests/test_business_logic.py | {
"start": 574,
"end": 7411
} | class ____:
"""Test the pure functions that process GraphQL responses."""
def test_process_schedules_response_success(self, snapshot):
"""Test processing a successful schedules GraphQL response."""
# Sample GraphQL response structure
response = {
"schedulesOrError": {
... | TestProcessScheduleResponses |
python | donnemartin__interactive-coding-challenges | graphs_trees/check_balance/test_check_balance.py | {
"start": 18,
"end": 1043
} | class ____(unittest.TestCase):
def test_check_balance_empty(self):
bst = BstBalance(None)
bst.check_balance()
def test_check_balance(self):
bst = BstBalance(Node(5))
self.assertEqual(bst.check_balance(), True)
bst.insert(3)
bst.insert(8)
bst.insert(1)
... | TestCheckBalance |
python | langchain-ai__langchain | libs/core/langchain_core/utils/aiter.py | {
"start": 8996,
"end": 10574
} | class ____(AbstractAsyncContextManager): # noqa: N801
"""Async context manager to wrap an AsyncGenerator that has a `aclose()` method.
Code like this:
```python
async with aclosing(<module>.fetch(<arguments>)) as agen:
<block>
```
is equivalent to this:
```python
agen = <mod... | aclosing |
python | pytorch__pytorch | torch/package/package_importer.py | {
"start": 1904,
"end": 28601
} | class ____(Importer):
"""Importers allow you to load code written to packages by :class:`PackageExporter`.
Code is loaded in a hermetic way, using files from the package
rather than the normal python import system. This allows
for the packaging of PyTorch model code and data so that it can be run
on... | PackageImporter |
python | ansible__ansible | test/units/module_utils/basic/test_log.py | {
"start": 302,
"end": 1140
} | class ____:
DATA = [u'Text string', u'Toshio くらとみ non-ascii test']
DATA = DATA + [d.encode('utf-8') for d in DATA]
DATA += [b'non-utf8 :\xff: test']
@pytest.mark.parametrize('msg, stdin', ((m, {}) for m in DATA), indirect=['stdin'])
def test_smoketest_syslog(self, am, mocker, msg):
# These ... | TestAnsibleModuleLogSmokeTest |
python | python-openxml__python-docx | tests/oxml/test_ns.py | {
"start": 99,
"end": 1634
} | class ____:
def it_behaves_like_a_string_when_you_want_it_to(self, nsptag):
s = "- %s -" % nsptag
assert s == "- a:foobar -"
def it_knows_its_clark_name(self, nsptag, clark_name):
assert nsptag.clark_name == clark_name
def it_can_construct_from_a_clark_name(self, clark_name, nsptag... | DescribeNamespacePrefixedTag |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/util.py | {
"start": 32510,
"end": 38818
} | class ____(visitors.ReplacingExternalTraversal):
"""Clones and modifies clauses based on column correspondence.
E.g.::
table1 = Table(
"sometable",
metadata,
Column("col1", Integer),
Column("col2", Integer),
)
table2 = Table(
"someothertable"... | ClauseAdapter |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/transfers/bigquery_to_bigquery.py | {
"start": 1334,
"end": 10827
} | class ____(BaseOperator):
"""
Copies data from one BigQuery table to another.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BigQueryToBigQueryOperator`
.. seealso::
For more details about these parameters:
h... | BigQueryToBigQueryOperator |
python | weaviate__weaviate-python-client | weaviate/collections/queries/fetch_objects/generate/sync.py | {
"start": 320,
"end": 473
} | class ____(
Generic[Properties, References],
_FetchObjectsGenerateExecutor[ConnectionSync, Properties, References],
):
pass
| _FetchObjectsGenerate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.