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
numba__numba
numba/tests/test_datamodel.py
{ "start": 1590, "end": 1681 }
class ____(test_factory()): fe_type = types.Array(types.int32, 1, 'C')
Test1DArrayOfInt32
python
huggingface__transformers
src/transformers/models/xglm/modeling_xglm.py
{ "start": 11443, "end": 16207 }
class ____(GradientCheckpointingLayer): def __init__(self, config: XGLMConfig, layer_idx=None): super().__init__() self.embed_dim = config.d_model self.self_attn = XGLMAttention( embed_dim=self.embed_dim, num_heads=config.attention_heads, dropout=config.a...
XGLMDecoderLayer
python
tensorflow__tensorflow
tensorflow/python/framework/ops.py
{ "start": 9346, "end": 11034 }
class ____(pywrap_tf_session.PyTensor, tensor_lib.Tensor): """A symbolic tensor from a graph or tf.function.""" def __new__(cls, op, value_index, dtype, unique_id=None) -> "SymbolicTensor": if unique_id is None: unique_id = uid() return pywrap_tf_session.PyTensor.__new__( SymbolicTensor, op, ...
SymbolicTensor
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-pdf-table/llama_index/readers/pdf_table/base.py
{ "start": 216, "end": 1865 }
class ____(BaseReader): """ PDF Table Reader. Reads table from PDF. Args: row_separator (str): Row separator used to join rows of a DataFrame. col_separator (str): Col separator used to join columns of a DataFrame. """ def __init__( self, *args: Any, row_se...
PDFTableReader
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 102007, "end": 102842 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "pull_request_id", "commit_headline", "commit_body", "merge_method", "author_email", "client_mutation_id", ) pull_request_id ...
EnablePullRequestAutoMergeInput
python
joke2k__faker
faker/providers/bank/zh_CN/__init__.py
{ "start": 42, "end": 602 }
class ____(BankProvider): """Implement bank provider for ``zh_CN`` locale. Source: https://zh.wikipedia.org/wiki/中国大陆银行列表 """ banks = ( "中国人民银行", "国家开发银行", "中国进出口银行", "中国农业发展银行", "交通银行", "中国银行", "中国建设银行", "中国农业银行", "中国工商银行", ...
Provider
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/guides/external-systems/apis/env_var_configuration.py
{ "start": 70, "end": 1303 }
class ____(dg.ConfigurableResource): latitude: str longitude: str time_zone: str @property def query_string(self) -> str: return f"https://api.sunrise-sunset.org/json?lat={self.latitude}&lng={self.longitude}&date=today&tzid={self.time_zone}" def sunrise(self) -> str: data = req...
SunResource
python
python-pillow__Pillow
src/PIL/BmpImagePlugin.py
{ "start": 1659, "end": 13716 }
class ____(ImageFile.ImageFile): """Image plugin for the Windows Bitmap format (BMP)""" # ------------------------------------------------------------- Description format_description = "Windows Bitmap" format = "BMP" # -------------------------------------------------- BMP Compression values C...
BmpImageFile
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 188606, "end": 194220 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[]"): l_x_ = L_x_ _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 with your use case."); _saved_tensors_hooks_...
GraphModule
python
doocs__leetcode
solution/1600-1699/1665.Minimum Initial Energy to Finish Tasks/Solution.py
{ "start": 0, "end": 279 }
class ____: def minimumEffort(self, tasks: List[List[int]]) -> int: ans = cur = 0 for a, m in sorted(tasks, key=lambda x: x[0] - x[1]): if cur < m: ans += m - cur cur = m cur -= a return ans
Solution
python
pypa__pipenv
pipenv/vendor/ptyprocess/util.py
{ "start": 2703, "end": 2785 }
class ____(Exception): """Generic error class for this package."""
PtyProcessError
python
sqlalchemy__sqlalchemy
test/orm/test_joins.py
{ "start": 113953, "end": 116428 }
class ____(QueryTest, AssertsCompiledSQL): """test issue 6003 where creating a legacy query with only Core elements fails to accommodate for the ORM context thus producing a query that ignores the "legacy" joins """ __dialect__ = "default" @testing.combinations( ( lambda s...
JoinRawTablesWLegacyTest
python
getsentry__sentry
src/sentry/sentry_apps/utils/webhooks.py
{ "start": 465, "end": 611 }
class ____(SentryAppActionType): CRITICAL = "critical" OPEN = "open" RESOLVED = "resolved" WARNING = "warning"
MetricAlertActionType
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_types.py
{ "start": 17913, "end": 18136 }
class ____(IntervalTest): __requires__ = ("datetime_interval",) __backend__ = True datatype = Interval(day_precision=9, second_precision=9) data = datetime.timedelta(days=103, seconds=4)
PrecisionIntervalTest
python
catalyst-team__catalyst
tests/misc.py
{ "start": 88, "end": 904 }
class ____(data.TensorDataset): """Dataset wrapping tensors. Each sample will be retrieved by indexing tensors along the first dimension. Args: *args: tensors that have the same size of the first dimension. """ def __init__(self, *args: torch.Tensor, **kwargs) -> None: super().__i...
TensorDataset
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_float.py
{ "start": 31753, "end": 32760 }
class ____(__TestCase): @support.requires_IEEE_754 def test_double_specials_do_unpack(self): for fmt, data in [('>d', BE_DOUBLE_INF), ('>d', BE_DOUBLE_NAN), ('<d', LE_DOUBLE_INF), ('<d', LE_DOUBLE_NAN)]: struct.un...
IEEEFormatTestCase
python
jazzband__django-oauth-toolkit
oauth2_provider/migrations/0002_auto_20190406_1805.py
{ "start": 90, "end": 648 }
class ____(migrations.Migration): dependencies = [ ('oauth2_provider', '0001_initial'), ] operations = [ migrations.AddField( model_name='grant', name='code_challenge', field=models.CharField(blank=True, default='', max_length=128), ), mi...
Migration
python
spyder-ide__spyder
spyder/utils/stylesheet.py
{ "start": 891, "end": 2225 }
class ____(SpyderFontsMixin): """Enum with several constants used in the application style.""" # Size of margins. MarginSize = 3 # px # Size of find widget line edits (e.g. FinderWidget and FindReplace) FindMinWidth = 400 # px FindHeight = 26 # px # To have it for quick access because ...
AppStyle
python
getsentry__sentry
src/sentry/services/nodestore/bigtable/backend.py
{ "start": 302, "end": 4379 }
class ____(NodeStorage): """ A Bigtable-based backend for storing node data. :param project: Passed to bigtable client :param instance: Passed to bigtable client :param table: Passed to bigtable client :param automatic_expiry: Whether to set bigtable GC rule. :param default_ttl: How many da...
BigtableNodeStorage
python
django__django
tests/admin_checks/models.py
{ "start": 1171, "end": 1350 }
class ____(models.Model): author = models.ForeignKey(Author, models.CASCADE) book = models.ForeignKey(Book, models.CASCADE) featured = models.BooleanField()
AuthorsBooks
python
django-compressor__django-compressor
compressor/tests/test_offline.py
{ "start": 17738, "end": 18073 }
class ____( SuperMixin, OfflineCompressTestCaseWithContextList ): templates_dir = "test_with_context_super" expected_hash = ["b39975a8f6ea", "ed565a1d262f", "6ac9e4b29feb"] additional_test_settings = { "COMPRESS_OFFLINE_CONTEXT": list(offline_context_generator()) }
OfflineCompressTestCaseWithContextListSuper
python
pytorch__pytorch
torch/utils/_python_dispatch.py
{ "start": 25620, "end": 37772 }
class ____: args: list[AliasInfo] outs: list[AliasInfo] is_inplace_view_op: bool # [_get_write_alias(x) for x in outs]. Guaranteed to contain no Nones; we coerce # all-Nones result to empty list instead, and we don't support # some-but-not-all-Nones. outs_write_aliases: list[str] | None ...
SchemaInfo
python
jazzband__django-polymorphic
src/polymorphic/admin/inlines.py
{ "start": 654, "end": 9983 }
class ____(InlineModelAdmin): """ A polymorphic inline, where each formset row can be a different form. Note that: * Permissions are only checked on the base model. * The child inlines can't override the base model fields, only this parent inline can do that. """ formset = BasePolymorphic...
PolymorphicInlineModelAdmin
python
scipy__scipy
scipy/integrate/tests/test_tanhsinh.py
{ "start": 28324, "end": 44339 }
class ____: rng = np.random.default_rng(5895448232066142650) p = rng.uniform(1, 10, size=10).tolist() def f1(self, k): # Integers are never passed to `f1`; if they were, we'd get # integer to negative integer power error return k**(-2) f1.ref = np.pi**2/6 f1.a = 1 f1.b ...
TestNSum
python
sympy__sympy
sympy/series/formal.py
{ "start": 25582, "end": 25824 }
class ____(Function): """ Coeff(p, x, n) represents the nth coefficient of the polynomial p in x """ @classmethod def eval(cls, p, x, n): if p.is_polynomial(x) and n.is_integer: return p.coeff(x, n)
Coeff
python
openai__openai-python
src/openai/types/realtime/output_audio_buffer_clear_event.py
{ "start": 232, "end": 493 }
class ____(BaseModel): type: Literal["output_audio_buffer.clear"] """The event type, must be `output_audio_buffer.clear`.""" event_id: Optional[str] = None """The unique ID of the client event used for error handling."""
OutputAudioBufferClearEvent
python
mwaskom__seaborn
seaborn/external/docscrape.py
{ "start": 3579, "end": 3847 }
class ____(Exception): def __str__(self): message = self.args[0] if hasattr(self, 'docstring'): message = f"{message} in {self.docstring!r}" return message Parameter = namedtuple('Parameter', ['name', 'type', 'desc'])
ParseError
python
huggingface__transformers
src/transformers/models/biogpt/modeling_biogpt.py
{ "start": 14484, "end": 21579 }
class ____(BioGptPreTrainedModel): def __init__(self, config: BioGptConfig): super().__init__(config) self.config = config self.layerdrop = config.layerdrop self.dropout = config.hidden_dropout_prob self.embed_dim = config.hidden_size self.padding_idx = config.pad_tok...
BioGptModel
python
numpy__numpy
numpy/linalg/lapack_lite/clapack_scrub.py
{ "start": 1157, "end": 3385 }
class ____(MyScanner): """Following clapack, we remove ftnlen arguments, which f2c puts after a char * argument to hold the length of the passed string. This is just a nuisance in C. """ def __init__(self, info, name='<ftnlen>'): MyScanner.__init__(self, info, name) self.paren_count ...
LenSubsScanner
python
PrefectHQ__prefect
tests/server/orchestration/api/test_deployments.py
{ "start": 103123, "end": 109446 }
class ____: async def test_pause_deployment(self, client, deployment, session): assert deployment.paused is False response = await client.post(f"/deployments/{deployment.id}/pause_deployment") assert response.status_code == status.HTTP_200_OK await session.refresh(deployment) ...
TestPauseAndResumeDeployment
python
Netflix__metaflow
metaflow/plugins/datatools/local.py
{ "start": 258, "end": 348 }
class ____(MetaflowException): headline = "Local object not found"
MetaflowLocalNotFound
python
ray-project__ray
release/ray_release/exception.py
{ "start": 1710, "end": 1810 }
class ____(ClusterManagerError): exit_code = ExitCode.CLUSTER_RESOURCE_ERROR
ClusterEnvCreateError
python
numpy__numpy
numpy/ma/core.py
{ "start": 25168, "end": 25881 }
class ____: """ Define a valid interval, so that : ``domain_check_interval(a,b)(x) == True`` where ``x < a`` or ``x > b``. """ def __init__(self, a, b): "domain_check_interval(a,b)(x) = true where x < a or y > b" if a > b: (a, b) = (b, a) self.a = a ...
_DomainCheckInterval
python
ApeWorX__ape
src/ape/api/accounts.py
{ "start": 25693, "end": 30558 }
class ____(BaseInterfaceModel): """ An API class representing a collection of :class:`~ape.api.accounts.AccountAPI` instances. """ name: str """ The name of the account container. For example, the ``ape-ledger`` plugin uses ``"ledger"`` as its name. """ account_type: type[A...
AccountContainerAPI
python
python__mypy
mypy/erasetype.py
{ "start": 1108, "end": 5265 }
class ____(TypeVisitor[ProperType]): def visit_unbound_type(self, t: UnboundType) -> ProperType: # TODO: replace with an assert after UnboundType can't leak from semantic analysis. return AnyType(TypeOfAny.from_error) def visit_any(self, t: AnyType) -> ProperType: return t def visi...
EraseTypeVisitor
python
openai__openai-python
src/openai/types/file_list_params.py
{ "start": 204, "end": 960 }
class ____(TypedDict, total=False): after: str """A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the ...
FileListParams
python
realpython__materials
python-class/workers.py
{ "start": 0, "end": 454 }
class ____: def __init__(self, name, address, hourly_salary): self.name = name self.address = address self.hourly_salary = hourly_salary def show_profile(self): print("== Worker profile ==") print(f"Name: {self.name}") print(f"Address: {self.address}") pr...
Worker
python
huggingface__transformers
src/transformers/models/eomt/modeling_eomt.py
{ "start": 39504, "end": 41094 }
class ____(GradientCheckpointingLayer): """This corresponds to the Block class in the original implementation.""" def __init__(self, config: EomtConfig) -> None: super().__init__() self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.attention = EomtAttention(c...
EomtLayer
python
google__pytype
pytype/ast/visitor_test.py
{ "start": 935, "end": 1181 }
class ____(visitor.BaseVisitor): """Tests enter() by recording names.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.names = [] def enter_Name(self, node): self.names.append(node.id)
_EnterVisitor
python
tensorflow__tensorflow
tensorflow/python/distribute/mirrored_run.py
{ "start": 5318, "end": 12071 }
class ____(Exception): # pylint: disable=g-bad-exception-name pass def _get_thread_local_configuration_callable(): if traceback_utils.is_traceback_filtering_enabled(): thread_local_callables = {traceback_utils.enable_traceback_filtering} else: thread_local_callables = {traceback_utils.disable_traceback...
_RequestedStop
python
PrefectHQ__prefect
tests/cli/test_work_queues.py
{ "start": 8016, "end": 11124 }
class ____: async def test_pause(self, prefect_client, work_queue): assert not work_queue.is_paused await run_sync_in_worker_thread( invoke_and_assert, command=f"work-queue pause {work_queue.name} --pool default-agent-pool", expected_code=0, ) q = ...
TestPauseWorkQueue
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_connection.py
{ "start": 558, "end": 5911 }
class ____(BaseConnectionInfo): """Base connection information for Azure Database for PostgreSQL connections. :param host: Hostname of the Azure Database for PostgreSQL server. :type host: str | None :param dbname: Name of the database to connect to. :type dbname: str :param port: Port number f...
ConnectionInfo
python
django__django
tests/queries/models.py
{ "start": 9714, "end": 9782 }
class ____(ObjectB): class Meta: proxy = True
ProxyObjectB
python
Textualize__textual
tests/css/test_css_reloading.py
{ "start": 467, "end": 2368 }
class ____(App[None]): CSS_PATH = CSS_PATH def on_mount(self) -> None: self.push_screen(BaseScreen()) self.push_screen(TopScreen()) async def test_css_reloading_applies_to_non_top_screen(monkeypatch) -> None: # type: ignore """Regression test for https://github.com/Textualize/textual/iss...
MyApp
python
pytest-dev__pytest
testing/python/collect.py
{ "start": 40985, "end": 55352 }
class ____: def test_itemreport_reportinfo(self, pytester: Pytester) -> None: pytester.makeconftest( """ import pytest class MyFunction(pytest.Function): def reportinfo(self): return "ABCDE", 42, "custom" def pytest_pycollec...
TestReportInfo
python
walkccc__LeetCode
solutions/982. Triples with Bitwise AND Equal To Zero/982.py
{ "start": 0, "end": 334 }
class ____: def countTriplets(self, nums: list[int]) -> int: MAX = 1 << 16 ans = 0 count = [0] * MAX # {nums[i] & nums[j]: times} for a in nums: for b in nums: count[a & b] += 1 for num in nums: for i in range(MAX): if (num & i) == 0: ans += count[i] r...
Solution
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_alloy_db.py
{ "start": 64455, "end": 69577 }
class ____: def setup_method(self): self.operator = AlloyDBUpdateUserOperator( task_id=TEST_TASK_ID, user_id=TEST_USER_ID, cluster_id=TEST_CLUSTER_ID, user_configuration=TEST_USER, update_mask=TEST_UPDATE_MASK, allow_missing=TEST_ALLOW_...
TestAlloyDBUpdateUserOperator
python
scrapy__scrapy
tests/test_spidermiddleware.py
{ "start": 13822, "end": 14004 }
class ____: def process_spider_output(self, response, result): yield def process_spider_output_async(self, response, result): yield
UniversalMiddlewareBothSync
python
sphinx-doc__sphinx
sphinx/builders/manpage.py
{ "start": 827, "end": 4500 }
class ____(Builder): """Builds groff output in manual page format.""" name = 'man' format = 'man' epilog = __('The manual pages are in %(outdir)s.') default_translator_class = ManualPageTranslator supported_image_types = [] def init(self) -> None: if not self.config.man_pages: ...
ManualPageBuilder
python
django__django
tests/urlpatterns_reverse/method_view_urls.py
{ "start": 31, "end": 371 }
class ____: def method_view(self, request): pass @classmethod def classmethod_view(cls, request): pass view_container = ViewContainer() urlpatterns = [ path("", view_container.method_view, name="instance-method-url"), path("", ViewContainer.classmethod_view, name="instance-metho...
ViewContainer
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 23685, "end": 23948 }
class ____(Pix2SkyProjection, PseudoCylindrical): r""" Sanson-Flamsteed projection - pixel to sky. Corresponds to the ``SFL`` projection in FITS WCS. .. math:: \phi &= \frac{x}{\cos y} \\ \theta &= y """
Pix2Sky_SansonFlamsteed
python
readthedocs__readthedocs.org
readthedocs/core/migrations/0009_historicaluserprofile.py
{ "start": 245, "end": 4138 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("core", "0008_add_extra_history_fields"), ] operations = [ migrations.CreateModel( name="HistoricalUserProfile", fiel...
Migration
python
astropy__astropy
astropy/utils/masked/core.py
{ "start": 17015, "end": 18261 }
class ____(MaskedInfoBase): """Mixin class to create a subclasses such as MaskedQuantityInfo.""" # This is used below in __init_subclass__, which also inserts a # 'serialize_method' attribute in attr_names. def _represent_as_dict(self): # Use the data_cls as the class name for serialization, ...
MaskedArraySubclassInfo
python
ansible__ansible
test/integration/targets/task-args/action_plugins/echo_raw.py
{ "start": 84, "end": 276 }
class ____(ActionBase): supports_raw_params = True def run(self, tmp=None, task_vars=None): action_args = self._task.args return dict(action_args=action_args)
ActionModule
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/operators/any_downstream_conditions_operator.py
{ "start": 1711, "end": 4234 }
class ____(BuiltinAutomationCondition[AssetKey]): @property def description(self) -> str: return "Any downstream conditions" @property def name(self) -> str: return "ANY_DOWNSTREAM_CONDITIONS" @property def requires_cursor(self) -> bool: return False def _get_ignor...
AnyDownstreamConditionsCondition
python
python__mypy
mypy/exportjson.py
{ "start": 1556, "end": 18914 }
class ____: def __init__(self, *, implicit_names: bool = True) -> None: self.implicit_names = implicit_names def convert_binary_cache_to_json(data: bytes, *, implicit_names: bool = True) -> Json: tree = MypyFile.read(ReadBuffer(data)) return convert_mypy_file_to_json(tree, Config(implicit_names=im...
Config
python
huggingface__transformers
benchmark/benchmarks_entrypoint.py
{ "start": 1020, "end": 19806 }
class ____: def __init__( self, connection, logger: logging.Logger, repository: str, branch: str, commit_id: str, commit_msg: str, collect_csv_data: bool = True, ): self.conn = connection self.use_database = connection is not None ...
MetricsRecorder
python
getsentry__sentry
src/sentry/monitors/endpoints/base_monitor_checkin_index.py
{ "start": 548, "end": 1927 }
class ____(BaseEndpointMixin): def get_monitor_checkins(self, request: Request, project, monitor) -> Response: """ Retrieve a list of check-ins for a monitor """ start, end = get_date_range_from_params(request.GET) if start is None or end is None: raise ParseError...
MonitorCheckInMixin
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_django/DJ012.py
{ "start": 66, "end": 323 }
class ____(models.Model): """Model with `__str__` before a random property.""" class Meta: verbose_name = "test" verbose_name_plural = "tests" def __str__(self): return "" random_property = "foo"
StrBeforeRandomField
python
pandas-dev__pandas
pandas/tests/test_algos.py
{ "start": 76184, "end": 77890 }
class ____: @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"]) def test_diff_datetimelike_nat(self, dtype): # NaT - NaT is NaT, not 0 arr = np.arange(12).astype(np.int64).view(dtype).reshape(3, 4) arr[:, 2] = arr.dtype.type("NaT", "ns") result = algos.diff(arr, 1, axis=0) ...
TestDiff
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/AxisItem.py
{ "start": 324, "end": 68102 }
class ____(GraphicsWidget): """ GraphicsItem showing a single plot axis with ticks, values, and label. Can be configured to fit on any side of a plot, automatically synchronize its displayed scale with ViewBox items. Ticks can be extended to draw a grid. If maxTickLength is negative, ticks...
AxisItem
python
anthropics__anthropic-sdk-python
tests/lib/tools/test_functions.py
{ "start": 388, "end": 16941 }
class ____: def test_basic_function_schema_conversion(self) -> None: """Test basic function schema conversion with simple types.""" def get_weather(location: str, unit: str = "celsius") -> str: """Get the weather for a specific location.""" return f"Weather in {location} is ...
TestFunctionTool
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/task_instances.py
{ "start": 3130, "end": 3307 }
class ____(BaseModel): """Task scheduling dependencies collection serializer for responses.""" dependencies: list[TaskDependencyResponse]
TaskDependencyCollectionResponse
python
tensorflow__tensorflow
tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py
{ "start": 47697, "end": 48145 }
class ____(rnn_cell_wrapper_impl.DropoutWrapperBase, _RNNCellWrapperV1): """Operator adding dropout to inputs and outputs of the given cell.""" def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation super(DropoutWrapper, self).__init__(*args, **kwargs) __init__...
DropoutWrapper
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/rand_augment_test.py
{ "start": 164, "end": 4256 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_layer(self): self.run_layer_test( layers.RandAugment, init_kwargs={ "value_range": (0, 255), "num_ops": 2, "factor": 1, "interpolation": ...
RandAugmentTest
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_ray.py
{ "start": 1859, "end": 8942 }
class ____: def setup_method(self): with mock.patch( BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id ): self.hook = RayHook(gcp_conn_id=TEST_GCP_CONN_ID) self.hook.get_credentials = mock.MagicMock() @mock.patch(RAY_STR...
TestRayWithDefaultProjectIdHook
python
django__django
django/db/models/fields/related.py
{ "start": 3287, "end": 19725 }
class ____(FieldCacheMixin, Field): """Base class that all relational fields inherit from.""" # Field flags one_to_many = False one_to_one = False many_to_many = False many_to_one = False def __init__( self, related_name=None, related_query_name=None, limit_...
RelatedField
python
jmcnamara__XlsxWriter
xlsxwriter/test/workbook/test_write_book_views.py
{ "start": 299, "end": 933 }
class ____(unittest.TestCase): """ Test the Workbook _write_book_views() method. """ def setUp(self): self.fh = StringIO() self.workbook = Workbook() self.workbook._set_filehandle(self.fh) def test_write_book_views(self): """Test the _write_book_views() method""" ...
TestWriteBookViews
python
mlflow__mlflow
tests/resources/mlflow-test-plugin/mlflow_test_plugin/local_artifact.py
{ "start": 80, "end": 229 }
class ____(LocalArtifactRepository): """LocalArtifactRepository provided through plugin system""" is_plugin = True
PluginLocalArtifactRepository
python
google__jax
tests/array_extensibility_test.py
{ "start": 1010, "end": 1231 }
class ____: """Class that provides a __jax_array__ method.""" x: ArrayLike def __jax_array__(self) -> jax.Array: return jnp.asarray(self.x) @jax.tree_util.register_dataclass @dataclasses.dataclass
JaxArrayWrapper
python
pyqtgraph__pyqtgraph
pyqtgraph/widgets/PlotWidget.py
{ "start": 345, "end": 4480 }
class ____(GraphicsView): # signals wrapped from PlotItem / ViewBox sigRangeChanged = QtCore.Signal(object, object) sigTransformChanged = QtCore.Signal(object) """ :class:`GraphicsView <pyqtgraph.GraphicsView>` widget with a single :class:`PlotItem <pyqtgraph.PlotItem>` inside. ...
PlotWidget
python
pytorch__pytorch
.github/scripts/test_trymerge.py
{ "start": 38686, "end": 42927 }
class ____(TestCase): def test_pr_dependencies(self, *args: Any) -> None: pr = GitHubPR("pytorch", "pytorch", 106068) msg = pr.gen_commit_message(filter_ghstack=True) self.assertEqual( msg, f"{pr.get_title()} (#106068)\n\n{RE_GHSTACK_DESC.sub('', pr.get_body())}\n" ...
TestGitHubPRGhstackDependencies
python
pytorch__pytorch
torch/export/_unlift.py
{ "start": 33186, "end": 33317 }
class ____(torch.nn.Module): """ Module class for guard functions. """ def forward(self, *args): pass
GuardsFn
python
ray-project__ray
python/ray/serve/schema.py
{ "start": 45634, "end": 45950 }
class ____(BaseModel, frozen=True): ip: str = Field(description="IP address of the target.") port: int = Field(description="Port of the target.") instance_id: str = Field(description="Instance ID of the target.") name: str = Field(description="Name of the target.") @PublicAPI(stability="alpha")
Target
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 41586, "end": 41618 }
class ____(p_int32): pass
n_un
python
pytorch__pytorch
torch/_dynamo/variables/ctx_manager.py
{ "start": 31774, "end": 33937 }
class ____(ContextWrappingVariable): """represents torch.autograd.graph.disable_saved_tensors_hook.""" @staticmethod def create( tx: "InstructionTranslator", target_value: Optional[str], **kwargs: Any ) -> "DisabledSavedTensorsHooksVariable": var = DisabledSavedTensorsHooksVariable( ...
DisabledSavedTensorsHooksVariable
python
kamyu104__LeetCode-Solutions
Python/linked-list-in-binary-tree.py
{ "start": 350, "end": 1603 }
class ____(object): def isSubPath(self, head, root): """ :type head: ListNode :type root: TreeNode :rtype: bool """ def getPrefix(head): pattern, prefix = [head.val], [-1] j = -1 node = head.next while node: ...
Solution
python
pandas-dev__pandas
asv_bench/benchmarks/groupby.py
{ "start": 32608, "end": 33469 }
class ____: # GH 28635 def setup(self): num_timedeltas = 20_000 num_groups = 3 index = MultiIndex.from_product( [ np.arange(num_groups), to_timedelta(np.arange(num_timedeltas), unit="s"), ], names=["groups", "timedeltas...
Resample
python
kamyu104__LeetCode-Solutions
Python/maximum-linear-stock-score.py
{ "start": 69, "end": 339 }
class ____(object): def maxScore(self, prices): """ :type prices: List[int] :rtype: int """ cnt = collections.Counter() for i, x in enumerate(prices): cnt[x-i] += x return max(cnt.itervalues())
Solution
python
sympy__sympy
sympy/polys/polyoptions.py
{ "start": 9597, "end": 9814 }
class ____(BooleanOption, metaclass=OptionType): """``field`` option to polynomial manipulation functions. """ option = 'field' requires: list[str] = [] excludes = ['domain', 'split', 'gaussian']
Field
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py
{ "start": 10192, "end": 11469 }
class ____(BaseModel): """Response schema for TaskInstance run context.""" dag_run: DagRun """DAG run information for the task instance.""" task_reschedule_count: int = 0 """How many times the task has been rescheduled.""" max_tries: int """Maximum number of tries for the task instance (f...
TIRunContext
python
coleifer__peewee
examples/adjacency_list.py
{ "start": 56, "end": 1489 }
class ____(Model): name = TextField() parent = ForeignKeyField('self', backref='children', null=True) class Meta: database = db def __str__(self): return self.name def dump(self, _indent=0): return (' ' * _indent + self.name + '\n' + ''.join(child.dump(_in...
Node
python
pytorch__pytorch
test/inductor/test_torchinductor.py
{ "start": 9400, "end": 10459 }
class ____(InductorTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls._stack = contextlib.ExitStack() cls._stack.enter_context( config.patch( { "debug": True, "debug_index_asserts": True, ...
TestCase
python
tornadoweb__tornado
tornado/ioloop.py
{ "start": 1876, "end": 31102 }
class ____(Configurable): """An I/O event loop. As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event loop. Example usage for a simple TCP server: .. testcode:: import asyncio import errno import functools import socket import tornado fr...
IOLoop
python
pypa__pipenv
pipenv/patched/pip/_internal/models/installation_report.py
{ "start": 239, "end": 2863 }
class ____: def __init__(self, install_requirements: Sequence[InstallRequirement]): self._install_requirements = install_requirements @classmethod def _install_req_to_dict(cls, ireq: InstallRequirement) -> Dict[str, Any]: assert ireq.download_info, f"No download_info for {ireq}" res...
InstallationReport
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 26111, "end": 26254 }
class ____(Base20DeprecationWarning): """Subtype of Base20DeprecationWarning to indicate an API that moved only. """
MovedIn20Warning
python
getsentry__sentry
tests/sentry/sentry_apps/api/serializers/test_sentry_app_avatar.py
{ "start": 332, "end": 1591 }
class ____(TestCase): def setUp(self) -> None: self.sentry_app = self.create_sentry_app(organization=self.organization) self.avatar = self.create_sentry_app_avatar(sentry_app=self.sentry_app) def test_avatar(self) -> None: serial_avatar = serialize(self.avatar, None) assert seri...
SentryAppSerializerTest
python
PyCQA__pylint
tests/functional/i/invalid/invalid_str_returned.py
{ "start": 303, "end": 413 }
class ____: """__str__ returns <type 'str'>""" def __str__(self): return str(123)
SecondGoodStr
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 93775, "end": 94500 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(3, 2, 5, bias=True).to(dtype=torch.float) self.bn1 = nn.BatchNorm2d(2).to(dtype=torch.float) self.relu1 = nn.ReLU(inplace=True).to(dtype=torch.float) self.conv2 = nn.Conv2d(2, 2, 1, b...
ModelForFusionWithBias
python
encode__django-rest-framework
tests/test_renderers.py
{ "start": 15083, "end": 15654 }
class ____(TestCase): """ Tests specific for the Unicode JSON Renderer """ def test_proper_encoding(self): class AsciiJSONRenderer(JSONRenderer): ensure_ascii = True obj = {'countries': ['United Kingdom', 'France', 'España']} renderer = AsciiJSONRenderer() con...
AsciiJSONRendererTests
python
skorch-dev__skorch
skorch/tests/test_hf.py
{ "start": 19757, "end": 41728 }
class ____: @pytest.fixture(scope='module') def data(self, classifier_data): return classifier_data @pytest.fixture(scope='module') def module_cls(self, classifier_module): return classifier_module @pytest.fixture def accelerator_cls(self): # pylint: disable=missing-fun...
TestAccelerate
python
davidhalter__parso
parso/parser.py
{ "start": 1337, "end": 1594 }
class ____(Exception): """ Contains error information about the parser tree. May be raised as an exception. """ def __init__(self, message, error_leaf): self.message = message self.error_leaf = error_leaf
ParserSyntaxError
python
encode__django-rest-framework
tests/test_request.py
{ "start": 6321, "end": 6746 }
class ____(TestCase): def test_fileuploads_closed_at_request_end(self): with tempfile.NamedTemporaryFile() as f: response = self.client.post('/upload/', {'file': f}) # sanity check that file was processed assert len(response.data) == 1 for file in response.data: ...
FileUploadTests
python
pdm-project__pdm
src/pdm/project/config.py
{ "start": 2899, "end": 18867 }
class ____(MutableMapping[str, str]): """A dict-like object for configuration key and values""" _config_map: ClassVar[dict[str, ConfigItem]] = { "cache_dir": ConfigItem( "The root directory of cached files", platformdirs.user_cache_dir("pdm"), True, env_v...
Config
python
keras-team__keras
keras/src/trainers/data_adapters/array_slicing.py
{ "start": 3488, "end": 4077 }
class ____(Sliceable): def __getitem__(self, indices): from keras.src.utils.module_utils import tensorflow as tf if isinstance(indices, slice): return self.array[indices] else: return tf.gather(self.array, indices, axis=0) @classmethod def cast(cls, x, dtype...
TensorflowSliceable
python
django__django
tests/generic_views/models.py
{ "start": 513, "end": 711 }
class ____(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() class Meta: ordering = ["name"] def __str__(self): return self.name
Author
python
cython__cython
Demos/benchmarks/bm_raytrace.py
{ "start": 5735, "end": 8362 }
class ____(object): def __init__(self): self.objects = [] self.lightPoints = [] self.position = Point(0, 1.8, 10) self.lookingAt = Point.ZERO self.fieldOfView = 45 self.recursionDepth = 0 def moveTo(self, p): self.position = p def lookAt(self, p): ...
Scene
python
readthedocs__readthedocs.org
readthedocs/builds/reporting.py
{ "start": 286, "end": 1554 }
class ____: content: str diff: FileTreeDiff def get_build_overview(build: Build) -> BuildOverview | None: """ Generate a build overview for the given build. The overview includes a diff of the files changed between the current build and the base version of the project (latest by default). ...
BuildOverview
python
huggingface__transformers
src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py
{ "start": 22093, "end": 23445 }
class ____(nn.Module): def __init__(self, config: Qwen3VLMoeVisionConfig, use_postshuffle_norm=False) -> None: super().__init__() self.hidden_size = config.hidden_size * (config.spatial_merge_size**2) self.use_postshuffle_norm = use_postshuffle_norm self.norm = nn.LayerNorm(self.hidd...
Qwen3VLMoeVisionPatchMerger
python
prabhupant__python-ds
data_structures/binary_trees/check_perfect_binary_tree.py
{ "start": 118, "end": 887 }
class ____: def __init__(self, val): self.val = val self.left = None self.right = None # Returns depth of leftmost leaf def find_depth(root): d = 0 while root: d += 1 root = root.left return d def check_perfect(root, d, level=0): if not root: ret...
Node