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
getsentry__sentry
src/sentry/api/bases/project.py
{ "start": 3356, "end": 3657 }
class ____(ProjectPermission): scope_map = { "GET": ["project:read", "project:write", "project:admin"], "POST": ["project:write", "project:admin"], "PUT": ["project:write", "project:admin"], "DELETE": ["project:write", "project:admin"], }
ProjectSettingPermission
python
keras-team__keras
keras/src/layers/core/reversible_embedding.py
{ "start": 278, "end": 14168 }
class ____(layers.Embedding): """An embedding layer which can project backwards to the input dim. This layer is an extension of `keras.layers.Embedding` for language models. This layer can be called "in reverse" with `reverse=True`, in which case the layer will linearly project from `output_dim` back t...
ReversibleEmbedding
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py
{ "start": 7591, "end": 9496 }
class ____(BaseConfig): config_path: str = config_path deployment_mode: Optional[str] = deployment_mode configured_catalog_path: Optional[str] = configured_catalog_path empty_streams: Set[EmptyStreamConfiguration] = Field( default_factory=set, description="We validate that all streams has record...
BasicReadTestConfig
python
PyCQA__pylint
tests/functional/c/consider/consider_iterating_dictionary.py
{ "start": 2603, "end": 3768 }
class ____: def a_function(self): class InnerClass: def another_function(self): def inner_function(): another_metadata = {} print("a" not in list(another_metadata.keys())) # [consider-iterating-dictionary] print("a" not ...
AClass
python
langchain-ai__langchain
libs/core/langchain_core/callbacks/manager.py
{ "start": 17392, "end": 18580 }
class ____(BaseRunManager): """Sync Run Manager.""" def on_text( self, text: str, **kwargs: Any, ) -> None: """Run when a text is received. Args: text: The received text. **kwargs: Additional keyword arguments. """ if not self...
RunManager
python
huggingface__transformers
src/transformers/models/mask2former/image_processing_mask2former.py
{ "start": 13477, "end": 58324 }
class ____(BaseImageProcessor): r""" Constructs a Mask2Former image processor. The image processor can be used to prepare image(s) and optional targets for the model. This image processor inherits from [`BaseImageProcessor`] which contains most of the main methods. Users should refer to this superc...
Mask2FormerImageProcessor
python
huggingface__transformers
src/transformers/convert_slow_tokenizer.py
{ "start": 33268, "end": 34032 }
class ____(SpmConverter): def vocab(self, proto): vocab = [ ("<pad>", 0.0), ("<unk>", 0.0), ("<s>", 0.0), ("</s>", 0.0), ] vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]] return vocab def unk_id(self, proto): ...
SeamlessM4TConverter
python
wandb__wandb
wandb/vendor/pygments/lexers/lisp.py
{ "start": 132102, "end": 140665 }
class ____(RegexLexer): """An xtlang lexer for the `Extempore programming environment <http://extempore.moso.com.au>`_. This is a mixture of Scheme and xtlang, really. Keyword lists are taken from the Extempore Emacs mode (https://github.com/extemporelang/extempore-emacs-mode) .. versionadded:...
XtlangLexer
python
mlflow__mlflow
mlflow/data/polars_dataset.py
{ "start": 4482, "end": 11963 }
class ____(Dataset, PyFuncConvertibleDatasetMixin): """A polars DataFrame for use with MLflow Tracking.""" def __init__( self, df: pl.DataFrame, source: DatasetSource, targets: str | None = None, name: str | None = None, digest: str | None = None, predict...
PolarsDataset
python
pytorch__pytorch
torch/testing/_internal/common_pruning.py
{ "start": 3735, "end": 4796 }
class ____(nn.Module): r"""Model with only Linear layers, some with bias, some in a Sequential and some following. Activation functions modules in between each Linear in the Sequential, and functional activationals are called in between each outside layer. Used to test pruned Linear(Bias)-Activation-Lin...
LinearActivationFunctional
python
run-llama__llama_index
llama-index-cli/llama_index/cli/rag/base.py
{ "start": 1522, "end": 13132 }
class ____(BaseModel): """ CLI tool for chatting with output of a IngestionPipeline via a RetrieverQueryEngine. """ ingestion_pipeline: IngestionPipeline = Field( description="Ingestion pipeline to run for RAG ingestion." ) verbose: bool = Field( description="Whether to print ou...
RagCLI
python
sphinx-doc__sphinx
sphinx/environment/collectors/__init__.py
{ "start": 314, "end": 3219 }
class ____: """An EnvironmentCollector is a specific data collector from each document. It gathers data and stores :py:class:`BuildEnvironment <sphinx.environment.BuildEnvironment>` as a database. Examples of specific data would be images, download files, section titles, metadatas, index entries an...
EnvironmentCollector
python
pennersr__django-allauth
tests/apps/socialaccount/providers/discord/tests.py
{ "start": 2015, "end": 3552 }
class ____(DiscordTests, TestCase): provider_id = DiscordProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """{ "id": "80351110224678912", "username": "Nelly", "discriminator": "1337", "avatar": "8342...
OldDiscordTests
python
getsentry__sentry
src/sentry/preprod/api/models/project_preprod_build_details_models.py
{ "start": 512, "end": 585 }
class ____(BaseModel): has_proguard_mapping: bool = True
AndroidAppInfo
python
huggingface__transformers
tests/models/bart/test_modeling_bart.py
{ "start": 8249, "end": 15788 }
class ____(unittest.TestCase): vocab_size = 99 def _get_config_and_data(self): input_ids = torch.tensor( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], ...
BartHeadTests
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 18324, "end": 18707 }
class ____(Literal): """A constant template string.""" fields = ("data",) data: str def as_const(self, eval_ctx: EvalContext | None = None) -> str: eval_ctx = get_eval_context(self, eval_ctx) if eval_ctx.volatile: raise Impossible() if eval_ctx.autoescape: ...
TemplateData
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 43840, "end": 44525 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("zh-TW") Faker.seed(0) def test_day(self): day = self.fake.day_of_week() assert day in ZhTwProvider.DAY_NAMES.values() def test_month(self): month = self.fake.month_name() assert month in ZhTw...
TestZhTw
python
apache__airflow
providers/databricks/tests/unit/databricks/plugins/test_databricks_workflow.py
{ "start": 15157, "end": 18595 }
class ____: """Test Databricks Workflow Plugin functionality specific to Airflow 2.x.""" def test_plugin_operator_extra_links_full_functionality(self): """Test that all operator_extra_links are present in Airflow 2.x.""" plugin = DatabricksWorkflowPlugin() # In Airflow 2.x, all links s...
TestDatabricksWorkflowPluginAirflow2
python
realpython__materials
python-getter-setter/employee.py
{ "start": 0, "end": 120 }
class ____: def __init__(self, name, birth_date): self.name = name self.birth_date = birth_date
Employee
python
Netflix__metaflow
metaflow/runner/deployer.py
{ "start": 3307, "end": 5060 }
class ____(metaclass=DeployerMeta): """ Use the `Deployer` class to configure and access one of the production orchestrators supported by Metaflow. Parameters ---------- flow_file : str Path to the flow file to deploy, relative to current directory. show_output : bool, default True ...
Deployer
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 307719, "end": 308815 }
class ____: def test_entropy(self): # Test that dweibull entropy follows that of weibull_min. # (Generic tests check that the dweibull entropy is consistent # with its PDF. As for accuracy, dweibull entropy should be just # as accurate as weibull_min entropy. Checks of accuracy aga...
TestDweibull
python
pandas-dev__pandas
pandas/tests/indexing/interval/test_interval_new.py
{ "start": 187, "end": 8134 }
class ____: @pytest.fixture def series_with_interval_index(self): """ Fixture providing a Series with an IntervalIndex. """ return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) def test_loc_with_interval(self, series_with_interval_index, indexer_sl): ...
TestIntervalIndex
python
keras-team__keras
keras/src/layers/convolutional/conv2d.py
{ "start": 179, "end": 6251 }
class ____(BaseConv): """2D convolution layer. This layer creates a convolution kernel that is convolved with the layer input over a 2D spatial (or temporal) dimension (height and width) to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finall...
Conv2D
python
huggingface__transformers
tests/models/timesfm/test_modeling_timesfm.py
{ "start": 1024, "end": 4315 }
class ____: def __init__( self, parent, patch_length: int = 32, context_length: int = 512, horizon_length: int = 128, freq_size: int = 3, num_hidden_layers: int = 1, hidden_size: int = 16, intermediate_size: int = 32, head_dim: int = 8,...
TimesFmModelTester
python
dagster-io__dagster
python_modules/libraries/dagster-azure/dagster_azure/adls2/file_manager.py
{ "start": 1304, "end": 4648 }
class ____(FileManager): def __init__(self, adls2_client: DataLakeServiceClient, file_system: str, prefix: str): self._client = adls2_client self._file_system = check.str_param(file_system, "file_system") self._prefix = check.str_param(prefix, "prefix") self._local_handle_cache: dict...
ADLS2FileManager
python
jazzband__django-waffle
waffle/tests/test_testutils.py
{ "start": 10392, "end": 10599 }
class ____(OverrideFlagOnClassTestsMixin, TransactionTestCase): """ Run tests with Django TransactionTestCase """
OverrideFlagOnClassTransactionTestCase
python
scikit-learn__scikit-learn
sklearn/ensemble/tests/test_stacking.py
{ "start": 9808, "end": 10023 }
class ____(RegressorMixin, BaseEstimator): def fit(self, X, y): self.reg = DummyRegressor() return self.reg.fit(X, y) def predict(self, X): return np.ones(X.shape[0])
NoWeightRegressor
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call.py
{ "start": 2944, "end": 8110 }
class ____: """Test retry logic with wrap_model_call.""" def test_simple_retry_on_error(self) -> None: """Test middleware that retries once on error.""" call_count = {"value": 0} class FailOnceThenSucceed(GenericFakeChatModel): def _generate(self, messages, **kwargs): ...
TestRetryLogic
python
getsentry__sentry
tests/acceptance/test_issue_details.py
{ "start": 410, "end": 8869 }
class ____(AcceptanceTestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() patcher = patch("django.utils.timezone.now", return_value=now) patcher.start() self.addCleanup(patcher.stop) self.user = self.create_user("foo@example.com") self.org = self.create_...
IssueDetailsTest
python
sympy__sympy
sympy/functions/special/error_functions.py
{ "start": 59306, "end": 61621 }
class ____(TrigonometricIntegral): r""" Sinh integral. Explanation =========== This function is defined by .. math:: \operatorname{Shi}(z) = \int_0^z \frac{\sinh{t}}{t} \mathrm{d}t. It is an entire function. Examples ======== >>> from sympy import Shi >>> from sympy.abc...
Shi
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/metaclass10.py
{ "start": 261, "end": 410 }
class ____(EnumMeta): def __getitem__(cls: type[_EnumMemberT], name: str) -> _EnumMemberT: return EnumMeta.__getitem__(cls, name)
EnumMeta2
python
getsentry__sentry
tests/sentry/dashboards/endpoints/test_organization_dashboard_details.py
{ "start": 4265, "end": 30407 }
class ____(OrganizationDashboardDetailsTestCase): def test_get(self) -> None: response = self.do_request("get", self.url(self.dashboard.id)) assert response.status_code == 200, response.content self.assert_serialized_dashboard(response.data, self.dashboard) assert len(response.data[...
OrganizationDashboardDetailsGetTest
python
huggingface__transformers
src/transformers/hyperparameter_search.py
{ "start": 2066, "end": 2476 }
class ____(HyperParamSearchBackendBase): name = "ray" pip_package = "'ray[tune]'" @staticmethod def is_available(): return is_ray_tune_available() def run(self, trainer, n_trials: int, direction: str, **kwargs): return run_hp_search_ray(trainer, n_trials, direction, **kwargs) ...
RayTuneBackend
python
django__django
tests/forms_tests/field_tests/test_multivaluefield.py
{ "start": 1841, "end": 7406 }
class ____(SimpleTestCase): @classmethod def setUpClass(cls): cls.field = ComplexField(widget=ComplexMultiWidget()) super().setUpClass() def test_clean(self): self.assertEqual( self.field.clean(["some text", ["J", "P"], ["2007-04-25", "6:24:00"]]), "some text...
MultiValueFieldTest
python
lxml__lxml
src/lxml/html/tests/test_html5parser.py
{ "start": 13440, "end": 13577 }
class ____: def __init__(self, namespaceHTMLElements=True): self.namespaceHTMLElements = namespaceHTMLElements
DummyTreeBuilder
python
huggingface__transformers
src/transformers/models/mra/modeling_mra.py
{ "start": 30004, "end": 30795 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.h...
MraPredictionHeadTransform
python
celery__celery
t/smoke/conftest.py
{ "start": 663, "end": 1010 }
class ____(CeleryTestSetup): def ready(self, *args, **kwargs) -> bool: # Force false, false, true return super().ready( ping=False, control=False, docker=True, ) @pytest.fixture def celery_setup_cls() -> type[CeleryTestSetup]: # type: ignore return ...
SmokeTestSetup
python
kamyu104__LeetCode-Solutions
Python/all-ancestors-of-a-node-in-a-directed-acyclic-graph.py
{ "start": 51, "end": 911 }
class ____(object): def getAncestors(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: List[List[int]] """ def iter_dfs(adj, i, result): lookup = [False]*len(adj) stk = [i] while stk: u = stk.pop...
Solution
python
doocs__leetcode
solution/0300-0399/0371.Sum of Two Integers/Solution.py
{ "start": 0, "end": 262 }
class ____: def getSum(self, a: int, b: int) -> int: a, b = a & 0xFFFFFFFF, b & 0xFFFFFFFF while b: carry = ((a & b) << 1) & 0xFFFFFFFF a, b = a ^ b, carry return a if a < 0x80000000 else ~(a ^ 0xFFFFFFFF)
Solution
python
numpy__numpy
numpy/f2py/tests/test_semicolon_split.py
{ "start": 1056, "end": 1627 }
class ____(util.F2PyTest): suffix = ".pyf" module_name = "callstatement" code = f""" python module {module_name} usercode ''' void foo(int* x) {{ }} ''' interface subroutine foo(x) intent(c) foo integer intent(out) :: x callprotoargument int* c...
TestCallstatement
python
PyCQA__pylint
tests/functional/s/super/super_init_not_called.py
{ "start": 1691, "end": 1846 }
class ____(Base): def __init__(self, param: int, param_two: str) -> None: self.param = param + 1 self.param_two = param_two[::-1]
Derived
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1493746, "end": 1495230 }
class ____(sgqlc.types.Type, Node): """A record that is promoted on a GitHub Sponsors profile.""" __schema__ = github_schema __field_names__ = ("created_at", "description", "featureable", "position", "sponsors_listing", "updated_at") created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphq...
SponsorsListingFeaturedItem
python
pyca__cryptography
tests/x509/test_x509.py
{ "start": 238496, "end": 242035 }
class ____: def test_init_empty(self): with pytest.raises(ValueError): x509.RelativeDistinguishedName([]) def test_init_not_nameattribute(self): with pytest.raises(TypeError): x509.RelativeDistinguishedName( ["not-a-NameAttribute"] # type:ignore[list-ite...
TestRelativeDistinguishedName
python
django__django
django/db/models/lookups.py
{ "start": 16530, "end": 16904 }
class ____: """ Allow floats to work as query values for IntegerField. Without this, the decimal portion of the float would always be discarded. """ def get_prep_lookup(self): if isinstance(self.rhs, float): self.rhs = math.ceil(self.rhs) return super().get_prep_lookup()...
IntegerFieldFloatRounding
python
pytorch__pytorch
test/onnx/test_onnx_opset.py
{ "start": 2159, "end": 21713 }
class ____(pytorch_test_common.ExportTestCase): def test_opset_fallback(self): class MyModule(Module): def forward(self, x): return torch.isnan(x) ops = [{"op_name": "IsNaN"}] ops = {9: ops, 10: ops} x = torch.tensor([1.0, float("nan"), 2.0]) chec...
TestONNXOpset
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 234159, "end": 238025 }
class ____(sgqlc.types.Input): """A description of a set of changes to a file tree to be made as part of a git commit, modeled as zero or more file `additions` and zero or more file `deletions`. Both fields are optional; omitting both will produce a commit with no file changes. `deletions` and `ad...
FileChanges
python
falconry__falcon
examples/look/look/images.py
{ "start": 88, "end": 700 }
class ____: def __init__(self, image_store): self._image_store = image_store def on_get(self, req, resp): max_size = req.get_param_as_int('maxsize', min_value=1, default=-1) images = self._image_store.list(max_size) doc = {'images': [{'href': '/images/' + image} for image in ima...
Collection
python
Textualize__textual
src/textual/widgets/_data_table.py
{ "start": 7771, "end": 7924 }
class ____: """Metadata for a row in the DataTable.""" key: RowKey height: int label: Text | None = None auto_height: bool = False
Row
python
getsentry__sentry
tests/sentry/issues/test_run.py
{ "start": 1421, "end": 5937 }
class ____(TestCase, OccurrenceTestMixin): def build_mock_message( self, data: MutableMapping[str, Any] | None, topic: ArroyoTopic | None = None ) -> mock.Mock: message = mock.Mock() message.value.return_value = json.dumps(data) if topic: message.topic.return_value = ...
TestOccurrenceConsumer
python
kubernetes-client__python
kubernetes/client/models/v1beta1_device_request_allocation_result.py
{ "start": 383, "end": 17712 }
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...
V1beta1DeviceRequestAllocationResult
python
aimacode__aima-python
learning.py
{ "start": 14488, "end": 27263 }
class ____: """A leaf of a decision tree holds just a result.""" def __init__(self, result): self.result = result def __call__(self, example): return self.result def display(self): print('RESULT =', self.result) def __repr__(self): return repr(self.result) def D...
DecisionLeaf
python
plotly__plotly.py
plotly/io/_base_renderers.py
{ "start": 23222, "end": 24435 }
class ____(HtmlRenderer): def __init__( self, connected=True, config=None, auto_play=False, post_script=None, animation_opts=None, ): super(SphinxGalleryHtmlRenderer, self).__init__( connected=connected, full_html=False, ...
SphinxGalleryHtmlRenderer
python
catalyst-team__catalyst
examples/detection/models/yolo_x.py
{ "start": 1820, "end": 2536 }
class ____(nn.Module): # Standard bottleneck def __init__( self, in_channels, out_channels, shortcut=True, expansion=0.5, depthwise=False, act="silu", ): super().__init__() hidden_channels = int(out_channels * expansion) Conv = ...
Bottleneck
python
huggingface__transformers
src/transformers/data/processors/squad.py
{ "start": 17265, "end": 22937 }
class ____(DataProcessor): """ Processor for the SQuAD data set. overridden by SquadV1Processor and SquadV2Processor, used by the version 1.1 and version 2.0 of SQuAD, respectively. """ train_file = None dev_file = None def _get_example_from_tensor_dict(self, tensor_dict, evaluate=False): ...
SquadProcessor
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 45215, "end": 45624 }
class ____(PrefectBaseModel): """Filter criteria definition for a work queue.""" tags: Optional[list[str]] = Field( default=None, description="Only include flow runs with these tags in the work queue.", ) deployment_ids: Optional[list[UUID]] = Field( default=None, descri...
QueueFilter
python
PyCQA__pylint
pylint/pyreverse/inspector.py
{ "start": 14205, "end": 16358 }
class ____(AbstractRelationshipHandler): """Handle aggregation relationships where parent receives child objects.""" def handle( self, node: nodes.AssignAttr | nodes.AssignName, parent: nodes.ClassDef ) -> None: # If the node is not part of an assignment, pass to next handler if not...
AggregationsHandler
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 28126, "end": 28910 }
class ____(MixinSequenceOfValues): """ y-axis tick labels Parameters ---------- theme_element : element_text Notes ----- Use the `margin` to control the gap between the ticks and the text. e.g. ```python theme(axis_text_y=element_text(margin={"r": 5, "units": "pt"})) `...
axis_text_y
python
bokeh__bokeh
src/bokeh/core/property/bases.py
{ "start": 14644, "end": 17486 }
class ____(Property[T]): """ A base class for Properties that have type parameters, e.g. ``List(String)``. """ _type_params: list[Property[Any]] def __init__(self, *type_params: TypeOrInst[Property[T]], default: Init[T] = Intrinsic, help: str | None = None) -> None: _type_params = [ self._val...
ParameterizedProperty
python
mlflow__mlflow
mlflow/entities/multipart_upload.py
{ "start": 1273, "end": 1923 }
class ____: upload_id: str | None credentials: list[MultipartUploadCredential] def to_proto(self): response = ProtoCreateMultipartUpload.Response() if self.upload_id: response.upload_id = self.upload_id response.credentials.extend([credential.to_proto() for credential in...
CreateMultipartUploadResponse
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/asyncpg.py
{ "start": 12744, "end": 12818 }
class ____(_AsyncpgNumericCommon, sqltypes.Numeric): pass
AsyncpgNumeric
python
langchain-ai__langchain
libs/core/langchain_core/callbacks/manager.py
{ "start": 34489, "end": 35809 }
class ____(ParentRunManager, RetrieverManagerMixin): """Callback manager for retriever run.""" def on_retriever_end( self, documents: Sequence[Document], **kwargs: Any, ) -> None: """Run when retriever ends running. Args: documents: The retrieved documen...
CallbackManagerForRetrieverRun
python
pandas-dev__pandas
pandas/tests/window/test_pairwise.py
{ "start": 6830, "end": 16169 }
class ____: # GH 7738 @pytest.mark.parametrize("f", [lambda x: x.cov(), lambda x: x.corr()]) def test_no_flex(self, pairwise_frames, pairwise_target_frame, f): # DataFrame methods (which do not call flex_binary_moment()) result = f(pairwise_frames) tm.assert_index_equal(result.index...
TestPairwise
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_C.py
{ "start": 17137, "end": 18237 }
class ____(Benchmark): r""" Cube objective function. This class defines the Cube global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Cube}}(x) = 100(x_2 - x_1^3)^2 + (1 - x1)^2 Here, :math:`n` represents the number of dimensi...
Cube
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 294440, "end": 297133 }
class ____: def setup_method(self): self.rng = np.random.default_rng(7186715712) # gh-6227 def test_logpdf(self): y = stats.rayleigh.logpdf(50) assert_allclose(y, -1246.0879769945718) def test_logsf(self): y = stats.rayleigh.logsf(50) assert_allclose(y, -1250) ...
TestRayleigh
python
pytorch__pytorch
torch/_dynamo/source.py
{ "start": 15104, "end": 15840 }
class ____(AttrSource): pass # This source is intended to be used in places where a source is needed but it is expected # that the symbol will be simplified out later on. Symbols with ephemeral sources are # prioritized to be simplified out when e.g. compared against a symbol without an ephemeral # source. Guardi...
UnspecializedParamBufferSource
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_type_check.py
{ "start": 4217, "end": 5120 }
class ____(TestCase): def test_real(self): y = np.random.rand( 10, ) assert_array_equal(y, np.real(y)) y = np.array(1) out = np.real(y) assert_array_equal(y, out) assert_(isinstance(out, np.ndarray)) y = 1 out = np.real(y) ...
TestReal
python
pdm-project__pdm
src/pdm/cli/commands/venv/backends.py
{ "start": 4885, "end": 5533 }
class ____(Backend): def pip_args(self, with_pip: bool) -> Iterable[str]: if with_pip: return () return ("--no-pip", "--no-setuptools", "--no-wheel") def perform_create(self, location: Path, args: tuple[str, ...], prompt: str | None = None) -> None: prompt_option = (f"--prom...
VirtualenvBackend
python
numba__numba
numba/tests/test_dyn_array.py
{ "start": 31385, "end": 33526 }
class ____(ConstructorLikeBaseTest, TestCase): def check_result_value(self, ret, expected): np.testing.assert_equal(ret, expected) def test_like(self): def func(arr): return np.full_like(arr, 3.5) self.check_like(func, np.float64) # Not supported yet. @unittest.exp...
TestNdFullLike
python
django-import-export__django-import-export
tests/core/tests/resources.py
{ "start": 1820, "end": 2459 }
class ____(resources.ModelResource): class Meta: model = Author @classmethod def widget_from_django_field(cls, f, default=widgets.Widget): if f.name == "name": return HarshRussianWidget result = default internal_type = ( f.get_internal_type() ...
AuthorResourceWithCustomWidget
python
giampaolo__psutil
tests/test_posix.py
{ "start": 17047, "end": 17287 }
class ____(PsutilTestCase): def test_getpagesize(self): pagesize = psutil._psplatform.cext.getpagesize() assert pagesize > 0 assert pagesize == resource.getpagesize() assert pagesize == mmap.PAGESIZE
TestMisc
python
scipy__scipy
scipy/stats/_survival.py
{ "start": 7924, "end": 17400 }
class ____: """ Result object returned by `scipy.stats.ecdf` Attributes ---------- cdf : `~scipy.stats._result_classes.EmpiricalDistributionFunction` An object representing the empirical cumulative distribution function. sf : `~scipy.stats._result_classes.EmpiricalDistributionFunction` ...
ECDFResult
python
jazzband__django-model-utils
model_utils/fields.py
{ "start": 7100, "end": 7963 }
class ____: def __init__(self, instance: models.Model, field_name: str, excerpt_field_name: str): # instead of storing actual values store a reference to the instance # along with field names, this makes assignment possible self.instance = instance self.field_name = field_name ...
SplitText
python
kamyu104__LeetCode-Solutions
Python/sum-of-floored-pairs.py
{ "start": 97, "end": 618 }
class ____(object): def sumOfFlooredPairs(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9+7 prefix, counter = [0]*(max(nums)+1), collections.Counter(nums) for num, cnt in counter.iteritems(): for j in xrange(num, len(prefix), num...
Solution
python
scipy__scipy
scipy/spatial/tests/test_kdtree.py
{ "start": 12974, "end": 13114 }
class ____(_Test_random_ball): def setup_method(self): super().setup_method() self.p = 1 @KDTreeTest
_Test_random_ball_l1
python
apache__airflow
providers/apache/pinot/tests/integration/apache/pinot/hooks/test_pinot.py
{ "start": 970, "end": 1551 }
class ____: # This test occasionally fail in the CI. Re-run this test if it failed after timeout but only once. @pytest.mark.flaky(reruns=1, reruns_delay=30) @mock.patch.dict("os.environ", AIRFLOW_CONN_PINOT_BROKER_DEFAULT="pinot://pinot:8000/") def test_should_return_records(self): hook = Pinot...
TestPinotDbApiHookIntegration
python
numba__numba
numba/core/datamodel/models.py
{ "start": 24386, "end": 24853 }
class ____(StructModel): def __init__(self, dmm, fe_type): payload_type = types.ListPayload(fe_type) members = [ # The meminfo data points to a ListPayload ('meminfo', types.MemInfoPointer(payload_type)), # This member is only used only for reflected lists ...
ListModel
python
ray-project__ray
rllib/offline/estimators/weighted_importance_sampling.py
{ "start": 516, "end": 7047 }
class ____(OffPolicyEstimator): r"""The step-wise WIS estimator. Let s_t, a_t, and r_t be the state, action, and reward at timestep t. For behavior policy \pi_b and evaluation policy \pi_e, define the cumulative importance ratio at timestep t as: p_t = \sum_{t'=0}^t (\pi_e(a_{t'} | s_{t'}) / \pi_b...
WeightedImportanceSampling
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/asset.py
{ "start": 987, "end": 1264 }
class ____(BaseModel): """Asset checks execution status.""" status: Optional[str] # HEALTHY, WARNING, DEGRADED, UNKNOWN, NOT_APPLICABLE num_failed_checks: Optional[int] num_warning_checks: Optional[int] total_num_checks: Optional[int]
DgApiAssetChecksStatus
python
getsentry__sentry
src/sentry/replays/lib/eap/snuba_transpiler.py
{ "start": 31561, "end": 33942 }
class ____(TypedDict): data: list[dict[str, bool | float | int | str | None]] meta: QueryResultMeta def translate_response( query: Query, settings: Settings, query_result: TraceItemTableResponse ) -> QueryResult: # We infer the type of each expression in the select statement. The type information is ...
QueryResult
python
pytorch__pytorch
torch/_dynamo/output_graph.py
{ "start": 14750, "end": 18064 }
class ____(OutputGraphGuardsState): """ A minimal interface for full graph capture. It is intended to be the target of any tracer that feeds into backends. Currently dynamo's OutputGraph is the only known implementation of this interface, used by (aot) precompile and (strict) export. Importantl...
OutputGraphCommon
python
kamyu104__LeetCode-Solutions
Python/pour-water-between-buckets-to-make-water-levels-equal.py
{ "start": 49, "end": 697 }
class ____(object): def equalizeWater(self, buckets, loss): """ :type buckets: List[int] :type loss: int :rtype: float """ def check(buckets, rate, x): return sum(b-x for b in buckets if b-x > 0)*rate >= sum(x-b for b in buckets if x-b > 0) EPS = ...
Solution
python
ApeWorX__ape
src/ape/exceptions.py
{ "start": 15198, "end": 15450 }
class ____(ProjectError): """ Raised when trying to install an unknown version of a package. """ def __init__(self, version: str, name: str): super().__init__(f"Unknown version '{version}' for repo '{name}'.")
UnknownVersionError
python
eth-brownie__brownie
brownie/test/managers/runner.py
{ "start": 3765, "end": 4693 }
class ____: """ Custom printer for test execution. Produces more-readable output when stdout capture is disabled. """ _builtins_print = builtins.print def start(self): self.first_line = True builtins.print = self def __call__(self, *values, sep=" ", end="\n", file=sys.std...
PytestPrinter
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/errors.py
{ "start": 16730, "end": 17455 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneError,) name = "DuplicateDynamicPartitionError" partitions_def_name = graphene.NonNull(graphene.String) partition_name = graphene.NonNull(graphene.String) def __init__(self, partitions_def_name, partition_name): ...
GrapheneDuplicateDynamicPartitionError
python
PyCQA__pylint
tests/functional/u/unused/unused_private_member.py
{ "start": 8587, "end": 8886 }
class ____: __ham = 1 def method(self): print(self.__class__.__ham) # https://github.com/pylint-dev/pylint/issues/4756 # Check for false positives emitted when private functions are not referenced in the class body # with standard calls but passed as arguments to other functions.
Foo
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-pgvector/destination_pgvector/common/sql/sql_processor.py
{ "start": 3707, "end": 34182 }
class ____(RecordProcessorBase): """A base class to be used for SQL Caches.""" type_converter_class: type[SQLTypeConverter] = SQLTypeConverter """The type converter class to use for converting JSON schema types to SQL types.""" normalizer = LowerCaseNormalizer """The name normalizer to user for ta...
SqlProcessorBase
python
Lightning-AI__lightning
src/lightning/fabric/plugins/precision/precision.py
{ "start": 1359, "end": 5592 }
class ____: """Base class for all plugins handling the precision-specific parts of the training. The class attribute precision must be overwritten in child classes. The default value reflects fp32 training. """ precision: _PRECISION_INPUT_STR = "32-true" def convert_module(self, module: Module) ...
Precision
python
sympy__sympy
sympy/utilities/codegen.py
{ "start": 18557, "end": 30697 }
class ____: """Abstract class for the code generators.""" printer = None # will be set to an instance of a CodePrinter subclass def _indent_code(self, codelines): return self.printer.indent_code(codelines) def _printer_method_with_settings(self, method, settings=None, *args, **kwargs): ...
CodeGen
python
matplotlib__matplotlib
lib/matplotlib/backends/_backend_gtk.py
{ "start": 2623, "end": 3707 }
class ____(TimerBase): """Subclass of `.TimerBase` using GTK timer events.""" def __init__(self, *args, **kwargs): self._timer = None super().__init__(*args, **kwargs) def _timer_start(self): # Need to stop it, otherwise we potentially leak a timer id that will # never be s...
TimerGTK
python
sympy__sympy
sympy/functions/special/polynomials.py
{ "start": 28821, "end": 32927 }
class ____(DefinedFunction): r""" ``assoc_legendre(n, m, x)`` gives $P_n^m(x)$, where $n$ and $m$ are the degree and order or an expression which is related to the nth order Legendre polynomial, $P_n(x)$ in the following manner: .. math:: P_n^m(x) = (-1)^m (1 - x^2)^{\frac{m}{2}} ...
assoc_legendre
python
google__pytype
pytype/pytd/parse/node.py
{ "start": 663, "end": 8252 }
class ____( _Struct, frozen=True, tag=True, tag_field="_struct_type", kw_only=True, omit_defaults=True, cache_hash=True, ): """Base Node class.""" # We pretend that `name` is a ClassVar so that msgspec treats it as a struct # field only when it is defined in a subclass. name: ClassV...
Node
python
rushter__MLAlgorithms
mla/base/base.py
{ "start": 36, "end": 1826 }
class ____: y_required = True fit_required = True def _setup_input(self, X, y=None): """Ensure inputs to an estimator are in the expected format. Ensures X and y are stored as numpy ndarrays by converting from an array-like object if necessary. Enables estimators to define whether ...
BaseEstimator
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/enum6.py
{ "start": 940, "end": 986 }
class ____(EnumWithValue): z: int
EnumSubclass
python
kamyu104__LeetCode-Solutions
Python/find-the-safest-path-in-a-grid.py
{ "start": 2662, "end": 4425 }
class ____(object): def maximumSafenessFactor(self, grid): """ :type grid: List[List[int]] :rtype: int """ DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1)) def bfs(): dist = [[0 if grid[r][c] == 1 else -1 for c in xrange(len(grid[0]))] for r in xrange(len(g...
Solution2
python
django__django
tests/mail/tests.py
{ "start": 124598, "end": 125427 }
class ____(SMTPBackendTestsBase): @classmethod def setUpClass(cls): super().setUpClass() cls.backend = smtp.EmailBackend(username="", password="") cls.smtp_controller.stop() @classmethod def stop_smtp(cls): # SMTP controller is stopped in setUpClass(). pass ...
SMTPBackendStoppedServerTests
python
tensorflow__tensorflow
tensorflow/python/training/training.py
{ "start": 15028, "end": 15653 }
class ____(typing.NamedTuple): context: Dict[str, Feature] feature_lists: FeatureLists ``` This proto implements the `List[Feature]` portion. """ FeatureLists.__doc__ = """\ Mainly used as part of a `tf.train.SequenceExample`. Contains a list of `tf.train.Feature`s. The `tf.train.SequenceExample` proto can be ...
SequenceExample
python
plotly__plotly.py
plotly/graph_objs/_carpet.py
{ "start": 215, "end": 39833 }
class ____(_BaseTraceType): _parent_path_str = "" _path_str = "carpet" _valid_props = { "a", "a0", "aaxis", "asrc", "b", "b0", "baxis", "bsrc", "carpet", "cheaterslope", "color", "customdata", "customdata...
Carpet
python
getsentry__sentry
src/sentry/workflow_engine/typings/notification_action.py
{ "start": 12493, "end": 13334 }
class ____(BaseActionTranslator): @property def action_type(self) -> ActionType: return ActionType.OPSGENIE field_mappings = { "priority": FieldMapping( source_field="priority", default_value=str(OPSGENIE_DEFAULT_PRIORITY) ) } @property def required_fields(s...
OpsgenieActionTranslator
python
doocs__leetcode
solution/0300-0399/0349.Intersection of Two Arrays/Solution.py
{ "start": 0, "end": 138 }
class ____: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: return list(set(nums1) & set(nums2))
Solution
python
pola-rs__polars
py-polars/src/polars/interchange/protocol.py
{ "start": 7215, "end": 7346 }
class ____(RuntimeError): """Exception raised when a copy is required, but `allow_copy` is set to `False`."""
CopyNotAllowedError