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
etianen__django-reversion
tests/test_app/tests/test_views.py
{ "start": 109, "end": 487 }
class ____(TestModelMixin, TestBase): def testCreateRevision(self): response = self.client.post("/test-app/create-revision/") obj = TestModel.objects.get(pk=response.content) self.assertSingleRevision((obj,)) def testCreateRevisionGet(self): self.client.get("/test-app/create-re...
CreateRevisionTest
python
ApeWorX__ape
tests/functional/test_plugins.py
{ "start": 2949, "end": 3552 }
class ____: def test_from_package_names(self, plugin_metadata): actual = plugin_metadata assert actual.core.plugin_names == list(CORE_PLUGINS) assert actual.third_party.plugin_names == list(THIRD_PARTY) assert actual.installed.plugin_names == [INSTALLED_PLUGINS[0]] # Not 3rd party ...
TestPluginMetadataList
python
jmcnamara__XlsxWriter
xlsxwriter/test/styles/test_write_dxfs.py
{ "start": 295, "end": 740 }
class ____(unittest.TestCase): """ Test the Styles _write_dxfs() method. """ def setUp(self): self.fh = StringIO() self.styles = Styles() self.styles._set_filehandle(self.fh) def test_write_dxfs(self): """Test the _write_dxfs() method""" self.styles._write...
TestWriteDxfs
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_sql.py
{ "start": 20095, "end": 22175 }
class ____(CloudSQLBaseOperator): """ Delete a Cloud SQL instance. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudSQLDeleteInstanceOperator` :param instance: Cloud SQL instance ID. This does not include the project ID....
CloudSQLDeleteInstanceOperator
python
Lightning-AI__lightning
examples/fabric/dcgan/train_fabric.py
{ "start": 6948, "end": 8011 }
class ____(nn.Module): def __init__(self): super().__init__() self.main = nn.Sequential( # input is Z, going into a convolution nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(ngf * 8), nn.ReLU(True), # state size. (ngf...
Generator
python
coleifer__peewee
tests/dataset.py
{ "start": 451, "end": 518 }
class ____(TestModel): username = TextField(primary_key=True)
User
python
doocs__leetcode
solution/3600-3699/3672.Sum of Weighted Modes in Subarrays/Solution.py
{ "start": 0, "end": 690 }
class ____: def modeWeight(self, nums: List[int], k: int) -> int: pq = [] cnt = defaultdict(int) for x in nums[:k]: cnt[x] += 1 heappush(pq, (-cnt[x], x)) def get_mode() -> int: while -pq[0][0] != cnt[pq[0][1]]: heappop(pq) ...
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/interfaces.py
{ "start": 4388, "end": 4517 }
class ____(ORMColumnsClauseRole[_T]): __slots__ = () _role_name = "ORM mapped or aliased entity"
ORMEntityColumnsClauseRole
python
pypa__pip
src/pip/_internal/index/collector.py
{ "start": 2411, "end": 6005 }
class ____(Exception): pass def _ensure_api_response(url: str, session: PipSession) -> None: """ Send a HEAD request to the URL, and ensure the response contains a simple API Response. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotAPIContent` if the content type is...
_NotHTTP
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/asyncpg.py
{ "start": 10105, "end": 10309 }
class ____(INTERVAL): render_bind_cast = True @classmethod def adapt_emulated_to_native(cls, interval, **kw): return AsyncPgInterval(precision=interval.second_precision)
AsyncPgInterval
python
urllib3__urllib3
src/urllib3/contrib/emscripten/fetch.py
{ "start": 2900, "end": 3071 }
class ____(_RequestError): pass def _obj_from_dict(dict_val: dict[str, Any]) -> JsProxy: return to_js(dict_val, dict_converter=js.Object.fromEntries)
_TimeoutError
python
sympy__sympy
sympy/stats/matrix_distributions.py
{ "start": 7087, "end": 8806 }
class ____(Distribution, NamedArgsMixin): """ Abstract class for Matrix Distribution. """ def __new__(cls, *args): args = [ImmutableMatrix(arg) if isinstance(arg, list) else _sympify(arg) for arg in args] return Basic.__new__(cls, *args) @staticmethod def check(*...
MatrixDistribution
python
PyCQA__pylint
tests/functional/n/not_async_context_manager.py
{ "start": 425, "end": 511 }
class ____: def __aexit__(self, *args): pass
SecondPartialAsyncContextManager
python
pyca__cryptography
tests/hazmat/primitives/decrepit/test_algorithms.py
{ "start": 4194, "end": 4672 }
class ____: test_ofb = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "Blowfish"), ["bf-ofb.txt"], lambda key, **kwargs: Blowfish(binascii.unhexlify(key)), lambda iv, **kwargs: OFB(binascii.unhexlify(iv)), ) @pytest.mark.supported( only_if=lambda ...
TestBlowfishModeOFB
python
ray-project__ray
python/ray/tune/tests/_test_trial_runner_pg.py
{ "start": 9392, "end": 11882 }
class ____(unittest.TestCase): def tearDown(self) -> None: if ray.is_initialized: ray.shutdown() def testResourceDeadlock(self): """Tests that resource deadlock is avoided for heterogeneous PGFs. We start 4 trials in a cluster with 2 CPUs. The first two trials requi...
TrialRunnerPlacementGroupHeterogeneousTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1534290, "end": 1535064 }
class ____(sgqlc.types.Type, Node): """Represents a 'transferred' event on a given issue or pull request.""" __schema__ = github_schema __field_names__ = ("actor", "created_at", "from_repository", "issue") actor = sgqlc.types.Field(Actor, graphql_name="actor") """Identifies the actor who performed ...
TransferredEvent
python
getsentry__sentry
tests/sentry/integrations/test_client.py
{ "start": 576, "end": 13824 }
class ____(TestCase): @responses.activate def test_get(self) -> None: responses.add(responses.GET, "http://example.com", json={}) resp = ApiClient().get("http://example.com") assert isinstance(resp, BaseApiResponse) assert resp.status_code == 200 @responses.activate def...
ApiClientTest
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-qdrant/llama_index/readers/qdrant/base.py
{ "start": 169, "end": 6913 }
class ____(BaseReader): """ Qdrant reader. Retrieve documents from existing Qdrant collections. Args: location: If `:memory:` - use in-memory Qdrant instance. If `str` - use it as a `url` parameter. If `None` - use default values for `host` and `port`. ...
QdrantReader
python
cython__cython
Cython/Shadow.py
{ "start": 11226, "end": 11949 }
class ____(ArrayType): # Implemented as class to support both 'array(int, 5)' and 'array[int, 5]'. def __new__(cls, basetype, n): class ArrayInstance(ArrayType): _basetype = basetype _n = n return ArrayInstance def __class_getitem__(cls, item): basetype, n = ...
array
python
cython__cython
Demos/benchmarks/bm_async_generators.py
{ "start": 240, "end": 1354 }
class ____: def __init__(self, left: Tree | None, value: int, right: Tree | None) -> None: self.left = left self.value = value self.right = right async def __aiter__(self) -> AsyncIterator[int]: if self.left: async for i in self.left: yield i ...
Tree
python
tensorflow__tensorflow
tensorflow/python/ops/nccl_ops_test.py
{ "start": 5267, "end": 5538 }
class ____(NcclTestCase): def testSum(self): self._Test(partial(_NcclReduce, nccl_ops.reduce_sum), lambda x, y: x + y) def testSumGrad(self): self._TestGradient(partial(_NcclReduce, nccl_ops.reduce_sum), lambda x, y: x)
SingleReduceTest
python
davidhalter__jedi
test/completion/recursion.py
{ "start": 609, "end": 801 }
class ____(): def __init__(self): self.recursive = [1] def annoying(self): self.recursive = [x for x in self.recursive] #? int() FooListComp().recursive[0]
FooListComp
python
scrapy__scrapy
tests/test_utils_datatypes.py
{ "start": 8353, "end": 9000 }
class ____: def test_cache_with_limit(self): cache = LocalCache(limit=2) cache["a"] = 1 cache["b"] = 2 cache["c"] = 3 assert len(cache) == 2 assert "a" not in cache assert "b" in cache assert "c" in cache assert cache["b"] == 2 assert c...
TestLocalCache
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 12122, "end": 12187 }
class ____(Spec): p: PSpec | None # PSpec.model_rebuild()
GSpec
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws/s3/compute_log_manager.py
{ "start": 905, "end": 12451 }
class ____(TruncatingCloudStorageComputeLogManager, ConfigurableClass): """Logs compute function stdout and stderr to S3. Users should not instantiate this class directly. Instead, use a YAML block in ``dagster.yaml`` such as the following: .. code-block:: YAML compute_logs: module:...
S3ComputeLogManager
python
openai__openai-python
src/openai/types/batch_request_counts.py
{ "start": 155, "end": 408 }
class ____(BaseModel): completed: int """Number of requests that have been completed successfully.""" failed: int """Number of requests that have failed.""" total: int """Total number of requests in the batch."""
BatchRequestCounts
python
PyCQA__pylint
tests/functional/i/invalid/invalid_index_returned.py
{ "start": 194, "end": 302 }
class ____: """__index__ returns <type 'int'>""" def __index__(self): return 1
FirstGoodIndex
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 186962, "end": 187467 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("ref_id", "oid", "force", "client_mutation_id") ref_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="refId") oid = sgqlc.types.Field(sgqlc.types.non_null(GitObj...
UpdateRefInput
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/paramSpec24.py
{ "start": 582, "end": 804 }
class ____(Protocol[P, T]): foo: int = 0 val: T def __init__(self, val: T) -> None: self.val = val def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: return self.val
_callable_cache
python
getsentry__sentry
src/sentry/migrations/0996_add_dashboard_field_link_model.py
{ "start": 269, "end": 2678 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
scipy__scipy
scipy/io/matlab/_miobase.py
{ "start": 356, "end": 434 }
class ____(Exception): """Exception indicating a read issue."""
MatReadError
python
kamyu104__LeetCode-Solutions
Python/longest-substring-of-one-repeating-character.py
{ "start": 3755, "end": 5110 }
class ____(object): def longestRepeating(self, s, queryCharacters, queryIndices): """ :type s: str :type queryCharacters: str :type queryIndices: List[int] :rtype: List[int] """ LEFT, RIGHT, LEFT_LEN, RIGHT_LEN, LEN, MAX_LEN, SIZE = xrange(7) def build...
Solution2
python
huggingface__transformers
src/transformers/models/esm/modeling_esmfold.py
{ "start": 40215, "end": 40831 }
class ____(nn.Module): def __init__(self, pairwise_state_dim, num_heads): super().__init__() self.layernorm = nn.LayerNorm(pairwise_state_dim) self.linear = nn.Linear(pairwise_state_dim, num_heads, bias=False) def forward(self, pairwise_state): """ Inputs: pai...
EsmFoldPairToSequence
python
Netflix__metaflow
metaflow/plugins/argo/argo_workflows_deployer.py
{ "start": 212, "end": 4444 }
class ____(DeployerImpl): """ Deployer implementation for Argo Workflows. Parameters ---------- name : str, optional, default None Argo workflow name. The flow name is used instead if this option is not specified. """ TYPE: ClassVar[Optional[str]] = "argo-workflows" def __init...
ArgoWorkflowsDeployer
python
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/95_annotation_class_no_value.py
{ "start": 0, "end": 23 }
class ____(): z: int
F
python
davidhalter__jedi
sith.py
{ "start": 2224, "end": 7351 }
class ____(object): def __init__(self, operation, path, line, column, traceback=None): if operation not in self.operations: raise ValueError("%s is not a valid operation" % operation) # Set other attributes self.operation = operation self.path = path self.line = ...
TestCase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/generator10.py
{ "start": 171, "end": 384 }
class ____(Awaitable): def __await__(self): yield from (sleep(0.1).__await__()) async def func1(): x: None = await MyAwaitable() loop = get_event_loop() loop.run_until_complete(func1())
MyAwaitable
python
pytorch__pytorch
test/distributed/checkpoint/test_utils.py
{ "start": 2162, "end": 4920 }
class ____(TestCase): def test_init_convert_offset(self): a = MetadataIndex("foo", [1, 2]) b = MetadataIndex("foo", torch.Size([1, 2])) self.assertEqual(a, b) def test_index_hint_ignored_on_equals(self): a = MetadataIndex("foo") b = MetadataIndex("foo", index=99) ...
TestMedatadaIndex
python
django__django
tests/filtered_relation/models.py
{ "start": 1357, "end": 1445 }
class ____(models.Model): name = models.CharField(max_length=50, unique=True)
Borrower
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_object_position07.py
{ "start": 315, "end": 933 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("object_position07.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook =...
TestCompareXLSXFiles
python
pydantic__pydantic
tests/mypy/modules/final_with_default.py
{ "start": 137, "end": 193 }
class ____(BaseModel): f: Final[int] = 1 Model()
Model
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_ignore_params.py
{ "start": 2232, "end": 6223 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() q = torch.randn(10, device=device_type) self.q = nn.Parameter(q) self.y = Y() def _append_prefix(prefix: str, name: str) -> str: if prefix != "" and name != "": return prefix + "." + name else: ...
X
python
numba__llvmlite
llvmlite/ir/types.py
{ "start": 5846, "end": 6282 }
class ____(Type): """ The type for empty values (e.g. a function returning no value). """ def _to_string(self): return 'void' def __eq__(self, other): return isinstance(other, VoidType) def __hash__(self): return hash(VoidType) @classmethod def from_llvm(cls, ...
VoidType
python
scikit-learn__scikit-learn
sklearn/feature_selection/_univariate_selection.py
{ "start": 20928, "end": 24522 }
class ____(_BaseFilter): """Select features according to a percentile of the highest scores. Read more in the :ref:`User Guide <univariate_feature_selection>`. Parameters ---------- score_func : callable, default=f_classif Function taking two arrays X and y, and returning a pair of arrays ...
SelectPercentile
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/random/parameterized_truncated_normal_op_test.py
{ "start": 18808, "end": 20601 }
class ____(test.Benchmark): def benchmarkParameterizedOpVsNaiveOpCpu(self): self._benchmarkParameterizedOpVsNaiveOp(False) def benchmarkParameterizedOpVsNaiveOpGpu(self): self._benchmarkParameterizedOpVsNaiveOp(True) def _benchmarkParameterizedOpVsNaiveOp(self, use_gpu): num_iters = 50 print(("...
TruncatedNormalBenchmark
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 10274, "end": 10790 }
class ____: def setup_method(self): class TestSerializer(serializers.Serializer): initial_field = serializers.IntegerField(initial=123) blank_field = serializers.IntegerField() self.serializer = TestSerializer() def test_initial(self): """ Initial values ...
TestInitial
python
doocs__leetcode
lcp/LCP 56. 信物传送/Solution.py
{ "start": 0, "end": 876 }
class ____: def conveyorBelt(self, matrix: List[str], start: List[int], end: List[int]) -> int: dirs = (-1, 0, 1, 0, -1) d = {"^": 0, "v": 2, "<": 3, ">": 1} i, j = start q = deque([(i, j)]) m, n = len(matrix), len(matrix[0]) dist = [[inf] * n for _ in range(m)] ...
Solution
python
facelessuser__pymdown-extensions
tests/test_extensions/test_blocks/test_captions.py
{ "start": 20446, "end": 36635 }
class ____(util.MdCase): """Test Blocks caption cases with enabled `auto`.""" extension = ['pymdownx.blocks.caption', 'md_in_html'] extension_configs = { 'pymdownx.blocks.caption': { } } def test_caption_number_and_id(self): """Test captions with IDs and number.""" ...
TestBlocksCaptionAutoPrefix
python
PrefectHQ__prefect
src/prefect/server/schemas/core.py
{ "start": 2487, "end": 3836 }
class ____(PrefectBaseModel): """Defines of how a flow run should retry.""" max_retries: int = Field( default=0, description=( "The maximum number of retries. Field is not used. Please use `retries`" " instead." ), deprecated=True, ) retry_delay_s...
FlowRunPolicy
python
prabhupant__python-ds
data_structures/binary_trees/print_full_nodes.py
{ "start": 105, "end": 552 }
class ____: def __init__(self, val): self.val = val self.right = None self.left = None def print_full(root): if not root: return if root.left and root.right: print(root.val, end=' ') print_full(root.left) print_full(root.right) root = Node(10) root.left =...
Node
python
getsentry__sentry
src/sentry/integrations/jira_server/client.py
{ "start": 8903, "end": 13503 }
class ____(ApiClient): """ Client for making requests to JiraServer to follow OAuth1 flow. Jira OAuth1 docs: https://developer.atlassian.com/server/jira/platform/oauth/ """ request_token_url = "{}/plugins/servlet/oauth/request-token" access_token_url = "{}/plugins/servlet/oauth/access-token" ...
JiraServerSetupClient
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_v3.py
{ "start": 3951, "end": 5819 }
class ____(control_flow_ops.ControlFlowContext): """Sets the _embedding_pipelining attribute on all ops created in the scope.""" def __init__(self, mode: str, enable: bool): super().__init__() self._name = "EmbeddingPipelinigContext" self._mode = attr_value_pb2.AttrValue(s=compat.as_bytes(mode)) se...
EmbeddingPipeliningContext
python
joke2k__faker
faker/providers/phone_number/bs_BA/__init__.py
{ "start": 49, "end": 879 }
class ____(PhoneNumberProvider): formats = ( "030 ### ###", "031 ### ###", "032 ### ###", "033 ### ###", "034 ### ###", "035 ### ###", "036 ### ###", "037 ### ###", "038 ### ###", "039 ### ###", "049 ### ###", "050 ### #...
Provider
python
huggingface__transformers
tests/cli/test_serve.py
{ "start": 26803, "end": 30722 }
class ____(ServeCompletionsMixin, unittest.TestCase): """Tests the `continuous_batching` version of the Completions API.""" @classmethod def setUpClass(cls): """Starts a server for tests to connect to.""" cls.port = 8002 cls.server = Serve( port=cls.port, continuous_batc...
ServeCompletionsContinuousBatchingIntegrationTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 62916, "end": 63639 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("title", "summary", "text", "annotations", "images") title = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="title") summary = sgqlc.types.Field(sgqlc.types.non...
CheckRunOutput
python
wandb__wandb
wandb/vendor/promise-2.3.0/tests/test_extra.py
{ "start": 646, "end": 905 }
class ____(Thread): def __init__(self, d, p, r): self.delay = d self.promise = p self.reason = r Thread.__init__(self) def run(self): sleep(self.delay) self.promise.do_reject(self.reason)
DelayedRejection
python
django-extensions__django-extensions
tests/test_logging_filters.py
{ "start": 219, "end": 2636 }
class ____(TestCase): """Tests for RateLimiterFilter.""" def setUp(self): self.rate_limiter_filter = RateLimiterFilter() self.record = mock.Mock(msg=TEST_SUBJECT) self.record.getMessage.return_value = TEST_SUBJECT.encode() self.time_patch = mock.patch.object(time, "time", return...
RateLimiterFilterTests
python
matplotlib__matplotlib
lib/matplotlib/sphinxext/roles.py
{ "start": 1467, "end": 4912 }
class ____(nodes.Inline, nodes.TextElement): """ Wraps a reference or pending reference to add a query string. The query string is generated from the attributes added to this node. Also equivalent to a `~docutils.nodes.literal` node. """ def to_query_string(self): """Generate query st...
_QueryReference
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py
{ "start": 18316, "end": 20098 }
class ____(Qwen3Config): def __init__( self, vocab_size: Optional[int] = 2048, hidden_size: Optional[int] = 1024, intermediate_size: Optional[int] = 3072, num_hidden_layers: Optional[int] = 5, num_attention_heads: Optional[int] = 16, num_key_value_heads: Optio...
Qwen3OmniMoeTalkerCodePredictorConfig
python
pytorch__pytorch
torch/mtia/__init__.py
{ "start": 8813, "end": 9449 }
class ____: r"""Context-manager that changes the selected device. Args: device (torch.device or int): device index to select. It's a no-op if this argument is a negative integer or ``None``. """ def __init__(self, device: Any): self.idx = _get_device_index(device, optional=...
device
python
pdm-project__pdm
src/pdm/cli/commands/python.py
{ "start": 677, "end": 1537 }
class ____(BaseCommand): """Manage installed Python interpreters""" arguments = () def add_arguments(self, parser: ArgumentParser) -> None: self.parser = parser subparsers = parser.add_subparsers(title="commands", metavar="") ListCommand.register_to(subparsers, name="list") ...
Command
python
ray-project__ray
python/ray/train/v2/_internal/execution/worker_group/poll.py
{ "start": 1269, "end": 3866 }
class ____: worker_statuses: Dict[int, WorkerStatus] @property def errors(self) -> Dict[int, Exception]: return { world_rank: status.error for world_rank, status in self.worker_statuses.items() if status.error is not None } def get_worker_group_error...
WorkerGroupPollStatus
python
rapidsai__cudf
python/cudf/cudf/pandas/_logger.py
{ "start": 331, "end": 2681 }
class ____: # https://docs.python.org/3/howto/logging-cookbook.html#implementing-structured-logging def __init__(self, debug_type: str, /, **kwargs) -> None: self.debug_type = debug_type self.kwargs = kwargs def __str__(self) -> str: log = {"debug_type": self.debug_type} ret...
StructuredMessage
python
django__django
tests/staticfiles_tests/test_liveserver.py
{ "start": 886, "end": 2019 }
class ____(LiveServerBase): @classmethod def setUpClass(cls): # If contrib.staticfiles isn't configured properly, the exception # should bubble up to the main thread. old_STATIC_URL = TEST_SETTINGS["STATIC_URL"] TEST_SETTINGS["STATIC_URL"] = None try: cls.rais...
StaticLiveServerChecks
python
allegroai__clearml
clearml/backend_api/services/v2_9/queues.py
{ "start": 14098, "end": 15236 }
class ____(Response): """ Response of queues.add_task endpoint. :param added: Number of tasks added (0 or 1) :type added: int """ _service = "queues" _action = "add_task" _version = "2.9" _schema = { "definitions": {}, "properties": { "added": { ...
AddTaskResponse
python
kamyu104__LeetCode-Solutions
Python/maximize-subarray-sum-after-removing-all-occurrences-of-one-element.py
{ "start": 639, "end": 1221 }
class ____(object): def maxSubarraySum(self, nums): """ :type nums: List[int] :rtype: int """ result = float("-inf") curr = mn = mn0 = 0 mn1 = collections.defaultdict(int) for x in nums: curr += x result = max(result, curr-mn) ...
Solution2
python
gevent__gevent
src/gevent/baseserver.py
{ "start": 1241, "end": 16716 }
class ____(object): """ An abstract base class that implements some common functionality for the servers in gevent. :param listener: Either be an address that the server should bind on or a :class:`gevent.socket.socket` instance that is already bound (and put into listening mode in case of ...
BaseServer
python
getsentry__sentry
tests/sentry/sentry_apps/external_requests/test_issue_link_requester.py
{ "start": 896, "end": 10253 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.user = self.create_user(name="foo") self.org = self.create_organization(owner=self.user) self.project = self.create_project(slug="boop", organization=self.org) self.group = self.create_group(project=self.pro...
TestIssueLinkRequester
python
pypa__warehouse
warehouse/accounts/models.py
{ "start": 13598, "end": 14235 }
class ____(db.Model): __tablename__ = "prohibited_email_domains" __repr__ = make_repr("domain") created: Mapped[datetime_now] domain: Mapped[str] = mapped_column(unique=True) is_mx_record: Mapped[bool_false] = mapped_column( comment="Prohibit any domains that have this domain as an MX recor...
ProhibitedEmailDomain
python
getsentry__sentry
src/sentry/migrations/0998_add_prebuilt_id_to_dashboards.py
{ "start": 250, "end": 2644 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
ray-project__ray
python/ray/autoscaler/_private/node_provider_availability_tracker.py
{ "start": 383, "end": 573 }
class ____: node_type: str is_available: bool last_checked_timestamp: float unavailable_node_information: Optional[UnavailableNodeInformation] @dataclass
NodeAvailabilityRecord
python
vyperlang__vyper
vyper/semantics/types/primitives.py
{ "start": 10549, "end": 12212 }
class ____(NumericT): typeclass = "decimal" _bits = 168 # TODO generalize _decimal_places = 10 # TODO generalize _id = "decimal" _is_signed = True _invalid_ops = ( vy_ast.Pow, vy_ast.FloorDiv, vy_ast.BitAnd, vy_ast.BitOr, vy_ast.BitXor, vy_ast.N...
DecimalT
python
pytorch__pytorch
torch/utils/data/datapipes/iter/selecting.py
{ "start": 569, "end": 3308 }
class ____(IterDataPipe[_T_co]): r""" Filters out elements from the source datapipe according to input ``filter_fn`` (functional name: ``filter``). Args: datapipe: Iterable DataPipe being filtered filter_fn: Customized function mapping an element to a boolean. input_col: Index or in...
FilterIterDataPipe
python
graphql-python__graphene
graphene/types/tests/test_decimal.py
{ "start": 112, "end": 2165 }
class ____(ObjectType): decimal = Decimal(input=Decimal()) def resolve_decimal(self, info, input): return input schema = Schema(query=Query) def test_decimal_string_query(): decimal_value = decimal.Decimal("1969.1974") result = schema.execute("""{ decimal(input: "%s") }""" % decimal_value) ...
Query
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_alloy_db.py
{ "start": 82370, "end": 88047 }
class ____: def setup_method(self): self.operator = AlloyDBUpdateBackupOperator( task_id=TEST_TASK_ID, backup_id=TEST_BACKUP_ID, backup_configuration=TEST_BACKUP, update_mask=TEST_UPDATE_MASK, allow_missing=TEST_ALLOW_MISSING, project_i...
TestAlloyDBUpdateBackupOperator
python
pypa__hatch
src/hatch/publish/plugin/interface.py
{ "start": 74, "end": 3353 }
class ____(ABC): """ Example usage: ```python tab="plugin.py" from hatch.publish.plugin.interface import PublisherInterface class SpecialPublisher(PublisherInterface): PLUGIN_NAME = 'special' ... ``` ```python tab="hooks.py" from hatchling.plugin i...
PublisherInterface
python
nedbat__coveragepy
coverage/plugin_support.py
{ "start": 7025, "end": 8458 }
class ____(FileTracer): """A debugging `FileTracer`.""" def __init__(self, tracer: FileTracer, debug: LabelledDebug) -> None: self.tracer = tracer self.debug = debug def _show_frame(self, frame: FrameType) -> str: """A short string identifying a frame, for debug messages.""" ...
DebugFileTracerWrapper
python
huggingface__transformers
src/transformers/models/chameleon/modeling_chameleon.py
{ "start": 33776, "end": 34668 }
class ____(PreTrainedModel): config: ChameleonConfig base_model_prefix = "model" input_modalities = ("image", "text") supports_gradient_checkpointing = True _no_split_modules = ["ChameleonDecoderLayer", "ChameleonSwinDecoderLayer"] _skip_keys_device_placement = ["past_key_values", "causal_mask"]...
ChameleonPreTrainedModel
python
pyinstaller__pyinstaller
tests/unit/test_modulegraph/test_imports.py
{ "start": 19928, "end": 20640 }
class ____ (unittest.TestCase): if not hasattr(unittest.TestCase, 'assertIsInstance'): def assertIsInstance(self, value, types): if not isinstance(value, types): self.fail("%r is not an instance of %r"%(value, types)) def test_extended_args_import(): source = "".join(f"dumm...
TestInvalidAsyncFunction
python
ray-project__ray
rllib/examples/envs/classes/multi_agent/footsies/encoder.py
{ "start": 296, "end": 8564 }
class ____: """Encoder class to generate observations from the game state""" def __init__(self, observation_delay: int): self._encoding_history = { agent_id: collections.deque(maxlen=int(observation_delay)) for agent_id in ["p1", "p2"] } self.observation_delay = ...
FootsiesEncoder
python
scipy__scipy
scipy/optimize/_differentialevolution.py
{ "start": 85674, "end": 90022 }
class ____: """Object to wrap/evaluate user defined constraints. Very similar in practice to `PreparedConstraint`, except that no evaluation of jac/hess is performed (explicit or implicit). If created successfully, it will contain the attributes listed below. Parameters ---------- constra...
_ConstraintWrapper
python
pennersr__django-allauth
allauth/mfa/stages.py
{ "start": 1406, "end": 2302 }
class ____(LoginStage): key = LoginStageKey.MFA_TRUST.value urlname = "mfa_trust" def handle(self): lbc_stage = self.controller.get_stage(AccountLoginStageKey.LOGIN_BY_CODE) auth_stage = self.controller.get_stage(AuthenticateStage.key) if ( not app_settings.TRUST_ENABLE...
TrustStage
python
kubernetes-client__python
kubernetes/client/models/v1beta2_capacity_request_policy_range.py
{ "start": 383, "end": 6247 }
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...
V1beta2CapacityRequestPolicyRange
python
protocolbuffers__protobuf
python/google/protobuf/json_format.py
{ "start": 5360, "end": 16285 }
class ____(object): """JSON format printer for protocol message.""" def __init__( self, preserving_proto_field_name=False, use_integers_for_enums=False, descriptor_pool=None, always_print_fields_with_no_presence=False, ): self.always_print_fields_with_no_presence = ( alw...
_Printer
python
eventlet__eventlet
tests/greendns_test.py
{ "start": 7735, "end": 10921 }
class ____(tests.LimitedTestCase): def setUp(self): # Store this so we can reuse it for each test self.query = greendns.dns.message.Message() self.query.flags = greendns.dns.flags.QR self.query_wire = self.query.to_wire() super().setUp() def test_udp_ipv4(self): ...
TestUdp
python
xlwings__xlwings
xlwings/_xlwindows.py
{ "start": 2421, "end": 3472 }
class ____: def __init__(self, method): self.__method = method def __call__(self, *args, **kwargs): n_attempt = 1 while True: try: v = self.__method(*args, **kwargs) if isinstance(v, (CDispatch, CoClassBaseClass, DispatchBaseClass)): ...
COMRetryMethodWrapper
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 100270, "end": 101754 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, shop: str, start_date: str, api_key: str, api_secret: str, conversion_window_days: Optional[int] = None, ): """Airbyte Source for Woocommerce. Documentation can...
WoocommerceSource
python
astropy__astropy
astropy/samp/client.py
{ "start": 450, "end": 25371 }
class ____: """ Utility class which provides facilities to create and manage a SAMP compliant XML-RPC server that acts as SAMP callable client application. Parameters ---------- hub : :class:`~astropy.samp.SAMPHubProxy` An instance of :class:`~astropy.samp.SAMPHubProxy` to be us...
SAMPClient
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType28.py
{ "start": 940, "end": 979 }
class ____(Generic[T_contra]): ...
Class4
python
streamlit__streamlit
lib/tests/streamlit/elements/lib/options_selector_utils_test.py
{ "start": 1178, "end": 2240 }
class ____: def test_check_and_convert_to_indices_none_default(self): res = check_and_convert_to_indices(["a"], None) assert res is None def test_check_and_convert_to_indices_single_default(self): res = check_and_convert_to_indices(["a", "b"], "a") assert res == [0] def tes...
TestCheckAndConvertToIndices
python
streamlit__streamlit
lib/streamlit/vendor/pympler/asizeof.py
{ "start": 50203, "end": 50439 }
class ____(dict): """Internal obj visits counter.""" def again(self, key): try: s = self[key] + 1 except KeyError: s = 1 if s > 0: self[key] = s # Public classes
_Seen
python
huggingface__transformers
src/transformers/models/cwm/modeling_cwm.py
{ "start": 15547, "end": 19056 }
class ____(CwmPreTrainedModel): config_class = CwmConfig def __init__(self, config: CwmConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.paddi...
CwmModel
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1138546, "end": 1139205 }
class ____(ScaleInvalidDataShowAsradius): """ ScaleInvalidDataShowAsValueradius schema wrapper. Parameters ---------- value : float For arc mark, the primary (outer) radius in pixels. For text marks, polar coordinate radial offset, in pixels, of the text from the origin det...
ScaleInvalidDataShowAsValueradius
python
google__flatbuffers
tests/monster_test_generated.py
{ "start": 97485, "end": 103957 }
class ____(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset=0): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = TypeAliases() x.Init(buf, n + offset) return x @classmethod def GetRootAsTypeAliases(cls, buf, offset=0):...
TypeAliases
python
apache__airflow
providers/pinecone/tests/unit/pinecone/hooks/test_pinecone.py
{ "start": 992, "end": 8295 }
class ____: @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( host="pinecone.io", conn_id="pinecone_default", conn_type="pinecone", login="us-west1...
TestPineconeHook
python
getsentry__sentry
src/sentry/ingest/consumer/processors.py
{ "start": 1484, "end": 15426 }
class ____(Exception): pass def trace_func(**span_kwargs): def wrapper(f): @functools.wraps(f) def inner(*args, **kwargs): # First we check a local env var # if that's not set we check our conf file # if neither are set use 0 sample_rate = float(...
Retriable
python
django__django
tests/signals/tests.py
{ "start": 391, "end": 1187 }
class ____: def setUp(self): # Save up the number of connected signals so that we can check at the # end that all the signals we register get properly unregistered # (#9989) self.pre_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers)...
BaseSignalSetup
python
django__django
tests/file_storage/test_inmemory_storage.py
{ "start": 9446, "end": 11975 }
class ____(SimpleTestCase): def test_deconstruction(self): storage = InMemoryStorage() path, args, kwargs = storage.deconstruct() self.assertEqual(path, "django.core.files.storage.InMemoryStorage") self.assertEqual(args, ()) self.assertEqual(kwargs, {}) kwargs_orig =...
InMemoryStorageTests
python
ray-project__ray
python/ray/util/metrics.py
{ "start": 5820, "end": 8304 }
class ____(Metric): """A cumulative metric that is monotonically increasing. This corresponds to Prometheus' counter metric: https://prometheus.io/docs/concepts/metric_types/#counter Before Ray 2.10, this exports a Prometheus gauge metric instead of a counter metric, which is wrong. Since 2.10...
Counter
python
django__django
django/db/models/manager.py
{ "start": 6678, "end": 6866 }
class ____(Manager): def __init__(self, model): super().__init__() self.model = model def get_queryset(self): return super().get_queryset().none()
EmptyManager