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
pennersr__django-allauth
tests/apps/socialaccount/providers/clever/tests.py
{ "start": 240, "end": 1540 }
class ____(OAuth2TestsMixin, TestCase): provider_id = CleverProvider.id def get_mocked_response(self): return [ MockedResponse( HTTPStatus.OK, """{ "type": "user", "data": { "id": "62027798269867124d10259e", ...
CleverOAuth2Tests
python
davidhalter__jedi
jedi/inference/value/instance.py
{ "start": 2375, "end": 3100 }
class ____(BaseFunctionExecutionContext): def __init__(self, instance, value): super().__init__(value) self.instance = instance def get_filters(self, until_position=None, origin_scope=None): yield AnonymousMethodExecutionFilter( self.instance, self, self._value, ...
AnonymousMethodExecutionContext
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 40261, "end": 40715 }
class ____[T](TypedDict): t: 'T' """ ) with pytest.raises(ValidationError): TypeAdapter(mod_1.TD[str]).validate_python({'t': 1}) @pytest.mark.skipif(sys.version_info < (3, 12), reason='Test related to PEP 695 syntax.') def test_pep695_generics_class_locals_take_priority(create_module) -> ...
TD
python
getsentry__sentry
tests/sentry_plugins/trello/test_plugin.py
{ "start": 498, "end": 1663 }
class ____(TrelloPluginTestBase): def test_get_issue_label(self) -> None: group = self.create_group(message="Hello world", culprit="foo.bar") # test new and old format assert self.plugin.get_issue_label(group, "rPPDb") == "Trello-rPPDb" assert ( self.plugin.get_issue_labe...
TrelloPluginTest
python
walkccc__LeetCode
solutions/2133. Check if Every Row and Column Contains All Numbers/2133.py
{ "start": 0, "end": 195 }
class ____: def checkValid(self, matrix: list[list[int]]) -> bool: return all(min(len(set(row)), len(set(col))) == len(matrix) for row, col in zip(matrix, zip(*matrix)))
Solution
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_lambda_function.py
{ "start": 925, "end": 1918 }
class ____: def test_serialization(self): function_name = "test_function_name" function_arn = "test_function_arn" waiter_delay = 60 waiter_max_attempts = 30 aws_conn_id = "aws_default" trigger = LambdaCreateFunctionCompleteTrigger( function_name=function_...
TestLambdaCreateFunctionCompleteTrigger
python
getsentry__sentry
tests/sentry/api/test_data_secrecy.py
{ "start": 162, "end": 2456 }
class ____(APITestCase): # Picked an endpoint with OrganizationAndStaffPermission endpoint = "sentry-api-0-organization-projects" method = "get" def setUp(self) -> None: super().setUp() self.login_as(self.user) self.organization.flags.prevent_superuser_access = True self...
DataSecrecyTestCase
python
spack__spack
lib/spack/spack/oci/opener.py
{ "start": 5999, "end": 7342 }
class ____(NamedTuple): username: str password: str @property def basic_auth_header(self) -> str: encoded = base64.b64encode(f"{self.username}:{self.password}".encode("utf-8")).decode( "utf-8" ) return f"Basic {encoded}" def _get_bearer_challenge(challenges: List[C...
UsernamePassword
python
kubernetes-client__python
kubernetes/client/models/v1_network_policy_ingress_rule.py
{ "start": 383, "end": 5852 }
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...
V1NetworkPolicyIngressRule
python
faif__python-patterns
patterns/behavioral/visitor.py
{ "start": 773, "end": 1698 }
class ____: def visit(self, node: Union[A, C, B], *args, **kwargs) -> None: meth = None for cls in node.__class__.__mro__: meth_name = "visit_" + cls.__name__ meth = getattr(self, meth_name, None) if meth: break if not meth: me...
Visitor
python
spyder-ide__spyder
spyder/plugins/pylint/tests/test_pylint.py
{ "start": 2063, "end": 12212 }
class ____(QMainWindow): sig_editor_focus_changed = Signal(str) def __init__(self): super().__init__(None) self.editor = Mock() self.editor.sig_editor_focus_changed = self.sig_editor_focus_changed self.projects = MagicMock() PLUGIN_REGISTRY.plugin_registry = { ...
MainWindowMock
python
scipy__scipy
scipy/optimize/_dual_annealing.py
{ "start": 8776, "end": 15609 }
class ____: """ Class that implements within a Markov chain the strategy for location acceptance and local search decision making. Parameters ---------- acceptance_param : float Parameter for acceptance distribution. It is used to control the probability of acceptance. The lower...
StrategyChain
python
networkx__networkx
networkx/algorithms/shortest_paths/tests/test_weighted.py
{ "start": 739, "end": 3010 }
class ____: """Base class for test classes that test functions for computing shortest paths in weighted graphs. """ def setup_method(self): """Creates some graphs for use in the unit tests.""" cnlti = nx.convert_node_labels_to_integers self.grid = cnlti(nx.grid_2d_graph(4, 4), ...
WeightedTestBase
python
explosion__spaCy
spacy/pipeline/spancat.py
{ "start": 2080, "end": 5386 }
class ____(Protocol): def __call__(self, docs: Iterable[Doc], *, ops: Optional[Ops] = None) -> Ragged: ... def ngram_suggester( docs: Iterable[Doc], sizes: List[int], *, ops: Optional[Ops] = None ) -> Ragged: if ops is None: ops = get_current_ops() spans = [] lengths = [] for doc in do...
Suggester
python
pytest-dev__pytest
testing/test_capture.py
{ "start": 41058, "end": 54679 }
class ____: def test_stdcapture_fd_invalid_fd(self, pytester: Pytester) -> None: pytester.makepyfile( """ import os from fnmatch import fnmatch from _pytest import capture def StdCaptureFD(out=True, err=True, in_=True): return capt...
TestStdCaptureFDinvalidFD
python
numba__numba
numba/core/ir.py
{ "start": 20419, "end": 20798 }
class ____(Stmt): """ del target[index] """ def __init__(self, target, index, loc): assert isinstance(target, Var) assert isinstance(index, Var) assert isinstance(loc, Loc) self.target = target self.index = index self.loc = loc def __repr__(self): ...
DelItem
python
dask__dask
dask/_expr.py
{ "start": 39839, "end": 41657 }
class ____(HLGExpr): def _simplify_down(self): if not self.postcompute: return self.dsk from dask.delayed import Delayed # Skip finalization for Delayed if self.dsk.postcompute == Delayed.__dask_postcompute__(self.dsk): return self.dsk return self ...
HLGFinalizeCompute
python
streamlit__streamlit
lib/tests/streamlit/elements/layout_test_utils.py
{ "start": 641, "end": 770 }
class ____(Enum): PIXEL_WIDTH = "pixel_width" USE_STRETCH = "use_stretch" USE_CONTENT = "use_content"
WidthConfigFields
python
astropy__astropy
astropy/cosmology/_src/tests/test_utils.py
{ "start": 2388, "end": 5588 }
class ____: @classmethod def setup_class(cls): def noop(a, b, c, d): # a minimal function that does nothing, # with multiple positional-or-keywords arguments return cls.base_func = noop cls.depr_funcs = { 1: deprecated_keywords("a", since=...
TestDeprecatedKeywords
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py
{ "start": 7018, "end": 7128 }
class ____(IncrementalShopifyGraphQlBulkStream): bulk_query: OrderAgreement = OrderAgreement
OrderAgreements
python
ray-project__ray
python/ray/tune/search/repeater.py
{ "start": 2468, "end": 7007 }
class ____(Searcher): """A wrapper algorithm for repeating trials of same parameters. Set tune.TuneConfig(num_samples=...) to be a multiple of `repeat`. For example, set num_samples=15 if you intend to obtain 3 search algorithm suggestions and repeat each suggestion 5 times. Any leftover trials (nu...
Repeater
python
pytorch__pytorch
torch/distributed/elastic/metrics/api.py
{ "start": 1066, "end": 1288 }
class ____(MetricHandler): def emit(self, metric_data: MetricData): print( f"[{metric_data.timestamp}][{metric_data.group_name}]: {metric_data.name}={metric_data.value}" )
ConsoleMetricHandler
python
jmcnamara__XlsxWriter
xlsxwriter/test/styles/test_write_mru_colors.py
{ "start": 330, "end": 952 }
class ____(unittest.TestCase): """ Test the Styles _write_mru_colors() method. """ def setUp(self): self.fh = StringIO() self.styles = Styles() self.styles._set_filehandle(self.fh) def test_write_mru_colors(self): """Test the _write_mru_colors() method""" ...
TestWriteMruColors
python
huggingface__transformers
src/transformers/models/donut/modeling_donut_swin.py
{ "start": 30938, "end": 35251 }
class ____(nn.Module): def __init__(self, config, grid_size): super().__init__() self.num_layers = len(config.depths) self.config = config dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")] self.layers = nn.ModuleList( ...
DonutSwinEncoder
python
huggingface__transformers
tests/models/nanochat/test_modeling_nanochat.py
{ "start": 1068, "end": 1283 }
class ____(CausalLMModelTester): config_class = NanoChatConfig if is_torch_available(): base_model_class = NanoChatModel causal_lm_class = NanoChatForCausalLM @require_torch
NanoChatModelTester
python
django__django
tests/template_backends/test_jinja2.py
{ "start": 443, "end": 5725 }
class ____(TemplateStringsTests): engine_class = Jinja2 backend_name = "jinja2" options = { "keep_trailing_newline": True, "context_processors": [ "django.template.context_processors.static", ], } def test_origin(self): template = self.engine.get_template...
Jinja2Tests
python
huggingface__transformers
src/transformers/models/vjepa2/modeling_vjepa2.py
{ "start": 2360, "end": 3319 }
class ____(ModelOutput): r""" masked_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*, returned when `context_mask` is provided which is applied on VJEPA2Encoder outputs): The masked hidden state of the model. predictor_output (`VJEPA2WithMaskedInpu...
VJEPA2WithMaskedInputModelOutput
python
doocs__leetcode
solution/2500-2599/2502.Design Memory Allocator/Solution.py
{ "start": 0, "end": 774 }
class ____: def __init__(self, n: int): self.m = [0] * n def allocate(self, size: int, mID: int) -> int: cnt = 0 for i, v in enumerate(self.m): if v: cnt = 0 else: cnt += 1 if cnt == size: self.m...
Allocator
python
urllib3__urllib3
test/test_response.py
{ "start": 56872, "end": 57070 }
class ____(MockChunkedEncodingResponse): def _encode_chunk(self, chunk: bytes) -> bytes: return f"{len(chunk):X};asd=qwe\r\n{chunk.decode()}\r\n".encode()
MockChunkedEncodingWithExtensions
python
scikit-learn__scikit-learn
sklearn/compose/tests/test_target.py
{ "start": 14100, "end": 14891 }
class ____(BaseEstimator): """A regressor that expects the target to have a specific number of dimensions.""" def __init__(self, ndim): self.ndim = ndim def fit(self, X, y): assert y.ndim == self.ndim def predict(self, X): pass # pragma: no cover @pytest.mark.parametrize("n...
ValidateDimensionRegressor
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1464056, "end": 1467760 }
class ____(sgqlc.types.Type, Node): """A repository ruleset.""" __schema__ = github_schema __field_names__ = ( "bypass_actors", "bypass_mode", "conditions", "created_at", "database_id", "enforcement", "name", "rules", "source", ...
RepositoryRuleset
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/tab_rename.py
{ "start": 95, "end": 506 }
class ____(App[None]): def compose(self) -> ComposeResult: with TabbedContent(): yield TabPane("!", id="test") for n in range(5): yield TabPane(str(n) * (n+1)) def on_mount(self) -> None: self.query_one(TabbedContent).get_tab("test").label = "This is a m...
TabRenameApp
python
rapidsai__cudf
python/cudf/cudf/core/accessors/struct.py
{ "start": 547, "end": 3434 }
class ____(BaseAccessor): """ Struct methods for Series """ _column: StructColumn def __init__(self, parent: Series | Index): if not is_dtype_obj_struct(parent.dtype): raise AttributeError( "Can only use .struct accessor with a 'struct' dtype" ) ...
StructMethods
python
psf__black
tests/data/cases/allow_empty_first_line.py
{ "start": 620, "end": 1524 }
class ____: def method(self): pass async def async_fn(): """Docstring.""" @decorated async def async_fn(): """Docstring.""" def top_level( a: int, b: str, ) -> Whatever[Generic, Something]: def nested(x: int) -> int: pass # output def foo(): """ Docstring...
Cls
python
getsentry__sentry
tests/sentry/api/fields/test_serializedfile.py
{ "start": 323, "end": 1369 }
class ____(unittest.TestCase): def test_to_representation(self) -> None: field = SerializedFileField() assert field.to_representation(None) == "" assert field.to_representation("") == "" with pytest.raises(ValueError): assert field.to_representation(1) result = ...
SerializedFileFieldTest
python
apache__thrift
lib/py/src/protocol/TBase.py
{ "start": 2093, "end": 2829 }
class ____(TBase): def __setitem__(self, *args): raise TypeError("Can't modify frozen struct") def __delitem__(self, *args): raise TypeError("Can't modify frozen struct") def __hash__(self, *args): return hash(self.__class__) ^ hash(self.__slots__) @classmethod def read(cl...
TFrozenBase
python
walkccc__LeetCode
solutions/471. Encode String with Shortest Length/471.py
{ "start": 0, "end": 905 }
class ____: def encode(self, s: str) -> str: n = len(s) @functools.lru_cache(None) def dp(i: int, j: int) -> str: """Returns the shortest encoded string of s[i..j].""" curr = s[i:j + 1] res = curr if len(res) < 5: return res # Try all possible partitions. for...
Solution
python
django__django
tests/messages_tests/tests.py
{ "start": 3542, "end": 3711 }
class ____: def __init__(self): request = RequestFactory().get("/") request._messages = DummyStorage() self.wsgi_request = request
FakeResponse
python
langchain-ai__langchain
libs/core/langchain_core/outputs/generation.py
{ "start": 1611, "end": 2564 }
class ____(Generation): """`GenerationChunk`, which can be concatenated with other Generation chunks.""" def __add__(self, other: GenerationChunk) -> GenerationChunk: """Concatenate two `GenerationChunk`s. Args: other: Another `GenerationChunk` to concatenate with. Raises:...
GenerationChunk
python
wandb__wandb
wandb/vendor/pygments/formatters/terminal.py
{ "start": 1981, "end": 4919 }
class ____(Formatter): r""" Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly. The `get_style_defs()` method doesn't do anything special since there is no support for common styles. O...
TerminalFormatter
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_fragment_names.py
{ "start": 69, "end": 597 }
class ____(ValidationRule): def enter_FragmentSpread(self, node, key, parent, path, ancestors): fragment_name = node.name.value fragment = self.context.get_fragment(fragment_name) if not fragment: self.context.report_error(GraphQLError( self.unknown_fragment_mes...
KnownFragmentNames
python
davidhalter__parso
parso/python/tree.py
{ "start": 8203, "end": 8414 }
class ____(PythonLeaf): """ f-strings contain f-string expressions and normal python strings. These are the string parts of f-strings. """ type = 'fstring_start' __slots__ = ()
FStringStart
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/refurb/FURB180.py
{ "start": 587, "end": 681 }
class ____(metaclass=Meta, no_metaclass=ABCMeta): @abstractmethod def foo(self): pass
A4
python
huggingface__transformers
src/transformers/models/unispeech/modeling_unispeech.py
{ "start": 29125, "end": 37809 }
class ____(PreTrainedModel): config: UniSpeechConfig base_model_prefix = "unispeech" main_input_name = "input_values" input_modalities = "audio" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True @torch.no_grad() d...
UniSpeechPreTrainedModel
python
facelessuser__pymdown-extensions
pymdownx/_bypassnorm.py
{ "start": 665, "end": 1018 }
class ____(Preprocessor): """Preprocessor to remove workaround symbols.""" def run(self, lines): """Remove workaround placeholder markers before adding actual workaround placeholders.""" source = '\n'.join(lines) source = source.replace(SOH, '').replace(EOT, '') return source.s...
PreNormalizePreprocessor
python
pytorch__pytorch
test/distributed/checkpoint/test_pg_transport.py
{ "start": 10638, "end": 12707 }
class ____(TestCase): def test_prepare_tensor_basic(self): """Test basic tensor preparation.""" tensor = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32) prepared_tensor, meta = _prepare_tensor(tensor) # Check metadata self.assertEqual(meta.shape, tensor.shape) sel...
TestPrepareTensor
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/metadata_set.py
{ "start": 6150, "end": 7317 }
class ____(NamespacedMetadataSet): """Metadata entries that apply to definitions, observations, or materializations of assets that are tables. Args: column_schema (Optional[TableSchema]): The schema of the columns in the table. column_lineage (Optional[TableColumnLineage]): The lineage of c...
TableMetadataSet
python
rq__rq
rq/results.py
{ "start": 399, "end": 8058 }
class ____: class Type(Enum): SUCCESSFUL = 1 FAILED = 2 STOPPED = 3 RETRIED = 4 def __init__( self, job_id: str, type: Type, connection: Redis, id: Optional[str] = None, created_at: Optional[datetime] = None, return_value: ...
Result
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/random_erasing_test.py
{ "start": 164, "end": 2800 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_layer(self): self.run_layer_test( layers.RandomErasing, init_kwargs={ "factor": 1.0, "scale": 0.5, "fill_value": 0, "value_range": (0, 25...
RandomErasingTest
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/matrix_multiply.py
{ "start": 265, "end": 1246 }
class ____(Operator): """Base class for matrix multiplication operations.""" def __init__(self, name: str): super().__init__(name) def can_produce(self, output_spec: Spec) -> bool: """Matrix multiply operations can produce float/complex tensors of dimension >= 2.""" if not isinstan...
MatrixMultiplyOperator
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 7637, "end": 7864 }
class ____(BaseModel): grpc_timeout_ms: int = Field(..., description="") p2p: "P2pConfigTelemetry" = Field(..., description="") consensus: "ConsensusConfigTelemetry" = Field(..., description="")
ClusterConfigTelemetry
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/resource_definition.py
{ "start": 1809, "end": 12306 }
class ____(AnonymousConfigurableDefinition, IHasInternalInit): """Core class for defining resources. Resources are scoped ways to make external resources (like database connections) available to ops and assets during job execution and to clean up after execution resolves. If resource_fn yields once ra...
ResourceDefinition
python
openai__openai-python
src/openai/types/beta/threads/file_citation_annotation.py
{ "start": 326, "end": 595 }
class ____(BaseModel): end_index: int file_citation: FileCitation start_index: int text: str """The text in the message content that needs to be replaced.""" type: Literal["file_citation"] """Always `file_citation`."""
FileCitationAnnotation
python
huggingface__transformers
src/transformers/models/wav2vec2/configuration_wav2vec2.py
{ "start": 843, "end": 20077 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Wav2Vec2Model`]. It is used to instantiate an Wav2Vec2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar co...
Wav2Vec2Config
python
getsentry__sentry
src/sentry/preprod/pull_request/comment_types.py
{ "start": 1138, "end": 1507 }
class ____(BaseModel): """Reaction counts on a comment.""" url: str total_count: int plus_one: int = Field(alias="+1") minus_one: int = Field(alias="-1") laugh: int confused: int heart: int hooray: int eyes: int rocket: int class Config: populate_by_name = True ...
CommentReactions
python
realpython__materials
arcade-platformer/arcade_platformer/13_pause_view.py
{ "start": 6510, "end": 19359 }
class ____(arcade.View): def __init__(self) -> None: super().__init__() # These lists will hold different sets of sprites self.coins = None self.background = None self.walls = None self.ladders = None self.goals = None self.enemies = None # O...
PlatformerView
python
django__django
tests/backends/sqlite/test_functions.py
{ "start": 171, "end": 915 }
class ____(SimpleTestCase): def test_sqlite_date_trunc(self): msg = "Unsupported lookup type: 'unknown-lookup'" with self.assertRaisesMessage(ValueError, msg): _sqlite_date_trunc("unknown-lookup", "2005-08-11", None, None) def test_sqlite_datetime_trunc(self): msg = "Unsuppo...
FunctionTests
python
ansible__ansible
test/lib/ansible_test/_internal/provider/__init__.py
{ "start": 1494, "end": 1858 }
class ____(ApplicationError): """Exception generated when a path based provider cannot be found for a given path.""" def __init__(self, provider_type: t.Type, path: str) -> None: super().__init__('No %s found for path: %s' % (provider_type.__name__, path)) self.provider_type = provider_type ...
ProviderNotFoundForPath
python
python-excel__xlwt
xlwt/antlr.py
{ "start": 6495, "end": 6627 }
class ____(RecognitionException): def __init__(self, *args): RecognitionException.__init__(self, *args)
SemanticException
python
joblib__joblib
joblib/executor.py
{ "start": 4785, "end": 5229 }
class ____(MemmappingExecutor): """Wrapper around ReusableExecutor to ease memmapping testing with Pool and Executor. This is only for testing purposes. """ def apply_async(self, func, args): """Schedule a func to be run""" future = self.submit(func, *args) future.get = future....
_TestingMemmappingExecutor
python
facelessuser__soupsieve
tests/test_level3/test_nth_last_of_type.py
{ "start": 63, "end": 1320 }
class ____(util.TestCase): """Test `nth` last of type selectors.""" def test_nth_last_of_type(self): """Test `nth` last of type.""" markup = """ <p id="0"></p> <p id="1"></p> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id...
TestNthLastOfType
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 300948, "end": 301128 }
class ____(ColorScheme): """Cyclical schema wrapper.""" _schema = {"$ref": "#/definitions/Cyclical"} def __init__(self, *args): super().__init__(*args)
Cyclical
python
huggingface__transformers
tests/models/longformer/test_modeling_longformer.py
{ "start": 12855, "end": 17255 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( LongformerModel, LongformerForMaskedLM, LongformerForSequenceClassification, LongformerForQuestionAnswering, LongformerForTokenClassification, ...
LongformerModelTest
python
falconry__falcon
tests/test_app_initializers.py
{ "start": 241, "end": 1432 }
class ____(media.BaseHandler): def serialize(self, media, content_type): return str(media).encode() def deserialize(self, stream, content_type, content_length): return stream.read().decode() @pytest.fixture def client(request): app = request.param(media_type=falcon.MEDIA_XML) app.add_...
PlainTextHandler
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_aggregate_metrics/column_distinct_values.py
{ "start": 5670, "end": 7725 }
class ____(ColumnAggregateMetricProvider): metric_name = "column.distinct_values.count.under_threshold" condition_keys = ("threshold",) @column_aggregate_value(engine=PandasExecutionEngine) # type: ignore[misc] # untyped-decorator def _pandas(cls, column: pd.Series, threshold: int, **kwargs) -> bool: ...
ColumnDistinctValuesCountUnderThreshold
python
tensorflow__tensorflow
tensorflow/python/keras/utils/generic_utils.py
{ "start": 1601, "end": 4491 }
class ____(object): """Exposes custom classes/functions to Keras deserialization internals. Under a scope `with custom_object_scope(objects_dict)`, Keras methods such as `tf.keras.models.load_model` or `tf.keras.models.model_from_config` will be able to deserialize any custom object referenced by a saved con...
CustomObjectScope
python
dagster-io__dagster
python_modules/dagster/dagster/_core/pipes/utils.py
{ "start": 7515, "end": 10154 }
class ____(PipesMessageReader): """Message reader that reads messages by tailing an automatically-generated temporary file.""" def __init__(self, include_stdio_in_messages: bool = False): self._include_stdio_in_messages = check.bool_param( include_stdio_in_messages, "include_stdio_in_messag...
PipesTempFileMessageReader
python
pappasam__jedi-language-server
jedi_language_server/initialization_options.py
{ "start": 730, "end": 906 }
class ____: disable_snippets: bool = False resolve_eagerly: bool = False ignore_patterns: List[Pattern[str]] = field(default_factory=list) @light_dataclass
Completion
python
ray-project__ray
python/ray/serve/_private/proxy_state.py
{ "start": 3462, "end": 10764 }
class ____(ProxyWrapper): def __init__( self, logging_config: LoggingConfig, actor_handle: Optional[ActorHandle] = None, http_options: Optional[HTTPOptions] = None, grpc_options: Optional[gRPCOptions] = None, name: Optional[str] = None, node_id: Optional[str] ...
ActorProxyWrapper
python
django__django
tests/db_utils/tests.py
{ "start": 346, "end": 2322 }
class ____(SimpleTestCase): def test_connection_handler_no_databases(self): """ Empty DATABASES and empty 'default' settings default to the dummy backend. """ for DATABASES in ( {}, # Empty DATABASES setting. {"default": {}}, # Empty 'default' databa...
ConnectionHandlerTests
python
bokeh__bokeh
tests/unit/bokeh/embed/test_util__embed.py
{ "start": 5089, "end": 8866 }
class ____: def test_single_model_with_document(self) -> None: # should use existing doc in with-block p = SomeModel() d = Document() orig_theme = d.theme d.add_root(p) with beu.OutputDocumentFor([p]): assert p.document is d assert d.theme is o...
Test_OutputDocumentFor_default_apply_theme
python
python-poetry__poetry
src/poetry/mixology/incompatibility_cause.py
{ "start": 470, "end": 1027 }
class ____(IncompatibilityCauseError): """ The incompatibility was derived from two existing incompatibilities during conflict resolution. """ def __init__(self, conflict: Incompatibility, other: Incompatibility) -> None: self._conflict = conflict self._other = other @property ...
ConflictCauseError
python
mlflow__mlflow
mlflow/gateway/config.py
{ "start": 7163, "end": 7376 }
class ____(ConfigModel): mistral_api_key: str @field_validator("mistral_api_key", mode="before") def validate_mistral_api_key(cls, value): return _resolve_api_key_from_input(value)
MistralConfig
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 83943, "end": 84767 }
class ____(Head, Blockwise): """Take the first `n` rows of every partition Typically used after `Partitions(..., [0])` to take the first `n` rows of an entire collection. """ _parameters = ["frame", "n", "npartitions", "safe"] _preserves_partitioning_information = True def _simplify_down(...
BlockwiseHead
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/pretty_printer.py
{ "start": 784, "end": 4165 }
class ____(gast.NodeVisitor): """Print AST nodes.""" def __init__(self, color, noanno): self.indent_lvl = 0 self.result = '' self.color = color self.noanno = noanno def _color(self, string, color, attrs=None): if self.color: return termcolor.colored(string, color, attrs=attrs) retu...
PrettyPrinter
python
walkccc__LeetCode
solutions/2162. Minimum Cost to Set Cooking Time/2162.py
{ "start": 0, "end": 648 }
class ____: def minCostSetTime( self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int, ) -> int: ans = math.inf mins = 99 if targetSeconds > 5999 else targetSeconds // 60 secs = targetSeconds - mins * 60 def getCost(mins: int, secs: int) -> int: co...
Solution
python
django-haystack__django-haystack
test_haystack/test_indexes.py
{ "start": 29959, "end": 30853 }
class ____(TestCase): def test_full_prepare(self): index = ModelWithManyToManyFieldAndAttributeLookupSearchIndex() left_model = ManyToManyLeftSideModel.objects.create() right_model_1 = ManyToManyRightSideModel.objects.create(name="Right side 1") right_model_2 = ManyToManyRightSideMo...
ModelWithManyToManyFieldAndAttributeLookupSearchIndexTestCase
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/video_audio/base.py
{ "start": 336, "end": 2164 }
class ____(BaseReader): """ Video audio parser. Extract text from transcript of video/audio files. """ def __init__(self, *args: Any, model_version: str = "base", **kwargs: Any) -> None: """Init parser.""" super().__init__(*args, **kwargs) self._model_version = model_versi...
VideoAudioReader
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 40705, "end": 41021 }
class ____(Blockwise): _parameters = ["frame", "_expr", "expr_kwargs"] _defaults: dict[str, Any] = {"expr_kwargs": {}} # type: ignore[dict-item] _keyword_only = ["expr_kwargs"] operation = M.query @functools.cached_property def _kwargs(self) -> dict: return {**self.expr_kwargs}
Query
python
encode__django-rest-framework
tests/test_validators.py
{ "start": 6024, "end": 6174 }
class ____(serializers.ModelSerializer): class Meta: model = UniquenessTogetherModel fields = '__all__'
UniquenessTogetherSerializer
python
chroma-core__chroma
chromadb/auth/token_authn/__init__.py
{ "start": 740, "end": 1884 }
class ____(str, Enum): """ Accceptable token transport headers. """ # I don't love having this enum here -- it's weird to have an enum # for just two values and it's weird to have users pass X_CHROMA_TOKEN # to configure "x-chroma-token". But I also like having a single source # of truth, s...
TokenTransportHeader
python
numpy__numpy
numpy/ma/tests/test_extras.py
{ "start": 6241, "end": 17360 }
class ____: # Several tests of average. Why so many ? Good point... def test_testAverage1(self): # Test of average. ott = array([0., 1., 2., 3.], mask=[True, False, False, False]) assert_equal(2.0, average(ott, axis=0)) assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.])) ...
TestAverage
python
huggingface__transformers
src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py
{ "start": 43079, "end": 63975 }
class ____(Qwen2_5_VLPreTrainedModel): base_model_prefix = "model" _checkpoint_conversion_mapping = {"^model": "language_model"} # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False config: Qwen2_5_VLConfig _no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"] ...
Qwen2_5_VLModel
python
getsentry__sentry
src/sentry/snuba/metrics/naming_layer/mri.py
{ "start": 2128, "end": 5086 }
class ____(Enum): # Ingested # Do *not* use these metrics in product queries. Use the derived metrics below instead. # The raw metrics do not necessarily add up in intuitive ways. For example, `RAW_SESSION` # double-counts crashed sessions. RAW_SESSION = "c:sessions/session@none" RAW_ERROR = "s:...
SessionMRI
python
Farama-Foundation__Gymnasium
tests/envs/registration/test_env_spec.py
{ "start": 6099, "end": 7262 }
class ____(gym.Env): def __init__(self, unpickleable_obj): self.action_space = gym.spaces.Discrete(2) self.observation_space = gym.spaces.Discrete(2) self.unpickleable_obj = unpickleable_obj def step(self, action): return self.observation_space.sample(), 0, False, False, {} ...
EnvWithUnpickleableObj
python
ray-project__ray
python/ray/serve/tests/test_config_files/use_custom_request_router.py
{ "start": 903, "end": 1184 }
class ____: def __init__(self): context = _get_internal_replica_context() self.replica_id: ReplicaID = context.replica_id async def __call__(self): return "hello_from_custom_request_router" app = UniformRequestRouterApp.bind()
UniformRequestRouterApp
python
PyCQA__pylint
tests/functional/u/unused/unused_private_member.py
{ "start": 2082, "end": 2370 }
class ____: """Regression test for issue 4638""" def __init__(self): type(self).__a() self.__b() Bla.__c() @classmethod def __a(cls): pass @classmethod def __b(cls): pass @classmethod def __c(cls): pass
Bla
python
plotly__plotly.py
plotly/graph_objs/scatterpolar/unselected/_marker.py
{ "start": 233, "end": 4076 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterpolar.unselected" _path_str = "scatterpolar.unselected.marker" _valid_props = {"color", "opacity", "size"} @property def color(self): """ Sets the marker color of unselected points, applied only when a selection...
Marker
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F701.py
{ "start": 150, "end": 179 }
class ____: break break
Foo
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 203929, "end": 205222 }
class ____(test_util.TensorFlowTestCase): def testFormats(self): prefix = "tensorflow/core/lib" paths = ("png/testdata/lena_gray.png", "jpeg/testdata/jpeg_merge_test1.jpg", "gif/testdata/lena.gif") decoders = { "jpeg": functools.partial(image_ops.decode_jpeg, channels=3), "pn...
FormatTest
python
walkccc__LeetCode
solutions/733. Flood Fill/733.py
{ "start": 0, "end": 535 }
class ____: def floodFill(self, image: list[list[int]], sr: int, sc: int, newColor: int) -> list[list[int]]: startColor = image[sr][sc] seen = set() def dfs(i: int, j: int) -> None: if i < 0 or i == len(image) or j < 0 or j == len(image[0]): return if image[i][j] != st...
Solution
python
keras-team__keras
keras/src/callbacks/swap_ema_weights.py
{ "start": 202, "end": 6843 }
class ____(Callback): """Swaps model weights and EMA weights before and after evaluation. This callbacks replaces the model's weight values with the values of the optimizer's EMA weights (the exponential moving average of the past model weights values, implementing "Polyak averaging") before model ...
SwapEMAWeights
python
spyder-ide__spyder
spyder/plugins/run/confpage.py
{ "start": 6042, "end": 18578 }
class ____(PluginConfigPage): """Default Run Settings configuration page.""" def setup_page(self): self._params_to_delete = {} # --- Executors tab --- self.plugin_container: RunContainer = self.plugin.get_container() self.executor_model = RunExecutorNamesListModel( ...
RunConfigPage
python
getsentry__sentry
src/sentry/services/eventstore/reprocessing/base.py
{ "start": 98, "end": 2279 }
class ____(Service): __all__ = ( "event_count_for_hashes", "pop_batched_events", "pop_batched_events_by_key", "get_old_primary_hashes", "expire_hash", "add_hash", "get_remaining_event_count", "rename_key", "mark_event_reprocessed", "sta...
ReprocessingStore
python
numba__numba
numba/tests/test_listobject.py
{ "start": 24373, "end": 25252 }
class ____(MemoryLeakMixin, TestCase): """Test list contains. """ def test_list_contains_empty(self): @njit def foo(i): l = listobject.new_list(int32) return i in l self.assertFalse(foo(0)) self.assertFalse(foo(1)) def test_list_contains_singleton(s...
TestContains
python
walkccc__LeetCode
solutions/116. Populating Next Right Pointers in Each Node/116.py
{ "start": 0, "end": 375 }
class ____: def connect(self, root: 'Node | None') -> 'Node | None': if not root: return None def connectTwoNodes(p, q) -> None: if not p: return p.next = q connectTwoNodes(p.left, p.right) connectTwoNodes(q.left, q.right) connectTwoNodes(p.right, q.left) conn...
Solution
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 28540, "end": 28651 }
class ____(ProjectRedirectsMixin, CreateView): success_message = _("Redirect created")
ProjectRedirectsCreate
python
apache__airflow
providers/oracle/src/airflow/providers/oracle/hooks/oracle.py
{ "start": 1916, "end": 22250 }
class ____(DbApiHook): """ Interact with Oracle SQL. :param oracle_conn_id: The :ref:`Oracle connection id <howto/connection:oracle>` used for Oracle credentials. :param thick_mode: Specify whether to use python-oracledb in thick mode. Defaults to False. If set to True, you must have th...
OracleHook
python
conda__conda
tests/plugins/test_env_specs.py
{ "start": 355, "end": 610 }
class ____(EnvironmentSpecBase): def __init__(self, source: str): self.source = source def can_handle(self): raise TypeError("This is a naughty spec") def env(self): raise TypeError("This is a naughty spec")
NaughtySpec
python
allegroai__clearml
clearml/backend_api/services/v2_13/models.py
{ "start": 18489, "end": 21098 }
class ____(Request): """ Add or update model metadata :param model: ID of the model :type model: str :param metadata: Metadata items to add or update :type metadata: Metadata """ _service = "models" _action = "add_or_update_metadata" _version = "2.13" _schema = { "de...
AddOrUpdateMetadataRequest