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 | automl__auto-sklearn | autosklearn/evaluation/abstract_evaluator.py | {
"start": 1413,
"end": 3451
} | class ____(DummyClassifier):
def __init__(
self,
config: Configuration,
random_state: Optional[Union[int, np.random.RandomState]],
feat_type: Optional[FEAT_TYPE_TYPE] = None,
init_params: Optional[Dict[str, Any]] = None,
dataset_properties: Dict[str, Any] = {},
... | MyDummyClassifier |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 222346,
"end": 222764
} | class ____(spack.error.SpecError):
def __init__(self, msg, *specs):
spec_fmt = (
"{namespace}.{name}{@version}{variants}"
"{ platform=architecture.platform}{ os=architecture.os}{ target=architecture.target}"
"{/hash:7}"
)
specs_str = "\n " + "\n ".join(s... | AmbiguousHashError |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP045.py | {
"start": 695,
"end": 1866
} | class ____:
service_specification: Optional[str]is not True = None
# Test for: https://github.com/astral-sh/ruff/issues/18508
# Optional[None] should not be offered a fix
foo: Optional[None] = None
from typing import NamedTuple, Optional
import typing_extensions
from typing_extensions import (
NamedTuple a... | ServiceRefOrValue |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 260245,
"end": 261541
} | class ____(rv_continuous):
r"""A Lomax (Pareto of the second kind) continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `lomax` is:
.. math::
f(x, c) = \frac{c}{(1+x)^{c+1}}
for :math:`x \ge 0`, :math:`c > 0`.
`lomax` takes ``c`` as ... | lomax_gen |
python | mwaskom__seaborn | seaborn/_core/subplots.py | {
"start": 411,
"end": 9964
} | class ____:
"""
Interface for creating and using matplotlib subplots based on seaborn parameters.
Parameters
----------
subplot_spec : dict
Keyword args for :meth:`matplotlib.figure.Figure.subplots`.
facet_spec : dict
Parameters that control subplot faceting.
pair_spec : dic... | Subplots |
python | getsentry__sentry | tests/sentry/tasks/test_commits.py | {
"start": 986,
"end": 13122
} | class ____(TestCase):
def _test_simple_action(self, user, org):
repo = Repository.objects.create(name="example", provider="dummy", organization_id=org.id)
release = Release.objects.create(organization_id=org.id, version="abcabcabc")
commit = Commit.objects.create(organization_id=org.id, rep... | FetchCommitsTest |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 12940,
"end": 13510
} | class ____:
params = (["all", "any"], [0, 1])
param_names = ["how", "axis"]
def setup(self, how, axis):
self.df = DataFrame(np.random.randn(10000, 1000))
self.df.iloc[50:1000, 20:50] = np.nan
self.df.iloc[2000:3000] = np.nan
self.df.iloc[:, 60:70] = np.nan
self.df_mi... | Dropna |
python | allegroai__clearml | clearml/storage/helper.py | {
"start": 5739,
"end": 14822
} | class ____(_Driver):
"""LibCloud http/https adapter (simple, enough for now)"""
timeout_connection = deferred_config("http.timeout.connection", 30)
timeout_total = deferred_config("http.timeout.total", 30)
max_retries = deferred_config("http.download.max_retries", 15)
min_kbps_speed = 50
schem... | _HttpDriver |
python | huggingface__transformers | src/transformers/models/aya_vision/modeling_aya_vision.py | {
"start": 7219,
"end": 14914
} | class ____(AyaVisionPreTrainedModel):
_checkpoint_conversion_mapping = {
r"^language_model.model": "language_model",
}
def __init__(self, config: AyaVisionConfig):
super().__init__(config)
self.vision_tower = AutoModel.from_config(config.vision_config)
self.multi_modal_proj... | AyaVisionModel |
python | joblib__joblib | joblib/_dask.py | {
"start": 3868,
"end": 13217
} | class ____(AutoBatchingMixin, ParallelBackendBase):
MIN_IDEAL_BATCH_DURATION = 0.2
MAX_IDEAL_BATCH_DURATION = 1.0
supports_retrieve_callback = True
default_n_jobs = -1
def __init__(
self,
scheduler_host=None,
scatter=None,
client=None,
loop=None,
wait... | DaskDistributedBackend |
python | gevent__gevent | src/gevent/tests/test__subprocess.py | {
"start": 858,
"end": 12371
} | class ____(greentest.TestCase):
# Use the normal error handling. Make sure that any background greenlets
# subprocess spawns propagate errors as expected.
error_fatal = False
def test_exit(self):
popen = subprocess.Popen([sys.executable, '-c', 'import sys; sys.exit(10)'])
self.assertEq... | TestPopen |
python | doocs__leetcode | solution/2500-2599/2585.Number of Ways to Earn Points/Solution.py | {
"start": 0,
"end": 515
} | class ____:
def waysToReachTarget(self, target: int, types: List[List[int]]) -> int:
n = len(types)
mod = 10**9 + 7
f = [[0] * (target + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
count, marks = types[i - 1]
for j in range(target +... | Solution |
python | django__django | tests/serializers/models/data.py | {
"start": 1252,
"end": 1331
} | class ____(models.Model):
data = models.FilePathField(null=True)
| FilePathData |
python | kamyu104__LeetCode-Solutions | Python/count-beautiful-splits-in-an-array.py | {
"start": 984,
"end": 1636
} | class ____(object):
def beautifulSplits(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [[0]*len(nums) for _ in xrange(len(nums))]
for i in reversed(xrange(len(nums))):
for j in xrange(i+1, len(dp)):
dp[i][j] = 1+(dp[i+1][j+1] i... | Solution2 |
python | python__mypy | mypy/inspections.py | {
"start": 6147,
"end": 23813
} | class ____:
"""Engine for locating and statically inspecting expressions."""
def __init__(
self,
fg_manager: FineGrainedBuildManager,
*,
verbosity: int = 0,
limit: int = 0,
include_span: bool = False,
include_kind: bool = False,
include_object_att... | InspectionEngine |
python | numpy__numpy | numpy/matrixlib/tests/test_matrix_linalg.py | {
"start": 1598,
"end": 1658
} | class ____(PinvCases, MatrixTestCase):
pass
| TestPinvMatrix |
python | getsentry__sentry | src/sentry/integrations/jira_server/integration.py | {
"start": 11227,
"end": 53014
} | class ____(IssueSyncIntegration):
"""
IntegrationInstallation implementation for Jira-Server
"""
comment_key = "sync_comments"
outbound_status_key = "sync_status_forward"
inbound_status_key = "sync_status_reverse"
outbound_assignee_key = "sync_forward_assignment"
inbound_assignee_key = ... | JiraServerIntegration |
python | pyparsing__pyparsing | pyparsing/exceptions.py | {
"start": 10027,
"end": 10332
} | class ____(ParseFatalException):
"""
Just like :class:`ParseFatalException`, but thrown internally
when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates
that parsing is to stop immediately because an unbacktrackable
syntax error has been found.
"""
| ParseSyntaxException |
python | django__django | django/db/models/fields/json.py | {
"start": 23551,
"end": 23667
} | class ____(
CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IEndsWith
):
pass
| KeyTransformIEndsWith |
python | numpy__numpy | numpy/_core/tests/test_numerictypes.py | {
"start": 12939,
"end": 13361
} | class ____:
def _bad_call(self):
ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8')
return ary['f0', 'f1']
def test_no_tuple(self):
assert_raises(IndexError, self._bad_call)
def test_return(self):
ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c... | TestMultipleFields |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py | {
"start": 48026,
"end": 48248
} | class ____(RendezvousBackend):
@property
def name(self):
return "dummy_backend"
def get_state(self):
return None
def set_state(self, state, token):
return None
| DummyRendezvousBackend |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py | {
"start": 1449,
"end": 1814
} | class ____:
assertDictEqual: Callable
def assert_state_equal(
self, actual: _RendezvousState, expected: _RendezvousState
) -> None:
self.assertDictEqual(vars(actual), vars(expected))
def assert_state_empty(self, actual: _RendezvousState) -> None:
self.assertDictEqual(vars(actua... | CustomAssertMixin |
python | keras-team__keras | keras/src/trainers/data_adapters/py_dataset_adapter_test.py | {
"start": 1675,
"end": 2466
} | class ____(py_dataset_adapter.PyDataset):
def __init__(self, inputs, batch_size=32, **kwargs):
super().__init__(**kwargs)
self.inputs = inputs
self.batch_size = batch_size
@property
def num_batches(self):
return math.ceil(len(self.inputs["x"]) / self.batch_size)
def __g... | DictPyDataset |
python | python-attrs__attrs | tests/test_utils.py | {
"start": 34,
"end": 440
} | class ____:
"""
Tests for the testing helper function `make_class`.
"""
def test_returns_class(self):
"""
Returns a class object.
"""
assert type is simple_class().__class__
def test_returns_distinct_classes(self):
"""
Each call returns a completely ... | TestSimpleClass |
python | pytorch__pytorch | test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_misc.py | {
"start": 170,
"end": 1350
} | class ____(TestCase):
def test_backend_module_name(self):
self.assertEqual(torch._C._get_privateuse1_backend_name(), "openreg")
# backend can be renamed to the same name multiple times
torch.utils.rename_privateuse1_backend("openreg")
with self.assertRaisesRegex(RuntimeError, "has al... | TestBackendModule |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/plugins.py | {
"start": 2797,
"end": 4094
} | class ____(BaseModel):
"""Plugin serializer."""
name: str
macros: list[str]
flask_blueprints: list[str]
fastapi_apps: list[FastAPIAppResponse]
fastapi_root_middlewares: list[FastAPIRootMiddlewareResponse]
external_views: list[ExternalViewResponse] = Field(
description="Aggregate all... | PluginResponse |
python | getsentry__sentry | src/sentry/newsletter/dummy.py | {
"start": 2021,
"end": 4190
} | class ____(Newsletter):
"""
The ``DummyNewsletter`` implementation is primarily used for test cases. It uses a in-memory
store for tracking subscriptions, which means its not suitable for any real production use-case.
"""
def __init__(self, enabled: bool = False) -> None:
self._subscription... | DummyNewsletter |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/private.py | {
"start": 285,
"end": 557
} | class ____:
#: A public class attribute whose name starts with an underscore.
#:
#: :meta public:
_public_attribute = 47
#: A private class attribute whose name does not start with an underscore.
#:
#: :meta private:
private_attribute = 11
| Foo |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/markdown.py | {
"start": 11537,
"end": 11649
} | class ____(TypedDict):
"""Header type as typed dict."""
level: int
name: str
data: str
| HeaderType |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 177706,
"end": 183979
} | class ____(DataplexCatalogBaseOperator):
"""
Update an Entry resource.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataplexCatalogUpdateEntryOperator`
:param project_id: Required. The ID of the Google Cloud project that ... | DataplexCatalogUpdateEntryOperator |
python | run-llama__llama_index | llama-index-core/llama_index/core/objects/fn_node_mapping.py | {
"start": 262,
"end": 1933
} | class ____(BaseObjectNodeMapping[Any]):
"""Fn node mapping."""
def __init__(
self,
from_node_fn: Callable[[BaseNode], Any],
to_node_fn: Callable[[Any], BaseNode],
) -> None:
self._to_node_fn = to_node_fn
self._from_node_fn = from_node_fn
@classmethod
def fro... | FnNodeMapping |
python | kamyu104__LeetCode-Solutions | Python/reducing-dishes.py | {
"start": 33,
"end": 402
} | class ____(object):
def maxSatisfaction(self, satisfaction):
"""
:type satisfaction: List[int]
:rtype: int
"""
satisfaction.sort(reverse=True)
result, curr = 0, 0
for x in satisfaction:
curr += x
if curr <= 0:
break
... | Solution |
python | pallets__click | src/click/core.py | {
"start": 57465,
"end": 57721
} | class ____(type):
def __subclasscheck__(cls, subclass: type) -> bool:
return issubclass(subclass, cls.__bases__[0])
def __instancecheck__(cls, instance: t.Any) -> bool:
return isinstance(instance, cls.__bases__[0])
| _FakeSubclassCheck |
python | pytorch__pytorch | torch/_inductor/fx_passes/memory_estimator.py | {
"start": 390,
"end": 768
} | class ____:
storage: torch.UntypedStorage
device: torch.device
def __hash__(self) -> int:
return self.storage._cdata
def __eq__(self, other: object) -> bool:
if not isinstance(other, StorageKey):
return False
return (
self.storage._cdata == other.storage... | StorageKey |
python | conda__conda | conda/plugins/types.py | {
"start": 8394,
"end": 8832
} | class ____(CondaPlugin):
"""
Return type to use when the defining the conda auth handlers hook.
:param name: Name (e.g., ``basic-auth``). This name should be unique
and only one may be registered at a time.
:param handler: Type that will be used as the authentication handler
... | CondaAuthHandler |
python | pytorch__pytorch | torch/utils/mobile_optimizer.py | {
"start": 237,
"end": 6414
} | class ____(Enum):
BUNDLED_INPUT = 1
REQUIRES_GRAD = 2
DROPOUT = 3
BATCHNORM = 4
def optimize_for_mobile(
script_module: torch.jit.ScriptModule,
optimization_blocklist: set[MobileOptimizerType] | None = None,
preserved_methods: list[AnyStr] | None = None,
backend: str = '... | LintCode |
python | getsentry__sentry | src/sentry/integrations/jira/utils/create_issue_schema_transformers.py | {
"start": 297,
"end": 4876
} | class ____(Exception):
pass
def parse_number_field(num_str: Any) -> int | float:
try:
if isinstance(num_str, str) and "." in num_str:
return float(num_str)
return int(num_str)
except ValueError:
raise JiraSchemaParseError(f"Invalid number value provided for field: '{nu... | JiraSchemaParseError |
python | bokeh__bokeh | src/bokeh/core/query.py | {
"start": 7642,
"end": 7963
} | class ____(_Operator):
''' Predicate to test if property values are less than some value.
Construct and ``LT`` predicate as a dict with ``LT`` as the key,
and a value to compare against.
.. code-block:: python
# matches any models with .size < 10
dict(size={ LT: 10 })
'''
pas... | LT |
python | kamyu104__LeetCode-Solutions | Python/k-divisible-elements-subarrays.py | {
"start": 804,
"end": 1720
} | class ____(object):
def countDistinct(self, nums, k, p):
"""
:type nums: List[int]
:type k: int
:type p: int
:rtype: int
"""
MOD, P = 10**9+7, 113
def check(nums, lookup, l, i):
return all(any(nums[i+k] != nums[j+k] for k in xrange(l)) for ... | Solution2 |
python | jina-ai__jina | tests/integration/streaming/test_streaming.py | {
"start": 1520,
"end": 3999
} | class ____(Executor):
@requests(on='/hello')
async def task(self, doc: Document, **kwargs):
for i in range(5):
yield Document(text=f'{doc.text} {i}')
await asyncio.sleep(0.5)
@pytest.mark.asyncio
@pytest.mark.parametrize('protocol', ['http', 'grpc'])
@pytest.mark.parametrize('i... | WaitStreamExecutor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypeEquals1.py | {
"start": 1210,
"end": 1613
} | class ____:
pass
def func6(val: AFinal | BFinal) -> None:
if type(val) == AFinal:
reveal_type(val, expected_text="AFinal")
else:
reveal_type(val, expected_text="BFinal")
def func7(val: Any):
if type(val) == int:
reveal_type(val, expected_text="int")
else:
reveal_t... | BFinal |
python | getsentry__sentry | fixtures/page_objects/base.py | {
"start": 100,
"end": 409
} | class ____:
"""Base class for PageObjects"""
def __init__(self, browser: Browser):
self.browser = browser
@property
def driver(self):
return self.browser.driver
def wait_until_loaded(self):
self.browser.wait_until_not('[data-test-id="loading-indicator"]')
| BasePage |
python | sympy__sympy | sympy/functions/special/bessel.py | {
"start": 30139,
"end": 32635
} | class ____(SphericalBesselBase):
r"""
Spherical Bessel function of the first kind.
Explanation
===========
This function is a solution to the spherical Bessel equation
.. math ::
z^2 \frac{\mathrm{d}^2 w}{\mathrm{d}z^2}
+ 2z \frac{\mathrm{d}w}{\mathrm{d}z} + (z^2 - \nu(\nu +... | jn |
python | getsentry__sentry | src/sentry/notifications/models/notificationaction.py | {
"start": 861,
"end": 1286
} | class ____(IntEnum):
@classmethod
def as_choices(cls) -> tuple[tuple[int, str], ...]:
raise NotImplementedError
@classmethod
def get_name(cls, value: int) -> str | None:
return dict(cls.as_choices()).get(value)
@classmethod
def get_value(cls, name: str) -> int | None:
i... | FlexibleIntEnum |
python | openai__openai-python | src/openai/types/realtime/realtime_truncation_retention_ratio.py | {
"start": 252,
"end": 691
} | class ____(BaseModel):
post_instructions: Optional[int] = None
"""
Maximum tokens allowed in the conversation after instructions (which including
tool definitions). For example, setting this to 5,000 would mean that truncation
would occur when the conversation exceeds 5,000 tokens after instructions... | TokenLimits |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 53014,
"end": 53596
} | class ____(Block):
"""Base class for the sidebar and main body containers."""
def __init__(
self,
proto: BlockProto | None,
root: ElementTree,
type: str | None = None,
) -> None:
self.children = {}
self.proto = proto
if type:
self.type = t... | SpecialBlock |
python | kamyu104__LeetCode-Solutions | Python/matrix-block-sum.py | {
"start": 37,
"end": 773
} | class ____(object):
def matrixBlockSum(self, mat, K):
"""
:type mat: List[List[int]]
:type K: int
:rtype: List[List[int]]
"""
m, n = len(mat), len(mat[0])
accu = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)]
for i in xrange(m):
for j in x... | Solution |
python | agronholm__apscheduler | src/apscheduler/executors/thread.py | {
"start": 324,
"end": 900
} | class ____(JobExecutor):
"""
Executes functions in a thread pool.
:param max_workers: the maximum number of worker threads to keep
"""
max_workers: int = 40
_limiter: CapacityLimiter = attrs.field(init=False)
async def start(self, exit_stack: AsyncExitStack) -> None:
self._limiter... | ThreadPoolJobExecutor |
python | google__pytype | pytype/tools/runner.py | {
"start": 72,
"end": 931
} | class ____:
"""Convenience wrapper around subprocess.
Use as:
ret, out, err = BinaryRun([exe, arg, ...]).communicate()
"""
def __init__(self, args, dry_run=False):
self.args = args
self.results = None
if dry_run:
self.results = (0, b"", b"")
else:
self.proc = subprocess.Popen(... | BinaryRun |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass10.py | {
"start": 616,
"end": 1116
} | class ____(A):
@staticmethod
def method1() -> None:
# This should generate an error.
return super(B).method1()
@staticmethod
def method2() -> None:
return super(B).method2()
@classmethod
def method3(cls) -> None:
# This should generate an error.
return s... | B |
python | numba__numba | numba/tests/test_unsafe_intrinsics.py | {
"start": 4723,
"end": 5345
} | class ____(TestCase):
def test_dump_refcount(self):
@njit
def use_dump_refcount():
a = np.ones(10)
b = (a, a)
dump_refcount(a)
dump_refcount(b)
# Capture output to sys.stdout
with captured_stdout() as stream:
use_dump_refco... | TestRefCount |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_export.py | {
"start": 16533,
"end": 19962
} | class ____(TestCase):
mock_request = MagicMock(spec=HttpRequest)
mock_request.POST = {"django-import-export-format": 0, "bookresource_id": True}
class TestMixin(ExportMixin):
model = Book
def __init__(self, test_str=None):
self.test_str = test_str
def get_data_for_expo... | TestExportEncoding |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_tkcairo.py | {
"start": 164,
"end": 771
} | class ____(FigureCanvasCairo, FigureCanvasTk):
def draw(self):
width = int(self.figure.bbox.width)
height = int(self.figure.bbox.height)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
self._renderer.set_context(cairo.Context(surface))
self._renderer.dpi = se... | FigureCanvasTkCairo |
python | spyder-ide__spyder | spyder/plugins/maininterpreter/container.py | {
"start": 881,
"end": 12326
} | class ____(PluginMainContainer):
sig_interpreter_changed = Signal(str)
"""
Signal to report that the main interpreter has changed.
Parameters
----------
path: str
Path to the new interpreter.
"""
sig_environments_updated = Signal(dict)
"""
This signal is emitted when t... | MainInterpreterContainer |
python | jina-ai__jina | jina/jaml/parsers/executor/legacy.py | {
"start": 222,
"end": 4515
} | class ____(BaseLegacyParser):
"""Legacy parser for executor."""
def parse(
self,
cls: Type['BaseExecutor'],
data: Dict,
runtime_args: Optional[Dict[str, Any]] = None,
) -> 'BaseExecutor':
"""
:param cls: target class type to parse into, must be a :class:`JAML... | ExecutorLegacyParser |
python | davidhalter__jedi | jedi/inference/gradual/base.py | {
"start": 11251,
"end": 11969
} | class ____(ValueWrapper):
def py__stop_iteration_returns(self):
for cls in self._wrapped_value.class_value.py__mro__():
if cls.py__name__() == 'Generator':
generics = cls.get_generics()
try:
return generics[2].execute_annotation()
... | _GenericInstanceWrapper |
python | pennersr__django-allauth | allauth/account/views.py | {
"start": 42432,
"end": 46358
} | class ____(NextRedirectMixin, FormView):
form_class = VerifyPhoneForm
template_name = (
"account/confirm_phone_verification_code." + app_settings.TEMPLATE_EXTENSION
)
@cached_property
def _action(self):
action = self.request.POST.get("action")
valid_actions = ["verify"]
... | _BaseVerifyPhoneView |
python | weaviate__weaviate-python-client | weaviate/groups/base.py | {
"start": 3449,
"end": 6160
} | class ____(Generic[ConnectionType], _BaseExecutor[ConnectionType]):
@overload
def get_assigned_roles(
self, *, group_id: str, include_permissions: Literal[False] = False
) -> executor.Result[Dict[str, RoleBase]]: ...
@overload
def get_assigned_roles(
self, *, group_id: str, include_... | _GroupsOIDCExecutor |
python | astropy__astropy | astropy/visualization/stretch.py | {
"start": 25347,
"end": 27445
} | class ____(BaseStretch):
r"""
A stretch that takes into account contrast and bias.
The stretch is given by:
.. math::
y = (x - {\rm bias}) * {\rm contrast} + 0.5
and the output values are clipped to the [0:1] range.
Parameters
----------
contrast : float
The contrast ... | ContrastBiasStretch |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_dtype.py | {
"start": 11189,
"end": 11904
} | class ____(TestCase):
def test_simple(self):
class dt:
dtype = np.dtype("f8")
assert np.dtype(dt) == np.float64
assert np.dtype(dt()) == np.float64
@skip(
reason="We simply require the .name attribute, so this "
"fails with an AttributeError."
)
def ... | TestFromDTypeAttribute |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 25979,
"end": 26111
} | class ____(Base20DeprecationWarning):
"""indicates an API that is in 'legacy' status, a long term deprecation."""
| LegacyAPIWarning |
python | tensorflow__tensorflow | tensorflow/python/summary/plugin_asset_test.py | {
"start": 887,
"end": 1055
} | class ____(plugin_asset.PluginAsset):
"""An example asset with a dummy serialize method provided, but no name."""
def assets(self):
return {}
| _UnnamedPluginAsset |
python | huggingface__transformers | src/transformers/models/deepseek_vl_hybrid/modeling_deepseek_vl_hybrid.py | {
"start": 9257,
"end": 10749
} | class ____(PreTrainedModel):
config: DeepseekVLHybridConfig
base_model_prefix = "model"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["LlamaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values", "causal_mask"]
_supports_flash_attn ... | DeepseekVLHybridPreTrainedModel |
python | tensorflow__tensorflow | tensorflow/python/training/input_test.py | {
"start": 16707,
"end": 17391
} | class ____(test_lib.TestCase):
def testListInputs(self):
l = [1, 2, 3, 11, 22, 33]
l2 = inp._as_tensor_list(l)
self.assertEqual(l, l2)
l3 = inp._as_original_type(l, l2)
self.assertEqual(l, l3)
def testDictInputs(self):
d = {"a": 1, "b": 2, "c": 3, "aa": 11, "bb": 22, "cc": 33}
l = inp.... | DictHelperTest |
python | mlflow__mlflow | tests/store/tracking/test_plugin_validation.py | {
"start": 2902,
"end": 4153
} | class ____(SqlAlchemyStore):
pass
db_path = r"{db_path}"
artifact_path = r"{artifact_path}"
store = PluginStore(f"sqlite:///{{db_path}}", artifact_path)
dataset = store.create_dataset("test_dataset", tags={{"key": "value"}}, experiment_ids=[])
assert dataset is not None
assert dataset.name == "test_dataset"
"""
... | PluginStore |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/operators/check_operators.py | {
"start": 4632,
"end": 6037
} | class ____(ChecksAutomationCondition):
@property
def base_name(self) -> str:
return "ANY_CHECKS_MATCH"
@property
def operator_type(self) -> OperatorType:
return "or"
async def evaluate(self, context: AutomationContext[AssetKey]) -> AutomationResult[AssetKey]: # pyright: ignore[rep... | AnyChecksCondition |
python | scipy__scipy | scipy/integrate/_ivp/rk.py | {
"start": 22150,
"end": 22800
} | class ____(DenseOutput):
def __init__(self, t_old, t, y_old, F):
super().__init__(t_old, t)
self.h = t - t_old
self.F = F
self.y_old = y_old
def _call_impl(self, t):
x = (t - self.t_old) / self.h
if t.ndim == 0:
y = np.zeros_like(self.y_old)
... | Dop853DenseOutput |
python | chroma-core__chroma | chromadb/test/property/test_collections_with_database_tenant_overwrite.py | {
"start": 793,
"end": 7713
} | class ____(
TenantDatabaseCollectionStateMachine
):
singleton_client: Client
singleton_admin_client: AdminAPI
root_client: Client
root_admin_client: AdminAPI
def __init__(
self,
singleton_client: Client,
root_client: Client,
client_factories: ClientFactories,
... | SingletonTenantDatabaseCollectionStateMachine |
python | great-expectations__great_expectations | great_expectations/exceptions/resource_freshness.py | {
"start": 2275,
"end": 2594
} | class ____(ResourceFreshnessError):
def __init__(self, name: str) -> None:
super().__init__(
f"BatchDefinition '{name}' has changed since it has last been saved. "
"Please update using the parent asset or data source, then try your action again."
)
| BatchDefinitionNotFreshError |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 28145,
"end": 28617
} | class ____(AbstractTemplate):
def generic(self, args, kws):
assert not kws
[arg] = args
if isinstance(arg, (types.Boolean, types.Number)):
return signature(types.boolean, arg)
# XXX typing for bool cannot be polymorphic because of the
# types.Function thing, so w... | Bool |
python | tox-dev__tox | src/tox/config/of_type.py | {
"start": 2249,
"end": 4802
} | class ____(ConfigDefinition[T]): # noqa: PLW1641
"""A configuration definition that comes from a source (such as in memory, an ini file, a toml file, etc.)."""
def __init__( # noqa: PLR0913
self,
keys: Iterable[str],
desc: str,
of_type: type[T] | UnionType,
default: Ca... | ConfigDynamicDefinition |
python | django__django | tests/serializers/models/base.py | {
"start": 1945,
"end": 2166
} | class ____(models.Model):
author = models.OneToOneField(Author, models.CASCADE, primary_key=True)
date_of_birth = models.DateField()
def __str__(self):
return "Profile of %s" % self.author
| AuthorProfile |
python | pytorch__pytorch | torch/backends/cuda/__init__.py | {
"start": 2509,
"end": 3797
} | class ____:
r"""
Represent all cuFFT plan caches, return the cuFFTPlanCache for a given device when indexed.
Finally, this object, when used directly as a `cuFFTPlanCache` object (e.g.,
setting the `.max_size`) attribute, the current device's cuFFT plan cache is
used.
"""
__initialized = F... | cuFFTPlanCacheManager |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py | {
"start": 118974,
"end": 119692
} | class ____(GeneratedAirbyteDestination):
@public
def __init__(self, name: str, host: str, api_key: Optional[str] = None):
"""Airbyte Destination for Meilisearch.
Documentation can be found at https://docs.airbyte.com/integrations/destinations/meilisearch
Args:
name (str): T... | MeilisearchDestination |
python | sqlalchemy__sqlalchemy | test/orm/test_cycles.py | {
"start": 46472,
"end": 47584
} | class ____(fixtures.DeclarativeMappedTest):
"""test #12748"""
run_setup_classes = "each"
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
count = 0
def _counter():
nonlocal count
count += 1
return count
class Parent... | PostUpdatePrefetchTest |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 14267,
"end": 14684
} | class ____(Static, can_focus=True, inherit_bindings=False):
"""A widget that has its own bindings for the movement keys, no binding inheritance."""
BINDINGS = AppKeyRecorder.make_bindings("local_")
async def action_local_record(self, key: str) -> None:
# Sneaky forward reference. Just for the purp... | WidgetWithBindingsNoInherit |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/types.py | {
"start": 766,
"end": 1118
} | class ____:
"""Base for MySQL numeric types.
This is the base both for NUMERIC as well as INTEGER, hence
it's a mixin.
"""
def __init__(
self, unsigned: bool = False, zerofill: bool = False, **kw: Any
):
self.unsigned = unsigned
self.zerofill = zerofill
super()... | _NumericCommonType |
python | django__django | tests/migrations/migrations_test_apps/alter_fk/author_app/migrations/0002_alter_id.py | {
"start": 43,
"end": 421
} | class ____(migrations.Migration):
dependencies = [
("author_app", "0001_initial"),
("book_app", "0001_initial"), # Forces the book table to alter the FK
]
operations = [
migrations.AlterField(
model_name="author",
name="id",
field=models.CharFiel... | Migration |
python | getsentry__sentry | src/sentry/discover/endpoints/discover_key_transactions.py | {
"start": 5632,
"end": 6534
} | class ____(KeyTransactionBase):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (KeyTransactionPermission,)
def get(self, request: Request, organization: Organization) -> Response:
if not self.has_feature(organization, request):
return Response(sta... | KeyTransactionListEndpoint |
python | walkccc__LeetCode | solutions/3159. Find Occurrences of an Element in an Array/3159.py | {
"start": 0,
"end": 295
} | class ____:
def occurrencesOfElement(
self,
nums: list[int],
queries: list[int],
x: int,
) -> list[int]:
indices = [i for i, num in enumerate(nums) if num == x]
return [indices[query - 1] if query <= len(indices) else -1
for query in queries]
| Solution |
python | pyinstaller__pyinstaller | PyInstaller/utils/osx.py | {
"start": 12999,
"end": 31254
} | class ____(Exception):
"""
Exception raised by `binary_to_target_arch` when the passed binary fails the strict architecture check.
"""
def __init__(self, message):
url = "https://pyinstaller.org/en/stable/feature-notes.html#macos-multi-arch-support"
super().__init__(f"{message} For detai... | IncompatibleBinaryArchError |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/comments.py | {
"start": 23769,
"end": 24160
} | class ____(CommentedMapView):
__slots__ = ()
def __contains__(self, value):
# type: (Any) -> Any
for key in self._mapping:
if value == self._mapping[key]:
return True
return False
def __iter__(self):
# type: () -> Any
for key in self._map... | CommentedMapValuesView |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 8418,
"end": 8778
} | class ____:
scheduling: SchedulingConstructor
wrapper_codegen: WrapperConstructor
cpp_wrapper_codegen: Optional[WrapperConstructor] = None
fx_wrapper_codegen: Optional[WrapperConstructor] = None
KernelArgType = Union[WorkspaceArg, TensorArg, SizeArg, TMADescriptorArg, ConstexprArg]
device_codegens: d... | DeviceCodegen |
python | google__pytype | pytype/tests/test_dataclass_transform.py | {
"start": 3050,
"end": 7196
} | class ____(test_base.BaseTest):
"""Tests for @dataclass_transform on classes."""
def test_single_inheritance(self):
self.CheckWithErrors("""
from typing_extensions import dataclass_transform
@dataclass_transform()
class Base: ...
class A(Base):
x: int
y: str
... | TestClass |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/powerbi.py | {
"start": 6409,
"end": 8930
} | class ____(BaseOperator):
"""
Gets a list of workspaces where the service principal from the connection is assigned as admin.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:PowerBIWorkspaceListOperator`
:param conn_id: The ... | PowerBIWorkspaceListOperator |
python | python-markdown__markdown | markdown/extensions/codehilite.py | {
"start": 9778,
"end": 11192
} | class ____(Treeprocessor):
""" Highlight source code in code blocks. """
config: dict[str, Any]
def code_unescape(self, text: str) -> str:
"""Unescape code."""
text = text.replace("<", "<")
text = text.replace(">", ">")
# Escaped '&' should be replaced at the end to a... | HiliteTreeprocessor |
python | openai__openai-python | src/openai/types/chat/chat_completion_token_logprob.py | {
"start": 867,
"end": 1769
} | class ____(BaseModel):
token: str
"""The token."""
bytes: Optional[List[int]] = None
"""A list of integers representing the UTF-8 bytes representation of the token.
Useful in instances where characters are represented by multiple tokens and
their byte representations must be combined to genera... | ChatCompletionTokenLogprob |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 198962,
"end": 202228
} | class ____(ParseElementEnhance):
"""Lookbehind matching of the given parse expression.
``PrecededBy`` does not advance the parsing position within the
input string, it only verifies that the specified parse expression
matches prior to the current position. ``PrecededBy`` always
returns a null token... | PrecededBy |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-ollama/llama_index/embeddings/ollama/base.py | {
"start": 355,
"end": 5083
} | class ____(BaseEmbedding):
"""Class for Ollama embeddings."""
base_url: str = Field(description="Base url the model is hosted by Ollama")
model_name: str = Field(description="The Ollama model to use.")
embed_batch_size: int = Field(
default=DEFAULT_EMBED_BATCH_SIZE,
description="The bat... | OllamaEmbedding |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 106920,
"end": 107269
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("user_id", "client_mutation_id")
user_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="userId")
client_mutation_id = sgqlc.types.Field(String, graphql_name="cli... | FollowUserInput |
python | realpython__materials | python-mixins/utils.py | {
"start": 35,
"end": 290
} | class ____:
def __setitem__(self, key, value):
super().__setitem__(key, value)
print(f"Item set: {key=!r}, {value=!r}")
def __delitem__(self, key):
super().__delitem__(key)
print(f"Item deleted: {key=!r}")
| DebugMixin |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec14.py | {
"start": 396,
"end": 723
} | class ____:
@deco
@classmethod
def identity_cls(cls, val: float) -> float:
return val
@deco
@staticmethod
def identity_static(val: float) -> float:
return val
reveal_type(ClassA.identity_cls(1.2), expected_text="int")
reveal_type(ClassA.identity_static(1.2), expected_text="int... | ClassA |
python | PyCQA__pylint | pylint/pyreverse/diagrams.py | {
"start": 10104,
"end": 13099
} | class ____(ClassDiagram):
"""Package diagram handling."""
TYPE = "package"
def modules(self) -> list[PackageEntity]:
"""Return all module nodes in the diagram."""
return [o for o in self.objects if isinstance(o, PackageEntity)]
def module(self, name: str) -> PackageEntity:
"""... | PackageDiagram |
python | encode__django-rest-framework | tests/test_renderers.py | {
"start": 4584,
"end": 10571
} | class ____(TestCase):
"""
End-to-end testing of renderers using an RendererMixin on a generic view.
"""
def test_default_renderer_serializes_content(self):
"""If the Accept header is not set the default renderer should serialize the response."""
resp = self.client.get('/')
self.a... | RendererEndToEndTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/enum1.py | {
"start": 8165,
"end": 8264
} | class ____(TestEnum22Base):
A = 1
reveal_type(TestEnum22.A.value, expected_text="str")
| TestEnum22 |
python | pyqtgraph__pyqtgraph | pyqtgraph/exporters/CSVExporter.py | {
"start": 264,
"end": 4580
} | class ____(Exporter):
Name = "CSV of original plot data"
windows = []
def __init__(self, item):
Exporter.__init__(self, item)
self.params = Parameter.create(name='params', type='group', children=[
{
'name': 'separator',
'title': translate("Exporter... | CSVExporter |
python | numba__numba | numba/cuda/tests/cudapy/test_idiv.py | {
"start": 129,
"end": 1056
} | class ____(CUDATestCase):
def test_inplace_div(self):
@cuda.jit(void(float32[:, :], int32, int32))
def div(grid, l_x, l_y):
for x in range(l_x):
for y in range(l_y):
grid[x, y] /= 2.0
x = np.ones((2, 2), dtype=np.float32)
grid = cuda.... | TestCudaIDiv |
python | Lightning-AI__lightning | examples/pytorch/domain_templates/semantic_segmentation.py | {
"start": 1783,
"end": 5595
} | class ____(Dataset):
"""Class for KITTI Semantic Segmentation Benchmark dataset.
Dataset link - http://www.cvlibs.net/datasets/kitti/eval_semseg.php?benchmark=semantics2015
There are 34 classes in the given labels. However, not all of them are useful for training
(like railings on highways, road divid... | KITTI |
python | networkx__networkx | networkx/classes/tests/dispatch_interface.py | {
"start": 873,
"end": 954
} | class ____(MultiGraph):
__networkx_backend__ = "nx_loopback"
| LoopbackMultiGraph |
python | huggingface__transformers | src/transformers/models/swin/modeling_swin.py | {
"start": 1539,
"end": 2487
} | class ____(ModelOutput):
r"""
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
... | SwinEncoderOutput |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.