language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | huggingface__transformers | src/transformers/models/csm/modular_csm.py | {
"start": 1775,
"end": 5016
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the lan... | CsmOutputWithPast |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis17.py | {
"start": 315,
"end": 1389
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis17.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | spyder-ide__spyder | spyder/plugins/run/models.py | {
"start": 728,
"end": 5850
} | class ____(QAbstractListModel):
sig_executor_widget_changed = Signal(object)
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.uuid: Optional[str] = None
self.current_input: Optional[Tuple[str, str]] = None
self.executor_names: Dict[str, str]... | RunExecutorListModel |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/matmul_op_test.py | {
"start": 1376,
"end": 2408
} | class ____(test_lib.TestCase):
"""Simple test for tf.matmul where Tout is different from T."""
def testBatchMatMulV3OutputType(self):
# TODO(shivaniagrawal): uint8 is not supported for mixed matmul type in XLA.
for (a_dtype, b_dtype) in [(np.int8, np.int8), (np.uint8, np.uint8)]:
a = np.array([[1, 2]... | MatMulMixedType |
python | weaviate__weaviate-python-client | weaviate/collections/aggregate.py | {
"start": 668,
"end": 773
} | class ____(_Hybrid, _NearImage, _NearObject, _NearText, _NearVector, _OverAll):
pass
| _AggregateCollection |
python | django__django | tests/admin_inlines/admin.py | {
"start": 4276,
"end": 4634
} | class ____(forms.ModelForm):
title1 = forms.CharField(max_length=100)
def clean(self):
cleaned_data = self.cleaned_data
title1 = cleaned_data.get("title1")
title2 = cleaned_data.get("title2")
if title1 != title2:
raise ValidationError("The two titles must be the same... | TitleForm |
python | ray-project__ray | python/ray/train/tests/test_session.py | {
"start": 9537,
"end": 10992
} | class ____(Accelerator):
pass
def test_set_and_get_accelerator(session):
accelerator = FakeAccelerator()
set_accelerator(accelerator)
assert get_accelerator(FakeAccelerator) is accelerator
def test_get_accelerator_constructs_default_accelerator(session):
assert isinstance(get_accelerator(FakeAcc... | FakeAccelerator |
python | PyCQA__pylint | tests/functional/c/consider/consider_using_in.py | {
"start": 2307,
"end": 2383
} | class ____:
value = 2
A.value == 1 or A.value == 2 # [consider-using-in]
| A |
python | realpython__materials | python-class/mixins.py | {
"start": 127,
"end": 285
} | class ____:
def to_json(self):
return json.dumps(self.__dict__)
def to_pickle(self):
return pickle.dumps(self.__dict__)
| SerializerMixin |
python | huggingface__transformers | src/transformers/models/clipseg/modeling_clipseg.py | {
"start": 29060,
"end": 30974
} | class ____(CLIPSegPreTrainedModel):
config: CLIPSegTextConfig
input_modalities = ("text",)
_no_split_modules = ["CLIPSegTextEmbeddings", "CLIPSegEncoderLayer"]
def __init__(self, config: CLIPSegTextConfig):
super().__init__(config)
self.text_model = CLIPSegTextTransformer(config)
... | CLIPSegTextModel |
python | pypa__pip | src/pip/_vendor/pyproject_hooks/_impl.py | {
"start": 1774,
"end": 3746
} | class ____(Exception):
"""May be raised by build_sdist if the backend indicates that it can't."""
def __init__(self, traceback: str) -> None:
self.traceback = traceback
def default_subprocess_runner(
cmd: Sequence[str],
cwd: Optional[str] = None,
extra_environ: Optional[Mapping[str, str]]... | UnsupportedOperation |
python | tensorflow__tensorflow | tensorflow/python/distribute/multi_worker_test_base.py | {
"start": 15007,
"end": 19524
} | class ____(test.TestCase):
"""Base class for testing multi node strategy and dataset."""
@classmethod
def setUpClass(cls, num_workers=2, num_ps=1): # pylint: disable=g-missing-super-call
"""Create a local cluster with 2 workers."""
cls._cluster_spec = create_in_process_cluster(num_workers=num_workers,
... | MultiWorkerTestBase |
python | apache__airflow | airflow-core/src/airflow/executors/workloads.py | {
"start": 1457,
"end": 1726
} | class ____(BaseModel):
token: str
"""The identity token for this workload"""
@staticmethod
def generate_token(sub_id: str, generator: JWTGenerator | None = None) -> str:
return generator.generate({"sub": sub_id}) if generator else ""
| BaseWorkload |
python | scipy__scipy | doc/source/array_api_capabilities_table.py | {
"start": 2233,
"end": 3392
} | class ____(SphinxDirective):
has_content = False
option_spec = {
module_name.replace("scipy.", ""): directives.unchanged
for module_name in PUBLIC_MODULES
}
option_spec["backend_type"] = directives.unchanged
def run(self):
backend_type = self.options.pop("backend_type")
... | ArrayAPISupportPerModule |
python | astropy__astropy | astropy/visualization/wcsaxes/tests/test_transform_coord_meta.py | {
"start": 1386,
"end": 4721
} | class ____(BaseImageTests):
@figure_test
def test_coords_overlay(self):
# Set up a simple WCS that maps pixels to non-projected distances
wcs = WCS(naxis=2)
wcs.wcs.ctype = ["x", "y"]
wcs.wcs.cunit = ["km", "km"]
wcs.wcs.crpix = [614.5, 856.5]
wcs.wcs.cdelt = [6.2... | TestTransformCoordMeta |
python | Textualize__textual | tests/tree/test_tree_expand_etc.py | {
"start": 114,
"end": 4824
} | class ____(App[None]):
"""Test tree app."""
def compose(self) -> ComposeResult:
yield Tree("Test")
def on_mount(self) -> None:
tree = self.query_one(Tree)
for n in range(10):
tree.root.add(f"Trunk {n}")
node = tree.root.children[0]
for n in range(10):
... | TreeApp |
python | pandas-dev__pandas | pandas/tests/indexes/period/test_tools.py | {
"start": 135,
"end": 1060
} | class ____:
"""
Wish to match NumPy units
"""
@pytest.mark.parametrize(
"freq, base_date",
[
("W-THU", "1970-01-01"),
("D", "1970-01-01"),
("B", "1970-01-01"),
("h", "1970-01-01"),
("min", "1970-01-01"),
("s", "1970... | TestPeriodRepresentation |
python | scrapy__scrapy | tests/test_squeues.py | {
"start": 1133,
"end": 1453
} | class ____:
def test_serialize(self):
q = self.queue()
q.push("a")
q.push(123)
q.push({"a": "dict"})
assert q.pop() == "a"
assert q.pop() == 123
assert q.pop() == {"a": "dict"}
test_nonserializable_object = nonserializable_object_test
| FifoDiskQueueTestMixin |
python | pytorch__pytorch | test/distributed/checkpoint/test_file_system_checkpoint_cpu.py | {
"start": 3602,
"end": 4686
} | class ____(TestCase):
@parametrize("thread_count", _THREAD_COUNTS)
def test_read_write_only_tensor(self, thread_count) -> None:
with tempfile.TemporaryDirectory() as path:
state_dict_to_save = MyTestModule().state_dict()
fs_writer = FileSystemWriter(path=path, thread_count=threa... | TestDistributedStateDictSaveLoad |
python | Netflix__metaflow | test/core/tests/merge_artifacts_include.py | {
"start": 67,
"end": 2313
} | class ____(MetaflowTest):
PRIORITY = 1
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"recursive_switch",
"recursive_switch_inside_foreach",
]
@steps(0, [... | MergeArtifactsIncludeTest |
python | getsentry__sentry | tests/sentry/integrations/github/test_client.py | {
"start": 1647,
"end": 19493
} | class ____(TestCase):
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
def setUp(self, get_jwt):
ten_days = timezone.now() + timedelta(days=10)
self.integration = self.create_integration(
organization=self.organization,
provider="github... | GitHubApiClientTest |
python | openai__openai-python | src/openai/types/beta/realtime/input_audio_buffer_committed_event.py | {
"start": 236,
"end": 733
} | class ____(BaseModel):
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the user message item that will be created."""
type: Literal["input_audio_buffer.committed"]
"""The event type, must be `input_audio_buffer.committed`."""
previous_item_id: Optional[str... | InputAudioBufferCommittedEvent |
python | kamyu104__LeetCode-Solutions | Python/implement-stack-using-queues.py | {
"start": 77,
"end": 428
} | class ____(object):
def __init__(self):
self.data = collections.deque()
def push(self, x):
self.data.append(x)
def peek(self):
return self.data[0]
def pop(self):
return self.data.popleft()
def size(self):
return len(self.data)
def empty(self):
... | Queue |
python | celery__celery | t/unit/apps/test_multi.py | {
"start": 727,
"end": 1689
} | class ____:
def test_parse(self):
x = NamespacedOptionParser(['-c:1,3', '4'])
x.parse()
assert x.namespaces.get('1,3') == {'-c': '4'}
x = NamespacedOptionParser(['-c:jerry,elaine', '5',
'--loglevel:kramer=DEBUG',
... | test_NamespacedOptionParser |
python | sympy__sympy | sympy/polys/agca/modules.py | {
"start": 33190,
"end": 33500
} | class ____(ProductOrder):
"""A product monomial order with a zeroth term as module index."""
def __init__(self, o1, o2, TOP):
if TOP:
ProductOrder.__init__(self, (o2, _subs1), (o1, _subs0))
else:
ProductOrder.__init__(self, (o1, _subs0), (o2, _subs1))
| ModuleOrder |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_B.py | {
"start": 13716,
"end": 15035
} | class ____(Benchmark):
r"""
Branin01 objective function.
The Branin01 global optimization problem is a multimodal minimization
problem defined as follows
.. math::
f_{\text{Branin01}}(x) = \left(- 1.275 \frac{x_1^{2}}{\pi^{2}} + 5
\frac{x_1}{\pi} + x_2 -6\right)^{2} + \left(10 -... | Branin01 |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_rotation_test.py | {
"start": 189,
"end": 2631
} | class ____(testing.TestCase):
@parameterized.named_parameters(
("random_rotate_neg4", -0.4),
("random_rotate_neg2", -0.2),
("random_rotate_4", 0.4),
("random_rotate_2", 0.2),
("random_rotate_tuple", (-0.2, 0.4)),
)
def test_random_rotation_shapes(self, factor):
... | RandomRotationTest |
python | xlwings__xlwings | xlwings/pro/_xlremote.py | {
"start": 7253,
"end": 8996
} | class ____(base_classes.Book):
def __init__(self, api, books):
self.books = books
self._api = api
self._json = {"actions": []}
if api["version"] != __version__ and api["client"] != "Office.js":
raise XlwingsError(
f"Your xlwings version is different on the... | Book |
python | spack__spack | lib/spack/spack/oci/opener.py | {
"start": 7342,
"end": 15615
} | class ____(urllib.request.BaseHandler):
def __init__(self, credentials_provider: Callable[[str], Optional[UsernamePassword]]):
"""
Args:
credentials_provider: A function that takes a domain and may return a UsernamePassword.
"""
self.credentials_provider = credentials_pro... | OCIAuthHandler |
python | pypa__pipenv | pipenv/patched/pip/_internal/index/sources.py | {
"start": 2974,
"end": 4295
} | class ____(LinkSource):
"""Link source specified by ``--find-links=<path-to-dir>``.
This looks the content of the directory, and returns:
* ``page_candidates``: Links listed on each HTML file in the directory.
* ``file_candidates``: Archives in the directory.
"""
_paths_to_urls: Dict[str, _Fl... | _FlatDirectorySource |
python | rapidsai__cudf | python/cudf/cudf/core/window/rolling.py | {
"start": 1729,
"end": 18178
} | class ____(GetAttrGetItemMixin, _RollingBase, Reducible):
"""
Rolling window calculations.
Parameters
----------
window : int, offset or a BaseIndexer subclass
Size of the window, i.e., the number of observations used
to calculate the statistic.
For datetime indexes, an offs... | Rolling |
python | django__django | tests/get_earliest_or_latest/models.py | {
"start": 401,
"end": 628
} | class ____(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE)
likes_count = models.PositiveIntegerField()
# Ticket #23555 - model with an intentionally broken QuerySet.__iter__ method.
| Comment |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/stateful.py | {
"start": 37696,
"end": 40411
} | class ____:
name: str
# There are multiple alternatives for annotating the `precond` type, all of them
# have drawbacks. See https://github.com/HypothesisWorks/hypothesis/pull/3068#issuecomment-906642371
def precondition(precond: Callable[[Any], bool]) -> Callable[[TestFunc], TestFunc]:
"""Decorator to apply ... | VarReference |
python | encode__starlette | starlette/routing.py | {
"start": 7076,
"end": 11030
} | class ____(BaseRoute):
def __init__(
self,
path: str,
endpoint: Callable[..., Any],
*,
methods: Collection[str] | None = None,
name: str | None = None,
include_in_schema: bool = True,
middleware: Sequence[Middleware] | None = None,
) -> None:
... | Route |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/schema.py | {
"start": 204933,
"end": 205645
} | class ____(TypedDict, total=False):
fk: _NamingSchemaDirective
pk: _NamingSchemaDirective
ix: _NamingSchemaDirective
ck: _NamingSchemaDirective
uq: _NamingSchemaDirective
_NamingSchemaParameter = Union[
# it seems like the TypedDict here is useful for pylance typeahead,
# and not much else... | _NamingSchemaTD |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 3446,
"end": 4479
} | class ____(ActionBaseModel):
active: Optional[bool] = Field(
default=None, description="Whether or not the schedule is active."
)
schedule: Optional[schemas.schedules.SCHEDULE_TYPES] = Field(
default=None, description="The schedule for the deployment."
)
max_scheduled_runs: Optional... | DeploymentScheduleUpdate |
python | pypa__pip | src/pip/_vendor/rich/live_render.py | {
"start": 340,
"end": 3521
} | class ____:
"""Creates a renderable that may be updated.
Args:
renderable (RenderableType): Any renderable object.
style (StyleType, optional): An optional style to apply to the renderable. Defaults to "".
"""
def __init__(
self,
renderable: RenderableType,
styl... | LiveRender |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_vectors.py | {
"start": 732,
"end": 2554
} | class ____(ColumnMapMetricProvider):
VECTOR_REGEX = r"\[\d+\.*\d*,\s*\d+\.*\d*(,\s*\d+\.*\d*)*]"
# This is the id string that will be used to reference your metric.
# Please see https://docs.greatexpectations.io/en/latest/reference/core_concepts/metrics.html#metrics
# for information on how to choose a... | ColumnValuesIsVector |
python | pandas-dev__pandas | pandas/tests/window/test_numba.py | {
"start": 9731,
"end": 13805
} | class ____:
@pytest.mark.parametrize(
"grouper", [lambda x: x, lambda x: x.groupby("A")], ids=["None", "groupby"]
)
@pytest.mark.parametrize("method", ["mean", "sum"])
def test_invalid_engine(self, grouper, method):
df = DataFrame({"A": ["a", "b", "a", "b"], "B": range(4)})
with ... | TestEWM |
python | langchain-ai__langchain | libs/core/langchain_core/language_models/fake.py | {
"start": 2057,
"end": 2137
} | class ____(Exception):
"""Fake error for testing purposes."""
| FakeListLLMError |
python | facebook__pyre-check | client/commands/tests/statistics_test.py | {
"start": 18721,
"end": 22630
} | class ____(testslide.TestCase):
def test_collect_statistics(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root)
setup.ensure_files_exist(root_path, ["foo.py", "bar.py"])
foo_path = root_path / "foo.py"
bar_path = root_path / "bar.... | StatisticsTest |
python | pypa__pipenv | pipenv/patched/pip/_internal/utils/logging.py | {
"start": 1090,
"end": 2129
} | class ____(Exception):
"""
Raised if BrokenPipeError occurs for the stdout stream while logging.
"""
def _is_broken_pipe_error(exc_class: Type[BaseException], exc: BaseException) -> bool:
if exc_class is BrokenPipeError:
return True
# On Windows, a broken pipe can show up as EINVAL rather... | BrokenStdoutLoggingError |
python | ray-project__ray | doc/source/serve/doc_code/http_guide/disconnects.py | {
"start": 196,
"end": 1615
} | class ____:
def __init__(self):
self.print_storage: List[str] = []
def add(self, s: str):
self.print_storage.append(s)
def clear(self):
self.print_storage.clear()
def get(self) -> List[str]:
return self.print_storage
print_storage_handle = PrintStorage.remote()
def... | PrintStorage |
python | doocs__leetcode | lcof/面试题61. 扑克牌中的顺子/Solution.py | {
"start": 0,
"end": 346
} | class ____:
def isStraight(self, nums: List[int]) -> bool:
vis = set()
mi, mx = inf, -inf
for x in nums:
if x == 0:
continue
if x in vis:
return False
vis.add(x)
mi = min(mi, x)
mx = max(mx, x)
... | Solution |
python | pydata__xarray | xarray/backends/pydap_.py | {
"start": 840,
"end": 1954
} | class ____(BackendArray):
def __init__(self, array, checksums=True):
self.array = array
@property
def shape(self) -> tuple[int, ...]:
return self.array.shape
@property
def dtype(self):
return self.array.dtype
def __getitem__(self, key):
return indexing.explicit... | PydapArrayWrapper |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 152878,
"end": 153971
} | class ____(Operation):
def call(self, x1, x2):
return backend.numpy.minimum(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape", [])
output_shape = broadcast_shapes(x1_shape, x2_shape)
output_dtype = dtypes.re... | Minimum |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/s3.py | {
"start": 25009,
"end": 32810
} | class ____(AwsBaseOperator[S3Hook]):
"""
Copies data from a source S3 location to a temporary location on the local filesystem.
Runs a transformation on this file as specified by the transformation
script and uploads the output to a destination S3 location.
The locations of the source and the dest... | S3FileTransformOperator |
python | ray-project__ray | python/ray/llm/tests/serve/gpu/integration/test_openai_compatibility.py | {
"start": 42,
"end": 4643
} | class ____:
"""Test that the rayllm are compatible with the OpenAI API"""
def test_models(self, testing_model): # noqa: F811
client, model = testing_model
models = client.models.list()
assert len(models.data) == 1, "Only the test model should be returned"
assert models.data[0].... | TestOpenAICompatibility |
python | huggingface__transformers | src/transformers/models/clvp/configuration_clvp.py | {
"start": 6999,
"end": 15038
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ClvpDecoder`]. It is used to instantiate a CLVP
Decoder Model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar c... | ClvpDecoderConfig |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/autograd_cache.py | {
"start": 2396,
"end": 10470
} | class ____(BypassAOTAutogradCache):
pass
def should_use_remote_autograd_cache():
if torch.compiler.config.force_disable_caches:
return False
if config.enable_remote_autograd_cache is not None:
return config.enable_remote_autograd_cache
if not config.is_fbcode():
return False
... | FXGraphCacheMiss |
python | doocs__leetcode | solution/3100-3199/3183.The Number of Ways to Make the Sum/Solution2.py | {
"start": 154,
"end": 371
} | class ____:
def numberOfWays(self, n: int) -> int:
ans = f[n]
if n >= 4:
ans = (ans + f[n - 4]) % mod
if n >= 8:
ans = (ans + f[n - 8]) % mod
return ans
| Solution |
python | getsentry__sentry | src/sentry/monitors/serializers.py | {
"start": 5178,
"end": 5295
} | class ____(TypedDict, total=False):
alertRule: MonitorAlertRuleSerializerResponse
| MonitorSerializerResponseOptional |
python | anthropics__anthropic-sdk-python | tests/test_legacy_response.py | {
"start": 330,
"end": 1930
} | class ____(pydantic.BaseModel): ...
def test_response_parse_mismatched_basemodel(client: Anthropic) -> None:
response = LegacyAPIResponse(
raw=httpx.Response(200, content=b"foo"),
client=client,
stream=False,
stream_cls=None,
cast_to=str,
options=FinalRequestOptions... | PydanticModel |
python | kennethreitz__tablib | tests/test_tablib_dbfpy_packages_fields.py | {
"start": 122,
"end": 1208
} | class ____(unittest.TestCase):
"""dbfpy.fields.DbfFieldDef comparison test cases, via child classes."""
def setUp(self) -> None:
self.length = 10
self.a = fields.DbfCharacterFieldDef("abc", self.length)
self.z = fields.DbfCharacterFieldDef("xyz", self.length)
self.a2 = fields.Db... | DbfFieldDefTestCompareCase |
python | pdm-project__pdm | src/pdm/models/repositories/base.py | {
"start": 836,
"end": 1485
} | class ____(NamedTuple):
dependencies: list[Requirement]
requires_python: str
summary: str
def cache_result(func: Callable[[T, Candidate], CandidateMetadata]) -> Callable[[T, Candidate], CandidateMetadata]:
@wraps(func)
def wrapper(self: T, candidate: Candidate) -> CandidateMetadata:
result... | CandidateMetadata |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 22288,
"end": 22873
} | class ____:
param_names = ["shape"]
params = [get_benchmark_shapes("TimeIndexing")]
def setup(self, shape):
self.df = generate_dataframe("int", *shape, RAND_LOW, RAND_HIGH)
self.numeric_indexer = [0, 1]
self.labels_indexer = self.df.columns[self.numeric_indexer].tolist()
def ti... | TimeIndexingColumns |
python | openai__openai-python | src/openai/_base_client.py | {
"start": 66840,
"end": 68237
} | class ____:
def __init__(self, name: str) -> None:
self.name = name
@override
def __str__(self) -> str:
return f"other:{self.name}"
Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]]
def get_python_runtime() -> str:
try:
return platform.python_implemen... | OtherArch |
python | doocs__leetcode | solution/3100-3199/3104.Find Longest Self-Contained Substring/Solution.py | {
"start": 0,
"end": 576
} | class ____:
def maxSubstringLength(self, s: str) -> int:
first, last = {}, {}
for i, c in enumerate(s):
if c not in first:
first[c] = i
last[c] = i
ans, n = -1, len(s)
for c, i in first.items():
mx = last[c]
for j in ran... | Solution |
python | scipy__scipy | scipy/special/_generate_pyx.py | {
"start": 13887,
"end": 16388
} | class ____:
"""
Base class for Ufunc.
"""
def __init__(self, name, signatures):
self.name = name
self.signatures = []
self.function_name_overrides = {}
for header in signatures.keys():
for name, sig in signatures[header].items():
inarg, outar... | Func |
python | django__django | tests/forms_tests/tests/test_forms.py | {
"start": 208068,
"end": 208121
} | class ____(FormsTestCase):
pass
| Jinja2FormsTestCase |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 59799,
"end": 60454
} | class ____(
TestMaskedArrayInteractionWithNumpyMA, QuantitySetup
):
pass
@pytest.mark.skipif(not HAS_PLT, reason="requires matplotlib.pyplot")
def test_plt_scatter_masked():
# check that plotting Masked data doesn't raise an exception
# see https://github.com/astropy/astropy/issues/12481
import ma... | TestMaskedQuantityInteractionWithNumpyMA |
python | tensorflow__tensorflow | tensorflow/python/saved_model/nested_structure_coder_test.py | {
"start": 1725,
"end": 21542
} | class ____(test.TestCase):
def testEncodeDecodeList(self):
structure = [1.5, 2.5, 3.0]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected.list_value.values.add().float64_value ... | NestedStructureCoderTest |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker/lkml/dagster_looker_lkml_translator.py | {
"start": 6698,
"end": 31242
} | class ____:
"""Holds a set of methods that derive Dagster asset definition metadata given a representation
of a LookML structure (dashboards, explores, views).
This class is exposed so that methods can be overridden to customize how Dagster asset metadata
is derived.
"""
@public
def get_as... | DagsterLookerLkmlTranslator |
python | celery__celery | t/unit/app/test_builtins.py | {
"start": 788,
"end": 1096
} | class ____(BuiltinsCase):
def setup_method(self):
self.accumulate = self.app.tasks['celery.accumulate']
def test_with_index(self):
assert self.accumulate(1, 2, 3, 4, index=0) == 1
def test_no_index(self):
assert self.accumulate(1, 2, 3, 4), (1, 2, 3 == 4)
| test_accumulate |
python | walkccc__LeetCode | solutions/2054. Two Best Non-Overlapping Events/2054.py | {
"start": 0,
"end": 497
} | class ____:
def maxTwoEvents(self, events: list[list[int]]) -> int:
ans = 0
maxValue = 0
evts = [] # (time, isStart, value)
for s, e, v in events:
evts.append((s, 1, v))
evts.append((e + 1, 0, v))
# When two events have the same time, the one is not start will be in the front
ev... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias1.py | {
"start": 952,
"end": 1103
} | class ____:
TA1 = list
def __init__(self) -> None:
self.val = self.TA1
b = B()
reveal_type(b.val, expected_text="type[list[Unknown]]")
| B |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_code_interpreter.py | {
"start": 3236,
"end": 16704
} | class ____:
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.CodeInterpreter"
)
def test_init(self, mock_code_interpreter):
tool_spec = AgentCoreCodeInterpreterToolSpec(region="us-east-1")
assert tool_spec.region == "us-east-1"
assert tool_spec._code_int... | TestAgentCoreCodeInterpreterToolSpec |
python | realpython__materials | nearbyshops/shops/migrations/0002_auto_20181020_0450.py | {
"start": 982,
"end": 1150
} | class ____(migrations.Migration):
dependencies = [
('shops', '0001_initial'),
]
operations = [
migrations.RunPython(load_data)
]
| Migration |
python | langchain-ai__langchain | libs/core/langchain_core/tracers/event_stream.py | {
"start": 2342,
"end": 34966
} | class ____(AsyncCallbackHandler, _StreamingCallbackHandler):
"""An implementation of an async callback handler for astream events."""
def __init__(
self,
*args: Any,
include_names: Sequence[str] | None = None,
include_types: Sequence[str] | None = None,
include_tags: Seq... | _AstreamEventsCallbackHandler |
python | django-extensions__django-extensions | tests/management/commands/test_drop_test_database.py | {
"start": 1360,
"end": 2420
} | class ____(TestCase):
"""Test for drop_test_database command."""
def test_should_raise_CommandError_if_database_is_unknown(self):
with self.assertRaisesRegex(CommandError, "Unknown database unknown"):
call_command("drop_test_database", "--database=unknown")
@override_settings(DATABASES... | DropTestDatabaseExceptionsTests |
python | sphinx-doc__sphinx | sphinx/theming.py | {
"start": 1395,
"end": 4889
} | class ____:
"""A Theme is a set of HTML templates and configurations.
This class supports both theme directory and theme archive (zipped theme).
"""
def __init__(
self,
name: str,
*,
configs: dict[str, _ConfigFile],
paths: list[Path],
tmp_dirs: list[Path... | Theme |
python | kamyu104__LeetCode-Solutions | Python/count-almost-equal-pairs-ii.py | {
"start": 1536,
"end": 2879
} | class ____(object):
def countPairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
L = 7
K = 2
POW10 = [0]*L
POW10[0] = 1
for i in xrange(L-1):
POW10[i+1] = POW10[i]*10
def at_most(k, x):
lookup = {x}
... | Solution2 |
python | kamyu104__LeetCode-Solutions | Python/maximum-score-of-a-good-subarray.py | {
"start": 29,
"end": 744
} | class ____(object):
def maximumScore(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result = curr = nums[k]
left = right = k
while left-1 >= 0 or right+1 < len(nums):
# choosing larger one to expand is always better ... | Solution |
python | astropy__astropy | astropy/units/tests/test_logarithmic.py | {
"start": 24678,
"end": 33261
} | class ____:
@pytest.mark.parametrize(
"other",
[
2.4 * u.mag(),
12.34 * u.ABmag,
u.Magnitude(3.45 * u.Jy),
u.Dex(3.0),
u.Dex(np.linspace(3000, 5000, 10) * u.Angstrom),
u.Magnitude(6.78, 2.0 * u.mag),
],
)
@pytest... | TestLogQuantityArithmetic |
python | doocs__leetcode | solution/3100-3199/3196.Maximize Total Cost of Alternating Subarrays/Solution2.py | {
"start": 0,
"end": 183
} | class ____:
def maximumTotalCost(self, nums: List[int]) -> int:
f, g = -inf, 0
for x in nums:
f, g = max(f, g) + x, f - x
return max(f, g)
| Solution |
python | doocs__leetcode | solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.py | {
"start": 0,
"end": 202
} | class ____:
def minOperations(self, nums: List[int]) -> int:
ans = mx = 0
for v in nums:
ans += max(0, mx + 1 - v)
mx = max(mx + 1, v)
return ans
| Solution |
python | scrapy__scrapy | tests/CrawlerProcess/reactor_default.py | {
"start": 148,
"end": 383
} | class ____(scrapy.Spider):
name = "no_request"
async def start(self):
return
yield
process = CrawlerProcess(settings={})
d = process.crawl(NoRequestsSpider)
d.addErrback(log.err)
process.start()
| NoRequestsSpider |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 14144,
"end": 15666
} | class ____(ranges.AbstractMultiRangeImpl):
def bind_processor(self, dialect):
asyncpg_Range = dialect.dbapi.asyncpg.Range
def to_range(value):
if isinstance(value, (str, NoneType)):
return value
def to_range(value):
if isinstance(value, range... | _AsyncpgMultiRange |
python | joke2k__faker | faker/providers/bank/fa_IR/__init__.py | {
"start": 42,
"end": 1327
} | class ____(BankProvider):
"""Implement bank provider for ``fa_IR`` locale."""
bban_format = "IR########################"
country_code = "IR"
swift_bank_codes = (
"BEGN",
"KESH",
"BKMN",
"BKBP",
"CIYB",
"BTOS",
"IVBB",
"KBID",
"KIBO... | Provider |
python | huggingface__transformers | tests/models/evolla/test_processing_evolla.py | {
"start": 1029,
"end": 8595
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = EvollaProcessor
model_id = "westlake-repl/Evolla-10B-hf"
input_keys = ["protein_input_ids", "protein_attention_mask", "input_ids", "attention_mask"]
@unittest.skip("EvollaProcessor requires `messages_list` and `proteins` inputs.")
... | EvollaProcessorTest |
python | django__django | tests/apps/apps.py | {
"start": 36,
"end": 138
} | class ____(AppConfig):
name = "django.contrib.admin"
verbose_name = "Admin sweet admin."
| MyAdmin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF053.py | {
"start": 2074,
"end": 2119
} | class ____[T](Generic[Unpack[_As, _Bs]]): ...
| C |
python | streamlit__streamlit | e2e_playwright/st_altair_chart_basic_select_test.py | {
"start": 1108,
"end": 15502
} | class ____:
x: int
y: int
def _create_selection_rectangle(
app: Page,
chart: Locator,
canvas_start_pos: _MousePosition,
canvas_end_pos: _MousePosition,
) -> None:
expect(chart).to_be_visible()
chart.scroll_into_view_if_needed()
bounding_box = chart.bounding_box()
assert boundi... | _MousePosition |
python | django__django | tests/forms_tests/tests/test_renderers.py | {
"start": 1352,
"end": 1442
} | class ____(SharedTests, SimpleTestCase):
renderer = TemplatesSetting
| TemplatesSettingTests |
python | apache__airflow | helm-tests/tests/helm_tests/security/test_extra_configmaps_secrets.py | {
"start": 1055,
"end": 10260
} | class ____:
"""Tests extra configmaps and secrets."""
def test_extra_configmaps(self):
values_str = textwrap.dedent(
"""
extraConfigMaps:
"{{ .Release.Name }}-airflow-variables":
data: |
AIRFLOW_VAR_HELLO_MESSAGE: "Hi!"
... | TestExtraConfigMapsSecrets |
python | pytorch__pytorch | benchmarks/dynamo/genai_layers/kernels.py | {
"start": 331,
"end": 4039
} | class ____(BenchmarkKernel):
def __init__(self, script_args):
super().__init__(script_args)
self.available_backends = ["eager", "compiled", "quack", "liger"]
def get_shapes(self) -> tuple[tuple[int, ...], ...]:
return (
(32768, 256),
(32768, 512),
(32... | CrossEntropyForward |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0001_initial.py | {
"start": 163,
"end": 8886
} | class ____(migrations.Migration):
safe = Safe.always()
dependencies = [
("projects", "0001_initial"),
("taggit", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="Build",
fields=[
(
"id",
... | Migration |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/codeFlow2.py | {
"start": 180,
"end": 518
} | class ____(object):
# The symbol "stat" is a module even though
# it is redeclared below in this scope as
# a method.
_stat_mode: int = stat.S_IFDIR
def stat(self):
return None
def outer():
a = 1
def inner():
# This should generate an error
a += 1
inner()
... | FakeOsModule |
python | jazzband__pip-tools | tests/conftest.py | {
"start": 1801,
"end": 16360
} | class ____(BaseRepository):
def __init__(self, options: FakeOptions):
self._options = options
with open(os.path.join(TEST_DATA_PATH, "fake-index.json")) as f:
self.index = json.load(f)
with open(os.path.join(TEST_DATA_PATH, "fake-editables.json")) as f:
self.editabl... | FakeRepository |
python | getsentry__sentry | src/sentry/monitors/validators.py | {
"start": 22384,
"end": 23138
} | class ____(serializers.Serializer):
status = serializers.ChoiceField(
choices=(
("ok", CheckInStatus.OK),
("error", CheckInStatus.ERROR),
("in_progress", CheckInStatus.IN_PROGRESS),
),
help_text="The status of the job run.",
)
duration = EmptyInteg... | MonitorCheckInValidator |
python | sympy__sympy | sympy/physics/control/lti.py | {
"start": 161725,
"end": 194030
} | class ____(MIMOLinearTimeInvariant):
r"""
A class for representing the MIMO (multiple-input and multiple-output)
generalization of the SISO (single-input and single-output) transfer function.
It is a matrix of transfer functions (``TransferFunction``, SISO-``Series`` or SISO-``Parallel``).
There is... | TransferFunctionMatrix |
python | huggingface__transformers | src/transformers/cli/chat.py | {
"start": 8088,
"end": 24709
} | class ____:
"""Chat with a model from the command line."""
# Defining a class to help with internal state but in practice it's just a method to call
# TODO: refactor into a proper module with helpers + 1 main method
def __init__(
self,
model_id: Annotated[str, typer.Argument(help="ID of... | Chat |
python | huggingface__transformers | tests/models/dab_detr/test_modeling_dab_detr.py | {
"start": 31825,
"end": 35126
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return ConditionalDetrImageProcessor.from_pretrained(CHECKPOINT) if is_vision_available() else None
def test_inference_no_head(self):
model = DabDetrModel.from_pretrained(CHECKPOINT).to(torch_device)
... | DabDetrModelIntegrationTests |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 28089,
"end": 29487
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = AlignTextAttention(config)
self.intermediate = AlignTextIntermediate(config)
self... | AlignTextLayer |
python | cython__cython | Cython/Compiler/ParseTreeTransforms.py | {
"start": 71107,
"end": 75966
} | class ____(VisitorTransform, SkipDeclarations):
# used from within CreateClosureClasses
def __call__(self, node):
from . import Visitor
assert isinstance(node, ExprNodes.GeneratorExpressionNode)
self.gen_node = node
self.args = list(node.def_node.args)
self.call_paramet... | _HandleGeneratorArguments |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_onetimes.py | {
"start": 1826,
"end": 3800
} | class ____(StreamTestCase):
_STREAM_NAME = "onetimes"
@HttpMocker()
def test_state_message_produced_while_read_and_state_match_latest_record(self, http_mocker: HttpMocker) -> None:
min_cursor_value = "2024-01-01T00:00:00+00:00"
max_cursor_value = "2024-02-01T00:00:00+00:00"
http_mo... | TestIncremental |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/operands.py | {
"start": 4642,
"end": 5100
} | class ____(SubsetAutomationCondition):
@property
def name(self) -> str:
return "backfill_in_progress"
async def compute_subset(self, context: AutomationContext) -> EntitySubset: # pyright: ignore[reportIncompatibleMethodOverride]
return await context.asset_graph_view.compute_backfill_in_pr... | BackfillInProgressAutomationCondition |
python | numpy__numpy | benchmarks/benchmarks/bench_trim_zeros.py | {
"start": 166,
"end": 607
} | class ____(Benchmark):
param_names = ["dtype", "size"]
params = [
[_INT, _FLOAT, _COMPLEX, _BOOL],
[3000, 30_000, 300_000]
]
def setup(self, dtype, size):
n = size // 3
self.array = np.hstack([
np.zeros(n),
np.random.uniform(size=n),
n... | TrimZeros |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_code_execution_result_block.py | {
"start": 304,
"end": 499
} | class ____(BaseModel):
content: List[BetaCodeExecutionOutputBlock]
return_code: int
stderr: str
stdout: str
type: Literal["code_execution_result"]
| BetaCodeExecutionResultBlock |
python | pandas-dev__pandas | pandas/core/indexing.py | {
"start": 21940,
"end": 40738
} | class ____(NDFrameIndexerBase):
_valid_types: str
axis: AxisInt | None = None
# sub-classes need to set _takeable
_takeable: bool
@final
def __call__(self, axis: Axis | None = None) -> Self:
# we need to return a copy of ourselves
new_self = type(self)(self.name, self.obj)
... | _LocationIndexer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.