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
pandas-dev__pandas
pandas/tests/indexes/multi/test_lexsort.py
{ "start": 32, "end": 626 }
class ____: def test_is_lexsorted(self): levels = [[0, 1], [0, 1, 2]] index = MultiIndex( levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]] ) assert index._is_lexsorted() index = MultiIndex( levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1...
TestIsLexsorted
python
sympy__sympy
sympy/categories/diagram_drawing.py
{ "start": 4388, "end": 6316 }
class ____: """ Holds a growable grid of objects. Explanation =========== It is possible to append or prepend a row or a column to the grid using the corresponding methods. Prepending rows or columns has the effect of changing the coordinates of the already existing elements. Thi...
_GrowableGrid
python
mlflow__mlflow
mlflow/types/responses_helpers.py
{ "start": 3476, "end": 3626 }
class ____(Status): arguments: str call_id: str name: str type: str = "function_call" id: str | None = None
ResponseFunctionToolCall
python
huggingface__transformers
src/transformers/models/pegasus_x/modeling_pegasus_x.py
{ "start": 53077, "end": 60483 }
class ____(PegasusXPreTrainedModel): _tied_weights_keys = { "encoder.embed_tokens.weight": "shared.weight", "decoder.embed_tokens.weight": "shared.weight", } def __init__(self, config: PegasusXConfig): super().__init__(config) vocab_size = config.vocab_size embed_sc...
PegasusXModel
python
pandas-dev__pandas
pandas/errors/__init__.py
{ "start": 19300, "end": 19883 }
class ____(Exception): """ Exception raised when performing an operation on non-numerical data. For example, calling ``ohlc`` on a non-numerical column or a function on a rolling window. See Also -------- Series.rolling : Provide rolling window calculations on Series object. DataFrame....
DataError
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 117390, "end": 118617 }
class ____(BaseView): """Pretend our storage has a different type""" target_dtype: torch.dtype @classmethod def create(cls, x: IRNode, new_dtype: torch.dtype) -> BaseView: if is_storage_and_layout(x): storage, old_layout = as_storage_and_layout(x) new_layout = FixedLayo...
DtypeView
python
ansible__ansible
test/lib/ansible_test/_util/controller/sanity/yamllint/yamllinter.py
{ "start": 2320, "end": 2585 }
class ____(CParser, TestConstructor, Resolver): """Custom YAML loader that recognizes custom Ansible tags.""" def __init__(self, stream): CParser.__init__(self, stream) TestConstructor.__init__(self) Resolver.__init__(self)
TestLoader
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/methods/test_normalize.py
{ "start": 253, "end": 3181 }
class ____: def test_normalize(self): rng = date_range("1/1/2000 9:30", periods=10, freq="D") result = rng.normalize() expected = date_range("1/1/2000", periods=10, freq="D") tm.assert_index_equal(result, expected) arr_ns = np.array([1380585623454345752, 1380585612343234312...
TestNormalize
python
vyperlang__vyper
vyper/exceptions.py
{ "start": 8739, "end": 8826 }
class ____(VyperException): """Invalid operator for a given type."""
InvalidOperation
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/self2.py
{ "start": 784, "end": 993 }
class ____: def set_scale(self, scale: float) -> Self: self.scale = scale return self @classmethod def from_config(cls, config: dict[str, float]) -> Self: return cls()
Shape1
python
joke2k__faker
faker/providers/person/fr_DZ/__init__.py
{ "start": 44, "end": 9101 }
class ____(PersonProvider): formats_female = ("{{last_name}} {{first_name_female}}",) formats_male = ("{{last_name}} {{first_name_male}}",) formats = formats_male + formats_female # Source: https://studentsoftheworld.info/penpals/stats_fr.php?Pays=ALG # Last checked: 2025-09-27 first_names_ma...
Provider
python
dask__distributed
distributed/tests/test_failed_workers.py
{ "start": 9628, "end": 19280 }
class ____: def __init__(self, data, delay=0.1): self.delay = delay self.data = data def __reduce__(self): sleep(self.delay) return SlowTransmitData, (self.data, self.delay) def __sizeof__(self) -> int: # Ensure this is offloaded to avoid blocking loop retur...
SlowTransmitData
python
conda__conda
conda/gateways/logging.py
{ "start": 762, "end": 2020 }
class ____(Filter): TOKEN_URL_PATTERN = re.compile( r"(|https?://)" # \1 scheme r"(|\s" # \2 space, or r"|(?:(?:\d{1,3}\.){3}\d{1,3})" # ipv4, or r"|(?:" # domain name r"(?:[a-zA-Z0-9-]{1,20}\.){0,10}" # non-tld r"(?:[a-zA-Z]{2}[a-zA-Z0-9-]{0,18})" # tld ...
TokenURLFilter
python
getsentry__sentry
tests/sentry/receivers/test_releases.py
{ "start": 1224, "end": 1722 }
class ____(TestCase): @patch("sentry.tasks.clear_expired_resolutions.clear_expired_resolutions.delay") def test_simple(self, mock_delay: MagicMock) -> None: with self.capture_on_commit_callbacks(execute=True): release = Release.objects.create( version="a", organization_id=sel...
ResolveGroupResolutionsTest
python
facelessuser__pymdown-extensions
tests/test_extensions/test_highlight.py
{ "start": 54, "end": 882 }
class ____(util.MdCase): """Test that highlighting works with guessing.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'guess_lang': True } } def test_guess(self): """Test guessing.""" self.ch...
TestHighlightGuess
python
keras-team__keras
keras/src/metrics/reduction_metrics_test.py
{ "start": 337, "end": 1910 }
class ____(testing.TestCase): def test_config(self): sum_obj = reduction_metrics.Sum(name="sum", dtype="float32") self.assertEqual(sum_obj.name, "sum") self.assertEqual(len(sum_obj.variables), 1) self.assertEqual(sum_obj._dtype, "float32") # Check save and restore config ...
SumTest
python
numba__numba
numba/tests/test_gdb_dwarf.py
{ "start": 393, "end": 2196 }
class ____(TestCase): # This runs the tests in numba.tests.gdb, each submodule must contain one # test class called "Test" and it must contain one test called "test". # Variation is provided by the module name. The reason this convention exits # is because gdb tests tend to be line number sensitive (bre...
TestGDBDwarf
python
pypa__pip
src/pip/_vendor/pygments/lexer.py
{ "start": 23592, "end": 27965 }
class ____(Lexer, metaclass=RegexLexerMeta): """ Base for simple stateful regular expression-based lexers. Simplifies the lexing process so that you need only provide a list of states and regular expressions. """ #: Flags for compiling the regular expressions. #: Defaults to MULTILINE. ...
RegexLexer
python
pytorch__pytorch
torch/utils/data/sampler.py
{ "start": 584, "end": 3752 }
class ____(Generic[_T_co]): r"""Base class for all Samplers. Every Sampler subclass has to provide an :meth:`__iter__` method, providing a way to iterate over indices or lists of indices (batches) of dataset elements, and may provide a :meth:`__len__` method that returns the length of the returned iter...
Sampler
python
numpy__numpy
numpy/linalg/tests/test_linalg.py
{ "start": 68049, "end": 72492 }
class ____: arr1 = np.arange(3) arr2 = np.arange(3) expected = np.array( [[0, 0, 0], [0, 1, 2], [0, 2, 4]] ) assert_array_equal(np.linalg.outer(arr1, arr2), expected) with assert_raises_regex( ValueError, "Input arrays must be one-dimensional" ): n...
TestOuter
python
kamyu104__LeetCode-Solutions
Python/binary-tree-coloring-game.py
{ "start": 191, "end": 838 }
class ____(object): def btreeGameWinningMove(self, root, n, x): """ :type root: TreeNode :type n: int :type x: int :rtype: bool """ def count(node, x, left_right): if not node: return 0 left, right = count(node.left, x, ...
Solution
python
pyodide__pyodide
tools/backport.py
{ "start": 6137, "end": 8441 }
class ____: """A section of the changelog for a particular version of Pyodide Introduced by ### or ##. Ends when there is another line with ### or ##. header: Consists of all the lines starting with and the subsection start "###" line and including all content lines up untile the first lin...
ChangelogSection
python
Pylons__pyramid
tests/test_integration.py
{ "start": 714, "end": 1618 }
class ____(unittest.TestCase): def test_it(self): import types from venusian import ATTACH_ATTR self.assertTrue(getattr(wsgiapptest, ATTACH_ATTR)) self.assertIsInstance(wsgiapptest, types.FunctionType) context = DummyContext() request = DummyRequest() result ...
WGSIAppPlusViewConfigTests
python
pytorch__pytorch
test/package/test_misc.py
{ "start": 620, "end": 12817 }
class ____(PackageTestCase): """Tests for one-off or random functionality. Try not to add to this!""" def test_file_structure(self): """ Tests package's Directory structure representation of a zip file. Ensures that the returned Directory prints what is expected and filters inpu...
TestMisc
python
PyCQA__pylint
tests/functional/m/mapping_context.py
{ "start": 904, "end": 1127 }
class ____: kwargs = None def get_kwargs(self): return self.kwargs def run(self, **kwargs): print(kwargs) def dispatch(self): kws = self.get_kwargs() self.run(**kws)
SomeMixin
python
numpy__numpy
numpy/_core/tests/test_scalar_methods.py
{ "start": 4226, "end": 5118 }
class ____: @pytest.mark.parametrize("str_value", ["inf", "nan"]) @pytest.mark.parametrize("code", np.typecodes["Float"]) def test_special(self, code: str, str_value: str) -> None: cls = np.dtype(code).type value = cls(str_value) assert not value.is_integer() @pytest.mark.parame...
TestIsInteger
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/inference.py
{ "start": 330, "end": 568 }
class ____(NamedTuple): """The information about an input that can be inferred from the function signature.""" name: str annotation: Any description: Optional[str] default_value: Any = NoValueSentinel
InferredInputProps
python
lxml__lxml
src/lxml/tests/test_sax.py
{ "start": 11215, "end": 12632 }
class ____(ContentHandler): """A SAX content handler that just stores the events""" def __init__(self): self.sax_events = [] super().__init__() def startDocument(self): self.sax_events.append(('startDocument',)) def endDocument(self): self.sax_events.append(('endDocume...
SimpleContentHandler
python
pallets__click
examples/aliases/aliases.py
{ "start": 46, "end": 887 }
class ____: """The config in this example only holds aliases.""" def __init__(self): self.path = os.getcwd() self.aliases = {} def add_alias(self, alias, cmd): self.aliases.update({alias: cmd}) def read_config(self, filename): parser = configparser.RawConfigParser() ...
Config
python
doocs__leetcode
solution/0300-0399/0387.First Unique Character in a String/Solution.py
{ "start": 0, "end": 190 }
class ____: def firstUniqChar(self, s: str) -> int: cnt = Counter(s) for i, c in enumerate(s): if cnt[c] == 1: return i return -1
Solution
python
dask__distributed
distributed/deploy/tests/test_spec_cluster.py
{ "start": 524, "end": 12400 }
class ____(Worker): pass worker_spec = { 0: {"cls": "dask.distributed.Worker", "options": {"nthreads": 1}}, 1: {"cls": Worker, "options": {"nthreads": 2}}, "my-worker": {"cls": MyWorker, "options": {"nthreads": 3}}, } scheduler = {"cls": Scheduler, "options": {"dashboard_address": ":0"}} @gen_test()...
MyWorker
python
PrefectHQ__prefect
src/prefect/client/schemas/actions.py
{ "start": 30004, "end": 30750 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to update a work queue.""" name: Optional[str] = Field(default=None) description: Optional[str] = Field(default=None) is_paused: bool = Field( default=False, description="Whether or not the work queue is paused." ) concur...
WorkQueueUpdate
python
apache__airflow
providers/google/tests/unit/google/cloud/transfers/test_bigquery_to_postgres.py
{ "start": 1781, "end": 10809 }
class ____: @mock.patch("airflow.providers.google.cloud.transfers.bigquery_to_postgres.bigquery_get_data") @mock.patch.object(BigQueryToPostgresOperator, "bigquery_hook", new_callable=mock.PropertyMock) @mock.patch.object(BigQueryToPostgresOperator, "postgres_hook", new_callable=mock.PropertyMock) def t...
TestBigQueryToPostgresOperator
python
django__django
django/contrib/staticfiles/handlers.py
{ "start": 2721, "end": 4043 }
class ____(StaticFilesHandlerMixin, ASGIHandler): """ ASGI application which wraps another and intercepts requests for static files, passing them off to Django's static file serving. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.ge...
ASGIStaticFilesHandler
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 9828, "end": 10452 }
class ____(BaseModel): """ Current clustering distribution for the collection """ peer_id: int = Field(..., description="ID of this peer") shard_count: int = Field(..., description="Total number of shards") local_shards: List["LocalShardInfo"] = Field(..., description="Local shards") remote...
CollectionClusterInfo
python
cookiecutter__cookiecutter
cookiecutter/environment.py
{ "start": 214, "end": 2003 }
class ____: """Mixin providing sane loading of extensions specified in a given context. The context is being extracted from the keyword arguments before calling the next parent class in line of the child. """ def __init__(self, *, context: dict[str, Any] | None = None, **kwargs: Any) -> None: ...
ExtensionLoaderMixin
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/math_ops/clip_ops_test.py
{ "start": 1294, "end": 21702 }
class ____(test.TestCase): # ClipByValue test def testClipByValue(self): with self.session(): x = constant_op.constant([-5.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3]) np_ans = [[-4.4, 2.0, 3.0], [4.0, 4.4, 4.4]] clip_value = 4.4 ans = clip_ops.clip_by_value(x, -clip_value, clip_value) ...
ClipTest
python
realpython__materials
python-range/pi_digits.py
{ "start": 47, "end": 182 }
class ____: num_digits: int def __index__(self): return int("3141592653589793238462643383279"[: self.num_digits])
PiDigits
python
ray-project__ray
python/ray/llm/_internal/batch/processor/vllm_engine_proc.py
{ "start": 1686, "end": 2026 }
class ____(BaseModelExtended): bundles: List[BundleSchema] = Field( default_factory=list, description="The bundles for the placement group." ) strategy: Literal["PACK", "STRICT_PACK", "SPREAD", "STRICT_SPREAD"] = Field( default="PACK", description="The strategy for the placement group." ...
PlacementGroupSchema
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_qt.py
{ "start": 37700, "end": 41924 }
class ____(QtWidgets.QDialog): def __init__(self, targetfig, parent): super().__init__(parent) self.setWindowIcon(QtGui.QIcon( str(cbook._get_data_path("images/matplotlib.png")))) self.setObjectName("SubplotTool") self._spinboxes = {} main_layout = QtWidgets.QHBox...
SubplotToolQt
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/refurb/FURB118.py
{ "start": 2918, "end": 3233 }
class ____: @pytest.mark.parametrize( "slicer, expected", [ (lambda x: x[-2:], "foo"), (lambda x: x[-5:-3], "bar"), ], ) def test_inlet_asset_alias_extra_slice(self, slicer, expected): assert slice("whatever") == expected
TheLambdasHereAreNotMethods
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1064794, "end": 1089685 }
class ____(VegaLiteSchema): """ Scale schema wrapper. Parameters ---------- align : dict, float, :class:`ExprRef` The alignment of the steps within the scale range. This value must lie in the range ``[0,1]``. A value of ``0.5`` indicates that the steps should be centered wi...
Scale
python
pypa__pip
src/pip/_internal/cli/spinners.py
{ "start": 3487, "end": 4809 }
class ____: def __init__(self, min_update_interval_seconds: float) -> None: self._min_update_interval_seconds = min_update_interval_seconds self._last_update: float = 0 def ready(self) -> bool: now = time.time() delta = now - self._last_update return delta >= self._min_u...
RateLimiter
python
huggingface__transformers
tests/models/instructblip/test_modeling_instructblip.py
{ "start": 1673, "end": 4800 }
class ____: def __init__( self, parent, batch_size=12, image_size=30, patch_size=2, num_channels=3, is_training=True, hidden_size=32, projection_dim=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, ...
InstructBlipVisionModelTester
python
plotly__plotly.py
plotly/graph_objs/_parcats.py
{ "start": 215, "end": 35722 }
class ____(_BaseTraceType): _parent_path_str = "" _path_str = "parcats" _valid_props = { "arrangement", "bundlecolors", "counts", "countssrc", "dimensiondefaults", "dimensions", "domain", "hoverinfo", "hoveron", "hovertemplate",...
Parcats
python
run-llama__llama_index
llama-index-core/llama_index/core/voice_agents/interface.py
{ "start": 61, "end": 2761 }
class ____(ABC): """ Abstract base class for a voice agent audio input/output interface. """ @abstractmethod def __init__(self, *args: Any, **kwargs: Any) -> None: """Please implement this method by initializing the class with arbitrary attributes.""" ... @abstractmethod de...
BaseVoiceAgentInterface
python
sqlalchemy__sqlalchemy
test/sql/test_syntax_extensions.py
{ "start": 4439, "end": 8638 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" def test_illegal_section(self): class SomeExtension(SyntaxExtension, ClauseElement): _traverse_internals = [] def apply_to_select(self, select_stmt): select_stmt.apply_syntax_extension_po...
TestExtensionPoints
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 9683, "end": 9763 }
class ____(HTTPClientError): status_code = 431
HTTPRequestHeaderFieldsTooLarge
python
django__django
tests/invalid_models_tests/test_ordinary_fields.py
{ "start": 24908, "end": 26751 }
class ____(SimpleTestCase): def test_valid_default_case(self): class Model(models.Model): field = models.FileField() self.assertEqual(Model._meta.get_field("field").check(), []) def test_valid_case(self): class Model(models.Model): field = models.FileField(uploa...
FileFieldTests
python
realpython__materials
python-microservices-with-grpc/marketplace/recommendations_pb2_grpc.py
{ "start": 150, "end": 656 }
class ____(object): """Missing associated documentation comment in .proto file""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.Recommend = channel.unary_unary( "/Recommendations/Recommend", request_seri...
RecommendationsStub
python
django__django
django/utils/tree.py
{ "start": 155, "end": 4394 }
class ____: """ A single internal node in the tree graph. A Node should be viewed as a connection (the root) with the children being either leaf nodes or other Node instances. """ # Standard connector type. Clients usually won't use this at all and # subclasses will usually override the val...
Node
python
pytorch__pytorch
test/torch_np/test_unary_ufuncs.py
{ "start": 293, "end": 5092 }
class ____(TestCase): def test_absolute(self): assert_allclose(np.absolute(0.5), absolute(0.5), atol=1e-14, check_dtype=False) def test_arccos(self): assert_allclose(np.arccos(0.5), arccos(0.5), atol=1e-14, check_dtype=False) def test_arccosh(self): assert_allclose(np.arccosh(1.5),...
TestUnaryUfuncs
python
pytorch__pytorch
torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py
{ "start": 916, "end": 6579 }
class ____: layout_a: str layout_b: str layout_c: str datatype_a: str datatype_b: str datatype_c: str tile_m: int tile_n: int tile_k: int warp_m: int warp_n: int warp_k: int warp_tile_m: int warp_tile_n: int warp_tile_k: int m_is_padded: str n_is_...
CKTileGemmOperation
python
langchain-ai__langchain
libs/core/langchain_core/runnables/base.py
{ "start": 214080, "end": 214242 }
class ____(Protocol[Input, Output]): def __call__( self, _in: Input, /, *, config: RunnableConfig ) -> Awaitable[Output]: ...
_RunnableCallableAsync
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-signnow/llama_index/tools/signnow/base.py
{ "start": 2114, "end": 5403 }
class ____(BaseToolSpec): """ Thin wrapper over McpToolSpec: - creates BasicMCPClient for STDIO spawn, - dynamically pulls tools from SignNow MCP server, - sugar factories: from_env. See McpToolSpec.to_tool_list() / .to_tool_list_async() for getting FunctionTool. """ # Follow BaseToolS...
SignNowMCPToolSpec
python
gevent__gevent
src/gevent/tests/test__greenlet.py
{ "start": 14268, "end": 14479 }
class ____(AbstractGenericGetTestCase): def wait(self, timeout): g = gevent.spawn(gevent.sleep, 10) try: return g.get(timeout=timeout) finally: g.kill()
TestGet
python
pytorch__pytorch
test/distributed/tensor/test_attention.py
{ "start": 2989, "end": 15869 }
class ____(DTensorTestBase): @property def world_size(self) -> int: return torch.cuda.device_count() @property def destroy_pg_upon_exit(self) -> bool: return False @skip_if_lt_x_gpu(2) @skipIfRocm # Missing _c10d_functional_autograd::all_to_all_single @unittest.skipIf( ...
RingAttentionTest
python
openai__openai-python
src/openai/types/shared/response_format_text.py
{ "start": 195, "end": 326 }
class ____(BaseModel): type: Literal["text"] """The type of response format being defined. Always `text`."""
ResponseFormatText
python
sqlalchemy__sqlalchemy
examples/inheritance/concrete.py
{ "start": 724, "end": 1008 }
class ____(Base): __tablename__ = "company" id: Mapped[intpk] name: Mapped[str50] employees: Mapped[list[Person]] = relationship( back_populates="company", cascade="all, delete-orphan" ) def __repr__(self): return f"Company {self.name}"
Company
python
django__django
django/core/cache/backends/base.py
{ "start": 257, "end": 322 }
class ____(ImproperlyConfigured): pass
InvalidCacheBackendError
python
allegroai__clearml
clearml/backend_api/services/v2_20/models.py
{ "start": 28245, "end": 39121 }
class ____(Request): """ Create a new model not associated with a task :param uri: URI for the model :type uri: str :param name: Model name Unique within the company. :type name: str :param comment: Model comment :type comment: str :param tags: User-defined tags list :type tags:...
CreateRequest
python
spyder-ide__spyder
spyder/widgets/helperwidgets.py
{ "start": 19142, "end": 21692 }
class ____(QTableView): """QTableView subclass that can highlight an entire row when hovered.""" sig_hover_index_changed = Signal(object) """ This is emitted when the index that is currently hovered has changed. Parameters ---------- index: object QModelIndex that has changed on ho...
HoverRowsTableView
python
docker__docker-py
tests/unit/context_test.py
{ "start": 180, "end": 1624 }
class ____(unittest.TestCase): @pytest.mark.skipif( IS_WINDOWS_PLATFORM, reason='Linux specific path check' ) def test_url_compatibility_on_linux(self): c = Context("test") assert c.Host == DEFAULT_UNIX_SOCKET[5:] @pytest.mark.skipif( not IS_WINDOWS_PLATFORM, reason='Win...
BaseContextTest
python
openai__openai-python
tests/api_resources/responses/test_input_tokens.py
{ "start": 395, "end": 2711 }
class ____: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_count(self, client: OpenAI) -> None: input_token = client.responses.input_tokens.count() assert_matches_type(InputTokenCountResponse, input_token, ...
TestInputTokens
python
walkccc__LeetCode
solutions/2488. Count Subarrays With Median K/2488.py
{ "start": 0, "end": 665 }
class ____: def countSubarrays(self, nums: list[int], k: int) -> int: INDEX = nums.index(k) ans = 0 count = collections.Counter() balance = 0 for i in range(INDEX, -1, -1): if nums[i] < k: balance -= 1 elif nums[i] > k: balance += 1 count[balance] += 1 balan...
Solution
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 53400, "end": 53994 }
class ____(Blockwise): _parameters = ["frame"] operation = staticmethod(_check_divisions) _preserves_partitioning_information = True @functools.cached_property def _meta(self): return self.frame._meta def _task(self, name: Key, index: int) -> Task: args = [self._blockwise_arg(o...
EnforceRuntimeDivisions
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 81527, "end": 82356 }
class ____(Response): """ Response of datasets.create endpoint. :param id: ID of the dataset :type id: str """ _service = "datasets" _action = "create" _version = "2.23" _schema = { "definitions": {}, "properties": { "id": {"description": "ID of the dat...
CreateResponse
python
django__django
tests/auth_tests/test_remote_user.py
{ "start": 16838, "end": 17501 }
class ____(RemoteUserBackend): """ Backend that overrides RemoteUserBackend methods. """ def clean_username(self, username): """ Grabs username before the @ character. """ return username.split("@")[0] def configure_user(self, request, user, created=True): "...
CustomRemoteUserBackend
python
ansible__ansible
packaging/release.py
{ "start": 4436, "end": 9169 }
class ____: """ Simple command line framework inspired by nox. Argument parsing is handled by argparse. Each function annotated with an instance of this class becomes a subcommand. Options are shared across all commands, and are defined by providing kwargs when creating an instance of this class. O...
CommandFramework
python
python__mypy
mypy/applytype.py
{ "start": 7575, "end": 12032 }
class ____(TypeTranslator): """Make free type variables generic in the type if possible. See docstring for apply_poly() for details. """ def __init__( self, poly_tvars: Iterable[TypeVarLikeType], bound_tvars: frozenset[TypeVarLikeType] = frozenset(), seen_aliases: froze...
PolyTranslator
python
sympy__sympy
sympy/tensor/array/dense_ndim_array.py
{ "start": 3658, "end": 4719 }
class ____(DenseNDimArray, ImmutableNDimArray): # type: ignore def __new__(cls, iterable, shape=None, **kwargs): return cls._new(iterable, shape, **kwargs) @classmethod def _new(cls, iterable, shape, **kwargs): shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs...
ImmutableDenseNDimArray
python
sqlalchemy__sqlalchemy
test/orm/test_query.py
{ "start": 91893, "end": 97698 }
class ____(QueryTest): __dialect__ = "default" __sparse_driver_backend__ = True def test_first(self): User = self.classes.User assert User(id=7) == fixture_session().query(User).first() assert ( fixture_session().query(User).filter(User.id == 27).first() is None ...
SliceTest
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_container.py
{ "start": 14474, "end": 15349 }
class ____: def test_valid(self) -> None: prop = bcpc.Len(bcpc.List(Int), 2) assert prop.is_valid([0, 1]) def test_invalid(self) -> None: prop = bcpc.Len(bcpc.List(Int), 2) assert not prop.is_valid([]) assert not prop.is_valid([0]) assert not prop.is_valid([0, 1,...
Test_Len
python
keras-team__keras
keras/src/utils/tracking.py
{ "start": 769, "end": 4589 }
class ____: """Attribute tracker, used for e.g. Variable tracking. Monitors certain attribute types and put them in appropriate lists in case of a match. Also passively tracks certain mutable collections (dict, list) so that items added to them later still get tracked. This is done by wrapping...
Tracker
python
tensorflow__tensorflow
tensorflow/compiler/mlir/quantization/tensorflow/python/integration_test/quantize_model_test.py
{ "start": 203080, "end": 213604 }
class ____(quantize_model_test_base.QuantizedModelTest): def _run_model_in_sess(self, model_dir, tags, signature_key, sample_inputs): with tensorflow.compat.v1.Session(graph=tensorflow.Graph()) as sess: meta_graph = saved_model_loader.load(sess, tags, export_dir=model_dir) signature_def = meta_graph....
DebuggerTest
python
allegroai__clearml
clearml/storage/callbacks.py
{ "start": 4972, "end": 6892 }
class ____(ProgressReport): def __init__( self, filename: str, verbose: bool, total_size: float, log: logging.Logger, report_chunk_size_mb: Optional[int] = None, report_start: Optional[bool] = None, ) -> None: report_chunk_size_mb = ( r...
UploadProgressReport
python
mwaskom__seaborn
seaborn/axisgrid.py
{ "start": 12712, "end": 43514 }
class ____(Grid): """Multi-plot grid for plotting conditional relationships.""" def __init__( self, data, *, row=None, col=None, hue=None, col_wrap=None, sharex=True, sharey=True, height=3, aspect=1, palette=None, row_order=None, col_order=None, hue_order=None, hue_kws=None, ...
FacetGrid
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/shrinker.py
{ "start": 3140, "end": 73872 }
class ____: """A shrinker is a child object of a ConjectureRunner which is designed to manage the associated state of a particular shrink problem. That is, we have some initial ConjectureData object and some property of interest that it satisfies, and we want to find a ConjectureData object with a s...
Shrinker
python
getsentry__sentry
tests/sentry/auth/test_access.py
{ "start": 43094, "end": 43709 }
class ____(TestCase): def test_system_access(self) -> None: org = self.create_organization() team = self.create_team(organization=org) project = self.create_project(teams=[team]) result = access.SystemAccess() assert not result.sso_is_valid assert not result.requires_...
SystemAccessTest
python
lepture__authlib
tests/clients/asgi_helper.py
{ "start": 126, "end": 1101 }
class ____: def __init__(self, body=b"", status_code=200, headers=None, assert_func=None): if headers is None: headers = {} if isinstance(body, dict): body = json.dumps(body).encode() headers["Content-Type"] = "application/json" else: if isinst...
AsyncMockDispatch
python
sqlalchemy__sqlalchemy
examples/dogpile_caching/model.py
{ "start": 1057, "end": 1464 }
class ____(Base): __tablename__ = "postal_code" id = Column(Integer, primary_key=True) code = Column(String(10), nullable=False) city_id = Column(Integer, ForeignKey("city.id"), nullable=False) city = relationship(City) @property def country(self): return self.city.country def...
PostalCode
python
python__mypy
mypy/report.py
{ "start": 4466, "end": 4702 }
class ____(TraverserVisitor): def __init__(self) -> None: super().__init__() self.counts = [0, 0] def visit_func_def(self, defn: FuncDef) -> None: self.counts[defn.type is not None] += 1
FuncCounterVisitor
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 61364, "end": 62436 }
class ____(Operation): def __init__(self, x_min, x_max, *, name=None): super().__init__(name=name) self.x_min = x_min self.x_max = x_max def call(self, x): return backend.numpy.clip(x, self.x_min, self.x_max) def compute_output_spec(self, x): dtype = backend.standar...
Clip
python
python-jsonschema__jsonschema
jsonschema/tests/test_validators.py
{ "start": 78451, "end": 87535 }
class ____(TestCase): base_uri = "" stored_uri = "foo://stored" stored_schema = {"stored": "schema"} def setUp(self): self.referrer = {} self.store = {self.stored_uri: self.stored_schema} self.resolver = validators._RefResolver( self.base_uri, self.referrer, self.st...
TestRefResolver
python
django__django
django/core/management/commands/squashmigrations.py
{ "start": 492, "end": 10131 }
class ____(BaseCommand): help = ( "Squashes an existing set of migrations (from first until specified) into a " "single new one." ) def add_arguments(self, parser): parser.add_argument( "app_label", help="App label of the application to squash migrations for....
Command
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 20078, "end": 21209 }
class ____(themeable): """ Plot title Parameters ---------- theme_element : element_text Notes ----- The default horizontal alignment for the title is center. However the title will be left aligned if and only if there is a subtitle and its horizontal alignment has not been set...
plot_title
python
django__django
django/http/multipartparser.py
{ "start": 818, "end": 1044 }
class ____(Exception): """ No more reads are allowed from this device. """ pass RAW = "raw" FILE = "file" FIELD = "field" FIELD_TYPES = frozenset([FIELD, RAW]) MAX_TOTAL_HEADER_SIZE = 1024
InputStreamExhausted
python
MorvanZhou__Reinforcement-learning-with-tensorflow
contents/8_Actor_Critic_Advantage/AC_continue_Pendulum.py
{ "start": 3073, "end": 6388 }
class ____(object): def __init__(self, sess, n_features, lr=0.01): self.sess = sess with tf.name_scope('inputs'): self.s = tf.placeholder(tf.float32, [1, n_features], "state") self.v_ = tf.placeholder(tf.float32, [1, 1], name="v_next") self.r = tf.placeholder(tf.f...
Critic
python
doocs__leetcode
solution/0900-0999/0930.Binary Subarrays With Sum/Solution2.py
{ "start": 0, "end": 479 }
class ____: def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: i1 = i2 = s1 = s2 = j = ans = 0 n = len(nums) while j < n: s1 += nums[j] s2 += nums[j] while i1 <= j and s1 > goal: s1 -= nums[i1] i1 += 1 ...
Solution
python
bokeh__bokeh
src/bokeh/models/ui/icons.py
{ "start": 2518, "end": 3545 }
class ____(Icon): """ Built-in icons included with BokehJS. """ # explicit __init__ to support Init signatures def __init__(self, icon_name: Init[str] = Intrinsic, **kwargs: Any) -> None: super().__init__(icon_name=icon_name, **kwargs) icon_name = Required(Either(Enum(ToolIcon), String), help=...
BuiltinIcon
python
encode__django-rest-framework
tests/test_viewsets.py
{ "start": 3026, "end": 3102 }
class ____: def __init__(self): self.mapping = {}
ThingWithMapping
python
huggingface__transformers
src/transformers/models/whisper/modeling_whisper.py
{ "start": 8315, "end": 9628 }
class ____(nn.Embedding): def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None): super().__init__(num_positions, embedding_dim) def forward(self, input_ids, past_key_values_length=0, position_ids=None): if position_ids is None: return self.wei...
WhisperPositionalEmbedding
python
PrefectHQ__prefect
tests/server/schemas/test_schedules.py
{ "start": 25445, "end": 30070 }
class ____: async def test_rrule_schedule_hourly_daylight_savings_time_forward_with_UTC( self, ): """ On 3/11/2018, at 2am, America/New_York switched clocks forward an hour. """ dt = datetime(2018, 3, 11, 4, tzinfo=ZoneInfo("UTC")) s = RRuleSchedule.from_rrule(rru...
TestRRuleScheduleDaylightSavingsTime
python
scrapy__scrapy
scrapy/spiders/feed.py
{ "start": 4315, "end": 6413 }
class ____(Spider): """Spider for parsing CSV feeds. It receives a CSV file in a response; iterates through each of its rows, and calls parse_row with a dict containing each field's data. You can set some options regarding the CSV file, such as the delimiter, quotechar and the file's headers. "...
CSVFeedSpider
python
great-expectations__great_expectations
great_expectations/core/configuration.py
{ "start": 1237, "end": 1568 }
class ____(Schema): REMOVE_KEYS_IF_NONE = ["id", "name"] @post_dump def filter_none(self, data: dict, **kwargs) -> dict: return { key: value for key, value in data.items() if key not in AbstractConfigSchema.REMOVE_KEYS_IF_NONE or value is not None }
AbstractConfigSchema
python
django-haystack__django-haystack
test_haystack/test_query.py
{ "start": 3464, "end": 14312 }
class ____(TestCase): fixtures = ["base_data.json", "bulk_data.json"] @classmethod def setUpClass(cls): for connection in connections.all(): connection.get_unified_index().reset() super().setUpClass() def setUp(self): super().setUp() self.bsq = BaseSearchQue...
BaseSearchQueryTestCase
python
boto__boto3
tests/unit/dynamodb/test_transform.py
{ "start": 952, "end": 2541 }
class ____(unittest.TestCase): def setUp(self): self.target_shape = 'MyShape' self.original_value = 'orginal' self.transformed_value = 'transformed' self.transformer = ParameterTransformer() self.json_model = {} self.nested_json_model = {} self.setup_models() ...
BaseTransformationTest
python
django__django
tests/admin_views/admin.py
{ "start": 14552, "end": 15025 }
class ____(admin.ModelAdmin): list_display = ["title", "slug"] prepopulated_fields = {"slug": ("title",)} inlines = [SubPostInline] def get_readonly_fields(self, request, obj=None): if obj and obj.published: return ("slug",) return self.readonly_fields def get_prepopul...
PrePopulatedPostAdmin
python
readthedocs__readthedocs.org
readthedocs/api/v3/views.py
{ "start": 4079, "end": 4875 }
class ____: """ Django REST Framework settings for APIv3. Override global DRF settings for APIv3 in particular. All ViewSet should inherit from this class to share/apply the same settings all over the APIv3. .. note:: The only settings used from ``settings.REST_FRAMEWORK`` is ``DE...
APIv3Settings
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-scrapegraph/llama_index/tools/scrapegraph/base.py
{ "start": 258, "end": 5750 }
class ____(BaseToolSpec): """ ScrapeGraph tool specification for web scraping operations. This tool provides access to ScrapeGraph AI's web scraping capabilities, including smart scraping, content conversion to markdown, search functionality, and basic HTML scraping with various options. """ ...
ScrapegraphToolSpec