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
PyCQA__pylint
tests/functional/a/abstract/abstract_method.py
{ "start": 1031, "end": 1164 }
class ____(Abstract): # [abstract-method] """Concrete class""" def aaaa(self): """overridden form Abstract"""
Concrete
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_v2_types.py
{ "start": 864, "end": 9822 }
class ____(object, metaclass=abc.ABCMeta): """Represents a feature column abstraction. WARNING: Do not subclass this layer unless you know what you are doing: the API is subject to future changes. To distinguish between the concept of a feature family and a specific binary feature within a family, we refer ...
FeatureColumn
python
huggingface__transformers
tests/utils/test_cache_utils.py
{ "start": 11763, "end": 25314 }
class ____(unittest.TestCase): """Hard cache integration tests that require loading different models""" def setUp(self): # Clears memory before each test. Some tests use large models, which might result in suboptimal torch # re-allocation if we run multiple tests in a row without clearing memor...
CacheHardIntegrationTest
python
huggingface__transformers
tests/models/llava_next_video/test_video_processing_llava_next_video.py
{ "start": 3249, "end": 4922 }
class ____(VideoProcessingTestMixin, unittest.TestCase): fast_video_processing_class = LlavaNextVideoVideoProcessor if is_torchvision_available() else None def setUp(self): super().setUp() self.video_processor_tester = LlavaNextVideoProcessingTester(self) @property def video_processor_...
LlavaNextVideoProcessingTest
python
fastai__fastai
fastai/vision/gan.py
{ "start": 7133, "end": 8030 }
class ____(Module): "Expand the `target` to match the `output` size before applying `crit`." def __init__(self, crit:Callable): self.crit = crit def forward(self, output:Tensor, target:Tensor): return self.crit(output, target[:,None].expand_as(output).float()) # %% ../../nbs/24_vision.gan.ipynb 25 ...
AdaptiveLoss
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/tests/utils.py
{ "start": 251, "end": 2371 }
class ____: """HACK: We Mock the Dagger.container class manually as AsyncMock does not properly infer the return type of the with_label and with_exec methods.""" def with_label(self, *args, **kwargs): return self async def with_exec(self, *args, **kwargs): return self def with_file(se...
MockContainerClass
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 16361, "end": 16881 }
class ____(_Multi2VecBase): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.MULTI2VEC_COHERE, frozen=True, exclude=True ) baseURL: Optional[AnyHttpUrl] model: Optional[str] dimensions: Optional[int] truncate: Optional[CohereTruncation] def _to_dict(self) ->...
_Multi2VecCohereConfig
python
getsentry__sentry
tests/sentry/silo/test_silo_aware_transaction_patch.py
{ "start": 2660, "end": 2916 }
class ____(TestCase): """Repeat the function above in a test class, just in case doing so produces small differences in the execution stack.""" def test_is_in_test_case_body(self) -> None: assert is_in_test_case_body()
TestIsInTestCaseBody
python
readthedocs__readthedocs.org
readthedocs/core/middleware.py
{ "start": 181, "end": 1676 }
class ____: """ Block all requests that contains NULL characters (0x00) on their GET attributes. Requests containing NULL characters make our code to break. In particular, when trying to save the content containing a NULL character into the database, producing a 500 and creating an event in Sentry....
NullCharactersMiddleware
python
getsentry__sentry
tests/sentry/backup/test_exports.py
{ "start": 34978, "end": 36585 }
class ____(ExportTestCase): """ Some models have custom export logic that requires bespoke testing. """ def test_export_query_for_option_model(self) -> None: # There are a number of options we specifically exclude by name, for various reasons # enumerated in that model's definition file...
QueryTests
python
pytorch__pytorch
test/distributed/checkpoint/test_pg_transport.py
{ "start": 7646, "end": 8793 }
class ____(MultiProcContinuousTest): world_size = 2 timeout: timedelta = timedelta(seconds=20) @classmethod def backend_str(cls) -> Optional[str]: return dist.get_default_backend_for_device(cls.device_type()) @property def device(self) -> torch.device: return torch.device(f"{se...
PgTransportGPU
python
huggingface__transformers
src/transformers/models/qwen3_moe/modular_qwen3_moe.py
{ "start": 1563, "end": 1852 }
class ____(Qwen3Attention): # This is the main diff with qwen2Moe! def __init__(self, config: Qwen3MoeConfig, layer_idx: int): super().__init__(config, layer_idx) del self.layer_type self.sliding_window = getattr(config, "sliding_window", None)
Qwen3MoeAttention
python
google__jax
jax/_src/core.py
{ "start": 44447, "end": 46046 }
class ____: axis_sizes : dict[AxisName, int] spmd_axis_names : set[AxisName] explicit_mesh_axis_names: frozenset[AxisName] def axis_size(self, axis_name): if axis_name not in self.axis_sizes: raise NameError(f"unbound axis name: {axis_name}") else: return self.axis_sizes[axis_name] def a...
AxisEnv
python
huggingface__transformers
src/transformers/models/granitemoeshared/modeling_granitemoeshared.py
{ "start": 4030, "end": 4775 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ GraniteMoeSharedRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): ...
GraniteMoeSharedRMSNorm
python
conda__conda
conda/common/io.py
{ "start": 3265, "end": 12306 }
class ____(Enum): """Constants used for contextmanager captured. Used similarly like the constants PIPE, STDOUT for stdlib's subprocess.Popen. """ STRING = -1 STDOUT = -2 @contextmanager def env_vars(var_map=None, callback=None, stack_callback=None): if var_map is None: var_map = {} ...
CaptureTarget
python
django-debug-toolbar__django-debug-toolbar
tests/test_integration.py
{ "start": 26542, "end": 39310 }
class ____(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() options = Options() if os.environ.get("CI"): options.add_argument("-headless") # Set the browser preference to light mode for consistent testing options.set_preference...
DebugToolbarLiveTestCase
python
Pylons__pyramid
tests/test_security.py
{ "start": 11985, "end": 12705 }
class ____(unittest.TestCase): def setUp(self): testing.setUp() def tearDown(self): testing.tearDown() def test_no_security_policy(self): request = _makeRequest() self.assertIs(request.is_authenticated, False) def test_with_security_policy(self): request = _mak...
TestIsAuthenticated
python
scipy__scipy
scipy/stats/_distribution_infrastructure.py
{ "start": 34379, "end": 61625 }
class ____: r""" Represents a parameterization of a distribution. Distributions can have multiple parameterizations. A `_Parameterization` object is responsible for recording the parameters used by the parameterization, checking whether keyword arguments passed to the distribution match the paramet...
_Parameterization
python
qiwsir__algorithm
binary_tree.py
{ "start": 38, "end": 3694 }
class ____: """ 二叉树左右枝 """ def __init__(self, data): """ 节点结构 """ self.left = None self.right = None self.data = data def insert(self, data): """ 插入节点数据 """ if data < self.data: if self.left is None: ...
Node
python
run-llama__llama_index
llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-firestore/llama_index/storage/kvstore/firestore/base.py
{ "start": 797, "end": 8087 }
class ____(BaseKVStore): """ Firestore Key-Value store. Args: project (str): The project which the client acts on behalf of. database (str): The database name that the client targets. credentials (google.auth.credentials.Credentials): The OAuth2 Credentials to access Fir...
FirestoreKVStore
python
neetcode-gh__leetcode
python/0106-construct-binary-tree-from-inorder-and-postorder-traversal.py
{ "start": 192, "end": 834 }
class ____: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: def buildTreeHelper(left, right): if left > right: return None rootVal = postorder.pop() rootNode = TreeNode(rootVal) idx = inorderIndexMap[rootV...
Solution
python
getsentry__sentry
tests/sentry/api/serializers/test_organization_member.py
{ "start": 427, "end": 2171 }
class ____(TestCase): def setUp(self) -> None: self.owner_user = self.create_user("foo@localhost", username="foo") self.user_2 = self.create_user("bar@localhost", username="bar") self.org = self.create_organization(owner=self.owner_user) self.org.member_set.create(user_id=self.user_...
OrganizationMemberSerializerTest
python
django__django
tests/unmanaged_models/models.py
{ "start": 1852, "end": 2469 }
class ____(models.Model): a02 = models.ForeignKey(A02, models.CASCADE, db_column="a01_id") c02 = models.ForeignKey(C02, models.CASCADE, db_column="c01_id") class Meta: db_table = "d01" managed = False # These next models test the creation (or not) of many to many join tables # between man...
Intermediate
python
scrapy__scrapy
tests/test_engine.py
{ "start": 21086, "end": 22541 }
class ____(TestEngineDownloadAsync): """Test cases for ExecutionEngine.download().""" @staticmethod async def _download(engine: ExecutionEngine, request: Request) -> Response: return await maybe_deferred_to_future(engine.download(request)) def test_request_scheduled_signal(caplog): class Test...
TestEngineDownload
python
doocs__leetcode
solution/0100-0199/0121.Best Time to Buy and Sell Stock/Solution.py
{ "start": 0, "end": 199 }
class ____: def maxProfit(self, prices: List[int]) -> int: ans, mi = 0, inf for v in prices: ans = max(ans, v - mi) mi = min(mi, v) return ans
Solution
python
pytorch__pytorch
torch/ao/nn/quantized/modules/activation.py
{ "start": 2526, "end": 3501 }
class ____(torch.nn.ELU): r"""This is the quantized equivalent of :class:`~torch.nn.ELU`. Args: scale: quantization scale of the output tensor zero_point: quantization zero point of the output tensor alpha: the alpha constant """ def __init__(self, scale, zero_point, alpha=1.0)...
ELU
python
getsentry__sentry
src/sentry/backup/services/import_export/model.py
{ "start": 8009, "end": 8253 }
class ____(str, Enum): Unknown = "Unknown" IncorrectSiloModeForModel = "IncorrectSiloModeForModel" UnknownModel = "UnknownModel" UnexportableModel = "UnexportableModel" UnspecifiedScope = "UnspecifiedScope"
RpcExportErrorKind
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 54250, "end": 57060 }
class ____(Request): """ Remove old logs from task :param task: Task ID :type task: str :param allow_locked: Allow deleting events even if the task is locked :type allow_locked: bool :param threshold_sec: The amount of seconds ago to retain the log records. The older log records wil...
ClearTaskLogRequest
python
pydantic__pydantic
pydantic-core/tests/validators/test_model_fields.py
{ "start": 33307, "end": 52122 }
class ____: a: int = 1 b: int = 2 c: str = 'ham' @pytest.mark.parametrize( 'input_value,expected', [ (ClassWithAttributes(), ({'a': 1, 'b': 2, 'c': 'ham'}, None, {'a', 'b', 'c'})), (MyDataclass(), ({'a': 1, 'b': 2, 'c': 'ham'}, None, {'a', 'b', 'c'})), (Cls(a=1, b=2, c='ham...
MyDataclass
python
walkccc__LeetCode
solutions/3280. Convert Date to Binary/3280.py
{ "start": 0, "end": 318 }
class ____: def convertDateToBinary(self, date: str) -> str: year, month, day = map(int, date.split('-')) def toBinary(value: int) -> str: """Converts an integer to binary without leading zeros.""" return bin(value)[2:] return '-'.join([toBinary(year), toBinary(month), toBinary(day)])
Solution
python
django__django
tests/contenttypes_tests/test_models.py
{ "start": 13256, "end": 14199 }
class ____(TestCase): def test_querysets_required(self): msg = ( "GenericPrefetch.__init__() missing 1 required " "positional argument: 'querysets'" ) with self.assertRaisesMessage(TypeError, msg): GenericPrefetch("question") def test_values_queryset(...
GenericPrefetchTests
python
huggingface__transformers
src/transformers/models/flex_olmo/modular_flex_olmo.py
{ "start": 10636, "end": 10835 }
class ____(OlmoeSparseMoeBlock): pass # FlexOlmo decoder layer is identical to OlmoE decoder layer except: # - Norm is applied after attention/feedforward rather than before.
FlexOlmoSparseMoeBlock
python
numba__numba
numba/core/base.py
{ "start": 44302, "end": 45673 }
class ____(object): def __init__(self, fn): self.func = fn # store this to help with debug def __call__(self): """Wrap function for missing ``loc`` keyword argument. Otherwise, return the original *fn*. """ fn = self.func if not _has_loc(fn): def wra...
_wrap_missing_loc
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/execution_plan.py
{ "start": 311, "end": 644 }
class ____(graphene.Union): class Meta: types = ( GrapheneExecutionPlan, GrapheneRunConfigValidationInvalid, GraphenePipelineNotFoundError, GrapheneInvalidSubsetError, GraphenePythonError, ) name = "ExecutionPlanOrError"
GrapheneExecutionPlanOrError
python
yaml__pyyaml
lib/yaml/loader.py
{ "start": 224, "end": 548 }
class ____(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): def __init__(self, stream): Reader.__init__(self, stream) Scanner.__init__(self) Parser.__init__(self) Composer.__init__(self) BaseConstructor.__init__(self) BaseResolver.__init__(self)
BaseLoader
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/test_fail/package.py
{ "start": 217, "end": 678 }
class ____(Package): """This package has a test method that fails in a subprocess.""" homepage = "http://www.example.com/test-failure" url = "http://www.test-failure.test/test-failure-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") def install(self, spec, prefix): mkdir...
TestFail
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 172176, "end": 174251 }
class ____(TestCase): def test_r_less_than_n(self): iterable = 'abcdefg' r = 4 first_index = {} for index, element in enumerate( combinations_with_replacement(iterable, r) ): actual = mi.combination_with_replacement_index(element, iterable) ...
CombinationWithReplacementIndexTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py
{ "start": 3971, "end": 5212 }
class ____(Base1): value: Base1 def handler(node: Base1) -> Any: if isinstance(node, Sub1_1): reveal_type(node.value, expected_text="str") elif isinstance(node, Sub1_2): reveal_type(node.value, expected_text="Base1") if isinstance(node.value, Sub1_1): reveal_type(node.v...
Sub1_2
python
pandas-dev__pandas
asv_bench/benchmarks/multiindex_object.py
{ "start": 9161, "end": 9864 }
class ____: params = [ (("Int64", NA), ("int64", 0)), ] param_names = ["dtype_val"] def setup(self, dtype_val): level = Series( [1, 2, dtype_val[1], dtype_val[1]] + list(range(1_000_000)), dtype=dtype_val[0], ) self.midx = MultiIndex.from_arrays([...
Unique
python
walkccc__LeetCode
solutions/1381. Design a Stack With Increment Operation/1381.py
{ "start": 0, "end": 730 }
class ____: def __init__(self, maxSize: int): self.maxSize = maxSize self.stack = [] # pendingIncrements[i] := the pending increment for stack[0..i]. self.pendingIncrements = [] def push(self, x: int) -> None: if len(self.stack) == self.maxSize: return self.stack.append(x) self.pe...
CustomStack
python
django__django
django/contrib/gis/db/models/functions.py
{ "start": 18539, "end": 18579 }
class ____(GeoFunc): arity = 1
Reverse
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 188646, "end": 189717 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateProject""" __schema__ = github_schema __field_names__ = ("owner_id", "name", "body", "template", "repository_ids", "client_mutation_id") owner_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="ownerId") """The owner ID...
CreateProjectInput
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/asyncpg.py
{ "start": 23522, "end": 30591 }
class ____( AsyncAdapt_terminate, AsyncAdapt_dbapi_connection ): _cursor_cls = AsyncAdapt_asyncpg_cursor _ss_cursor_cls = AsyncAdapt_asyncpg_ss_cursor _connection: _AsyncpgConnection _transaction: Optional[_AsyncpgTransaction] __slots__ = ( "isolation_level", "_isolation_settin...
AsyncAdapt_asyncpg_connection
python
huggingface__transformers
src/transformers/models/unispeech/modular_unispeech.py
{ "start": 12281, "end": 17347 }
class ____(UniSpeechPreTrainedModel): def __init__(self, config: UniSpeechConfig): super().__init__(config) self.unispeech = UniSpeechModel(config) self.dropout_features = nn.Dropout(config.feat_quantizer_dropout) self.quantizer = UniSpeechGumbelVectorQuantizer(config) self....
UniSpeechForPreTraining
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/mappedoperator.py
{ "start": 6017, "end": 11432 }
class ____: """ An "intermediate state" returned by ``BaseOperator.partial()``. This only exists at Dag-parsing time; the only intended usage is for the user to call ``.expand()`` on it at some point (usually in a method chain) to create a ``MappedOperator`` to add into the Dag. """ operat...
OperatorPartial
python
python-openxml__python-docx
tests/image/test_png.py
{ "start": 1980, "end": 4914 }
class ____: def it_can_parse_the_headers_of_a_PNG_stream( self, stream_, _Chunks_, _PngParser__init_, chunks_ ): png_parser = _PngParser.parse(stream_) _Chunks_.from_stream.assert_called_once_with(stream_) _PngParser__init_.assert_called_once_with(ANY, chunks_) assert is...
Describe_PngParser
python
pypa__setuptools
setuptools/_distutils/tests/test_file_util.py
{ "start": 423, "end": 3522 }
class ____: def test_move_file_verbosity(self, caplog): jaraco.path.build({self.source: 'some content'}) move_file(self.source, self.target, verbose=False) assert not caplog.messages # back to original state move_file(self.target, self.source, verbose=False) move_f...
TestFileUtil
python
pydata__xarray
xarray/core/utils.py
{ "start": 15658, "end": 17388 }
class ____(Frozen[K, V]): """ Class which behaves like a Mapping but warns if the values are accessed. Temporary object to aid in deprecation cycle of `Dataset.dims` (see GH issue #8496). `Dataset.dims` is being changed from returning a mapping of dimension names to lengths to just returning a froz...
FrozenMappingWarningOnValuesAccess
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_comment06.py
{ "start": 315, "end": 1099 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("comment06.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with comments.""" workbook = Workboo...
TestCompareXLSXFiles
python
doocs__leetcode
solution/0300-0399/0377.Combination Sum IV/Solution.py
{ "start": 0, "end": 270 }
class ____: def combinationSum4(self, nums: List[int], target: int) -> int: f = [1] + [0] * target for i in range(1, target + 1): for x in nums: if i >= x: f[i] += f[i - x] return f[target]
Solution
python
tensorflow__tensorflow
tensorflow/lite/python/lite.py
{ "start": 60512, "end": 63612 }
class ____(TFLiteConverterBaseV2): """Converts the given SavedModel into TensorFlow Lite model. Attributes: saved_model_dir: Directory of the SavedModel. """ def __init__( self, saved_model_dir, saved_model_tags=None, saved_model_exported_names=None, trackable_obj=None, )...
TFLiteSavedModelConverterV2
python
mlflow__mlflow
mlflow/utils/environment.py
{ "start": 1822, "end": 36135 }
class ____: BUILD_PACKAGES = ("pip", "setuptools", "wheel") def __init__(self, python=None, build_dependencies=None, dependencies=None): """ Represents environment information for MLflow Models and Projects. Args: python: Python version for the environment. If unspecified, ...
_PythonEnv
python
conda__conda
conda/models/package_info.py
{ "start": 975, "end": 1292 }
class ____(Entity): # from info/package_metadata.json package_metadata_version = IntegerField() noarch = ComposableField(Noarch, required=False, nullable=True) preferred_env = ComposableField( PreferredEnv, required=False, nullable=True, default=None, default_in_dump=False )
PackageMetadata
python
django-extensions__django-extensions
tests/test_management_command.py
{ "start": 13642, "end": 19323 }
class ____(TestCase): """ Tests for the `merge_model_instances` management command. """ @mock.patch( "django_extensions.management.commands.merge_model_instances.apps.get_models" ) @mock.patch("django_extensions.management.commands.merge_model_instances.input") def test_get_model_to...
MergeModelInstancesTests
python
getsentry__sentry
src/sentry/api/helpers/group_index/validators/in_commit.py
{ "start": 224, "end": 323 }
class ____(TypedDict): commit: str repository: str @extend_schema_serializer()
InCommitResult
python
nedbat__coveragepy
tests/test_lcov.py
{ "start": 344, "end": 18903 }
class ____(CoverageTest): """Tests of the LCOV reports from coverage.py.""" def create_initial_files(self) -> None: """ Helper for tests that handles the common ceremony so the tests can show the consequences of changes in the setup. """ self.make_file( "main...
LcovTest
python
spyder-ide__spyder
spyder/plugins/pylint/main_widget.py
{ "start": 2366, "end": 2565 }
class ____: FileComboBox = 'file_combo' RateLabel = 'rate_label' DateLabel = 'date_label' Stretcher1 = 'stretcher_1' Stretcher2 = 'stretcher_2' # ---- Items
PylintWidgetToolbarItems
python
python__mypy
mypy/types.py
{ "start": 18067, "end": 20486 }
class ____: # A type variable is uniquely identified by its raw id and meta level. # For plain variables (type parameters of generic classes and # functions) raw ids are allocated by semantic analysis, using # positive ids 1, 2, ... for generic class parameters and negative # ids -1, ... for generi...
TypeVarId
python
plotly__plotly.py
plotly/graph_objs/scattersmith/unselected/_marker.py
{ "start": 233, "end": 4076 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattersmith.unselected" _path_str = "scattersmith.unselected.marker" _valid_props = {"color", "opacity", "size"} @property def color(self): """ Sets the marker color of unselected points, applied only when a selection...
Marker
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 7494, "end": 8317 }
class ____(CompileError): """Raised when an operation is not supported by the given compiler. .. seealso:: :ref:`faq_sql_expression_string` :ref:`error_l7de` """ code = "l7de" def __init__( self, compiler: Union[Compiled, TypeCompiler], element_type: Type...
UnsupportedCompilationError
python
openai__openai-python
src/openai/resources/vector_stores/files.py
{ "start": 18951, "end": 36917 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFilesWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.gith...
AsyncFiles
python
scipy__scipy
scipy/stats/_multivariate.py
{ "start": 258612, "end": 268815 }
class ____(multi_rv_generic): r"""Normal-inverse-gamma distribution. The normal-inverse-gamma distribution is the conjugate prior of a normal distribution with unknown mean and variance. Methods ------- pdf(x, s2, mu=0, lmbda=1, a=1, b=1) Probability density function. logpdf(x, s2,...
normal_inverse_gamma_gen
python
getsentry__sentry
src/sentry/api/serializers/models/exploresavedquery.py
{ "start": 1322, "end": 5126 }
class ____(Serializer): def get_attrs(self, item_list, user, **kwargs): result: DefaultDict[str, dict] = defaultdict(lambda: {"created_by": {}}) starred_queries = dict( ExploreSavedQueryStarred.objects.filter( explore_saved_query__in=item_list, user_id=us...
ExploreSavedQueryModelSerializer
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 437859, "end": 439784 }
class ____(Request): """ Get the list of task configuration items names :param tasks: Task IDs :type tasks: Sequence[str] :param skip_empty: If set to 'true' then the names for configurations with missing values are not returned :type skip_empty: bool """ _service = "tasks" ...
GetConfigurationNamesRequest
python
pola-rs__polars
py-polars/tests/docs/run_doctest.py
{ "start": 3416, "end": 6638 }
class ____(unittest.TestSuite): # noqa: D101 def __iter__(self) -> Iterator[Any]: for suite in self._tests: suite._tests = [ # type: ignore[attr-defined] test for test in suite._tests # type: ignore[attr-defined] if test.id().rsplit(".", 1)[-1] ...
FilteredTestSuite
python
pytorch__pytorch
test/test_privateuseone_python_backend.py
{ "start": 447, "end": 3411 }
class ____(torch.Tensor): @staticmethod def __new__(cls, size, dtype, raw_data=None, requires_grad=False): # Use a meta Tensor here to be used as the wrapper res = torch._C._acc.create_empty_tensor(size, dtype) res.__class__ = MyDeviceTensor return res def __init__(self, siz...
MyDeviceTensor
python
django__django
tests/model_fields/models.py
{ "start": 2925, "end": 3015 }
class ____(models.Model): d = models.DecimalField(max_digits=32, decimal_places=30)
BigD
python
getsentry__sentry
src/sentry/auth/services/auth/model.py
{ "start": 956, "end": 1465 }
class ____(RpcModel): id: int = -1 user_id: int = -1 organization_id: int | None = None application_id: int | None = None application_is_active: bool = False token: str = Field(repr=False, default="") hashed_token: str | None = Field(repr=False, default=None) expires_at: datetime.datetim...
RpcApiToken
python
fastai__fastai
nbs/examples/migrating_ignite.py
{ "start": 541, "end": 3837 }
class ____(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 10) def forwa...
Net
python
huggingface__transformers
src/transformers/models/dots1/modeling_dots1.py
{ "start": 16280, "end": 18749 }
class ____(nn.Module): """ A mixed expert module containing shared experts. """ def __init__(self, config): super().__init__() self.config = config self.experts = Dots1NaiveMoe(config) self.gate = Dots1TopkRouter(config) self.shared_experts = Dots1MLP( ...
Dots1MoE
python
jmcnamara__XlsxWriter
xlsxwriter/test/table/test_table10.py
{ "start": 481, "end": 2037 }
class ____(unittest.TestCase): """ Test assembling a complete Table file. """ def test_assemble_xml_file(self): """Test writing a table""" self.maxDiff = None worksheet = Worksheet() worksheet.worksheet_meta = WorksheetMeta() worksheet.str_table = SharedStringT...
TestAssembleTable
python
huggingface__transformers
src/transformers/models/swinv2/modeling_swinv2.py
{ "start": 52481, "end": 55773 }
class ____(Swinv2PreTrainedModel, BackboneMixin): def __init__(self, config): super().__init__(config) super()._init_backbone(config) self.num_features = [config.embed_dim] + [int(config.embed_dim * 2**i) for i in range(len(config.depths))] self.embeddings = Swinv2Embeddings(config)...
Swinv2Backbone
python
mozilla__bleach
bleach/_vendor/html5lib/treewalkers/etree_lxml.py
{ "start": 1747, "end": 1967 }
class ____(Root): def __init__(self, children): self.children = [FragmentWrapper(self, child) for child in children] self.text = self.tail = None def getnext(self): return None
FragmentRoot
python
ApeWorX__ape
tests/functional/test_project.py
{ "start": 26669, "end": 30652 }
class ____: """ All tests related to ``ape.Project``. """ def test_init(self, with_dependencies_project_path): # Purpose not using `project_with_contracts` fixture. project = Project(with_dependencies_project_path) # NOTE: Using tempdir to avoid clashing with other tests during...
TestProject
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 75927, "end": 79832 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[8, 8]"): l_x_ = L_x_ subgraph_0 = self.subgraph_0 invoke_subgraph = torch.ops.higher_order.invoke_subgraph(subgraph_0, 'subgraph_0', l_x_); subgraph_0 = None getitem: "f32[8, 8]" = invoke_subgraph[0]; invoke_subgraph = None...
GraphModule
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_assets.py
{ "start": 1349, "end": 6007 }
class ____: def test_should_response_200(self, test_client, dag_maker): with dag_maker( dag_id="upstream", schedule=[Asset(uri="s3://bucket/next-run-asset/1", name="asset1")], serialized=True, ): EmptyOperator(task_id="task1") dag_maker.create...
TestNextRunAssets
python
ray-project__ray
python/ray/remote_function.py
{ "start": 1233, "end": 24448 }
class ____: """A remote function. This is a decorated function. It can be used to spawn tasks. Attributes: _language: The target language. _function: The original function. _function_descriptor: The function descriptor. This is not defined until the remote function is f...
RemoteFunction
python
crytic__slither
slither/printers/summary/function.py
{ "start": 171, "end": 3945 }
class ____(AbstractPrinter): ARGUMENT = "function-summary" HELP = "Print a summary of the functions" WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#function-summary" @staticmethod def _convert(l): if l: n = 2 l = [l[i : i + n] for i in ra...
FunctionSummary
python
jazzband__django-model-utils
tests/test_fields/test_field_tracker.py
{ "start": 26086, "end": 30877 }
class ____(FieldTrackerMixin, TestCase): tracked_class = TrackedFileField instance: TrackedFileField def setUp(self) -> None: self.instance = self.tracked_class() self.tracker = self.instance.tracker self.some_file = 'something.txt' self.another_file = 'another.txt' de...
FieldTrackerFileFieldTests
python
django__django
tests/multiple_database/tests.py
{ "start": 80369, "end": 80539 }
class ____: """ A router that sends all writes to the other database. """ def db_for_write(self, model, **hints): return "other"
WriteToOtherRouter
python
spack__spack
lib/spack/spack/error.py
{ "start": 4375, "end": 4494 }
class ____(SpackError): """Raised when the wrong arguments are suppled to the patch directive."""
PatchDirectiveError
python
allegroai__clearml
clearml/backend_api/services/v2_23/queues.py
{ "start": 57164, "end": 57426 }
class ____(Request): """ """ _service = "queues" _action = "get_default" _version = "2.23" _schema = { "additionalProperties": True, "definitions": {}, "properties": {}, "type": "object", }
GetDefaultRequest
python
PrefectHQ__prefect
tests/test_logging.py
{ "start": 53795, "end": 55992 }
class ____: def test_json_log_formatter(self): formatter = JsonFormatter("default", None, "%") record = logging.LogRecord( name="Test Log", level=1, pathname="/path/file.py", lineno=1, msg="log message", args=None, e...
TestJsonFormatter
python
instagram__MonkeyType
tests/test_config.py
{ "start": 290, "end": 1090 }
class ____: def test_excludes_stdlib(self): assert not config.default_code_filter(sysconfig.get_path.__code__) def test_excludes_site_packages(self): assert not config.default_code_filter(pytest.skip.__code__) def test_includes_otherwise(self): assert config.default_code_filter(con...
TestDefaultCodeFilter
python
great-expectations__great_expectations
tests/datasource/fluent/_fake_cloud_api.py
{ "start": 1925, "end": 2168 }
class ____(pydantic.BaseModel): data: _DatasourceSchema @classmethod def from_datasource_json(cls, ds_payload: str | bytes) -> CloudResponseSchema: data = json.loads(ds_payload) return cls(**data)
CloudResponseSchema
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/sqlite/aiosqlite.py
{ "start": 8225, "end": 9639 }
class ____(SQLiteDialect_pysqlite): driver = "aiosqlite" supports_statement_cache = True is_async = True supports_server_side_cursors = True execution_ctx_cls = SQLiteExecutionContext_aiosqlite @classmethod def import_dbapi(cls) -> AsyncAdapt_aiosqlite_dbapi: return AsyncAdapt_ai...
SQLiteDialect_aiosqlite
python
streamlit__streamlit
lib/tests/streamlit/elements/graphviz_test.py
{ "start": 867, "end": 6082 }
class ____(DeltaGeneratorTestCase): """Test ability to marshall graphviz_chart protos.""" def test_spec(self): """Test that it can be called with spec.""" graph = graphviz.Graph(comment="The Round Table") graph.node("A", "King Arthur") graph.node("B", "Sir Bedevere the Wise") ...
GraphvizTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 8429, "end": 8940 }
class ____(SQLAlchemyError): """A disconnect is detected on a raw DB-API connection. This error is raised and consumed internally by a connection pool. It can be raised by the :meth:`_events.PoolEvents.checkout` event so that the host pool forces a retry; the exception will be caught three times i...
DisconnectionError
python
django__django
tests/cache/tests.py
{ "start": 107654, "end": 111483 }
class ____(SimpleTestCase): """ Tests various headers w/ TemplateResponse. Most are probably redundant since they manipulate the same object anyway but the ETag header is 'special' because it relies on the content being complete (which is not necessarily always the case with a TemplateResponse)...
TestWithTemplateResponse
python
tensorflow__tensorflow
tensorflow/python/keras/engine/training_utils_v1.py
{ "start": 16739, "end": 68807 }
class ____(Aggregator): """Aggregator that concatenates outputs.""" _structure = None def create(self, batch_outs): # SparseTensorValue is a named tuple which nest will flatten, so we need # to guard it to properly handle the structure. self._structure = nest.get_traverse_shallow_structure( ...
OutputsAggregator
python
scikit-learn__scikit-learn
asv_benchmarks/benchmarks/decomposition.py
{ "start": 1623, "end": 2406 }
class ____(Transformer, Estimator, Benchmark): """ Benchmarks for MiniBatchDictionaryLearning """ param_names = ["fit_algorithm", "n_jobs"] params = (["lars", "cd"], Benchmark.n_jobs_vals) def setup_cache(self): super().setup_cache() def make_data(self, params): return _ol...
MiniBatchDictionaryLearningBenchmark
python
dagster-io__dagster
python_modules/libraries/dagster-mlflow/dagster_mlflow/resources.py
{ "start": 1676, "end": 2352 }
class ____(type): """Mlflow Metaclass to create methods that "inherit" all of Mlflow's methods. If the class has a method defined it is excluded from the attribute setting from mlflow. """ def __new__(cls, name, bases, attrs): class_cls = super().__new__(cls, name, bases, attrs) for...
MlflowMeta
python
astropy__astropy
astropy/samp/tests/test_helpers.py
{ "start": 1188, "end": 2198 }
class ____: def __init__(self, client): self.client = client def receive_notification(self, private_key, sender_id, mtype, params, extra): write_output(mtype, private_key, sender_id, params) def receive_call(self, private_key, sender_id, msg_id, mtype, params, extra): # Here we nee...
Receiver
python
tensorflow__tensorflow
tensorflow/python/data/ops/from_tensor_slices_op.py
{ "start": 1103, "end": 2409 }
class ____(dataset_ops.DatasetSource): """A `Dataset` of slices from a dataset element.""" def __init__(self, element, is_files=False, name=None): """See `Dataset.from_tensor_slices` for details.""" element = structure.normalize_element(element) batched_spec = structure.type_spec_from_value(element) ...
_TensorSliceDataset
python
getsentry__sentry
src/sentry/analytics/events/base_notification_sent.py
{ "start": 67, "end": 412 }
class ____(analytics.Event, abc.ABC): organization_id: int project_id: int | None = None category: str actor_id: int | None = None user_id: int | None = None group_id: int | None = None id: int | None = None actor_type: str | None = None notification_uuid: str alert_id: int | Non...
BaseNotificationSent
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_table07.py
{ "start": 315, "end": 914 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("table07.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with tables.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
mlflow__mlflow
mlflow/utils/async_logging/run_artifact.py
{ "start": 93, "end": 1074 }
class ____: def __init__( self, filename: str, artifact_path: str, artifact: Union["PIL.Image.Image"], completion_event: threading.Event, ) -> None: """Initializes an instance of `RunArtifacts`. Args: filename: Filename of the artifact to be l...
RunArtifact
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py
{ "start": 2339, "end": 2775 }
class ____: """Test EcsTaskInfo dataclass.""" def test_ecs_task_info_creation(self): """Test EcsTaskInfo object creation.""" cmd = ["echo", "hello"] queue = "default" config = {"key": "value"} task_info = EcsTaskInfo(cmd=cmd, queue=queue, config=config) assert ...
TestEcsTaskInfo
python
crytic__slither
slither/tools/upgradeability/checks/variables_order.py
{ "start": 8432, "end": 9303 }
class ____(ExtraVariablesProxy): ARGUMENT = "extra-vars-v2" HELP = "Extra vars in the v2" WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#extra-variables-in-the-v2" WIKI_TITLE = "Extra variables in the v2" # region wiki_description WIKI_DESCRIPTION = """ Show new variables...
ExtraVariablesNewContract
python
realpython__materials
flask-connexion-rest-part-4/models.py
{ "start": 1728, "end": 2030 }
class ____(ma.ModelSchema): """ This class exists to get around a recursion issue """ def __init__(self, **kwargs): super().__init__(strict=True, **kwargs) person_id = fields.Int() lname = fields.Str() fname = fields.Str() timestamp = fields.Str()
NotePersonSchema