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
apache__airflow
providers/fab/src/airflow/providers/fab/auth_manager/views/user.py
{ "start": 4055, "end": 4869 }
class ____(MultiResourceUserMixin, UserRemoteUserModelView): """Customize permission names for FAB's builtin UserRemoteUserModelView.""" _class_permission_name = permissions.RESOURCE_USER class_permission_name_mapping = { "userinfoedit": permissions.RESOURCE_MY_PROFILE, "userinfo": permiss...
CustomUserRemoteUserModelView
python
apache__airflow
providers/google/src/airflow/providers/google/suite/transfers/gcs_to_gdrive.py
{ "start": 1339, "end": 7947 }
class ____(BaseOperator): """ Copies objects from a Google Cloud Storage service to a Google Drive service, with renaming if requested. Using this operator requires the following OAuth 2.0 scope: .. code-block:: none https://www.googleapis.com/auth/drive .. seealso:: For more inf...
GCSToGoogleDriveOperator
python
getsentry__sentry
src/sentry/lang/native/symbolicator.py
{ "start": 2498, "end": 15574 }
class ____: def __init__( self, task_kind: SymbolicatorTaskKind, on_request: Callable[[], None], project: Project, event_id: str, ): URLS = settings.SYMBOLICATOR_POOL_URLS pool = pool_for_platform(task_kind.platform) base_url = ( URLS....
Symbolicator
python
huggingface__transformers
src/transformers/models/plbart/modeling_plbart.py
{ "start": 10710, "end": 13723 }
class ____(GradientCheckpointingLayer): def __init__(self, config: PLBartConfig, layer_idx: Optional[int] = None): super().__init__() self.embed_dim = config.d_model self.self_attn = PLBartAttention( embed_dim=self.embed_dim, num_heads=config.encoder_attention_heads,...
PLBartEncoderLayer
python
aio-libs__aiohttp
aiohttp/multipart.py
{ "start": 38054, "end": 40066 }
class ____: def __init__(self, writer: Any) -> None: self._writer = writer self._encoding: str | None = None self._compress: ZLibCompressor | None = None self._encoding_buffer: bytearray | None = None def enable_encoding(self, encoding: str) -> None: if encoding == "base...
MultipartPayloadWriter
python
jina-ai__jina
jina/serve/runtimes/gateway/gateway.py
{ "start": 1184, "end": 1390 }
class ____(JAMLCompatible, metaclass=GatewayType): """ The base class of all custom Gateways, can be used to build a custom interface to a Jina Flow that supports gateway logic """
BaseGateway
python
redis__redis-py
redis/cache.py
{ "start": 2510, "end": 3451 }
class ____(ABC): @property @abstractmethod def collection(self) -> OrderedDict: pass @property @abstractmethod def config(self) -> CacheConfigurationInterface: pass @property @abstractmethod def eviction_policy(self) -> EvictionPolicyInterface: pass @pr...
CacheInterface
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classes1.py
{ "start": 354, "end": 391 }
class ____(metaclass=EMeta): pass
E
python
altair-viz__altair
altair/utils/execeval.py
{ "start": 369, "end": 2716 }
class ____: """Class to temporarily catch sys.displayhook.""" def __init__(self) -> None: self.output: Any | None = None def __enter__(self) -> Self: self.old_hook: Callable[[object], Any] = sys.displayhook sys.displayhook = self return self def __exit__(self, type, va...
_CatchDisplay
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_npfuncs.py
{ "start": 81, "end": 384 }
class ____: def test_split_non_utc(self): # GH#14042 indices = date_range("2016-01-01 00:00:00+0200", freq="s", periods=10) result = np.split(indices, indices_or_sections=[])[0] expected = indices._with_freq(None) tm.assert_index_equal(result, expected)
TestSplit
python
zarr-developers__zarr-python
src/zarr/testing/store.py
{ "start": 782, "end": 20748 }
class ____(Generic[S, B]): store_cls: type[S] buffer_cls: type[B] @abstractmethod async def set(self, store: S, key: str, value: Buffer) -> None: """ Insert a value into a storage backend, with a specific key. This should not use any store methods. Bypassing the store methods al...
StoreTests
python
pyparsing__pyparsing
examples/pythonGrammarParser.py
{ "start": 5883, "end": 5942 }
class ____(SemanticGroup): label = "AND" pass
AndList
python
Textualize__textual
src/textual/demo/projects.py
{ "start": 656, "end": 2604 }
class ____(Vertical, can_focus=True, can_focus_children=False): """Display project information and open repo links.""" ALLOW_MAXIMIZE = True DEFAULT_CSS = """ Project { width: 1fr; height: auto; padding: 0 1; border: tall transparent; box-sizing: border-box; ...
Project
python
kamyu104__LeetCode-Solutions
Python/count-artifacts-that-can-be-extracted.py
{ "start": 115, "end": 611 }
class ____(object): def digArtifacts(self, n, artifacts, dig): """ :type n: int :type artifacts: List[List[int]] :type dig: List[List[int]] :rtype: int """ lookup = set(map(tuple, dig)) return sum(all((i, j) in lookup for i in xrange(r1, r2+1) for j in...
Solution
python
huggingface__transformers
src/transformers/models/kosmos2/modeling_kosmos2.py
{ "start": 35187, "end": 36132 }
class ____(nn.Module): def __init__(self, config: Kosmos2TextConfig): super().__init__() self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropout = config.activation_dropout self.fc1 = nn.Linear(config.embed_dim, config.f...
Kosmos2TextFFN
python
PrefectHQ__prefect
tests/cli/test_deploy.py
{ "start": 218681, "end": 221677 }
class ____: @pytest.fixture async def work_pool(self, prefect_client): await prefect_client.create_work_pool( WorkPoolCreate(name="test-pool", type="test") ) async def test_uses_job_variables( self, project_dir: Path, work_pool: WorkPool, prefect_...
TestDeployInfraOverrides
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/base.py
{ "start": 42373, "end": 43573 }
class ____(sqltypes._Binary): """Implement the SQL Server TIMESTAMP type. Note this is **completely different** than the SQL Standard TIMESTAMP type, which is not supported by SQL Server. It is a read-only datatype that does not support INSERT of values. .. seealso:: :class:`_mssql.ROWVE...
TIMESTAMP
python
gevent__gevent
src/gevent/tests/test__pywsgi.py
{ "start": 24930, "end": 34654 }
class ____(TestCase): calls = 0 def setUp(self): super().setUp() self.calls = 0 def application(self, env, start_response): self.calls += 1 self.assertTrue(env.get('wsgi.input_terminated')) start_response('200 OK', [('Content-Type', 'text/plain')]) if env['...
TestChunkedPost
python
numba__numba
numba/cuda/stubs.py
{ "start": 6929, "end": 7075 }
class ____(Stub): """ brev(x) Returns the reverse of the bit pattern of x. For example, 0b10110110 becomes 0b01101101. """
brev
python
pytorch__pytorch
torch/testing/_internal/common_utils.py
{ "start": 119837, "end": 119932 }
class ____: # causes pytest to not recognize this class as a test __test__ = False
NoTest
python
geekcomputers__Python
venv/Lib/site-packages/pip/_internal/utils/logging.py
{ "start": 6842, "end": 11606 }
class ____(Filter): """ A logging Filter that excludes records from a logger (or its children). """ def filter(self, record: logging.LogRecord) -> bool: # The base Filter class allows only records from a logger (or its # children). return not super().filter(record) def setup_l...
ExcludeLoggerFilter
python
ray-project__ray
rllib/examples/envs/classes/multi_agent/footsies/game/footsies_binary.py
{ "start": 463, "end": 1123 }
class ____: # Uploaded 07.28.2025 S3_ROOT = "https://ray-example-data.s3.us-west-2.amazonaws.com/rllib/env-footsies/binaries/" # Zip file names ZIP_LINUX_SERVER = "footsies_linux_server_021725.zip" ZIP_LINUX_WINDOWED = "footsies_linux_windowed_021725.zip" ZIP_MAC_HEADLESS = "footsies_mac_headle...
BinaryUrls
python
ansible__ansible
test/units/module_utils/facts/system/test_lsb.py
{ "start": 1509, "end": 4399 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'lsb'] valid_subsets = ['lsb'] fact_namespace = 'ansible_lsb' collector_class = LSBFactCollector def _mock_module(self): mock_module = Mock() mock_module.params = {'gather_subset': self.gather_subset, ...
TestLSBFacts
python
sphinx-doc__sphinx
sphinx/search/de.py
{ "start": 191, "end": 589 }
class ____(SearchLanguage): lang = 'de' language_name = 'German' js_stemmer_rawcode = 'german-stemmer.js' stopwords = GERMAN_STOPWORDS def __init__(self, options: dict[str, str]) -> None: super().__init__(options) self.stemmer = snowballstemmer.stemmer('german') def stem(self, ...
SearchGerman
python
pypa__setuptools
setuptools/_distutils/tests/support.py
{ "start": 1370, "end": 4099 }
class ____: """Class to store options for retrieval via set_undefined_options().""" def __init__(self, **kwargs): vars(self).update(kwargs) def ensure_finalized(self): pass def copy_xxmodule_c(directory): """Helper for tests that need the xxmodule.c source file. Example use: ...
DummyCommand
python
astropy__astropy
astropy/io/fits/column.py
{ "start": 13810, "end": 15223 }
class ____(str): """For P format in variable length table.""" # As far as I can tell from my reading of the FITS standard, a type code is # *required* for P and Q formats; there is no default _format_re_template = ( r"(?P<repeat>\d+)?{}(?P<dtype>[LXBIJKAEDCM])(?:\((?P<max>\d*)\))?" ) _f...
_FormatP
python
django-extensions__django-extensions
tests/management/commands/test_update_permissions.py
{ "start": 405, "end": 2905 }
class ____(TestCase): def setUp(self): class PermModel(models.Model): class Meta: app_label = "django_extensions" permissions = (("test_permission", "test_permission"),) class TestModel(models.Model): class Meta: app_label = "t...
UpdatePermissionsTests
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 730260, "end": 730526 }
class ____(sgqlc.types.Type, Contribution): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("issue",) issue = sgqlc.types.Field(sgqlc.types.non_null("Issue"), graphql_name="issue")
CreatedIssueContribution
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_scalar_ctors.py
{ "start": 2333, "end": 3328 }
class ____(TestCase): """gh-15467""" def _do_test(self, t1, t2): x = t1(2) arr = np.array(x, dtype=t2) # type should be preserved exactly if t2 is None: assert arr.dtype.type is t1 else: assert arr.dtype.type is t2 arr1 = np.asarray(x, dt...
TestArrayFromScalar
python
pypa__pip
src/pip/_internal/utils/temp_dir.py
{ "start": 994, "end": 2079 }
class ____: """Manages temp directory behavior""" def __init__(self) -> None: self._should_delete: dict[str, bool] = {} def set_delete(self, kind: str, value: bool) -> None: """Indicate whether a TempDirectory of the given kind should be auto-deleted. """ self._shou...
TempDirectoryTypeRegistry
python
walkccc__LeetCode
solutions/2340. Minimum Adjacent Swaps to Make a Valid Array/2340.py
{ "start": 0, "end": 714 }
class ____: def minimumSwaps(self, nums: list[int]) -> int: minIndex = self._getLeftmostMinIndex(nums) maxIndex = self._getRightmostMaxIndex(nums) swaps = minIndex + (len(nums) - 1 - maxIndex) return swaps if minIndex <= maxIndex else swaps - 1 def _getLeftmostMinIndex(self, nums: list[int]) -> int...
Solution
python
google__jax
tests/api_test.py
{ "start": 259448, "end": 260134 }
class ____(jtu.JaxTestCase): def test_sharding_constraint_as_noop(self): def f(x): return jax.lax.with_sharding_constraint( x, jax.sharding.SingleDeviceSharding(jax.devices()[0])) def wsc_as_noop(ctx, operand, *args, **kwargs): del ctx, args, kwargs return [operand] rules = ...
OverrideLoweringTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F841_0.py
{ "start": 3084, "end": 3175 }
class ____: def foo(): nonlocal __class__ __class__ = 1
NonlocalDunderClass
python
scipy__scipy
scipy/optimize/tests/test__shgo.py
{ "start": 7557, "end": 7933 }
class ____(StructTestFunction): def f(self, x): return ((x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2 + (x[2] - 0.5) ** 2 + (x[3] - 0.5) ** 2) g = None cons = wrap_constraints(g) test_s = StructTestS(bounds=[(0, 2.0), ] * 4, expected_fun=0.0, expe...
StructTestS
python
keon__algorithms
tests/test_bfs.py
{ "start": 104, "end": 848 }
class ____(unittest.TestCase): def test_count_islands(self): grid_1 = [[1, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 0, 0, 0, 0]] self.assertEqual(1, count_islands(grid_1)) grid_2 = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1,...
TestCountIslands
python
pytorch__pytorch
test/inductor/test_lookup_table.py
{ "start": 5862, "end": 26659 }
class ____(BaseLookupTableTest): """Consolidated tests for lookup table functionality""" def test_lookup_mismatch(self): """Test mismatch scenario in lookup table""" kernel_inputs = self.create_mock_mm_kernel_inputs() lookup_table_data = { self.create_lookup_key("mm", kerne...
TestLookupTable
python
PyCQA__pylint
pylint/checkers/design_analysis.py
{ "start": 9880, "end": 24682 }
class ____(BaseChecker): """Checker of potential misdesigns. Checks for sign of poor/misdesign: * number of methods, attributes, local variables... * size, complexity of functions, methods """ # configuration section name name = "design" # messages msgs = MSGS # configuration o...
MisdesignChecker
python
getsentry__sentry
src/sentry/search/events/fields.py
{ "start": 34059, "end": 34764 }
class ____(NumberRange): def __init__(self, name: str, start: float | None, end: float | None): super().__init__(name, start, end) self.has_default = True def get_default(self, params: ParamsType) -> int: if not params or not params.get("start") or not params.get("end"): rai...
IntervalDefault
python
plotly__plotly.py
plotly/graph_objs/histogram2d/_marker.py
{ "start": 233, "end": 2783 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram2d" _path_str = "histogram2d.marker" _valid_props = {"color", "colorsrc"} @property def color(self): """ Sets the aggregation data. The 'color' property is an array that may be specified as a tuple, l...
Marker
python
rq__rq
tests/test_timeouts.py
{ "start": 519, "end": 2639 }
class ____(RQTestCase): def test_timer_death_penalty(self): """Ensure TimerDeathPenalty works correctly.""" q = Queue(connection=self.connection) q.empty() finished_job_registry = FinishedJobRegistry(connection=self.connection) failed_job_registry = FailedJobRegistry(connecti...
TestTimeouts
python
apache__airflow
providers/openai/src/airflow/providers/openai/triggers/openai.py
{ "start": 1050, "end": 4439 }
class ____(BaseTrigger): """Triggers OpenAI Batch API.""" def __init__( self, conn_id: str, batch_id: str, poll_interval: float, end_time: float, ) -> None: super().__init__() self.conn_id = conn_id self.poll_interval = poll_interval s...
OpenAIBatchTrigger
python
encode__django-rest-framework
tests/test_renderers.py
{ "start": 20627, "end": 21344 }
class ____(TestCase): def setUp(self): class TestSerializer(serializers.Serializer): test_field = serializers.CharField() self.renderer = HTMLFormRenderer() self.serializer = TestSerializer(data={}) def test_render_with_default_args(self): self.serializer.is_valid()...
TestHTMLFormRenderer
python
astropy__astropy
astropy/units/tests/test_logarithmic.py
{ "start": 840, "end": 6020 }
class ____: def test_logarithmic_units(self): """Check logarithmic units are set up correctly.""" assert u.dB.to(u.dex) == 0.1 assert u.dex.to(u.mag) == -2.5 assert u.mag.to(u.dB) == -4 @pytest.mark.parametrize("lu_unit, lu_cls", list(zip(lu_units, lu_subclasses))) def test_...
TestLogUnitCreation
python
huggingface__transformers
src/transformers/models/prompt_depth_anything/modular_prompt_depth_anything.py
{ "start": 7166, "end": 8549 }
class ____(DepthAnythingNeck): def forward( self, hidden_states: list[torch.Tensor], patch_height: Optional[int] = None, patch_width: Optional[int] = None, prompt_depth: Optional[torch.Tensor] = None, ) -> list[torch.Tensor]: """ Args: hidden_s...
PromptDepthAnythingNeck
python
ray-project__ray
rllib/connectors/connector.py
{ "start": 9571, "end": 11287 }
class ____(Connector): """Action connector connects policy outputs including actions, to user environments. An action connector transforms a single piece of policy output in ActionConnectorDataType format, which is basically PolicyOutputType plus env and agent IDs. Any functions that operate d...
ActionConnector
python
django__django
tests/forms_tests/tests/test_formsets.py
{ "start": 76962, "end": 77021 }
class ____(TestIsBoundBehavior): pass
TestIsBoundBehavior
python
getsentry__sentry
src/sentry/models/files/control_file.py
{ "start": 516, "end": 1883 }
class ____(AbstractFile[ControlFileBlobIndex, ControlFileBlob]): blobs = models.ManyToManyField("sentry.ControlFileBlob", through="sentry.ControlFileBlobIndex") # Looking for the "blob" FK or the path attribute? These are deprecated and unavailable in the control silo class Meta: app_label = "sentr...
ControlFile
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/oracle/cx_oracle.py
{ "start": 25017, "end": 25135 }
class ____(_LOBDataType, oracle.LONG): def get_dbapi_type(self, dbapi): return dbapi.LONG_STRING
_OracleLong
python
python-openxml__python-docx
src/docx/section.py
{ "start": 14443, "end": 16433 }
class ____(_BaseHeaderFooter): """Page footer, used for all three types (default, even-page, and first-page). Note that, like a document or table cell, a footer must contain a minimum of one paragraph and a new or otherwise "empty" footer contains a single empty paragraph. This first paragraph can be a...
_Footer
python
kamyu104__LeetCode-Solutions
Python/sort-threats-by-severity-and-exploitability.py
{ "start": 40, "end": 277 }
class ____(object): def sortThreats(self, threats): """ :type threats: List[List[int]] :rtype: List[List[int]] """ threats.sort(key=lambda x: (-(2*x[1]+x[2]), x[0])) return threats
Solution
python
getsentry__sentry
src/django_picklefield/fields.py
{ "start": 1112, "end": 2799 }
class ____: """ A class used to wrap object that have properties that may clash with the ORM internals. For example, objects with the `prepare_database_save` property such as `django.db.Model` subclasses won't work under certain conditions and the same apply for trying to retrieve any `callable...
_ObjectWrapper
python
run-llama__llama_index
llama-index-core/llama_index/core/readers/string_iterable.py
{ "start": 214, "end": 1203 }
class ____(BasePydanticReader): """ String Iterable Reader. Gets a list of documents, given an iterable (e.g. list) of strings. Example: .. code-block:: python from llama_index.core.legacy import StringIterableReader, TreeIndex documents = StringIterableReader().load_...
StringIterableReader
python
apache__thrift
test/py/TestClient.py
{ "start": 15197, "end": 15378 }
class ____(MultiplexedOptionalTest): def get_protocol(self, transport): return make_pedantic(TCompactProtocol.TCompactProtocolFactory().getProtocol(transport))
CompactTest
python
tensorflow__tensorflow
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
{ "start": 20906, "end": 21769 }
class ____(test.TestCase): @test_util.run_in_graph_and_eager_modes def testL2Loss(self): for dtype in [dtypes.float32, dtypes.float64]: x = constant_op.constant( [1.0, 0.0, 3.0, 2.0], shape=[2, 2], name="x", dtype=dtype ) l2loss = nn_ops.l2_loss(x) value = self.evaluate(l2loss...
L2LossTest
python
pytorch__pytorch
torch/_dynamo/source.py
{ "start": 36551, "end": 37025 }
class ____(ChainedSource): def name(self) -> str: return f"___from_numpy({self.base.name()})" def guard_source(self) -> GuardSource: return self.base.guard_source() def reconstruct(self, codegen: "PyCodegen") -> None: codegen.add_push_null(lambda: codegen.load_import_from("torch", ...
NumpyTensorSource
python
pandas-dev__pandas
pandas/tests/indexes/test_engines.py
{ "start": 695, "end": 1716 }
class ____: @pytest.mark.parametrize( "scalar", [ pd.Timedelta(pd.Timestamp("2016-01-01").asm8.view("m8[ns]")), pd.Timestamp("2016-01-01")._value, pd.Timestamp("2016-01-01").to_pydatetime(), pd.Timestamp("2016-01-01").to_datetime64(), ], ) ...
TestDatetimeEngine
python
lepture__authlib
authlib/integrations/base_client/sync_app.py
{ "start": 5916, "end": 9729 }
class ____: client_cls = None def __init__( self, framework, name=None, fetch_token=None, update_token=None, client_id=None, client_secret=None, access_token_url=None, access_token_params=None, authorize_url=None, authorize...
OAuth2Base
python
scipy__scipy
scipy/signal/tests/test_signaltools.py
{ "start": 96316, "end": 101878 }
class ____: def _setup_rank1(self, dt, xp): a = xp.linspace(0, 3, 4, dtype=dt) b = xp.linspace(1, 2, 2, dtype=dt) y_r = xp.asarray([0, 2, 5, 8, 3], dtype=dt) return a, b, y_r def equal_tolerance(self, res_dt): # default value of keyword decimal = 6 try: ...
TestCorrelateReal
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_U.py
{ "start": 1090, "end": 2587 }
class ____(Benchmark): r""" Ursem 3 objective function. This class defines the Ursem 3 [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Ursem03}}(x) = - \sin(2.2 \pi x_1 + 0.5 \pi) \frac{2 ...
Ursem03
python
spack__spack
lib/spack/spack/repo.py
{ "start": 70061, "end": 70741 }
class ____(RepoDescriptor): """A descriptor for a broken repository, used to indicate errors in the configuration that aren't fatal untill the repository is used.""" def __init__(self, name: Optional[str], error: str) -> None: super().__init__(name) self.error = error def initialize( ...
BrokenRepoDescriptor
python
pytorch__pytorch
torch/ao/nn/quantized/reference/modules/conv.py
{ "start": 3480, "end": 5176 }
class ____(_ConvNd, nn.Conv2d): def __init__( self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode="zeros", device=None, dtype=None, weight_qparams: dic...
Conv2d
python
getsentry__sentry
src/sentry/mail/forms/assigned_to.py
{ "start": 161, "end": 405 }
class ____(MemberTeamForm[AssigneeTargetType]): targetType = forms.ChoiceField(choices=ASSIGNEE_CHOICES) teamValue = AssigneeTargetType.TEAM memberValue = AssigneeTargetType.MEMBER targetTypeEnum = AssigneeTargetType
AssignedToForm
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 43352, "end": 47493 }
class ____(fixtures.MappedTest): run_setup_mappers = "each" run_setup_classes = "each" @classmethod def define_tables(cls, metadata): Table( "parents", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ...
ReconstitutionTest
python
django__django
tests/cache/closeable_cache.py
{ "start": 60, "end": 162 }
class ____: closed = False def close(self, **kwargs): self.closed = True
CloseHookMixin
python
pypa__warehouse
warehouse/accounts/models.py
{ "start": 15120, "end": 16536 }
class ____(db.Model): __tablename__ = "user_unique_logins" __table_args__ = ( UniqueConstraint( "user_id", "ip_address", name="_user_unique_logins_user_id_ip_address_uc" ), Index( "user_unique_logins_user_id_ip_address_idx", "user_id", "ip_...
UserUniqueLogin
python
sqlalchemy__sqlalchemy
test/sql/test_inspect.py
{ "start": 315, "end": 1428 }
class ____(fixtures.TestBase): def test_table(self): t = Table("t", MetaData(), Column("x", Integer)) is_(inspect(t), t) assert t.is_selectable is_(t.selectable, t) def test_select(self): t = Table("t", MetaData(), Column("x", Integer)) s = t.select() i...
TestCoreInspection
python
explosion__spaCy
spacy/lang/bn/__init__.py
{ "start": 325, "end": 540 }
class ____(BaseDefaults): tokenizer_exceptions = TOKENIZER_EXCEPTIONS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES stop_words = STOP_WORDS
BengaliDefaults
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/return_in_init.py
{ "start": 187, "end": 245 }
class ____: def __init__(self): return 1
MyClass
python
kamyu104__LeetCode-Solutions
Python/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.py
{ "start": 538, "end": 1673 }
class ____(object): def findCriticalAndPseudoCriticalEdges(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: List[List[int]] """ def MST(n, edges, unused=None, used=None): union_find = UnionFind(n) weight = 0 if...
Solution
python
apache__airflow
providers/redis/src/airflow/providers/redis/hooks/redis.py
{ "start": 1060, "end": 5348 }
class ____(BaseHook): """ Wrapper for connection to interact with Redis in-memory data structure store. You can set your db in the extra field of your connection as ``{"db": 3}``. Also you can set ssl parameters as: ``{"ssl": true, "ssl_cert_reqs": "require", "ssl_certfile": "/path/to/cert.pem", et...
RedisHook
python
walkccc__LeetCode
solutions/563. Binary Tree Tilt/563.py
{ "start": 0, "end": 320 }
class ____: def findTilt(self, root: TreeNode | None) -> int: ans = 0 def summ(root: TreeNode | None) -> None: nonlocal ans if not root: return 0 l = summ(root.left) r = summ(root.right) ans += abs(l - r) return root.val + l + r summ(root) return ans
Solution
python
walkccc__LeetCode
solutions/1183. Maximum Number of Ones/1183-2.py
{ "start": 0, "end": 459 }
class ____: def maximumNumberOfOnes( self, width: int, height: int, sideLength: int, maxOnes: int, ) -> int: subCount = [] def getCount(length: int, index: int) -> int: return (length - index - 1) // sideLength + 1 for i in range(sideLength): for j in range(si...
Solution
python
cherrypy__cherrypy
cherrypy/lib/covercp.py
{ "start": 8207, "end": 12287 }
class ____(object): """HTTP handler for the coverage stats.""" def __init__(self, coverage, root=None): """Initialize the coverage stats application.""" self.coverage = coverage if root is None: # Guess initial depth. Files outside this path will not be # reachab...
CoverStats
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 148100, "end": 150450 }
class ____(ASTBase): def __init__( self, concept: ASTNestedName, params: list[ASTTemplateIntroductionParameter] ) -> None: assert len(params) > 0 self.concept = concept self.params = params def __eq__(self, other: object) -> bool: if not isinstance(other, ASTTemplate...
ASTTemplateIntroduction
python
huggingface__transformers
src/transformers/models/qwen3_moe/modular_qwen3_moe.py
{ "start": 2820, "end": 3094 }
class ____(MixtralPreTrainedModel): _can_record_outputs = { "router_logits": OutputRecorder(Qwen3MoeTopKRouter, layer_name="mlp.router", index=0), "hidden_states": Qwen3MoeDecoderLayer, "attentions": Qwen3MoeAttention, }
Qwen3MoePreTrainedModel
python
kamyu104__LeetCode-Solutions
Python/split-concatenated-strings.py
{ "start": 31, "end": 658 }
class ____(object): def splitLoopedString(self, strs): """ :type strs: List[str] :rtype: str """ tmp = [] for s in strs: tmp += max(s, s[::-1]) s = "".join(tmp) result, st = "a", 0 for i in xrange(len(strs)): body = ""....
Solution
python
getsentry__sentry
src/sentry/status_checks/base.py
{ "start": 1831, "end": 2022 }
class ____: def check(self) -> list[Problem]: """ Perform required checks and return a list of ``Problem`` instances. """ raise NotImplementedError
StatusCheck
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/vertex_ai/test_experiment_service.py
{ "start": 4839, "end": 5681 }
class ____: @mock.patch(VERTEX_AI_PATH.format("ExperimentRunHook")) def test_execute(self, mock_hook): op = ListExperimentRunsOperator( task_id=TASK_ID, project_id=GCP_PROJECT, location=GCP_LOCATION, experiment_name=TEST_EXPERIMENT_NAME, gcp_co...
TestVertexAIListExperimentRunsOperator
python
kamyu104__LeetCode-Solutions
Python/number-of-distinct-islands.py
{ "start": 37, "end": 918 }
class ____(object): def numDistinctIslands(self, grid): """ :type grid: List[List[int]] :rtype: int """ directions = {'l':[-1, 0], 'r':[ 1, 0], \ 'u':[ 0, 1], 'd':[ 0, -1]} def dfs(i, j, grid, island): if not (0 <= i < len(grid) a...
Solution
python
coleifer__peewee
tests/cockroachdb.py
{ "start": 517, "end": 569 }
class ____(TestModel): data = JSONField()
JsonModel
python
openai__openai-python
src/openai/types/vector_store_update_params.py
{ "start": 313, "end": 920 }
class ____(TypedDict, total=False): expires_after: Optional[ExpiresAfter] """The expiration policy for a vector store.""" metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a str...
VectorStoreUpdateParams
python
doocs__leetcode
solution/0000-0099/0005.Longest Palindromic Substring/Solution2.py
{ "start": 0, "end": 479 }
class ____: def longestPalindrome(self, s: str) -> str: def f(l, r): while l >= 0 and r < n and s[l] == s[r]: l, r = l - 1, r + 1 return r - l - 1 n = len(s) start, mx = 0, 1 for i in range(n): a = f(i, i) b = f(i, i + ...
Solution
python
tensorflow__tensorflow
tensorflow/python/data/experimental/ops/batching.py
{ "start": 12914, "end": 14358 }
class ____(dataset_ops.UnaryDataset): """A `Dataset` that batches ragged dense elements into `tf.sparse.SparseTensor`s.""" def __init__(self, input_dataset, batch_size, row_shape): """See `Dataset.dense_to_sparse_batch()` for more details.""" if not isinstance( dataset_ops.get_legacy_output_types(i...
_DenseToSparseBatchDataset
python
scikit-learn__scikit-learn
examples/calibration/plot_calibration_curve.py
{ "start": 6841, "end": 11519 }
class ____(LinearSVC): """LinearSVC with `predict_proba` method that naively scales `decision_function` output for binary classification.""" def fit(self, X, y): super().fit(X, y) df = self.decision_function(X) self.df_min_ = df.min() self.df_max_ = df.max() def predict...
NaivelyCalibratedLinearSVC
python
airbytehq__airbyte
airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_external_account_bank_accounts.py
{ "start": 8069, "end": 14457 }
class ____(TestCase): @HttpMocker() def test_given_no_state_when_read_then_use_external_accounts_endpoint(self, http_mocker: HttpMocker) -> None: http_mocker.get( _external_accounts_request().with_object(_OBJECT).with_limit(100).build(), _external_bank_accounts_response().with_re...
IncrementalTest
python
doocs__leetcode
solution/1700-1799/1761.Minimum Degree of a Connected Trio in a Graph/Solution.py
{ "start": 63, "end": 676 }
class ____: def minTrioDegree(self, n: int, edges: List[List[int]]) -> int: g = [[False] * n for _ in range(n)] deg = [0] * n for u, v in edges: u, v = u - 1, v - 1 g[u][v] = g[v][u] = True deg[u] += 1 deg[v] += 1 ans = inf for ...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/workspace.py
{ "start": 495, "end": 629 }
class ____: commit_hash: Optional[str] = None url: Optional[str] = None @whitelist_for_serdes @record(kw_only=False)
GitMetadata
python
joblib__joblib
joblib/externals/loky/initializers.py
{ "start": 961, "end": 2567 }
class ____: """Compound worker initializer This is meant to be used in conjunction with _chain_initializers to produce the necessary chained_args list to be passed to __call__. """ def __init__(self, initializers): self._initializers = initializers def __call__(self, *chained_args): ...
_ChainedInitializer
python
neetcode-gh__leetcode
python/0210-course-schedule-ii.py
{ "start": 0, "end": 789 }
class ____: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: prereq = {c: [] for c in range(numCourses)} for crs, pre in prerequisites: prereq[crs].append(pre) output = [] visit, cycle = set(), set() def dfs(crs): if...
Solution
python
pydata__xarray
xarray/plot/facetgrid.py
{ "start": 1556, "end": 37980 }
class ____(Generic[T_DataArrayOrSet]): """ Initialize the Matplotlib figure and FacetGrid object. The :class:`FacetGrid` is an object that links a xarray DataArray to a Matplotlib figure with a particular structure. In particular, :class:`FacetGrid` is used to draw plots with multiple axes, wh...
FacetGrid
python
huggingface__transformers
tests/models/chinese_clip/test_modeling_chinese_clip.py
{ "start": 14334, "end": 17120 }
class ____(ModelTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as CHINESE_CLIP does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (ChineseCLIPVisionModel,) if is_torch_available() else () test...
ChineseCLIPVisionModelTest
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/misc.py
{ "start": 985, "end": 3187 }
class ____(SampledFromStrategy[Ex]): """A strategy which always returns a single fixed value. It's implemented as a length-one SampledFromStrategy so that all our special-case logic for filtering and sets applies also to just(x). The important difference from a SampledFromStrategy with only one el...
JustStrategy
python
huggingface__transformers
src/transformers/training_args.py
{ "start": 143292, "end": 143554 }
class ____(Enum): NOT_PARALLEL = "not_parallel" NOT_DISTRIBUTED = "not_distributed" DISTRIBUTED = "distributed" SAGEMAKER_MODEL_PARALLEL = "sagemaker_model_parallel" SAGEMAKER_DATA_PARALLEL = "sagemaker_data_parallel" TPU = "tpu"
ParallelMode
python
pytorch__pytorch
torch/_subclasses/fake_tensor.py
{ "start": 2960, "end": 3188 }
class ____: def __init__(self) -> None: global RECURSION_COUNT RECURSION_COUNT += 1 def __del__(self) -> None: global RECURSION_COUNT RECURSION_COUNT -= 1 @dataclass
IncrementRecursionCount
python
numpy__numpy
numpy/_core/tests/test_dtype.py
{ "start": 37600, "end": 39273 }
class ____: """Test deeply nested subtypes.""" def test1(self): simple1 = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'], 'titles': ['Red pixel', 'Blue pixel']}) a = np.dtype([('yo', int), ('ye', simple1), ('yi', np.dtype((int, (3, 2))))]) b = np.dtype([(...
TestMonsterType
python
aimacode__aima-python
deep_learning4e.py
{ "start": 5973, "end": 12998 }
class ____(Layer): """Batch normalization layer.""" def __init__(self, size, eps=0.001): super().__init__(size) self.eps = eps # self.weights = [beta, gamma] self.weights = [0, 0] self.inputs = None def forward(self, inputs): # mean value of inputs m...
BatchNormalizationLayer
python
huggingface__transformers
tests/models/glm4v/test_processor_glm4v.py
{ "start": 1038, "end": 10848 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = Glm4vProcessor model_id = "THUDM/GLM-4.1V-9B-Thinking" @classmethod def _setup_test_attributes(cls, processor): cls.image_token = processor.image_token @classmethod def _setup_from_pretrained(cls, model_id, **kwargs...
Glm4vProcessorTest
python
huggingface__transformers
src/transformers/models/speecht5/number_normalizer.py
{ "start": 728, "end": 6948 }
class ____: def __init__(self): self.ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] self.teens = [ "", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", ...
EnglishNumberNormalizer
python
apache__airflow
airflow-core/src/airflow/executors/workloads.py
{ "start": 3370, "end": 4603 }
class ____(BaseDagBundleWorkload): """Execute the given Task.""" ti: TaskInstance sentry_integration: str = "" type: Literal["ExecuteTask"] = Field(init=False, default="ExecuteTask") @classmethod def make( cls, ti: TIModel, dag_rel_path: Path | None = None, gen...
ExecuteTask
python
pytorch__pytorch
torch/_inductor/codegen/wrapper.py
{ "start": 21876, "end": 22660 }
class ____(WrapperLine): wrapper: PythonWrapperCodegen def plan(self, state: MemoryPlanningState) -> MemoryPlanningLine: """First pass to find reuse""" return self def codegen(self, code: IndentedBuffer) -> None: """Second pass to output code""" def __str__(self) -> str: ...
MemoryPlanningLine