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
ray-project__ray
python/ray/data/tests/test_dynamic_block_split.py
{ "start": 3530, "end": 13536 }
class ____(CSVDatasource): def _read_stream(self, f: "pa.NativeFile", path: str): for block in super()._read_stream(f, path): time.sleep(3) yield block # Tests that we don't block on exponential rampup when doing bulk reads. # https://github.com/ray-project/ray/issues/20625 @pytest...
SlowCSVDatasource
python
Pylons__pyramid
tests/test_config/test_actions.py
{ "start": 32447, "end": 32635 }
class ____: autocommit = False info = '' def __init__(self): self.actions = [] def action(self, *arg, **kw): self.actions.append((arg, kw))
DummyActionState
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dlp.py
{ "start": 33064, "end": 36772 }
class ____(GoogleCloudBaseOperator): """ Deletes a DeidentifyTemplate. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDLPDeleteDeidentifyTemplateOperator` :param template_id: The ID of deidentify template to be deleted...
CloudDLPDeleteDeidentifyTemplateOperator
python
pydata__xarray
xarray/testing/strategies.py
{ "start": 804, "end": 18050 }
class ____(Protocol[T_DuckArray]): def __call__( self, *, shape: "_ShapeLike", dtype: "_DTypeLikeNested", ) -> st.SearchStrategy[T_DuckArray]: ... def supported_dtypes() -> st.SearchStrategy[np.dtype]: """ Generates only those numpy dtypes which xarray can handle. ...
ArrayStrategyFn
python
pennersr__django-allauth
allauth/socialaccount/providers/reddit/provider.py
{ "start": 262, "end": 688 }
class ____(OAuth2Provider): id = "reddit" name = "Reddit" account_class = RedditAccount oauth2_adapter_class = RedditAdapter def extract_uid(self, data): return data["name"] def extract_common_fields(self, data): return dict(username=data.get("name")) def get_default_scope...
RedditProvider
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 10132, "end": 10302 }
class ____(InvalidRequestError): """A transaction has failed and needs to be rolled back before continuing. .. versionadded:: 1.4 """
PendingRollbackError
python
walkccc__LeetCode
solutions/1453. Maximum Number of Darts Inside of a Circular Dartboard/1453.py
{ "start": 87, "end": 1001 }
class ____: def numPoints(self, darts: list[list[int]], r: int) -> int: ERR = 1e-6 ans = 1 points = [Point(x, y) for x, y in darts] def dist(p: Point, q: Point) -> float: return ((p.x - q.x)**2 + (p.y - q.y)**2)**0.5 def getCircles(p: Point, q: Point) -> list[Point]: if dist(p, q) - ...
Solution
python
ray-project__ray
doc/source/ray-core/doc_code/streaming_generator.py
{ "start": 1068, "end": 1188 }
class ____: async def f(self): for i in range(5): yield i @ray.remote(max_concurrency=5)
AsyncActor
python
getsentry__sentry
tests/sentry/integrations/vsts/test_client.py
{ "start": 1184, "end": 17932 }
class ____(VstsIntegrationTestCase): @pytest.fixture(autouse=True) def _setup_metric_patch(self): with mock.patch("sentry.shared_integrations.client.base.metrics") as self.metrics: yield def test_refreshes_expired_token(self) -> None: self.assert_installation() integrati...
VstsApiClientTest
python
apache__airflow
providers/git/tests/unit/git/bundles/test_git.py
{ "start": 2705, "end": 33536 }
class ____: @classmethod def teardown_class(cls) -> None: return # TODO: Potential performance issue, converted setup_class to a setup_connections function level fixture @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db, request): # Skip setup fo...
TestGitDagBundle
python
dask__dask
dask/dataframe/tseries/resample.py
{ "start": 6670, "end": 6728 }
class ____(ResampleReduction): how = "ohlc"
ResampleOhlc
python
doocs__leetcode
solution/3100-3199/3158.Find the XOR of Numbers Which Appear Twice/Solution2.py
{ "start": 0, "end": 244 }
class ____: def duplicateNumbersXOR(self, nums: List[int]) -> int: ans = mask = 0 for x in nums: if mask >> x & 1: ans ^= x else: mask |= 1 << x return ans
Solution
python
tensorflow__tensorflow
tensorflow/python/ops/gradients_test.py
{ "start": 36707, "end": 41324 }
class ____(test_util.TensorFlowTestCase): def testNoVariables(self): with ops.Graph().as_default(): func = lambda x: array_ops.identity(x) + 5.0 input_t = constant_op.constant(2.0) result_t = func(input_t) dependent_vars = custom_gradient._get_dependent_variables( [input_t], [re...
GetDependentVariablesTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/request_builders/streams.py
{ "start": 5490, "end": 6481 }
class ____(AbstractRequestBuilder): URL = "https://api.hubapi.com/contacts/v1/lists/all/contacts/all" def __init__(self) -> None: self._filters = [] self._vid_offset = None @property def _count(self) -> str: return "count=100" def with_filter(self, filter_field: str, filte...
ContactsStreamRequestBuilder
python
pytorch__pytorch
benchmarks/dynamo/runner.py
{ "start": 38994, "end": 43697 }
class ____: """ Compares the most recent 2 benchmarks to find previously unflagged models that are now flagged. """ def __init__(self, args): self.args = args self.lookup_file = os.path.join(self.args.dashboard_archive_path, "lookup.csv") assert os.path.exists(self.lookup_fi...
RegressionDetector
python
keras-team__keras
keras/src/layers/regularization/dropout_test.py
{ "start": 125, "end": 4167 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_dropout_basics(self): self.run_layer_test( layers.Dropout, init_kwargs={ "rate": 0.2, }, input_shape=(2, 3), call_kwargs={"training": True}, ...
DropoutTest
python
nedbat__coveragepy
tests/test_html.py
{ "start": 6869, "end": 15191 }
class ____(HtmlTestHelpers, CoverageTest): """Tests of the HTML delta speed-ups.""" def setUp(self) -> None: super().setUp() # At least one of our tests monkey-patches the version of coverage.py, # so grab it here to restore it later. self.real_coverage_version = coverage.__ver...
HtmlDeltaTest
python
realpython__materials
python-copy/mutable_int.py
{ "start": 0, "end": 287 }
class ____: def __init__(self, value): self.value = value def __iadd__(self, other): self.value += other return self def __str__(self): return str(self.value) if __name__ == "__main__": x = MutableInt(40) x += 2 print(x)
MutableInt
python
getsentry__sentry
tests/flagpole/test_feature.py
{ "start": 298, "end": 11710 }
class ____: def get_is_true_context_builder( self, is_true_value: bool ) -> ContextBuilder[SimpleTestContextData]: return ContextBuilder().add_context_transformer(lambda _data: dict(is_true=is_true_value)) def test_feature_with_empty_segments(self) -> None: feature = Feature.from_fe...
TestParseFeatureConfig
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/run_operands.py
{ "start": 6667, "end": 7079 }
class ____(NewUpdatesWithRunTagsCondition): @property def base_name(self) -> str: return "any_new_update_has_run_tags" def match_candidate_runs(self, candidate_run_ids: Set[str], matching_run_ids: Set[str]) -> bool: # at least one candidate run must have matched return len(candidate...
AnyNewUpdateHasRunTagsCondition
python
gevent__gevent
src/gevent/tests/test__threadpool.py
{ "start": 15203, "end": 15497 }
class ____(TestCase): def test(self): pool = self._makeOne(1) pool.spawn(noop) gevent.sleep(0) pool.kill() from gevent import monkey @greentest.skipUnless( hasattr(gevent.threadpool, 'ThreadPoolExecutor'), "Requires ThreadPoolExecutor")
TestRefCount
python
joke2k__faker
faker/providers/user_agent/en_US/__init__.py
{ "start": 67, "end": 131 }
class ____(UserAgentProvider): # pragma: no cover pass
Provider
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/cloud_sql.py
{ "start": 20168, "end": 32571 }
class ____(LoggingMixin): """ Downloads and runs cloud-sql-proxy as subprocess of the Python process. The cloud-sql-proxy needs to be downloaded and started before we can connect to the Google Cloud SQL instance via database connection. It establishes secure tunnel connection to the database. It au...
CloudSqlProxyRunner
python
celery__celery
celery/worker/consumer/delayed_delivery.py
{ "start": 1307, "end": 10127 }
class ____(bootsteps.StartStopStep): """Bootstep that sets up native delayed delivery functionality. This component handles the setup and configuration of native delayed delivery for Celery workers. It is automatically included when quorum queues are detected in the application configuration. Resp...
DelayedDelivery
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 21151, "end": 25747 }
class ____(_MutableSetTestFixture): run_define_tables = "each" def setup_mappers(cls): foo = cls.tables.foo cls.mapper_registry.map_imperatively(Foo, foo) def test_coerce_none(self): sess = fixture_session() f1 = Foo(data=None) sess.add(f1) sess.commit() ...
_MutableSetTestBase
python
vyperlang__vyper
vyper/compiler/input_bundle.py
{ "start": 5888, "end": 7287 }
class ____(InputBundle): def _normalize_path(self, path: Path) -> Path: # normalize the path with os.path.normpath, to break down # things like "foo/bar/../x.vy" => "foo/x.vy", with all # the caveats around symlinks that os.path.normpath comes with. try: return path.resol...
FilesystemInputBundle
python
astropy__astropy
astropy/utils/console.py
{ "start": 10224, "end": 22540 }
class ____: """ A class to display a progress bar in the terminal. It is designed to be used either with the ``with`` statement:: with ProgressBar(len(items)) as bar: for item in enumerate(items): bar.update() or as a generator:: for item in ProgressBar(it...
ProgressBar
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/experiment_service.py
{ "start": 10457, "end": 12792 }
class ____(GoogleCloudBaseOperator): """ Use the Vertex AI SDK to list experiment runs in experiment. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param location: Required. The ID of the Google Cloud location that the service belongs to. :param exper...
ListExperimentRunsOperator
python
pypa__warehouse
warehouse/i18n/extensions.py
{ "start": 1939, "end": 3463 }
class ____(InternationalizationExtension): """ Replica of InternationalizationExtension which overrides a single method _install_callables to inject our own wrappers for gettext and ngettext with the _make_newer_gettext and _make_newer_ngettext defined above. Diff from original method is: ...
FallbackInternationalizationExtension
python
coleifer__peewee
tests/pwiz_integration.py
{ "start": 2721, "end": 3083 }
class ____(BaseModel): user = ForeignKeyField(column_name='user_id', field='username', model=User) text = TextField(index=True) data = IntegerField() misc = IntegerField() class Meta: table_name = 'note' indexes = ( (('user', 'data', 'misc'), False), (('user'...
Note
python
pytorch__pytorch
torch/distributions/exp_family.py
{ "start": 185, "end": 2485 }
class ____(Distribution): r""" ExponentialFamily is the abstract base class for probability distributions belonging to an exponential family, whose probability mass/density function has the form is defined below .. math:: p_{F}(x; \theta) = \exp(\langle t(x), \theta\rangle - F(\theta) + k(x)) ...
ExponentialFamily
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/spacetobatch_op_test.py
{ "start": 2954, "end": 3202 }
class ____(object): @staticmethod def space_to_batch(*args, **kwargs): return array_ops.space_to_batch(*args, **kwargs) @staticmethod def batch_to_space(*args, **kwargs): return array_ops.batch_to_space(*args, **kwargs)
PythonOpImpl
python
PyCQA__pyflakes
pyflakes/test/test_api.py
{ "start": 9375, "end": 21308 }
class ____(TestCase): """ Tests for L{check} and L{checkPath} which check a file for flakes. """ @contextlib.contextmanager def makeTempFile(self, content): """ Make a temporary file containing C{content} and return a path to it. """ fd, name = tempfile.mkstemp() ...
CheckTests
python
joerick__pyinstrument
pyinstrument/middleware.py
{ "start": 862, "end": 4239 }
class ____(MiddlewareMixin): # type: ignore def process_request(self, request): profile_dir = getattr(settings, "PYINSTRUMENT_PROFILE_DIR", None) func_or_path = getattr(settings, "PYINSTRUMENT_SHOW_CALLBACK", None) if isinstance(func_or_path, str): show_pyinstrument = import_st...
ProfilerMiddleware
python
tensorflow__tensorflow
tensorflow/python/keras/layers/recurrent.py
{ "start": 81366, "end": 91648 }
class ____(RNN): """Gated Recurrent Unit - Cho et al. 2014. There are two variants. The default one is based on 1406.1078v3 and has reset gate applied to hidden state before matrix multiplication. The other one is based on original 1406.1078v1 and has the order reversed. The second variant is compatible wit...
GRU
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_zip9.py
{ "start": 1610, "end": 3927 }
class ____(ColumnMapExpectation): """Expect values in this column to be valid zip9 string types. See https://pypi.org/project/zipcodes/ for more information. """ # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ ...
ExpectColumnValuesToBeValidZip9
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/external.py
{ "start": 6889, "end": 7152 }
class ____(graphene.ObjectType): class Meta: name = "FeatureFlag" name = graphene.NonNull(graphene.String) enabled = graphene.NonNull(graphene.Boolean) GrapheneDefinitionsSource = graphene.Enum.from_enum(DefinitionsSource)
GrapheneFeatureFlag
python
astropy__astropy
astropy/modeling/tests/test_fitters.py
{ "start": 7545, "end": 13511 }
class ____: def test_compound_model_raises_error(self): """Test that if an user tries to use a compound model, raises an error""" MESSAGE = r"Model must be simple, not compound" with pytest.raises(ValueError, match=MESSAGE): init_model1 = models.Polynomial1D(degree=2, c0=[1, 1], ...
TestLinearLSQFitter
python
automl__auto-sklearn
autosklearn/pipeline/components/data_preprocessing/rescaling/robust_scaler.py
{ "start": 731, "end": 2827 }
class ____(Rescaling, AutoSklearnPreprocessingAlgorithm): def __init__( self, q_min: float, q_max: float, random_state: Optional[Union[int, np.random.RandomState]] = None, ) -> None: from sklearn.preprocessing import RobustScaler self.q_min = q_min self.q...
RobustScalerComponent
python
cython__cython
Cython/Compiler/UtilNodes.py
{ "start": 9733, "end": 10935 }
class ____(Nodes.StatNode, LetNodeMixin): # Implements a local temporary variable scope. Imagine this # syntax being present: # let temp = VALUE: # BLOCK (can modify temp) # if temp is an object, decref # # Usually used after analysis phase, but forwards analysis methods # to its...
LetNode
python
pypa__setuptools
setuptools/config/setupcfg.py
{ "start": 26588, "end": 26695 }
class ____(SetuptoolsDeprecationWarning): _SEE_DOCS = "userguide/declarative_config.html"
_DeprecatedConfig
python
pytorch__pytorch
torch/_inductor/runtime/caching/exceptions.py
{ "start": 3519, "end": 3814 }
class ____(UserError): """Base class for errors that occur during cache value encoding operations. Raised when cache values cannot be properly encoded for storage or transmission. This includes serialization, compression, or other encoding-related failures. """
ValueEncodingError
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/schema.py
{ "start": 205645, "end": 229594 }
class ____(HasSchemaAttr): """A collection of :class:`_schema.Table` objects and their associated schema constructs. Holds a collection of :class:`_schema.Table` objects as well as an optional binding to an :class:`_engine.Engine` or :class:`_engine.Connection`. If bound, the :class:`_schema.T...
MetaData
python
kamyu104__LeetCode-Solutions
Python/largest-multiple-of-three.py
{ "start": 895, "end": 1800 }
class ____(object): def largestMultipleOfThree(self, digits): """ :type digits: List[int] :rtype: str """ def candidates_gen(r): if r == 0: return for i in xrange(10): yield [i] for i in xrange(10): ...
Solution2
python
lazyprogrammer__machine_learning_examples
supervised_class/bayes.py
{ "start": 610, "end": 2276 }
class ____(object): def fit(self, X, Y, smoothing=1e-2): N, D = X.shape self.gaussians = dict() self.priors = dict() labels = set(Y) for c in labels: current_x = X[Y == c] self.gaussians[c] = { 'mean': current_x.mean(axis=0), ...
Bayes
python
spyder-ide__spyder
spyder/api/shellconnect/main_widget.py
{ "start": 1392, "end": 7842 }
class ____(PluginMainWidget): """ Main widget to use in a plugin that shows console-specific content. Notes ----- * This is composed of a QStackedWidget to stack widgets associated to each shell widget in the console and only show one of them at a time. * The current widget in the stack w...
ShellConnectMainWidget
python
pypa__twine
twine/sdist.py
{ "start": 2069, "end": 2918 }
class ____(SDist): def read(self) -> bytes: with zipfile.ZipFile(self.filename) as sdist: # The sdist must contain a single top-level direcotry... root = os.path.commonpath(sdist.namelist()) if root in {".", "/", ""}: raise exceptions.InvalidDistribution(...
ZipSDist
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/async_job_manager.py
{ "start": 359, "end": 2635 }
class ____: """ Centralizes throttle/concurrency. Jobs call try_consume() before starting, and must call release() exactly once when they finish (success/skip/fail/timeout). """ def __init__(self, api, account_id: str, *, throttle_limit: float = 90.0, max_jobs: int = 100): self._api = api ...
APILimit
python
apache__airflow
providers/common/sql/tests/unit/common/sql/operators/test_sql.py
{ "start": 19437, "end": 28277 }
class ____: count_check = "COUNT(*) == 1000" sum_check = "col_a + col_b < col_c" checks = { "row_count_check": {"check_statement": f"{count_check}"}, "column_sum_check": {"check_statement": f"{sum_check}"}, } correct_generate_sql_query_no_partitions = f""" SELECT 'row_count_chec...
TestTableCheckOperator
python
pytorch__pytorch
torch/ao/nn/intrinsic/modules/fused.py
{ "start": 1817, "end": 2384 }
class ____(_FusedModule): r"""This is a sequential container which calls the Conv3d and ReLU modules. During quantization this will be replaced with the corresponding fused module.""" def __init__(self, conv, relu): assert ( type_before_parametrizations(conv) == Conv3d and t...
ConvReLU3d
python
kamyu104__LeetCode-Solutions
Python/count-primes.py
{ "start": 145, "end": 717 }
class ____(object): # @param {integer} n # @return {integer} def countPrimes(self, n): if n <= 2: return 0 is_prime = [True]*(n//2) cnt = len(is_prime) for i in xrange(3, n, 2): if i * i >= n: break if not is_prime[i//2]: ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 490191, "end": 490571 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("CheckRun", graphql_name="...
CheckRunEdge
python
tensorflow__tensorflow
tensorflow/python/ops/collective_ops_gpu_test.py
{ "start": 1260, "end": 12693 }
class ____(test.TestCase): @classmethod def setUpClass(cls): """Set group_size = num_gpus = 2 for all tests in this class.""" super(CollectiveOpGPUTest, cls).setUpClass() # Group size is the number of devices in a group communicating collectively. # This will be passed into the collective ops in th...
CollectiveOpGPUTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py
{ "start": 10082, "end": 10218 }
class ____: if True: print("conditional") def test(): pass # end # Test case for nested class scenario
Foo
python
great-expectations__great_expectations
great_expectations/datasource/fluent/config_str.py
{ "start": 3938, "end": 9524 }
class ____(AnyUrl, ConfigStr): # type: ignore[misc] # Mixin "validate" signature mismatch """ Special type that enables great_expectation config variable substitution for the `user` and `password` section of a URI. Example: ``` "snowflake://${MY_USER}:${MY_PASSWORD}@account/database/schema/tab...
ConfigUri
python
walkccc__LeetCode
solutions/1296. Divide Array in Sets of K Consecutive Numbers/1296.py
{ "start": 0, "end": 336 }
class ____: def isPossibleDivide(self, nums: list[int], k: int) -> bool: count = collections.Counter(nums) for start in sorted(count): value = count[start] if value > 0: for i in range(start, start + k): count[i] -= value if count[i] < 0: return False ...
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/log_manager.py
{ "start": 11471, "end": 18051 }
class ____(logging.Logger): """Centralized dispatch for logging from user code. Handles the construction of uniform structured log messages and passes them through to the underlying loggers/handlers. An instance of the log manager is made available to ops as ``context.log``. Users should not initi...
DagsterLogManager
python
pytorch__pytorch
torch/package/file_structure_representation.py
{ "start": 103, "end": 4746 }
class ____: """A file structure representation. Organized as Directory nodes that have lists of their Directory children. Directories for a package are created by calling :meth:`PackageImporter.file_structure`.""" def __init__(self, name: str, is_dir: bool): self.name = name self.is_dir...
Directory
python
astropy__astropy
astropy/io/votable/tree.py
{ "start": 64610, "end": 66592 }
class ____(SimpleElement, _UtypeProperty, _UcdProperty): """ FIELDref_ element: used inside of GROUP_ elements to refer to remote FIELD_ elements. """ _attr_list_11 = ["ref"] _attr_list_12 = _attr_list_11 + ["ucd", "utype"] _element_name = "FIELDref" _utype_in_v1_2 = True _ucd_in_v1_2 =...
FieldRef
python
automl__auto-sklearn
autosklearn/pipeline/components/feature_preprocessing/select_rates_regression.py
{ "start": 489, "end": 4039 }
class ____(AutoSklearnPreprocessingAlgorithm): def __init__( self, alpha, mode="percentile", score_func="f_regression", random_state=None ): import sklearn.feature_selection self.random_state = random_state # We don't use this self.alpha = alpha self.mode = mode ...
SelectRegressionRates
python
pytest-dev__pytest
testing/_py/test_local.py
{ "start": 50628, "end": 51576 }
class ____: def test_join_ensure(self, tmpdir, monkeypatch): if "LANG" not in os.environ: pytest.skip("cannot run test without locale") x = local(tmpdir.strpath) part = "hällo" y = x.ensure(part) assert x.join(part) == y def test_listdir(self, tmpdir): ...
TestUnicode
python
google__flatbuffers
python/flatbuffers/reflection/AdvancedFeatures.py
{ "start": 173, "end": 322 }
class ____(object): AdvancedArrayFeatures = 1 AdvancedUnionFeatures = 2 OptionalScalars = 4 DefaultVectorsAndStrings = 8
AdvancedFeatures
python
numpy__numpy
benchmarks/benchmarks/bench_array_coercion.py
{ "start": 52, "end": 1665 }
class ____(Benchmark): # More detailed benchmarks for array coercion, # some basic benchmarks are in `bench_core.py`. params = [[range(3), [1], 1, np.array([5], dtype=np.int64), np.int64(5)]] param_names = ['array_like'] int64 = np.dtype(np.int64) def time_array_invalid_kwarg(self, array_like):...
ArrayCoercionSmall
python
django__django
tests/cache/tests.py
{ "start": 111483, "end": 112855 }
class ____(SimpleTestCase): def test_without_vary_on(self): key = make_template_fragment_key("a.fragment") self.assertEqual( key, "template.cache.a.fragment.d41d8cd98f00b204e9800998ecf8427e" ) def test_with_one_vary_on(self): key = make_template_fragment_key("foo", [...
TestMakeTemplateFragmentKey
python
gevent__gevent
src/gevent/pywsgi.py
{ "start": 56929, "end": 60224 }
class ____(Environ): """ An environment that does not print its keys and values by default. Provisional API. This is intended to keep potentially sensitive information like HTTP authorization and cookies from being inadvertently printed or logged. For debugging, each instance can have...
SecureEnviron
python
apache__airflow
providers/elasticsearch/src/airflow/providers/elasticsearch/log/es_response.py
{ "start": 2871, "end": 3430 }
class ____(AttributeDict): """ The HitMeta class is used to manage and access metadata of a document. This class inherits from the AttributeDict class and provides attribute-like access to its elements. """ def __init__(self, document, exclude=("_source", "_fields")): d = {k[1:] if k.s...
HitMeta
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 44950, "end": 71479 }
class ____(NonStrictDataModel): """ :param id: Task id :type id: str :param name: Task Name :type name: str :param user: Associated user id :type user: str :param company: Company ID :type company: str :param type: Type of task. Values: 'training', 'testing' :type type: TaskT...
Task
python
getsentry__sentry
src/sentry/issue_detection/detectors/http_overhead_detector.py
{ "start": 734, "end": 877 }
class ____: """ Keep span data that will be used to store the problem together. """ span: Span delay: float
ProblemIndicator
python
openai__openai-python
src/openai/types/vector_stores/vector_store_file.py
{ "start": 547, "end": 2261 }
class ____(BaseModel): id: str """The identifier, which can be referenced in API endpoints.""" created_at: int """The Unix timestamp (in seconds) for when the vector store file was created.""" last_error: Optional[LastError] = None """The last error associated with this vector store file. ...
VectorStoreFile
python
EpistasisLab__tpot
tpot/builtin_modules/passkbinsdiscretizer.py
{ "start": 2385, "end": 3982 }
class ____(TransformerMixin, BaseEstimator ): def __init__(self, n_bins=5, encode='onehot-dense', strategy='quantile', subsample=None, random_state=None): self.n_bins = n_bins self.encode = encode self.strategy = strategy self.subsample = subsample self.random_state = random...
PassKBinsDiscretizer
python
simonw__datasette
tests/plugins/my_plugin.py
{ "start": 5166, "end": 17933 }
class ____(Facet): type = "dummy" async def suggest(self): columns = await self.get_columns(self.sql, self.params) return ( [ { "name": column, "toggle_url": self.ds.absolute_url( self.request, ...
DummyFacet
python
pypa__pip
src/pip/_vendor/rich/segment.py
{ "start": 21880, "end": 22710 }
class ____: """A simple renderable to render an iterable of segments. This class may be useful if you want to print segments outside of a __rich_console__ method. Args: segments (Iterable[Segment]): An iterable of segments. new_lines (bool, optional): Add new lines between segments. Default...
Segments
python
huggingface__transformers
src/transformers/models/deberta/modeling_deberta.py
{ "start": 32864, "end": 36467 }
class ____(DebertaPreTrainedModel): _tied_weights_keys = { "cls.predictions.decoder.bias": "cls.predictions.bias", "cls.predictions.decoder.weight": "deberta.embeddings.word_embeddings.weight", } def __init__(self, config): super().__init__(config) self.legacy = config.legac...
DebertaForMaskedLM
python
langchain-ai__langchain
libs/standard-tests/tests/unit_tests/test_embeddings.py
{ "start": 212, "end": 484 }
class ____(EmbeddingsUnitTests): @property def embeddings_class(self) -> type[Embeddings]: return DeterministicFakeEmbedding @property def embedding_model_params(self) -> dict: return {"size": 6} # embedding dimension
TestFakeEmbeddingsUnit
python
streamlit__streamlit
lib/streamlit/runtime/scriptrunner/script_runner.py
{ "start": 2338, "end": 5926 }
class ____(Enum): # "Control" events. These are emitted when the ScriptRunner's state changes. # The script started running. SCRIPT_STARTED = "SCRIPT_STARTED" # The script run stopped because of a compile error. SCRIPT_STOPPED_WITH_COMPILE_ERROR = "SCRIPT_STOPPED_WITH_COMPILE_ERROR" # The scr...
ScriptRunnerEvent
python
PyCQA__pylint
tests/functional/ext/docparams/parameter/missing_param_doc_required_no_doc_rgx_test_all.py
{ "start": 283, "end": 732 }
class ____: """test_all_docstring_rgx Function that matches "check all functions" 'no-docstring-rgx' config option No error message is emitted. """ def __init__(self, my_param: int) -> None: """ My init docstring :param my_param: My first param """ # test_fail_empt...
MyClass
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_vitals.py
{ "start": 415, "end": 9513 }
class ____(APITestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.start = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0) self.end = self.start + timedelta(hours=6) self.transaction_data = load_data("transaction", timestamp=self.start) ...
OrganizationEventsVitalsEndpointTest
python
ansible__ansible
test/units/module_utils/facts/test_collectors.py
{ "start": 3462, "end": 3835 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'apparmor'] valid_subsets = ['apparmor'] fact_namespace = 'ansible_apparmor' collector_class = ApparmorFactCollector def test_collect(self): facts_dict = super(TestApparmorFacts, self)._test_collect() self.asser...
TestApparmorFacts
python
google__pytype
pytype/rewrite/tests/test_basic.py
{ "start": 3786, "end": 4249 }
class ____(RewriteTest): """Enum tests.""" def test_member(self): self.Check(""" import enum class E(enum.Enum): X = 42 assert_type(E.X, E) """) def test_member_pyi(self): with self.DepTree([('foo.pyi', """ import enum class E(enum.Enum): X = 42 """)...
EnumTest
python
fastapi__sqlmodel
docs_src/tutorial/where/tutorial011_py310.py
{ "start": 76, "end": 1559 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str secret_name: str age: int | None = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLM...
Hero
python
langchain-ai__langchain
libs/core/langchain_core/runnables/utils.py
{ "start": 9638, "end": 13238 }
class ____(ast.NodeVisitor): """Get the source code of a lambda function.""" def __init__(self) -> None: """Initialize the visitor.""" self.source: str | None = None self.count = 0 @override def visit_Lambda(self, node: ast.Lambda) -> None: """Visit a lambda function. ...
GetLambdaSource
python
getsentry__sentry
src/sentry/attachments/redis.py
{ "start": 178, "end": 635 }
class ____(BaseAttachmentCache): def __init__(self, **options): cluster_id = options.pop("cluster_id", None) if cluster_id is None: cluster_id = getattr(settings, "SENTRY_ATTACHMENTS_REDIS_CLUSTER", "rc-short") BaseAttachmentCache.__init__(self, inner=RedisClusterCache(cluster_id...
RedisClusterAttachmentCache
python
pytorch__pytorch
test/distributed/checkpoint/e2e/test_e2e_save_and_load.py
{ "start": 2534, "end": 2875 }
class ____: def __init__(self) -> None: self.data = torch.rand(10, 10, device=device_type) def state_dict(self): return {"data": self.data} def load_state_dict(self, state_dict): self.data = state_dict["data"] def __eq__(self, other): return torch.equal(self.data, othe...
TestStatefulObj
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_scalarmath.py
{ "start": 13753, "end": 16734 }
class ____(TestCase): @skip(reason="With pytorch, 1/(0+0j) is nan + nan*j, not inf + nan*j") def test_zero_division(self): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b / a)) b = t(complex(np.inf, np.inf)) ass...
TestComplexDivision
python
numpy__numpy
tools/swig/test/testMatrix.py
{ "start": 12312, "end": 12585 }
class ____(MatrixTestCase): def __init__(self, methodName="runTest"): MatrixTestCase.__init__(self, methodName) self.typeStr = "ulongLong" self.typeCode = "Q" ######################################################################
ulongLongTestCase
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 80159, "end": 85960 }
class ____(rv_continuous): r"""Weibull minimum continuous random variable. The Weibull Minimum Extreme Value distribution, from extreme value theory (Fisher-Gnedenko theorem), is also often simply called the Weibull distribution. It arises as the limiting distribution of the rescaled minimum of iid...
weibull_min_gen
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_use_orig_params.py
{ "start": 22168, "end": 28508 }
class ____(FSDPTest): """Tests the unshard/reshard flow.""" @property def world_size(self) -> int: return 2 def _get_fsdp_models_and_optims( self, sharding_strategy: ShardingStrategy, cpu_offload: CPUOffload, ) -> tuple[FSDP, torch.optim.Optimizer, FSDP, torch.optim...
TestFSDPUseOrigParamsUnshardReshard
python
getsentry__sentry
src/sentry/plugins/bases/notify.py
{ "start": 638, "end": 698 }
class ____(forms.Form): pass
NotificationConfigurationForm
python
pypa__pip
src/pip/_vendor/pygments/lexer.py
{ "start": 27965, "end": 28364 }
class ____: """ A helper object that holds lexer position data. """ def __init__(self, text, pos, stack=None, end=None): self.text = text self.pos = pos self.end = end or len(text) # end=0 not supported ;-) self.stack = stack or ['root'] def __repr__(self): ...
LexerContext
python
run-llama__llama_index
llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-dynamodb/llama_index/storage/chat_store/dynamodb/base.py
{ "start": 797, "end": 15256 }
class ____(BaseChatStore): """ DynamoDB Chat Store. Args: table_name (str): The name of the preexisting DynamoDB table. primary_key (str, optional): The primary/partition key to use for the table. Defaults to "SessionId". profile_name (str, optional): The AWS profile to ...
DynamoDBChatStore
python
streamlit__streamlit
lib/tests/streamlit/runtime/context_util_test.py
{ "start": 834, "end": 5003 }
class ____(unittest.TestCase): @parameterized.expand( [ # Test case: URL with no page path ("https://example.com", {}, "https://example.com"), # Test case: URL with page path that matches a page ( "https://example.com/page1", {"...
ContextUtilTest
python
dagster-io__dagster
python_modules/dagster/dagster/components/lib/shim_components/asset.py
{ "start": 224, "end": 511 }
class ____(ShimScaffolder): def get_text(self, request: ScaffoldRequest) -> str: return f"""import dagster as dg @dg.asset def {request.target_path.stem}(context: dg.AssetExecutionContext) -> dg.MaterializeResult: ... """ scaffold_with(AssetScaffolder)(asset)
AssetScaffolder
python
jazzband__django-oauth-toolkit
tests/app/idp/idp/oauth.py
{ "start": 404, "end": 1703 }
class ____(OAuth2Validator): def validate_silent_login(self, request) -> None: # request is an OAuthLib.common.Request and doesn't have the session # or user of the django request. We will emulate the session and auth # middleware here, since that is what the idp is using for auth. You ...
CustomOAuth2Validator
python
sympy__sympy
sympy/combinatorics/partitions.py
{ "start": 8806, "end": 20822 }
class ____(Basic): """ This class represents an integer partition. Explanation =========== In number theory and combinatorics, a partition of a positive integer, ``n``, also called an integer partition, is a way of writing ``n`` as a list of positive integers that sum to n. Two partitions ...
IntegerPartition
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 3865, "end": 4111 }
class ____(FlexBwDConfig): """ ROCm subclass for FlexAttn backward, with AMD backend specific tuneable kernargs """ matrix_instr_nonkdim: int = 0 waves_per_eu: int = 0 kpack: int = 2 @dataclasses.dataclass
ROCmFlexBwDConfig
python
numba__numba
numba/core/typing/npdatetime.py
{ "start": 5346, "end": 5441 }
class ____(TimedeltaOrderedCmpOp): key = operator.gt @infer_global(operator.ge)
TimedeltaCmpGt
python
pypa__virtualenv
src/virtualenv/seed/wheels/util.py
{ "start": 3327, "end": 3962 }
class ____: #: the version bundled with virtualenv bundle = "bundle" embed = "embed" #: custom version handlers non_version = (bundle, embed) @staticmethod def of_version(value): return None if value in Version.non_version else value @staticmethod def as_pip_req(distributio...
Version
python
huggingface__transformers
tests/models/markuplm/test_tokenization_markuplm.py
{ "start": 1218, "end": 210630 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "microsoft/markuplm-base" tokenizer_class = MarkupLMTokenizer rust_tokenizer_class = MarkupLMTokenizerFast test_rust_tokenizer = True from_pretrained_kwargs = {"cls_token": "<s>"} test_seq2seq = False input_text = "He...
MarkupLMTokenizationTest
python
django__django
django/db/models/lookups.py
{ "start": 24773, "end": 26451 }
class ____(Lookup): def year_lookup_bounds(self, connection, year): from django.db.models.functions import ExtractIsoYear iso_year = isinstance(self.lhs, ExtractIsoYear) output_field = self.lhs.lhs.output_field if isinstance(output_field, DateTimeField): bounds = connect...
YearLookup
python
pallets__jinja
tests/test_bytecode_cache.py
{ "start": 420, "end": 644 }
class ____: def test_simple(self, env): tmpl = env.get_template("test.html") assert tmpl.render().strip() == "BAR" pytest.raises(TemplateNotFound, env.get_template, "missing.html")
TestByteCodeCache