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
spyder-ide__spyder
spyder/utils/stylesheet.py
{ "start": 11722, "end": 13004 }
class ____(SpyderStyleSheet): """Stylesheet for application toolbars.""" BUTTON_WIDTH = '47px' BUTTON_HEIGHT = '47px' BUTTON_MARGIN_LEFT = '3px' BUTTON_MARGIN_RIGHT = '3px' def set_stylesheet(self): css = self.get_stylesheet() # Main background color css.QToolBar.setVa...
ApplicationToolbarStylesheet
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/_generated.py
{ "start": 17198, "end": 18019 }
class ____(BaseModel): """ Asset event schema with fields that are needed for Runtime. """ id: Annotated[int, Field(title="Id")] timestamp: Annotated[AwareDatetime, Field(title="Timestamp")] extra: Annotated[dict[str, JsonValue] | None, Field(title="Extra")] = None asset: AssetResponse ...
AssetEventResponse
python
PyCQA__pylint
tests/functional/u/unnecessary/unnecessary_ellipsis.py
{ "start": 1836, "end": 2933 }
class ____(List[int]): @overload def __getitem__(self, index: int) -> int: ... @overload def __getitem__(self, index: slice) -> List[int]: ... def __getitem__(self, index: Union[int, slice]) -> Union[int, List[int]]: if isinstance(index, int): ... elif isinstance(index,...
MyIntegerList
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/versions/v2025_08_10.py
{ "start": 1912, "end": 2315 }
class ____(VersionChange): """Add the `include_prior_dates` field to GetXComSliceFilterParams and GetXcomFilterParams.""" description = __doc__ instructions_to_migrate_to_previous_version = ( schema(GetXComSliceFilterParams).field("include_prior_dates").didnt_exist, schema(GetXcomFilterPar...
AddIncludePriorDatesToGetXComSlice
python
Textualize__textual
src/textual/css/_style_properties.py
{ "start": 17777, "end": 18379 }
class ____: """Descriptor for getting and setting keyline information.""" def __get__( self, obj: StylesBase, objtype: type[StylesBase] | None = None ) -> tuple[CanvasLineType, Color]: return obj.get_rule("keyline", ("none", TRANSPARENT)) # type: ignore[return-value] def __set__(self,...
KeylineProperty
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_common_errors.py
{ "start": 3155, "end": 5083 }
class ____: """Test detection of incorrect indentation in docstrings.""" # Using function-based validation approach def test_incorrect_parameter_indentation(self): """Test detection of incorrect parameter description indentation.""" docstring = '''"""Function with incorrect parameter inden...
TestIndentationErrors
python
django__django
django/template/base.py
{ "start": 39957, "end": 40440 }
class ____(list): # Set to True the first time a non-TextNode is inserted by # extend_nodelist(). contains_nontext = False def render(self, context): return SafeString("".join([node.render_annotated(context) for node in self])) def get_nodes_by_type(self, nodetype): "Return a list ...
NodeList
python
langchain-ai__langchain
libs/core/langchain_core/tools/retriever.py
{ "start": 520, "end": 3791 }
class ____(BaseModel): """Input to the retriever.""" query: str = Field(description="query to look up in retriever") def _get_relevant_documents( query: str, retriever: BaseRetriever, document_prompt: BasePromptTemplate, document_separator: str, callbacks: Callbacks = None, response_f...
RetrieverInput
python
django__django
tests/composite_pk/test_update.py
{ "start": 208, "end": 7663 }
class ____(TestCase): maxDiff = None @classmethod def setUpTestData(cls): cls.tenant_1 = Tenant.objects.create(name="A") cls.tenant_2 = Tenant.objects.create(name="B") cls.user_1 = User.objects.create( tenant=cls.tenant_1, id=1, email="user0001@ex...
CompositePKUpdateTests
python
getsentry__sentry
src/sentry/types/activity.py
{ "start": 24, "end": 2378 }
class ____(Enum): SET_RESOLVED = 1 SET_UNRESOLVED = 2 SET_IGNORED = 3 SET_PUBLIC = 4 SET_PRIVATE = 5 SET_REGRESSION = 6 CREATE_ISSUE = 7 NOTE = 8 FIRST_SEEN = 9 RELEASE = 10 ASSIGNED = 11 UNASSIGNED = 12 SET_RESOLVED_IN_RELEASE = 13 MERGE = 14 SET_RESOLVED_BY_...
ActivityType
python
pytorch__pytorch
tools/linter/adapters/ruff_linter.py
{ "start": 360, "end": 565 }
class ____(str, enum.Enum): """Severity of a lint message.""" ERROR = "error" WARNING = "warning" ADVICE = "advice" DISABLED = "disabled" @dataclasses.dataclass(frozen=True)
LintSeverity
python
langchain-ai__langchain
libs/core/langchain_core/output_parsers/openai_tools.py
{ "start": 9969, "end": 12815 }
class ____(JsonOutputToolsParser): """Parse tools from OpenAI response.""" tools: Annotated[list[TypeBaseModel], SkipValidation()] """The tools to parse.""" # TODO: Support more granular streaming of objects. Currently only streams once all # Pydantic object fields are present. def parse_resul...
PydanticToolsParser
python
scipy__scipy
scipy/interpolate/tests/test_bsplines.py
{ "start": 84371, "end": 86375 }
class ____: def __init__(self, t, c, k=3): """Tensor product spline object. c[i1, i2, ..., id] * B(x1, i1) * B(x2, i2) * ... * B(xd, id) Parameters ---------- c : ndarray, shape (n1, n2, ..., nd, ...) b-spline coefficients t : tuple of 1D ndarrays ...
NdBSpline0
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_date_1904_02.py
{ "start": 342, "end": 1348 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("date_1904_02.xlsx") def test_create_file(self): """Test the creation of a XlsxWriter file with date times in 1900 and1904 epochs.""" ...
TestCompareXLSXFiles
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py
{ "start": 27217, "end": 29197 }
class ____: JOB_NAME = "job_name" ROLE_ARN = "role_arn" MODEL_ID = "model_id" INPUT_URI = "input_uri" OUTPUT_URI = "output_uri" INVOKE_KWARGS = {"tags": {"key": "key", "value": "value"}} JOB_ARN = "job_arn" @pytest.fixture def mock_conn(self) -> Generator[BaseAwsConnection, None, N...
TestBedrockBatchInferenceOperator
python
tensorflow__tensorflow
tensorflow/python/tpu/tests/tpu_embedding_v2_correctness_hd_ragged_forward_test.py
{ "start": 954, "end": 1441 }
class ____( tpu_embedding_v2_correctness_base_test.TPUEmbeddingCorrectnessBaseTest): @parameterized.parameters( ['sgd', 'adagrad', 'adam', 'ftrl', 'adagrad_momentum']) def test_embedding(self, optimizer_name): if optimizer_name != 'sgd': self.skip_if_oss() self._test_embedding( opti...
TPUEmbeddingCorrectnessTest
python
ray-project__ray
rllib/core/learner/torch/torch_differentiable_learner.py
{ "start": 930, "end": 16838 }
class ____(DifferentiableLearner): """A `DifferentiableLearner` class leveraging PyTorch for functional updates. This class utilizes PyTorch 2.0's `func` module to perform functional updates on the provided parameters. """ # Set the framework to `"torch"`. framework: str = "torch" def __i...
TorchDifferentiableLearner
python
boto__boto3
tests/unit/dynamodb/test_transform.py
{ "start": 2541, "end": 12328 }
class ____(BaseTransformationTest): def setUp(self): super().setUp() self.transformation = lambda params: self.transformed_value self.add_shape({self.target_shape: {'type': 'string'}}) def test_transform_structure(self): input_params = { 'Structure': { ...
TestInputOutputTransformer
python
pytorch__pytorch
torch/nn/modules/activation.py
{ "start": 25933, "end": 27439 }
class ____(Module): r"""Applies the Softplus function element-wise. .. math:: \text{Softplus}(x) = \frac{1}{\beta} * \log(1 + \exp(\beta * x)) SoftPlus is a smooth approximation to the ReLU function and can be used to constrain the output of a machine to always be positive. For numerical ...
Softplus
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/language/visitor_meta.py
{ "start": 1912, "end": 2980 }
class ____(type): def __new__(cls, name, bases, attrs): enter_handlers = {} leave_handlers = {} for base in bases: if hasattr(base, '_enter_handlers'): enter_handlers.update(base._enter_handlers) if hasattr(base, '_leave_handlers'): ...
VisitorMeta
python
keon__algorithms
tests/test_dp.py
{ "start": 4544, "end": 4797 }
class ____(unittest.TestCase): def test_longest_increasing_subsequence_optimized(self): sequence = [1, 101, 10, 2, 3, 100, 4, 6, 2] self.assertEqual(5, longest_increasing_subsequence(sequence))
TestLongestIncreasingSubsequenceOptimized
python
apache__airflow
providers/google/tests/unit/google/cloud/sensors/test_gcs.py
{ "start": 10904, "end": 14827 }
class ____: @mock.patch("airflow.providers.google.cloud.sensors.gcs.GCSHook") def test_should_pass_arguments_to_hook(self, mock_hook): task = GCSObjectsWithPrefixExistenceSensor( task_id="task-id", bucket=TEST_BUCKET, prefix=TEST_PREFIX, google_cloud_conn_...
TestGoogleCloudStoragePrefixSensor
python
getsentry__sentry
src/sentry/workflow_engine/types.py
{ "start": 9647, "end": 11279 }
class ____(ABC, Generic[T]): @staticmethod @abstractmethod def bulk_get_query_object(data_sources) -> dict[int, T | None]: """ Bulk fetch related data-source models returning a dict of the `DataSource.id -> T`. """ raise NotImplementedError @staticmethod @abs...
DataSourceTypeHandler
python
langchain-ai__langchain
libs/langchain_v1/tests/integration_tests/cache/fake_embeddings.py
{ "start": 150, "end": 1007 }
class ____(Embeddings): """Fake embeddings functionality for testing.""" def embed_documents(self, texts: list[str]) -> list[list[float]]: """Return simple embeddings. Embeddings encode each text as its index. """ return [[1.0] * 9 + [float(i)] for i in range(len(texts))] ...
FakeEmbeddings
python
sympy__sympy
sympy/polys/polyerrors.py
{ "start": 2364, "end": 2421 }
class ____(BasePolynomialError): pass
HeuristicGCDFailed
python
google__pytype
pytype/pyc/opcodes.py
{ "start": 16212, "end": 16304 }
class ____(OpcodeWithArg): # Arg: Flags _FLAGS = HAS_ARGUMENT __slots__ = ()
FORMAT_VALUE
python
django__django
django/contrib/admin/migrations/0001_initial.py
{ "start": 111, "end": 2507 }
class ____(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("contenttypes", "__first__"), ] operations = [ migrations.CreateModel( name="LogEntry", fields=[ ( "id", ...
Migration
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 142853, "end": 146774 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[4, 3]", L_y_: "f32[3, 4]"): l_x_ = L_x_ l_y_ = L_y_ _saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable("torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue wi...
GraphModule
python
jamielennox__requests-mock
requests_mock/mocker.py
{ "start": 9163, "end": 11439 }
class ____(MockerCore): """The standard entry point for mock Adapter loading. """ #: Defines with what should method name begin to be patched TEST_PREFIX = 'test' def __init__(self, **kwargs): """Create a new mocker adapter. :param str kw: Pass the mock object through to the decor...
Mocker
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 1606, "end": 2828 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, app_id: str, api_token: str, start_date: str, timezone: Optional[str] = None, ): """Airbyte Source for Appsflyer. Args: name (str): The name of the destinat...
AppsflyerSource
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_contextlib.py
{ "start": 17833, "end": 22458 }
class ____(__TestCase): @support.requires_docstrings def test_instance_docs(self): # Issue 19330: ensure context manager instances have good docstrings cm_docstring = mycontext.__doc__ obj = mycontext() self.assertEqual(obj.__doc__, cm_docstring) def test_contextdecorator(s...
TestContextDecorator
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 114252, "end": 114593 }
class ____(BaseModel): """ Pair of points (a, b) with score """ a: "ExtendedPointId" = Field(..., description="Pair of points (a, b) with score") b: "ExtendedPointId" = Field(..., description="Pair of points (a, b) with score") score: float = Field(..., description="Pair of points (a, b) with s...
SearchMatrixPair
python
tensorflow__tensorflow
tensorflow/compiler/mlir/quantization/tensorflow/calibrator/calibration_algorithm.py
{ "start": 13537, "end": 15090 }
class ____(_HistogramCalibrationAlgorithmBase): """HistogramMseSymmetric for calculating min and max values of calibration result.""" def get_min_max_value(self) -> tuple[float, float]: """Finds min and max starting from the center index. The HistogramMseSymmetric method starts from the center bin and exp...
_HistogramMseSymmetric
python
pytorch__pytorch
test/test_fx_passes.py
{ "start": 6828, "end": 14113 }
class ____(JitTestCase): @parametrize("fn, expected_partition, bookend_non_compute_pass", [ (TestPartitionFunctions.forward1, [["add_7", "add_6"], ["add_5", "add_4", "add_3"], ["add_2", "add_1", "add"]], False), (TestPartitionFunctions.forward2, [["add_3", "add_2"], ["add_1", "add"]], False), ...
TestFXGraphPasses
python
sympy__sympy
sympy/logic/algorithms/lra_theory.py
{ "start": 31052, "end": 31770 }
class ____(): """ Object to keep track of upper and lower bounds on `self.var`. """ def __init__(self, var): self.upper = LRARational(float("inf"), 0) self.upper_from_eq = False self.upper_from_neg = False self.lower = LRARational(-float("inf"), 0) self.lower_...
LRAVariable
python
pytorch__pytorch
torch/distributions/constraints.py
{ "start": 15205, "end": 15504 }
class ____(Constraint): """ Constrain to the unit simplex in the innermost (rightmost) dimension. Specifically: `x >= 0` and `x.sum(-1) == 1`. """ event_dim = 1 def check(self, value): return torch.all(value >= 0, dim=-1) & ((value.sum(-1) - 1).abs() < 1e-6)
_Simplex
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_theme05.py
{ "start": 350, "end": 2146 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_theme05.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Wo...
TestCompareXLSXFiles
python
openai__openai-python
src/openai/lib/streaming/responses/_responses.py
{ "start": 3166, "end": 4303 }
class ____(Generic[TextFormatT]): def __init__( self, api_request: Callable[[], Stream[RawResponseStreamEvent]], *, text_format: type[TextFormatT] | Omit, input_tools: Iterable[ToolParam] | Omit, starting_after: int | None, ) -> None: self.__stream: Respon...
ResponseStreamManager
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_simplify/SIM910.py
{ "start": 1026, "end": 1431 }
class ____: def __init__(self): self.name = "Tom" data = Data() ages = {"Tom": 23, "Maria": 23, "Dog": 11} age = ages.get(data.name, None) # Complex expression as key ages = {"Tom": 23, "Maria": 23, "Dog": 11} age = ages.get("Tom" if True else "Maria", None) # Function call as key def get_key(): retu...
Data
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 2278, "end": 2907 }
class ____(TypedDict): """The serializable data passed from the orchestration process to the external process. This gets wrapped in a :py:class:`PipesContext`. """ asset_keys: Optional[Sequence[str]] code_version_by_asset_key: Optional[Mapping[str, Optional[str]]] provenance_by_asset_key: Optio...
PipesContextData
python
pydantic__pydantic
pydantic/deprecated/config.py
{ "start": 1876, "end": 2508 }
class ____(type): def __getattribute__(self, __name: str) -> Any: # The @deprecated decorator accesses other attributes, so we only emit a warning for the expected ones if __name in {'allow', 'ignore', 'forbid'}: warnings.warn( "`pydantic.config.Extra` is deprecated, use ...
_ExtraMeta
python
pyca__cryptography
tests/doubles.py
{ "start": 475, "end": 621 }
class ____(CipherAlgorithm): name = "dummy-cipher" block_size = 128 key_size = 256 key_sizes = frozenset([256])
DummyCipherAlgorithm
python
kamyu104__LeetCode-Solutions
Python/move-zeroes.py
{ "start": 29, "end": 587 }
class ____(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ pos = 0 for i in xrange(len(nums)): if nums[i]: nums[i], nums[pos] = nums[pos], nums[i] ...
Solution
python
plotly__plotly.py
plotly/graph_objs/scattergeo/_line.py
{ "start": 233, "end": 4133 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattergeo" _path_str = "scattergeo.line" _valid_props = {"color", "dash", "width"} @property def color(self): """ Sets the line color. The 'color' property is a color and may be specified as: - A hex string...
Line
python
getsentry__sentry
src/sentry/digests/types.py
{ "start": 977, "end": 1401 }
class ____(NamedTuple): key: str value: Notification timestamp: float @property def datetime(self) -> datetime_mod.datetime: return to_datetime(self.timestamp) def with_rules(self, rules: list[Rule]) -> RecordWithRuleObjects: return RecordWithRuleObjects( key=self.k...
Record
python
django-haystack__django-haystack
test_haystack/solr_tests/test_solr_backend.py
{ "start": 28859, "end": 30069 }
class ____(TestCase): def test_all_cases(self, mock_send_request, mock_log): self.sample_objs = [] for i in range(1, 4): mock = MockModel() mock.id = i mock.author = "daniel%s" % i mock.pub_date = datetime.date(2009, 2, 25) - datetime.timedelta(days=i...
FailedSolrSearchBackendTestCase
python
fluentpython__example-code
attic/sequences/table.py
{ "start": 2638, "end": 4572 }
class ____(collections.UserList): """A table with rows, all of the same width""" def __init__(self, rows): super().__init__(Row(r) for r in rows) if len(self) < 1: raise ValueError('Table must have at least one row.') self.width = self.check_width() def check_width(self...
Table
python
huggingface__transformers
src/transformers/models/flex_olmo/modular_flex_olmo.py
{ "start": 13311, "end": 15827 }
class ____(MixtralModel): @check_model_inputs() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, ...
FlexOlmoModel
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/comments.py
{ "start": 7275, "end": 8560 }
class ____: """ line and column information wrt document, values start at zero (0) """ attrib = line_col_attrib def __init__(self): # type: () -> None self.line = None self.col = None self.data = None # type: Optional[Dict[Any, Any]] def add_kv_line_col(self, ...
LineCol
python
getsentry__sentry
src/sentry/integrations/api/endpoints/integration_features.py
{ "start": 734, "end": 1276 }
class ____(Endpoint): owner = ApiOwner.INTEGRATIONS publish_status = { "GET": ApiPublishStatus.PRIVATE, } permission_classes = (IntegrationFeaturesPermissions,) def get(self, request: Request, *args: Any, **kwargs: Any) -> Response: return self.respond( [ ...
IntegrationFeaturesEndpoint
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0027_remove_json_with_html_feature.py
{ "start": 533, "end": 773 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0026_ad-free-option"), ] operations = [ migrations.RunPython(forward_add_feature, reverse_add_feature), ]
Migration
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_pretty.py
{ "start": 20734, "end": 20832 }
class ____: def _repr_pretty_(self, p, cycle): p.text("I am a banana") @dataclass
Banana
python
cython__cython
Cython/Compiler/TypeSlots.py
{ "start": 21940, "end": 23561 }
class ____(SlotDescriptor): # Descriptor for a substructure of the type object. # # sub_slots [SlotDescriptor] def __init__(self, sub_slots, slot_type, slot_name, substructures, ifdef=None, cast_cname=None): SlotDescriptor.__init__(self, slot_name, ifdef=ifdef) self.sub_slots = sub_...
SuiteSlot
python
django__django
tests/custom_managers/models.py
{ "start": 6518, "end": 6569 }
class ____(AbstractPerson): pass
PersonFromAbstract
python
cherrypy__cherrypy
cherrypy/lib/cpstats.py
{ "start": 11781, "end": 16323 }
class ____(cherrypy.Tool): """Record various information about the current request.""" def __init__(self): """Initialize the statistics gathering tool.""" cherrypy.Tool.__init__(self, 'on_end_request', self.record_stop) def _setup(self): """Plug this tool into ``cherrypy.request``....
StatsTool
python
scrapy__scrapy
tests/test_command_shell.py
{ "start": 4889, "end": 5666 }
class ____: def test_fetch(self, mockserver: MockServer) -> None: args = ( sys.executable, "-m", "scrapy.cmdline", "shell", ) env = os.environ.copy() env["SCRAPY_PYTHON_SHELL"] = "python" logfile = BytesIO() # https://gi...
TestInteractiveShell
python
pypa__pip
src/pip/_vendor/rich/_win32_console.py
{ "start": 10402, "end": 22755 }
class ____: """This class allows interaction with the legacy Windows Console API. It should only be used in the context of environments where virtual terminal processing is not available. However, if it is used in a Windows environment, the entire API should work. Args: file (IO[str]): The file...
LegacyWindowsTerm
python
sphinx-doc__sphinx
sphinx/domains/std/__init__.py
{ "start": 2994, "end": 3817 }
class ____(XRefRole): """Cross-referencing role for environment variables (adds an index entry).""" def result_nodes( self, document: nodes.document, env: BuildEnvironment, node: Element, is_ref: bool, ) -> tuple[list[Node], list[system_message]]: if not is_r...
EnvVarXRefRole
python
python-attrs__attrs
tests/test_packaging.py
{ "start": 203, "end": 1033 }
class ____: def test_version(self, mod, recwarn): """ __version__ returns the correct version and doesn't warn. """ assert metadata.version("attrs") == mod.__version__ assert [] == recwarn.list def test_does_not_exist(self, mod): """ Asking for unsupport...
TestLegacyMetadataHack
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 18680, "end": 19661 }
class ____(PrefectFilterBaseModel): """Filter by `FlowRun.next_scheduled_start_time`.""" before_: Optional[DateTime] = Field( default=None, description=( "Only include flow runs with a next_scheduled_start_time or before this" " time" ), ) after_: Optiona...
FlowRunFilterNextScheduledStartTime
python
huggingface__transformers
src/transformers/models/nanochat/modular_nanochat.py
{ "start": 4323, "end": 4592 }
class ____(CLIPMLP): def __init__(self, config): super().__init__(config) self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
NanoChatMLP
python
pallets__werkzeug
src/werkzeug/routing/exceptions.py
{ "start": 598, "end": 1225 }
class ____(HTTPException, RoutingException): """Raise if the map requests a redirect. This is for example the case if `strict_slashes` are activated and an url that requires a trailing slash. The attribute `new_url` contains the absolute destination url. """ code = 308 def __init__(self, new_...
RequestRedirect
python
davidhalter__jedi
jedi/inference/filters.py
{ "start": 11155, "end": 11705 }
class ____(type): def __init__(cls, name, bases, dct): super().__init__(name, bases, dct) base_dct = {} for base_cls in reversed(cls.__bases__): try: base_dct.update(base_cls.overwritten_methods) except AttributeError: pass fo...
_OverwriteMeta
python
huggingface__transformers
src/transformers/models/dots1/modeling_dots1.py
{ "start": 18749, "end": 20704 }
class ____(GradientCheckpointingLayer): def __init__(self, config: Dots1Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = Dots1Attention(config=config, layer_idx=layer_idx) if layer_idx >= config.first_k_dense_replace: se...
Dots1DecoderLayer
python
justquick__django-activity-stream
actstream/gfk.py
{ "start": 478, "end": 1436 }
class ____(QuerySet): """ A QuerySet with a fetch_generic_relations() method to bulk fetch all generic related items. Similar to select_related(), but for generic foreign keys. This wraps QuerySet.prefetch_related. """ def fetch_generic_relations(self, *args): qs = self._clone() ...
GFKQuerySet
python
numba__numba
numba/core/errors.py
{ "start": 19101, "end": 19243 }
class ____(NumbaError): """ An error occurred because parfors is not supported on the platform. """ pass
UnsupportedParforsError
python
huggingface__transformers
tests/models/modernbert/test_modeling_modernbert.py
{ "start": 9443, "end": 22372 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( ModernBertModel, ModernBertForMaskedLM, ModernBertForSequenceClassification, ModernBertForTokenClassification, ModernBertForQuestionAnswering, ...
ModernBertModelTest
python
scrapy__scrapy
tests/spiders.py
{ "start": 6237, "end": 6538 }
class ____(SimpleSpider): name = "asyncdef_deferred_wrapped" async def parse(self, response): resp = await maybe_deferred_to_future( get_web_client_agent_req(self.mockserver.url("/status?n=200")) ) yield {"code": resp.code}
AsyncDefDeferredMaybeWrappedSpider
python
facebook__pyre-check
client/dataclasses_json_extensions.py
{ "start": 480, "end": 706 }
class ____(dataclasses_json.DataClassJsonMixin): @classmethod @functools.lru_cache(maxsize=64) def cached_schema(cls) -> dataclasses_json.api.SchemaType: return cls.schema()
DataclassJsonMixinWithCachedSchema
python
tensorflow__tensorflow
tensorflow/python/distribute/failure_handling/preemption_watcher.py
{ "start": 1900, "end": 5788 }
class ____: """Watch preemption signal and store it. Notice: Currently only support Borg TPU environment with TPUClusterResolver. This class provides a way to monitor the preemption signal during training on TPU. It will start a background thread to watch the training process, trying to fetch preemption mes...
PreemptionWatcher
python
anthropics__anthropic-sdk-python
src/anthropic/lib/streaming/_messages.py
{ "start": 828, "end": 4335 }
class ____: text_stream: Iterator[str] """Iterator over just the text deltas in the stream. ```py for text in stream.text_stream: print(text, end="", flush=True) print() ``` """ def __init__(self, raw_stream: Stream[RawMessageStreamEvent]) -> None: self._raw_stream = ra...
MessageStream
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_misc.py
{ "start": 2017, "end": 24163 }
class ____(FSDPTest): @property def world_size(self): return 2 @property def process_group(self): return dist.distributed_c10d._get_default_group() @skip_if_lt_x_gpu(2) @parametrize("use_index", [True, False]) def test_fsdp_device_id(self, use_index): """ Te...
TestFSDPMiscMultiProcess
python
pypa__hatch
tests/backend/metadata/test_core.py
{ "start": 46010, "end": 49808 }
class ____: def test_dynamic(self, isolation): metadata = ProjectMetadata( str(isolation), None, {"project": {"dependencies": 9000, "dynamic": ["dependencies"]}} ) with pytest.raises( ValueError, match=( "Metadata field `dependencies` cann...
TestDependencies
python
google__jax
tests/sparse_test.py
{ "start": 31510, "end": 43926 }
class ____(sptu.SparseTestCase): @parameterized.named_parameters( {"testcase_name": f"_{cls.__name__}", "cls": cls} for cls in [sparse.CSR, sparse.CSC, sparse.COO, sparse.BCOO, sparse.BCSR]) def test_pytree_flattening(self, cls): sparse_format = cls.__name__.lower() M = sparse.empty((2, 4), sparse_f...
SparseObjectTest
python
tensorflow__tensorflow
tensorflow/python/distribute/collective_all_reduce_strategy_test.py
{ "start": 18243, "end": 27234 }
class ____( CollectiveAllReduceStrategyTestBase, strategy_test_lib.DistributionTestBase, strategy_test_lib.TwoDeviceDistributionTestBase, parameterized.TestCase): @combinations.generate(combinations.combine(mode=['eager'])) def testStrategyInitializationError(self): with self.assertRaisesRegex( ...
SingleWorkerCollectiveAllReduceStrategy
python
google__pytype
pytype/load_pytd_test.py
{ "start": 31711, "end": 37052 }
class ____(test_base.UnitTest): def _create_files(self, tempdir): src = """ import module2 from typing import List constant = True x = List[int] b = List[int] class SomeClass: def __init__(self, a: module2.ObjectMod2): pass def Mod...
PickledPyiLoaderTest
python
getsentry__sentry
src/sentry/integrations/services/repository/impl.py
{ "start": 776, "end": 6381 }
class ____(RepositoryService): def serialize_repository( self, *, organization_id: int, id: int, as_user: RpcUser | None = None, ) -> Any | None: repository = Repository.objects.filter(id=id).first() if repository is None: return None r...
DatabaseBackedRepositoryService
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 89784, "end": 93257 }
class ____(GoogleCloudBaseOperator): """ Deletes an asset resource. :param project_id: Required. The ID of the Google Cloud project that the task belongs to. :param region: Required. The ID of the Google Cloud region that the task belongs to. :param lake_id: Required. The ID of the Google Cloud lak...
DataplexDeleteAssetOperator
python
streamlit__streamlit
lib/tests/streamlit/runtime/fragment_test.py
{ "start": 3492, "end": 18152 }
class ____(unittest.TestCase): def setUp(self): self.original_dg_stack = context_dg_stack.get() root_container = MagicMock() context_dg_stack.set( ( DeltaGenerator( root_container=root_container, cursor=MagicMock(root_contai...
FragmentTest
python
takluyver__flit
flit_core/flit_core/common.py
{ "start": 214, "end": 3560 }
class ____: """This represents the module/package that we are going to distribute """ in_namespace_package = False namespace_package_name = None def __init__(self, name: str, directory=Path()): self.name = name self.is_stub_pkg = name.endswith('-stubs') # It must exist eith...
Module
python
apache__airflow
task-sdk/tests/task_sdk/definitions/_internal/test_templater.py
{ "start": 1043, "end": 4469 }
class ____: def test_get_template_env(self): # Test get_template_env when a Dag is provided templater = Templater() dag = DAG(dag_id="test_dag", schedule=None, render_template_as_native_obj=True) env = templater.get_template_env(dag) assert isinstance(env, jinja2.Environment)...
TestTemplater
python
doocs__leetcode
solution/1800-1899/1818.Minimum Absolute Sum Difference/Solution.py
{ "start": 0, "end": 554 }
class ____: def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: mod = 10**9 + 7 nums = sorted(nums1) s = sum(abs(a - b) for a, b in zip(nums1, nums2)) % mod mx = 0 for a, b in zip(nums1, nums2): d1, d2 = abs(a - b), inf i = bisect_...
Solution
python
keras-team__keras
keras/src/layers/pooling/global_average_pooling3d.py
{ "start": 265, "end": 2603 }
class ____(BaseGlobalPooling): """Global average pooling operation for 3D data. Args: data_format: string, either `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, spatia...
GlobalAveragePooling3D
python
weaviate__weaviate-python-client
journey_tests/journeys.py
{ "start": 206, "end": 1255 }
class ____: def __init__(self, client: WeaviateClient) -> None: self.__client = client @classmethod def use(cls) -> "SyncJourneys": return cls(connect_to_local(port=8090, grpc_port=50061)) def close(self) -> None: self.__client.close() def simple(self) -> List[dict]: ...
SyncJourneys
python
gevent__gevent
src/greentest/3.10/test_ftplib.py
{ "start": 34349, "end": 39285 }
class ____(TestCase): """Specific TLS_FTP class tests.""" def setUp(self, encoding=DEFAULT_ENCODING): self.server = DummyTLS_FTPServer((HOST, 0), encoding=encoding) self.server.start() self.client = ftplib.FTP_TLS(timeout=TIMEOUT) self.client.connect(self.server.host, self.serve...
TestTLS_FTPClass
python
getsentry__sentry
src/sentry/api/serializers/models/exploresavedquery.py
{ "start": 740, "end": 914 }
class ____(TypedDict): orderby: list[dict[str, str]] | None equations: list[dict[str, str | list[str]]] | None columns: list[str]
ExploreSavedQueryChangedReasonType
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 104543, "end": 105466 }
class ____(Operation): def __init__(self, axis=None, *, name=None): super().__init__(name=name) self.axis = axis def call(self, x): return backend.numpy.flip(x, axis=self.axis) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) @keras_export(["ke...
Flip
python
openai__openai-python
src/openai/types/realtime/realtime_mcp_list_tools.py
{ "start": 560, "end": 889 }
class ____(BaseModel): server_label: str """The label of the MCP server.""" tools: List[Tool] """The tools available on the server.""" type: Literal["mcp_list_tools"] """The type of the item. Always `mcp_list_tools`.""" id: Optional[str] = None """The unique ID of the list."""
RealtimeMcpListTools
python
PrefectHQ__prefect
tests/server/utilities/test_schemas.py
{ "start": 5567, "end": 6373 }
class ____: @pytest.mark.parametrize("type_", (PlainOwner, ModelOwner)) def test_class_access(self, type_: Union[PlainOwner, ModelOwner]): assert type_.descr is type_.__dict__["descr"] def test_base_implementation(self): instance = PlainOwner() with pytest.raises(AttributeError): ...
TestPrefectDescriptorBase
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 55762, "end": 55955 }
class ____(PyConstNode): # '...' in a subscript list. value = "Py_Ellipsis" constant_result = Ellipsis def compile_time_value(self, denv): return Ellipsis
EllipsisNode
python
django__django
tests/serializers/test_deserialization.py
{ "start": 478, "end": 4336 }
class ____(SimpleTestCase): def setUp(self): self.object_list = [ {"pk": 1, "model": "serializers.author", "fields": {"name": "Jane"}}, {"pk": 2, "model": "serializers.author", "fields": {"name": "Joe"}}, ] self.deserializer = Deserializer(self.object_list) se...
TestDeserializer
python
django__django
django/contrib/gis/geos/prototypes/geom.py
{ "start": 913, "end": 1062 }
class ____(GEOSFuncFactory): "For GEOS routines that return a geometry." restype = GEOM_PTR errcheck = staticmethod(check_geom)
GeomOutput
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/via_type_of.py
{ "start": 2497, "end": 3501 }
class ____: x = ... y: Any = 0 z: object = [] def test4_alarm1(c: Test4_C): # always-via-type:unknown c.x = _test_source() def test4_alarm2(c: Test4_C): # always-via-type:Any c.y = _test_source() def test4_alarm3(c: Test4_C): # always-via-type:object c.z = _test_source() def ...
Test4_C
python
getsentry__sentry
tests/sentry/core/endpoints/test_project_team_details.py
{ "start": 257, "end": 440 }
class ____(APITestCase): endpoint = "sentry-api-0-project-team-details" def setUp(self) -> None: super().setUp() self.login_as(self.user)
ProjectTeamDetailsTest
python
django__django
tests/test_utils/test_transactiontestcase.py
{ "start": 1277, "end": 1797 }
class ____(TestCase): available_apps = [] databases = {"default", "other"} def test_queries_cleared(self): """ TransactionTestCase._pre_setup() clears the connections' queries_log so that it's less likely to overflow. An overflow causes assertNumQueries() to fail. ""...
TransactionTestCaseDatabasesTests
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py
{ "start": 32663, "end": 33679 }
class ____(nn.Module): """ This module adds 2D position embeddings to all intermediate feature maps of the convolutional encoder. """ def __init__(self, conv_encoder, position_embedding): super().__init__() self.conv_encoder = conv_encoder self.position_embedding = position_embe...
MMGroundingDinoConvModel
python
getsentry__sentry
src/sentry/api/serializers/models/userreport.py
{ "start": 811, "end": 914 }
class ____(UserReportSerializerResponse): issue: dict[str, Any]
UserReportWithGroupSerializerResponse
python
realpython__materials
build-a-django-content-aggregator/source_code_final/podcasts/tests.py
{ "start": 135, "end": 1504 }
class ____(TestCase): def setUp(self): self.episode = Episode.objects.create( title="My Awesome Podcast Episode", description="Look mom, I made it!", pub_date=timezone.now(), link="https://myawesomeshow.com", image="https://image.myawesomeshow.com"...
PodCastsTests
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 73573, "end": 75506 }
class ____(SimpleHandlerTestCase): class Handler(RequestHandler): def get(self): exc = self.get_argument("exc") if exc == "http": raise HTTPError(410, "no longer here") elif exc == "zero": 1 / 0 elif exc == "permission": ...
ExceptionHandlerTest
python
kamyu104__LeetCode-Solutions
Python/maximum-subarray-with-equal-products.py
{ "start": 939, "end": 1380 }
class ____(object): def maxLength(self, nums): """ :type nums: List[int] :rtype: int """ result = 2 lookup = collections.defaultdict(int) left = 0 for right, x in enumerate(nums): for p in PRIME_DIVISORS[x]: left = max(left,...
Solution