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
bokeh__bokeh
src/bokeh/models/axes.py
{ "start": 9100, "end": 9552 }
class ____(ContinuousAxis): ''' An axis that picks nice numbers for tick locations on a log scale. Configured with a ``LogTickFormatter`` by default. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) ...
LogAxis
python
sqlalchemy__sqlalchemy
test/sql/test_types.py
{ "start": 135462, "end": 144358 }
class ____( fixtures.TablesTest, AssertsExecutionResults, AssertsCompiledSQL ): """test edge cases for booleans. Note that the main boolean test suite is now in testing/suite/test_types.py the default value of create_constraint was changed to False in version 1.4 with #5367. """ __sparse...
BooleanTest
python
tiangolo__fastapi
tests/test_dependency_after_yield_streaming.py
{ "start": 256, "end": 3314 }
class ____: def __init__(self) -> None: self.data = ["foo", "bar", "baz"] self.open = True def __iter__(self) -> Generator[str, None, None]: for item in self.data: if self.open: yield item else: raise ValueError("Session closed") ...
Session
python
Lightning-AI__lightning
tests/tests_pytorch/loops/test_loops.py
{ "start": 25315, "end": 25680 }
class ____(torch.utils.data.Dataset): def __init__(self, size: int, length: int): self.len = length data = torch.arange(0, size) / size self.data = data.unsqueeze(0).repeat(length, 1) def __getitem__(self, index: int) -> torch.Tensor: return self.data[index] def __len__(sel...
RangeDataset
python
gevent__gevent
src/gevent/tests/test__socket_dns.py
{ "start": 34172, "end": 35054 }
class ____(TestCase): @unittest.skipIf(RESOLVER_DNSPYTHON, "dnspython raises an error when multiple results are returned") def test_NUMERICHOST(self): self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), 0) self._test('getnameinfo', (TestGeventOrg.HOSTNAME, 80), socket.N...
Test_getnameinfo_geventorg
python
getsentry__sentry
tests/sentry/utils/test_services.py
{ "start": 655, "end": 5865 }
class ____(Operation): def apply(self, x: int, y: int) -> int: raise Exception("error") @pytest.fixture def delegator_fixture() -> tuple[Delegator, Mock, Mock]: executor = SynchronousExecutor() selector = Mock() callback = Mock() delegator = Delegator( Operation, {"add": (A...
Error
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 6547, "end": 7000 }
class ____(BaseSafeMigrationTest): app = "bad_flow_run_sql_nested_disabled_app" migrate_from = "0001_initial" migrate_to = "0001_initial" def test(self) -> None: with pytest.raises( UnsafeOperationException, match="Using `RunSQL` is unsafe because our migrations safety f...
RunSqlDisabledNestedTest
python
huggingface__transformers
src/transformers/models/idefics/perceiver.py
{ "start": 5122, "end": 8626 }
class ____(nn.Module): def __init__(self, embed_dim: int, n_heads: int, head_dim: int, qk_layer_norms: bool) -> None: """Perceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`""" super().__init__() self.embed_dim, self.n_heads, self.head_dim...
IdeficsPerceiverAttention
python
vyperlang__vyper
vyper/builtins/functions.py
{ "start": 59116, "end": 59376 }
class ____(CreateMinimalProxyTo): def build_IR(self, expr, context): vyper_warn( "`create_forwarder_to` is a deprecated alias of `create_minimal_proxy_to`!", expr ) return super().build_IR(expr, context)
CreateForwarderTo
python
catalyst-team__catalyst
catalyst/contrib/data/transforms.py
{ "start": 2798, "end": 3491 }
class ____(object): """Convert a ``numpy.ndarray`` to tensor. Converts numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] if the numpy.ndarray has dtype = np.uint8 In the other cases, tensors are returned without scaling. """ ...
ImageToTensor
python
run-llama__llama_index
llama-index-packs/llama-index-packs-searchain/llama_index/packs/searchain/base.py
{ "start": 1361, "end": 11501 }
class ____(BaseLlamaPack): """Simple short form SearChain pack.""" def __init__( self, data_path: str, dprtokenizer_path: str = "facebook/dpr-reader-multiset-base", # download from https://huggingface.co/facebook/dpr-reader-multiset-base, dprmodel_path: str = "facebook/dpr-read...
SearChainPack
python
gevent__gevent
src/gevent/_ffi/watcher.py
{ "start": 14873, "end": 15862 }
class ____(object): EVENT_MASK = 0 def __init__(self, loop, fd, events, ref=True, priority=None, _args=None): # Win32 only works with sockets, and only when we use libuv, because # we don't use _open_osfhandle. See libuv/watchers.py:io for a description. self._validate_fd(fd) ...
IoMixin
python
charliermarsh__ruff
crates/ruff_benchmark/resources/pydantic/types.py
{ "start": 2654, "end": 8367 }
class ____(_fields.PydanticMetadata): allow_inf_nan: bool = True def confloat( *, strict: bool | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, multiple_of: float | None = None, allow_inf_nan: bool | None = None, ) -...
AllowInfNan
python
python-openxml__python-docx
tests/opc/test_packuri.py
{ "start": 105, "end": 3313 }
class ____: def cases(self, expected_values): """ Return list of tuples zipped from uri_str cases and `expected_values`. Raise if lengths don't match. """ uri_str_cases = [ "/", "/ppt/presentation.xml", "/ppt/slides/slide1.xml", ] ...
DescribePackURI
python
doocs__leetcode
solution/2900-2999/2902.Count of Sub-Multisets With Bounded Sum/Solution.py
{ "start": 0, "end": 831 }
class ____: def countSubMultisets(self, nums: List[int], l: int, r: int) -> int: kMod = 1_000_000_007 # dp[i] := # of submultisets of nums with sum i dp = [1] + [0] * r count = collections.Counter(nums) zeros = count.pop(0, 0) for num, freq in count.items(): ...
Solution
python
doocs__leetcode
solution/2700-2799/2713.Maximum Strictly Increasing Cells in a Matrix/Solution.py
{ "start": 0, "end": 664 }
class ____: def maxIncreasingCells(self, mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) g = defaultdict(list) for i in range(m): for j in range(n): g[mat[i][j]].append((i, j)) rowMax = [0] * m colMax = [0] * n ans = 0 fo...
Solution
python
PrefectHQ__prefect
src/prefect/client/schemas/schedules.py
{ "start": 6241, "end": 12602 }
class ____(PrefectBaseModel): """ RRule schedule, based on the iCalendar standard ([RFC 5545](https://datatracker.ietf.org/doc/html/rfc5545)) as implemented in `dateutils.rrule`. RRules are appropriate for any kind of calendar-date manipulation, including irregular intervals, repetition, exclus...
RRuleSchedule
python
h5py__h5py
h5py/tests/test_dataset_getitem.py
{ "start": 16309, "end": 17300 }
class ____(TestCase): def setUp(self): TestCase.setUp(self) self.data = np.ones((5,3), dtype='f') self.dset = self.f.create_dataset('x', data=self.data) def test_ndim(self): """ Verify number of dimensions """ self.assertEqual(self.dset.ndim, 2) def test_size(self)...
Test2DFloat
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 538135, "end": 538784 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("PullRequestReviewEdge"), graphql_name="edges" ) nodes = s...
PullRequestReviewConnection
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 12187, "end": 13108 }
class ____(BaseModel): g: GSpec | None = None p: PSpec | None """ ) Filter = module.Filter assert isinstance(Filter(p={'sort': 'some_field:asc', 'fields': []}), Filter) def test_forward_ref_with_create_model(create_module): @create_module def module(): import pydantic ...
Filter
python
tensorflow__tensorflow
tensorflow/python/checkpoint/checkpoint_view.py
{ "start": 1230, "end": 12045 }
class ____(object): """Gathers and serializes a checkpoint view. This is for loading specific portions of a module from a checkpoint, and be able to compare two modules by matching components. Example usage: >>> class SimpleModule(tf.Module): ... def __init__(self, name=None): ... super().__init_...
CheckpointView
python
pytorch__pytorch
test/inductor/test_aot_inductor_arrayref.py
{ "start": 10587, "end": 11581 }
class ____( TestCase ): device = "cpu" device_type = "cpu" check_model = check_model check_model_with_multiple_inputs = check_model_with_multiple_inputs code_check_count = code_check_count allow_stack_allocation = True use_minimal_arrayref_interface = True if IS_FBCODE: # The follo...
AOTInductorTestABICompatibleCpuWithStackAllocationAndMinimalArrayRefInterface
python
apache__airflow
task-sdk/tests/task_sdk/definitions/test_asset_decorators.py
{ "start": 7845, "end": 9934 }
class ____: @mock.patch("airflow.sdk.definitions.asset.decorators._AssetMainOperator.from_definition") @mock.patch("airflow.sdk.definitions.dag.DAG") def test__attrs_post_init__(self, DAG, from_definition, example_asset_func_with_valid_arg_as_inlet_asset): asset_definition = asset(schedule=None, uri...
TestAssetDefinition
python
skorch-dev__skorch
skorch/llm/classifier.py
{ "start": 6351, "end": 9362 }
class ____: """Helper class that caches model generations For label ids, if one token sequence is [1, 2, 3] and the next token sequence is [1, 2, 4], for the 2nd sequence, the generation will retrieve the cached logits for [1, 2] and only generate [4]. Set use_caching=False to disable it, e.g. for...
_CacheModelWrapper
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/dataplex.py
{ "start": 2163, "end": 2351 }
class ____(BaseGoogleLink): """Helper class for constructing Dataplex Task link.""" name = "Dataplex Task" key = "task_conf" format_str = DATAPLEX_TASK_LINK
DataplexTaskLink
python
huggingface__transformers
src/transformers/models/distilbert/modeling_distilbert.py
{ "start": 5817, "end": 8130 }
class ____(nn.Module): def __init__(self, config: PreTrainedConfig): super().__init__() self.config = config self.n_heads = config.n_heads self.dim = config.dim self.attention_head_size = self.dim // self.n_heads self.scaling = self.attention_head_size**-0.5 ...
DistilBertSelfAttention
python
spack__spack
lib/spack/spack/solver/asp.py
{ "start": 52018, "end": 53444 }
class ____(SourceContext): """Tracks context in which a condition (i.e. ``SpackSolverSetup.condition``) is generated (e.g. for a ``depends_on``). This may modify the required/imposed specs generated as relevant for the context. """ def __init__(self): super().__init__() # trans...
ConditionContext
python
pytorch__pytorch
test/distributed/checkpoint/test_hf_safetensor_e2e.py
{ "start": 1131, "end": 9584 }
class ____(TestCase): @with_temp_dir def test_save(self) -> None: try: from safetensors.torch import load_file except ImportError: print("safetensors not installed") return CHECKPOINT_DIR = self.temp_dir state_dict_to_save = MyTestModule().st...
TestSingleRankSaveLoad
python
sphinx-doc__sphinx
sphinx/domains/c/_ast.py
{ "start": 57246, "end": 58057 }
class ____(ASTBase): def __init__(self, name: ASTNestedName) -> None: self.name = name def __eq__(self, other: object) -> bool: if not isinstance(other, ASTStruct): return NotImplemented return self.name == other.name def __hash__(self) -> int: return hash(self....
ASTStruct
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/publish/pipeline.py
{ "start": 1843, "end": 3260 }
class ____(Step): context: PublishConnectorContext title = "Check if the connector docker image does not exist on the registry." async def _run(self) -> StepResult: docker_repository, docker_tag = self.context.docker_image.split(":") crane_ls = ( docker.with_crane( ...
CheckConnectorImageDoesNotExist
python
walkccc__LeetCode
solutions/543. Diameter of Binary Tree/543.py
{ "start": 0, "end": 348 }
class ____: def diameterOfBinaryTree(self, root: TreeNode | None) -> int: ans = 0 def maxDepth(root: TreeNode | None) -> int: nonlocal ans if not root: return 0 l = maxDepth(root.left) r = maxDepth(root.right) ans = max(ans, l + r) return 1 + max(l, r) maxDep...
Solution
python
huggingface__transformers
src/transformers/utils/quantization_config.py
{ "start": 1356, "end": 1827 }
class ____(str, Enum): BITS_AND_BYTES = "bitsandbytes" GPTQ = "gptq" AWQ = "awq" AQLM = "aqlm" VPTQ = "vptq" QUANTO = "quanto" EETQ = "eetq" HIGGS = "higgs" HQQ = "hqq" COMPRESSED_TENSORS = "compressed-tensors" FBGEMM_FP8 = "fbgemm_fp8" TORCHAO = "torchao" BITNET = "b...
QuantizationMethod
python
qdrant__qdrant-client
qdrant_client/local/payload_value_setter.py
{ "start": 5563, "end": 6219 }
class ____(_ListSetter): @classmethod def _set_compatible_types( cls, data: Any, current_key: JsonPathItem, k_list: list[JsonPathItem], value: dict[str, Any], ) -> None: assert current_key.index is not None if current_key.index < len(data): ...
IndexSetter
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_function_base.py
{ "start": 121262, "end": 127426 }
class ____(TestCase): # most of this is already tested by TestPercentile @skip(reason="do not chase 1ulp") def test_max_ulp(self): x = [0.0, 0.2, 0.4] a = np.quantile(x, 0.45) # The default linear method would result in 0 + 0.2 * (0.45/2) = 0.18. # 0.18 is not exactly repres...
TestQuantile
python
huggingface__transformers
src/transformers/models/emu3/modeling_emu3.py
{ "start": 16318, "end": 17161 }
class ____(nn.Module): def __init__( self, in_channel: int, out_channel: int, ): super().__init__() self.conv = Emu3VQVAEConv3d( in_channel, out_channel, kernel_size=(3, 3, 3), stride=(1, 1, 1), ) def forward(se...
Emu3VQVAETemporalUpsample
python
falconry__falcon
tests/test_validators.py
{ "start": 1242, "end": 2268 }
class ____: @validators.jsonschema.validate(req_schema=_TEST_SCHEMA) async def request_validated(self, req, resp): # NOTE(kgriffs): Verify that we can await req.get_media() multiple times for i in range(3): m = await req.get_media() assert m == _VALID_MEDIA asser...
ResourceAsync
python
Lightning-AI__lightning
examples/pytorch/basics/transformer.py
{ "start": 183, "end": 1913 }
class ____(L.LightningModule): def __init__(self, vocab_size): super().__init__() self.model = Transformer(vocab_size=vocab_size) def training_step(self, batch, batch_idx): input, target = batch output = self.model(input, target) loss = F.nll_loss(output, target.view(-1)...
LanguageModel
python
numpy__numpy
numpy/polynomial/tests/test_polynomial.py
{ "start": 15282, "end": 16948 }
class ____: # some random values in [-1, 1) x = np.random.random((3, 5)) * 2 - 1 def test_polyvander(self): # check for 1d x x = np.arange(3) v = poly.polyvander(x, 3) assert_(v.shape == (3, 4)) for i in range(4): coef = [0] * i + [1] assert_a...
TestVander
python
getsentry__sentry
src/sentry/cache/django.py
{ "start": 67, "end": 589 }
class ____(BaseCache): def set(self, key, value, timeout, version=None, raw=False): cache.set(key, value, timeout, version=version or self.version) self._mark_transaction("set") def delete(self, key, version=None): cache.delete(key, version=version or self.version) self._mark_tr...
DjangoCache
python
kubernetes-client__python
kubernetes/client/models/v1_storage_os_volume_source.py
{ "start": 383, "end": 8411 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1StorageOSVolumeSource
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 40966, "end": 41932 }
class ____(PrefectFilterBaseModel): """DEPRECATED: Prefer `Deployment.concurrency_limit_id` over `Deployment.concurrency_limit`.""" ge_: Optional[int] = Field( default=None, description="Only include deployments with a concurrency limit greater than or equal to this value", ) le_: Opti...
DeploymentFilterConcurrencyLimit
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 12140, "end": 15036 }
class ____(SingleContinuousDistribution): _argnames = ('alpha', 'beta', 'lamda') set = Interval(0, 1) @staticmethod def check(alpha, beta, lamda): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") ...
BetaNoncentralDistribution
python
numpy__numpy
numpy/_core/tests/test_arraymethod.py
{ "start": 1113, "end": 2565 }
class ____: # Test mainly error paths of the resolve_descriptors function, # note that the `casting_unittests` tests exercise this non-error paths. # Casting implementations are the main/only current user: method = get_castingimpl(type(np.dtype("d")), type(np.dtype("f"))) @pytest.mark.parametrize(...
TestSimpleStridedCall
python
sanic-org__sanic
sanic/models/futures.py
{ "start": 852, "end": 940 }
class ____(NamedTuple): middleware: MiddlewareType attach_to: str
FutureMiddleware
python
conda__conda
conda/exceptions.py
{ "start": 43224, "end": 44462 }
class ____(CondaError): def __init__( self, filename: str, exporters: Iterable[CondaEnvironmentExporter], *args, **kwargs, ): self.filename = filename supported_filenames: list[str] = [] available_formats: list[str] = [] for exporter in exp...
EnvironmentExporterNotDetected
python
lepture__authlib
authlib/oauth2/rfc9068/claims.py
{ "start": 95, "end": 1981 }
class ____(JWTClaims): REGISTERED_CLAIMS = JWTClaims.REGISTERED_CLAIMS + [ "client_id", "auth_time", "acr", "amr", "scope", "groups", "roles", "entitlements", ] def validate(self, **kwargs): self.validate_typ() super().validat...
JWTAccessTokenClaims
python
keon__algorithms
tests/test_graph.py
{ "start": 5037, "end": 5560 }
class ____(unittest.TestCase): """ Test for the file def maximum_flow_dfs.py Arguments: unittest {[type]} -- [description] """ def test_maximum_flow_dfs(self): graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], ...
TestMaximum_Flow_Dfs
python
altair-viz__altair
tests/utils/test_schemapi.py
{ "start": 3900, "end": 4095 }
class ____(_TestSchema): _schema = { "$schema": _JSON_SCHEMA_DRAFT_URL, "type": "array", "items": {"anyOf": [{"type": "integer"}, {"type": "string"}]}, }
SimpleArray
python
keras-team__keras
keras/src/backend/torch/optimizers/torch_rmsprop.py
{ "start": 147, "end": 2053 }
class ____( torch_parallel_optimizer.TorchParallelOptimizer, optimizers.RMSprop ): def _parallel_update_step( self, grads, variables, learning_rate, ): keras_variables = variables variables = [v.value for v in variables] dtype = variables[0].dtype ...
RMSprop
python
pypa__pip
src/pip/_internal/resolution/resolvelib/candidates.py
{ "start": 12061, "end": 14324 }
class ____(Candidate): is_installed = True source_link = None def __init__( self, dist: BaseDistribution, template: InstallRequirement, factory: Factory, ) -> None: self.dist = dist self._ireq = _make_install_req_from_dist(dist, template) self._fa...
AlreadyInstalledCandidate
python
huggingface__transformers
src/transformers/models/xlm_roberta/modular_xlm_roberta.py
{ "start": 17514, "end": 20001 }
class ____(RobertaForTokenClassification): def __init__(self, config): super().__init__(config) del self.xlm_roberta self.roberta = XLMRobertaModel(config, add_pooling_layer=False) @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.Lo...
XLMRobertaForTokenClassification
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 222135, "end": 222584 }
class ____(sgqlc.types.Input): """Ordering options for deployment connections""" __schema__ = github_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(sgqlc.types.non_null(DeploymentOrderField), graphql_name="field") """The field to order deployments by.""" direction = ...
DeploymentOrder
python
TheAlgorithms__Python
dynamic_programming/floyd_warshall.py
{ "start": 14, "end": 2177 }
class ____: def __init__(self, n=0): # a graph with Node 0,1,...,N-1 self.n = n self.w = [ [math.inf for j in range(n)] for i in range(n) ] # adjacency matrix for weight self.dp = [ [math.inf for j in range(n)] for i in range(n) ] # dp[i][j] stores ...
Graph
python
chroma-core__chroma
chromadb/execution/expression/operator.py
{ "start": 32690, "end": 32880 }
class ____(Rank): """Maximum of multiple ranks""" ranks: List[Rank] def to_dict(self) -> Dict[str, Any]: return {"$max": [r.to_dict() for r in self.ranks]} @dataclass
Max
python
sympy__sympy
sympy/physics/biomechanics/curve.py
{ "start": 877, "end": 2297 }
class ____(Function): """Base class for all musculotendon characteristic curve functions.""" @classmethod def eval(cls): msg = ( f'Cannot directly instantiate {cls.__name__!r}, instances of ' f'characteristic curves must be of a concrete subclass.' ) raise T...
CharacteristicCurveFunction
python
miyuchina__mistletoe
mistletoe/span_token.py
{ "start": 4851, "end": 5591 }
class ____(SpanToken): """ Link token. ("[name](target "title")") This is an inline token. Its children are inline (span) tokens holding the link text. One of the core tokens. Attributes: target (str): link target. title (str): link title (default to empty). label (str): lin...
Link
python
spack__spack
lib/spack/spack/detection/path.py
{ "start": 14435, "end": 15457 }
class ____(Finder): def default_path_hints(self) -> List[str]: return spack.util.environment.get_path("PATH") def search_patterns(self, *, pkg: Type["spack.package_base.PackageBase"]) -> List[str]: result = [] if hasattr(pkg, "executables") and hasattr(pkg, "platform_executables"): ...
ExecutablesFinder
python
celery__celery
t/unit/contrib/test_migrate.py
{ "start": 1524, "end": 3747 }
class ____: @contextmanager def move_context(self, **kwargs): with patch('celery.contrib.migrate.start_filter') as start: with patch('celery.contrib.migrate.republish') as republish: pred = Mock(name='predicate') move(pred, app=self.app, ...
test_move
python
scipy__scipy
scipy/interpolate/tests/test_polyint.py
{ "start": 12734, "end": 20850 }
class ____: def setup_method(self): self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2]) self.test_xs = np.linspace(-1, 1, 100) self.xs = np.linspace(-1, 1, 5) self.ys = self.true_poly(self.xs) def test_lagrange(self): # Ensure backwards compatible post SPEC7 ...
TestBarycentric
python
kamyu104__LeetCode-Solutions
Python/check-if-strings-can-be-made-equal-with-operations-i.py
{ "start": 63, "end": 412 }
class ____(object): def canBeEqual(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ return all(collections.Counter(s1[j] for j in xrange(i, len(s1), 2)) == collections.Counter(s2[j] for j in xrange(i, len(s2), 2)) for i in xrange(2)) # Time: O(1) # S...
Solution
python
ray-project__ray
rllib/offline/estimators/off_policy_estimator.py
{ "start": 705, "end": 10124 }
class ____(OfflineEvaluator): """Interface for an off policy estimator for counterfactual evaluation.""" @DeveloperAPI def __init__( self, policy: Policy, gamma: float = 0.0, epsilon_greedy: float = 0.0, ): """Initializes an OffPolicyEstimator instance. ...
OffPolicyEstimator
python
huggingface__transformers
src/transformers/models/ijepa/modeling_ijepa.py
{ "start": 7567, "end": 9874 }
class ____(nn.Module): def __init__(self, config: IJepaConfig): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size {config.hidden_size} is not a multiple of the number o...
IJepaSelfAttention
python
allegroai__clearml
examples/advanced/execute_remotely_example.py
{ "start": 915, "end": 6495 }
class ____(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5, 1) self.conv2 = nn.Conv2d(20, 50, 5, 1) self.fc1 = nn.Linear(4 * 4 * 50, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): x = F.relu(self.conv1(x)) ...
Net
python
huggingface__transformers
src/transformers/models/mimi/modeling_mimi.py
{ "start": 38498, "end": 42362 }
class ____(MimiAttention): """ Mimi attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from `MimiAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to SDPA API. """ # Adapted from MimiAttention.fo...
MimiSdpaAttention
python
getsentry__sentry
tests/sentry/api/endpoints/test_commit_filechange.py
{ "start": 335, "end": 3672 }
class ____(APITestCase): endpoint = "sentry-api-0-release-commitfilechange" def setUp(self) -> None: super().setUp() self.project = self.create_project(name="foo") self.release = Release.objects.create( organization_id=self.project.organization_id, version="1" ) ...
CommitFileChangeTest
python
django__django
tests/csrf_tests/tests.py
{ "start": 2561, "end": 6790 }
class ____(CsrfFunctionTestMixin, SimpleTestCase): def test_unmask_cipher_token(self): cases = [ (TEST_SECRET, MASKED_TEST_SECRET1), (TEST_SECRET, MASKED_TEST_SECRET2), ( 32 * "a", "vFioG3XOLyGyGsPRFyB9iYUs341ufzIEvFioG3XOLyGyGsPRFyB9iYUs34...
CsrfFunctionTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed3.py
{ "start": 505, "end": 605 }
class ____(ParentClosed1, extra_items=Never): pass # This should generate an error.
ChildClosed1_1
python
pydantic__pydantic
pydantic-core/tests/validators/test_dataclasses.py
{ "start": 60152, "end": 66322 }
class ____: a: str def test_alias_allow_pop(py_and_json: PyAndJson): schema = core_schema.dataclass_schema( BasicDataclass, core_schema.dataclass_args_schema( 'BasicDataclass', [ core_schema.dataclass_field(name='a', schema=core_schema.str_schema(), vali...
BasicDataclass
python
getsentry__sentry
src/sentry/notifications/api/endpoints/user_notification_settings_options_detail.py
{ "start": 534, "end": 1573 }
class ____(UserEndpoint): publish_status = { "DELETE": ApiPublishStatus.PRIVATE, } owner = ApiOwner.ALERTS_NOTIFICATIONS def convert_args( self, request: Request, user_id: int | str | None = None, *args, notification_option_id: int, **kwargs, ...
UserNotificationSettingsOptionsDetailEndpoint
python
pytorch__pytorch
test/quantization/eager/test_quantize_eager_qat.py
{ "start": 9738, "end": 10872 }
class ____(_ReferenceConvBnNd, nn.Conv2d): _FLOAT_MODULE = torch.ao.nn.intrinsic.ConvBn2d def __init__( self, # ConvNd args in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=None, paddi...
_ReferenceConvBn2d
python
walkccc__LeetCode
solutions/2475. Number of Unequal Triplets in Array/2475.py
{ "start": 525, "end": 779 }
class ____: def unequalTriplets(self, nums: list[int]) -> int: ans = 0 prev = 0 next = len(nums) for freq in collections.Counter(nums).values(): next -= freq ans += prev * freq * next prev += freq return ans
Solution
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 30572, "end": 31223 }
class ____(DictDot): def __init__( self, graph: Optional[dict] = None, ): self.graph = graph @override def __repr__(self) -> str: return json.dumps(self.to_json_dict(), indent=2) @override def __str__(self) -> str: return json.dumps(self.to_json_dict(), ...
RenderedAtomicValueGraph
python
django__django
django/forms/fields.py
{ "start": 33018, "end": 34594 }
class ____(ChoiceField): hidden_widget = MultipleHiddenInput widget = SelectMultiple default_error_messages = { "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), "invalid_list": _("Enter a list of values."), } def to_...
MultipleChoiceField
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 16269, "end": 17388 }
class ____(BaseSafeMigrationTest): app = "good_flow_delete_field_simple_app" migrate_from = "0001" migrate_to = "0003" def test(self) -> None: with override_settings( ZERO_DOWNTIME_MIGRATIONS_LOCK_TIMEOUT="5s", ZERO_DOWNTIME_MIGRATIONS_STATEMENT_TIMEOUT="5s", ): ...
DeletionFieldGoodDeleteSimpleLockTimeoutTest
python
RaRe-Technologies__gensim
gensim/models/callbacks.py
{ "start": 22550, "end": 24318 }
class ____: """Base class to build callbacks for :class:`~gensim.models.word2vec.Word2Vec` & subclasses. Callbacks are used to apply custom functions over the model at specific points during training (epoch start, batch end etc.). This is a base class and its purpose is to be inherited by custom Callba...
CallbackAny2Vec
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_from_sparse_op_test.py
{ "start": 1182, "end": 4482 }
class ____(test_util.TensorFlowTestCase): def testDocStringExample(self): st = sparse_tensor.SparseTensor( indices=[[0, 0], [0, 1], [0, 2], [1, 0], [3, 0]], values=[1, 2, 3, 4, 5], dense_shape=[4, 3]) rt = RaggedTensor.from_sparse(st) self.assertAllEqual(rt, [[1, 2, 3], [4], [], ...
RaggedTensorToSparseOpTest
python
pandas-dev__pandas
pandas/tests/extension/test_string.py
{ "start": 3025, "end": 10335 }
class ____(base.ExtensionTests): def test_combine_le(self, data_repeated): dtype = next(iter(data_repeated(2))).dtype if dtype.storage == "pyarrow" and dtype.na_value is pd.NA: self._combine_le_expected_dtype = "bool[pyarrow]" else: self._combine_le_expected_dtype = "...
TestStringArray
python
miyuchina__mistletoe
mistletoe/core_tokens.py
{ "start": 16703, "end": 17339 }
class ____: def __init__(self, start, end, *fields): self._start = start self._end = end self.fields = fields def start(self, n=0): if n == 0: return self._start return self.fields[n - 1][0] def end(self, n=0): if n == 0: return self....
MatchObj
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 756640, "end": 764796 }
class ____( DatumChannelMixin, core.FieldOrDatumDefWithConditionDatumDefnumber ): """ StrokeWidthDatum schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned...
StrokeWidthDatum
python
apache__airflow
providers/odbc/src/airflow/providers/odbc/hooks/odbc.py
{ "start": 1152, "end": 9840 }
class ____(DbApiHook): """ Interact with odbc data sources using pyodbc. To configure driver, in addition to supplying as constructor arg, the following are also supported: * set ``driver`` parameter in ``hook_params`` dictionary when instantiating hook by SQL operators. * set ``driver`` ex...
OdbcHook
python
gevent__gevent
src/greentest/3.9/test_signal.py
{ "start": 14682, "end": 20428 }
class ____(unittest.TestCase): @unittest.skipIf(_testcapi is None, 'need _testcapi') def test_socket(self): # use a subprocess to have only one thread code = """if 1: import signal import socket import struct import _testcapi signum = signal.SIGINT ...
WakeupSocketSignalTests
python
ZoranPandovski__al-go-rithms
data_structures/doubly_linked_list/python/main.py
{ "start": 234, "end": 1583 }
class ____: def __init__(self): self.head = None # the head is being created as soon as the classs is invoked def append(self, data): # insertion or addition of the nodess new_node = Node(data) # creation of the node if self.head is None: # The list is checked wheater it is empty or...
DoubleLinkedList
python
PyCQA__pylint
tests/functional/a/access/access_to_protected_members.py
{ "start": 1501, "end": 3014 }
class ____: """Test for GitHub issue 1802""" def __init__(self, value): self._foo = value self.__private = 2 * value def __eq__(self, other): """Test a correct access as the access to protected member is in a special method""" if isinstance(other, self.__class__): ...
Issue1802
python
pypa__warehouse
tests/unit/helpdesk/test_services.py
{ "start": 1485, "end": 2377 }
class ____: def test_create_service(self): service = ConsoleHelpDeskService.create_service(None, None) assert isinstance(service, ConsoleHelpDeskService) def test_create_conversation(self, capsys): service = ConsoleHelpDeskService() service.create_conversation( requ...
TestConsoleHelpDeskService
python
ray-project__ray
python/ray/data/_internal/cluster_autoscaler/default_cluster_autoscaler.py
{ "start": 547, "end": 4179 }
class ____(ClusterAutoscaler): # Min number of seconds between two autoscaling requests. MIN_GAP_BETWEEN_AUTOSCALING_REQUESTS = 20 def __init__( self, topology: "Topology", resource_manager: "ResourceManager", *, execution_id: str, ): super().__init__(to...
DefaultClusterAutoscaler
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType28.py
{ "start": 702, "end": 737 }
class ____(Generic[T_co]): ...
Class3
python
numba__numba
numba/tests/test_sys_monitoring.py
{ "start": 34693, "end": 35472 }
class ____(TestCase): @TestCase.run_test_in_subprocess( envvars={"NUMBA_ENABLE_SYS_MONITORING": ''}) def test_default_off(self): @jit def foo(x): return x + 1 self.assertFalse(foo._enable_sysmon) @TestCase.run_test_in_subprocess( envvars={"NUMBA_ENABLE_S...
TestMonitoringEnvVarControl
python
PyCQA__pylint
pylint/testutils/_run.py
{ "start": 847, "end": 1430 }
class ____(LintRun): """Like Run, but we're using an explicitly set empty pylintrc. We don't want to use the project's pylintrc during tests, because it means that a change in our config could break tests. But we want to see if the changes to the default break tests. """ def __init__( ...
_Run
python
kamyu104__LeetCode-Solutions
Python/count-nodes-equal-to-average-of-subtree.py
{ "start": 165, "end": 1158 }
class ____(object): def averageOfSubtree(self, root): """ :type root: Optional[TreeNode] :rtype: int """ def iter_dfs(root): result = 0 stk = [(1, (root, [0]*2))] while stk: step, args = stk.pop() if step == ...
Solution
python
pandas-dev__pandas
asv_bench/benchmarks/rolling.py
{ "start": 6754, "end": 7384 }
class ____: params = ( ["DataFrame", "Series"], [10, 1000], ["int", "float"], [0, 0.5, 1], ["linear", "nearest", "lower", "higher", "midpoint"], ) param_names = ["constructor", "window", "dtype", "percentile"] def setup(self, constructor, window, dtype, percentil...
Quantile
python
getsentry__sentry
src/sentry/models/dashboard.py
{ "start": 6940, "end": 8127 }
class ____(DefaultFieldsModel): __relocation_scope__ = RelocationScope.Organization user_id = HybridCloudForeignKey("sentry.User", on_delete="CASCADE") organization = FlexibleForeignKey("sentry.Organization") dashboard = FlexibleForeignKey("sentry.Dashboard", on_delete=models.CASCADE) position = m...
DashboardFavoriteUser
python
apache__airflow
airflow-core/tests/unit/core/test_example_dags_system.py
{ "start": 2534, "end": 4909 }
class ____(SystemTest): @pytest.mark.parametrize( "module", ["example_bash_operator", "example_branch_operator", "tutorial_dag", "example_dag_decorator"], ) def test_dag_example(self, module): test_run = import_string(f"airflow.example_dags.{module}.test_run") test_run() ...
TestExampleDagsSystem
python
walkccc__LeetCode
solutions/935. Knight Dialer/935.py
{ "start": 0, "end": 806 }
class ____: def knightDialer(self, n: int) -> int: DIRS = ((1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)) MOD = 1_000_000_007 # dp[i][j] := the number of ways stand on (i, j) dp = [[1] * 3 for _ in range(4)] dp[3][0] = dp[3][2] = 0 for _ in range(n - 1): ...
Solution
python
pypa__virtualenv
tasks/make_zipapp.py
{ "start": 11545, "end": 11844 }
class ____: def __init__(self, wheel=None, versions=None) -> None: self.wheel = wheel self.versions = versions or [] def __repr__(self) -> str: return f"{self.__class__.__name__}({self.wheel!r}, {self.versions!r})" if __name__ == "__main__": main()
WheelForVersion
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-hire-k-workers.py
{ "start": 67, "end": 672 }
class ____(object): def mincostToHireWorkers(self, quality, wage, K): """ :type quality: List[int] :type wage: List[int] :type K: int :rtype: float """ result, qsum = float("inf"), 0 max_heap = [] for r, q in sorted([float(w)/q, q] for w, q in ...
Solution
python
facelessuser__pymdown-extensions
pymdownx/__meta__.py
{ "start": 820, "end": 6788 }
class ____(namedtuple("Version", ["major", "minor", "micro", "release", "pre", "post", "dev"])): """ Get the version (PEP 440). A biased approach to the PEP 440 semantic version. Provides a tuple structure which is sorted for comparisons `v1 > v2` etc. (major, minor, micro, release type, pre-rel...
Version
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/utils.py
{ "start": 3144, "end": 3597 }
class ____(AirbyteTracedException): """Raises the error when Shopify resources couldn't be accessed because of the ConnectionError occured (100-x)""" def __init__(self, details, **kwargs) -> None: self.message = f"Invalid `Shopify Store` name used or `host` couldn't be verified by Shopify. Details: {de...
ShopifyConnectionError
python
buildout__buildout
src/zc/buildout/configparser.py
{ "start": 1010, "end": 1842 }
class ____(Exception): """Base class for ConfigParser exceptions.""" def _get_message(self): """Getter for 'message'; needed only to override deprecation in BaseException.""" return self.__message def _set_message(self, value): """Setter for 'message'; needed only to overri...
Error
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dlp.py
{ "start": 68516, "end": 72303 }
class ____(GoogleCloudBaseOperator): """ Finds potentially sensitive info in content; limits input size, processing time, and output size. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDLPInspectContentOperator` :para...
CloudDLPInspectContentOperator
python
pypa__build
src/build/_exceptions.py
{ "start": 876, "end": 1151 }
class ____(BuildException): """ Exception raised when the ``[build-system]`` table in pyproject.toml is invalid. """ def __str__(self) -> str: return f'Failed to validate `build-system` in pyproject.toml: {self.args[0]}'
BuildSystemTableValidationError