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
numpy__numpy
numpy/distutils/command/egg_info.py
{ "start": 75, "end": 921 }
class ____(_egg_info): def run(self): if 'sdist' in sys.argv: import warnings import textwrap msg = textwrap.dedent(""" `build_src` is being run, this may lead to missing files in your sdist! You want to use distutils.sdist ...
egg_info
python
PrefectHQ__prefect
tests/blocks/test_abstract.py
{ "start": 1059, "end": 1927 }
class ____: def test_notification_block_is_abstract(self): with pytest.raises( TypeError, match="Can't instantiate abstract class NotificationBlock" ): NotificationBlock() def test_notification_block_implementation(self, caplog): class ANotificationBlock(Notifica...
TestNotificationBlock
python
doocs__leetcode
lcof2/剑指 Offer II 116. 朋友圈/Solution.py
{ "start": 0, "end": 432 }
class ____: def findCircleNum(self, isConnected: List[List[int]]) -> int: def dfs(i): vis[i] = True for j in range(n): if not vis[j] and isConnected[i][j]: dfs(j) n = len(isConnected) vis = [False] * n ans = 0 for i...
Solution
python
walkccc__LeetCode
solutions/3408. Design Task Manager/3408.py
{ "start": 319, "end": 1302 }
class ____: def __init__(self, tasks: list[list[int]]): self.taskMap = SortedDict() # {taskId: Task}, keeps tasks sorted by taskId self.taskSet = SortedSet() # Stores tasks sorted by priority and taskId for task in tasks: self.add(task[0], task[1], task[2]) def add(self, userId: int, taskId: in...
TaskManager
python
google__jax
jax/experimental/sparse/transform.py
{ "start": 9277, "end": 37575 }
class ____(core.Trace): __slots__ = ("parent_trace", "tag", "spenv") def __init__(self, parent_trace, tag, spenv): super().__init__() self.parent_trace = parent_trace self.tag = tag self.spenv = spenv def to_sparse_tracer(self, val): if isinstance(val, SparseTracer) and self.tag is val._tra...
SparseTrace
python
scipy__scipy
scipy/ndimage/tests/test_interpolation.py
{ "start": 48508, "end": 54503 }
class ____: @pytest.mark.parametrize('order', range(0, 6)) def test_zoom1(self, order, xp): for z in [2, [2, 2]]: arr = xp.reshape(xp.arange(25, dtype=xp.float64), (5, 5)) arr = ndimage.zoom(arr, z, order=order) assert arr.shape == (10, 10) assert xp.all(...
TestZoom
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py
{ "start": 14733, "end": 18316 }
class ____(Qwen2_5OmniThinkerConfig): r""" This is the configuration class to store the configuration of a [`Qwen3OmniMoeThinker`]. It is used to instantiate a Qwen3-Omni-Thinker model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults ...
Qwen3OmniMoeThinkerConfig
python
spyder-ide__spyder
spyder/plugins/shortcuts/widgets/table.py
{ "start": 24115, "end": 31604 }
class ____(HoverRowsTableView): def __init__(self, parent=None): HoverRowsTableView.__init__(self, parent, custom_delegate=True) self._parent = parent self.finder = None self.shortcut_data: List[ShortcutData] = [] self.source_model = ShortcutsModel(self) self.proxy_mo...
ShortcutsTable
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py
{ "start": 21749, "end": 30884 }
class ____(test_util.TensorFlowTestCase): def _SparseTensorValue_5x6(self, dtype=np.int32): ind = np.array([[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]]) val = np.array([0, 10, 13, 14, 32, 33]) shape = np.array([5, 6]) return sparse_tensor.SparseTensorValue( np.array(ind, np.int64), np.arr...
SparseFillEmptyRowsTest
python
ray-project__ray
python/ray/dag/tests/experimental/test_torch_tensor_transport.py
{ "start": 6200, "end": 9055 }
class ____: """Tests driver to worker tensor transport with GPU device.""" def create_and_execute_dag(self, actor, device, tensor_input, is_dict=False): """Create a DAG with tensor transport and execute it.""" with InputNode() as inp: method = actor.echo_dict_device if is_dict else ...
TestDriverToWorkerDeviceGPU
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/lrn_op_test.py
{ "start": 1312, "end": 6841 }
class ____(test.TestCase): def _LRN(self, input_image, lrn_depth_radius=5, bias=1.0, alpha=1.0, beta=0.5): """Compute expected result.""" output = copy.deepcopy(input_image) batch_size = input_image.shape[0] rows = input_image.shape[1] cols = input_image.shape[2] depth = input_imag...
LRNOpTest
python
eriklindernoren__ML-From-Scratch
mlfromscratch/supervised_learning/random_forest.py
{ "start": 495, "end": 3683 }
class ____(): """Random Forest classifier. Uses a collection of classification trees that trains on random subsets of the data using a random subsets of the features. Parameters: ----------- n_estimators: int The number of classification trees that are used. max_features: int Th...
RandomForest
python
crytic__slither
slither/solc_parsing/declarations/event_contract.py
{ "start": 373, "end": 2031 }
class ____: """ EventContract class """ def __init__( self, event: EventContract, event_data: Dict, contract_parser: "ContractSolc" ) -> None: self._event = event self._contract_parser = contract_parser if self.is_compact_ast: self._event.name = event_d...
EventContractSolc
python
pytorch__pytorch
torch/utils/weak.py
{ "start": 11545, "end": 12267 }
class ____: """Wrapper around a weak ref of a Tensor that handles the _fix_weakref() call required when unwrapping a Tensor weakref.""" ref: WeakRef[Tensor] def __init__(self, tensor: Tensor) -> None: if not isinstance(tensor, Tensor): raise AssertionError(f"expected torch.Tensor, got ...
TensorWeakRef
python
django-extensions__django-extensions
django_extensions/management/jobs.py
{ "start": 205, "end": 404 }
class ____: help = "undefined job description." when = None # type: Optional[str] def execute(self): raise NotImplementedError("Job needs to implement the execute method")
BaseJob
python
wandb__wandb
wandb/wandb_agent.py
{ "start": 5274, "end": 18821 }
class ____: POLL_INTERVAL = 5 REPORT_INTERVAL = 0 KILL_DELAY = 30 FLAPPING_MAX_SECONDS = 60 FLAPPING_MAX_FAILURES = 3 MAX_INITIAL_FAILURES = 5 DEFAULT_SWEEP_COMMAND: List[str] = [ "${env}", "${interpreter}", "${program}", "${args}", ] SWEEP_COMMAND_ENV...
Agent
python
pytest-dev__pytest
src/_pytest/warning_types.py
{ "start": 2097, "end": 2272 }
class ____(PytestWarning): """Warning emitted on use of unknown markers. See :ref:`mark` for details. """ __module__ = "pytest" @final
PytestUnknownMarkWarning
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 86992, "end": 87245 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING AutoModelForSemanticSegmentation = auto_class_update( AutoModelForSemanticSegmentation, head_doc="semantic segmentation" )
AutoModelForSemanticSegmentation
python
pandas-dev__pandas
pandas/tests/window/test_numba.py
{ "start": 20618, "end": 22246 }
class ____: @pytest.mark.parametrize( "is_max, has_nan, exp_list", [ (True, False, [3.0, 5.0, 2.0, 5.0, 1.0, 5.0, 6.0, 7.0, 8.0, 9.0]), (True, True, [3.0, 4.0, 2.0, 4.0, 1.0, 4.0, 6.0, 7.0, 7.0, 9.0]), (False, False, [3.0, 2.0, 2.0, 1.0, 1.0, 0.0, 0.0, 0.0, 7.0, 0...
TestMinMaxNumba
python
walkccc__LeetCode
solutions/2261. K Divisible Elements Subarrays/2261.py
{ "start": 103, "end": 599 }
class ____: def countDistinct(self, nums: list[int], k: int, p: int) -> int: ans = 0 root = TrieNode() def insert(node: TrieNode, i: int, k: int): nonlocal ans if i == len(nums) or k - (nums[i] % p == 0) < 0: return if nums[i] not in node.children: node.children[nums[i]]...
Solution
python
lepture__authlib
authlib/integrations/flask_oauth1/resource_protector.py
{ "start": 324, "end": 3842 }
class ____(_ResourceProtector): """A protecting method for resource servers. Initialize a resource protector with the these method: 1. query_client 2. query_token, 3. exists_nonce Usually, a ``query_client`` method would look like (if using SQLAlchemy):: def query_client(client_id): ...
ResourceProtector
python
django-extensions__django-extensions
tests/test_find_template.py
{ "start": 140, "end": 656 }
class ____(TestCase): @patch("sys.stdout", new_callable=StringIO) def test_finding_template(self, m_stdout): call_command("find_template", "admin/change_form.html") self.assertIn("admin/change_form.html", m_stdout.getvalue()) @patch("sys.stderr", new_callable=StringIO) def test_should_...
FindTemplateTests
python
huggingface__transformers
src/transformers/models/albert/modeling_albert.py
{ "start": 25963, "end": 29149 }
class ____(AlbertPreTrainedModel): def __init__(self, config: AlbertConfig): super().__init__(config) self.num_labels = config.num_labels self.config = config self.albert = AlbertModel(config) self.dropout = nn.Dropout(config.classifier_dropout_prob) self.classifier ...
AlbertForSequenceClassification
python
Netflix__metaflow
test/test_config/config_parser.py
{ "start": 2137, "end": 2735 }
class ____(FlowSpec): trigger_param = Parameter( "trigger_param", default="", external_trigger=True, external_artifact=trigger_name_func, ) cfg = Config("cfg", default_value=default_config) req_config = Config( "req_config", default="config_parser_requirements.t...
ConfigParser
python
wandb__wandb
wandb/vendor/pygments/lexers/templates.py
{ "start": 70928, "end": 73077 }
class ____(RegexLexer): """ Generic `angular2 <http://victorsavkin.com/post/119943127151/angular-2-template-syntax>`_ template lexer. Highlights only the Angular template tags (stuff between `{{` and `}}` and special attributes: '(event)=', '[property]=', '[(twoWayBinding)]='). Everything e...
Angular2Lexer
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/inputs.py
{ "start": 774, "end": 995 }
class ____(graphene.InputObjectType): assetKey = graphene.NonNull(GrapheneAssetKeyInput) name = graphene.NonNull(graphene.String) class Meta: name = "AssetCheckHandleInput"
GrapheneAssetCheckHandleInput
python
pytorch__pytorch
torch/distributed/_tools/memory_tracker.py
{ "start": 1262, "end": 11862 }
class ____: """ Collect and plot the memory stats at operator level. Includes ``memories_allocated``, ``memories_active`` and ``memories_reserved``. It also prints a summary for the top 20 operators that generate the most memories. Example usage: >>> # xdoctest: +SKIP(failing) >>>...
MemoryTracker
python
walkccc__LeetCode
solutions/2178. Maximum Split of Positive Even Integers/2178.py
{ "start": 0, "end": 294 }
class ____: def maximumEvenSplit(self, finalSum: int) -> list[int]: if finalSum % 2 == 1: return [] ans = [] needSum = finalSum even = 2 while needSum - even >= even + 2: ans.append(even) needSum -= even even += 2 return ans + [needSum]
Solution
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/utils/sortby.py
{ "start": 161, "end": 1817 }
class ____: """ SortByParam assists in parsing a 'sortBy' parameter from the request, validating it against an endpoint-specific config, and providing the values that should be passed along to QuerySet.order_by and the Paginator. To guarantee stable results with potentially duplicated sort keys, 'id...
SortByParam
python
doocs__leetcode
solution/0200-0299/0244.Shortest Word Distance II/Solution.py
{ "start": 0, "end": 649 }
class ____: def __init__(self, wordsDict: List[str]): self.d = defaultdict(list) for i, w in enumerate(wordsDict): self.d[w].append(i) def shortest(self, word1: str, word2: str) -> int: a, b = self.d[word1], self.d[word2] ans = inf i = j = 0 while i <...
WordDistance
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/super1.py
{ "start": 260, "end": 358 }
class ____(ClassA): def __init__(self): pass def method2(self): pass
ClassB
python
faif__python-patterns
patterns/structural/composite.py
{ "start": 1240, "end": 1376 }
class ____(ABC): @abstractmethod def render(self) -> None: raise NotImplementedError("You should implement this!")
Graphic
python
numba__numba
numba/tests/test_sort.py
{ "start": 16618, "end": 17370 }
class ____(object): timsort = jit_array_timsort test_merge_at = None test_merge_force_collapse = None def wrap_with_mergestate(self, timsort, func, _cache=None): """ Wrap *func* into another compiled function inserting a runtime-created mergestate as the first function argumen...
JITTimsortMixin
python
pytorch__pytorch
torch/fx/_symbolic_trace.py
{ "start": 42037, "end": 42225 }
class ____(_PatchedFn): def revert(self): self.frame_dict[self.fn_name] = self.orig_fn def patch(self): self.frame_dict[self.fn_name] = self.new_fn
_PatchedFnSetItem
python
PyCQA__pylint
tests/functional/d/dataclass/dataclass_typecheck.py
{ "start": 1831, "end": 1960 }
class ____: def __enter__(self): pass def __exit__(self, type_, value, traceback): pass @dataclass
Manager
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_data_class.py
{ "start": 1144, "end": 1373 }
class ____: a: list[int] b: list[int] #----------------------------------------------------------------------------- # General API #-----------------------------------------------------------------------------
DataclassData
python
kamyu104__LeetCode-Solutions
Python/array-transformation.py
{ "start": 31, "end": 641 }
class ____(object): def transformArray(self, arr): """ :type arr: List[int] :rtype: List[int] """ def is_changable(arr): return any(arr[i-1] > arr[i] < arr[i+1] or arr[i-1] < arr[i] > arr[i+1] for i in xrange(1, len(a...
Solution
python
django__django
tests/admin_checks/models.py
{ "start": 950, "end": 1171 }
class ____(models.Model): name = models.CharField(max_length=100) subtitle = models.CharField(max_length=100) price = models.FloatField() authors = models.ManyToManyField(Author, through="AuthorsBooks")
Book
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_private_ip_v4.py
{ "start": 876, "end": 1875 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_ipv4_private" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pand...
ColumnValuesToBePrivateIpV4
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 37932, "end": 38955 }
class ____(AssetSelection): include_sources: bool kind_str: Optional[str] def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool, ) -> AbstractSet[AssetKey]: base_nodes = { node.key: node for node in asset_graph.asset_nodes ...
KindAssetSelection
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/overrides.py
{ "start": 2638, "end": 2710 }
class ____: def method(self, arg): return arg
SkippedOverrides
python
kamyu104__LeetCode-Solutions
Python/sentence-screen-fitting.py
{ "start": 37, "end": 941 }
class ____(object): def wordsTyping(self, sentence, rows, cols): """ :type sentence: List[str] :type rows: int :type cols: int :rtype: int """ def words_fit(sentence, start, cols): if len(sentence[start]) > cols: return 0 ...
Solution
python
PrefectHQ__prefect
src/prefect/logging/clients.py
{ "start": 10920, "end": 11825 }
class ____(PrefectLogsSubscriber): """Logs subscriber for Prefect Cloud""" def __init__( self, api_url: Optional[str] = None, api_key: Optional[str] = None, filter: Optional["LogFilter"] = None, reconnection_attempts: int = 10, ): """ Args: ...
PrefectCloudLogsSubscriber
python
PrefectHQ__prefect
tests/_internal/pydantic/test_validated_func.py
{ "start": 4267, "end": 5171 }
class ____: """Test positional-only parameters (Python 3.8+).""" def test_positional_only_valid(self): def func(a, b, /, c): return a + b + c vf = ValidatedFunction(func) result = vf.validate_call_args((1, 2, 3), {}) assert result == {"a": 1, "b": 2, "c": 3} d...
TestPositionalOnly
python
vyperlang__vyper
tests/evm_backends/base_env.py
{ "start": 577, "end": 752 }
class ____: address: str topics: list[str] data: tuple[list[bytes], bytes] # (topic list, non-topic) # object returned by `last_result` property @dataclass
LogEntry
python
doocs__leetcode
solution/1700-1799/1768.Merge Strings Alternately/Solution.py
{ "start": 0, "end": 161 }
class ____: def mergeAlternately(self, word1: str, word2: str) -> str: return ''.join(a + b for a, b in zip_longest(word1, word2, fillvalue=''))
Solution
python
PrefectHQ__prefect
src/prefect/server/schemas/actions.py
{ "start": 37539, "end": 37879 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to update an artifact.""" data: Optional[Union[Dict[str, Any], Any]] = Field(None) description: Optional[str] = Field(None) metadata_: Optional[ Annotated[dict[str, str], AfterValidator(validate_max_metadata_length)] ] = Fiel...
ArtifactUpdate
python
milvus-io__pymilvus
pymilvus/client/asynch.py
{ "start": 812, "end": 1451 }
class ____: @abc.abstractmethod def result(self, **kwargs): """Return deserialized result. It's a synchronous interface. It will wait executing until server respond or timeout occur(if specified). This API is thread-safe. """ raise NotImplementedError @abc....
AbstractFuture
python
Textualize__textual
tests/test_path.py
{ "start": 361, "end": 432 }
class ____(App[None]): CSS_PATH = "/tmp/test.tcss"
AbsolutePathStrApp
python
PrefectHQ__prefect
src/prefect/server/events/actions.py
{ "start": 38356, "end": 39930 }
class ____(FlowRunAction): """Changes the state of a flow run associated with the trigger""" @abc.abstractmethod async def new_state(self, triggered_action: "TriggeredAction") -> StateCreate: """Return the new state for the flow run""" async def act(self, triggered_action: "TriggeredAction") -...
FlowRunStateChangeAction
python
tensorflow__tensorflow
tensorflow/dtensor/python/tpu_util.py
{ "start": 2030, "end": 32826 }
class ____: """Represents a TPU core's location in the mesh.""" def __init__(self, x: int = 0, y: int = 0, z: int = 0, core: int = 0): self.x = x self.y = y self.z = z self.core = core def __eq__(self, other): if not isinstance(other, _CoreLocation): return False return self.x == o...
_CoreLocation
python
TheAlgorithms__Python
other/greedy.py
{ "start": 0, "end": 1970 }
class ____: def __init__(self, name, value, weight): self.name = name self.value = value self.weight = weight def __repr__(self): return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})" def get_value(self): return self.value def get_name(s...
Things
python
getsentry__sentry
src/sentry/integrations/utils/metrics.py
{ "start": 16359, "end": 16552 }
class ____(StrEnum): """An instance to be recorded of a integration proxy event.""" SHOULD_PROXY = "should_proxy" PROXY_REQUEST = "proxy_request" @dataclass
IntegrationProxyEventType
python
ray-project__ray
python/ray/_private/ray_logging/__init__.py
{ "start": 6080, "end": 7148 }
class ____: def __init__(self): self.handlers = [] self._lock = threading.Lock() def add_handler(self, name: str, handler: Callable) -> None: with self._lock: self.handlers.append((name, handler)) def remove_handler(self, name: str) -> None: with self._lock: ...
WorkerStandardStreamDispatcher
python
nedbat__coveragepy
tests/test_report.py
{ "start": 40137, "end": 45515 }
class ____(CoverageTest): """Tests of SummaryReporter.""" def make_rigged_file(self, filename: str, stmts: int, miss: int) -> None: """Create a file that will have specific results. `stmts` and `miss` are ints, the number of statements, and missed statements that should result. ...
SummaryReporterConfigurationTest
python
cython__cython
tests/run/pep3135_class_cell.py
{ "start": 2597, "end": 2971 }
class ____: """ >>> obj = CE() >>> obj.method()().__name__ 'CE' >>> obj.method2()()().__name__ 'CE' """ def method(self): def inner(): return __class__ return inner def method2(self): def inner(): def inner_inner(): return __class_...
CE
python
astropy__astropy
astropy/units/tests/test_quantity.py
{ "start": 66375, "end": 66606 }
class ____: def __init__(self, value, unit): self.value = value self.unit = unit def __array__(self, dtype=None, copy=COPY_IF_NEEDED): return np.array(self.value, dtype=dtype, copy=copy)
QuantityMimic
python
openai__openai-python
src/openai/types/responses/response_function_web_search_param.py
{ "start": 383, "end": 571 }
class ____(TypedDict, total=False): type: Required[Literal["url"]] """The type of source. Always `url`.""" url: Required[str] """The URL of the source."""
ActionSearchSource
python
doocs__leetcode
solution/2600-2699/2611.Mice and Cheese/Solution2.py
{ "start": 0, "end": 250 }
class ____: def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: for i, x in enumerate(reward2): reward1[i] -= x reward1.sort(reverse=True) return sum(reward2) + sum(reward1[:k])
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/tags/tag_set.py
{ "start": 437, "end": 1946 }
class ____(NamespacedKVSet): """Extend this class to define a set of tags in the same namespace. Supports splatting to a dictionary that can be placed inside a tags argument along with other tags. .. code-block:: python my_tags: NamespacedTagsSet = ... @asset( tags={**my_t...
NamespacedTagSet
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/preserve_defaults.py
{ "start": 366, "end": 1050 }
class ____: """docstring""" def meth( self, name: str = CONSTANT, sentinel: Any = SENTINEL, now: datetime = datetime.now(), # NoQA: B008,DTZ005 color: int = 0xFFFFFF, *, kwarg1, kwarg2=0xFFFFFF, ) -> None: """docstring""" @classm...
Class
python
tensorflow__tensorflow
tensorflow/python/debug/cli/debugger_cli_common.py
{ "start": 27447, "end": 32831 }
class ____: """Registry for tab completion responses.""" def __init__(self): self._comp_dict = {} # TODO(cais): Rename method names with "comp" to "*completion*" to avoid # confusion. def register_tab_comp_context(self, context_words, comp_items): """Register a tab-completion context. Register...
TabCompletionRegistry
python
pennersr__django-allauth
allauth/socialaccount/providers/stackexchange/provider.py
{ "start": 463, "end": 1156 }
class ____(OAuth2Provider): id = "stackexchange" name = "Stack Exchange" account_class = StackExchangeAccount oauth2_adapter_class = StackExchangeOAuth2Adapter def get_site(self): settings = self.get_settings() return settings.get("SITE", "stackoverflow") def extract_uid(self, ...
StackExchangeProvider
python
pydata__xarray
xarray/backends/file_manager.py
{ "start": 854, "end": 1943 }
class ____(Generic[T_File]): """Manager for acquiring and closing a file object. Use FileManager subclasses (CachingFileManager in particular) on backend storage classes to automatically handle issues related to keeping track of many open files and transferring them between multiple processes. """ ...
FileManager
python
PrefectHQ__prefect
tests/cli/transfer/test_work_queues.py
{ "start": 416, "end": 15588 }
class ____: async def test_construct_creates_new_instance(self, transfer_work_queue: WorkQueue): """Test that construct creates a new MigratableWorkQueue instance.""" # Clear any existing instances MigratableWorkQueue._instances.clear() migratable = await MigratableWorkQueue.constru...
TestMigratableWorkQueue
python
sympy__sympy
sympy/series/sequences.py
{ "start": 27276, "end": 28586 }
class ____(SeqBase): """ Base class for operations on sequences. Examples ======== >>> from sympy.series.sequences import SeqExprOp, sequence >>> from sympy.abc import n >>> s1 = sequence(n**2, (n, 0, 10)) >>> s2 = sequence((1, 2, 3), (n, 5, 10)) >>> s = SeqExprOp(s1, s2) >>> s...
SeqExprOp
python
pandas-dev__pandas
scripts/check_test_naming.py
{ "start": 301, "end": 5234 }
class ____ function definition. Though hopefully that shouldn't be necessary. """ from __future__ import annotations import argparse import ast import os from pathlib import Path import sys from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import ( Iterator, Sequence, ) ...
or
python
huggingface__transformers
tests/models/vivit/test_modeling_vivit.py
{ "start": 5736, "end": 12561 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as Vivit does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (VivitModel, VivitForVideoClassification) if is_torch...
VivitModelTest
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/model_saver/torch_model_saver.py
{ "start": 667, "end": 6620 }
class ____(BaseModelSaver): """ ModelSaver class for PyTorch """ def __init__( self, trainer_settings: TrainerSettings, model_path: str, load: bool = False ): super().__init__() self.model_path = model_path self.initialize_path = trainer_settings.init_path se...
TorchModelSaver
python
python-pillow__Pillow
Tests/test_image_resample.py
{ "start": 8436, "end": 10004 }
class ____: def make_case( self, mode: str, fill: tuple[int, int, int] | float ) -> tuple[Image.Image, float | tuple[int, ...]]: im = Image.new(mode, (512, 9), fill) px = im.load() assert px is not None return im.resize((9, 512), Image.Resampling.LANCZOS), px[0, 0] d...
TestCoreResampleConsistency
python
PrefectHQ__prefect
tests/cli/test_server_services.py
{ "start": 945, "end": 3749 }
class ____: def test_start_and_stop_services(self, pid_file: Path): invoke_and_assert( command=[ "server", "services", "start", "--background", ], expected_output_contains="Services are running in the backgro...
TestBackgroundServices
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/commands/ci/state.py
{ "start": 1092, "end": 2007 }
class ____(BaseModel, extra=Extra.forbid): # we intentionally don't save api_token here for security reasons url: str deployment_name: str location_file: str location_name: str is_branch_deployment: bool selected: bool = True build: BuildMetadata build_output: Optional[Union[DockerBu...
LocationState
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_model_retry.py
{ "start": 1844, "end": 20743 }
class ____(FakeToolCallingModel): """Model that always fails with a specific exception.""" error_message: str = Field(default="Model error") error_type: type[Exception] = Field(default=ValueError) def _generate( self, messages: list[BaseMessage], stop: list[str] | None = None, ...
AlwaysFailingModel
python
pydata__xarray
xarray/util/generate_aggregations.py
{ "start": 13340, "end": 15439 }
class ____(AggregationGenerator): _dim_docstring = _DIM_DOCSTRING_GROUPBY _template_signature = TEMPLATE_REDUCTION_SIGNATURE_GROUPBY def generate_code(self, method, has_keep_attrs): extra_kwargs = [kwarg.call for kwarg in method.extra_kwargs if kwarg.call] if self.datastructure.numeric_onl...
GroupByAggregationGenerator
python
google__pytype
pytype/tools/merge_pyi/test_data/scope.py
{ "start": 0, "end": 186 }
class ____: def f(self, x): pass def g(self): def f(x): #gets ignored by pytype but fixer sees it, generates warning (FIXME?) return 1 return f
C
python
huggingface__transformers
tests/models/focalnet/test_modeling_focalnet.py
{ "start": 16164, "end": 16446 }
class ____(BackboneTesterMixin, unittest.TestCase): all_model_classes = (FocalNetBackbone,) if is_torch_available() else () config_class = FocalNetConfig has_attentions = False def setUp(self): self.model_tester = FocalNetModelTester(self)
FocalNetBackboneTest
python
hyperopt__hyperopt
hyperopt/exceptions.py
{ "start": 399, "end": 603 }
class ____(ValueError): """Status of fmin evaluation was not in base.STATUS_STRINGS""" def __init__(self, result): ValueError.__init__(self) self.result = result
InvalidResultStatus
python
pypa__warehouse
tests/unit/organizations/test_models.py
{ "start": 24802, "end": 26454 }
class ____: def test_is_in_good_standing_company_with_manual_activation(self, db_session): organization = DBOrganizationFactory.create(orgtype="Company") DBOrganizationManualActivationFactory.create( organization=organization, expires=datetime.date.today() + datetime.timedelt...
TestOrganizationBillingMethods
python
apache__airflow
providers/papermill/src/airflow/providers/papermill/hooks/kernel.py
{ "start": 1582, "end": 3436 }
class ____(BaseHook): """ The KernelHook can be used to interact with remote jupyter kernel. Takes kernel host/ip from connection and refers to jupyter kernel ports and session_key from ``extra`` field. :param kernel_conn_id: connection that has kernel host/ip """ conn_name_attr = "kerne...
KernelHook
python
walkccc__LeetCode
solutions/1944. Number of Visible People in a Queue/1944.py
{ "start": 0, "end": 331 }
class ____: def canSeePersonsCount(self, heights: list[int]) -> list[int]: ans = [0] * len(heights) stack = [] for i, height in enumerate(heights): while stack and heights[stack[-1]] <= height: ans[stack.pop()] += 1 if stack: ans[stack[-1]] += 1 stack.append(i) retu...
Solution
python
kamyu104__LeetCode-Solutions
Python/binary-prefix-divisible-by-5.py
{ "start": 29, "end": 274 }
class ____(object): def prefixesDivBy5(self, A): """ :type A: List[int] :rtype: List[bool] """ for i in xrange(1, len(A)): A[i] += A[i-1] * 2 % 5 return [x % 5 == 0 for x in A]
Solution
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 347397, "end": 351516 }
class ____(Request): """ Mark a task status as published. If a model was created, it should be set to ready. :param force: If not true, call fails if the task status is not 'stopped' :type force: bool :param publish_model: Indicates that the task output model (if exists) should be published...
PublishRequest
python
astropy__astropy
astropy/io/votable/converters.py
{ "start": 35801, "end": 44626 }
class ____(Converter): """ Handles the boolean datatype. """ format = "b1" array_type = BooleanArray vararray_type = ScalarVarArray default = False binary_question_mark = b"?" binary_true = b"T" binary_false = b"F" def parse(self, value, config=None, pos=None): if v...
Boolean
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 914273, "end": 914993 }
class ____(sgqlc.types.relay.Connection): """The connection type for Reactor.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("ReactorEdge"), graphql_name="edges") """A list of edges.""" nodes = sgqlc....
ReactorConnection
python
doocs__leetcode
solution/1600-1699/1675.Minimize Deviation in Array/Solution.py
{ "start": 0, "end": 445 }
class ____: def minimumDeviation(self, nums: List[int]) -> int: h = [] mi = inf for v in nums: if v & 1: v <<= 1 h.append(-v) mi = min(mi, v) heapify(h) ans = -h[0] - mi while h[0] % 2 == 0: x = heappop(h...
Solution
python
getsentry__sentry
src/sentry_plugins/bitbucket/client.py
{ "start": 238, "end": 3641 }
class ____(AuthApiClient): base_url = "https://api.bitbucket.org" plugin_name = "bitbucket" def has_auth(self): return ( self.auth and "oauth_token" in self.auth.tokens and "oauth_token_secret" in self.auth.tokens ) def bind_auth(self, **kwargs): ...
BitbucketClient
python
sqlalchemy__sqlalchemy
test/typing/plain_files/sql/dml.py
{ "start": 611, "end": 1249 }
class ____(Base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] data: Mapped[str] # test #9376 d1: dict[str, Any] = {} stmt1 = insert(User).values(d1) d2: Dict[str, Any] = {} stmt2 = insert(User).values(d2) d3: Dict[Column[str], Any] = {} stmt3 = inser...
User
python
spyder-ide__spyder
spyder/utils/syntaxhighlighters.py
{ "start": 57588, "end": 66578 }
class ____(BaseSH): """Simple Diff/Patch Syntax Highlighter Class""" def highlight_block(self, text): """Implement highlight specific Diff/Patch files.""" text = str(text) if text.startswith("+++"): self.setFormat(0, qstring_length(text), self.formats["keyword"]) elif...
DiffSH
python
tensorflow__tensorflow
tensorflow/python/eager/polymorphic_function/polymorphic_function.py
{ "start": 7972, "end": 8834 }
class ____(object): """Class for the management of all _FrequentTracingDetector objects.""" __slots__ = ["_detectors", "_lock"] def __init__(self): self._detectors = weakref.WeakKeyDictionary() # GUARDED_BY(self._lock) self._lock = threading.Lock() def _get_detector(self, key): if key not in sel...
_FrequentTracingDetectorManager
python
bottlepy__bottle
test/test_outputfilter.py
{ "start": 290, "end": 6258 }
class ____(ServerTestBase): ''' Tests for WSGI functionality, routing and output casting (decorators) ''' def test_bytes(self): self.app.route('/')(lambda: tob('test')) self.assertBody('test') def test_bytearray(self): self.app.route('/')(lambda: map(tob, ['t', 'e', 'st'])) ...
TestOutputFilter
python
wireservice__csvkit
csvkit/utilities/csvlook.py
{ "start": 101, "end": 3049 }
class ____(CSVKitUtility): description = 'Render a CSV file in the console as a Markdown-compatible, fixed-width table.' def add_arguments(self): self.argparser.add_argument( '--max-rows', dest='max_rows', type=int, help='The maximum number of rows to display before truncating t...
CSVLook
python
pandas-dev__pandas
pandas/tests/arithmetic/test_datetime64.py
{ "start": 73796, "end": 91345 }
class ____: # ------------------------------------------------------------- # Binary operations DatetimeIndex and TimedeltaIndex/array def test_dti_add_tdi(self, tz_naive_fixture): # GH#17558 tz = tz_naive_fixture dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10) td...
TestDatetimeIndexArithmetic
python
getsentry__sentry
src/flagpole/evaluation_context.py
{ "start": 355, "end": 2486 }
class ____: """ Prepared by the application and passed to flagpole to evaluate feature conditions. """ __data: EvaluationContextDict __identity_fields: set[str] __id: int def __init__(self, data: EvaluationContextDict, identity_fields: set[str] | None = None): self.__data = dee...
EvaluationContext
python
doocs__leetcode
solution/1700-1799/1753.Maximum Score From Removing Stones/Solution2.py
{ "start": 0, "end": 190 }
class ____: def maximumScore(self, a: int, b: int, c: int) -> int: a, b, c = sorted([a, b, c]) if a + b < c: return a + b return (a + b + c) >> 1
Solution
python
apache__thrift
lib/py/src/transport/TSSLSocket.py
{ "start": 7851, "end": 12535 }
class ____(TSocket.TSocket, TSSLBase): """ SSL implementation of TSocket This class creates outbound sockets wrapped using the python standard ssl module for encrypted connections. """ # New signature # def __init__(self, host='localhost', port=9090, unix_socket=None, # **...
TSSLSocket
python
numba__numba
numba/tests/test_array_analysis.py
{ "start": 3369, "end": 5743 }
class ____(Compiler): @classmethod def mk_pipeline(cls, args, return_type=None, flags=None, locals=None, library=None, typing_context=None, target_context=None): if locals is None: locals = {} if not flags: flags = Flags() flags.nrt = True ...
ArrayAnalysisTester
python
conda__conda
conda/exceptions.py
{ "start": 39203, "end": 39954 }
class ____(CondaError): def __init__(self, caused_by: Any, **kwargs): message = ( dals( """ A unicode encoding or decoding error has occurred. Python 2 is the interpreter under which conda is running in your base environment. Replacing your base environmen...
EncodingError
python
doocs__leetcode
solution/3500-3599/3517.Smallest Palindromic Rearrangement I/Solution.py
{ "start": 0, "end": 369 }
class ____: def smallestPalindrome(self, s: str) -> str: cnt = Counter(s) t = [] ch = "" for c in ascii_lowercase: v = cnt[c] // 2 t.append(c * v) cnt[c] -= v * 2 if cnt[c] == 1: ch = c ans = "".join(t) a...
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_config/stack.py
{ "start": 1551, "end": 1639 }
class ____(EvaluationStackEntry): list_index: int @record
EvaluationStackListItemEntry
python
google__jax
tests/colocated_python_test.py
{ "start": 1308, "end": 27671 }
class ____(jtu.JaxTestCase): def setUp(self): super().setUp() if not HAS_CLOUDPICKLE: self.skipTest( "ColocatedPythonTest depends on cloudpickle library" ) if np.lib.NumpyVersion(np.__version__) < "2.0.0": self.skipTest( "Serialization in Colocated Python needs StringDTy...
ColocatedPythonTest