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
doocs__leetcode
solution/0100-0199/0112.Path Sum/Solution.py
{ "start": 192, "end": 586 }
class ____: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: def dfs(root, s): if root is None: return False s += root.val if root.left is None and root.right is None and s == targetSum: return True return...
Solution
python
weaviate__weaviate-python-client
weaviate/collections/classes/grpc.py
{ "start": 9617, "end": 10716 }
class ____(_WeaviateInput, Generic[V]): dimensionality: Literal["1D", "2D"] vectors: Sequence[V] @staticmethod def is_one_dimensional( self_: "_ListOfVectorsQuery", ) -> TypeGuard["_ListOfVectorsQuery[OneDimensionalVectorType]"]: return self_.dimensionality == "1D" @staticmetho...
_ListOfVectorsQuery
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py
{ "start": 18148, "end": 18212 }
class ____(Sam2VideoAttention): pass
Sam3TrackerVideoAttention
python
Pylons__pyramid
tests/test_path.py
{ "start": 8305, "end": 10442 }
class ____(unittest.TestCase): def _getTargetClass(self): from pyramid.path import PkgResourcesAssetDescriptor return PkgResourcesAssetDescriptor def _makeOne(self, pkg='tests', path='test_asset.py'): return self._getTargetClass()(pkg, path) def test_class_conforms_to_IAssetDescri...
TestPkgResourcesAssetDescriptor
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/special_math_test.py
{ "start": 2760, "end": 5008 }
class ____(test.TestCase): def assertAllFinite(self, x): is_finite = np.isfinite(x) all_true = np.ones_like(is_finite, dtype=np.bool_) self.assertAllEqual(all_true, is_finite) @test_util.run_in_graph_and_eager_modes def testNdtri(self): """Verifies that ndtri computation is correct.""" if no...
NdtriTest
python
pytest-dev__pytest-django
tests/test_fixtures.py
{ "start": 26907, "end": 32552 }
class ____: @pytest.mark.django_db def test_block_manually(self, django_db_blocker: DjangoDbBlocker) -> None: try: django_db_blocker.block() with pytest.raises(RuntimeError, match="^Database access not allowed,"): Item.objects.exists() finally: ...
Test_django_db_blocker
python
has2k1__plotnine
plotnine/_utils/registry.py
{ "start": 1000, "end": 1953 }
class ____(ABCMeta): """ Creates class that automatically registers all subclasses To prevent the base class from showing up in the registry, it should inherit from ABC. This metaclass uses a single dictionary to register all types of subclasses. To access the registered objects, use: ...
Register
python
falconry__falcon
tests/asgi/_asgi_test_app.py
{ "start": 8260, "end": 8913 }
class ____: async def on_get(self, req, resp): # NOTE(myusko): In the future we shouldn't change the cookie # a test depends on the input. # NOTE(kgriffs): This is the only test that uses a single # cookie (vs. multiple) as input; if this input ever changes, # ...
TestJar
python
davidhalter__jedi
test/completion/classes.py
{ "start": 9832, "end": 10046 }
class ____(MyBase): def f3(self): #! 13 ['def f1'] self.f1() . # hey''' #? 13 MyBase.f1 self.f1() . # hey''' # ----------------- # With a very weird __init__ # -----------------
C1
python
optuna__optuna
optuna/cli.py
{ "start": 10552, "end": 12274 }
class ____(_BaseCommand): """Create a new study.""" def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument( "--study-name", default=None, help="A human-readable name of a study to distinguish it from others.", ) parser.add_argume...
_CreateStudy
python
openai__gym
gym/envs/mujoco/humanoid_v4.py
{ "start": 419, "end": 27951 }
class ____(MujocoEnv, utils.EzPickle): """ ### Description This environment is based on the environment introduced by Tassa, Erez and Todorov in ["Synthesis and stabilization of complex behaviors through online trajectory optimization"](https://ieeexplore.ieee.org/document/6386025). The 3D bipedal ...
HumanoidEnv
python
matplotlib__matplotlib
lib/matplotlib/backends/_backend_gtk.py
{ "start": 3707, "end": 3777 }
class ____(FigureCanvasBase): _timer_cls = TimerGTK
_FigureCanvasGTK
python
getsentry__sentry
src/sentry/api/serializers/models/discoversavedquery.py
{ "start": 637, "end": 1018 }
class ____(TypedDict, total=False): environment: list[str] query: str fields: list[str] widths: list[str] conditions: list[str] aggregations: list[str] range: str start: str end: str orderby: str limit: str yAxis: list[str] display: str topEvents: int interval...
DiscoverSavedQueryResponseOptional
python
gevent__gevent
src/gevent/events.py
{ "start": 4732, "end": 5509 }
class ____(Interface): """ The contract for the periodic monitoring thread that is started by the hub. """ def add_monitoring_function(function, period): """ Schedule the *function* to be called approximately every *period* fractional seconds. The *function* receives one ar...
IPeriodicMonitorThread
python
sympy__sympy
sympy/combinatorics/free_groups.py
{ "start": 9552, "end": 39641 }
class ____(CantSympify, DefaultPrinting, tuple): """Used to create elements of FreeGroup. It cannot be used directly to create a free group element. It is called by the `dtype` method of the `FreeGroup` class. """ __slots__ = () is_assoc_word = True def new(self, init): return self...
FreeGroupElement
python
anthropics__anthropic-sdk-python
src/anthropic/types/thinking_config_enabled_param.py
{ "start": 226, "end": 724 }
class ____(TypedDict, total=False): budget_tokens: Required[int] """Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality. Must be ≥1024 and less than `max_tokens`. See ...
ThinkingConfigEnabledParam
python
gevent__gevent
src/greentest/3.14/test_socketserver.py
{ "start": 15877, "end": 17812 }
class ____(unittest.TestCase): def test_all(self): # objects defined in the module should be in __all__ expected = [] for name in dir(socketserver): if not name.startswith('_'): mod_object = getattr(socketserver, name) if getattr(mod_object, '__mo...
MiscTestCase
python
kamyu104__LeetCode-Solutions
Python/out-of-boundary-paths.py
{ "start": 41, "end": 906 }
class ____(object): def findPaths(self, m, n, N, x, y): """ :type m: int :type n: int :type N: int :type x: int :type y: int :rtype: int """ M = 1000000000 + 7 dp = [[[0 for _ in xrange(n)] for _ in xrange(m)] for _ in xrange(2)] ...
Solution
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_multiple_wrapping.py
{ "start": 877, "end": 1102 }
class ____(Module): def __init__(self, device): super().__init__() self.layers = Sequential(FSDP(Linear(5, 5), device_id=device_type.type)) def forward(self, x): return self.layers(x)
InnerModel
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_column_proportion_of_unique_values_to_be_between.py
{ "start": 2723, "end": 17972 }
class ____(ColumnAggregateExpectation): __doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION} For example, in a column containing [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], there are 4 unique values and 10 total \ values for a proportion of 0.4. ExpectColumnProportionOfUniqueValuesToBeBetween is a \ Column Aggregate...
ExpectColumnProportionOfUniqueValuesToBeBetween
python
django__django
django/contrib/gis/gdal/raster/band.py
{ "start": 7836, "end": 8343 }
class ____(list): def __init__(self, source): self.source = source super().__init__() def __iter__(self): for idx in range(1, len(self) + 1): yield GDALBand(self.source, idx) def __len__(self): return capi.get_ds_raster_count(self.source._ptr) def __getitem...
BandList
python
kamyu104__LeetCode-Solutions
Python/longest-common-subpath.py
{ "start": 37, "end": 1542 }
class ____(object): def longestCommonSubpath(self, n, paths): """ :type n: int :type paths: List[List[int]] :rtype: int """ def RabinKarp(arr, x): # double hashing hashes = tuple([reduce(lambda h,x: (h*p+x)%MOD, (arr[i] for i in xrange(x)), 0) for p in P]...
Solution
python
google__flatbuffers
tests/monster_test_generated.py
{ "start": 14302, "end": 15353 }
class ____(object): __slots__ = ['_tab'] @classmethod def SizeOf(cls): return 20 # StructOfStructs def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) # StructOfStructs def A(self, obj): obj.Init(self._tab.Bytes, self._tab.Pos + 0) retur...
StructOfStructs
python
nedbat__coveragepy
tests/test_python.py
{ "start": 2174, "end": 2914 }
class ____(CoverageTest): """Tests using runpy.""" @pytest.mark.parametrize("convert_to", ["str", "Path"]) def test_runpy_path(self, convert_to: str) -> None: # Ensure runpy.run_path(path) works when path is pathlib.Path or str. # # runpy.run_path(pathlib.Path(...)) causes __file__ ...
RunpyTest
python
dask__distributed
distributed/tests/test_client.py
{ "start": 142136, "end": 175729 }
class ____: def __getstate__(self): return 1 def __dask_tokenize__(self): return uuid.uuid4().hex def __setstate__(self, state): raise MyException("hello") def __call__(self): return 1 @gen_cluster(client=True) async def test_robust_undeserializable(c, s, a, b): ...
BrokenSetState
python
getsentry__sentry
src/sentry/rules/processing/buffer_processing.py
{ "start": 542, "end": 593 }
class ____: project_id: int @dataclass
FilterKeys
python
ray-project__ray
doc/source/ray-core/doc_code/tasks_fault_tolerance.py
{ "start": 934, "end": 2797 }
class ____(Exception): pass @ray.remote(max_retries=1, retry_exceptions=True) def potentially_fail(failure_probability): if failure_probability < 0 or failure_probability > 1: raise ValueError( "failure_probability must be between 0 and 1, but got: " f"{failure_probability}" ...
RandomError
python
numba__numba
numba/core/ccallback.py
{ "start": 1002, "end": 4312 }
class ____(object): """ A compiled C callback, as created by the @cfunc decorator. """ _targetdescr = registry.cpu_target def __init__(self, pyfunc, sig, locals, options, pipeline_class=compiler.Compiler): args, return_type = sig if return_type is None: ...
CFunc
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/annotated1.py
{ "start": 192, "end": 396 }
class ____: @staticmethod def ctype(a: str): pass class Packed: pass UnsignedShort = Annotated[int, struct2.ctype("H")] SignedChar = Annotated[int, struct2.ctype("b")]
struct2
python
walkccc__LeetCode
solutions/437. Path Sum III/437.py
{ "start": 0, "end": 447 }
class ____: def pathSum(self, root: TreeNode | None, summ: int) -> int: if not root: return 0 def dfs(root: TreeNode, summ: int) -> int: if not root: return 0 return (int(summ == root.val) + dfs(root.left, summ - root.val) + dfs(root.right, summ - root.va...
Solution
python
pytorch__pytorch
torch/distributed/fsdp/_flat_param.py
{ "start": 4899, "end": 5612 }
class ____(NamedTuple): """Shard-related information for an original parameter.""" in_shard: bool # Use to index into the sharded flat parameter, e.g. # `flat_param[offset_in_shard : offset_in_shard + numel_in_shard]` offset_in_shard: Optional[int] numel_in_shard: Optional[int] # Use to get...
_ShardParamInfo
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_tags.py
{ "start": 17645, "end": 19650 }
class ____(APITestCase, ReplaysSnubaTestCase): def test_dataset_replays(self) -> None: self.login_as(user=self.user) replay1_id = uuid.uuid4().hex replay2_id = uuid.uuid4().hex replay3_id = uuid.uuid4().hex self.r1_seq0_timestamp = before_now(seconds=22) self.r1_seq1_...
ReplayOrganizationTagsTest
python
bokeh__bokeh
src/bokeh/resources.py
{ "start": 7896, "end": 19016 }
class ____: """ The Resources class encapsulates information relating to loading or embedding Bokeh Javascript and CSS. Args: mode (str) : how should Bokeh JS and CSS be included in output See below for descriptions of available modes version (str, optional) : what version...
Resources
python
rq__rq
tests/test_cli.py
{ "start": 1418, "end": 31948 }
class ____(CLITestCase): @pytest.fixture(autouse=True) def set_tmpdir(self, tmpdir): self.tmpdir = tmpdir def assert_normal_execution(self, result): if result.exit_code == 0: return True else: print('Non normal execution') print(f'Exit Code: {resu...
TestRQCli
python
kubernetes-client__python
kubernetes/client/models/v1alpha1_cluster_trust_bundle_list.py
{ "start": 383, "end": 7259 }
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...
V1alpha1ClusterTrustBundleList
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol3.py
{ "start": 2619, "end": 2656 }
class ____(Protocol): x: str
Proto7
python
tox-dev__tox
src/tox/tox_env/errors.py
{ "start": 69, "end": 152 }
class ____(Exception): # noqa: N818 """Recreate the tox environment."""
Recreate
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/fmt_on_off/fmt_off_unclosed_trailing_comment.py
{ "start": 126, "end": 162 }
class ____: x: int # Optional[int]
A
python
pypa__warehouse
tests/unit/admin/test_bans.py
{ "start": 193, "end": 1257 }
class ____: def test_no_ip_not_banned(self, db_request): assert not db_request.banned.by_ip("4.3.2.1") def test_with_ip_not_banned(self, db_request): assert not db_request.banned.by_ip(db_request.ip_address.ip_address) def test_with_ip_banned(self, db_request): user_service = prete...
TestAdminFlag
python
getsentry__sentry
src/sentry/api/endpoints/relay/public_keys.py
{ "start": 421, "end": 1558 }
class ____(Endpoint): publish_status = { "POST": ApiPublishStatus.PRIVATE, } authentication_classes = (RelayAuthentication,) permission_classes = (RelayPermission,) enforce_rate_limit = False owner = ApiOwner.OWNERS_INGEST def post(self, request: Request) -> Response: callin...
RelayPublicKeysEndpoint
python
wandb__wandb
wandb/vendor/pygments/lexers/erlang.py
{ "start": 578, "end": 5972 }
class ____(RegexLexer): """ For the Erlang functional programming language. Blame Jeremy Thurgood (http://jerith.za.net/). .. versionadded:: 0.9 """ name = 'Erlang' aliases = ['erlang'] filenames = ['*.erl', '*.hrl', '*.es', '*.escript'] mimetypes = ['text/x-erlang'] keywords...
ErlangLexer
python
ApeWorX__ape
src/ape/pytest/utils.py
{ "start": 24, "end": 285 }
class ____(int, Enum): SESSION = 0 PACKAGE = 1 MODULE = 2 CLASS = 3 FUNCTION = 4 def __str__(self) -> str: return self.name.lower() @property def isolation_fixturename(self) -> str: return f"_{self}_isolation"
Scope
python
jina-ai__jina
jina/clients/grpc.py
{ "start": 189, "end": 781 }
class ____(GRPCBaseClient, PostMixin, HealthCheckMixin, ProfileMixin): """A client connecting to a Gateway using gRPC protocol. Instantiate this class through the :meth:`jina.Client` convenience method. EXAMPLE USAGE .. code-block:: python from jina import Client from docarray import...
GRPCClient
python
pennersr__django-allauth
allauth/socialaccount/providers/dingtalk/client.py
{ "start": 140, "end": 1345 }
class ____(OAuth2Client): def get_access_token(self, code, pkce_code_verifier=None): data = { "clientId": self.consumer_key, "clientSecret": self.consumer_secret, "code": code, "grantType": "authorization_code", } params = None if pkce_...
DingTalkOAuth2Client
python
getsentry__sentry
src/sentry/integrations/discord/integration.py
{ "start": 4958, "end": 11261 }
class ____(IntegrationProvider): key = IntegrationProviderSlug.DISCORD.value name = "Discord" metadata = metadata integration_cls = DiscordIntegration features = frozenset([IntegrationFeatures.CHAT_UNFURL, IntegrationFeatures.ALERT_RULE]) # https://discord.com/developers/docs/topics/oauth2#shar...
DiscordIntegrationProvider
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/freshness_policy.py
{ "start": 173, "end": 576 }
class ____(graphene.ObjectType): # How old is the current data currentLagMinutes = graphene.Field(graphene.Float) # How overdue is the current data (currentLagMinutes - maximumLagMinutes) currentMinutesLate = graphene.Field(graphene.Float) latestMaterializationMinutesLate = graphene.Field(graphene.F...
GrapheneAssetFreshnessInfo
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 12454, "end": 12517 }
class ____(FrameFieldMatch): field = "category"
CategoryMatch
python
PyCQA__pylint
tests/functional/n/no/no_member_decorator.py
{ "start": 77, "end": 450 }
class ____: # pylint: disable=too-few-public-methods """https://github.com/pylint-dev/pylint/issues/9246""" @classmethod @lru_cache def __cached_fun(cls, arg: int) -> str: return str(arg) @classmethod def cache_clear(cls): """__cached_fun()'s @cache decorator supplies cache_cle...
SomeClass
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/streams.py
{ "start": 18464, "end": 18559 }
class ____(IterableExportEventsStreamAdjustableRange): data_field = "smsSendSkip"
SmsSendSkip
python
openai__openai-python
src/openai/resources/uploads/parts.py
{ "start": 7283, "end": 7488 }
class ____: def __init__(self, parts: Parts) -> None: self._parts = parts self.create = _legacy_response.to_raw_response_wrapper( parts.create, )
PartsWithRawResponse
python
fastai__fastai
fastai/data/core.py
{ "start": 19553, "end": 24416 }
class ____(FilteredBase): "A dataset that creates a tuple from each `tfms`" def __init__(self, items:list=None, # List of items to create `Datasets` tfms:MutableSequence|Pipeline=None, # List of `Transform`(s) or `Pipeline` to apply tls:TfmdLists=None, # If None, `self.tls` is generated...
Datasets
python
scipy__scipy
scipy/sparse/linalg/_interface.py
{ "start": 21317, "end": 21821 }
class ____(LinearOperator): """Adjoint of arbitrary Linear Operator""" def __init__(self, A): shape = (A.shape[1], A.shape[0]) super().__init__(dtype=A.dtype, shape=shape) self.A = A self.args = (A,) def _matvec(self, x): return self.A._rmatvec(x) def _rmatvec(...
_AdjointLinearOperator
python
getsentry__sentry
src/sentry/data_export/endpoints/data_export.py
{ "start": 1921, "end": 10420 }
class ____(serializers.Serializer[dict[str, Any]]): query_type = serializers.ChoiceField(choices=ExportQueryType.as_str_choices(), required=True) query_info = serializers.JSONField(required=True) def validate(self, data: dict[str, Any]) -> dict[str, Any]: organization = self.context["organization"]...
DataExportQuerySerializer
python
getsentry__sentry
tests/sentry/sentry_apps/api/parsers/test_markdown.py
{ "start": 201, "end": 804 }
class ____(unittest.TestCase): def setUp(self) -> None: self.schema: dict[str, Any] = { "type": "markdown", "text": """ # This Is a Title - this - is - a - list """, } def test_valid_schema(self) -> None: validate_component(self.schema) @invalid_...
TestMarkdownSchemaValidation
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels29.py
{ "start": 315, "end": 1481 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels29.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
keras-team__keras
keras/src/distillation/distiller.py
{ "start": 301, "end": 22984 }
class ____(Model): """Distillation model for transferring knowledge from teacher to student. Knowledge distillation transfers knowledge from a large, complex model (teacher) to a smaller, simpler model (student). The student learns from both ground truth labels and the teacher's predictions, often ...
Distiller
python
kamyu104__LeetCode-Solutions
Python/max-sum-of-sub-matrix-no-larger-than-k.py
{ "start": 116, "end": 1234 }
class ____(object): def maxSumSubmatrix(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ if not matrix: return 0 m = min(len(matrix), len(matrix[0])) n = max(len(matrix), len(matrix[0])) result = flo...
Solution
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_map_metrics/column_values_match_regex.py
{ "start": 1923, "end": 3732 }
class ____(MetricProvider): metric_name = "column_values.match_regex.count" metric_value_kwargs = ("regex",) @metric_value(engine=PandasExecutionEngine) def _pandas(*, metrics, **kwargs): return metrics[ f"column_values.not_match_regex.{SummarizationMetricNameSuffixes.UNEXPECTED_CO...
ColumnValuesMatchRegexCount
python
pydata__xarray
xarray/core/nputils.py
{ "start": 5168, "end": 11105 }
class ____: """Object that implements indexing like vindex on a np.ndarray. This is a pure Python implementation of (some of) the logic in this NumPy proposal: https://github.com/numpy/numpy/pull/6256 """ def __init__(self, array): self._array = array def __getitem__(self, key): ...
NumpyVIndexAdapter
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 429343, "end": 429508 }
class ____(Format): """Dict schema wrapper.""" _schema = {"$ref": "#/definitions/Dict"} def __init__(self, **kwds): super().__init__(**kwds)
Dict
python
numba__numba
numba/cuda/tests/cudapy/test_laplace.py
{ "start": 267, "end": 3211 }
class ____(CUDATestCase): def test_laplace_small(self): @cuda.jit(float64(float64, float64), device=True, inline=True) def get_max(a, b): if a > b: return a else: return b @cuda.jit(void(float64[:, :], float64[:, :], float64[:, :])) ...
TestCudaLaplace
python
networkx__networkx
networkx/classes/reportviews.py
{ "start": 24122, "end": 26340 }
class ____(EdgeViewABC): """EdgeDataView for outward edges of DiGraph; See EdgeDataView""" __slots__ = ( "_viewer", "_nbunch", "_data", "_default", "_adjdict", "_nodes_nbrs", "_report", ) def __getstate__(self): return { "view...
OutEdgeDataView
python
tensorflow__tensorflow
tensorflow/python/training/server_lib_same_variables_clear_container_test.py
{ "start": 1002, "end": 3161 }
class ____(test.TestCase): # Verifies behavior of tf.Session.reset() with multiple containers using # default container names as defined by the target name. # TODO(b/34465411): Starting multiple servers with different configurations # in the same test is flaky. Move this test case back into # "server_lib_tes...
SameVariablesClearContainerTest
python
oauthlib__oauthlib
oauthlib/openid/connect/core/request_validator.py
{ "start": 261, "end": 13766 }
class ____(OAuth2RequestValidator): def get_authorization_code_scopes(self, client_id, code, redirect_uri, request): """ Extracts scopes from saved authorization code. The scopes returned by this method is used to route token requests based on scopes passed to Authorization Code requests. ...
RequestValidator
python
apache__airflow
airflow-core/src/airflow/traces/tracer.py
{ "start": 2106, "end": 3268 }
class ____: """If no Tracer is configured, EmptySpan is used as a fallback.""" def __enter__(self) -> Self: """Enter.""" return self def __exit__(self, *args, **kwargs): """Exit.""" pass def __call__(self, obj): """Call.""" return obj def get_span_...
EmptySpan
python
django__django
tests/decorators/tests.py
{ "start": 12742, "end": 20723 }
class ____(SimpleTestCase): """ Tests for async method_decorator """ async def test_preserve_signature(self): class Test: @async_simple_dec_m async def say(self, msg): return f"Saying {msg}" self.assertEqual(await Test().say("hello"), "returned: ...
AsyncMethodDecoratorTests
python
ipython__ipython
tests/test_async_helpers.py
{ "start": 552, "end": 10709 }
class ____(TestCase): def test_should_be_async(self): self.assertFalse(_should_be_async("False")) self.assertTrue(_should_be_async("await bar()")) self.assertTrue(_should_be_async("x = await bar()")) self.assertFalse( _should_be_async( dedent( ...
AsyncTest
python
walkccc__LeetCode
solutions/1894. Find the Student that Will Replace the Chalk/1894.py
{ "start": 0, "end": 207 }
class ____: def chalkReplacer(self, chalk: list[int], k: int) -> int: k %= sum(chalk) if k == 0: return 0 for i, c in enumerate(chalk): k -= c if k < 0: return i
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/workspace/autodiscovery.py
{ "start": 528, "end": 5309 }
class ____(NamedTuple): attribute: str target_definition: object def loadable_targets_from_python_file( python_file: str, working_directory: Optional[str] = None ) -> Sequence[LoadableTarget]: loaded_module = load_python_file(python_file, working_directory) return loadable_targets_from_loaded_modu...
LoadableTarget
python
getsentry__sentry
src/sentry/models/rulefirehistory.py
{ "start": 297, "end": 998 }
class ____(Model): __relocation_scope__ = RelocationScope.Excluded project = FlexibleForeignKey("sentry.Project", db_constraint=False) rule = FlexibleForeignKey("sentry.Rule") group = FlexibleForeignKey("sentry.Group", db_constraint=False) event_id = CharField("event_id", max_length=32, null=True) ...
RuleFireHistory
python
PyCQA__pylint
pylint/pyreverse/inspector.py
{ "start": 11161, "end": 12078 }
class ____(RelationshipHandlerInterface): """ Chain of Responsibility for handling types of relationships, useful to expand in the future if we want to add more distinct relationships. Every link of the chain checks if it's a certain type of relationship. If no relationship is found it's set as a g...
AbstractRelationshipHandler
python
scipy__scipy
scipy/sparse/tests/test_minmax1d.py
{ "start": 2643, "end": 4269 }
class ____: def test_minmax(self, spcreator): dat = np.array([[-1, 5, 0, 3], [0, 0, -1, -2], [0, 0, 1, 2]]) datsp = spcreator(dat) for (spminmax, npminmax) in [ (datsp.min, np.min), (datsp.max, np.max), (datsp.nanmin, np.nanmin), (datsp.nanmax...
Test_ShapeMinMax2DWithAxis
python
scrapy__scrapy
scrapy/spiderloader.py
{ "start": 956, "end": 1639 }
class ____(Protocol): @classmethod def from_settings(cls, settings: BaseSettings) -> Self: """Return an instance of the class for the given settings""" def load(self, spider_name: str) -> type[Spider]: """Return the Spider class for the given spider name. If the spider name is not f...
SpiderLoaderProtocol
python
pandas-dev__pandas
pandas/tests/indexing/test_scalar.py
{ "start": 8504, "end": 9929 }
class ____: def test_multiindex_at_get(self): # GH 26989 # DataFrame.at and DataFrame.loc getter works with MultiIndex df = DataFrame({"a": [1, 2]}, index=[[1, 2], [3, 4]]) assert df.index.nlevels == 2 assert df.at[(1, 3), "a"] == 1 assert df.loc[(1, 3), "a"] == 1 ...
TestMultiIndexScalar
python
modin-project__modin
asv_bench/benchmarks/benchmarks.py
{ "start": 10757, "end": 11830 }
class ____: param_names = ["shape", "item_length", "loc", "is_equal_indices"] @staticmethod def get_loc(df, loc, axis, item_length): locs_dict = { "zero": 0, "middle": len(df.axes[axis]) // 2, "last": len(df.axes[axis]) - 1, } base_loc = locs_dict...
BaseTimeSetItem
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_coordinator_test.py
{ "start": 4301, "end": 4635 }
class ____(object): def __init__(self): self._joined = False self._started = False def start(self): self._started = True def join(self): assert not self._joined self._joined = True @property def joined(self): return self._joined @property def started(self): return self._st...
MockServer
python
PrefectHQ__prefect
tests/test_tasks.py
{ "start": 130790, "end": 137615 }
class ____: async def test_task_cannot_configure_poorly_typed_retry_delay(self): with pytest.raises(TypeError, match="Invalid"): @task(retries=42, retry_delay_seconds=dict(x=4)) async def insanity(): raise RuntimeError("try again!") with pytest.raises(TypeEr...
TestTaskConstructorValidation
python
scipy__scipy
benchmarks/benchmarks/fft_basic.py
{ "start": 4531, "end": 5162 }
class ____(Benchmark): params = [ ["100x100", "313x100", "1000x100", "256x256", "512x512"], ['real', 'cmplx'], ['scipy.fftpack', 'scipy.fft', 'numpy.fft'] ] param_names = ['size', 'type', 'module'] def setup(self, size, cmplx, module): size = list(map(int, size.split("x"...
Fftn
python
encode__django-rest-framework
tests/test_requests_client.py
{ "start": 1933, "end": 2957 }
class ____(APIView): @method_decorator(ensure_csrf_cookie) def get(self, request): if request.user.is_authenticated: username = request.user.username else: username = None return Response({ 'username': username }) @method_decorator(csrf_pr...
AuthView
python
mlflow__mlflow
mlflow/data/evaluation_dataset.py
{ "start": 8940, "end": 20783 }
class ____: """ An input dataset for model evaluation. This is intended for use with the :py:func:`mlflow.models.evaluate()` API. """ NUM_SAMPLE_ROWS_FOR_HASH = 5 SPARK_DATAFRAME_LIMIT = 10000 def __init__( self, data, *, targets=None, name=None,...
EvaluationDataset
python
bokeh__bokeh
tests/unit/bokeh/command/subcommands/test_serve.py
{ "start": 1612, "end": 2880 }
class ____: def __init__(self, stream) -> None: ''' stream: the stream to read from. Usually a process' stdout or stderr. ''' self._s = stream self._q = Queue() def _populateQueue(stream, queue): ''' Collect lines from 'stream...
NBSR
python
getsentry__sentry
src/sentry/integrations/analytics.py
{ "start": 1809, "end": 1978 }
class ____(analytics.Event): provider: str | None id: int organization_id: int @analytics.eventclass("integration.stacktrace.linked")
IntegrationResolvePREvent
python
getsentry__sentry
src/sentry/incidents/grouptype.py
{ "start": 6147, "end": 12527 }
class ____(StatefulDetectorHandler[MetricUpdate, MetricResult]): def build_detector_evidence_data( self, evaluation_result: ProcessedDataConditionGroup, data_packet: DataPacket[MetricUpdate], priority: DetectorPriorityLevel, ) -> dict[str, Any]: try: alert_ru...
MetricIssueDetectorHandler
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 34518, "end": 35066 }
class ____( _MutableDictTestBase, fixtures.MappedTest ): @classmethod def define_tables(cls, metadata): MutableDict = cls._type_fixture() MutableDict.associate_with(PickleType) Table( "foo", metadata, Column( "id", Integer, primary...
MutableAssociationScalarPickleTest
python
python-openxml__python-docx
src/docx/oxml/shape.py
{ "start": 8216, "end": 8883 }
class ____(BaseOxmlElement): """``<a:xfrm>`` element, specifies size and shape of picture container.""" off = ZeroOrOne("a:off", successors=("a:ext",)) ext = ZeroOrOne("a:ext", successors=()) @property def cx(self): ext = self.ext if ext is None: return None ret...
CT_Transform2D
python
spack__spack
lib/spack/spack/test/installer.py
{ "start": 25723, "end": 25935 }
class ____(inst.InstallStatus): def next_pkg(self, *args, **kwargs): pass def set_term_title(self, *args, **kwargs): pass def get_progress(self): return "1/1"
MockInstallStatus
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/random/parameterized_truncated_normal_op_test.py
{ "start": 3896, "end": 18808 }
class ____(test.TestCase): z_limit = 6.0 # Stop at moment 10 to avoid numerical errors in the theoretical moments. max_moment = 10 def validateMoments(self, shape, mean, stddev, minval, maxval, ...
ParameterizedTruncatedNormalTest
python
wandb__wandb
wandb/util.py
{ "start": 47914, "end": 61418 }
class ____: def __init__(self) -> None: self.modules: dict[str, ModuleType] = dict() self.on_import: dict[str, list] = dict() def add(self, fullname: str, on_import: Callable) -> None: self.on_import.setdefault(fullname, []).append(on_import) def install(self) -> None: sys....
ImportMetaHook
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events.py
{ "start": 246309, "end": 253913 }
class ____( OrganizationEventsEndpointTestBase, SearchIssueTestMixin, PerformanceIssueTestCase ): def test_performance_issue_id_filter(self) -> None: event = self.create_performance_issue() assert event.group is not None query = { "field": ["count()"], "statsPeri...
OrganizationEventsIssuePlatformDatasetEndpointTest
python
pikepdf__pikepdf
src/pikepdf/codec.py
{ "start": 3578, "end": 4041 }
class ____(codecs.Codec): """Implement PdfDocEncoding character map used inside PDFs.""" def encode(self, input: str, errors: str = 'strict') -> tuple[bytes, int]: """Implement codecs.Codec.encode for pdfdoc.""" return pdfdoc_encode(input, errors) def decode(self, input: Buffer, errors: st...
PdfDocCodec
python
numpy__numpy
numpy/ma/tests/test_extras.py
{ "start": 70946, "end": 72625 }
class ____: def test_ndenumerate_nomasked(self): ordinary = np.arange(6.).reshape((1, 3, 2)) empty_mask = np.zeros_like(ordinary, dtype=bool) with_mask = masked_array(ordinary, mask=empty_mask) assert_equal(list(np.ndenumerate(ordinary)), list(ndenumerate(ordina...
TestNDEnumerate
python
sphinx-doc__sphinx
sphinx/builders/latex/theming.py
{ "start": 356, "end": 1245 }
class ____: """A set of LaTeX configurations.""" LATEX_ELEMENTS_KEYS = ['papersize', 'pointsize'] UPDATABLE_KEYS = ['papersize', 'pointsize'] def __init__(self, name: str) -> None: self.name = name self.docclass = name self.wrapperclass = name self.papersize = 'letterpa...
Theme
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 64357, "end": 64418 }
class ____(str, Enum): KEYWORD = "keyword"
KeywordIndexType
python
huggingface__transformers
tests/models/xmod/test_modeling_xmod.py
{ "start": 13816, "end": 26921 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( XmodForCausalLM, XmodForMaskedLM, XmodModel, XmodForSequenceClassification, XmodForTokenClassification, XmodForMultiple...
XmodModelTest
python
jina-ai__jina
tests/unit/orchestrate/flow/flow-orchestrate/test_flow_routing.py
{ "start": 1524, "end": 2512 }
class ____(Executor): @requests def add_doc(self, docs, **kwargs): return docs @pytest.mark.parametrize('disable_reduce', [True, False]) def test_complex_flow(disable_reduce): f = ( Flow() .add(name='first', uses=SimpleAddExecutor, needs=['gateway']) .add(name='forth', uses...
MergeDocsExecutor
python
rapidsai__cudf
python/cudf/cudf/core/series.py
{ "start": 123587, "end": 153765 }
class ____(BaseDatelikeProperties): """ Accessor object for datetimelike properties of the Series values. Returns ------- Returns a Series indexed like the original Series. Examples -------- >>> import cudf >>> import pandas as pd >>> seconds_series = cudf.Series(pd.date_range(...
DatetimeProperties
python
plotly__plotly.py
tests/test_core/test_figure_messages/test_plotly_relayout.py
{ "start": 101, "end": 5460 }
class ____(TestCase): def setUp(self): # Construct with mocked _send_relayout_msg method self.figure = go.Figure(layout={"xaxis": {"range": [-1, 4]}}) # Mock out the message method self.figure._send_relayout_msg = MagicMock() def test_property_assignment_toplevel(self): ...
TestRelayoutMessage
python
walkccc__LeetCode
solutions/453. Minimum Moves to Equal Array Elements/453.py
{ "start": 0, "end": 122 }
class ____: def minMoves(self, nums: list[int]) -> int: mn = min(nums) return sum(num - mn for num in nums)
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/event_log/polling_event_watcher.py
{ "start": 3877, "end": 8267 }
class ____(threading.Thread): """subclass of Thread that watches a given run_id for new Events by polling every POLLING_CADENCE. Holds a list of callbacks (_callback_fn_list) each passed in by an `Observer`. Note that the callbacks have a cursor associated; this means that the callbacks should be ...
SqlPollingRunIdEventWatcherThread
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 299652, "end": 301373 }
class ____(Response): """ Response of tasks.edit endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict """ _service = "tasks" _action = "edit" _version = "2.23" _schema = { "d...
EditResponse