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
ansible__ansible
test/units/_internal/_errors/test_error_utils.py
{ "start": 722, "end": 2032 }
class ____(Exception, _error_utils.ContributesToTaskResult): @property def result_contribution(self) -> c.Mapping[str, object]: return dict(msg="contributed msg") @pytest.mark.parametrize("exceptions,expected", ( ( (Exception("e0"), _TestContributesError("e1"), ValueError("e2")), d...
_TestContributesMsg
python
kubernetes-client__python
kubernetes/client/models/v1_object_meta.py
{ "start": 383, "end": 28280 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1ObjectMeta
python
numba__numba
numba/core/types/misc.py
{ "start": 12881, "end": 13336 }
class ____(Type): """ Internal only. Represents the data of the instance. The representation of ClassInstanceType contains a pointer to a ClassDataType which represents a C structure that contains all the data fields of the class instance. """ def __init__(self, classtyp): self.cla...
ClassDataType
python
crytic__slither
slither/detectors/functions/suicidal.py
{ "start": 432, "end": 2582 }
class ____(AbstractDetector): """ Unprotected function detector """ ARGUMENT = "suicidal" HELP = "Functions allowing anyone to destruct the contract" IMPACT = DetectorClassification.HIGH CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Do...
Suicidal
python
PrefectHQ__prefect
tests/runtime/test_flow_run.py
{ "start": 5754, "end": 6812 }
class ____: async def test_run_count_is_attribute(self): assert "run_count" in dir(flow_run) async def test_run_count_is_zero_when_not_set(self): assert flow_run.run_count == 0 async def test_run_count_returns_run_count_when_present_dynamically(self): assert flow_run.run_count == 0...
TestRunCount
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/gelu_test.py
{ "start": 236, "end": 603 }
class ____(op_bench.TorchBenchmarkBase): def init(self, N, C, H, W, device): self.inputs = {"input": torch.rand(N, C, H, W, device=device)} def forward(self, input): return torch.nn.functional.gelu(input) op_bench.generate_pt_test(gelu_configs_long, GeluBenchmark) if __name__ == "__main__":...
GeluBenchmark
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_reload_repository_location.py
{ "start": 15955, "end": 17374 }
class ____(ManagedTestSuite): def test_managed_grpc_reload_location(self, graphql_context): result = execute_dagster_graphql( graphql_context, RELOAD_REPOSITORY_LOCATION_QUERY, {"repositoryLocationName": main_repo_location_name()}, ) assert result ...
TestReloadRepositoriesManagedGrpc
python
ray-project__ray
python/ray/serve/_private/deployment_scheduler.py
{ "start": 25036, "end": 32015 }
class ____(DeploymentScheduler): def schedule( self, upscales: Dict[DeploymentID, List[ReplicaSchedulingRequest]], downscales: Dict[DeploymentID, DeploymentDownscaleRequest], ) -> Dict[DeploymentID, Set[ReplicaID]]: """Called for each update cycle to do batch scheduling. ...
DefaultDeploymentScheduler
python
spyder-ide__spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
{ "start": 1864, "end": 2061 }
class ____: Close = 'close' Copy = 'copy_action' Edit = 'edit_action' Preferences = 'preferences_action' Refresh = 'refresh_action' Resize = 'resize_action'
ArrayEditorActions
python
altair-viz__altair
tools/schemapi/utils.py
{ "start": 11628, "end": 32248 }
class ____: """A wrapper for inspecting a JSON schema.""" _remap_title: ClassVar[dict[str, Sequence[str]]] = {} def __init__( self, schema: Mapping[str, Any], rootschema: Mapping[str, Any] | None = None ) -> None: if not rootschema: rootschema = schema self.raw_sche...
SchemaInfo
python
Netflix__metaflow
metaflow/plugins/argo/argo_workflows.py
{ "start": 199860, "end": 205171 }
class ____(object): # https://argoproj.github.io/argo-workflows/fields/#template def __init__(self, name): tree = lambda: defaultdict(tree) self.payload = tree() self.payload["name"] = name def active_deadline_seconds(self, active_deadline_seconds): # Overall duration of a ...
Template
python
arrow-py__arrow
arrow/locales.py
{ "start": 128039, "end": 129403 }
class ____(Locale): names = ["sq", "sq-al"] past = "{0} më parë" future = "në {0}" and_word = "dhe" timeframes = { "now": "tani", "second": "sekondë", "seconds": "{0} sekonda", "minute": "minutë", "minutes": "{0} minuta", "hour": "orë", "hour...
AlbanianLocale
python
pytorch__pytorch
torch/_export/verifier.py
{ "start": 3760, "end": 12091 }
class ____(metaclass=_VerifierMeta): dialect = "ATEN" def allowed_builtin_ops(self) -> list: return [ operator.getitem, operator.add, operator.mul, operator.sub, operator.truediv, operator.ge, operator.le, o...
Verifier
python
getsentry__sentry
tests/sentry/snuba/test_discover_query.py
{ "start": 116651, "end": 128654 }
class ____(SnubaTestCase, TestCase): def setUp(self) -> None: super().setUp() self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0) self.now = before_now() event_data = load_data("transaction") # Half of duration so we don't get weird rounding...
ArithmeticTest
python
kamyu104__LeetCode-Solutions
Python/android-unlock-patterns.py
{ "start": 3682, "end": 5137 }
class ____(object): def numberOfPatterns(self, m, n): """ :type m: int :type n: int :rtype: int """ def merge(used, i): return used | (1 << i) def contain(used, i): return bool(used & (1 << i)) def convert(i, j): r...
Solution_TLE
python
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster/subschema/run_launcher.py
{ "start": 3144, "end": 3627 }
class ____(BaseModel): type: RunLauncherType config: RunLauncherConfig model_config = ConfigDict( extra="forbid", json_schema_extra={ "allOf": create_json_schema_conditionals( { RunLauncherType.CELERY: "celeryK8sRunLauncher", ...
RunLauncher
python
huggingface__transformers
tests/trainer/test_trainer.py
{ "start": 10469, "end": 11197 }
class ____: def __init__(self, thresh=0.25): self.thresh = thresh self.batch_acc = [] def __call__(self, eval_pred, compute_result): predictions, labels = eval_pred if isinstance(predictions, tuple): predictions = predictions[0] if isinstance(labels, tuple): ...
AlmostAccuracyBatched
python
great-expectations__great_expectations
tests/integration/data_sources_and_expectations/expectations/test_expect_column_values_to_not_match_like_pattern_list.py
{ "start": 863, "end": 4065 }
class ____: @pytest.mark.parametrize( "expectation", [ pytest.param( gxe.ExpectColumnValuesToNotMatchLikePatternList( column=COL_NAME, like_pattern_list=["bc"] ), id="one_pattern", ), pytest.param...
TestNormalSql
python
getsentry__sentry
src/sentry/deletions/tasks/hybrid_cloud.py
{ "start": 1586, "end": 16417 }
class ____: low: int up: int has_more: bool transaction_id: str def _get_redis_client() -> RedisCluster[str] | StrictRedis[str]: return redis.redis_clusters.get(settings.SENTRY_HYBRIDCLOUD_DELETIONS_REDIS_CLUSTER) def get_watermark_key(prefix: str, field: HybridCloudForeignKey[Any, Any]) -> str:...
WatermarkBatch
python
sqlalchemy__sqlalchemy
test/dialect/sqlite/test_reflection.py
{ "start": 1050, "end": 1814 }
class ____(fixtures.TestBase): __only_on__ = "sqlite" __backend__ = True def setup_test(self): exec_sql(testing.db, "CREATE TABLE a (id INTEGER PRIMARY KEY)") # this syntax actually works on other DBs perhaps we'd want to add # tests to test_reflection exec_sql( ...
ReflectHeadlessFKsTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F722.py
{ "start": 0, "end": 409 }
class ____: pass def f() -> "A": pass def g() -> "///": pass X: """List[int]"""'☃' = [] # Type annotations with triple quotes can contain newlines and indentation # https://github.com/python/typing-council/issues/9 y: """ int | str """ z: """( int | str ) """ invalid1: """ int | s...
A
python
altair-viz__altair
altair/expr/core.py
{ "start": 7694, "end": 7948 }
class ____(Expression): def __init__(self, name, args) -> None: super().__init__(name=name, args=args) def __repr__(self): args = ",".join(_js_repr(arg) for arg in self.args) return f"{self.name}({args})"
FunctionExpression
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solver12.py
{ "start": 248, "end": 350 }
class ____: def chain(self: _T1) -> _T1: ... def func1(p1: _T2) -> _T2: return p1.chain()
ClassA
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_ordered_dict.py
{ "start": 40983, "end": 41647 }
class ____: def __init__(self, size): super().__init__() self.size = size self.counts = dict.fromkeys(('get', 'set', 'del'), 0) def __getitem__(self, item): self.counts['get'] += 1 value = super().__getitem__(item) self.move_to_end(item) return value ...
SimpleLRUCache
python
vyperlang__vyper
vyper/builtins/functions.py
{ "start": 70591, "end": 73262 }
class ____(BuiltinFunctionT): _id = "uint2str" _inputs = [("x", IntegerT.unsigneds())] def fetch_call_return(self, node): arg_t = self.infer_arg_types(node)[0] bits = arg_t.bits len_needed = math.ceil(bits * math.log(2) / math.log(10)) return StringT(len_needed) def _tr...
Uint2Str
python
openai__openai-python
src/openai/types/responses/response_conversation_param.py
{ "start": 216, "end": 340 }
class ____(TypedDict, total=False): id: Required[str] """The unique ID of the conversation."""
ResponseConversationParam
python
pytorch__pytorch
torch/_dynamo/source.py
{ "start": 7723, "end": 8270 }
class ____(Source): random_call_index: int def guard_source(self) -> GuardSource: return GuardSource.RANDOM_VALUE def reconstruct(self, codegen: "PyCodegen") -> None: codegen.append_output(codegen.create_load(codegen.tx.output.random_values_var)) codegen.append_output(codegen.creat...
RandomValueSource
python
doocs__leetcode
solution/0700-0799/0799.Champagne Tower/Solution2.py
{ "start": 0, "end": 424 }
class ____: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: f = [poured] for i in range(1, query_row + 1): g = [0] * (i + 1) for j, v in enumerate(f): if v > 1: half = (v - 1) / 2 g[j] +...
Solution
python
getsentry__sentry
tests/sentry/snuba/test_validators.py
{ "start": 460, "end": 11447 }
class ____(TestCase): def setUp(self) -> None: self.valid_data = { "queryType": SnubaQuery.Type.ERROR.value, "dataset": Dataset.Events.value, "query": "test query", "aggregate": "count()", "timeWindow": 60, "environment": self.environme...
SnubaQueryValidatorTest
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 74958, "end": 75482 }
class ____(PrefectFilterBaseModel): """Filter by `Artifact.flow_run_id`.""" any_: Optional[list[UUID]] = Field( default=None, description="A list of flow run IDs to include" ) def _get_filter_list( self, db: "PrefectDBInterface" ) -> Iterable[sa.ColumnExpressionArgument[bool]]: ...
ArtifactFilterFlowRunId
python
plotly__plotly.py
plotly/graph_objs/layout/newselection/_line.py
{ "start": 235, "end": 4471 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.newselection" _path_str = "layout.newselection.line" _valid_props = {"color", "dash", "width"} @property def color(self): """ Sets the line color. By default uses either dark grey or white to increase contrast ...
Line
python
tensorflow__tensorflow
tensorflow/python/ops/parallel_for/control_flow_ops_test.py
{ "start": 80448, "end": 84858 }
class ____(PForTestCase): @test_util.run_v1_only("b/122612051") def test_var_loop_len(self): num_iters = array_ops.placeholder(dtypes.int32) def loop_fn(_): return sparse_tensor.SparseTensor([[0], [1], [2]], [4, 5, 6], [3]) # [0, 2, 0] pfor = pfor_contro...
SparseTest
python
tensorflow__tensorflow
tensorflow/python/ops/math_grad_test.py
{ "start": 21892, "end": 23974 }
class ____(test.TestCase): def _xlog1py_gradients(self, x, y): xlog1py_xgrad = self.evaluate( gradients.gradients(math_ops.xlog1py(x, y), x)[0]) xlog1py_ygrad = self.evaluate( gradients.gradients(math_ops.xlog1py(x, y), y)[0]) return xlog1py_xgrad, xlog1py_ygrad @test_util.run_deprecat...
Xlog1pyTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E70.py
{ "start": 1056, "end": 1193 }
class ____: match: Optional[Match] = None #: E702:2:4 while 1: 1;... #: E703:2:1 0\ ; #: E701:2:3 a = \ 5; #: with x(y) as z: ...
Foo
python
celery__celery
t/unit/backends/test_base.py
{ "start": 1958, "end": 7330 }
class ____: def setup_method(self): self.app.conf.accept_content = ['json'] def test_accept_precedence(self): # default is app.conf.accept_content accept_content = self.app.conf.accept_content b1 = BaseBackend(self.app) assert prepare_accept_content(accept_content) == ...
test_Backend_interface
python
falconry__falcon
tests/test_wsgi_interface.py
{ "start": 71, "end": 1480 }
class ____: def test_srmock(self): mock = testing.StartResponseMock() mock(falcon.HTTP_200, ()) assert mock.status == falcon.HTTP_200 assert mock.exc_info is None mock = testing.StartResponseMock() exc_info = sys.exc_info() mock(falcon.HTTP_200, (), exc_info...
TestWSGIInterface
python
keras-team__keras
keras/src/metrics/iou_metrics_test.py
{ "start": 8641, "end": 17737 }
class ____(testing.TestCase): def test_config(self): m_obj = metrics.MeanIoU(num_classes=2, name="mean_iou") self.assertEqual(m_obj.name, "mean_iou") self.assertEqual(m_obj.num_classes, 2) m_obj2 = metrics.MeanIoU.from_config(m_obj.get_config()) self.assertEqual(m_obj2.name,...
MeanIoUTest
python
dateutil__dateutil
src/dateutil/parser/_parser.py
{ "start": 19356, "end": 49747 }
class ____(object): def __init__(self, info=None): self.info = info or parserinfo() def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs): """ Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: ...
parser
python
ray-project__ray
python/ray/data/tests/preprocessors/test_chain.py
{ "start": 4909, "end": 5800 }
class ____(Preprocessor): pass def test_determine_transform_to_use(): # Test that _determine_transform_to_use doesn't throw any exceptions # and selects the transform function of the underlying preprocessor # while dealing with the nested Chain case. # Check that error is propagated correctly ...
PreprocessorWithoutTransform
python
ray-project__ray
python/ray/air/_internal/util.py
{ "start": 1788, "end": 3876 }
class ____(threading.Thread): """Supervisor thread that runs your script.""" def __init__(self, *args, error_queue, **kwargs): threading.Thread.__init__(self, *args, **kwargs) self._error_queue = error_queue self._ret = None def _propagate_exception(self, e: BaseException): ...
RunnerThread
python
gevent__gevent
src/gevent/tests/test__pywsgi.py
{ "start": 17682, "end": 17828 }
class ____(TestNoChunks): HTTP_CLIENT_VERSION = '1.0' PIPELINE_NOT_SUPPORTED_EXS = (ConnectionClosed,) EXPECT_CLOSE = True
TestNoChunks10
python
getsentry__sentry
src/sentry/integrations/jira/integration.py
{ "start": 4946, "end": 5015 }
class ____(TypedDict): value: str label: str
JiraProjectMapping
python
matplotlib__matplotlib
lib/matplotlib/patheffects.py
{ "start": 12178, "end": 13321 }
class ____(AbstractPathEffect): """ Draws a `.PathPatch` instance whose Path comes from the original PathEffect artist. """ def __init__(self, offset=(0, 0), **kwargs): """ Parameters ---------- offset : (float, float), default: (0, 0) The (x, y) offset t...
PathPatchEffect
python
apache__airflow
providers/common/sql/tests/unit/common/sql/operators/test_sql_execute.py
{ "start": 1549, "end": 14751 }
class ____(NamedTuple): id2: str value2: str @pytest.mark.parametrize( ("sql", "return_last", "split_statement", "hook_results", "hook_descriptions", "expected_results"), [ pytest.param( "select * from dummy", True, True, [Row(id="1", value="valu...
Row2
python
donnemartin__interactive-coding-challenges
online_judges/maximizing_xor/test_maximizing_xor.py
{ "start": 18, "end": 344 }
class ____(unittest.TestCase): def test_maximizing_xor(self): solution = Solution() self.assertEqual(solution.max_xor(10, 15), 7) print('Success: test_maximizing_xor') def main(): test = TestMaximizingXor() test.test_maximizing_xor() if __name__ == '__main__': main()
TestMaximizingXor
python
redis__redis-py
tests/test_cache.py
{ "start": 24272, "end": 27932 }
class ____: @pytest.mark.parametrize( "sentinel_setup", [ { "cache": DefaultCache(CacheConfig(max_size=128)), "force_master_ip": "localhost", }, { "cache": DefaultCache(CacheConfig(max_size=128)), "fo...
TestSentinelCache
python
huggingface__transformers
src/transformers/models/mobilevit/configuration_mobilevit.py
{ "start": 786, "end": 6789 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`MobileViTModel`]. It is used to instantiate a MobileViT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar c...
MobileViTConfig
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/deferred.py
{ "start": 860, "end": 3683 }
class ____(SearchStrategy[Ex]): """A strategy which may be used before it is fully defined.""" def __init__(self, definition: Callable[[], SearchStrategy[Ex]]): super().__init__() self.__wrapped_strategy: SearchStrategy[Ex] | None = None self.__in_repr: bool = False self.__defin...
DeferredStrategy
python
astropy__astropy
astropy/io/fits/tests/test_util.py
{ "start": 488, "end": 2449 }
class ____(FitsTestCase): @pytest.mark.skipif(sys.platform.startswith("win"), reason="Cannot test on Windows") def test_ignore_sigint(self): if threading.active_count() > 1: # Only check when test starts. pytest.skip("Cannot test when multiple threads are active") @ignore_sigint ...
TestUtils
python
getsentry__sentry
src/sentry/incidents/serializers/alert_rule_trigger_action.py
{ "start": 1202, "end": 10579 }
class ____(CamelSnakeModelSerializer): """ Serializer for creating/updating a trigger action. Required context: - `trigger`: The trigger related to this action. - `alert_rule`: The alert_rule related to this action. - `organization`: The organization related to this action. - `access`: An ac...
AlertRuleTriggerActionSerializer
python
jina-ai__jina
tests/unit/serve/executors/test_bad_executor_constructor.py
{ "start": 59, "end": 217 }
class ____(Executor): def __init__(self, **kwargs): super().__init__(**kwargs) @requests def foo(self, **kwargs): pass
GoodExecutor
python
pandas-dev__pandas
pandas/tests/arrays/period/test_reductions.py
{ "start": 66, "end": 981 }
class ____: def test_min_max(self): arr = period_array( [ "2000-01-03", "2000-01-03", "NaT", "2000-01-02", "2000-01-05", "2000-01-04", ], freq="D", ) result = ...
TestReductions
python
google__pytype
pytype/overlays/abc_overlay.py
{ "start": 446, "end": 991 }
class ____(overlay.Overlay): """A custom overlay for the 'abc' module.""" def __init__(self, ctx): member_map = { "abstractclassmethod": AbstractClassMethod.make, "abstractmethod": AbstractMethod.make, "abstractproperty": AbstractProperty.make, "abstractstaticmethod": AbstractSt...
ABCOverlay
python
RaRe-Technologies__gensim
gensim/test/test_similarities.py
{ "start": 19852, "end": 21254 }
class ____(_TestSimilarityABC): def setUp(self): self.cls = similarities.SparseMatrixSimilarity def test_maintain_sparsity(self): """Sparsity is correctly maintained when maintain_sparsity=True""" num_features = len(DICTIONARY) index = self.cls(CORPUS, num_features=num_features...
TestSparseMatrixSimilarity
python
google__pytype
pytype/vm_utils.py
{ "start": 1273, "end": 1550 }
class ____(enum.Enum): """Ways in which a JUMP_IF opcode may pop a value off the stack.""" NONE = enum.auto() # does not pop OR = enum.auto() # pops when the jump is not taken ALWAYS = enum.auto() # always pops @dataclasses.dataclass(eq=True, frozen=True)
PopBehavior
python
kubernetes-client__python
kubernetes/client/models/v1_custom_resource_definition_version.py
{ "start": 383, "end": 13909 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1CustomResourceDefinitionVersion
python
kamyu104__LeetCode-Solutions
Python/find-maximal-uncovered-ranges.py
{ "start": 52, "end": 665 }
class ____(object): def findMaximalUncoveredRanges(self, n, ranges): """ :type n: int :type ranges: List[List[int]] :rtype: List[List[int]] """ ranges.sort() covered = [[-1, -1]] for left, right in ranges: if covered[-1][1] < left: ...
Solution
python
getsentry__sentry
tests/sentry/api/test_authentication.py
{ "start": 21442, "end": 25331 }
class ____(TestCase): def setUp(self) -> None: super().setUp() # Create a concrete implementation for testing class TestServiceAuth(ServiceRpcSignatureAuthentication): shared_secret_setting_name = "TEST_SERVICE_RPC_SHARED_SECRET" service_name = "TestService" ...
TestServiceRpcSignatureAuthentication
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_reflection.py
{ "start": 108572, "end": 109859 }
class ____(fixtures.TablesTest): __requires__ = ("denormalized_names",) __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( quoted_name("t1", quote=True), metadata, Column("id", Integer, primary_key=True), ) ...
NormalizedNameTest
python
PrefectHQ__prefect
src/prefect/exceptions.py
{ "start": 7467, "end": 7662 }
class ____(PrefectException, RuntimeError): """ Raised when a method is called that requires a task or flow run context to be active but one cannot be found. """
MissingContextError
python
Netflix__metaflow
test/test_config/hellodecos_base.py
{ "start": 301, "end": 342 }
class ____(FlowSpec): pass
MyBaseFlowSpec
python
great-expectations__great_expectations
tests/data_context/abstract_data_context/test_data_docs_config_crud.py
{ "start": 2486, "end": 2768 }
class ____: @pytest.mark.unit def test_list_data_docs_sites(self, ephemeral_context_with_defaults: EphemeralDataContext): site_names = [d for d in ephemeral_context_with_defaults.list_data_docs_sites()] assert site_names == ["local_site"]
TestListDataDocsSites
python
astropy__astropy
astropy/coordinates/earth.py
{ "start": 716, "end": 3311 }
class ____(NamedTuple): """A namedtuple for geodetic coordinates. The longitude is increasing to the east, so west longitudes are negative. """ lon: Longitude """The longitude, increasting to the east.""" lat: Latitude """The latitude.""" height: u.Quantity """The height above th...
GeodeticLocation
python
huggingface__transformers
src/transformers/models/perceiver/modeling_perceiver.py
{ "start": 109100, "end": 110381 }
class ____(AbstractPreprocessor): """ Text preprocessing for Perceiver Encoder. Can be used to embed `inputs` and add positional encodings. The dimensionality of the embeddings is determined by the `d_model` attribute of the configuration. Args: config ([`PerceiverConfig`]): Model ...
PerceiverTextPreprocessor
python
sanic-org__sanic
sanic/pages/error.py
{ "start": 634, "end": 3939 }
class ____(BasePage): """Page for displaying an error.""" STYLE_APPEND = tracerite.html.style def __init__( self, debug: bool, title: str, text: str, request: Request, exc: Exception, ) -> None: super().__init__(debug) name = request.app....
ErrorPage
python
pytorch__pytorch
torch/testing/_internal/common_device_type.py
{ "start": 38397, "end": 41370 }
class ____(Enum): supported = 0 # Test all supported dtypes (default) unsupported = 1 # Test only unsupported dtypes supported_backward = 2 # Test all supported backward dtypes unsupported_backward = 3 # Test only unsupported backward dtypes any_one = 4 # Test precisely one supported dtype ...
OpDTypes
python
pytorch__pytorch
torch/_higher_order_ops/triton_kernel_wrap.py
{ "start": 6931, "end": 7059 }
class ____: idx: int def fake(self) -> bool: return self.idx < 0 @dataclasses.dataclass(frozen=True)
Intermediate
python
plotly__plotly.py
plotly/graph_objs/histogram/_xbins.py
{ "start": 233, "end": 8985 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram" _path_str = "histogram.xbins" _valid_props = {"end", "size", "start"} @property def end(self): """ Sets the end value for the x axis bins. The last bin may not end exactly at this value, we increment the bin...
XBins
python
kubernetes-client__python
kubernetes/client/models/v1beta1_json_patch.py
{ "start": 383, "end": 10016 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1beta1JSONPatch
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 35206, "end": 35437 }
class ____(IterableDataset): def __iter__(self): raise RuntimeError("Error in __iter__") # used with test_error_in_init def error_worker_init_fn(_): raise RuntimeError("Error in worker_init_fn")
ErrorIterableDataset
python
pytorch__pytorch
torch/fx/experimental/accelerator_partitioner.py
{ "start": 1751, "end": 9846 }
class ____(NamedTuple): """NameTuple used for returning DAG and a new fx module""" dag: DAG module_with_submodules: GraphModule """Followings are some helper functions for partition manipulation""" def reset_partition_device(partitions): for partition in partitions: partition.logical_device...
PartitionResult
python
getsentry__sentry
src/sentry/dynamic_sampling/tasks/common.py
{ "start": 6695, "end": 14847 }
class ____: """ Fetch organizations volumes in batches. A batch will return at max max_orgs elements """ def __init__( self, max_orgs: int = MAX_ORGS_PER_QUERY, time_interval: timedelta = ACTIVE_ORGS_VOLUMES_DEFAULT_TIME_INTERVAL, granularity: Granularity = ACTIVE_OR...
GetActiveOrgsVolumes
python
getsentry__sentry
tests/sentry/incidents/test_logic.py
{ "start": 9820, "end": 10801 }
class ____(BaseIncidentsTest, BaseIncidentsValidation): @cached_property def project_incident(self): self.create_event(self.now - timedelta(minutes=2)) self.create_event(self.now - timedelta(minutes=2)) self.create_event(self.now - timedelta(minutes=1)) return self.create_inciden...
BaseIncidentEventStatsTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/metrics_test.py
{ "start": 27742, "end": 35587 }
class ____(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() @test_util.run_deprecated_v1 def testVars(self): metrics.precision( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1))) _assert_metric_variables(self, ('precision/false_positives/coun...
PrecisionTest
python
pytorch__pytorch
torch/distributions/constraints.py
{ "start": 14034, "end": 14616 }
class ____(Constraint): """ Constrain to a real interval `[lower_bound, upper_bound]`. """ def __init__(self, lower_bound, upper_bound): self.lower_bound = lower_bound self.upper_bound = upper_bound super().__init__() def check(self, value): return (self.lower_bound...
_Interval
python
getsentry__sentry
src/sentry/sentry_metrics/indexer/mock.py
{ "start": 4127, "end": 4240 }
class ____(SimpleIndexer): """ Mock string indexer. Comes with a prepared set of strings. """
MockIndexer
python
falconry__falcon
falcon/stream.py
{ "start": 853, "end": 5690 }
class ____(io.IOBase): """Wrap *wsgi.input* streams to make them more robust. ``socket._fileobject`` and ``io.BufferedReader`` are sometimes used to implement *wsgi.input*. However, app developers are often burned by the fact that the `read()` method for these objects block indefinitely if either n...
BoundedStream
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-notion/llama_index/readers/notion/base.py
{ "start": 525, "end": 9091 }
class ____(BasePydanticReader): """ Notion Page reader. Reads a set of Notion pages. Args: integration_token (str): Notion integration token. """ is_remote: bool = True token: str headers: Dict[str, str] def __init__(self, integration_token: Optional[str] = None) -> None...
NotionPageReader
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 38678, "end": 39219 }
class ____(PipesStdioLogWriterChannel): """A log writer channel that writes stdout or stderr to a given file.""" def __init__( self, output_path: str, stream: Literal["stdout", "stderr"], name: str, interval: float ): self.output_path = output_path super().__init__(interval=interva...
PipesStdioFileLogWriterChannel
python
huggingface__transformers
src/transformers/models/instructblip/configuration_instructblip.py
{ "start": 9877, "end": 14704 }
class ____(PreTrainedConfig): r""" [`InstructBlipConfig`] is the configuration class to store the configuration of a [`InstructBlipForConditionalGeneration`]. It is used to instantiate a InstructBLIP model according to the specified arguments, defining the vision model, Q-Former model and language model...
InstructBlipConfig
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/matrix_exponential_op_test.py
{ "start": 6076, "end": 9364 }
class ____(test.Benchmark): shapes = [ (4, 4), (10, 10), (16, 16), (101, 101), (256, 256), (1000, 1000), (1024, 1024), (2048, 2048), (513, 4, 4), (513, 16, 16), (513, 256, 256), ] def _GenerateMatrix(self, shape): batch_shape = shape[:-2] ...
MatrixExponentialBenchmark
python
crytic__slither
slither/slithir/operations/new_elementary_type.py
{ "start": 244, "end": 790 }
class ____(Call, OperationWithLValue): def __init__(self, new_type, lvalue): assert isinstance(new_type, ElementaryType) assert is_valid_lvalue(lvalue) super().__init__() self._type = new_type self._lvalue = lvalue @property def type(self): return self._type ...
NewElementaryType
python
sympy__sympy
sympy/polys/orderings.py
{ "start": 908, "end": 1107 }
class ____(MonomialOrder): """Lexicographic order of monomials. """ alias = 'lex' is_global = True is_default = True def __call__(self, monomial): return monomial
LexOrder
python
getsentry__sentry
tests/sentry/integrations/discord/test_integration.py
{ "start": 1146, "end": 7717 }
class ____(IntegrationTestCase): provider = DiscordIntegrationProvider def setUp(self) -> None: super().setUp() self.application_id = "application-id" self.public_key = "public-key" self.bot_token = "bot-token" self.client_secret = "client-secret" options.set("di...
DiscordSetupTestCase
python
ray-project__ray
python/ray/tests/test_output.py
{ "start": 17586, "end": 18939 }
class ____: def __init__(self, *, num_threads: int = 5): self._num_threads = num_threads self._done_count = 0 self._done_lock = threading.Lock() self._done_event = threading.Event() def _spin(): for _ in range(300000000): pass for _ in ra...
A
python
encode__django-rest-framework
rest_framework/throttling.py
{ "start": 5234, "end": 5757 }
class ____(SimpleRateThrottle): """ Limits the rate of API calls that may be made by a anonymous users. The IP address of the request will be used as the unique cache key. """ scope = 'anon' def get_cache_key(self, request, view): if request.user and request.user.is_authenticated: ...
AnonRateThrottle
python
automl__auto-sklearn
test/test_util/test_logging.py
{ "start": 134, "end": 1667 }
class ____(unittest.TestCase): def test_setup_logger(self): # Test that setup_logger function correctly configures the logger # according to the given dictionary, and uses the default # logging.yaml file if logging_config is not specified. with open( os.path.join(os.path...
LoggingTest
python
allegroai__clearml
clearml/backend_api/services/v2_23/workers.py
{ "start": 13886, "end": 25261 }
class ____(NonStrictDataModel): """ :param id: Worker ID :type id: str :param user: Associated user (under whose credentials are used by the worker daemon) :type user: IdNameEntry :param company: Associated company :type company: IdNameEntry :param ip: IP of the worker :type ...
Worker
python
mlflow__mlflow
mlflow/gateway/providers/base.py
{ "start": 432, "end": 2918 }
class ____(ABC): """ Base class for MLflow Gateway providers. """ NAME: str = "" SUPPORTED_ROUTE_TYPES: tuple[str, ...] CONFIG_TYPE: type[ConfigModel] def __init__(self, config: EndpointConfig): if self.NAME == "": raise ValueError( f"{self.__class__.__n...
BaseProvider
python
spack__spack
lib/spack/spack/util/compression.py
{ "start": 16640, "end": 16987 }
class ____(CompressedFileTypeInterface): _MAGIC_NUMBER = b"\x42\x5a\x68" extension = "bz2" name = "bzip2 compressed data" def peek(self, stream: BinaryIO, num_bytes: int) -> Optional[io.BytesIO]: if BZ2_SUPPORTED: return _decompressed_peek(bz2.BZ2File(stream), stream, num_bytes) ...
BZipFileType
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 33461, "end": 33693 }
class ____(PrefectBaseModel): """Filter by `ArtifactCollection.task_run_id`.""" any_: Optional[List[UUID]] = Field( default=None, description="A list of task run IDs to include" )
ArtifactCollectionFilterTaskRunId
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol10.py
{ "start": 133, "end": 224 }
class ____(Protocol): def a(self) -> None: ... def b(self) -> None: ...
ProtocolBase
python
tensorflow__tensorflow
tensorflow/python/data/benchmarks/from_tensor_slices_benchmark.py
{ "start": 2353, "end": 5958 }
class ____(benchmark_base.DatasetBenchmarkBase): """Benchmarks for `tf.data.Dataset.from_tensor_slices()`.""" def benchmark_slice_repeat_batch(self): input_size = 10000 batch_size = 100 num_epochs = 100 num_elements = input_size * num_epochs // batch_size input_data = np.random.randn(input_siz...
FromTensorSlicesBenchmark
python
getsentry__sentry
src/sentry/integrations/msteams/webhook.py
{ "start": 3255, "end": 3382 }
class ____(MsTeamsIntegrationAnalytics): pass @analytics.eventclass("integrations.msteams.archive")
MsTeamsIntegrationResolve
python
huggingface__transformers
src/transformers/models/pop2piano/modeling_pop2piano.py
{ "start": 23858, "end": 27674 }
class ____(PreTrainedModel): config: Pop2PianoConfig base_model_prefix = "transformer" output_modalities = ("audio",) supports_gradient_checkpointing = True _can_compile_fullgraph = False _no_split_modules = ["Pop2PianoBlock"] _keep_in_fp32_modules = ["wo"] @torch.no_grad() def _in...
Pop2PianoPreTrainedModel
python
pdm-project__pdm
src/pdm/resolver/base.py
{ "start": 887, "end": 2154 }
class ____(abc.ABC): """The resolver class.""" environment: BaseEnvironment """The environment instance.""" requirements: list[Requirement] """The list of requirements to resolve.""" update_strategy: str """The update strategy to use [all|reuse|eager|reuse-installed].""" strategies: set...
Resolver
python
scrapy__scrapy
tests/spiders.py
{ "start": 11753, "end": 12780 }
class ____(MockServerSpider, CrawlSpider): """ A CrawlSpider which overrides the 'parse' method """ name = "crawl_spider_with_parse_method" custom_settings: dict = { "RETRY_HTTP_CODES": [], # no need to retry } rules = (Rule(LinkExtractor(), callback="parse", follow=True),) as...
CrawlSpiderWithParseMethod
python
openai__openai-python
src/openai/types/responses/response_computer_tool_call.py
{ "start": 3092, "end": 3296 }
class ____(BaseModel): text: str """The text to type.""" type: Literal["type"] """Specifies the event type. For a type action, this property is always set to `type`. """
ActionType
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_P.py
{ "start": 1375, "end": 2780 }
class ____(Benchmark): r""" Pathological objective function. This class defines the Pathological [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Pathological}}(x) = \sum_{i=1}^{n -1} \frac{\sin^{2}\left( \sqrt{100...
Pathological
python
anthropics__anthropic-sdk-python
src/anthropic/types/message_create_params.py
{ "start": 10675, "end": 11036 }
class ____(MessageCreateParamsBase): stream: Required[Literal[True]] """Whether to incrementally stream the response using server-sent events. See [streaming](https://docs.claude.com/en/api/messages-streaming) for details. """ MessageCreateParams = Union[MessageCreateParamsNonStreaming, MessageCreate...
MessageCreateParamsStreaming