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
pytorch__pytorch
torch/autograd/variable.py
{ "start": 256, "end": 391 }
class ____(torch._C._LegacyVariableBase, metaclass=VariableMeta): # type: ignore[misc] _execution_engine = ImperativeEngine()
Variable
python
pytorch__pytorch
torch/nn/attention/experimental/_paged_attention.py
{ "start": 468, "end": 13026 }
class ____: """ PagedAttention supports flex attention inference with a large batch size. With PagedAttention, a batch of key/value tensors with varying kv length is split into tensor blocks of fixed length and cached in a compact way. Thus we can avoid redundant memory consumption due to varying kv...
PagedAttention
python
pytorch__pytorch
test/test_serialization.py
{ "start": 3664, "end": 3772 }
class ____: class Nested: pass def up_size(size): return (*size[:-1], size[-1] * 2)
ClassBMock
python
huggingface__transformers
src/transformers/models/bert_generation/tokenization_bert_generation.py
{ "start": 985, "end": 4370 }
class ____(SentencePieceBackend): """ Construct a BertGeneration tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece). This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regardi...
BertGenerationTokenizer
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_summarization.py
{ "start": 547, "end": 982 }
class ____(BaseChatModel): """Mock chat model for testing.""" def invoke(self, prompt): # type: ignore[no-untyped-def] return AIMessage(content="Generated summary") def _generate(self, messages, **kwargs): # type: ignore[no-untyped-def] return ChatResult(generations=[ChatGeneration(messa...
MockChatModel
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query_type_annotation.py
{ "start": 436, "end": 885 }
class ____: def test2_f1(self, taint_1: Test2_T1, taint_2: Test2_T2, no_taint_1: Test2_Foo): # self should not be tainted pass def test2_f2(self, taint_1: Dict[int, Test2_T1]): # self should not be tainted pass def test2_f3(self, no_taint_1: int, no_taint_2: str): #...
Test2_C
python
huggingface__transformers
src/transformers/utils/hub.py
{ "start": 38898, "end": 39554 }
class ____: """ Internal class to keep track of a push in progress (which might contain multiple `Future` jobs). """ def __init__(self, jobs: futures.Future | None = None) -> None: self.jobs = [] if jobs is None else jobs def is_done(self): return all(job.done() for job in self.job...
PushInProgress
python
django__django
tests/admin_utils/models.py
{ "start": 2167, "end": 2201 }
class ____(VehicleMixin): pass
Car
python
pytorch__pytorch
torch/export/_wrapper_utils.py
{ "start": 15, "end": 271 }
class ____(torch.nn.Module): def __init__(self, f): # type: ignore[no-untyped-def] super().__init__() self.f = f def forward(self, *args, **kwargs): # type: ignore[no-untyped-def] return self.f(*args, **kwargs)
_WrapperModule
python
pyqtgraph__pyqtgraph
pyqtgraph/flowchart/library/Operators.py
{ "start": 2032, "end": 2216 }
class ____(UniOpNode): """Returns abs(Inp). Does not check input types.""" nodeName = 'Abs' def __init__(self, name): UniOpNode.__init__(self, name, '__abs__')
AbsNode
python
tiangolo__fastapi
tests/test_multi_body_errors.py
{ "start": 226, "end": 8267 }
class ____(BaseModel): name: str age: condecimal(gt=Decimal(0.0)) # type: ignore @app.post("/items/") def save_item_no_body(item: List[Item]): return {"item": item} client = TestClient(app) def test_put_correct_body(): response = client.post("/items/", json=[{"name": "Foo", "age": 5}]) assert...
Item
python
sqlalchemy__sqlalchemy
test/sql/test_insert.py
{ "start": 2385, "end": 38526 }
class ____(_InsertTestBase, fixtures.TablesTest, AssertsCompiledSQL): __dialect__ = "default_enhanced" @testing.combinations( ((), ("z",), ()), (("x",), (), ()), (("x",), ("y",), ("x", "y")), (("x", "y"), ("y",), ("x", "y")), ) def test_return_defaults_generative( ...
InsertTest
python
pennersr__django-allauth
allauth/socialaccount/providers/discogs/provider.py
{ "start": 218, "end": 433 }
class ____(ProviderAccount): def get_username(self): return self.account.extra_data.get("username") def get_profile_url(self): return self.account.extra_data.get("resource_url")
DiscogsAccount
python
pytorch__pytorch
torch/testing/_internal/common_utils.py
{ "start": 233134, "end": 243287 }
class ____(TestCase): def assertEqualIgnoringNestedInts(self, a, b): # unbinding NJTs allows us to compare them as essentially equal without # caring about exact nested int comparison def _unbind_njts(x): if isinstance(x, torch.Tensor) and x.is_nested and x.layout == torch.jagged...
NestedTensorTestCase
python
django__django
django/db/backends/base/client.py
{ "start": 30, "end": 989 }
class ____: """Encapsulate backend-specific methods for opening a client shell.""" # This should be a string representing the name of the executable # (e.g., "psql"). Subclasses must override this. executable_name = None def __init__(self, connection): # connection is an instance of BaseDa...
BaseDatabaseClient
python
sympy__sympy
sympy/codegen/ast.py
{ "start": 52015, "end": 52702 }
class ____(Token): r""" Represents print command in the code. Parameters ========== formatstring : str *args : Basic instances (or convertible to such through sympify) Examples ======== >>> from sympy.codegen.ast import Print >>> from sympy import pycode >>> print(pycode(Prin...
Print
python
matplotlib__matplotlib
tools/run_examples.py
{ "start": 438, "end": 2985 }
class ____: def __init__(self, backend, elapsed, failed): self.backend = backend self.elapsed = elapsed self.failed = failed def __str__(self): s = "" if self.backend: s += f"{self.backend}: " s += f"{self.elapsed}ms" if self.failed: ...
RunInfo
python
spack__spack
lib/spack/spack/llnl/util/tty/color.py
{ "start": 13960, "end": 14599 }
class ____: def __init__(self, stream, color=None): self._stream = stream self._color = color def write(self, string, **kwargs): raw = kwargs.get("raw", False) raw_write = getattr(self._stream, "write") color = self._color if self._color is None: if ...
ColorStream
python
xlwings__xlwings
xlwings/main.py
{ "start": 744, "end": 2594 }
class ____: def __init__(self, impl): self.impl = impl @property def api(self): """ Returns the native object (``pywin32`` or ``appscript`` obj) of the engine being used. """ return self.impl.api def __call__(self, name_or_index): return self._wr...
Collection
python
kamyu104__LeetCode-Solutions
Python/find-a-value-of-a-mysterious-function-closest-to-target.py
{ "start": 1492, "end": 1890 }
class ____(object): def closestToTarget(self, arr, target): """ :type arr: List[int] :type target: int :rtype: int """ result, dp = float("inf"), set() # at most O(logm) dp states for x in arr: dp = {x}|{f&x for f in dp} for f in dp: ...
Solution2
python
huggingface__transformers
tests/models/idefics3/test_modeling_idefics3.py
{ "start": 1421, "end": 5267 }
class ____: def __init__( self, parent, is_training=True, batch_size=2, scale_factor=2, num_images=2, vision_config={ "image_size": 16, "patch_size": 4, "hidden_size": 32, "num_hidden_layers": 2, "num...
Idefics3VisionText2TextModelTester
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py
{ "start": 9496, "end": 10260 }
class ____(BaseConfig): """Full refresh test config Attributes: ignored_fields for each stream, list of fields path. Path should be in format "object_key/object_key2" """ config_path: str = config_path configured_catalog_path: Optional[str] = configured_catalog_path timeout_seconds: in...
FullRefreshConfig
python
prabhupant__python-ds
data_structures/circular_linked_list/traversal.py
{ "start": 0, "end": 706 }
class ____(): def __init__(self, val): self.val = val self.next = None def push(head, val): if not head: head = Node(val) head.next = head return curr = head while curr: if curr.next == head: break curr = curr.next curr.next = Nod...
Node
python
numba__numba
numba/tests/test_parallel_backend.py
{ "start": 2869, "end": 3109 }
class ____(runnable): def __call__(self): cfunc = jit(**self._options)(linalg) a = 4 b = 10 expected = linalg(a, b) got = cfunc(a, b) np.testing.assert_allclose(expected, got)
linalg_runner
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 362929, "end": 363861 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateProjectV2ItemFieldValue""" __schema__ = github_schema __field_names__ = ("project_id", "item_id", "field_id", "value", "client_mutation_id") project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId") """The ...
UpdateProjectV2ItemFieldValueInput
python
airbytehq__airbyte
airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/test_sponsored_streams.py
{ "start": 1639, "end": 17115 }
class ____(TestCase): @property def _config(self): return ConfigBuilder().build() def _given_oauth_and_profiles(self, http_mocker: HttpMocker, config: dict) -> None: """ Authenticate and get profiles """ http_mocker.post( OAuthRequestBuilder.oauth_endpoin...
TestSponsoredBrandsStreamsFullRefresh
python
apache__airflow
providers/snowflake/src/airflow/providers/snowflake/operators/snowflake.py
{ "start": 8468, "end": 11878 }
class ____(SQLIntervalCheckOperator): """ Checks that the metrics given as SQL expressions are within tolerance of the ones from days_back before. This method constructs a query like so :: SELECT {metrics_threshold_dict_key} FROM {table} WHERE {date_filter_column}=<date> :param table:...
SnowflakeIntervalCheckOperator
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/group_by_reducer_test.py
{ "start": 1485, "end": 7693 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.default_test_combinations()) def testSum(self): reducer = grouping.Reducer( init_func=lambda _: np.int64(0), reduce_func=lambda x, y: x + y, finalize_func=lambda x: x) for i in range(1, 1...
GroupByReducerTest
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/base.py
{ "start": 7043, "end": 7976 }
class ____(Expr): __slots__ = ("index", "table_ref") _non_child = ("dtype", "index", "table_ref") index: int table_ref: plc.expressions.TableReference def __init__( self, dtype: DataType, index: int, table_ref: plc.expressions.TableReference, column: Expr, ...
ColRef
python
python__mypy
mypyc/irbuild/for_helpers.py
{ "start": 42567, "end": 43680 }
class ____(ForGenerator): """Generate optimized IR for a for loop counting from 0 to infinity.""" def init(self) -> None: builder = self.builder # Create a register to store the state of the loop index and # initialize this register along with the loop index to 0. zero = Integer...
ForInfiniteCounter
python
dagster-io__dagster
examples/docs_projects/project_atproto_dashboard/src/project_atproto_dashboard/defs/modeling.py
{ "start": 474, "end": 1542 }
class ____(DagsterDbtTranslator): def get_asset_spec( self, manifest: Mapping[str, Any], unique_id: str, project: Optional[DbtProject], ) -> dg.AssetSpec: dbt_resource_props = get_node(manifest, unique_id) asset_path = dbt_resource_props["fqn"][1:-1] if as...
CustomizedDagsterDbtTranslator
python
huggingface__transformers
tests/quantization/bnb/test_mixed_int8.py
{ "start": 24839, "end": 26256 }
class ____(BaseMixedInt8Test): def setUp(self): super().setUp() def tearDown(self): r""" TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-releas...
MixedInt8TestPipeline
python
huggingface__transformers
src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py
{ "start": 10183, "end": 10962 }
class ____(nn.Module): def __init__(self, intermediate_size, config): super().__init__() embed_dim = config.hidden_size self.c_fc = nn.Linear(embed_dim, intermediate_size) self.c_proj = nn.Linear(intermediate_size, embed_dim) self.act = ACT2FN[config.activation_function] ...
GPTBigCodeMLP
python
apache__airflow
providers/cncf/kubernetes/tests/unit/cncf/kubernetes/operators/test_resource.py
{ "start": 2062, "end": 10172 }
class ____: @pytest.fixture(autouse=True) def setup_tests(self, dag_maker): self._default_client_patch = patch(f"{HOOK_CLASS}._get_default_client") self._default_client_mock = self._default_client_patch.start() yield patch.stopall() def setup_method(self): args = {...
TestKubernetesXResourceOperator
python
openai__openai-python
tests/api_resources/beta/test_assistants.py
{ "start": 9435, "end": 19106 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assis...
TestAsyncAssistants
python
bokeh__bokeh
src/bokeh/models/textures.py
{ "start": 1889, "end": 2197 }
class ____(Texture): ''' ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) code = Required(String, help=""" A snippet of JavaScript code to execute in the browser. """)
CanvasTexture
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataproc.py
{ "start": 125862, "end": 129188 }
class ____(GoogleCloudBaseOperator): """ Get the batch workload resource representation. :param batch_id: Required. The ID to use for the batch, which will become the final component of the batch's resource name. This value must be 4-63 characters. Valid characters are /[a-z][0-9]-/. :p...
DataprocGetBatchOperator
python
gevent__gevent
src/greentest/3.14/test_socket.py
{ "start": 200041, "end": 200693 }
class ____(ThreadedTCPSocketTest): def testClose(self): conn, _ = self.serv.accept() read, _, _ = select.select([conn], [], [], support.SHORT_TIMEOUT) self.assertEqual(read, [conn]) self.assertEqual(conn.recv(1), b'x') conn.close() # Calling close() many times shoul...
TCPCloserTest
python
pytorch__pytorch
torch/nn/modules/fold.py
{ "start": 6671, "end": 13227 }
class ____(Module): ( r"""Extracts sliding local blocks from a batched input tensor. Consider a batched :attr:`input` tensor of shape :math:`(N, C, *)`, where :math:`N` is the batch dimension, :math:`C` is the channel dimension, and :math:`*` represent arbitrary spatial dimensions. This operati...
Unfold
python
apache__airflow
providers/standard/tests/unit/standard/operators/test_weekday.py
{ "start": 2611, "end": 14134 }
class ____: """ Tests for BranchDayOfWeekOperator """ @classmethod def setup_class(cls): with create_session() as session: session.query(DagRun).delete() session.query(TI).delete() session.query(XCom).delete() def _assert_task_ids_match_states(self, ...
TestBranchDayOfWeekOperator
python
pytorch__pytorch
test/jit/test_hooks_modules.py
{ "start": 1201, "end": 1551 }
class ____(torch.nn.Module): def __init__(self, name: str, submodule_name: str): super().__init__() self.name = name self.submodule = SubmoduleForwardSingleInput(submodule_name) def forward(self, input: str): input = input + "_outermod" return self.submodule.forward(inpu...
ModuleDirectforwardSubmodCall
python
pytorch__pytorch
torch/_numpy/_funcs.py
{ "start": 1587, "end": 2097 }
class ____: """ Written by Konrad Hinsen <hinsen@cnrs-orleans.fr> last revision: 1999-7-23 Cosmetic changes by T. Oliphant 2001 """ def __init__(self, maketuple): self.maketuple = maketuple def __getitem__(self, item): if self.maketuple and not isinstance(item, tuple): ...
IndexExpression
python
matplotlib__matplotlib
lib/matplotlib/cbook.py
{ "start": 69842, "end": 82788 }
class ____(collections.abc.MutableSet): def __init__(self): self._od = collections.OrderedDict() def __contains__(self, key): return key in self._od def __iter__(self): return iter(self._od) def __len__(self): return len(self._od) def add(self, key): self....
_OrderedSet
python
PrefectHQ__prefect
src/prefect/server/api/clients.py
{ "start": 2388, "end": 8190 }
class ____(BaseClient): async def read_deployment_raw(self, deployment_id: UUID) -> Response: return await self._http_client.get(f"/deployments/{deployment_id}") async def read_deployment( self, deployment_id: UUID ) -> Optional[DeploymentResponse]: try: response = await...
OrchestrationClient
python
ray-project__ray
python/ray/serve/_private/test_utils.py
{ "start": 21023, "end": 27145 }
class ____: def __init__(self, target: int): self.count = 0 self.target = target self.ready_event = asyncio.Event() def inc(self): self.count += 1 if self.count == self.target: self.ready_event.set() async def wait(self): await self.ready_event.w...
Counter
python
Textualize__textual
docs/examples/styles/grid_size_columns.py
{ "start": 100, "end": 393 }
class ____(App): CSS_PATH = "grid_size_columns.tcss" def compose(self): yield Grid( Label("1"), Label("2"), Label("3"), Label("4"), Label("5"), ) if __name__ == "__main__": app = MyApp() app.run()
MyApp
python
google__pytype
pytype/tools/xref/parse_args.py
{ "start": 209, "end": 2642 }
class ____(arg_parser.Parser): """Subclass the tool parser to retain the raw input field.""" def process(self, tool_args, pytype_args): # Needed for the debug indexer tool_args.raw_input = pytype_args.input[0] def make_parser(): """Make parser for command line args. Returns: A Parser object. "...
XrefParser
python
openai__openai-python
src/openai/_module_client.py
{ "start": 2790, "end": 2929 }
class ____(LazyProxy["Responses"]): @override def __load__(self) -> Responses: return _load_client().responses
ResponsesProxy
python
getsentry__sentry
src/sentry/search/events/fields.py
{ "start": 44940, "end": 45267 }
class ____(StringArg): def normalize(self, value: str, params: ParamsType, combinator: Combinator | None) -> str: value = super().normalize(value, params, combinator) # SnQL interprets string types as string, so strip the # quotes added in StringArg.normalize. return value[1:-1]
SnQLStringArg
python
urllib3__urllib3
test/with_dummyserver/test_https.py
{ "start": 46525, "end": 46672 }
class ____(BaseTestHTTPS): tls_protocol_name = "TLSv1.1" certs = TLSv1_1_CERTS @pytest.mark.usefixtures("requires_tlsv1_2")
TestHTTPS_TLSv1_1
python
great-expectations__great_expectations
great_expectations/data_context/data_context/cloud_data_context.py
{ "start": 3816, "end": 3906 }
class ____: user_id: uuid.UUID workspaces: list[Workspace] @public_api
CloudUserInfo
python
doocs__leetcode
solution/3000-3099/3066.Minimum Operations to Exceed Threshold Value II/Solution.py
{ "start": 0, "end": 286 }
class ____: def minOperations(self, nums: List[int], k: int) -> int: heapify(nums) ans = 0 while len(nums) > 1 and nums[0] < k: x, y = heappop(nums), heappop(nums) heappush(nums, x * 2 + y) ans += 1 return ans
Solution
python
catalyst-team__catalyst
catalyst/callbacks/misc.py
{ "start": 12699, "end": 15039 }
class ____(Callback): """Executes only a pipeline part from the run. Args: num_batch_steps: number of batches to iterate in epoch num_epoch_steps: number of epoch to perform in an experiment Minimal working example (Notebook API): .. code-block:: python import torch f...
CheckRunCallback
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor26.py
{ "start": 525, "end": 1186 }
class ____(Generic[T, U]): def __init__(self): pass def test2(self) -> None: x1: Test2[U, T] x2: Test2[T, T] x3: Test2[T, U] x1 = Test2[U, T]() # This should generate an error. x2 = Test2[U, T]() # This should generate an error. x3 = Test...
Test2
python
scipy__scipy
scipy/optimize/_nonlin.py
{ "start": 37726, "end": 38816 }
class ____(GenericBroyden): """ Find a root of a function, using a scalar Jacobian approximation. .. warning:: This algorithm may be useful for specific problems, but whether it will work may depend strongly on the problem. Parameters ---------- %(params_basic)s alpha : floa...
LinearMixing
python
kubernetes-client__python
kubernetes/client/models/v1_validating_admission_policy_status.py
{ "start": 383, "end": 5781 }
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...
V1ValidatingAdmissionPolicyStatus
python
realpython__materials
build-a-gui-with-wxpython/mp3_tag_editor.py
{ "start": 38, "end": 1531 }
class ____(wx.Dialog): def __init__(self, mp3): title = 'Editing "{title}"'.format(title=mp3.tag.title) super().__init__(parent=None, title=title) self.mp3 = mp3 self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.artist = wx.TextCtrl(self, value=self.mp3.tag.artist) s...
EditDialog
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataflow.py
{ "start": 50078, "end": 52942 }
class ____(GoogleCloudBaseOperator): """ Deletes a Dataflow Data Pipeline. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DataflowDeletePipelineOperator` :param pipeline_name: The display name of the pipeline. In example ...
DataflowDeletePipelineOperator
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/conftest.py
{ "start": 493, "end": 1275 }
class ____(AmberSnapshotExtension): @classmethod def get_snapshot_name( # pyright: ignore[reportIncompatibleMethodOverride] cls, *, index: "SnapshotIndex", test_location: "PyTestLocation", ) -> str: snapshot_name = test_location.snapshot_name # Exclude any o...
SharedSnapshotExtension
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 14896, "end": 16125 }
class ____(Operation): def __init__(self, approximate=True, *, name=None): super().__init__(name=name) self.approximate = approximate def call(self, x): return backend.nn.gelu(x, self.approximate) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) ...
Gelu
python
ray-project__ray
python/ray/serve/tests/unit/test_proxy_state.py
{ "start": 1159, "end": 25335 }
class ____(ProxyWrapper): def __init__(self, *args, **kwargs): self.actor_handle = FakeProxyActor(*args, **kwargs) self.is_ready_response = None self.is_healthy_response = None self.is_drained_response = False self.worker_id = "mock_worker_id" self.log_file_path = "mo...
FakeProxyWrapper
python
pexpect__pexpect
tests/test_popen_spawn.py
{ "start": 1087, "end": 5018 }
class ____ (PexpectTestCase.PexpectTestCase): def test_expect_basic(self): p = PopenSpawn('cat', timeout=5) p.sendline(b'Hello') p.sendline(b'there') p.sendline(b'Mr. Python') p.expect(b'Hello') p.expect(b'there') p.expect(b'Mr. Python') p.sendeof() ...
ExpectTestCase
python
streamlit__streamlit
lib/tests/streamlit/elements/layouts_test.py
{ "start": 11222, "end": 14358 }
class ____(DeltaGeneratorTestCase): def test_label_required(self): """Test that label is required""" with pytest.raises(TypeError): st.expander() def test_just_label(self): """Test that it can be called with no params""" expander = st.expander("label") with ...
ExpanderTest
python
getsentry__sentry
tests/sentry/uptime/endpoints/test_project_uptime_alert_index.py
{ "start": 493, "end": 628 }
class ____(UptimeAlertBaseEndpointTest): endpoint = "sentry-api-0-project-uptime-alert-index"
ProjectUptimeAlertIndexBaseEndpointTest
python
django-haystack__django-haystack
test_haystack/test_query.py
{ "start": 14312, "end": 14507 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, model_attr="key") def get_model(self): return CharPKMockModel
CharPKMockModelSearchIndex
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_inline_schemas/pipeline.py
{ "start": 8304, "end": 14656 }
class ____: ref: str file_path: str def copy_directory(src: Path, dest: Path) -> None: if dest.exists(): shutil.rmtree(dest) shutil.copytree(src, dest) def _has_subdirectory(directory: Path) -> bool: # Iterate through all items in the directory for entry in directory.iterdir(): ...
JsonLoaderNode
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overloadOverlap1.py
{ "start": 6555, "end": 6604 }
class ____: ... TE1 = TypeVar("TE1", bound=E1)
E1
python
sphinx-doc__sphinx
sphinx/util/template.py
{ "start": 2562, "end": 3543 }
class ____(SphinxRenderer): def __init__( self, template_path: Sequence[str | os.PathLike[str]] | None = None, latex_engine: str | None = None, ) -> None: if template_path is None: template_path = (_LATEX_TEMPLATES_PATH,) super().__init__(template_path) ...
LaTeXRenderer
python
langchain-ai__langchain
libs/langchain/langchain_classic/evaluation/scoring/eval_chain.py
{ "start": 13253, "end": 15454 }
class ____(ScoreStringEvalChain): """A chain for scoring the output of a model on a scale of 1-10. Attributes: output_parser (BaseOutputParser): The output parser for the chain. """ @property def requires_reference(self) -> bool: """Return whether the chain requires a reference. ...
LabeledScoreStringEvalChain
python
sqlalchemy__sqlalchemy
test/engine/test_reflection.py
{ "start": 76027, "end": 80566 }
class ____(AssertsCompiledSQL, fixtures.TestBase): __dialect__ = "default" @testing.fixture def tab_wo_fks(self, connection, metadata): meta = metadata foo = Table( "foo", meta, *[ Column(n, sa.String(30)) for n in ["a", "b...
IncludeColsFksTest
python
kamyu104__LeetCode-Solutions
Python/count-distinct-integers-after-removing-zeros.py
{ "start": 48, "end": 690 }
class ____(object): def countDistinct(self, n): """ :type n: int :rtype: int """ def reverse(n): result, base = 0, 1 while n: n, r = divmod(n, 10) result = result*10+r base *= 9 return result,...
Solution
python
tornadoweb__tornado
tornado/test/gen_test.py
{ "start": 20086, "end": 22437 }
class ____(AsyncTestCase): @gen_test def test_timeout(self): with self.assertRaises(gen.TimeoutError): yield gen.with_timeout(datetime.timedelta(seconds=0.1), Future()) @gen_test def test_completes_before_timeout(self): future = Future() # type: Future[str] self.io_...
WithTimeoutTest
python
PyCQA__pylint
tests/functional/i/invalid/invalid_index_returned.py
{ "start": 720, "end": 852 }
class ____: """ __index__ returns str """ def __index__(self): # [invalid-index-returned] return "42"
SecondBadIndex
python
realpython__materials
arcade-platformer/arcade_platformer/14_enemies.py
{ "start": 7819, "end": 21799 }
class ____(arcade.View): def __init__(self) -> None: super().__init__() # These lists will hold different sets of sprites self.coins = None self.background = None self.walls = None self.ladders = None self.goals = None self.enemies = None # O...
PlatformerView
python
keras-team__keras
keras/src/callbacks/backup_and_restore_test.py
{ "start": 206, "end": 902 }
class ____(callbacks.Callback): """A callback to intentionally interrupt training.""" def __init__(self, steps_int, epoch_int): self.batch_count = 0 self.epoch_count = 0 self.steps_int = steps_int self.epoch_int = epoch_int def on_epoch_end(self, epoch, log=None): s...
InterruptingCallback
python
pypa__setuptools
setuptools/_vendor/jaraco/collections/__init__.py
{ "start": 22828, "end": 23175 }
class ____: """ A collection "containing" every possible thing. >>> 'foo' in Everything() True >>> import random >>> random.randint(1, 999) in Everything() True >>> random.choice([None, 'foo', 42, ('a', 'b', 'c')]) in Everything() True """ def __contains__(self, other): ...
Everything
python
run-llama__llama_index
llama-index-core/tests/agent/workflow/test_agent_with_structured_output.py
{ "start": 663, "end": 3554 }
class ____(LLM): def __init__(self, responses: List[ChatMessage], structured_response: str): super().__init__() self._responses = responses self._structured_response = structured_response self._response_index = 0 @property def metadata(self) -> LLMMetadata: return LL...
TestLLM
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py
{ "start": 36589, "end": 37712 }
class ____(TestConnectionEndpoint): def test_should_respond_204(self, test_client, session): response = test_client.post("/connections/defaults") assert response.status_code == 204 assert response.content == b"" _check_last_log(session, dag_id=None, event="create_default_connections"...
TestCreateDefaultConnections
python
huggingface__transformers
tests/models/opt/test_modeling_opt.py
{ "start": 7241, "end": 13707 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( (OPTModel, OPTForCausalLM, OPTForSequenceClassification, OPTForQuestionAnswering) if is_torch_available() else () ) pipeline_model_mapping = ( { "fea...
OPTModelTest
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/int.py
{ "start": 26052, "end": 31915 }
class ____(BaseInt[np.dtypes.Int32DType, np.int32], HasEndianness): """ A Zarr data type for arrays containing 32-bit signed integers. Wraps the [`np.dtypes.Int32DType`][numpy.dtypes.Int32DType] data type. Scalars for this data type are instances of [`np.int32`][numpy.int32]. Attributes ------...
Int32
python
sqlalchemy__sqlalchemy
test/orm/test_options.py
{ "start": 2658, "end": 3471 }
class ____: def _make_path(self, path): r = [] for i, item in enumerate(path): if i % 2 == 0: item = inspect(item) else: if isinstance(item, str): item = inspect(r[-1]).mapper.attrs[item] r.append(item) r...
PathTest
python
openai__gym
gym/spaces/box.py
{ "start": 939, "end": 12732 }
class ____(Space[np.ndarray]): r"""A (possibly unbounded) box in :math:`\mathbb{R}^n`. Specifically, a Box represents the Cartesian product of n closed intervals. Each interval has the form of one of :math:`[a, b]`, :math:`(-\infty, b]`, :math:`[a, \infty)`, or :math:`(-\infty, \infty)`. There are...
Box
python
pytorch__pytorch
test/distributed/fsdp/test_wrap.py
{ "start": 35587, "end": 39531 }
class ____(TestCase): def test_validate_frozen_params(self): """Tests the method ``_validate_frozen_params()``.""" for use_orig_params in [True, False]: self._test_validate_frozen_params(use_orig_params) def _test_validate_frozen_params(self, use_orig_params: bool): model = ...
TestWrapUtils
python
PrefectHQ__prefect
tests/server/utilities/test_text_search_parser.py
{ "start": 19364, "end": 21446 }
class ____: """Test realistic query parsing scenarios end-to-end""" @pytest.mark.parametrize( "query, expected", [ # Simple cases ("error", TextSearchQuery(include=["error"], exclude=[], required=[])), ("-debug", TextSearchQuery(include=[], exclude=["debug"],...
TestIntegrationScenarios
python
pallets__quart
src/quart/sessions.py
{ "start": 4629, "end": 8752 }
class ____(SessionInterface): """A Session interface that uses cookies as storage. This will store the data on the cookie in plain text, but with a signature to prevent modification. """ digest_method = staticmethod(hashlib.sha1) key_derivation = "hmac" salt = "cookie-session" serializ...
SecureCookieSessionInterface
python
tensorflow__tensorflow
tensorflow/python/util/dispatch_test.py
{ "start": 16191, "end": 16351 }
class ____(extension_type.ExtensionType): """Simple ExtensionType for testing v2 dispatch.""" values: tensor_lib.Tensor mask: tensor_lib.Tensor
MaskedTensor
python
catalyst-team__catalyst
catalyst/callbacks/metrics/r2_squared.py
{ "start": 112, "end": 2312 }
class ____(LoaderMetricCallback): """R2 Squared metric callback. Args: input_key: input key to use for r2squared calculation, specifies our ``y_true`` target_key: output key to use for r2squared calculation, specifies our ``y_pred`` prefix: metric prefix suffix: metric suffix ...
R2SquaredCallback
python
astropy__astropy
astropy/io/ascii/html.py
{ "start": 1495, "end": 3149 }
class ____(core.BaseInputter): """ Input lines of HTML in a valid form. This requires `BeautifulSoup <http://www.crummy.com/software/BeautifulSoup/>`_ to be installed. """ def process_lines(self, lines): """ Convert the given input into a list of SoupString rows for fur...
HTMLInputter
python
pytorch__pytorch
torchgen/selective_build/operator.py
{ "start": 434, "end": 6521 }
class ____: # The name of the operator. This includes the aten::, etc... prefix # The operator name may or may not have the overload name. If this # operator name does not specify an overload name, the way to determine # if this entry refers to the family of operators with this base name # or just t...
SelectiveBuildOperator
python
facelessuser__pymdown-extensions
tests/test_extensions/test_superfences.py
{ "start": 10968, "end": 12474 }
class ____(util.MdCase): """Test highlight line wraps.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'anchor_linenums': True, 'linenums_style': 'inline' } } def test_linespans(self): """Te...
TestHighlightAnchorLinenumInline
python
ray-project__ray
python/ray/_common/usage/usage_lib.py
{ "start": 5658, "end": 6001 }
class ____: """Usage stats to write to `USAGE_STATS_FILE` We are writing extra metadata such as the status of report to this file. """ usage_stats: UsageStatsToReport # Whether or not the last report succeeded. success: bool # The error message of the last report if it happens. err...
UsageStatsToWrite
python
django-extensions__django-extensions
tests/testapp/models.py
{ "start": 5457, "end": 5621 }
class ____(PostWithUniqField): new_field = models.CharField(max_length=10) class Meta: app_label = "django_extensions"
InheritedFromPostWithUniqField
python
PyCQA__pylint
tests/functional/i/invalid/invalid_bool_returned.py
{ "start": 415, "end": 521 }
class ____(type): def __bool__(cls): return True @six.add_metaclass(BoolMetaclass)
BoolMetaclass
python
patrick-kidger__equinox
equinox/nn/_conv.py
{ "start": 26651, "end": 27741 }
class ____(ConvTranspose): """As [`equinox.nn.ConvTranspose`][] with `num_spatial_dims=3`.""" def __init__( self, in_channels: int, out_channels: int, kernel_size: int | Sequence[int], stride: int | Sequence[int] = (1, 1, 1), output_padding: int | Sequence[int] =...
ConvTranspose3d
python
ray-project__ray
python/ray/data/_internal/block_batching/iter_batches.py
{ "start": 973, "end": 17930 }
class ____: """Defines an iterator pipeline to convert a stream of block object references into a stream of formatted batches ready to be consumed by the user. This takes a block iterator and creates batch_size batches, slicing, unioning, shuffling, prefetching, and formatting blocks as needed. Th...
BatchIterator
python
google__pytype
pytype/rewrite/frame_test.py
{ "start": 628, "end": 2191 }
class ____(test_utils.ContextfulTestBase): def _make_frame(self, src: str, name: str = '__main__') -> frame_lib.Frame: code = test_utils.parse(src) if name == '__main__': module_globals = self.ctx.abstract_loader.get_module_globals() initial_locals = initial_globals = { name: value.to_v...
FrameTestBase
python
django-haystack__django-haystack
test_haystack/core/models.py
{ "start": 1242, "end": 1492 }
class ____(models.Model): author = models.CharField(max_length=255) editor = models.CharField(max_length=255) pub_date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return self.author
AFourthMockModel
python
numba__numba
numba/tests/test_debug.py
{ "start": 3294, "end": 3636 }
class ____(DebugTestBase): func_name = 'simple_nopython' def compile_simple_nopython(self): with captured_stdout() as out: cfunc = njit((types.int64,))(simple_nopython) # Sanity check compiled function self.assertPreciseEqual(cfunc(2), 3) return out.getvalue...
FunctionDebugTestBase
python
skorch-dev__skorch
examples/nuclei_image_segmentation/dataset.py
{ "start": 663, "end": 2821 }
class ____(Dataset): """Creates patches of cells. Parameters ---------- base_dataset: CellsDataset Dataset of cells patch_size: tuple of ints (default=(256, 256)) The size of each patch random_flips: bool (default=False) If true, patches and masks will be randomly flippe...
PatchedDataset
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py
{ "start": 1271, "end": 18648 }
class ____(ABC, Generic[T_Packable]): """Utility class to wrap metadata values passed into Dagster events so that they can be displayed in the Dagster UI and other tooling. .. code-block:: python @op def emit_metadata(context, df): yield AssetMaterialization( as...
MetadataValue