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
Netflix__metaflow
metaflow/_vendor/importlib_metadata/__init__.py
{ "start": 19872, "end": 21335 }
class ____(MetaPathFinder): """ A MetaPathFinder capable of discovering installed distributions. """ class Context: """ Keyword arguments presented by the caller to ``distributions()`` or ``Distribution.discover()`` to narrow the scope of a search for distributions ...
DistributionFinder
python
pytorch__pytorch
torch/_inductor/fx_passes/group_batch_fusion.py
{ "start": 49678, "end": 49892 }
class ____(BatchPointwiseMathOpsPostGradFusion): def __init__(self, **kwargs) -> None: super().__init__(aten.add.Tensor, **kwargs) @register_fusion("batch_aten_sub", pre_grad=False)
BatchAddPostGradFusion
python
tqdm__tqdm
tqdm/std.py
{ "start": 1412, "end": 1533 }
class ____(TqdmWarning, FutureWarning): """beta feature, unstable API and behaviour""" pass
TqdmExperimentalWarning
python
patrick-kidger__equinox
equinox/nn/_sequential.py
{ "start": 3794, "end": 5061 }
class ____(Module): """Wraps a callable (e.g. an activation function) for use with [`equinox.nn.Sequential`][]. Precisely, this just adds an extra `key` argument (that is ignored). Given some function `fn`, then `Lambda` is essentially a convenience for `lambda x, key: f(x)`. `fn` is treated as a ...
Lambda
python
neetcode-gh__leetcode
python/1481-least-number-of-unique-integers-after-k-removals.py
{ "start": 388, "end": 923 }
class ____: def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int: freq = Counter(arr) freqList = [0] * (len(arr) + 1) for n, f in freq.items(): freqList[f] += 1 res = len(freq) for f in range(1, len(freqList)): remove = freqList[f] ...
Solution
python
spyder-ide__spyder
spyder/plugins/statusbar/widgets/status.py
{ "start": 752, "end": 1115 }
class ____(BaseTimerStatus): """Status bar widget for system cpu usage.""" ID = 'cpu_status' def get_value(self): """Return CPU usage.""" text = '%d%%' % psutil.cpu_percent(interval=0) return 'CPU ' + text.rjust(3) def get_tooltip(self): """Return the widget tooltip tex...
CPUStatus
python
bokeh__bokeh
src/bokeh/sphinxext/_internal/bokeh_options.py
{ "start": 2121, "end": 4329 }
class ____(BokehDirective): has_content = True required_arguments = 1 optional_arguments = 1 option_spec = {"module": unchanged} def run(self): sig = " ".join(self.arguments) m = py_sig_re.match(sig) if m is None: raise SphinxError(f"Unable to parse signature f...
BokehOptionsDirective
python
django__django
tests/m2m_through/models.py
{ "start": 257, "end": 717 }
class ____(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through="Membership") custom_members = models.ManyToManyField( Person, through="CustomMembership", related_name="custom" ) nodefaultsnonulls = models.ManyToManyField( Person, ...
Group
python
astropy__astropy
astropy/cosmology/_src/tests/io/test_cosmology.py
{ "start": 305, "end": 2092 }
class ____(ToFromTestMixinBase): """ Tests for a Cosmology[To/From]Format with ``format="astropy.cosmology"``. 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 m...
ToFromCosmologyTestMixin
python
dask__distributed
distributed/pytest_resourceleaks.py
{ "start": 7082, "end": 8723 }
class ____(ResourceChecker, name="processes"): def measure(self) -> set[ChildProcess]: children = set() p = psutil.Process() for c in p.children(recursive=True): try: with c.oneshot(): if ( c.ppid() == p.pid ...
ChildProcessesChecker
python
pytorch__pytorch
torch/_functorch/_aot_autograd/descriptors.py
{ "start": 20386, "end": 20625 }
class ____(AOTInput): """The seed for functionalized Philox RNG calls, specifically for backward graph.""" def expr(self) -> str: return "__philox_backward_seed" @dataclasses.dataclass(frozen=True)
PhiloxBackwardSeedAOTInput
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-pebblo/llama_index/readers/pebblo/utility.py
{ "start": 1524, "end": 1754 }
class ____(BaseModel): """ This class represents a Framework instance. Args: name (str): Name of the Framework. version (str): Version of the Framework. """ name: str version: str
Framework
python
pytorch__pytorch
test/inductor/test_triton_kernels.py
{ "start": 126212, "end": 162205 }
class ____(torch._inductor.test_case.TestCase): """Tests for custom ops wrapping triton kernels""" @requires_gpu @common_utils.parametrize("autotuned", [False, True]) @common_utils.parametrize("dynamic", [False, True]) def test_add_kernel(self, autotuned, dynamic): from torch._inductor.util...
CustomOpTests
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_redshift_cluster.py
{ "start": 1057, "end": 4717 }
class ____: def test_redshift_cluster_sensor_trigger_serialization(self): """ Asserts that the RedshiftClusterTrigger correctly serializes its arguments and classpath. """ trigger = RedshiftClusterTrigger( aws_conn_id="test_redshift_conn_id", cluster_i...
TestRedshiftClusterTrigger
python
getsentry__sentry
tests/sentry/utils/test_sentryappwebhookrequests.py
{ "start": 114, "end": 2444 }
class ____(TestCase): def setUp(self) -> None: self.sentry_app = self.create_sentry_app( name="Test App", events=["issue.resolved", "issue.ignored", "issue.assigned"] ) self.project = self.create_project() self.buffer = SentryAppWebhookRequestsBuffer(self.sentry_app) ...
TestSentryAppWebhookRequests
python
dagster-io__dagster
python_modules/libraries/dagster-dlt/dagster_dlt/dlt_event_iterator.py
{ "start": 2307, "end": 3862 }
class ____(Iterator[T]): """A wrapper around an iterator of Dlt events which contains additional methods for post-processing the events, such as fetching column metadata. """ def __init__( self, events: Iterator[T], context: Union[OpExecutionContext, AssetExecutionContext], ...
DltEventIterator
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingFalsy1.py
{ "start": 237, "end": 284 }
class ____: def __bool__(self) -> bool: ...
B
python
django__django
tests/logging_tests/tests.py
{ "start": 18899, "end": 19457 }
class ____(SimpleTestCase): """ Calling django.setup() initializes the logging configuration. """ def test_configure_initializes_logging(self): from django import setup try: with override_settings( LOGGING_CONFIG="logging_tests.tests.dictConfig", ...
SetupConfigureLogging
python
pypa__setuptools
setuptools/_vendor/platformdirs/unix.py
{ "start": 376, "end": 10643 }
class ____(PlatformDirsABC): # noqa: PLR0904 """ On Unix/Linux, we follow the `XDG Basedir Spec <https://specifications.freedesktop.org/basedir-spec/basedir-spec- latest.html>`_. The spec allows overriding directories with environment variables. The examples shown are the default values, alongside...
Unix
python
astropy__astropy
astropy/coordinates/errors.py
{ "start": 2133, "end": 2881 }
class ____(AstropyUserWarning): """ Emitted for transformations that are not simple rotations. Such transformations can change the angular separation between coordinates depending on its direction. """ def __init__( self, frame_to: "BaseCoordinateFrame", frame_from: "BaseCoordinateFrame...
NonRotationTransformationWarning
python
wireservice__csvkit
csvkit/convert/fixed.py
{ "start": 1654, "end": 2848 }
class ____: """ Given a fixed-width file and a schema file, produce an analog to a csv reader that yields a row of strings for each line in the fixed-width file, preceded with a row of headers as provided in the schema. (This might be problematic if fixed-width-files ever have header rows also, but...
FixedWidthReader
python
pypa__pipenv
pipenv/patched/pip/_vendor/rich/panel.py
{ "start": 467, "end": 11225 }
class ____(JupyterMixin): """A console renderable that draws a border around its contents. Example: >>> console.print(Panel("Hello, World!")) Args: renderable (RenderableType): A console renderable object. box (Box): A Box instance that defines the look of the border (see :ref:`app...
Panel
python
matplotlib__matplotlib
lib/mpl_toolkits/axes_grid1/axes_divider.py
{ "start": 19661, "end": 21892 }
class ____(SubplotDivider): """ A `.SubplotDivider` for laying out axes vertically, while ensuring that they have equal widths. """ def new_locator(self, ny, ny1=None): """ Create an axes locator callable for the specified cell. Parameters ---------- ny, ny1...
VBoxDivider
python
matplotlib__matplotlib
lib/matplotlib/lines.py
{ "start": 55210, "end": 57758 }
class ____: """ Manage the callbacks to maintain a list of selected vertices for `.Line2D`. Derived classes should override the `process_selected` method to do something with the picks. Here is an example which highlights the selected verts with red circles:: import numpy as np imp...
VertexSelector
python
huggingface__transformers
tests/models/janus/test_modeling_janus.py
{ "start": 6548, "end": 12105 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (JanusModel, JanusForConditionalGeneration) if is_torch_available() else () all_generative_model_classes = (JanusForConditionalGeneration,) if is_torch_available() else () pipeline_model_mapping ...
JanusVisionText2TextModelTest
python
pdm-project__pdm
src/pdm/project/project_file.py
{ "start": 453, "end": 4809 }
class ____(TOMLFile): """The data object representing th pyproject.toml file""" def _parse(self) -> dict[str, Any]: data = super()._parse() self._convert_pyproject(data) return data def open_for_write(self) -> tomlkit.TOMLDocument: if self._for_write: return cas...
PyProject
python
huggingface__transformers
src/transformers/models/flava/image_processing_flava_fast.py
{ "start": 4456, "end": 16804 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BICUBIC image_mean = FLAVA_IMAGE_MEAN image_std = FLAVA_IMAGE_STD size = {"height": 224, "width": 224} crop_size = {"height": 224, "width": 224} do_resize = True do_center_crop = True do_rescale = True do_normalize = T...
FlavaImageProcessorFast
python
huggingface__transformers
src/transformers/models/lfm2_moe/modeling_lfm2_moe.py
{ "start": 3072, "end": 6075 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: Lfm2MoeConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self...
Lfm2MoeRotaryEmbedding
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 38843, "end": 39248 }
class ____(SchemaVisitor): def __init__(self, connection, **kw): self.connection = connection assert not kw, f"Unexpected keywords: {kw.keys()}" @contextlib.contextmanager def with_ddl_events(self, target, **kw): """helper context manager that will apply appropriate DDL events ...
InvokeDDLBase
python
getsentry__sentry
src/sentry/auth/providers/saml2/provider.py
{ "start": 13231, "end": 17806 }
class ____(TypedDict): strict: bool sp: _SamlConfigSp security: _SamlConfigSecurity idp: NotRequired[_SamlConfigIdp] def build_saml_config(provider_config: Mapping[str, Any], org: str) -> SamlConfig: """ Construct the SAML configuration dict to be passed into the OneLogin SAML library. ...
SamlConfig
python
fluentpython__example-code-2e
14-inheritance/diamond.py
{ "start": 647, "end": 896 }
class ____: # <1> def ping(self): print(f'{self}.ping() in Root') def pong(self): print(f'{self}.pong() in Root') def __repr__(self): cls_name = type(self).__name__ return f'<instance of {cls_name}>'
Root
python
sanic-org__sanic
sanic/worker/loader.py
{ "start": 489, "end": 4707 }
class ____: """A helper to load application instances. Generally used by the worker to load the application instance. See [Dynamic Applications](/en/guide/deployment/app-loader) for information on when you may need to use this. Args: module_input (str): The module to load the application from...
AppLoader
python
eriklindernoren__ML-From-Scratch
mlfromscratch/supervised_learning/logistic_regression.py
{ "start": 202, "end": 2059 }
class ____(): """ Logistic Regression classifier. Parameters: ----------- learning_rate: float The step length that will be taken when following the negative gradient during training. gradient_descent: boolean True or false depending if gradient descent should be used when tr...
LogisticRegression
python
pytorch__pytorch
test/test_meta.py
{ "start": 44568, "end": 77011 }
class ____(TestCase): # Copies inputs to inplace operations to avoid inplace modifications # to leaves requiring gradient def _get_safe_inplace(self, inplace_variant): @wraps(inplace_variant) def _fn(t, *args, **kwargs): if isinstance(t, list): return inplace_va...
TestMeta
python
pydata__xarray
xarray/tests/test_utils.py
{ "start": 7018, "end": 13017 }
class ____: def test_hashable(self): for v in [False, 1, (2,), (3, 4), "four"]: assert utils.hashable(v) for v in [[5, 6], ["seven", "8"], {9: "ten"}]: assert not utils.hashable(v) @requires_dask def test_dask_array_is_scalar(): # regression test for GH1684 import d...
Test_hashable
python
getsentry__sentry
src/sentry/buffer/redis.py
{ "start": 6972, "end": 7251 }
class ____(Enum): SORTED_SET_ADD = "zadd" SORTED_SET_GET_RANGE = "zrangebyscore" SORTED_SET_DELETE_RANGE = "zremrangebyscore" HASH_ADD = "hset" HASH_ADD_BULK = "hmset" HASH_GET_ALL = "hgetall" HASH_DELETE = "hdel" HASH_LENGTH = "hlen"
RedisOperation
python
ray-project__ray
python/ray/data/grouped_data.py
{ "start": 866, "end": 27878 }
class ____: """Represents a grouped dataset created by calling ``Dataset.groupby()``. The actual groupby is deferred until an aggregation is applied. """ def __init__( self, dataset: Dataset, key: Optional[Union[str, List[str]]], *, num_partitions: Optional[int]...
GroupedData
python
ray-project__ray
python/ray/air/tests/_test_experiment_restore_run.py
{ "start": 970, "end": 1753 }
class ____(tune.Callback): def __init__(self): self._trial_iterations = collections.defaultdict(list) def on_trial_result( self, iteration: int, trials: List["Trial"], trial: "Trial", result: Dict, **info, ): self._trial_iterations[trial.trial...
StatefulCallback
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/hooks/test_sagemaker_unified_studio.py
{ "start": 1190, "end": 8521 }
class ____: @pytest.fixture(autouse=True) def setup(self): with patch( "airflow.providers.amazon.aws.hooks.sagemaker_unified_studio.SageMakerStudioAPI", autospec=True, ) as mock_sdk: self.execution_name = "test-execution" self.waiter_delay = 10 ...
TestSageMakerNotebookHook
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws_tests/pipes_tests/fake_lambda.py
{ "start": 1746, "end": 1806 }
class ____: pass LOG_TAIL_LIMIT = 4096
FakeLambdaContext
python
django__django
tests/model_formsets_regress/tests.py
{ "start": 19469, "end": 21354 }
class ____(TestCase): def test_resubmit(self): u = User.objects.create(username="foo", serial=1) us = UserSite.objects.create(user=u, data=7) formset_cls = inlineformset_factory(User, UserSite, fields="__all__") data = { "serial": "1", "username": "foo", ...
RedeleteTests
python
doocs__leetcode
solution/0400-0499/0468.Validate IP Address/Solution.py
{ "start": 0, "end": 904 }
class ____: def validIPAddress(self, queryIP: str) -> str: def is_ipv4(s: str) -> bool: ss = s.split(".") if len(ss) != 4: return False for t in ss: if len(t) > 1 and t[0] == "0": return False if not t.is...
Solution
python
fastapi__sqlmodel
docs_src/tutorial/one/tutorial005_py310.py
{ "start": 71, "end": 1600 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, ec...
Hero
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_properties05.py
{ "start": 314, "end": 1008 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("properties05.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
PrefectHQ__prefect
src/prefect/client/schemas/actions.py
{ "start": 14382, "end": 14941 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to update a flow run.""" name: Optional[str] = Field(default=None) flow_version: Optional[str] = Field(default=None) parameters: Optional[dict[str, Any]] = Field(default_factory=dict) empirical_policy: objects.FlowRunPolicy = Field( ...
FlowRunUpdate
python
getsentry__sentry
tests/sentry/deletions/test_validate_group_related_models.py
{ "start": 468, "end": 5351 }
class ____(TestCase): """ Validates that all models with group foreign keys are accounted for in the deletion configuration to prevent orphaned records or cascade delete timeouts. """ # Models that don't need to be in either list (with justification). # Note: Having a custom deletion task does ...
GroupRelatedModelsCompletenessTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/mro4.py
{ "start": 479, "end": 604 }
class ____(Generic[T1, T2], Foo1, Foo2[T2]): ... # This should generate an error because a consistent MRO cannot be found.
Bar2
python
streamlit__streamlit
lib/streamlit/testing/v1/element_tree.py
{ "start": 3917, "end": 4592 }
class ____: """Used to represent the initial value of a widget.""" pass # TODO: This class serves as a fallback option for elements that have not # been implemented yet, as well as providing implementations of some # trivial methods. It may have significantly reduced scope once all elements # have been imple...
InitialValue
python
PyCQA__pylint
tests/functional/g/generic_alias/generic_alias_typing.py
{ "start": 2770, "end": 3545 }
class ____(typing.Iterable): # [abstract-method] # __iter__ pass # Type annotations var_tuple: typing.Tuple[int, int] var_dict: typing.Dict[int, str] var_orderedDict: typing.OrderedDict[int, str] var_container: typing.Container[int] var_sequence: typing.Sequence[int] var_iterable: typing.Iterable[int] var_await...
DerivedIterable2
python
tensorflow__tensorflow
tensorflow/python/summary/writer/writer_test.py
{ "start": 26688, "end": 28166 }
class ____(test.TestCase): """FileWriterCache tests.""" def _test_dir(self, test_name): """Create an empty dir to use for tests. Args: test_name: Name of the test. Returns: Absolute path to the test directory. """ test_dir = os.path.join(self.get_temp_dir(), test_name) if os.p...
FileWriterCacheTest
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 5998, "end": 20829 }
class ____: """ Base class for all vyper AST nodes. Vyper nodes are generated from, and closely resemble, their Python counterparts. Divergences are always handled in a node's `__init__` method, and explained in the node docstring. Class Attributes ---------------- __slots__ : Tuple ...
VyperNode
python
walkccc__LeetCode
solutions/3110. Score of a String/3110.py
{ "start": 0, "end": 144 }
class ____: def scoreOfString(self, s: str) -> int: return sum(abs(ord(a) - ord(b)) for a, b in itertools.pairwise(s))
Solution
python
pypa__warehouse
warehouse/macaroons/caveats/_core.py
{ "start": 1898, "end": 3791 }
class ____: _tags: dict[int, type[Caveat]] def __init__(self, *args: Any, **kwargs: Any): super().__init__(*args, **kwargs) self._tags = {} def add(self, tag: int, cls: type[Caveat]): if tag in self._tags: raise TypeError( f"Cannot re-use tag: {tag}, alr...
_CaveatRegistry
python
squidfunk__mkdocs-material
material/plugins/optimize/config.py
{ "start": 1438, "end": 2326 }
class ____(Config): enabled = Type(bool, default = True) concurrency = Type(int, default = max(1, os.cpu_count() - 1)) # Settings for caching cache = Type(bool, default = True) cache_dir = Type(str, default = ".cache/plugin/optimize") # Settings for optimization optimize = Type(bool, defau...
OptimizeConfig
python
django__django
tests/template_tests/filter_tests/test_safeseq.py
{ "start": 68, "end": 704 }
class ____(SimpleTestCase): @setup({"safeseq01": '{{ a|join:", " }} -- {{ a|safeseq|join:", " }}'}) def test_safeseq01(self): output = self.engine.render_to_string("safeseq01", {"a": ["&", "<"]}) self.assertEqual(output, "&amp;, &lt; -- &, <") @setup( { "safeseq02": ( ...
SafeseqTests
python
getsentry__sentry
tests/sentry/integrations/github/test_search.py
{ "start": 848, "end": 15804 }
class ____(APITestCase): # There is another test case that inherits from this # one to ensure that github:enterprise behaves as expected. provider = "github" base_url = "https://api.github.com" def _create_integration(self) -> Integration: future = datetime.now() + timedelta(hours=1) ...
GithubSearchTest
python
sympy__sympy
sympy/matrices/matrices.py
{ "start": 1501, "end": 4023 }
class ____(MatrixCommon): """Provides basic matrix determinant operations. Should not be instantiated directly. See ``determinant.py`` for their implementations.""" def _eval_det_bareiss(self, iszerofunc=_is_zero_after_expand_mul): return _det_bareiss(self, iszerofunc=iszerofunc) def _eval_det...
MatrixDeterminant
python
conda__conda
conda/plugins/types.py
{ "start": 14032, "end": 14559 }
class ____(CondaPlugin): """ Return type to use when defining a pre-transaction action hook. For details on how this is used, see :meth:`~conda.plugins.hookspec.CondaSpecs.conda_pre_transaction_actions`. :param name: Pre transaction name (this is just a label) :param action: Action class which...
CondaPreTransactionAction
python
google__pytype
pytype/tools/analyze_project/pytype_runner_test.py
{ "start": 28404, "end": 29880 }
class ____(TestBase): """Test imports-related functionality.""" def setUp(self): super().setUp() self.conf = self.parser.config_from_defaults() def test_write_default_pyi(self): with test_utils.Tempdir() as d: self.conf.output = d.path runner = make_runner([], [], self.conf) self.a...
TestImports
python
wandb__wandb
wandb/sdk/artifacts/_generated/delete_artifact_sequence.py
{ "start": 394, "end": 565 }
class ____(GQLResult): artifact_collection: DeleteArtifactSequenceResultArtifactCollection = Field( alias="artifactCollection" )
DeleteArtifactSequenceResult
python
pytorch__pytorch
torch/storage.py
{ "start": 22007, "end": 50959 }
class ____: is_sparse: _bool = False # Used when stashing FakeTensor device onto storage in torch.save(metadata_only=True) _fake_device: _Optional[torch.device] = None dtype: torch.dtype @property def _dtype(self): return self.dtype @property def filename(self) -> _Optional[st...
TypedStorage
python
falconry__falcon
docs/ext/falcon_releases.py
{ "start": 3532, "end": 3720 }
class ____(enum.Enum): current = 'current' security = 'security' eol = 'eol' @property def ref(self): return f':ref:`stable_release_{self.value}`'
_ReleaseStatus
python
automl__auto-sklearn
autosklearn/pipeline/components/feature_preprocessing/densifier.py
{ "start": 308, "end": 1374 }
class ____(AutoSklearnPreprocessingAlgorithm): def __init__(self, random_state=None): pass def fit(self, X, y=None): self.fitted_ = True return self def transform(self, X): from scipy import sparse if sparse.issparse(X): return X.todense().getA() ...
Densifier
python
tensorflow__tensorflow
tensorflow/python/saved_model/tests/variable_wrapper_test.py
{ "start": 2155, "end": 2950 }
class ____(test.TestCase): def test_checkpoint(self): v = VariableWrapper(5.0) root = autotrackable.AutoTrackable() root.v = v save_prefix = os.path.join(self.get_temp_dir(), "checkpoint") ckpt = checkpoint.Checkpoint(v=v) save_path = ckpt.save(save_prefix) v.value.assign(100) ckpt....
VariableWrapperTest
python
readthedocs__readthedocs.org
readthedocs/core/filters.py
{ "start": 699, "end": 1870 }
class ____(ModelChoiceField): """ Choice field for tuning model choices. The underlying ModelChoiceField assumes that the model's ``__repr__`` method will return the best choice label. In our modeling, ``__repr__`` is almost exclusively used for debugging, so is not for user display. :param la...
FilteredModelChoiceField
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/test_code_references.py
{ "start": 780, "end": 2103 }
class ____(dg.Component): def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: return dg.Definitions( assets=[dg.AssetSpec(key="asset1"), MyCacheableAssetsDefinition(unique_id="my_asset")] ) @pytest.mark.skip("Find a way to set up this test with new Tree system") d...
CustomComponent
python
pappasam__jedi-language-server
jedi_language_server/initialization_options.py
{ "start": 2691, "end": 2881 }
class ____: environment_path: Optional[str] = None extra_paths: List[str] = field(default_factory=list) symbols: Symbols = field(default_factory=Symbols) @light_dataclass
Workspace
python
scipy__scipy
scipy/stats/_distribution_infrastructure.py
{ "start": 220553, "end": 225875 }
class ____(TransformedDistribution): r"""Distribution underlying a strictly monotonic function of a random variable Given a random variable :math:`X`; a strictly monotonic function :math:`g(u)`, its inverse :math:`h(u) = g^{-1}(u)`, and the derivative magnitude :math: `|h'(u)| = \left| \frac{dh(u)}{du}...
MonotonicTransformedDistribution
python
ray-project__ray
python/ray/util/iter.py
{ "start": 4150, "end": 26472 }
class ____(Generic[T]): """A parallel iterator over a set of remote actors. This can be used to iterate over a fixed set of task results (like an actor pool), or a stream of data (e.g., a fixed range of numbers, an infinite stream of RLlib rollout results). This class is **serializable** and can b...
ParallelIterator
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 347161, "end": 347397 }
class ____(Response): """ Response of tasks.ping endpoint. """ _service = "tasks" _action = "ping" _version = "2.20" _schema = {"additionalProperties": False, "definitions": {}, "type": "object"}
PingResponse
python
pypa__pipenv
pipenv/vendor/plette/models/sections.py
{ "start": 316, "end": 385 }
class ____(DataModelSequence): item_class = Source
SourceCollection
python
joke2k__faker
tests/providers/test_bank.py
{ "start": 9634, "end": 10116 }
class ____: """Test es_AR bank provider""" def test_bban(self, faker, num_samples): for _ in range(num_samples): assert re.fullmatch(r"[A-Z]{4}\d{20}", faker.bban()) def test_iban(self, faker, num_samples): for _ in range(num_samples): iban = faker.iban() ...
TestEsAr
python
huggingface__transformers
src/transformers/models/luke/modeling_luke.py
{ "start": 5554, "end": 6722 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification loss. logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`): Classification scores (before SoftMax). entity_hidden_states (`tuple(tor...
EntityClassificationOutput
python
ray-project__ray
python/ray/tune/error.py
{ "start": 259, "end": 577 }
class ____(TuneError): """The more specific TuneError that happens for a certain Tune subroutine. For example starting/stopping a trial. """ def __init__(self, traceback_str: str): self.traceback_str = traceback_str def __str__(self): return self.traceback_str
_SubCategoryTuneError
python
spack__spack
lib/spack/spack/vendor/attr/validators.py
{ "start": 13222, "end": 15068 }
class ____: bound = attrib() compare_op = attrib() compare_func = attrib() def __call__(self, inst, attr, value): """ We use a callable class to be able to change the ``__repr__``. """ if not self.compare_func(value, self.bound): raise ValueError( ...
_NumberValidator
python
gevent__gevent
src/gevent/tests/test__util.py
{ "start": 1978, "end": 7632 }
class ____(greentest.TestCase): def setUp(self): super(TestTree, self).setUp() self.track_greenlet_tree = gevent.config.track_greenlet_tree gevent.config.track_greenlet_tree = True self.maxDiff = None def tearDown(self): gevent.config.track_greenlet_tree = self.track_gr...
TestTree
python
pandas-dev__pandas
pandas/tests/extension/base/getitem.py
{ "start": 85, "end": 15815 }
class ____: """Tests for ExtensionArray.__getitem__.""" def test_iloc_series(self, data): ser = pd.Series(data) result = ser.iloc[:4] expected = pd.Series(data[:4]) tm.assert_series_equal(result, expected) result = ser.iloc[[0, 1, 2, 3]] tm.assert_series_equal(r...
BaseGetitemTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassConverter1.py
{ "start": 2464, "end": 2824 }
class ____: @overload def __call__(self, arg1: int) -> str: ... @overload def __call__(self, arg1: str) -> int: ... def __call__(self, arg1: str | int | list[str]) -> int | str: return 1 callable: Callable[[str], int] = converter_simple callable_union: Callable[[str], int] | Callable[[in...
CallableObject
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 109752, "end": 111770 }
class ____(TestCase): r""" Verify the behavior of a certain ``DataPipes`` with ``DataLoader`` """ def test_shuffler_iterdatapipe(self): r""" Verify ``IterDataPipe.shuffle`` is controlled by ``DataLoader`` to generate different seeds deterministically per epoch. """ ...
IntegrationTestDataLoaderDataPipe
python
sqlalchemy__sqlalchemy
test/engine/test_ddlevents.py
{ "start": 1022, "end": 12147 }
class ____(fixtures.TestBase): def setup_test(self): self.bind = engines.mock_engine() self.metadata = MetaData() self.table = Table("t", self.metadata, Column("id", Integer)) def test_table_create_before(self): table, bind = self.table, self.bind canary = mock.Mock() ...
DDLEventTest
python
faif__python-patterns
patterns/behavioral/iterator_alt.py
{ "start": 194, "end": 1237 }
class ____: """Counts by word numbers, up to a maximum of five""" _WORD_MAP = ( "one", "two", "three", "four", "five", ) def __init__(self, start: int, stop: int) -> None: self.start = start self.stop = stop def __iter__(self) -> NumberWords...
NumberWords
python
google__jax
jax/experimental/mosaic/gpu/constraints.py
{ "start": 2766, "end": 2908 }
class ____: expression: Expression source_shape: tuple[int, ...] target_shape: tuple[int, ...] @dataclasses.dataclass(frozen=True)
Reshape
python
mlflow__mlflow
mlflow/entities/trace_location.py
{ "start": 4197, "end": 4790 }
class ____(str, Enum): TRACE_LOCATION_TYPE_UNSPECIFIED = "TRACE_LOCATION_TYPE_UNSPECIFIED" MLFLOW_EXPERIMENT = "MLFLOW_EXPERIMENT" INFERENCE_TABLE = "INFERENCE_TABLE" UC_SCHEMA = "UC_SCHEMA" def to_proto(self): return pb.TraceLocation.TraceLocationType.Value(self) @classmethod def ...
TraceLocationType
python
doocs__leetcode
solution/2200-2299/2211.Count Collisions on a Road/Solution.py
{ "start": 0, "end": 155 }
class ____: def countCollisions(self, directions: str) -> int: s = directions.lstrip("L").rstrip("R") return len(s) - s.count("S")
Solution
python
pytorch__pytorch
test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py
{ "start": 5662, "end": 6858 }
class ____(RendezvousBackend): _state: Optional[bytes] _token: int def __init__(self) -> None: self._state = None self._token = 0 @property def name(self) -> str: return "fake_backend" def get_state(self) -> Optional[tuple[bytes, Token]]: if self._token == 0: ...
FakeRendezvousBackend
python
falconry__falcon
tests/_inspect_fixture.py
{ "start": 1323, "end": 1452 }
class ____: def process_request(self, *args): pass def process_response(self, *args): pass
OtherMiddleware
python
langchain-ai__langchain
libs/partners/qdrant/langchain_qdrant/qdrant.py
{ "start": 566, "end": 659 }
class ____(Exception): """`QdrantVectorStore` related exceptions."""
QdrantVectorStoreError
python
encode__django-rest-framework
rest_framework/fields.py
{ "start": 28901, "end": 30079 }
class ____(Field): valid_formats = ('hex_verbose', 'hex', 'int', 'urn') default_error_messages = { 'invalid': _('Must be a valid UUID.'), } def __init__(self, **kwargs): self.uuid_format = kwargs.pop('format', 'hex_verbose') if self.uuid_format not in self.valid_formats: ...
UUIDField
python
huggingface__transformers
src/transformers/models/mimi/modeling_mimi.py
{ "start": 18560, "end": 20625 }
class ____(nn.Module): """SEANet encoder as used by Mimi.""" def __init__(self, config: MimiConfig): super().__init__() model = [MimiConv1d(config, config.audio_channels, config.num_filters, config.kernel_size)] scaling = 1 # keep track of MimiConv1d submodule layer names for e...
MimiEncoder
python
scikit-learn__scikit-learn
sklearn/utils/tests/test_estimator_checks.py
{ "start": 6179, "end": 6651 }
class ____(BaseEstimator): def __init__(self, a=0, b="method1"): self.a = a self.b = b def set_params(self, **kwargs): if "a" in kwargs: a = kwargs.pop("a") self.a = a if a is None: kwargs.pop("b") self.b = "method2" ...
ModifiesAnotherValue
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol24.py
{ "start": 872, "end": 1003 }
class ____: def jump(self) -> int: ... def do_jump(j: Jumps): print(j.jump()) do_jump(Jumper1) do_jump(Jumper2())
Jumper2
python
pytorch__pytorch
test/distributions/test_distributions.py
{ "start": 252465, "end": 263553 }
class ____(DistributionsTestCase): def _test_pdf_score( self, dist_class, x, expected_value, probs=None, logits=None, expected_gradient=None, atol=1e-5, ): if probs is not None: p = probs.detach().requires_grad_() di...
TestNumericalStability
python
aio-libs__aiohttp
aiohttp/compression_utils.py
{ "start": 7386, "end": 9108 }
class ____(ZlibBaseHandler): def __init__( self, encoding: str | None = None, suppress_deflate_header: bool = False, executor: Executor | None = None, max_sync_chunk_size: int | None = MAX_SYNC_CHUNK_SIZE, ): super().__init__( mode=encoding_to_mode(enc...
ZLibDecompressor
python
dagster-io__dagster
python_modules/dagster/dagster_tests/storage_tests/utils/defs_state_storage.py
{ "start": 464, "end": 5229 }
class ____: """You can extend this class to easily run these set of tests on any state storage. When extending, you simply need to override the `state_storage` fixture and return your implementation of `StateStorage`. """ __test__ = False @pytest.fixture(name="storage") def state_storage(s...
TestDefsStateStorage
python
fabric__fabric
fabric/group.py
{ "start": 7815, "end": 8527 }
class ____(Group): """ Subclass of `.Group` which executes in simple, serial fashion. .. versionadded:: 2.0 """ def _do(self, method, *args, **kwargs): results = GroupResult() excepted = False for cxn in self: try: results[cxn] = getattr(cxn, met...
SerialGroup
python
PrefectHQ__prefect
src/prefect/settings/models/server/database.py
{ "start": 1598, "end": 2945 }
class ____(PrefectBaseSettings): """ Settings for controlling SQLAlchemy connection behavior; note that these settings only take effect when using a PostgreSQL database. """ model_config: ClassVar[SettingsConfigDict] = build_settings_config( ("server", "database", "sqlalchemy", "connect_arg...
SQLAlchemyConnectArgsSettings
python
sanic-org__sanic
sanic/cli/base.py
{ "start": 674, "end": 1075 }
class ____(_SubParsersAction): def __call__(self, parser, namespace, values, option_string=None): self._name_parser_map parser_name = values[0] if parser_name not in self._name_parser_map: self._name_parser_map[parser_name] = parser values = ["<custom>", *values] ...
SanicSubParsersAction
python
getsentry__sentry
src/sentry/preprod/migrations/0007_add_install_file.py
{ "start": 186, "end": 1549 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
huggingface__transformers
src/transformers/models/sam3/modeling_sam3.py
{ "start": 4458, "end": 5610 }
class ____(ModelOutput): r""" intermediate_hidden_states (`torch.FloatTensor` of shape `(num_layers, batch_size, num_queries, hidden_size)`): Decoder hidden states from all layers. reference_boxes (`torch.FloatTensor` of shape `(num_layers, batch_size, num_queries, 4)`): Predicted reference ...
Sam3DETRDecoderOutput
python
ansible__ansible
test/lib/ansible_test/_internal/ansible_util.py
{ "start": 10112, "end": 10245 }
class ____: """Collection detail.""" def __init__(self) -> None: self.version: t.Optional[str] = None
CollectionDetail