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
gevent__gevent
src/gevent/tests/test__greenlet.py
{ "start": 30654, "end": 31221 }
class ____(greentest.TestCase): def test_init(self): self.switch_expected = False # in python-dbg mode this will check that Greenlet() does not create any circular refs gevent.Greenlet() def test_kill_scheduled(self): gevent.spawn(gevent.sleep, timing.LARGE_TICK).kill() de...
TestRef
python
astropy__astropy
astropy/visualization/wcsaxes/patches.py
{ "start": 4901, "end": 7724 }
class ____(Polygon): """ Create a patch representing a latitude-longitude quadrangle. The edges of the quadrangle lie on two lines of constant longitude and two lines of constant latitude (or the equivalent component names in the coordinate frame of interest, such as right ascension and declination...
Quadrangle
python
tensorflow__tensorflow
tensorflow/python/keras/utils/generic_utils.py
{ "start": 28660, "end": 40600 }
class ____(object): """Displays a progress bar. Args: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose) stateful_metrics: Iterable of string names of metrics that should *not* be ...
Progbar
python
jazzband__tablib
src/tablib/core.py
{ "start": 25261, "end": 28380 }
class ____: """A book of :class:`Dataset` objects. """ def __init__(self, sets=None): self._datasets = sets or [] def __repr__(self): try: return f'<{self.title.lower()} databook>' except AttributeError: return '<databook object>' def wipe(self): ...
Databook
python
rapidsai__cudf
python/dask_cudf/dask_cudf/_expr/expr.py
{ "start": 1764, "end": 2346 }
class ____(CumulativeBlockwise): @property def _args(self) -> list: return self.operands[:1] @property def _kwargs(self) -> dict: # Must pass axis and skipna as kwargs in cudf return {"axis": self.axis, "skipna": self.skipna} # The upstream Var code uses `Series.values`, and r...
PatchCumulativeBlockwise
python
giampaolo__psutil
tests/__init__.py
{ "start": 34325, "end": 38730 }
class ____: """A container that lists all Process class method names + some reasonable parameters to be called with. Utility methods (parent(), children(), ...) are excluded. >>> ns = process_namespace(psutil.Process()) >>> for fun, name in ns.iter(ns.getters): ... fun() """ utils =...
process_namespace
python
jina-ai__jina
jina/serve/runtimes/servers/grpc.py
{ "start": 474, "end": 9030 }
class ____(BaseServer): """GRPC Server implementation""" def __init__( self, grpc_server_options: Optional[dict] = None, ssl_keyfile: Optional[str] = None, ssl_certfile: Optional[str] = None, proxy: bool = False, **kwargs, ): """Initialize the gateway...
GRPCServer
python
django-debug-toolbar__django-debug-toolbar
tests/panels/test_versions.py
{ "start": 235, "end": 1341 }
class ____(BaseTestCase): panel_id = VersionsPanel.panel_id def test_app_version_from_get_version_fn(self): class FakeApp: def get_version(self): return version_info_t(1, 2, 3, "", "") self.assertEqual(self.panel.get_app_version(FakeApp()), "1.2.3") def test_in...
VersionsPanelTestCase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassDescriptors1.py
{ "start": 160, "end": 659 }
class ____: @overload def __get__(self, __obj: None, __owner: Any) -> "MyDescriptor": ... @overload def __get__(self, __obj: object, __owner: Any) -> int: ... def __get__(self, __obj: object | None, __owner: Any) -> "int | MyDescriptor": if __obj is None: return self re...
MyDescriptor
python
pydantic__pydantic
tests/benchmarks/basemodel_eq_performance.py
{ "start": 645, "end": 1642 }
class ____(pydantic.BaseModel, frozen=True): def __eq__(self, other: Any) -> bool: if isinstance(other, pydantic.BaseModel): # When comparing instances of generic types for equality, as long as all field values are equal, # only require their generic origin types to be equal, rather ...
OldImplementationModel
python
doocs__leetcode
solution/1600-1699/1652.Defuse the Bomb/Solution.py
{ "start": 0, "end": 431 }
class ____: def decrypt(self, code: List[int], k: int) -> List[int]: n = len(code) ans = [0] * n if k == 0: return ans for i in range(n): if k > 0: for j in range(i + 1, i + k + 1): ans[i] += code[j % n] else: ...
Solution
python
eth-brownie__brownie
brownie/_gui/console.py
{ "start": 420, "end": 1211 }
class ____(tk.Text): def __init__(self, parent): super().__init__(parent, height=1) self.configure(**TEXT_STYLE) self.configure(background="#161616") self._content = "" def write(self, text): self.configure(state="normal") self.delete(1.0, "end") self.ins...
Console
python
ray-project__ray
python/ray/autoscaler/v2/event_logger.py
{ "start": 528, "end": 8141 }
class ____: """ Logs events related to the autoscaler. # TODO: - Add more logging for other events. - Rate limit the events if too spammy. """ def __init__(self, logger: EventLoggerAdapter): self._logger = logger def log_cluster_scheduling_update( self, cluster...
AutoscalerEventLogger
python
walkccc__LeetCode
solutions/3534. Path Existence Queries in a Graph II/3534.py
{ "start": 0, "end": 1635 }
class ____: def pathExistenceQueries( self, n: int, nums: list[int], maxDiff: int, queries: list[list[int]], ) -> list[int]: sortedNumAndIndexes = sorted((num, i) for i, num in enumerate(nums)) sortedNums = [num for num, _ in sortedNumAndIndexes] indexMap = {originalIndex: ...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-dg-core/dagster_dg_core/utils/__init__.py
{ "start": 13614, "end": 14163 }
class ____(DgClickHelpMixin, click.Command): # pyright: ignore[reportIncompatibleMethodOverride] def __init__(self, *args, unlaunched: bool = False, **kwargs): """DgClickCommand with conditional hiding for unlaunched features. Args: unlaunched: If True, the command will be hidden unles...
DgClickCommand
python
scipy__scipy
scipy/sparse/_base.py
{ "start": 57043, "end": 58343 }
class ____: """A namespace class to separate sparray from spmatrix""" @classmethod def __class_getitem__(cls, arg, /): """ Return a parametrized wrapper around the `~scipy.sparse.sparray` type. .. versionadded:: 1.16.0 Returns ------- alias : types.GenericA...
sparray
python
spyder-ide__spyder
spyder/utils/stylesheet.py
{ "start": 19755, "end": 23017 }
class ____(BaseDockTabBarStyleSheet): """ Style for special tab bars. Notes ----- This is the base class for horizontal tab bars that follow the design discussed on issue spyder-ide/ux-improvements#4. """ SCROLL_BUTTONS_BORDER_POS = 'right' def set_stylesheet(self): super(...
SpecialTabBarStyleSheet
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_E.py
{ "start": 1424, "end": 3875 }
class ____(Benchmark): r""" Eckerle4 objective function. Eckerle, K., NIST (1979). Circular Interference Transmittance Study. ..[1] https://www.itl.nist.gov/div898/strd/nls/data/eckerle4.shtml #TODO, this is a NIST regression standard dataset, docstring needs improving """ def __i...
Eckerle4
python
gevent__gevent
src/greentest/3.12/test_httplib.py
{ "start": 87192, "end": 99212 }
class ____(TestCase): def setUp(self): response_text = ( 'HTTP/1.1 200 OK\r\n\r\n' # Reply to CONNECT 'HTTP/1.1 200 OK\r\n' # Reply to HEAD 'Content-Length: 42\r\n\r\n' ) self.host = 'proxy.com' self.port = client.HTTP_PORT self.conn = clie...
TunnelTests
python
ansible__ansible
lib/ansible/_internal/_datatag/_tags.py
{ "start": 267, "end": 3259 }
class ____(AnsibleDatatagBase): """ A tag that stores origin metadata for a tagged value, intended for forensic/diagnostic use. Origin metadata should not be used to make runtime decisions, as it is not guaranteed to be present or accurate. Setting both `path` and `line_num` can result in diagnostic dis...
Origin
python
PyCQA__pylint
tests/functional/c/ctor_arguments.py
{ "start": 544, "end": 630 }
class ____(Class1Arg): def __init__(self, *args, **kwargs): pass
ClassAllArgs
python
getsentry__sentry
tests/snuba/search/test_backend.py
{ "start": 98282, "end": 98360 }
class ____(TestCase, EventsSnubaSearchTestCases): pass
EventsSnubaSearchTest
python
Lightning-AI__lightning
src/lightning/fabric/strategies/xla.py
{ "start": 1578, "end": 11443 }
class ____(ParallelStrategy): """Strategy for training multiple TPU devices using the :func:`torch_xla.distributed.xla_multiprocessing.spawn` method.""" def __init__( self, accelerator: Optional[Accelerator] = None, parallel_devices: Optional[list[torch.device]] = None, chec...
XLAStrategy
python
tiangolo__fastapi
tests/test_dependency_class.py
{ "start": 367, "end": 470 }
class ____: async def __call__(self, value: str) -> str: return value
AsyncCallableDependency
python
facebook__pyre-check
client/language_server/protocol.py
{ "start": 14813, "end": 15070 }
class ____(json_mixins.CamlCaseAndExcludeJsonMixin): """Result for nuclide-vscode-lsp coverage feature.""" covered_percent: float uncovered_ranges: List[Diagnostic] default_message: str @dataclasses.dataclass(frozen=True)
TypeCoverageResponse
python
django__django
tests/utils_tests/test_autoreload.py
{ "start": 11412, "end": 11782 }
class ____(SimpleTestCase): def test_common_roots(self): paths = ( Path("/first/second"), Path("/first/second/third"), Path("/first/"), Path("/root/first/"), ) results = autoreload.common_roots(paths) self.assertCountEqual(results, [Pat...
TestCommonRoots
python
huggingface__transformers
tests/models/parakeet/test_feature_extraction_parakeet.py
{ "start": 3433, "end": 8522 }
class ____(SequenceFeatureExtractionTestMixin, unittest.TestCase): feature_extraction_class = ParakeetFeatureExtractor def setUp(self): self.feat_extract_tester = ParakeetFeatureExtractionTester(self) def _load_datasamples(self, num_samples): ds = load_dataset("hf-internal-testing/librispe...
ParakeetFeatureExtractionTest
python
scrapy__scrapy
tests/test_engine_stop_download_bytes.py
{ "start": 618, "end": 3147 }
class ____(TestEngineBase): @deferred_f_from_coro_f async def test_crawler(self, mockserver: MockServer) -> None: for spider in ( MySpider, DictItemsSpider, AttrsItemsSpider, DataClassItemsSpider, ): run = BytesReceivedCrawlerRun(spider...
TestBytesReceivedEngine
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_partition_backfill.py
{ "start": 68161, "end": 103121 }
class ____(ExecutingGraphQLContextTestMatrix): def test_launch_from_failure(self, graphql_context): repository_selector = infer_repository_selector(graphql_context) partition_set_selector = { "repositorySelector": repository_selector, "partitionSetName": "chained_failure_job_...
TestLaunchDaemonBackfillFromFailure
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/yaml_utils/__init__.py
{ "start": 1735, "end": 1899 }
class ____(yaml.SafeLoader, _CanRemoveImplicitResolver): pass DagsterRunConfigYamlLoader.remove_implicit_resolver(YAML_TIMESTAMP_TAG)
DagsterRunConfigYamlLoader
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 107619, "end": 107844 }
class ____(Structure): _fields_ = [('version', c_uint), ('maxAttackerAdvantage', c_ulong), ] ConfComputeSetKeyRotationThresholdInfo_v1 = 0x1000010
c_nvmlConfComputeSetKeyRotationThresholdInfo_t
python
streamlit__streamlit
lib/streamlit/elements/image.py
{ "start": 1619, "end": 9611 }
class ____: @gather_metrics("image") def image( self, image: ImageOrImageList, # TODO: Narrow type of caption, dependent on type of image, # by way of overload caption: str | list[str] | None = None, width: Width = "content", use_column_width: UseColumnWi...
ImageMixin
python
joke2k__faker
faker/providers/address/ka_GE/__init__.py
{ "start": 45, "end": 28924 }
class ____(AddressProvider): city_formats = ["{{city_name}}"] street_name_formats = ["{{street_title}} {{street_suffix}}"] street_address_formats = ["{{street_name}} {{building_number}}"] address_formats = ["{{street_address}}, {{city}}"] building_number_formats = ["##"] street_suffixes = ["ქ."]...
Provider
python
huggingface__transformers
src/transformers/models/visual_bert/configuration_visual_bert.py
{ "start": 787, "end": 6767 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`VisualBertModel`]. It is used to instantiate an VisualBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a simila...
VisualBertConfig
python
great-expectations__great_expectations
contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_column_values_to_be_probabilistically_greater_than_or_equal_to_threshold.py
{ "start": 1788, "end": 6939 }
class ____(ColumnMapExpectation): """Expect the column values to be probabilistically greater than or equal to the specified threshold. This function builds upon the custom column map expectations of Great Expectations. This function asks a yes/no question of each row in the user-specified column; namely, does...
ExpectColumnValuesToBeProbabilisticallyGreaterThanOrEqualToThreshold
python
django__django
tests/inspectdb/models.py
{ "start": 1280, "end": 1761 }
class ____(models.Model): field = models.IntegerField(db_column="field") # Underscores field_field_0 = models.IntegerField(db_column="Field_") field_field_1 = models.IntegerField(db_column="Field__") field_field_2 = models.IntegerField(db_column="__field") # Other chars prc_x = models.Intege...
SpecialName
python
pytorch__pytorch
torch/distributed/elastic/rendezvous/dynamic_rendezvous.py
{ "start": 16034, "end": 16478 }
class ____(Enum): """Specifies the possible actions based on the state of the rendezvous.""" KEEP_ALIVE = 1 ADD_TO_PARTICIPANTS = 2 ADD_TO_WAIT_LIST = 3 ADD_TO_REDUNDANCY_LIST = 4 REMOVE_FROM_PARTICIPANTS = 5 REMOVE_FROM_WAIT_LIST = 6 REMOVE_FROM_REDUNDANCY_LIST = 7 MARK_RENDEZVOUS_...
_Action
python
facelessuser__pymdown-extensions
pymdownx/arithmatex.py
{ "start": 9526, "end": 11657 }
class ____(BlockProcessor): """MathJax block processor to find $$MathJax$$ content.""" def __init__(self, pattern, config, md): """Initialize.""" # Generic setup self.generic = config.get('generic', False) wrap = config.get('tex_block_wrap', ['\\[', '\\]']) self.wrap = ...
BlockArithmatexProcessor
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py
{ "start": 2253, "end": 2341 }
class ____(ABC): # error (not an abstract attribute) foo = 2
abc_set_class_variable_2
python
getsentry__sentry
tests/sentry/backup/test_imports.py
{ "start": 49090, "end": 59142 }
class ____(ImportTestCase): """ Ensures that filtering operations include the correct models. """ def test_import_filter_users(self) -> None: self.create_exhaustive_user("user_1") self.create_exhaustive_user("user_2") with tempfile.TemporaryDirectory() as tmp_dir: t...
FilterTests
python
walkccc__LeetCode
solutions/2574. Left and Right Sum Differences/2574.py
{ "start": 0, "end": 441 }
class ____: def leftRigthDifference(self, nums: list[int]) -> list[int]: n = len(nums) leftSum = [0] * n rightSum = [0] * n prefix = 0 suffix = 0 for i in range(n): if i > 0: prefix += nums[i - 1] leftSum[i] = prefix for i in range(n - 1, -1, -1): if i + 1 < n: ...
Solution
python
keon__algorithms
tests/test_graph.py
{ "start": 2554, "end": 3161 }
class ____(unittest.TestCase): def test_dijkstra(self): g = Dijkstra(9) g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2], [0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, ...
TestDijkstra
python
getsentry__sentry
src/sentry/replays/usecases/ingest/__init__.py
{ "start": 2108, "end": 2241 }
class ____(msgspec.Struct, gc=False, tag_field="type", tag=6): pass # These are the schema definitions we care about.
PluginEvent
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/vector/rendering.py
{ "start": 566, "end": 7216 }
class ____(VectorWrapper, gym.utils.RecordConstructorArgs): """Adds support for Human-based Rendering for Vector-based environments.""" ACCEPTED_RENDER_MODES = [ "rgb_array", "rgb_array_list", "depth_array", "depth_array_list", ] def __init__(self, env: VectorEnv, scree...
HumanRendering
python
doocs__leetcode
solution/1100-1199/1144.Decrease Elements To Make Array Zigzag/Solution.py
{ "start": 0, "end": 422 }
class ____: def movesToMakeZigzag(self, nums: List[int]) -> int: ans = [0, 0] n = len(nums) for i in range(2): for j in range(i, n, 2): d = 0 if j: d = max(d, nums[j] - nums[j - 1] + 1) if j < n - 1: ...
Solution
python
sympy__sympy
sympy/functions/combinatorial/numbers.py
{ "start": 56123, "end": 57712 }
class ____(DefinedFunction): r""" Partition numbers The Partition numbers are a sequence of integers `p_n` that represent the number of distinct ways of representing `n` as a sum of natural numbers (with order irrelevant). The generating function for `p_n` is given by: .. math:: \sum_{n=0}^\in...
partition
python
fluentpython__example-code-2e
10-dp-1class-func/untyped/strategy_param2.py
{ "start": 2616, "end": 2915 }
class ____(Promotion): """discount for orders with 10 or more distinct items""" def __call__(self, order): distinct_items = {item.product for item in order.cart} if len(distinct_items) >= 10: return order.total() * self.percent / 100 return 0
LargeOrderPromo
python
walkccc__LeetCode
solutions/2472. Maximum Number of Non-overlapping Palindrome Substrings/2472.py
{ "start": 0, "end": 1109 }
class ____: def maxPalindromes(self, s: str, k: int) -> int: n = len(s) # dp[i] := the maximum number of substrings in the first i chars of s dp = [0] * (n + 1) def isPalindrome(l: int, r: int) -> bool: """Returns True is s[i..j) is a palindrome.""" if l < 0: return False wh...
Solution
python
google__jax
jax/_src/core.py
{ "start": 48484, "end": 48965 }
class ____: __slots__ = ['prev', 'axis_names'] def __init__(self, axis_names: AxisName | None): self.axis_names = axis_names def __enter__(self): self.prev = trace_ctx.axis_env if self.axis_names is not None: trace_ctx.set_axis_env(self.prev.add_spmd_axis_names(self.axis_names)) def __exit_...
AddSpmdAxisNamesContextManager
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_reduce_op_test.py
{ "start": 1521, "end": 27060 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters( #========================================================================= # Docstring examples. RaggedTensor for testing is: # [[3, 1, 4], # [1, 5, ], # [9, ], # [2, 6 ...
RaggedReduceOpsTest
python
lepture__authlib
authlib/jose/rfc7516/models.py
{ "start": 3011, "end": 3769 }
class ____(dict): """Shared header object for JWE. Combines protected header and shared unprotected header together. """ def __init__(self, protected, unprotected): obj = {} if unprotected: obj.update(unprotected) if protected: obj.update(protected) ...
JWESharedHeader
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py
{ "start": 1685, "end": 1913 }
class ____: def __init__(self): self.name = "python" def __eq__(self, other): return isinstance(other, Language) and other.name == self.name def __hash__(self): return hash(self.name)
Language
python
getsentry__sentry
src/sentry/migrations/0993_add_event_id_to_grouphash_metadata.py
{ "start": 155, "end": 1466 }
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
tiangolo__fastapi
tests/test_default_response_class.py
{ "start": 197, "end": 358 }
class ____(JSONResponse): media_type = "application/x-orjson" def render(self, content: Any) -> bytes: return orjson.dumps(content)
ORJSONResponse
python
graphql-python__graphene
graphene/types/tests/test_interface.py
{ "start": 222, "end": 5077 }
class ____(UnmountedType): def get_type(self): return MyType def test_generate_interface(): class MyInterface(Interface): """Documentation""" assert MyInterface._meta.name == "MyInterface" assert MyInterface._meta.description == "Documentation" assert MyInterface._meta.fields == {...
MyScalar
python
tensorflow__tensorflow
tensorflow/python/distribute/coordinator/cluster_coordinator_test.py
{ "start": 17257, "end": 19252 }
class ____(test.TestCase, parameterized.TestCase): @classmethod def setUpClass(cls): super(CoordinatorContextTest, cls).setUpClass() cls.coordinator = make_coordinator(num_workers=5, num_ps=2) cls.strategy = cls.coordinator.strategy def testWorkerIndexDatasetFn(self): def dataset_fn(context): ...
CoordinatorContextTest
python
marshmallow-code__marshmallow
src/marshmallow/fields.py
{ "start": 35738, "end": 36829 }
class ____(Number[float]): """A double as an IEEE-754 double precision string. :param allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed, even though they are illegal according to the JSON specification. :param as_string: If `True`, format the value as a string. :param kwargs: ...
Float
python
PrefectHQ__prefect
src/integrations/prefect-docker/tests/test_host.py
{ "start": 378, "end": 2807 }
class ____: @pytest.fixture def host_kwargs(self): _host_kwargs = dict( base_url="unix:///var/run/docker.sock", version="1.35", max_pool_size=8, credstore_env=None, client_kwargs={"tls": True}, ) return _host_kwargs @pytest...
TestDockerHost
python
pytorch__pytorch
.github/scripts/test_gitutils.py
{ "start": 285, "end": 1002 }
class ____(TestCase): def test_iterator(self, input_: str = "abcdef") -> None: iter_ = PeekableIterator(input_) for idx, c in enumerate(iter_): self.assertEqual(c, input_[idx]) def test_is_iterable(self) -> None: from collections.abc import Iterator iter_ = Peekable...
TestPeekableIterator
python
getsentry__sentry
src/sentry/seer/anomaly_detection/types.py
{ "start": 1573, "end": 1697 }
class ____(TypedDict): organization_id: int project_id: NotRequired[int] alert: AlertInSeer
DeleteAlertDataRequest
python
sqlalchemy__sqlalchemy
test/perf/orm2010.py
{ "start": 430, "end": 670 }
class ____(Base): __tablename__ = "employee" id = Column(Integer, primary_key=True) name = Column(String(100), nullable=False) type = Column(String(50), nullable=False) __mapper_args__ = {"polymorphic_on": type}
Employee
python
great-expectations__great_expectations
great_expectations/types/__init__.py
{ "start": 8315, "end": 9678 }
class ____(DictDot): def to_json_dict(self) -> Dict[str, JSONValues]: """Returns a JSON-serializable dict representation of the SerializableDictDot. Subclasses must implement this abstract method. Returns: A JSON-serializable dict representation of the SerializableDictDot ...
SerializableDictDot
python
pydantic__pydantic
tests/mypy/modules/plugin_success_baseConfig.py
{ "start": 2366, "end": 2507 }
class ____(BaseModel): x: int y: ClassVar[int] = 1 ClassVarModel(x=1) @dataclass(config=dict(validate_assignment=True))
ClassVarModel
python
Lightning-AI__lightning
tests/tests_pytorch/loggers/test_all.py
{ "start": 8216, "end": 12929 }
class ____(Logger): @property def name(self): return "" @property def version(self): return None def log_metrics(self, metrics, step=None) -> None: pass def log_hyperparams(self, params, *args, **kwargs) -> None: pass @mock.patch.dict(os.environ, {}) @pytest....
CustomLoggerWithoutExperiment
python
django__django
tests/i18n/test_compilation.py
{ "start": 10563, "end": 12531 }
class ____(MessageCompilationTests): @cached_property def msgfmt_version(self): # Note that msgfmt is installed via GNU gettext tools, hence the msgfmt # version should align to gettext. out, err, status = popen_wrapper( ["msgfmt", "--version"], stdout_encoding=DE...
CompilationErrorHandling
python
eventlet__eventlet
tests/mock.py
{ "start": 74003, "end": 75697 }
class ____: def __init__(self, spec, spec_set=False, parent=None, name=None, ids=None, instance=False): self.spec = spec self.ids = ids self.spec_set = spec_set self.parent = parent self.instance = instance self.name = name FunctionTypes = ( # ...
_SpecState
python
pytorch__pytorch
test/test_functionalization.py
{ "start": 2806, "end": 96834 }
class ____(TestCase): crossref = False def get_logs(self, func, *inpts, reapply_views=False, run_reinplace=False): inpts_clone = tree_map_only(torch.Tensor, torch.clone, inpts) traced_f = make_fx( _functionalize(func, reapply_views=reapply_views, crossref=self.crossref) )(*i...
TestFunctionalization
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 3326, "end": 3771 }
class ____(BaseSafeMigrationTest): app = "bad_flow_add_column_with_notnull_app" migrate_from = "0001_initial" migrate_to = "0002_add_field_notnull" def test(self) -> None: with pytest.raises( UnsafeOperationException, match="Adding TestTable.field as a not null column wi...
AddColWithNotNullTest
python
pypa__warehouse
warehouse/utils/zipfiles.py
{ "start": 628, "end": 15509 }
class ____(Exception): """Internal exception used by this module""" def _seek_check(fp: typing.IO[bytes], amt: int, /) -> None: """Call seek and check that the seeked amount is correct. Returns True if the seeked amount is less than what is expected. """ if amt < 0: # pragma: no cover ...
InvalidZipFileError
python
giampaolo__psutil
tests/test_testutils.py
{ "start": 14214, "end": 14406 }
class ____(PsutilTestCase): def test_is_namedtuple(self): assert is_namedtuple(collections.namedtuple('foo', 'a b c')(1, 2, 3)) assert not is_namedtuple(tuple())
TestOtherUtils
python
huggingface__transformers
src/transformers/models/conditional_detr/modeling_conditional_detr.py
{ "start": 46285, "end": 51190 }
class ____(ConditionalDetrPreTrainedModel): """ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a [`ConditionalDetrEncoderLayer`]. The encoder updates the flattened feature map through multiple self-attention layers. Small tweak for ConditionalDETR: ...
ConditionalDetrEncoder
python
rq__rq
tests/test_scheduler.py
{ "start": 19146, "end": 23642 }
class ____(RQTestCase): def test_enqueue_at(self): """queue.enqueue_at() puts job in the scheduled""" queue = Queue(connection=self.connection) registry = ScheduledJobRegistry(queue=queue) scheduler = RQScheduler([queue], connection=self.connection) scheduler.acquire_locks() ...
TestQueue
python
numpy__numpy
numpy/distutils/tests/test_ccompiler_opt_conf.py
{ "start": 5862, "end": 6347 }
class ____(unittest.TestCase): def __init__(self, methodName="runTest"): unittest.TestCase.__init__(self, methodName) self._setup() def _setup(self): FakeCCompilerOpt.conf_nocache = True def test_features(self): for arch, compilers in arch_compilers.items(): for...
TestConfFeatures
python
PrefectHQ__prefect
src/prefect/client/schemas/actions.py
{ "start": 10315, "end": 13663 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to update a deployment.""" @model_validator(mode="before") @classmethod def remove_old_fields(cls, values: dict[str, Any]) -> dict[str, Any]: return remove_old_deployment_fields(values) version: Optional[str] = Field(default...
DeploymentUpdate
python
PrefectHQ__prefect
src/prefect/server/schemas/actions.py
{ "start": 22216, "end": 24407 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to create a flow run from a deployment.""" # FlowRunCreate states must be provided as StateCreate objects state: Optional[StateCreate] = Field( default=None, description="The state of the flow run to create" ) name: str = Fi...
DeploymentFlowRunCreate
python
ethereum__web3.py
web3/contract/contract.py
{ "start": 17715, "end": 19533 }
class ____(BaseContractCaller): # mypy types w3: "Web3" def __init__( self, abi: ABI, w3: "Web3", address: ChecksumAddress, transaction: TxParams | None = None, block_identifier: BlockIdentifier = None, ccip_read_enabled: bool | None = None, d...
ContractCaller
python
mlflow__mlflow
mlflow/transformers/flavor_config.py
{ "start": 534, "end": 9115 }
class ____: TASK = "task" INSTANCE_TYPE = "instance_type" TORCH_DTYPE = "torch_dtype" FRAMEWORK = "framework" MODEL = "model" MODEL_TYPE = "pipeline_model_type" MODEL_BINARY = "model_binary" MODEL_NAME = "source_model_name" MODEL_REVISION = "source_model_revision" PEFT = "peft_...
FlavorKey
python
ansible__ansible
test/units/_internal/templating/test_datatag.py
{ "start": 695, "end": 5022 }
class ____(_TestDatatagTarget): later = t.cast(t.Self, Later(locals(), _TestDatatagTarget)) lazy_serializable_types: t.Annotated[ list[type[c.Collection]], ParamDesc(["lazy_type"]) ] = list( t.cast(type[c.Collection], known_type) for known_type in AnsibleSerializable._known_type_map.values(...
TestDatatagTemplar
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis26.py
{ "start": 315, "end": 1475 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis26.xlsx") self.ignore_elements = {"xl/charts/chart1.xml": ["<a:defRPr"]} def test_create_file(self): """Test the creatio...
TestCompareXLSXFiles
python
lepture__authlib
authlib/jose/rfc7516/models.py
{ "start": 3769, "end": 4381 }
class ____(dict): """Header object for JWE. Combines protected header, shared unprotected header and specific recipient's unprotected header together. """ def __init__(self, protected, unprotected, header): obj = {} if unprotected: obj.update(unprotected) if hea...
JWEHeader
python
palantir__python-language-server
test/plugins/test_symbols.py
{ "start": 396, "end": 2838 }
class ____: def __init__(self): x = 2 self.y = x def main(x): y = 2 * x return y """ def helper_check_symbols_all_scope(symbols): # All eight symbols (import sys, a, B, __init__, x, y, main, y) assert len(symbols) == 8 def sym(name): return [s for s in symbols if s['...
B
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 3966, "end": 4107 }
class ____(str, Enum): ONE_BIT = "one_bit" TWO_BITS = "two_bits" ONE_AND_HALF_BITS = "one_and_half_bits"
BinaryQuantizationEncoding
python
kamyu104__LeetCode-Solutions
Python/number-of-unique-categories.py
{ "start": 68, "end": 158 }
class ____: def haveSameCategory(self, a, b): pass # brute force
CategoryHandler
python
automl__auto-sklearn
test/test_pipeline/components/classification/test_lda.py
{ "start": 163, "end": 769 }
class ____(BaseClassificationComponentTest): __test__ = True res = dict() res["default_iris"] = 1.0 res["default_iris_iterative"] = -1 res["default_iris_proba"] = 0.5614481896257509 res["default_iris_sparse"] = -1 res["default_digits"] = 0.88585306618093507 res["default_digits_iterativ...
LDAComponentTest
python
huggingface__transformers
src/transformers/models/luke/modeling_luke.py
{ "start": 88467, "end": 96420 }
class ____(LukePreTrainedModel): def __init__(self, config): super().__init__(config) self.luke = LukeModel(config) self.dropout = nn.Dropout( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.classifier = n...
LukeForMultipleChoice
python
kamyu104__LeetCode-Solutions
Python/maximum-length-of-repeated-subarray.py
{ "start": 2273, "end": 3080 }
class ____(object): def findLength(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: int """ if len(A) > len(B): return self.findLength(B, A) def check(length): lookup = set(A[i:i+length] \ for i in xrange(len(A...
Solution3
python
huggingface__transformers
src/transformers/models/vivit/modeling_vivit.py
{ "start": 14870, "end": 15644 }
class ____(PreTrainedModel): config: VivitConfig base_model_prefix = "vivit" main_input_name = "pixel_values" input_modalities = "video" supports_gradient_checkpointing = True _no_split_modules = [] _supports_sdpa = True _supports_flash_attn = True _supports_flex_attn = True _sup...
VivitPreTrainedModel
python
astropy__astropy
astropy/modeling/tests/test_quantities_evaluation.py
{ "start": 2993, "end": 12460 }
class ____: def setup_method(self, method): self.model = MyTestModel() def test_evaluate(self): # We should be able to evaluate with anything assert_quantity_allclose(self.model(3, 5), 15) assert_quantity_allclose(self.model(4 * u.m, 5), 20 * u.m) assert_quantity_allclos...
TestInputUnits
python
openai__openai-python
src/openai/types/beta/chatkit/chat_session_chatkit_configuration.py
{ "start": 368, "end": 689 }
class ____(BaseModel): automatic_thread_titling: ChatSessionAutomaticThreadTitling """Automatic thread titling preferences.""" file_upload: ChatSessionFileUpload """Upload settings for the session.""" history: ChatSessionHistory """History retention configuration."""
ChatSessionChatKitConfiguration
python
huggingface__transformers
tests/models/janus/test_modeling_janus.py
{ "start": 13840, "end": 15462 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (JanusVQVAE,) if is_torch_available() else () has_attentions = False test_resize_embeddings = False def setUp(self): self.model_tester = JanusVQModelTester(self) self.config_tester = ConfigTester( self, ...
JanusVQModelTest
python
ray-project__ray
rllib/offline/tests/test_offline_evaluation_runner_group.py
{ "start": 239, "end": 6786 }
class ____(unittest.TestCase): def setUp(self) -> None: data_path = "offline/tests/data/cartpole/cartpole-v1_large" self.base_path = Path(__file__).parents[2] self.data_path = "local://" + self.base_path.joinpath(data_path).as_posix() # Assign the observation and action spaces. ...
TestOfflineData
python
kamyu104__LeetCode-Solutions
Python/falling-squares.py
{ "start": 2813, "end": 6041 }
class ____(object): def __init__(self, nums, query_fn=min, update_fn=lambda x, y: y, default_val=float("inf")): """ initialize your data structure here. :type nums: List[int] """ N = len(nums) self.__original_length =...
SegmentTree2
python
has2k1__plotnine
plotnine/guides/guide_legend.py
{ "start": 10894, "end": 14212 }
class ____(GuideElements): """ Access & calculate theming for the legend """ @cached_property def text(self): size = self.theme.getp(("legend_text_legend", "size")) ha = self.theme.getp(("legend_text_legend", "ha"), "center") va = self.theme.getp(("legend_text_legend", "va")...
GuideElementsLegend
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 241012, "end": 241993 }
class ____(Operation): def call(self, x): return backend.numpy.slogdet(x) def compute_output_spec(self, x): sign = KerasTensor((), dtype=x.dtype) logabsdet = KerasTensor(x.shape[:-2], dtype=x.dtype) return (sign, logabsdet) @keras_export(["keras.ops.slogdet", "keras.ops.numpy....
Slogdet
python
hynek__structlog
tests/test_frames.py
{ "start": 4821, "end": 5619 }
class ____: def test_returns_str(self): """ Always returns a native string. """ assert isinstance(_format_stack(sys._getframe()), str) def test_formats(self): """ The passed stack is formatted. """ assert _format_stack(sys._getframe()).startswith(...
TestFormatStack
python
getsentry__sentry
tests/sentry/seer/similarity/test_config.py
{ "start": 2726, "end": 4272 }
class ____(TestCase): def test_returns_false_when_no_rollout(self): """Returns False when no new version is being rolled out""" with patch("sentry.seer.similarity.config.SEER_GROUPING_NEW_VERSION", None): result = should_send_new_model_embeddings(self.project, None) assert re...
ShouldSendNewModelEmbeddingsTest
python
astropy__astropy
astropy/io/votable/tests/test_vo.py
{ "start": 25927, "end": 27344 }
class ____(TestParse): def setup_class(self): with np.errstate(over="ignore"): # https://github.com/astropy/astropy/issues/13341 votable = parse(get_pkg_data_filename("data/regression.xml")) votable.get_first_table().format = "binary" self.xmlout = bio = io.BytesIO()...
TestThroughBinary
python
pytorch__pytorch
test/test_serialization.py
{ "start": 2587, "end": 3614 }
class ____: def __init__(self, data, has_fileno=True, has_readinto=False): if has_readinto: self.readinto = self.readinto_opt if has_fileno: # Python 2's StringIO.StringIO has no fileno attribute. # This is used to test that. self.fileno = self.fileno_...
FilelikeMock
python
bokeh__bokeh
src/bokeh/models/widgets/groups.py
{ "start": 3364, "end": 3718 }
class ____(ToggleInputGroup): ''' A group of radio boxes. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) active = Nullable(Int, help=""" The index of the selected radio box, or ``None`` if not...
RadioGroup
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_dms.py
{ "start": 1622, "end": 2829 }
class ____(TestBaseDmsTrigger): EXPECTED_WAITER_NAME = "replication_complete" REPLICATION_CONFIG_ARN = "arn:aws:dms:region:account:config" def test_serialization(self): trigger = DmsReplicationCompleteTrigger(replication_config_arn=self.REPLICATION_CONFIG_ARN) classpath, kwargs = trigger.s...
TestDmsReplicationCompleteTrigger