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 | pandas-dev__pandas | pandas/tests/series/methods/test_drop_duplicates.py | {
"start": 2201,
"end": 9468
} | class ____:
@pytest.fixture(
params=["int_", "uint", "float64", "str_", "timedelta64[h]", "datetime64[D]"]
)
def dtype(self, request):
"""
Fixture that provides different data types for testing.
"""
return request.param
@pytest.fixture
def cat_series_unused_c... | TestSeriesDropDuplicates |
python | getsentry__sentry | tests/sentry/api/endpoints/test_api_application_details.py | {
"start": 1352,
"end": 1971
} | class ____(APITestCase):
def test_simple(self) -> None:
app = ApiApplication.objects.create(owner=self.user, name="a")
self.login_as(self.user)
url = reverse("sentry-api-0-api-application-details", args=[app.client_id])
response = self.client.delete(url)
assert response.stat... | ApiApplicationDeleteTest |
python | apache__airflow | task-sdk/src/airflow/sdk/api/client.py | {
"start": 31405,
"end": 35746
} | class ____(httpx.Client):
@lru_cache()
@staticmethod
def _get_ssl_context_cached(ca_file: str, ca_path: str | None = None) -> ssl.SSLContext:
"""Cache SSL context to prevent memory growth from repeated context creation."""
ctx = ssl.create_default_context(cafile=ca_file)
if ca_path:
... | Client |
python | pypa__setuptools | setuptools/tests/test_sdist.py | {
"start": 28720,
"end": 32870
} | class ____:
"""
Can be removed/changed if the project decides to change how it handles symlinks
or external files.
"""
@staticmethod
def files_for_symlink_in_extension_depends(tmp_path, dep_path):
return {
"external": {
"dir": {"file.h": ""},
},
... | TestRegressions |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 34248,
"end": 34456
} | class ____(BoringModel):
def validation_step(self, batch, batch_idx):
if not self.trainer.sanity_checking and batch_idx == 1:
raise RuntimeError("Trouble!")
| TroubledModelInValidationStep |
python | ray-project__ray | python/ray/llm/_internal/serve/config_generator/inputs.py | {
"start": 1430,
"end": 7190
} | class ____(BaseModel):
id: str
hf_token: Optional[str] = None
type: ModelType
import_model_storage_uri: Optional[str] = None
reference_model_id: Optional[str] = None
def _get_user_input_from_lists(
prompt: str, options: List[str], allow_any_user_input: bool
):
while True:
res = Pro... | BaseModelInfo |
python | sphinx-doc__sphinx | tests/roots/test-api-set-translator/conf.py | {
"start": 1002,
"end": 1679
} | class ____(XMLTranslator):
pass
def setup(app):
app.set_translator('html', ConfHTMLTranslator)
app.set_translator('dirhtml', ConfDirHTMLTranslator)
app.set_translator('singlehtml', ConfSingleHTMLTranslator)
app.set_translator('pickle', ConfPickleTranslator)
app.set_translator('json', ConfJsonT... | ConfPseudoXMLTranslator |
python | psf__requests | src/requests/models.py | {
"start": 2127,
"end": 6052
} | class ____:
@property
def path_url(self):
"""Build the path URL to use."""
url = []
p = urlsplit(self.url)
path = p.path
if not path:
path = "/"
url.append(path)
query = p.query
if query:
url.append("?")
url... | RequestEncodingMixin |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 214523,
"end": 215524
} | class ____(TestCase):
def test_basic(self):
for i, iterable, expected_min, expected_max in (
(1, [10, 2, 20, 5, 17, 4], 1, 2),
(2, [10, -2, -20, 5, 17, 4], 2, 4),
(3, [10, 10, 20, 10], 0, 2),
(4, [30, 30, 20, 30], 2, 0),
):
with self.subTes... | ArgMinArgMaxTests |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-raptor/llama_index/packs/raptor/base.py | {
"start": 3134,
"end": 12243
} | class ____(BaseRetriever):
"""Raptor indexing retriever."""
def __init__(
self,
documents: List[BaseNode],
tree_depth: int = 3,
similarity_top_k: int = 2,
llm: Optional[LLM] = None,
embed_model: Optional[BaseEmbedding] = None,
vector_store: Optional[BaseP... | RaptorRetriever |
python | django__django | django/db/utils.py | {
"start": 619,
"end": 662
} | class ____(DatabaseError):
pass
| DataError |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/_error_z.py | {
"start": 233,
"end": 14397
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d"
_path_str = "scatter3d.error_z"
_valid_props = {
"array",
"arrayminus",
"arrayminussrc",
"arraysrc",
"color",
"symmetric",
"thickness",
"traceref",
"tracerefminus",
... | ErrorZ |
python | hyperopt__hyperopt | hyperopt/tests/unit/test_fmin.py | {
"start": 3671,
"end": 5816
} | class ____(unittest.TestCase):
class SomeError(Exception):
# XXX also test domain.exceptions mechanism that actually catches this
pass
def eval_fn(self, space):
raise TestFmin.SomeError()
def setUp(self):
self.trials = Trials()
def test_catch_eval_exceptions_True(self)... | TestFmin |
python | readthedocs__readthedocs.org | readthedocs/core/middleware.py | {
"start": 1676,
"end": 3180
} | class ____:
"""
Middleware to update the CSP headers for specific views given its URL name.
This is useful for views that we don't have much control over,
like views from third-party packages. For views that we have control over,
we should update the CSP headers directly in the view.
Use the `... | UpdateCSPMiddleware |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/databricks.py | {
"start": 837,
"end": 1649
} | class ____(DataSourceTestConfig):
@property
@override
def label(self) -> str:
return "databricks"
@property
@override
def pytest_mark(self) -> pytest.MarkDecorator:
return pytest.mark.databricks
@override
def create_batch_setup(
self,
request: pytest.Fix... | DatabricksDatasourceTestConfig |
python | joke2k__faker | faker/providers/bank/de_CH/__init__.py | {
"start": 42,
"end": 191
} | class ____(BankProvider):
"""Implement bank provider for ``de_CH`` locale."""
bban_format = "#################"
country_code = "CH"
| Provider |
python | Netflix__metaflow | metaflow/plugins/env_escape/override_decorators.py | {
"start": 2992,
"end": 3605
} | class ____(object):
def __init__(self, class_path, serializer):
self._class_path = class_path
self._serializer = serializer
@property
def class_path(self):
return self._class_path
@property
def serializer(self):
return self._serializer
def local_exception_deserial... | RemoteExceptionSerializer |
python | allegroai__clearml | clearml/backend_api/services/v2_20/models.py | {
"start": 49361,
"end": 51030
} | class ____(Request):
"""
Delete metadata from model
:param model: ID of the model
:type model: str
:param keys: The list of metadata keys to delete
:type keys: Sequence[str]
"""
_service = "models"
_action = "delete_metadata"
_version = "2.20"
_schema = {
"definitio... | DeleteMetadataRequest |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/fault_tolerance_test_base.py | {
"start": 4634,
"end": 25595
} | class ____(object): # pylint: disable=missing-docstring
def setUp(self, num_workers, num_ps, use_cs=False):
super(BaseFaultToleranceTest, self).setUp()
self._cluster = multi_worker_test_base.create_multi_process_cluster(
num_workers=num_workers,
num_ps=num_ps,
rpc_layer="grpc",
... | BaseFaultToleranceTest |
python | aimacode__aima-python | utils.py | {
"start": 21732,
"end": 21937
} | class ____(int):
"""Just like `bool`, except values display as 'T' and 'F' instead of 'True' and 'False'."""
__str__ = __repr__ = lambda self: 'T' if self else 'F'
T = Bool(True)
F = Bool(False)
| Bool |
python | catalyst-team__catalyst | catalyst/contrib/data/dataset.py | {
"start": 2845,
"end": 4149
} | class ____(Dataset):
"""General purpose dataset class to use with `numpy_data`."""
def __init__(
self,
numpy_data: np.ndarray,
numpy_key: str = "features",
dict_transform: Optional[Callable] = None,
):
"""
General purpose dataset class to use with `numpy_data... | NumpyDataset |
python | astropy__astropy | astropy/cosmology/_src/tests/io/base.py | {
"start": 1873,
"end": 2913
} | class ____(IOTestBase):
"""Tests for a Cosmology[Read/Write].
This class will not be directly called by :mod:`pytest` since its name does
not begin with ``Test``. To activate the contained tests this class must
be inherited in a subclass. Subclasses must define a :func:`pytest.fixture`
``cosmo`` th... | ReadWriteTestMixinBase |
python | astropy__astropy | astropy/modeling/functional_models.py | {
"start": 113674,
"end": 117901
} | class ____(Fittable1DModel):
"""
Projected (surface density) analytic King Model.
Parameters
----------
amplitude : float
Amplitude or scaling factor.
r_core : float
Core radius (f(r_c) ~ 0.5 f_0)
r_tide : float
Tidal radius.
Notes
-----
This model app... | KingProjectedAnalytic1D |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/relationship.py | {
"start": 2671,
"end": 3233
} | class ____(Base):
"""test for #9150"""
__tablename__ = "MyTable"
idx: Mapped[int] = mapped_column(Integer, primary_key=True)
mytable_id: Mapped[int] = mapped_column(ForeignKey("MyTable.idx"))
not_anno = mapped_column(Integer)
selfref_1: Mapped[Optional[SelfReferential]] = relationship(
... | SelfReferential |
python | apache__airflow | providers/apache/hive/src/airflow/providers/apache/hive/transfers/mssql_to_hive.py | {
"start": 1309,
"end": 5791
} | class ____(BaseOperator):
"""
Moves data from Microsoft SQL Server to Hive.
The operator runs your query against Microsoft SQL Server, stores
the file locally before loading it into a Hive table. If the
``create`` or ``recreate`` arguments are set to ``True``, a
``CREATE TABLE`` and ``DROP TABL... | MsSqlToHiveOperator |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/api.py | {
"start": 2630,
"end": 2753
} | class ____:
Consoles = 'tabs_consoles_section'
Edit = 'tabs_edit_section'
| IPythonConsoleWidgetTabsContextMenuSections |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_iter.py | {
"start": 2326,
"end": 2605
} | class ____:
def __init__(self, n):
self.n = n
self.i = 0
def __next__(self):
res = self.i
if res >= self.n:
raise StopIteration
self.i = res + 1
return res
def __iter__(self):
return self
| BasicIterClass |
python | huggingface__transformers | src/transformers/models/patchtst/modeling_patchtst.py | {
"start": 35122,
"end": 35777
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
MSE loss.
regression_outputs (`torch.FloatTensor` of shape `(batch_size, num_targets)`):
Regression outputs of the time series modeling heads.
"""
loss: Optional... | PatchTSTForRegressionOutput |
python | PyCQA__pylint | pylint/reporters/base_reporter.py | {
"start": 575,
"end": 3087
} | class ____:
"""Base class for reporters.
symbols: show short symbolic names for messages.
"""
extension = ""
name = "base"
"""Name of the reporter."""
def __init__(self, output: TextIO | None = None) -> None:
self.linter: PyLinter
self.section = 0
self.out: TextIO... | BaseReporter |
python | streamlit__streamlit | lib/tests/streamlit/commands/page_config_test.py | {
"start": 1151,
"end": 7737
} | class ____(DeltaGeneratorTestCase):
def test_set_page_config_title(self):
st.set_page_config(page_title="Hello")
c = self.get_message_from_queue().page_config_changed
assert c.title == "Hello"
@parameterized.expand([":shark:", "https://foo.com/image.png"])
def test_set_page_config_i... | PageConfigTest |
python | pypa__pip | tests/unit/test_locations.py | {
"start": 525,
"end": 3261
} | class ____:
def setup_method(self) -> None:
self.tempdir = tempfile.mkdtemp()
self.st_uid = 9999
self.username = "example"
self.patch()
def teardown_method(self) -> None:
self.revert_patch()
shutil.rmtree(self.tempdir, ignore_errors=True)
def patch(self) -> ... | TestLocations |
python | chardet__chardet | chardet/macromanprober.py | {
"start": 4377,
"end": 6077
} | class ____(CharSetProber):
def __init__(self) -> None:
super().__init__()
self._last_char_class = OTH
self._freq_counter: List[int] = []
self.reset()
def reset(self) -> None:
self._last_char_class = OTH
self._freq_counter = [0] * FREQ_CAT_NUM
# express t... | MacRomanProber |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/forms.py | {
"start": 6509,
"end": 6718
} | class ____(ReprForm):
def __init__(self, subfield_count=12, **kwargs):
super().__init__(**kwargs)
self.fields["mv_field"] = MultiBooleanField(subfield_count=subfield_count)
| ManyMultiValueForm |
python | dask__distributed | distributed/tests/test_core.py | {
"start": 1271,
"end": 4348
} | class ____:
"""
A class which counts the number of live instances.
"""
n_instances = 0
# Use __new__, as __init__ can be bypassed by pickle.
def __new__(cls):
cls.n_instances += 1
obj = object.__new__(cls)
weakref.finalize(obj, cls._finalize)
return obj
@cl... | CountedObject |
python | fastai__fastai | fastai/optimizer.py | {
"start": 15942,
"end": 19160
} | class ____(Optimizer, GetAttr):
"Wrap `opt` in a lookahead optimizer"
_default='opt'
def __init__(self,
opt:Optimizer, # `Optimizer` to wrap with Lookahead
k:int=6, # How often to conduct Lookahead step
alpha:float=0.5, # Slow weight moving average coefficient
):
store_a... | Lookahead |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 7451,
"end": 7597
} | class ____(ASTBase):
pass
# Primary expressions
################################################################################
| ASTExpression |
python | huggingface__transformers | src/transformers/models/gemma2/modeling_gemma2.py | {
"start": 20794,
"end": 24037
} | class ____(Gemma2PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = Gemma2... | Gemma2ForCausalLM |
python | doocs__leetcode | solution/2200-2299/2216.Minimum Deletions to Make Array Beautiful/Solution.py | {
"start": 0,
"end": 310
} | class ____:
def minDeletion(self, nums: List[int]) -> int:
n = len(nums)
i = ans = 0
while i < n - 1:
if nums[i] == nums[i + 1]:
ans += 1
i += 1
else:
i += 2
ans += (n - ans) % 2
return ans
| Solution |
python | pydantic__pydantic | tests/benchmarks/shared.py | {
"start": 4798,
"end": 5035
} | class ____(BaseModel):
model_config = {'defer_build': True}
def rebuild_model(model: type[BaseModel], raise_errors: bool = True) -> None:
model.model_rebuild(force=True, _types_namespace={}, raise_errors=raise_errors)
| DeferredModel |
python | jazzband__prettytable | tests/test_style.py | {
"start": 229,
"end": 6648
} | class ____:
"""Verify different cases for positional-junction characters"""
def test_default(self, city_data: PrettyTable) -> None:
city_data.set_style(TableStyle.DOUBLE_BORDER)
assert (
city_data.get_string().strip()
== """
╔═══════════╦══════╦════════════╦════════════... | TestPositionalJunctions |
python | Farama-Foundation__Gymnasium | gymnasium/vector/vector_env.py | {
"start": 22857,
"end": 23645
} | class ____(VectorWrapper):
"""Wraps the vectorized environment to allow a modular transformation of the actions.
Equivalent of :class:`gymnasium.ActionWrapper` for vectorized environments.
"""
def step(
self, actions: ActType
) -> tuple[ObsType, ArrayType, ArrayType, ArrayType, dict[str, A... | VectorActionWrapper |
python | protocolbuffers__protobuf | python/protobuf_distutils/protobuf_distutils/generate_py_protobufs.py | {
"start": 512,
"end": 4714
} | class ____(Command):
"""Generates Python sources for .proto files."""
description = 'Generate Python sources for .proto files'
user_options = [
('extra-proto-paths=', None,
'Additional paths to resolve imports in .proto files.'),
('protoc=', None,
'Path to a specific `protoc` c... | generate_py_protobufs |
python | gabrielfalcao__HTTPretty | tests/functional/test_fakesocket.py | {
"start": 1271,
"end": 2540
} | class ____(socket.socket):
"""
Just an editable socket factory
It allows mock to patch readonly functions
"""
connect = sendall = lambda *args, **kw: None
fake_socket_interupter_flag = {}
def recv(flag, size):
"""
Two pass recv implementation
This implementation will for the first t... | FakeSocket |
python | langchain-ai__langchain | libs/core/langchain_core/output_parsers/list.py | {
"start": 945,
"end": 4058
} | class ____(BaseTransformOutputParser[list[str]]):
"""Parse the output of a model to a list."""
@property
def _type(self) -> str:
return "list"
@abstractmethod
def parse(self, text: str) -> list[str]:
"""Parse the output of an LLM call.
Args:
text: The output of... | ListOutputParser |
python | xlwings__xlwings | xlwings/pro/_xlremote.py | {
"start": 34547,
"end": 37548
} | class ____(base_classes.Table):
@property
def show_autofilter(self):
return self.api["show_autofilter"]
@show_autofilter.setter
def show_autofilter(self, value):
self.append_json_action(
func="showAutofilterTable", args=[self.index - 1, value]
)
def __init__(sel... | Table |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/workspace.py | {
"start": 1210,
"end": 5149
} | class ____(IHaveNew, LegacyNamedTupleMixin):
image: Optional[str]
python_file: Optional[str]
package_name: Optional[str]
module_name: Optional[str]
working_directory: Optional[str]
executable_path: Optional[str]
attribute: Optional[str]
git_metadata: Optional[GitMetadata]
container_c... | CodeLocationDeployData |
python | sympy__sympy | sympy/stats/random_matrix_models.py | {
"start": 9682,
"end": 9846
} | class ____(CircularEnsembleModel):
def joint_eigen_distribution(self):
return self._compute_joint_eigen_distribution(S.One)
| CircularOrthogonalEnsembleModel |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-everlyai/llama_index/llms/everlyai/base.py | {
"start": 635,
"end": 2880
} | class ____(OpenAI):
"""
EverlyAI LLM.
Examples:
`pip install llama-index-llms-everlyai`
```python
from llama_index.llms.everlyai import EverlyAI
llm = EverlyAI(api_key="your-api-key")
response = llm.complete("Hello World!")
print(response)
```
... | EverlyAI |
python | django__django | tests/staticfiles_tests/test_storage.py | {
"start": 25106,
"end": 26022
} | class ____(CollectionTestCase):
run_collectstatic_in_setUp = False
hashed_file_path = hashed_file_path
def test_protocol_relative_url_ignored(self):
with override_settings(
STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "static_url_slash")],
STATICFILES_FINDERS=["djang... | TestCollectionManifestStorageStaticUrlSlash |
python | pandas-dev__pandas | asv_bench/benchmarks/index_object.py | {
"start": 1408,
"end": 1709
} | class ____:
def setup(self):
N = 10**5
B = N + 20000
self.datetime_left = DatetimeIndex(range(N))
self.datetime_right = DatetimeIndex(range(N, B))
def time_datetime_difference_disjoint(self):
self.datetime_left.difference(self.datetime_right)
| SetDisjoint |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 210894,
"end": 213456
} | class ____(ParseElementEnhance):
"""Helper to define a delimited list of expressions - the delimiter
defaults to ','. By default, the list elements and delimiters can
have intervening whitespace, and comments, but this can be
overridden by passing ``combine=True`` in the constructor. If
``combine`` ... | DelimitedList |
python | django__django | tests/admin_ordering/models.py | {
"start": 698,
"end": 889
} | class ____(admin.ModelAdmin):
def get_ordering(self, request):
if request.user.is_superuser:
return ["rank"]
else:
return ["name"]
| DynOrderingBandAdmin |
python | kamyu104__LeetCode-Solutions | Python/minimum-knight-moves.py | {
"start": 1806,
"end": 2403
} | class ____(object):
def __init__(self):
self.__lookup = {(0, 0):0, (1, 1):2, (1, 0):3} # special cases
def minKnightMoves(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
def dp(x, y):
x, y = abs(x), abs(y)
if x < y:
... | Solution2 |
python | keras-team__keras | keras/src/ops/linalg_test.py | {
"start": 21097,
"end": 24762
} | class ____(testing.TestCase):
def test_qr_init_mode_reduced(self):
qr_op = linalg.Qr(mode="reduced")
self.assertIsNotNone(qr_op)
def test_qr_init_mode_complete(self):
qr_op = linalg.Qr(mode="complete")
self.assertIsNotNone(qr_op)
def test_qr_init_invalid_mode(self):
... | QrOpTest |
python | getsentry__sentry-python | sentry_sdk/crons/consts.py | {
"start": 0,
"end": 87
} | class ____:
IN_PROGRESS = "in_progress"
OK = "ok"
ERROR = "error"
| MonitorStatus |
python | Textualize__textual | tests/text_area/test_setting_themes.py | {
"start": 205,
"end": 1561
} | class ____(App[None]):
def compose(self) -> ComposeResult:
yield TextArea("print('hello')", language="python")
async def test_default_theme():
app = TextAreaApp()
async with app.run_test():
text_area = app.query_one(TextArea)
assert text_area.theme is "css"
async def test_settin... | TextAreaApp |
python | tiangolo__fastapi | scripts/sponsors.py | {
"start": 1396,
"end": 1460
} | class ____(BaseModel):
user: SponsorsUser
| SponsorsResponseData |
python | astropy__astropy | astropy/table/tests/test_masked.py | {
"start": 14656,
"end": 15111
} | class ____:
def test_rename_masked_column(self):
t = Table(masked=True)
t.add_column(MaskedColumn(name="a", data=[1, 2, 3], mask=[0, 1, 0]))
t["a"].fill_value = 42
t.rename_column("a", "b")
assert t.masked
assert np.all(t["b"] == np.array([1, 2, 3]))
assert np... | TestRenameColumn |
python | pytorch__pytorch | torch/nn/modules/pooling.py | {
"start": 12460,
"end": 12618
} | class ____(Module):
def extra_repr(self) -> str:
return f"kernel_size={self.kernel_size}, stride={self.stride}, padding={self.padding}"
| _MaxUnpoolNd |
python | pytorch__pytorch | torch/_subclasses/functional_tensor.py | {
"start": 14285,
"end": 31991
} | class ____(TorchDispatchMode):
def __init__(self, pre_dispatch=False, export=False, _allow_token_discovery=False):
super().__init__()
self.export = export
self.is_on_stack = False
self.enter_stack = []
# Indicates to our torch_dispatch dispatching infra that
# this is... | FunctionalTensorMode |
python | PyCQA__pylint | tests/pyreverse/functional/class_diagrams/attributes/duplicates_9267.py | {
"start": 123,
"end": 260
} | class ____:
def __init__(self) -> None:
self.a_obj = A()
def func(self):
self.a_obj = A()
self.a_obj = A()
| B |
python | django-extensions__django-extensions | django_extensions/mongodb/fields/__init__.py | {
"start": 434,
"end": 1022
} | class ____(StringField):
description = _("String (up to %(max_length)s)")
def __init__(self, *args, **kwargs):
kwargs["max_length"] = kwargs.get("max_length", 50)
# Set db_index=True unless it's been set manually.
if "db_index" not in kwargs:
kwargs["db_index"] = True
... | SlugField |
python | sympy__sympy | sympy/polys/agca/modules.py | {
"start": 42821,
"end": 47240
} | class ____(Module):
"""
Class for quotient modules.
Do not instantiate this directly. For subquotients, see the
SubQuotientModule class.
Attributes:
- base - the base module we are a quotient of
- killed_module - the submodule used to form the quotient
- rank of the base
"""
... | QuotientModule |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/inset_locator.py | {
"start": 6311,
"end": 17874
} | class ____(BboxConnector):
@_docstring.interpd
def __init__(self, bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, **kwargs):
"""
Connect two bboxes with a quadrilateral.
The quadrilateral is specified by two lines that start and end at
corners of the bboxes. The four sides of the quad... | BboxConnectorPatch |
python | doocs__leetcode | solution/1300-1399/1312.Minimum Insertion Steps to Make a String Palindrome/Solution.py | {
"start": 0,
"end": 325
} | class ____:
def minInsertions(self, s: str) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= j:
return 0
if s[i] == s[j]:
return dfs(i + 1, j - 1)
return 1 + min(dfs(i + 1, j), dfs(i, j - 1))
return dfs(0, len(s) - 1)... | Solution |
python | simonw__datasette | tests/test_api.py | {
"start": 41798,
"end": 41960
} | class ____:
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
return other == self.a or other == self.b
| Either |
python | readthedocs__readthedocs.org | readthedocs/api/v3/tests/test_remoterepositories.py | {
"start": 422,
"end": 3899
} | class ____(APIEndpointMixin):
def setUp(self):
super().setUp()
self.remote_organization = fixture.get(
RemoteOrganization,
created=self.created,
modified=self.modified,
avatar_url="https://avatars.githubusercontent.com/u/366329?v=4",
name=... | RemoteRepositoryEndpointTests |
python | matplotlib__matplotlib | lib/matplotlib/container.py | {
"start": 6919,
"end": 8132
} | class ____(Container):
"""
Container for the artists created in a :meth:`.Axes.stem` plot.
The container can be treated like a namedtuple ``(markerline, stemlines,
baseline)``.
Attributes
----------
markerline : `~matplotlib.lines.Line2D`
The artist of the markers at the stem heads... | StemContainer |
python | joke2k__faker | faker/providers/job/fa_IR/__init__.py | {
"start": 42,
"end": 1821
} | class ____(BaseProvider):
jobs = [
"هنرپیشه",
"ناخدا",
"بخشدار",
"خیاط",
"گلهدار",
"باغدار",
"مؤذن",
"ساربان",
"آشپز",
"دندانپزشک",
"نجار",
"چوپان",
"خانهدار",
"شورا",
"نویسنده",
"گار... | Provider |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_integrations.py | {
"start": 6198,
"end": 7626
} | class ____(TestCase):
def test_subclass_is_replaced_on_get(self):
project = fixture.get(Project, main_language_project=None)
integration = Integration.objects.create(
project=project,
integration_type=Integration.GITHUB_WEBHOOK,
)
integration = Integration.obj... | IntegrationModelTests |
python | walkccc__LeetCode | solutions/1464. Maximum Product of Two Elements in an Array/1464.py | {
"start": 0,
"end": 242
} | class ____:
def maxProduct(self, nums: list[int]) -> int:
max1 = 0
max2 = 0
for num in nums:
if num > max1:
max2, max1 = max1, num
elif num > max2:
max2 = num
return (max1 - 1) * (max2 - 1)
| Solution |
python | PrefectHQ__prefect | src/prefect/client/orchestration/_artifacts/client.py | {
"start": 4912,
"end": 8414
} | class ____(BaseAsyncClient):
async def create_artifact(self, artifact: "ArtifactCreate") -> "Artifact":
response = await self.request(
"POST",
"/artifacts/",
json=artifact.model_dump(mode="json", exclude_unset=True),
)
from prefect.client.schemas.objects i... | ArtifactAsyncClient |
python | huggingface__transformers | src/transformers/models/janus/modular_janus.py | {
"start": 24722,
"end": 24796
} | class ____(ChameleonVQVAEEncoderResnetBlock):
pass
| JanusVQVAEResnetBlock |
python | joke2k__faker | faker/providers/person/en_IE/__init__.py | {
"start": 267,
"end": 58684
} | class ____(PersonProvider):
formats = (
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}-{{last_name}}",
"{{first_name_female}} {{last... | Provider |
python | ray-project__ray | python/ray/serve/_private/usage.py | {
"start": 130,
"end": 2580
} | class ____(Enum):
API_VERSION = TagKey.SERVE_API_VERSION
NUM_DEPLOYMENTS = TagKey.SERVE_NUM_DEPLOYMENTS
GCS_STORAGE = TagKey.GCS_STORAGE
NUM_GPU_DEPLOYMENTS = TagKey.SERVE_NUM_GPU_DEPLOYMENTS
FASTAPI_USED = TagKey.SERVE_FASTAPI_USED
DAG_DRIVER_USED = TagKey.SERVE_DAG_DRIVER_USED
HTTP_ADAPTER... | ServeUsageTag |
python | tensorflow__tensorflow | tensorflow/python/distribute/integration_test/mwms_peer_failure_test.py | {
"start": 1955,
"end": 5682
} | class ____(test.TestCase):
# Note that all the tests use auto_restart=True. Currently we rely on the
# assumption that an external system restarts failed tasks. If the assumption
# is not true, the remaining tasks may still hang instead of fail.
#
# In these tests we leverage the auto restart feature of Multi... | PeerFailureTest |
python | mlflow__mlflow | tests/dev/test_remove_experimental_decorators.py | {
"start": 1743,
"end": 2131
} | class ____:
@experimental(version="1.2.0")
def method(self):
pass
def regular_func():
pass
""")
output = subprocess.check_output([sys.executable, SCRIPT_PATH, test_file], text=True)
assert output.count("Removed") == 3 # Should remove all 3 decorators
content = test_file.read_text()
... | MyClass |
python | geekcomputers__Python | Checker_game_by_dz/modules/checker_board.py | {
"start": 128,
"end": 5492
} | class ____:
def __init__(self):
self.board = []
self.selected = None
self.black_l = self.white_l = 12
self.black_k = self.white_k = 0
self.create_board()
# to design the board
def draw_cubes(self, window):
window.fill(green)
for row in range(rows):
... | checker_board |
python | pyqtgraph__pyqtgraph | pyqtgraph/exporters/HDF5Exporter.py | {
"start": 293,
"end": 2570
} | class ____(Exporter):
Name = "HDF5 Export: plot (x,y)"
windows = []
allowCopy = False
def __init__(self, item):
Exporter.__init__(self, item)
self.params = Parameter.create(name='params', type='group', children=[
{'name': 'Name', 'title': translate("Exporter", 'Name'), 'type... | HDF5Exporter |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/loop18.py | {
"start": 203,
"end": 542
} | class ____: ...
def foo(v: A | B | None) -> Generator[A, None, None]:
reveal_type(v)
if not isinstance(v, B):
reveal_type(v, expected_text="A | None")
while v is not None:
reveal_type(v, expected_text="A")
yield v
v = v.parent
reveal_type(v, expe... | B |
python | viewflow__viewflow | viewflow/workflow/flow/nodes.py | {
"start": 1974,
"end": 2499
} | class ____(
mixins.NodeDetailMixin, mixins.NodeUndoMixin, mixins.NodeReviveMixin, nodes.End
):
"""
The ``End`` node in a flow.
This node serves as the terminal point of a flow
.. code-block:: python
class MyFlow(flow.Flow):
...
approved = this.End()
re... | End |
python | walkccc__LeetCode | solutions/2229. Check if an Array Is Consecutive/2229.py | {
"start": 0,
"end": 136
} | class ____:
def isConsecutive(self, nums: list[int]) -> bool:
return max(nums) - min(nums) + 1 == len(set(nums)) == len(nums)
| Solution |
python | gawel__pyquery | tests/test_pyquery.py | {
"start": 13541,
"end": 21867
} | class ____(TestCase):
html = '''
<div class="portlet">
<a href="/toto">Test<img src ="myimage" />My link text</a>
<a href="/toto2"><img src ="myimage2" />My link text 2</a>
</div>
'''
html2 = '''
<input name="spam" value="Spam">
<input name="eggs" value="Eggs">
<... | TestManipulating |
python | matplotlib__matplotlib | lib/matplotlib/ticker.py | {
"start": 108962,
"end": 111358
} | class ____(Locator):
"""
Place evenly spaced minor ticks, with the step size and maximum number of ticks
chosen automatically.
The Axis must use a linear scale and have evenly spaced major ticks.
"""
def __init__(self, n=None):
"""
Parameters
----------
n : int ... | AutoMinorLocator |
python | doocs__leetcode | solution/2400-2499/2411.Smallest Subarrays With Maximum Bitwise OR/Solution.py | {
"start": 0,
"end": 422
} | class ____:
def smallestSubarrays(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [1] * n
f = [-1] * 32
for i in range(n - 1, -1, -1):
t = 1
for j in range(32):
if (nums[i] >> j) & 1:
f[j] = i
elif f... | Solution |
python | ansible__ansible | lib/ansible/module_utils/_internal/_messages.py | {
"start": 2120,
"end": 2929
} | class ____(_datatag.AnsibleSerializableDataclass):
"""Base class for an error/warning/deprecation event with optional chain (from an exception __cause__ chain) and an optional traceback."""
_validation_auto_enabled = False
def __post_init__(self): ... # required for deferred dataclass validation
msg... | Event |
python | wandb__wandb | wandb/sync/sync.py | {
"start": 1036,
"end": 12499
} | class ____(threading.Thread):
def __init__(
self,
sync_list,
project=None,
entity=None,
run_id=None,
job_type=None,
view=None,
verbose=None,
mark_synced=None,
app_url=None,
sync_tensorboard=None,
log_path=None,
a... | SyncThread |
python | google__flatbuffers | python/flatbuffers/reflection/RPCCall.py | {
"start": 179,
"end": 5074
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = RPCCall()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsRPCCall(cls, buf, offset=0):
... | RPCCall |
python | pyodide__pyodide | src/py/pyodide/http/_pyfetch.py | {
"start": 2174,
"end": 12105
} | class ____:
"""A wrapper for a Javascript fetch :js:data:`Response`.
Parameters
----------
url
URL that was fetched
js_response
A :py:class:`~pyodide.ffi.JsProxy` of the fetch :js:class:`Response`.
abort_controller
The abort controller that may be used to cancel the fetc... | FetchResponse |
python | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 61376,
"end": 65513
} | class ____(ClapPreTrainedModel):
config: ClapTextConfig
input_modalities = ("text",)
def __init__(self, config, add_pooling_layer=True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config)
... | ClapTextModel |
python | keras-team__keras | keras/src/metrics/hinge_metrics.py | {
"start": 279,
"end": 1293
} | class ____(reduction_metrics.MeanMetricWrapper):
"""Computes the hinge metric between `y_true` and `y_pred`.
`y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are
provided we will convert them to -1 or 1.
Args:
name: (Optional) string name of the metric instance.
dt... | Hinge |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE807.py | {
"start": 11,
"end": 159
} | class ____:
foo: List[str] = field(default_factory=lambda: []) # PIE807
bar: Dict[str, int] = field(default_factory=lambda: {}) # PIE807
| Foo |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 93184,
"end": 97597
} | class ____(_AutoModelForVision2Seq):
@classmethod
def from_config(cls, config, **kwargs):
warnings.warn(
"The class `AutoModelForVision2Seq` is deprecated and will be removed in v5.0. Please use "
"`AutoModelForImageTextToText` instead.",
FutureWarning,
)
... | AutoModelForVision2Seq |
python | walkccc__LeetCode | solutions/3336. Find the Number of Subsequences With Equal GCD/3336-3.py | {
"start": 0,
"end": 967
} | class ____:
def subsequencePairCount(self, nums: list[int]) -> int:
MOD = 1_000_000_007
maxNum = max(nums)
# dp[x][y] := number of disjoint pairs `seq1` and `seq2` of
# nums so far, where GCD(seq1) == x and GCD(seq2) == y
dp = [[0] * (maxNum + 1) for _ in range(maxNum + 1)]
dp[0][0] = 1
f... | Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/helpers/execution/run_steps.py | {
"start": 740,
"end": 2340
} | class ____(Exception):
pass
def _get_dependency_graph(steps: STEP_TREE) -> Dict[str, List[str]]:
"""
Get the dependency graph of a step tree.
"""
dependency_graph: Dict[str, List[str]] = {}
for step in steps:
if isinstance(step, StepToRun):
dependency_graph[step.id] = step.... | InvalidStepConfiguration |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 96389,
"end": 97393
} | class ____(Response):
"""
Response of events.get_scalar_metrics_and_variants endpoint.
:param metrics:
:type metrics: dict
"""
_service = "events"
_action = "get_scalar_metrics_and_variants"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {"metrics": ... | GetScalarMetricsAndVariantsResponse |
python | Textualize__textual | docs/examples/how-to/containers01.py | {
"start": 272,
"end": 567
} | class ____(App):
"""Simple app to play with containers."""
def compose(self) -> ComposeResult:
with Horizontal(): # (1)!
yield Box() # (2)!
yield Box()
yield Box()
if __name__ == "__main__":
app = ContainerApp()
app.run()
| ContainerApp |
python | lepture__authlib | authlib/oauth1/rfc5849/errors.py | {
"start": 1010,
"end": 1082
} | class ____(OAuth1Error):
error = "invalid_request"
| InvalidRequestError |
python | ray-project__ray | python/ray/llm/tests/serve/gpu/integration/test_openai_compatibility_no_accelerator_type.py | {
"start": 28,
"end": 1733
} | class ____:
"""Test that rayllm is compatible with OpenAI API without specifying accelerator_type"""
def test_models_no_accelerator_type(
self, testing_model_no_accelerator
): # noqa: F811
"""Check model listing without accelerator_type"""
client, model = testing_model_no_accelerat... | TestOpenAICompatibilityNoAcceleratorType |
python | jazzband__django-pipeline | tests/tests/test_compiler.py | {
"start": 4691,
"end": 5516
} | class ____(TestCase):
def setUp(self):
default_collector.collect()
self.compiler = Compiler()
def test_output_path(self):
compiler_class = self.compiler.compilers[0]
compiler = compiler_class(
verbose=self.compiler.verbose,
storage=self.compiler.storage,
... | CompilerSelfWriterTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.