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
django__django
tests/template_tests/filter_tests/test_truncatewords.py
{ "start": 1032, "end": 1840 }
class ____(SimpleTestCase): def test_truncate(self): self.assertEqual(truncatewords("A sentence with a few words in it", 1), "A …") def test_truncate2(self): self.assertEqual( truncatewords("A sentence with a few words in it", 5), "A sentence with a few …", ) ...
FunctionTests
python
mitmproxy__pdoc
pdoc/__init__.py
{ "start": 10635, "end": 15772 }
class ____(BaseModel): @computed_field(description="Docs for field a.") @property def a(self) -> int: ... ``` ## ...render math formulas? Run `pdoc --math`, and pdoc will render formulas in your docstrings. See [`math_demo`](https://pdoc.dev/docs/math/math_demo.html) for details. ## ...render Me...
ComputedFoo
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclass5.py
{ "start": 1122, "end": 1203 }
class ____: x: int foo3 = F(3) < F(3) reveal_type(foo3, expected_text="bool")
F
python
modin-project__modin
modin/core/storage_formats/pandas/parsers.py
{ "start": 29943, "end": 30699 }
class ____(PandasParser): # pragma: no cover @staticmethod @doc( _doc_parse_func, parameters="""fname : str, path object, pandas.HDFStore or file-like object Name of the file, path pandas.HDFStore or file-like object to read.""", ) def parse(fname, **kwargs): kwargs["key"] =...
PandasHDFParser
python
langchain-ai__langchain
libs/core/langchain_core/vectorstores/in_memory.py
{ "start": 740, "end": 15690 }
class ____(VectorStore): """In-memory vector store implementation. Uses a dictionary, and computes cosine similarity for search using numpy. Setup: Install `langchain-core`. ```bash pip install -U langchain-core ``` Key init args — indexing params: embedding_f...
InMemoryVectorStore
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassTransform3.py
{ "start": 456, "end": 776 }
class ____: def __init__(self, *, init: bool = True, default: Any | None = None) -> None: ... def model_field( *, init: bool = True, default: Any | None = None, alias: str | None = None ) -> Any: ... @__dataclass_transform__( kw_only_default=True, field_specifiers=(ModelField, model_field), )
ModelField
python
getsentry__sentry
src/sentry/backup/comparators.py
{ "start": 28075, "end": 29324 }
class ____(JSONScrubbingComparator): """Comparator for fields that are lists of unordered elements, which simply orders them before doing the comparison.""" def compare(self, on: InstanceID, left: Any, right: Any) -> list[ComparatorFinding]: findings = [] fields = sorted(self.fields) ...
UnorderedListComparator
python
langchain-ai__langchain
libs/core/langchain_core/stores.py
{ "start": 7862, "end": 8458 }
class ____(InMemoryBaseStore[Any]): """In-memory store for any type of data. Attributes: store: The underlying dictionary that stores the key-value pairs. Examples: ```python from langchain.storage import InMemoryStore store = InMemoryStore() store.mset([("key1", "...
InMemoryStore
python
pandas-dev__pandas
asv_bench/benchmarks/timeseries.py
{ "start": 5388, "end": 6986 }
class ____: params = ["DataFrame", "Series"] param_names = ["constructor"] def setup(self, constructor): N = 10000 M = 10 rng = date_range(start="1/1/1990", periods=N, freq="53s") data = { "DataFrame": DataFrame(np.random.randn(N, M)), "Series": Serie...
AsOf
python
sympy__sympy
sympy/tensor/array/ndim_array.py
{ "start": 18878, "end": 19136 }
class ____(NDimArray, Basic): _op_priority = 11.0 def __hash__(self): return Basic.__hash__(self) def as_immutable(self): return self def as_mutable(self): raise NotImplementedError("abstract method")
ImmutableNDimArray
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 75075, "end": 76103 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) s3: Optional[S3StorageInfo] = Field( None, alias="S3", description=( "S3 location of init script. Destination and either region or e...
InitScriptInfo
python
MTrajK__coding-problems
Trees/zigzag_level_order_traversal.py
{ "start": 649, "end": 1566 }
class ____: def __init__(self, val, left=None, right=None): self.val = val self.left= left self.right = right def zigzag_level_order_traversal(root): results = [] queue = deque() # save nodes and levels in queue queue.append((root, 0)) while queue: node, lvl = q...
TreeNode
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_bash_code_execution_tool_result_error.py
{ "start": 213, "end": 476 }
class ____(BaseModel): error_code: Literal[ "invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded", "output_file_too_large" ] type: Literal["bash_code_execution_tool_result_error"]
BetaBashCodeExecutionToolResultError
python
django-haystack__django-haystack
test_haystack/whoosh_tests/test_whoosh_backend.py
{ "start": 43167, "end": 48076 }
class ____(WhooshTestCase): fixtures = ["bulk_data.json"] def setUp(self): super().setUp() # Stow. self.old_ui = connections["whoosh"].get_unified_index() self.ui = UnifiedIndex() self.wmmi = WhooshMockSearchIndex() self.wamsi = WhooshAnotherMockSearchIndex() ...
LiveWhooshMoreLikeThisTestCase
python
Delgan__loguru
tests/exceptions/source/others/exception_in_property.py
{ "start": 138, "end": 373 }
class ____: @property def value(self): try: 1 / 0 except: logger.opt(exception=True).debug("test") return None else: return "Never" a = A() value = a.value
A
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/output/vt100.py
{ "start": 3888, "end": 5007 }
class ____: """ Cache which maps (r, g, b) tuples to 16 ansi colors. :param bg: Cache for background colors, instead of foreground. """ def __init__(self, bg: bool = False) -> None: self.bg = bg self._cache: dict[Hashable, _ColorCodeAndName] = {} def get_code( self, va...
_16ColorCache
python
python__mypy
mypyc/irbuild/targets.py
{ "start": 657, "end": 1171 }
class ____(AssignmentTarget): """base[index] as assignment target""" def __init__(self, base: Value, index: Value) -> None: self.base = base self.index = index # TODO: object_rprimitive won't be right for user-defined classes. Store the # lvalue type in mypy and use a bett...
AssignmentTargetIndex
python
getsentry__sentry
tests/sentry/release_health/test_tasks.py
{ "start": 22447, "end": 22574 }
class ____(BaseTestReleaseMonitor, BaseMetricsTestCase): backend_class = MetricReleaseMonitorBackend
TestMetricReleaseMonitor
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-discord/llama_index/readers/discord/base.py
{ "start": 2763, "end": 5497 }
class ____(BasePydanticReader): """ Discord reader. Reads conversations from channels. Args: discord_token (Optional[str]): Discord token. If not provided, we assume the environment variable `DISCORD_TOKEN` is set. """ is_remote: bool = True discord_token: str de...
DiscordReader
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 1852, "end": 1961 }
class ____(_Union): as_expr: Annotated[SymExpr, 10] as_int: Annotated[int, 20] @_union_dataclass
SymInt
python
ray-project__ray
python/ray/dag/tests/experimental/test_collective_dag.py
{ "start": 778, "end": 2255 }
class ____(CPUCommunicator): """ Use a mock communicator to test the actor schedules. """ def __init__(self, world_size: int, actor_handles: List["ray.actor.ActorHandle"]): self._world_size = world_size self._actor_handles = actor_handles def send(self, value: "torch.Tensor", peer_...
MockCommunicator
python
ray-project__ray
release/nightly_tests/dataset/image_loader_microbenchmark.py
{ "start": 9823, "end": 19437 }
class ____(StreamingDataset): def __init__( self, s3_bucket: str, num_physical_nodes, cache_dir: str, transforms: Callable, cache_limit=None, epoch_size=None, ) -> None: super().__init__( remote=s3_bucket, local=cache_dir, ...
S3MosaicDataset
python
django__django
tests/migrations/test_fake_initial_case_insensitive/initial/0001_initial.py
{ "start": 43, "end": 845 }
class ____(migrations.Migration): initial = True operations = [ migrations.CreateModel( name="fakeinitialmodel", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.CharField(max_length=20)), ( ...
Migration
python
lepture__authlib
authlib/oauth2/client.py
{ "start": 636, "end": 18938 }
class ____: """Construct a new OAuth 2 protocol client. :param session: Requests session object to communicate with authorization server. :param client_id: Client ID, which you get from client registration. :param client_secret: Client Secret, which you get from registration. :p...
OAuth2Client
python
pypa__pip
src/pip/_vendor/tomli/_parser.py
{ "start": 9204, "end": 10261 }
class ____: def __init__(self) -> None: # The parsed content of the TOML document self.dict: dict[str, Any] = {} def get_or_create_nest( self, key: Key, *, access_lists: bool = True, ) -> dict[str, Any]: cont: Any = self.dict for k in key: ...
NestedDict
python
bokeh__bokeh
examples/server/app/surface3d/surface3d.py
{ "start": 1038, "end": 2349 }
class ____(LayoutDOM): # The special class attribute ``__implementation__`` should contain a string # of JavaScript (or TypeScript) code that implements the JavaScript side # of the custom extension model. __implementation__ = "surface3d.ts" # Below are all the "properties" for this model. Bokeh p...
Surface3d
python
chroma-core__chroma
chromadb/auth/token_authn/__init__.py
{ "start": 1884, "end": 3264 }
class ____(ClientAuthProvider): """ Client auth provider for token-based auth. Header key will be either "Authorization" or "X-Chroma-Token" depending on `chroma_auth_token_transport_header`. If the header is "Authorization", the token is passed as a bearer token. """ def __init__(self, sys...
TokenAuthClientProvider
python
python-openxml__python-docx
tests/image/test_jpeg.py
{ "start": 14253, "end": 16221 }
class ____: def it_constructs_the_appropriate_marker_object(self, call_fixture): marker_code, stream_, offset_, marker_cls_ = call_fixture marker = _MarkerFactory(marker_code, stream_, offset_) marker_cls_.from_stream.assert_called_once_with(stream_, marker_code, offset_) assert mark...
Describe_MarkerFactory
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 18402, "end": 18609 }
class ____(Projection): r"""Base class for Cylindrical projections. Cylindrical projections are so-named because the surface of projection is a cylinder. """ _separable = True
Cylindrical
python
arrow-py__arrow
tests/test_factory.py
{ "start": 12828, "end": 13217 }
class ____: def test_no_tz(self): assert_datetime_equality(self.factory.now(), datetime.now().astimezone()) def test_tzinfo(self): assert_datetime_equality( self.factory.now(ZoneInfo("EST")), datetime.now(ZoneInfo("EST")) ) def test_tz_str(self): assert_datetime...
TestNow
python
kamyu104__LeetCode-Solutions
Python/3sum-smaller.py
{ "start": 31, "end": 566 }
class ____(object): # @param {integer[]} nums # @param {integer} target # @return {integer} def threeSumSmaller(self, nums, target): nums.sort() n = len(nums) count, k = 0, 2 while k < n: i, j = 0, k - 1 while i < j: # Two Pointers, linear time. ...
Solution
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 12436, "end": 14436 }
class ____(Operation): def __init__(self, axis=None, keepdims=False, *, name=None): super().__init__(name=name) if isinstance(axis, int): axis = [axis] self.axis = axis self.keepdims = keepdims def call(self, x): return backend.numpy.amax( x, ...
Amax
python
ray-project__ray
doc/source/serve/doc_code/http_guide/streaming_example.py
{ "start": 226, "end": 1385 }
class ____: def generate_numbers(self, max: int) -> Generator[str, None, None]: for i in range(max): yield str(i) time.sleep(0.1) def __call__(self, request: Request) -> StreamingResponse: max = request.query_params.get("max", "25") gen = self.generate_numbers(in...
StreamingResponder
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/associationproxy.py
{ "start": 38423, "end": 41899 }
class ____(AssociationProxyInstance[_T]): """an :class:`.AssociationProxyInstance` where we cannot determine the type of target object. """ _is_canonical = False def _ambiguous(self) -> NoReturn: raise AttributeError( "Association proxy %s.%s refers to an attribute '%s' that is...
AmbiguousAssociationProxyInstance
python
crytic__slither
slither/tools/doctor/checks/__init__.py
{ "start": 292, "end": 585 }
class ____: title: str function: Callable[..., None] ALL_CHECKS: List[Check] = [ Check("PATH configuration", check_slither_path), Check("Software versions", show_versions), Check("Project platform", detect_platform), Check("Project compilation", compile_project), ]
Check
python
ray-project__ray
python/ray/experimental/collective/operations.py
{ "start": 5455, "end": 6151 }
class ____: """Wrapper for NCCL all-reduce.""" def bind( self, input_nodes: List["ray.dag.DAGNode"], op: ReduceOp = ReduceOp.SUM, transport: Optional[Union[str, Communicator]] = None, ) -> List[CollectiveOutputNode]: if not isinstance(op, ReduceOp): raise...
AllReduceWrapper
python
streamlit__streamlit
lib/tests/streamlit/data_test_cases.py
{ "start": 3486, "end": 3546 }
class ____(UserDict): # type: ignore pass
UserDictExample
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-aws-datalake/destination_aws_datalake/config_reader.py
{ "start": 76, "end": 428 }
class ____(enum.Enum): IAM_ROLE = "IAM Role" IAM_USER = "IAM User" @staticmethod def from_string(s: str): if s == "IAM Role": return CredentialsType.IAM_ROLE elif s == "IAM User": return CredentialsType.IAM_USER else: raise ValueError(f"Unknow...
CredentialsType
python
huggingface__transformers
src/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py
{ "start": 7086, "end": 14127 }
class ____(nn.Module): def __init__(self, config, use_bias=False, layer_idx=None): super().__init__() self.num_attention_heads = config.num_attention_heads self.hidden_size = config.hidden_size self.head_size = self.hidden_size // self.num_attention_heads if layer_idx is None...
GPTNeoXJapaneseAttention
python
pytorch__pytorch
torch/utils/data/dataset.py
{ "start": 12909, "end": 14673 }
class ____(Dataset[_T_co]): r"""Dataset as a concatenation of multiple datasets. This class is useful to assemble different existing datasets. Args: datasets (sequence): List of datasets to be concatenated """ datasets: list[Dataset[_T_co]] cumulative_sizes: list[int] @staticmeth...
ConcatDataset
python
chroma-core__chroma
chromadb/errors.py
{ "start": 2093, "end": 2296 }
class ____(ChromaError): @overrides def code(self) -> int: return 409 @classmethod @overrides def name(cls) -> str: return "UniqueConstraintError"
UniqueConstraintError
python
ray-project__ray
release/ray_release/exception.py
{ "start": 3496, "end": 3578 }
class ____(CommandError): exit_code = ExitCode.PREPARE_ERROR
PrepareCommandError
python
Textualize__textual
tests/select/test_value.py
{ "start": 239, "end": 3899 }
class ____(App[None]): def __init__(self, initial_value=Select.BLANK): self.initial_value = initial_value super().__init__() def compose(self): yield Select[int](SELECT_OPTIONS, value=self.initial_value) async def test_initial_value_is_validated(): """The initial value should be r...
SelectApp
python
scipy__scipy
benchmarks/benchmarks/sparse_csgraph_matching.py
{ "start": 2103, "end": 3078 }
class ____(Benchmark): sizes = range(100, 401, 100) param_names = ['shapes', 'input_type'] params = [ [(i, i) for i in sizes] + [(i, 2 * i) for i in sizes], ['random_uniform', 'random_uniform_sparse', 'random_uniform_integer', 'random_geometric', 'random_two_cost', 'machol_wien'] ...
MinWeightFullBipartiteMatching
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B017_1.py
{ "start": 183, "end": 560 }
class ____(unittest.TestCase): def call_form_raises(self) -> None: self.assertRaises(Exception, something_else) self.assertRaises(BaseException, something_else) def test_pytest_call_form() -> None: pytest.raises(Exception, something_else) pytest.raises(BaseException, something_else) p...
Foobar
python
airbytehq__airbyte
airbyte-integrations/connectors/source-gridly/source_gridly/source.py
{ "start": 568, "end": 2712 }
class ____(HttpStream, ABC): url_base = Helpers.base_url primary_key = "id" current_page = 1 limit = 100 def __init__(self, view_id: str, view_name: str, schema: Dict[str, Any], **kwargs): super().__init__(**kwargs) self.view_id = view_id self.view_name = view_name s...
GridlyStream
python
streamlit__streamlit
lib/tests/streamlit/runtime/runtime_test_case.py
{ "start": 1732, "end": 4104 }
class ____(SessionManager): """A MockSessionManager used for runtime tests. This is done so that our runtime tests don't rely on a specific SessionManager implementation. """ def __init__( self, session_storage: SessionStorage, uploaded_file_manager: UploadedFileManager, ...
MockSessionManager
python
matplotlib__matplotlib
galleries/examples/user_interfaces/toolmanager_sgskip.py
{ "start": 334, "end": 1297 }
class ____(ToolBase): """List all the tools controlled by the `ToolManager`.""" default_keymap = 'm' # keyboard shortcut description = 'List Tools' def trigger(self, *args, **kwargs): print('_' * 80) fmt_tool = "{:12} {:45} {}".format print(fmt_tool('Name (id)', 'Tool descripti...
ListTools
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/tests/test_build_image/test_manifest_only_connectors.py
{ "start": 384, "end": 5236 }
class ____: @pytest.fixture def all_platforms(self): return BUILD_PLATFORMS @pytest.fixture def test_context(self, mocker): return mocker.Mock(secrets_to_mask=[], targeted_platforms=BUILD_PLATFORMS) @pytest.fixture def test_context_with_connector_with_base_image(self, test_cont...
TestBuildConnectorImage
python
getsentry__sentry
tests/sentry/users/api/serializers/test_user_identity_config.py
{ "start": 509, "end": 4715 }
class ____(TestCase): def setUp(self) -> None: self.user = self.create_user() self.idp = self.create_identity_provider(type="github", external_id="c3r1zyq9") def test_user_social_auth(self) -> None: identity = UserSocialAuth.objects.create(user=self.user, provider="github", uid="uf4rom...
UserIdentityConfigSerializerTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/denormal_test.py
{ "start": 957, "end": 2930 }
class ____(test.TestCase): def testPythonHasDenormals(self): """Non-tf numpy code should treat denormals correctly.""" for dtype in np.float32, np.float64: tiny = np.finfo(dtype).tiny self.assertEqual(tiny, tiny / 16 * 16) def _flushDenormalsTest(self, dtypes): if (platform.machine() == "p...
DenormalTest
python
pandas-dev__pandas
pandas/tests/extension/test_common.py
{ "start": 2205, "end": 3071 }
class ____(pd.arrays.StringArray): """Extend StringArray to capture arguments to __getitem__""" def __getitem__(self, item): self.last_item_arg = item return super().__getitem__(item) def test_ellipsis_index(): # GH#42430 1D slices over extension types turn into N-dimensional slices #...
CapturingStringArray
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 81627, "end": 82079 }
class ____(FieldValues): """ Values for `DictField` with no `child` argument. """ valid_inputs = [ ({'a': 1, 'b': [4, 5, 6], 1: 123}, {'a': 1, 'b': [4, 5, 6], '1': 123}), ] invalid_inputs = [ ('not a dict', ['Expected a dictionary of items but got type "str".']), ] output...
TestUnvalidatedDictField
python
huggingface__transformers
src/transformers/models/deepseek_vl/modular_deepseek_vl.py
{ "start": 6976, "end": 12909 }
class ____(ProcessorMixin): r""" Constructs a DeepseekVL processor which wraps a DeepseekVL Image Processor and a Llama tokenizer into a single processor. [`DeepseekVLProcessor`] offers all the functionalities of [`DeepseekVLImageProcessor`] and [`LlamaTokenizerFast`]. See the [`~DeepseekVLProcessor.__...
DeepseekVLProcessor
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 12335, "end": 13735 }
class ____(graphene.ObjectType, AssetEventMixin): class Meta: interfaces = (GrapheneMessageEvent, GrapheneStepEvent, GrapheneDisplayableEvent) name = "MaterializationEvent" assetLineage = non_null_list(GrapheneAssetLineageInfo) def __init__(self, event: EventLogEntry, assetLineage=None): ...
GrapheneMaterializationEvent
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py
{ "start": 12434, "end": 13569 }
class ____(Benchmark): r""" Schwefel 6 objective function. This class defines the Schwefel 6 [1]_ global optimization problem. This is a unimodal minimization problem defined as follows: .. math:: f_{\text{Schwefel06}}(x) = \max(\lvert x_1 + 2x_2 - 7 \rvert, ...
Schwefel06
python
tensorflow__tensorflow
tensorflow/python/ops/resource_variable_ops.py
{ "start": 97005, "end": 105421 }
class ____(BaseResourceVariable): """Represents a future for a read of a variable. Pretends to be the tensor if anyone looks. """ def __init__(self, handle, dtype, shape, in_graph_mode, parent_op, unique_id): if isinstance(handle, ops.EagerTensor): handle_name = "" else: handle_name = hand...
_UnreadVariable
python
django__django
tests/postgres_tests/__init__.py
{ "start": 719, "end": 1391 }
class ____(TestCase): @cached_property def default_text_search_config(self): with connection.cursor() as cursor: cursor.execute("SHOW default_text_search_config") row = cursor.fetchone() return row[0] if row else None def check_default_text_search_config(self): ...
PostgreSQLTestCase
python
streamlit__streamlit
lib/tests/streamlit/elements/button_group_test.py
{ "start": 3122, "end": 4192 }
class ____: def test_serialize(self): option_indices = [5, 6, 7] serde = _SingleSelectSerde[int](option_indices) res = serde.serialize(6) assert res == [1] def test_serialize_raise_option_does_not_exist(self): option_indices = [5, 6, 7] serde = _SingleSelectSerde...
TestSingleSelectSerde
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 16407, "end": 16551 }
class ____(PydanticValueError): code = 'payment_card_number.luhn_check' msg_template = 'card number is not luhn valid'
LuhnValidationError
python
gevent__gevent
src/gevent/_socketcommon.py
{ "start": 4202, "end": 14114 }
class ____(error): # pylint: disable=undefined-variable def __init__(self): super(cancel_wait_ex, self).__init__( EBADF, 'File descriptor was closed in another greenlet') def cancel_wait(watcher, error=cancel_wait_ex): """See :meth:`gevent.hub.Hub.cancel_wait`""" get_hub()....
cancel_wait_ex
python
doocs__leetcode
solution/1300-1399/1389.Create Target Array in the Given Order/Solution.py
{ "start": 0, "end": 209 }
class ____: def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: target = [] for x, i in zip(nums, index): target.insert(i, x) return target
Solution
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 216995, "end": 218408 }
class ____(test_util.TensorFlowTestCase): @test_util.xla_allow_fallback( "non_max_suppression with dynamic output shape unsupported.") def testSelectFromThreeClustersWithSoftNMS(self): boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9], [0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 1...
NonMaxSuppressionWithScoresTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/constant_op_test.py
{ "start": 15806, "end": 19616 }
class ____(test.TestCase): def _Zeros(self, shape): with self.cached_session(): ret = array_ops.zeros(shape) self.assertEqual(shape, ret.get_shape()) return self.evaluate(ret) def testConst(self): self.assertTrue( np.array_equal(self._Zeros([2, 3]), np.array([[0] * 3] * 2))) d...
ZerosTest
python
doocs__leetcode
solution/2800-2899/2872.Maximum Number of K-Divisible Components/Solution.py
{ "start": 0, "end": 539 }
class ____: def maxKDivisibleComponents( self, n: int, edges: List[List[int]], values: List[int], k: int ) -> int: def dfs(i: int, fa: int) -> int: s = values[i] for j in g[i]: if j != fa: s += dfs(j, i) nonlocal ans ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-microsoft-dataverse/source_microsoft_dataverse/streams.py
{ "start": 366, "end": 3510 }
class ____(HttpStream, ABC): # Base url will be set by init(), using information provided by the user through config input url_base = "" primary_key = "" def __init__(self, url, stream_name, stream_path, schema, primary_key, odata_maxpagesize, **kwargs): super().__init__(**kwargs) self....
MicrosoftDataverseStream
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/property13.py
{ "start": 171, "end": 294 }
class ____(metaclass=MyMeta): def __new__(cls, arg) -> "Base": ... reveal_type(Base.something, expected_text="Base")
Base
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 21793, "end": 21963 }
class ____(InetTestBase): """Base class for UDP-over-IPv4 tests.""" def newSocket(self): return socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
UDPTestBase
python
ray-project__ray
python/ray/dashboard/modules/job/tests/test_job_manager.py
{ "start": 36562, "end": 53385 }
class ____: async def _tail_and_assert_logs( self, job_id, job_manager, expected_log="", num_iteration=5 ): i = 0 async for lines in job_manager.tail_job_logs(job_id): assert all( s == expected_log or "Runtime env" in s or "Runn...
TestTailLogs
python
tornadoweb__tornado
tornado/web.py
{ "start": 134086, "end": 134195 }
class ____(UIModule): def render(self) -> str: return self.handler.xsrf_form_html()
_xsrf_form_html
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 62943, "end": 66165 }
class ____(GoogleCloudBaseOperator): """ Deletes a DataScan DataProfile resource. :param project_id: Required. The ID of the Google Cloud project that the lake belongs to. :param region: Required. The ID of the Google Cloud region that the lake belongs to. :param data_scan_id: Required. Data Profil...
DataplexDeleteDataProfileScanOperator
python
pandas-dev__pandas
asv_bench/benchmarks/io/csv.py
{ "start": 6975, "end": 7099 }
class ____: def data(self, stringio_object): stringio_object.seek(0) return stringio_object
StringIORewind
python
astropy__astropy
astropy/utils/masked/tests/test_functions.py
{ "start": 19042, "end": 19129 }
class ____(TestMaskedArrayBroadcast, QuantitySetup): pass
TestMaskedQuantityBroadcast
python
PyCQA__pylint
tests/functional/a/async_functions.py
{ "start": 387, "end": 1337 }
class ____: async def some_method(self): super(OtherClass, self).test() # [bad-super-call] # +1: [line-too-long] # +1: [too-many-arguments, too-many-positional-arguments, too-many-return-statements, too-many-branches] async def complex_function(this, function, has, more, arguments, than, ...
Class
python
python-attrs__attrs
tests/test_filters.py
{ "start": 1735, "end": 2896 }
class ____: """ Tests for `exclude`. """ @pytest.mark.parametrize( ("excl", "value"), [ ((str,), 42), ((int,), "hello"), ((str, fields(C).b), 42), ((int, fields(C).b), "hello"), (("b",), 42), (("b",), "hello"), ...
TestExclude
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 6241, "end": 7123 }
class ____(sgqlc.types.Enum): """The possible errors that will prevent a user from updating a comment. Enumeration Choices: * `ARCHIVED`: Unable to create comment because repository is archived. * `DENIED`: You cannot update this comment * `INSUFFICIENT_ACCESS`: You must be the author or...
CommentCannotUpdateReason
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_tridiag_test.py
{ "start": 4022, "end": 5511 }
class ____( _LinearOperatorTriDiagBase, linear_operator_test_util.SquareLinearOperatorDerivedClassTest): """Most tests done in the base class LinearOperatorDerivedClassTest.""" def tearDown(self): config.enable_tensor_float_32_execution(self.tf32_keep_) def setUp(self): self.tf32_keep_ = config....
LinearOperatorTriDiagCompactTest
python
PrefectHQ__prefect
src/integrations/prefect-dbt/tests/cloud/test_runs.py
{ "start": 1592, "end": 3626 }
class ____: async def test_list_artifacts_success(self, dbt_cloud_credentials): with respx.mock(using="httpx") as respx_mock: respx_mock.get( "https://cloud.getdbt.com/api/v2/accounts/123456789/runs/12/artifacts/", headers={"Authorization": "Bearer my_api_key"}, ...
TestDbtCloudListRunArtifacts
python
pandas-dev__pandas
asv_bench/benchmarks/algos/isin.py
{ "start": 8416, "end": 9062 }
class ____: params = [ ["int64", "int32", "float64", "float32", "object", "Int64", "Float64"], ["random", "monotone"], ] param_names = ["dtype", "series_type"] def setup(self, dtype, series_type): N = 10**7 if series_type == "random": vals = np.random.randin...
IsInLongSeriesValuesDominate
python
pytest-dev__pytest
bench/xunit.py
{ "start": 82, "end": 236 }
class ____{i}: @classmethod def setup_class(cls): pass def test_1(self): pass def test_2(self): pass def test_3(self): pass """ )
Test
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/interfaces.py
{ "start": 4180, "end": 4440 }
class ____(Protocol): """protocol representing a :pep:`249` database type. .. versionadded:: 2.0 .. seealso:: `Type Objects <https://www.python.org/dev/peps/pep-0249/#type-objects>`_ - in :pep:`249` """ # noqa: E501
DBAPIType
python
pyinstaller__pyinstaller
bootloader/waflib/Tools/glib2.py
{ "start": 11394, "end": 12984 }
class ____(glib_gresource_base): run_str = glib_gresource_base.base_cmd + ' --target=${TGT} ${SRC}' shell = True @conf def find_glib_genmarshal(conf): conf.find_program('glib-genmarshal', var='GLIB_GENMARSHAL') @conf def find_glib_mkenums(conf): if not conf.env.PERL: conf.find_program('perl'...
glib_gresource_bundle
python
walkccc__LeetCode
solutions/2770. Maximum Number of Jumps to Reach the Last Index/2770.py
{ "start": 0, "end": 362 }
class ____: def maximumJumps(self, nums: list[int], target: int) -> int: n = len(nums) # dp[i] := the maximum number of jumps to reach i from 0 dp = [-1] * n dp[0] = 0 for j in range(1, n): for i in range(j): if dp[i] != -1 and abs(nums[j] - nums[i]) <= target: dp[j] = max...
Solution
python
automl__auto-sklearn
test/test_pipeline/components/data_preprocessing/test_scaling.py
{ "start": 202, "end": 2419 }
class ____(unittest.TestCase): def _test_helper(self, Preprocessor, dataset=None, make_sparse=False): X_train, Y_train, X_test, Y_test = get_dataset( dataset=dataset, make_sparse=make_sparse, ) dataset_properties = {"sparse": make_sparse} original_X_train = ...
ScalingComponentTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1587208, "end": 1587386 }
class ____(sgqlc.types.Union): """An object that is a member of an enterprise.""" __schema__ = github_schema __types__ = (EnterpriseUserAccount, User)
EnterpriseMember
python
pytorch__pytorch
torch/utils/hooks.py
{ "start": 222, "end": 3193 }
class ____: r""" A handle which provides the capability to remove a hook. Args: hooks_dict (dict): A dictionary of hooks, indexed by hook ``id``. extra_dict (Union[dict, List[dict]]): An additional dictionary or list of dictionaries whose keys will be deleted when the same keys ...
RemovableHandle
python
huggingface__transformers
src/transformers/models/edgetam/modular_edgetam.py
{ "start": 6235, "end": 6285 }
class ____(Sam2Attention): pass
EdgeTamAttention
python
kamyu104__LeetCode-Solutions
Python/remove-letter-to-equalize-frequency.py
{ "start": 645, "end": 1036 }
class ____(object): def equalFrequency(self, word): """ :type word: str :rtype: bool """ cnt = collections.Counter(collections.Counter(word)) for c in word: cnt[c] -= 1 if len(collections.Counter(c for c in cnt.itervalues() if c)) == 1: ...
Solution2
python
numba__numba
numba/tests/test_buffer_protocol.py
{ "start": 6536, "end": 8810 }
class ____(MemoryLeakMixin, TestCase): """ Test memoryview-specific attributes and operations. """ def _arrays(self): arr = np.arange(12) yield arr arr = arr.reshape((3, 4)) yield arr yield arr.T yield arr[::2] arr.setflags(write=False) yi...
TestMemoryView
python
sqlalchemy__sqlalchemy
test/base/test_utils.py
{ "start": 14625, "end": 16183 }
class ____(fixtures.TestBase): def test_memoized_property(self): val = [20] class Foo: @util.memoized_property def bar(self): v = val[0] val[0] += 1 return v ne_(Foo.bar, None) f1 = Foo() assert "bar" n...
MemoizedAttrTest
python
ansible__ansible
test/lib/ansible_test/_internal/ci/__init__.py
{ "start": 1857, "end": 2579 }
class ____(AuthHelper, metaclass=abc.ABCMeta): """Authentication helper which generates a key pair on demand.""" def __init__(self) -> None: super().__init__(pathlib.Path('~/.ansible/test/ansible-core-ci').expanduser()) def sign_request(self, request: dict[str, object], context: AuthContext) -> No...
GeneratingAuthHelper
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_uuid.py
{ "start": 881, "end": 2633 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_uuid" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, ...
ColumnValuesToBeValidUUID
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py
{ "start": 6871, "end": 7212 }
class ____(graphene.Union): """The output from deleting a run.""" class Meta: types = ( GrapheneDeletePipelineRunSuccess, GrapheneUnauthorizedError, GraphenePythonError, GrapheneRunNotFoundError, ) name = "DeletePipelineRunResult"
GrapheneDeletePipelineRunResult
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared_tests/test_record.py
{ "start": 11256, "end": 11380 }
class ____: def __init__(self, s: str): self.s = s @record_custom(field_to_new_mapping={"foo_str": "foo"})
Complex
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 5787, "end": 6118 }
class ____(PolymorphicModel): # Also test whether foreign keys receive the manager: field1 = models.CharField(max_length=30) # needed as MyManager uses it fk = models.ForeignKey( ParentModelWithManager, on_delete=models.CASCADE, related_name="childmodel_set" ) objects = MyManager()
ChildModelWithManager
python
conda__conda
conda/activate.py
{ "start": 33505, "end": 35170 }
class ____(_Activator): pathsep_join = ":".join sep = "/" path_conversion = staticmethod(win_path_to_unix if on_win else _path_identity) script_extension = ".sh" tempfile_extension = None # output to stdout command_join = "\n" needs_line_ending_fix = True # Using `unset %s` would cause...
PosixActivator
python
Pylons__pyramid
tests/test_config/test_init.py
{ "start": 287, "end": 42905 }
class ____(unittest.TestCase): def _makeOne(self, *arg, **kw): from pyramid.config import Configurator config = Configurator(*arg, **kw) return config def _getViewCallable( self, config, ctx_iface=None, request_iface=None, name='', except...
ConfiguratorTests
python
sympy__sympy
sympy/vector/coordsysrect.py
{ "start": 978, "end": 36894 }
class ____(Basic): """ Represents a coordinate system in 3-D space. """ def __new__(cls, name, transformation=None, parent=None, location=None, rotation_matrix=None, vector_names=None, variable_names=None): """ The orientation/location parameters are necessary if this sy...
CoordSys3D
python
walkccc__LeetCode
solutions/1237. Find Positive Integer Solution for a Given Equation/1237.py
{ "start": 0, "end": 354 }
class ____: def findSolution(self, customfunction: 'CustomFunction', z: int) -> list[list[int]]: ans = [] x = 1 y = 1000 while x <= 1000 and y >= 1: f = customfunction.f(x, y) if f < z: x += 1 elif f > z: y -= 1 else: ans.append([x, y]) x += 1 ...
Solution
python
mozilla__bleach
bleach/_vendor/html5lib/treewalkers/base.py
{ "start": 4819, "end": 7476 }
class ____(TreeWalker): def getNodeDetails(self, node): raise NotImplementedError def getFirstChild(self, node): raise NotImplementedError def getNextSibling(self, node): raise NotImplementedError def getParentNode(self, node): raise NotImplementedError def __iter...
NonRecursiveTreeWalker