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
facelessuser__pymdown-extensions
tests/test_extensions/test_fancylists.py
{ "start": 52, "end": 21855 }
class ____(util.MdCase): """Test fancy lists.""" extension = ['pymdownx.fancylists', 'pymdownx.saneheaders'] extension_configs = {} def test_fail_case(self): """Test failed case.""" self.check_markdown( """ 1. foo . bar 1) foo ...
TestFancyLists
python
scipy__scipy
scipy/stats/_multivariate.py
{ "start": 86237, "end": 105822 }
class ____(multi_rv_generic): r"""A Wishart random variable. The `df` keyword specifies the degrees of freedom. The `scale` keyword specifies the scale matrix, which must be symmetric and positive definite. In this context, the scale matrix is often interpreted in terms of a multivariate normal pre...
wishart_gen
python
mlflow__mlflow
mlflow/types/chat.py
{ "start": 3338, "end": 3424 }
class ____(BaseModel): type: AllowedType | list[AllowedType] | None = None
ParamType
python
kamyu104__LeetCode-Solutions
Python/design-skiplist.py
{ "start": 407, "end": 2897 }
class ____(object): P_NUMERATOR, P_DENOMINATOR = 1, 2 # P = 1/4 in redis implementation MAX_LEVEL = 32 # enough for 2^32 elements def __init__(self): self.__head = SkipNode() self.__len = 0 def search(self, target): """ :type target: int :rtype: bool "...
Skiplist
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_dtensor_state_dict.py
{ "start": 992, "end": 1538 }
class ____(torch.nn.Module): def __init__(self): super().__init__() torch.manual_seed(0) self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU()) self.net2 = nn.Sequential(nn.Linear(16, 32), nn.ReLU()) self.net3 = nn.Sequential(nn.Linear(32, 64), nn.ReLU()) self.net4 = ...
TestDummyModel
python
dagster-io__dagster
helm/dagster/schema/schema/charts/utils/kubernetes.py
{ "start": 2805, "end": 2986 }
class ____(BaseModel): model_config = { "extra": "allow", "json_schema_extra": {"$ref": create_definition_ref("io.k8s.api.core.v1.Container")}, }
InitContainer
python
google__pytype
pytype/tools/traces/traces_test.py
{ "start": 8401, "end": 9452 }
class ____(MatchAstTestCase): def test_num(self): matches = self._get_traces("v = 42", ast.Constant) self.assertTracesEqual(matches, [((1, 4), "LOAD_CONST", 42, ("int",))]) def test_str(self): matches = self._get_traces("v = 'hello'", ast.Constant) self.assertTracesEqual(matches, [((1, 4), "LOAD_C...
MatchConstantTest
python
ray-project__ray
python/ray/train/v2/api/result.py
{ "start": 735, "end": 4859 }
class ____(ResultV1): checkpoint: Optional[Checkpoint] error: Optional[TrainingFailedError] best_checkpoints: Optional[List[Tuple[Checkpoint, Dict[str, Any]]]] = None @PublicAPI(stability="alpha") def get_best_checkpoint( self, metric: str, mode: str ) -> Optional["ray.train.Checkpoint"...
Result
python
pytorch__pytorch
test/inductor/test_lookup_table.py
{ "start": 1547, "end": 2822 }
class ____(MMKernelInputs): """Mock MMKernelInputs that subclasses the real class and uses real tensors""" def __init__( self, tensors: list[torch.Tensor], scalars: Optional[dict[str, Union[float, int]]] = None, mat1_idx: int = -2, mat2_idx: int = -1, ): """I...
MockMMKernelInputs
python
apache__airflow
task-sdk/tests/task_sdk/definitions/test_callback.py
{ "start": 1548, "end": 6717 }
class ____: @pytest.mark.parametrize( ("subclass", "callable"), [ pytest.param(AsyncCallback, empty_async_callback_for_deadline_tests, id="async"), pytest.param(SyncCallback, empty_sync_callback_for_deadline_tests, id="sync"), ], ) def test_init_error_reserved...
TestCallback
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocolModule2.py
{ "start": 413, "end": 545 }
class ____(Protocol): var_1: str # This should generate an error because var_1 has the # wrong type. v2: P2 = protocolModule1
P2
python
realpython__materials
python-import/namespace_package/third_party/serializers/json.py
{ "start": 49, "end": 391 }
class ____: def __init__(self): self._current_object = None def start_object(self, object_name, object_id): self._current_object = dict(id=object_id) def add_property(self, name, value): self._current_object[name] = value def __str__(self): return json.dumps(self._curr...
JsonSerializer
python
scikit-image__scikit-image
src/skimage/transform/_thin_plate_splines.py
{ "start": 165, "end": 8124 }
class ____: """Thin-plate spline transformation. Given two matching sets of points, source and destination, this class estimates the thin-plate spline (TPS) transformation which transforms each point in source into its destination counterpart. Attributes ---------- src : (N, 2) array_like ...
ThinPlateSplineTransform
python
walkccc__LeetCode
solutions/22. Generate Parentheses/22.py
{ "start": 0, "end": 368 }
class ____: def generateParenthesis(self, n): ans = [] def dfs(l: int, r: int, s: list[str]) -> None: if l == 0 and r == 0: ans.append(''.join(s)) if l > 0: s.append('(') dfs(l - 1, r, s) s.pop() if l < r: s.append(')') dfs(l, r - 1, s) ...
Solution
python
doocs__leetcode
solution/1700-1799/1762.Buildings With an Ocean View/Solution.py
{ "start": 0, "end": 279 }
class ____: def findBuildings(self, heights: List[int]) -> List[int]: ans = [] mx = 0 for i in range(len(heights) - 1, -1, -1): if heights[i] > mx: ans.append(i) mx = heights[i] return ans[::-1]
Solution
python
scrapy__scrapy
tests/mockserver/http_resources.py
{ "start": 4190, "end": 4651 }
class ____(LeafResource): def render_GET(self, request): request.startedWriting = 1 self.deferRequest(request, 0, self._delayedRender, request) return NOT_DONE_YET render_POST = render_GET def _delayedRender(self, request): raw = getarg(request, b"raw", b"HTTP 1.1 200 OK\n"...
Raw
python
gevent__gevent
src/greentest/3.14/test_urllib2.py
{ "start": 17172, "end": 17556 }
class ____(urllib.request.HTTPHandler): # Very simple mock HTTP handler with no special behavior other than using a mock HTTP connection def __init__(self, debuglevel=None): super(MockHTTPHandler, self).__init__(debuglevel=debuglevel) self.httpconn = MockHTTPClass() def http_open(self, req...
MockHTTPHandler
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 336038, "end": 340277 }
class ____(Request): """ Publish tasks :param ids: Entities to move :type ids: Sequence[str] :param status_reason: Reason for status change :type status_reason: str :param status_message: Extra information regarding status change :type status_message: str :param force: If not true, ...
PublishManyRequest
python
apache__airflow
providers/opensearch/src/airflow/providers/opensearch/operators/opensearch.py
{ "start": 4389, "end": 5724 }
class ____(BaseOperator): """ Create a new index on an OpenSearch cluster with a given index name. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:OpenSearchCreateIndexOperator` :param index_name: The name of the index to be...
OpenSearchCreateIndexOperator
python
pyinstaller__pyinstaller
bootloader/waflib/Tools/cs.py
{ "start": 4175, "end": 4439 }
class ____(Task.Task): color = 'YELLOW' inst_to = None def runnable_status(self): return Task.SKIP_ME @conf def read_csshlib(self, name, paths=[]): return self(name=name, features='fake_lib', lib_paths=paths, lib_type='csshlib')
fake_csshlib
python
huggingface__transformers
src/transformers/models/modernbert/modeling_modernbert.py
{ "start": 22530, "end": 24600 }
class ____(GradientCheckpointingLayer): def __init__(self, config: ModernBertConfig, layer_id: Optional[int] = None): super().__init__() self.config = config if layer_id == 0: self.attn_norm = nn.Identity() else: self.attn_norm = nn.LayerNorm(config.hidden_siz...
ModernBertEncoderLayer
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 16099, "end": 16407 }
class ____(Sky2PixProjection, Zenithal): r""" Zenithal equidistant projection - sky to pixel. Corresponds to the ``ARC`` projection in FITS WCS. See `Zenithal` for a definition of the full transformation. .. math:: R_\theta = 90^\circ - \theta """
Sky2Pix_ZenithalEquidistant
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/math_ops/banded_triangular_solve_op_test.py
{ "start": 960, "end": 8924 }
class ____(test.TestCase): def _verifySolveAllWays(self, x, y, dtypes, batch_dims=None): for lower in (False,): for adjoint in (False, True): for use_placeholder in True, False: self._verifySolve( x, y, lower=lower, adjoint=adjoint, ...
BandedTriangularSolveOpTest
python
openai__openai-python
src/openai/types/evals/create_eval_completions_run_data_source.py
{ "start": 1746, "end": 1913 }
class ____(BaseModel): id: str """The identifier of the file.""" type: Literal["file_id"] """The type of jsonl source. Always `file_id`."""
SourceFileID
python
ansible__ansible
test/units/module_utils/datatag/test_datatag.py
{ "start": 30535, "end": 32713 }
class ____(AnsibleTaggedObject): """A surrogate test type that allows empty tags.""" __slots__ = ('_ansible_tags_mapping', '_value') _empty_tags_as_native: t.ClassVar[bool] = False _value: str def __init__(self, value: str): self._ansible_tags_mapping = _EMPTY_INTERNAL_TAGS_MAPPING def t...
NonNativeTaggedType
python
doocs__leetcode
solution/0700-0799/0707.Design Linked List/Solution.py
{ "start": 0, "end": 1214 }
class ____: def __init__(self): self.dummy = ListNode() self.cnt = 0 def get(self, index: int) -> int: if index < 0 or index >= self.cnt: return -1 cur = self.dummy.next for _ in range(index): cur = cur.next return cur.val def addAtHe...
MyLinkedList
python
TheAlgorithms__Python
graphs/bidirectional_a_star.py
{ "start": 526, "end": 1661 }
class ____: """ >>> k = Node(0, 0, 4, 3, 0, None) >>> k.calculate_heuristic() 5.0 >>> n = Node(1, 4, 3, 4, 2, None) >>> n.calculate_heuristic() 2.0 >>> l = [k, n] >>> n == l[0] False >>> l.sort() >>> n == l[0] True """ def __init__( self, pos_...
Node
python
scrapy__scrapy
tests/AsyncCrawlerProcess/caching_hostname_resolver.py
{ "start": 75, "end": 920 }
class ____(scrapy.Spider): """ Finishes in a finite amount of time (does not hang indefinitely in the DNS resolution) """ name = "caching_hostname_resolver_spider" async def start(self): yield scrapy.Request(self.url) def parse(self, response): for _ in range(10): ...
CachingHostnameResolverSpider
python
pydantic__pydantic
tests/test_pickle.py
{ "start": 4773, "end": 5021 }
class ____: a: int b: float def dataclass_factory() -> type: @pydantic.dataclasses.dataclass class NonImportableDataclass: a: int b: float return NonImportableDataclass @dataclasses.dataclass
ImportableDataclass
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py
{ "start": 7688, "end": 7961 }
class ____(graphene.Union): class Meta: types = ( GrapheneDefaultPartitionStatuses, GrapheneMultiPartitionStatuses, GrapheneTimePartitionStatuses, ) name = "AssetPartitionStatuses"
GrapheneAssetPartitionStatuses
python
tensorflow__tensorflow
tensorflow/compiler/tests/bucketize_op_test.py
{ "start": 1049, "end": 2955 }
class ____(xla_test.XLATestCase): def testInt(self): with self.session() as sess: p = array_ops.placeholder(dtypes.int32) with self.test_scope(): op = math_ops._bucketize(p, boundaries=[0, 3, 8, 11]) expected_out = [0, 1, 1, 2, 2, 3, 3, 4, 4] self.assertAllEqual(expected_out, ...
BucketizationOpTest
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 112486, "end": 114714 }
class ____(Response): """ Response of events.vector_metrics_iter_histogram endpoint. :param images: :type images: Sequence[dict] """ _service = "events" _action = "vector_metrics_iter_histogram" _version = "2.13" _schema = { "definitions": {}, "properties": {"images...
VectorMetricsIterHistogramResponse
python
numba__numba
numba/core/types/misc.py
{ "start": 7229, "end": 7962 }
class ____(Callable, Phantom): """ The type of exception classes (not instances). """ def __init__(self, exc_class): assert issubclass(exc_class, BaseException) name = "%s" % (exc_class.__name__) self.exc_class = exc_class super(ExceptionClass, self).__init__(name) ...
ExceptionClass
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/auth_manager/avp/facade.py
{ "start": 2248, "end": 2495 }
class ____(TypedDict, total=False): """Represent the parameters of ``is_authorized`` method in AVP facade.""" method: ExtendedResourceMethod entity_type: AvpEntities entity_id: str | None context: dict | None
IsAuthorizedRequest
python
nedbat__coveragepy
coverage/types.py
{ "start": 1237, "end": 2231 }
class ____(Protocol): """A simple value type for recording what to do with a file.""" original_filename: str canonical_filename: str source_filename: str | None trace: bool reason: str file_tracer: FileTracer | None has_dynamic_filename: bool # When collecting data, we use a dictionar...
TFileDisposition
python
ray-project__ray
rllib/offline/output_writer.py
{ "start": 124, "end": 461 }
class ____: """Writer API for saving experiences from policy evaluation.""" @PublicAPI def write(self, sample_batch: SampleBatchType): """Saves a batch of experiences. Args: sample_batch: SampleBatch or MultiAgentBatch to save. """ raise NotImplementedError @P...
OutputWriter
python
coleifer__peewee
peewee.py
{ "start": 98006, "end": 98452 }
class ____(object): __slots__ = ('db',) def __init__(self, db): self.db = db def __enter__(self): if self.db.is_closed(): self.db.connect() def __exit__(self, exc_type, exc_val, exc_tb): self.db.close() def __call__(self, fn): @wraps(fn) def inner(*args, **kwargs)...
ConnectionContext
python
ray-project__ray
python/ray/data/_internal/logical/interfaces/source_operator.py
{ "start": 150, "end": 471 }
class ____(ABC): """Mixin for Logical operators that can be logical source nodes. Subclasses: Read, InputData, FromAbstract. """ @abstractmethod def output_data(self) -> Optional[List["RefBundle"]]: """The output data of this operator if already known, or ``None``.""" pass
SourceOperator
python
getsentry__sentry
tests/sentry/api/serializers/test_apitoken.py
{ "start": 2532, "end": 3018 }
class ____(TestApiTokenSerializer): def test_field_is_returned(self) -> None: attrs = self._serializer.get_attrs(item_list=[self._token], user=self._user) attrs["application"] = None serialized_object = self._serializer.serialize( obj=self._token, user=self._user, attrs=attrs ...
TestLastTokenCharacters
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overloadOverride1.py
{ "start": 198, "end": 264 }
class ____: def foo(self, x: int) -> int: return x
Base1
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF023.py
{ "start": 5808, "end": 6131 }
class ____: # This should get flagged, *but* the fix is unsafe, # since the `__slots__` binding is used by the `__match_args__` definition __slots__ = ("foo", "bar") __match_args__ = __slots__ ################################### # These should all not get flagged: ###################################
VeryDRY
python
pytorch__pytorch
test/inductor/test_mmdecomp.py
{ "start": 3017, "end": 9775 }
class ____(NNTestCase): _do_cuda_memory_leak_check = GPU_TYPE == "cuda" _do_cuda_non_default_stream = GPU_TYPE == "cuda" @unittest.skipIf(not HAS_GPU, "GPU tests require triton") @parametrize("dtype", [torch.float, torch.bfloat16]) def test_simple_mm(self, device, dtype): fudge = 10 ...
TestDecomp
python
huggingface__transformers
tests/models/mllama/test_modeling_mllama.py
{ "start": 3916, "end": 4492 }
class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): """ Model tester for `MllamaForConditionalGeneration`. """ all_model_classes = (MllamaForCausalLM,) if is_torch_available() else () def setUp(self): self.model_tester = MllamaText2TextModelTester(self) self.con...
MllamaForCausalLMModelTest
python
plotly__plotly.py
tests/test_core/test_figure_messages/test_on_change.py
{ "start": 115, "end": 8442 }
class ____(TestCase): def setUp(self): # Construct initial scatter object self.figure = go.Figure( data=[ go.Scatter(y=[3, 2, 1], marker={"color": "green"}), go.Bar(y=[3, 2, 1, 0, -1], marker={"opacity": 0.5}), ], layout={"xaxis": {...
TestOnChangeCallbacks
python
fluentpython__example-code
20-descriptor/descriptorkinds.py
{ "start": 4961, "end": 5231 }
class ____: # <1> """a.k.a. data descriptor or enforced descriptor""" def __get__(self, instance, owner): print_args('get', self, instance, owner) # <2> def __set__(self, instance, value): print_args('set', self, instance, value)
Overriding
python
mlflow__mlflow
mlflow/pyfunc/model.py
{ "start": 10712, "end": 12146 }
class ____: """ A collection of artifacts that a :class:`~PythonModel` can use when performing inference. :class:`~PythonModelContext` objects are created *implicitly* by the :func:`save_model() <mlflow.pyfunc.save_model>` and :func:`log_model() <mlflow.pyfunc.log_model>` persistence methods, using ...
PythonModelContext
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/vertex_ai/test_generative_model.py
{ "start": 2025, "end": 3186 }
class ____: @mock.patch(VERTEX_AI_PATH.format("generative_model.GenerativeModelHook")) def test_execute(self, mock_hook): prompt = "In 10 words or less, what is Apache Airflow?" pretrained_model = "textembedding-gecko" with pytest.warns(AirflowProviderDeprecationWarning): op ...
TestVertexAITextEmbeddingModelGetEmbeddingsOperator
python
django-extensions__django-extensions
tests/testapp/jobs/weekly/test_weekly_job.py
{ "start": 122, "end": 229 }
class ____(WeeklyJob): help = "My sample weekly job." def execute(self): WEEKLY_JOB_MOCK()
Job
python
Lightning-AI__lightning
src/lightning/pytorch/loops/fit_loop.py
{ "start": 2370, "end": 24161 }
class ____(_Loop): """This loop is the top-level loop where training starts. It simply counts the epochs and iterates from one to the next by calling ``TrainingEpochLoop.run()`` in its ``advance()`` method. Example:: # FitLoop for epoch in range(max_epochs): # TrainingEpoc...
_FitLoop
python
pyca__cryptography
tests/hazmat/primitives/test_x25519.py
{ "start": 1402, "end": 14997 }
class ____: @pytest.mark.parametrize( "vector", load_vectors_from_file( os.path.join("asymmetric", "X25519", "rfc7748.txt"), load_nist_vectors, ), ) def test_rfc7748(self, vector, backend): private = binascii.unhexlify(vector["input_scalar"]) p...
TestX25519Exchange
python
protocolbuffers__protobuf
upb/cmake/staleness_test.py
{ "start": 2041, "end": 2317 }
class ____(unittest.TestCase): def testFilesMatch(self): errors = staleness_test_lib.CheckFilesMatch(config) self.assertFalse(errors, errors) if len(sys.argv) > 1 and sys.argv[1] == "--fix": staleness_test_lib.FixFiles(config) else: unittest.main()
TestFilesMatch
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_compile.py
{ "start": 1971, "end": 3913 }
class ____(FSDPTest): @unittest.skipIf(not HAS_GPU, "Inductor+gpu needs triton and recent GPU arch") @skip_if_lt_x_gpu(2) def test_disable_compiling_hooks(self): self.run_subtests( { "skip_fsdp_hooks": [False, True], }, self._test_disable_compiling...
TestFullyShardCompileCompute
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 26096, "end": 26346 }
class ____(Structure): _fields_ = (("entryoff", p_uint64), ("stacksize", p_uint64)) def describe(self): s = {} s["entryoff"] = int(self.entryoff) s["stacksize"] = int(self.stacksize) return s
entry_point_command
python
Textualize__textual
src/textual/canvas.py
{ "start": 2248, "end": 3309 }
class ____(Primitive): """A vertical line.""" origin: Offset length: int color: Color line_type: CanvasLineType = "thin" def render(self, canvas: Canvas) -> None: x, y = self.origin if x < 0 or x >= canvas.width: return line_type_index = _LINE_TYPE_INDEX[sel...
VerticalLine
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/context.py
{ "start": 17478, "end": 18488 }
class ____(_AssetRefResolutionMixin): """Wrapper to access an outlet asset event in template.""" key: BaseAssetUniqueKey extra: dict[str, JsonValue] = attrs.Factory(dict) asset_alias_events: list[AssetAliasEvent] = attrs.field(factory=list) def add(self, asset: Asset | AssetRef, extra: dict[str, J...
OutletEventAccessor
python
pytest-dev__pytest
src/_pytest/pytester.py
{ "start": 6015, "end": 6509 }
class ____: def __init__(self, request: FixtureRequest) -> None: self._request = request def gethookrecorder(self, hook) -> HookRecorder: hookrecorder = HookRecorder(hook._pm) self._request.addfinalizer(hookrecorder.finish_recording) return hookrecorder def get_public_names(va...
PytestArg
python
doocs__leetcode
solution/0100-0199/0144.Binary Tree Preorder Traversal/Solution.py
{ "start": 192, "end": 498 }
class ____: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: def dfs(root): if root is None: return ans.append(root.val) dfs(root.left) dfs(root.right) ans = [] dfs(root) return ans
Solution
python
Netflix__metaflow
metaflow/plugins/timeout_decorator.py
{ "start": 239, "end": 310 }
class ____(MetaflowException): headline = "@timeout"
TimeoutException
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 220523, "end": 220862 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("count", "state") count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="count") state = sgqlc.types.Field(sgqlc.types.non_null(CheckRunState), graphql_name="state...
CheckRunStateCount
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 16437, "end": 17798 }
class ____(StatNode): # include_file string or None # verbatim_include string or None # body StatListNode child_attrs = ["body"] def analyse_declarations(self, env): old_cinclude_flag = env.in_cinclude env.in_cinclude = 1 self.body.analyse_declarati...
CDefExternNode
python
python-pillow__Pillow
setup.py
{ "start": 8117, "end": 41479 }
class ____(build_ext): class ext_feature: features = [ "zlib", "jpeg", "tiff", "freetype", "raqm", "lcms", "webp", "jpeg2000", "imagequant", "xcb", "avif", ] r...
pil_build_ext
python
xlwings__xlwings
xlwings/conversion/standard.py
{ "start": 2208, "end": 2964 }
class ____: def __init__(self, options): self.options = options def __call__(self, c): chunksize = self.options.get("chunksize") if c.range and chunksize: parts = [] for i in range(math.ceil(c.range.shape[0] / chunksize)): raw_value = c.range[ ...
ReadValueFromRangeStage
python
pypa__hatch
src/hatch/utils/fs.py
{ "start": 1028, "end": 4377 }
class ____(_PathBase): @cached_property def long_id(self) -> str: from base64 import urlsafe_b64encode from hashlib import sha256 path = str(self) if sys.platform == "win32" or sys.platform == "darwin": path = path.casefold() digest = sha256(path.encode("utf...
Path
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess12.py
{ "start": 155, "end": 515 }
class ____(type): @overload def __get__(self: type[T], instance: None, owner: Any) -> type[T]: ... @overload def __get__(self: type[T], instance: object, owner: Any) -> T: ... def __get__(self: type[T], instance: object | None, owner: Any) -> type[T] | T: if instance is None: r...
MetaClass
python
PyCQA__pylint
pylint/utils/linterstats.py
{ "start": 1233, "end": 1401 }
class ____(TypedDict): """TypedDict to store counts of undocumented node types.""" function: int klass: int method: int module: int
UndocumentedNodes
python
spack__spack
lib/spack/spack/database.py
{ "start": 13355, "end": 19267 }
class ____: """Tracks installation failures. Prefix failure marking takes the form of a byte range lock on the nth byte of a file for coordinating between concurrent parallel build processes and a persistent file, named with the full hash and containing the spec, in a subdirectory of the database t...
FailureTracker
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 991445, "end": 993569 }
class ____(Gradient): """ RadialGradient schema wrapper. Parameters ---------- gradient : Literal['radial'] The type of gradient. Use ``"radial"`` for a radial gradient. stops : Sequence[dict, :class:`GradientStop`] An array of gradient stops defining the gradient color sequence...
RadialGradient
python
huggingface__transformers
src/transformers/models/align/modeling_align.py
{ "start": 29487, "end": 31179 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([AlignTextLayer(config) for i in range(config.num_hidden_layers)]) self.gradient_checkpointing = False @can_return_tuple def forward( self, h...
AlignTextEncoder
python
walkccc__LeetCode
solutions/75. Sort Colors/75.py
{ "start": 0, "end": 415 }
class ____: def sortColors(self, nums: list[int]) -> None: zero = -1 one = -1 two = -1 for num in nums: if num == 0: two += 1 one += 1 zero += 1 nums[two] = 2 nums[one] = 1 nums[zero] = 0 elif num == 1: two += 1 one += 1 ...
Solution
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 253034, "end": 254168 }
class ____(Response): """ Response of tasks.make_private endpoint. :param updated: Number of tasks updated :type updated: int """ _service = "tasks" _action = "make_private" _version = "2.9" _schema = { "definitions": {}, "properties": { "updated": { ...
MakePrivateResponse
python
streamlit__streamlit
lib/streamlit/runtime/media_file_storage.py
{ "start": 892, "end": 1303 }
class ____(Exception): """Exception class for errors raised by MediaFileStorage. When running in "development mode", the full text of these errors is displayed in the frontend, so errors should be human-readable (and actionable). When running in "release mode", errors are redacted on the front...
MediaFileStorageError
python
mlflow__mlflow
mlflow/data/schema.py
{ "start": 176, "end": 2650 }
class ____: """ Represents the schema of a dataset with tensor features and targets. """ def __init__(self, features: Schema, targets: Schema = None): if not isinstance(features, Schema): raise MlflowException( f"features must be mlflow.types.Schema, got '{type(featu...
TensorDatasetSchema
python
arrow-py__arrow
tests/test_locales.py
{ "start": 164485, "end": 167305 }
class ____: def test_describe(self): assert self.locale.describe("now", only_distance=True) == "հիմա" assert self.locale.describe("now", only_distance=False) == "հիմա" def test_meridians_hy(self): assert self.locale.meridian(7, "A") == "Ամ" assert self.locale.meridian(18, "A") =...
TestArmenianLocale
python
ray-project__ray
python/ray/serve/handle.py
{ "start": 20286, "end": 25264 }
class ____(_DeploymentResponseBase): """A future-like object wrapping the result of a streaming deployment handle call. This is returned when using `handle.options(stream=True)` and calling a generator deployment method. `DeploymentResponseGenerator` is both a synchronous and asynchronous iterator. ...
DeploymentResponseGenerator
python
facelessuser__pymdown-extensions
tests/test_extensions/test_highlight.py
{ "start": 20373, "end": 21409 }
class ____(util.MdCase): """Test default block language cases.""" extension = ['pymdownx.highlight', 'pymdownx.superfences', 'pymdownx.inlinehilite'] extension_configs = { 'pymdownx.highlight': { 'default_lang': 'python' } } def test_default_block(self): """Test...
TestDefaultLang
python
kamyu104__LeetCode-Solutions
Python/unique-paths-iii.py
{ "start": 61, "end": 1341 }
class ____(object): def uniquePathsIII(self, grid): """ :type grid: List[List[int]] :rtype: int """ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def index(grid, r, c): return 1 << (r*len(grid[0])+c) def dp(grid, src, dst, todo, lookup)...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/metaclass9.py
{ "start": 1407, "end": 1512 }
class ____(metaclass=Meta2): ... # This should generate an error because param4 is the wrong type.
Class2_4
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1148018, "end": 1148275 }
class ____(VegaLiteSchema): """ScaleInvalidDataShowAstime schema wrapper.""" _schema = {"$ref": '#/definitions/ScaleInvalidDataShowAs<"time">'} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
ScaleInvalidDataShowAstime
python
automl__auto-sklearn
autosklearn/metrics/__init__.py
{ "start": 5977, "end": 23924 }
class ____(Scorer): def __call__( self, y_true: np.ndarray, y_pred: np.ndarray, *, X_data: Optional[SUPPORTED_XDATA_TYPES] = None, sample_weight: Optional[List[float]] = None, ) -> float: """Evaluate decision function output for X relative to y_true. ...
_ThresholdScorer
python
wandb__wandb
wandb/vendor/pygments/lexers/rdf.py
{ "start": 505, "end": 6304 }
class ____(RegexLexer): """ Lexer for `SPARQL <http://www.w3.org/TR/rdf-sparql-query/>`_ query language. .. versionadded:: 2.0 """ name = 'SPARQL' aliases = ['sparql'] filenames = ['*.rq', '*.sparql'] mimetypes = ['application/sparql-query'] # character group definitions :: PN...
SparqlLexer
python
allegroai__clearml
clearml/backend_api/services/v2_20/projects.py
{ "start": 125167, "end": 128989 }
class ____(Request): """ Get user and system tags used for the tasks under the specified projects :param include_system: If set to 'true' then the list of the system tags is also returned. The default value is 'false' :type include_system: bool :param projects: The list of projects under wh...
GetTaskTagsRequest
python
catalyst-team__catalyst
catalyst/loggers/neptune.py
{ "start": 957, "end": 9880 }
class ____(ILogger): """Neptune logger for parameters, metrics, images and other artifacts (videos, audio, model checkpoints, etc.). Neptune documentation: https://docs.neptune.ai/integrations-and-supported-tools/model-training/catalyst When the logger is created, link to the run in Neptune will b...
NeptuneLogger
python
pypa__pipenv
pipenv/vendor/plette/models/base.py
{ "start": 2354, "end": 2972 }
class ____(DataModelCollection): """A sequence of data views. Each entry is an instance of `item_class`. """ @classmethod def validate(cls, data): for d in data: cls.item_class.validate(d) def __iter__(self): return (self.item_class(d) for d in self._data) def...
DataModelSequence
python
getsentry__sentry
src/sentry/integrations/vercel/integration.py
{ "start": 7550, "end": 15338 }
class ____(IntegrationInstallation): @property def metadata(self): return self.model.metadata def get_dynamic_display_information(self): qs = urlencode({"category": "source code management"}) source_code_link = absolute_uri(f"/settings/{self.organization.slug}/integrations/?{qs}") ...
VercelIntegration
python
apache__airflow
airflow-core/src/airflow/configuration.py
{ "start": 2432, "end": 6042 }
class ____: """ Holds modifications to be applied when writing out the config. :param rename: Mapping from (old_section, old_option) to (new_section, new_option) :param remove: Set of (section, option) to remove :param default_updates: Mapping from (section, option) to new default value """ ...
ConfigModifications
python
ray-project__ray
python/ray/_private/thirdparty/dacite/exceptions.py
{ "start": 2028, "end": 2275 }
class ____(DaciteError): def __init__(self, message: str) -> None: super().__init__() self.message = message def __str__(self) -> str: return f"can not resolve forward reference: {self.message}"
ForwardReferenceError
python
optuna__optuna
optuna/exceptions.py
{ "start": 1765, "end": 1943 }
class ____(OptunaError): """Exception for storage operation. This error is raised when an operation failed in backend DB of storage. """ pass
StorageInternalError
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py
{ "start": 1338, "end": 1426 }
class ____(metaclass=abc.ABCMeta): # error def method(self): foo()
abc_Base_2
python
fluentpython__example-code-2e
15-more-types/cafeteria/cafeteria.py
{ "start": 436, "end": 476 }
class ____: """Any garbage."""
Garbage
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 79589, "end": 79972 }
class ____(GeoJsonBaseField): """A GeoJSON field storing a list of Points. The data is represented as: .. code-block:: js {'type' : 'MultiPoint' , 'coordinates' : [[x1, y1], [x2, y2]]} You can either pass a dict with the full information or a list to set the value. Requires...
MultiPointField
python
huggingface__transformers
src/transformers/models/mask2former/modeling_mask2former.py
{ "start": 69140, "end": 75447 }
class ____(nn.Module): """ Multi-headed attention from 'Attention Is All You Need' paper. Here, we add position embeddings to the queries and keys (as explained in the DETR paper). """ def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, ...
Mask2FormerAttention
python
airbytehq__airbyte
airbyte-integrations/connectors/source-s3/source_s3/v4/zip_reader.py
{ "start": 11282, "end": 15390 }
class ____: """ A custom reader class that provides buffered reading capabilities on a decompressed stream. Supports reading lines, reading chunks, and iterating over the content. """ def __init__(self, decompressed_stream: DecompressedStream, encoding: Optional[str] = None, buffer_size: int = BUFF...
ZipContentReader
python
apache__airflow
airflow-core/tests/unit/utils/test_deprecation_tools.py
{ "start": 1692, "end": 10633 }
class ____: """Tests for the getattr_with_deprecation function.""" def test_getattr_with_deprecation_specific_class(self): """Test deprecated import for a specific class.""" imports = {"OldClass": "new.module.NewClass"} # Mock the new module and class mock_module = mock.MagicMo...
TestGetAttrWithDeprecation
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/asyncio/scoping.py
{ "start": 3323, "end": 54154 }
class ____(Generic[_AS]): """Provides scoped management of :class:`.AsyncSession` objects. See the section :ref:`asyncio_scoped_session` for usage details. .. versionadded:: 1.4.19 """ _support_async = True session_factory: async_sessionmaker[_AS] """The `session_factory` provided to `...
async_scoped_session
python
ray-project__ray
python/ray/train/_checkpoint.py
{ "start": 738, "end": 1518 }
class ____(type): def __getattr__(self, item): try: return super().__getattribute__(item) except AttributeError as exc: if item in { "from_dict", "to_dict", "from_bytes", "to_bytes", "get_internal...
_CheckpointMetaClass
python
apache__airflow
providers/apache/livy/tests/unit/apache/livy/triggers/test_livy.py
{ "start": 1142, "end": 9508 }
class ____: def test_livy_trigger_serialization(self): """ Asserts that the TaskStateTrigger correctly serializes its arguments and classpath. """ trigger = LivyTrigger( batch_id=1, spark_params={}, livy_conn_id=LivyHook.default_conn_name, polling_interval=0 ...
TestLivyTrigger
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte_tests/beta/test_translator.py
{ "start": 2514, "end": 3634 }
class ____(DagsterAirbyteTranslator): def get_asset_spec(self, props: AirbyteConnectionTableProps) -> AssetSpec: default_spec = super().get_asset_spec(props) return default_spec.replace_attributes( key=default_spec.key.with_prefix("test_connection"), ).merge_attributes(metadata={...
MyCustomTranslator
python
walkccc__LeetCode
solutions/1883. Minimum Skips to Arrive at Meeting On Time/1883.py
{ "start": 0, "end": 684 }
class ____: def minSkips(self, dist: list[int], speed: int, hoursBefore: int) -> int: INF = 10**7 EPS = 1e-9 n = len(dist) # dp[i][j] := the minimum time, where i is the number of roads we traversed # so far and j is the number of skips we did dp = [[INF] * (n + 1) for _ in range(n + 1)] d...
Solution
python
tornadoweb__tornado
tornado/test/iostream_test.py
{ "start": 47291, "end": 48313 }
class ____(TestReadWriteMixin, AsyncTestCase): @gen.coroutine def make_iostream_pair(self, **kwargs): r, w = os.pipe() return PipeIOStream(r, **kwargs), PipeIOStream(w, **kwargs) @gen_test def test_pipe_iostream(self): rs, ws = yield self.make_iostream_pair() ws.write(...
TestPipeIOStream
python
facelessuser__soupsieve
tests/test_bs4_cases.py
{ "start": 194, "end": 4810 }
class ____(unittest.TestCase): """ Original Beautiful soup test html document. http://bazaar.launchpad.net/~leonardr/beautifulsoup/bs4/view/head:/bs4/tests/test_tree.py, line 1627. """ HTML = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <hea...
SelectorNthOfTypeBugTest