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 | pypa__pip | src/pip/_vendor/idna/core.py | {
"start": 259,
"end": 366
} | class ____(UnicodeError):
"""Base exception for all IDNA-encoding related problems"""
pass
| IDNAError |
python | openai__openai-python | src/openai/types/responses/parsed_response.py | {
"start": 3232,
"end": 3799
} | class ____(Response, GenericModel, Generic[ContentType]):
if TYPE_CHECKING:
output: List[ParsedResponseOutputItem[ContentType]] # type: ignore[assignment]
else:
output: List[ParsedResponseOutputItem]
@property
def output_parsed(self) -> Optional[ContentType]:
for output in self... | ParsedResponse |
python | realpython__materials | structural-pattern-matching/repl_enhanced.py | {
"start": 1778,
"end": 3891
} | class ____:
lines: list[str] = field(default_factory=list)
def execute(self) -> None:
exec("\n".join(self.lines), globals())
self.lines = []
def main() -> None:
print('Type "help" for more information, "exit" or "quit" to finish.')
console = Console()
block = CodeBlock()
while... | CodeBlock |
python | doocs__leetcode | lcof2/剑指 Offer II 017. 含有所有字符的最短字符串/Solution.py | {
"start": 0,
"end": 816
} | class ____:
def minWindow(self, s: str, t: str) -> str:
m, n = len(s), len(t)
if n > m:
return ""
need, window = defaultdict(int), defaultdict(int)
for c in t:
need[c] += 1
start, minLen = 0, inf
left, right = 0, 0
while right < m:
... | Solution |
python | scipy__scipy | scipy/signal/tests/test_signaltools.py | {
"start": 188445,
"end": 190377
} | class ____:
@skip_xp_backends(np_only=True, reason="list inputs are numpy-specific")
def test_array_like(self, xp):
# From docstring example: with lists
original = [0.0, 1, 0, 0, 1, 1, 0, 0]
impulse_response = [2, 1]
recorded = xp.asarray([0.0, 2, 1, 0, 2, 3, 1, 0, 0])
r... | TestDeconvolve |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 97260,
"end": 97497
} | class ____:
xlPrintErrorsBlank = 1 # from enum XlPrintErrors
xlPrintErrorsDash = 2 # from enum XlPrintErrors
xlPrintErrorsDisplayed = 0 # from enum XlPrintErrors
xlPrintErrorsNA = 3 # from enum XlPrintErrors
| PrintErrors |
python | scipy__scipy | scipy/integrate/tests/test_integrate.py | {
"start": 6540,
"end": 7693
} | class ____(TestODEClass):
ode_class = complex_ode
def test_vode(self):
# Check the vode solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if not problem.stiff:
self._do_problem(problem, 'vode', 'adams')
else:
self._d... | TestComplexOde |
python | spyder-ide__spyder | spyder/plugins/plots/widgets/main_widget.py | {
"start": 1636,
"end": 16701
} | class ____(ShellConnectMainWidget):
# PluginMainWidget API
SHOW_MESSAGE_WHEN_EMPTY = True
IMAGE_WHEN_EMPTY = "plots"
MESSAGE_WHEN_EMPTY = _("No plots to show")
DESCRIPTION_WHEN_EMPTY = _(
"Run plot-generating code in the Editor or IPython console to see "
"your figures appear here. ... | PlotsWidget |
python | python-attrs__attrs | tests/test_validators.py | {
"start": 3429,
"end": 6255
} | class ____:
"""
Tests for `matches_re`.
"""
def test_in_all(self):
"""
validator is in ``__all__``.
"""
assert matches_re.__name__ in validator_module.__all__
def test_match(self):
"""
Silent on matches, raises ValueError on mismatches.
"""
... | TestMatchesRe |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_polymorphic_rel.py | {
"start": 1200,
"end": 64394
} | class ____:
__sparse_driver_backend__ = True
__dialect__ = "default_enhanced"
@classmethod
def setup_mappers(cls):
super().setup_mappers()
global people, engineers, managers, boss
global companies, paperwork, machines
people, engineers, managers, boss, companies, paperwo... | _PolymorphicTestBase |
python | google__jax | tests/pallas/tpu_pallas_interpret_test.py | {
"start": 1926,
"end": 2079
} | class ____():
"""Represents a grid point and the ID of the core that has processed it."""
grid_point: tuple[int, ...]
core_id: int
| ProcessedGridPoint |
python | pytest-dev__pytest | src/_pytest/doctest.py | {
"start": 16665,
"end": 25478
} | class ____(Module):
def collect(self) -> Iterable[DoctestItem]:
import doctest
class MockAwareDocTestFinder(doctest.DocTestFinder):
py_ver_info_minor = sys.version_info[:2]
is_find_lineno_broken = (
py_ver_info_minor < (3, 11)
or (py_ver_info_... | DoctestModule |
python | anthropics__anthropic-sdk-python | src/anthropic/resources/models.py | {
"start": 11794,
"end": 12088
} | class ____:
def __init__(self, models: Models) -> None:
self._models = models
self.retrieve = to_streamed_response_wrapper(
models.retrieve,
)
self.list = to_streamed_response_wrapper(
models.list,
)
| ModelsWithStreamingResponse |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 21926,
"end": 24202
} | class ____(AppKeyRecorder):
"""An application with a priority binding."""
BINDINGS = [
Binding("0", "record('app_0')", "0", priority=False),
Binding("a", "record('app_a')", "a", priority=True),
Binding("b", "record('app_b')", "b", priority=False),
Binding("c", "record('app_c')",... | PriorityOverlapApp |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0046_identifier_null.py | {
"start": 149,
"end": 558
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0045_alter_build_status"),
]
operations = [
migrations.AlterField(
model_name="version",
name="identifier",
field=models.CharField(
blank=True, m... | Migration |
python | ray-project__ray | python/ray/tune/tests/test_tune_restore.py | {
"start": 18457,
"end": 21762
} | class ____(unittest.TestCase):
def test(self):
"""Trainable crashes with fail_fast flag and the original crash message
should bubble up."""
def f(config):
ray.tune.report({"a": 1})
time.sleep(0.1)
raise RuntimeError("Error happens in trainable!!")
... | TrainableCrashWithFailFast |
python | google__pytype | pytype/tests/test_reingest1.py | {
"start": 150,
"end": 6546
} | class ____(test_base.BaseTest):
"""Tests for reloading the pyi we generate."""
def test_container(self):
ty = self.Infer("""
class Container:
def Add(self):
pass
class A(Container):
pass
""")
with test_utils.Tempdir() as d:
d.create_file("foo.pyi", pytd_utils... | ReingestTest |
python | huggingface__transformers | src/transformers/models/superpoint/modeling_superpoint.py | {
"start": 14524,
"end": 19471
} | class ____(SuperPointPreTrainedModel):
"""
SuperPoint model. It consists of a SuperPointEncoder, a SuperPointInterestPointDecoder and a
SuperPointDescriptorDecoder. SuperPoint was proposed in `SuperPoint: Self-Supervised Interest Point Detection and
Description <https://huggingface.co/papers/1712.07629>... | SuperPointForKeypointDetection |
python | ray-project__ray | rllib/offline/offline_env_runner.py | {
"start": 865,
"end": 13101
} | class ____(SingleAgentEnvRunner):
"""The environment runner to record the single agent case."""
@override(SingleAgentEnvRunner)
@OverrideToImplementCustomLogic_CallToSuperRecommended
def __init__(self, *, config: AlgorithmConfig, **kwargs):
# Initialize the parent.
super().__init__(conf... | OfflineSingleAgentEnvRunner |
python | coleifer__peewee | playhouse/pool.py | {
"start": 2111,
"end": 2360
} | class ____(object):
def __lt__(self, other):
return True
def locked(fn):
@functools.wraps(fn)
def inner(self, *args, **kwargs):
with self._pool_lock:
return fn(self, *args, **kwargs)
return inner
| _sentinel |
python | numba__numba | numba/stencils/stencilparfor.py | {
"start": 41974,
"end": 44974
} | class ____(object):
def __init__(self, typingctx, targetctx, args, f_ir):
from numba.core.compiler import StateDict
self.state = StateDict()
self.state.typingctx = typingctx
self.state.targetctx = targetctx
self.state.args = args
self.state.func_ir = f_ir
self... | DummyPipeline |
python | doocs__leetcode | solution/2200-2299/2213.Longest Substring of One Repeating Character/Solution.py | {
"start": 243,
"end": 1891
} | class ____:
__slots__ = "s", "tr"
def __init__(self, s: str):
self.s = list(s)
n = len(s)
self.tr: List[Node | None] = [None] * (n * 4)
self.build(1, 1, n)
def build(self, u: int, l: int, r: int):
self.tr[u] = Node(l, r)
if l == r:
return
... | SegmentTree |
python | kamyu104__LeetCode-Solutions | Python/find-sum-of-array-product-of-magical-sequences.py | {
"start": 65,
"end": 1723
} | class ____(object):
def magicalSum(self, m, k, nums):
"""
:type m: int
:type k: int
:type nums: List[int]
:rtype: int
"""
def popcount(x):
return bin(x).count('1')
MOD = 10**9+7
fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]
... | Solution |
python | davidhalter__jedi | jedi/inference/value/klass.py | {
"start": 18905,
"end": 19275
} | class ____(AbstractSignature):
"""
It represents the ``__init__`` signature of a class with dataclass semantics.
.. code:: python
"""
def __init__(self, value, param_names):
super().__init__(value)
self._param_names = param_names
def get_param_names(self, resolve_stars=False):... | DataclassSignature |
python | mlflow__mlflow | tests/tracking/integration_test_utils.py | {
"start": 3597,
"end": 5159
} | class ____(Thread):
"""Run a FastAPI/uvicorn app in a background thread, usable as a context manager."""
def __init__(self, app: FastAPI, port: int):
super().__init__(name="mlflow-tracking-server", daemon=True)
self.host = "127.0.0.1"
self.port = port
self.url = f"http://{self.h... | ServerThread |
python | getsentry__sentry | src/sentry/issues/suspect_flags.py | {
"start": 335,
"end": 430
} | class ____(TypedDict):
baseline: dict[str, float]
outliers: dict[str, float]
| Distribution |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 35846,
"end": 37690
} | class ____(TransactionTestCase):
browser: Browser
@pytest.fixture(autouse=True)
def _setup_today(self):
with mock.patch(
"django.utils.timezone.now",
return_value=(datetime(2013, 5, 18, 15, 13, 58, 132928, tzinfo=UTC)),
):
yield
def wait_for_loading(... | AcceptanceTestCase |
python | pypa__virtualenv | src/virtualenv/create/describe.py | {
"start": 2507,
"end": 2710
} | class ____(Describe, ABC):
@classmethod
def can_describe(cls, interpreter):
return interpreter.version_info.major == 3 and super().can_describe(interpreter) # noqa: PLR2004
| Python3Supports |
python | celery__celery | t/unit/worker/test_revoke.py | {
"start": 34,
"end": 238
} | class ____:
def test_is_working(self):
state.revoked.add('foo')
assert 'foo' in state.revoked
state.revoked.pop_value('foo')
assert 'foo' not in state.revoked
| test_revoked |
python | mozilla__bleach | tests/test_linkify.py | {
"start": 23399,
"end": 25053
} | class ____:
def test_no_href_links(self):
s = '<a name="anchor">x</a>'
assert linkify(s) == s
def test_rel_already_there(self):
"""Make sure rel attribute is updated not replaced"""
linked = 'Click <a href="http://example.com" rel="tooltip">here</a>.'
link_good = (
... | TestLinkify |
python | gevent__gevent | src/greentest/3.14/test_httpservers.py | {
"start": 58429,
"end": 62988
} | class ____(unittest.TestCase):
""" Test url parsing """
def setUp(self):
self.translated_1 = os.path.join(os.getcwd(), 'filename')
self.translated_2 = os.path.join('foo', 'filename')
self.translated_3 = os.path.join('bar', 'filename')
self.handler_1 = SocketlessRequestHandler()
... | SimpleHTTPRequestHandlerTestCase |
python | wandb__wandb | wandb/vendor/pygments/lexers/markup.py | {
"start": 15994,
"end": 16468
} | class ____(DelegatingLexer):
"""
Subclass of the `MozPreprocHashLexer` that highlights unlexed data with the
`JavascriptLexer`.
.. versionadded:: 2.0
"""
name = "Javascript+mozpreproc"
aliases = ['javascript+mozpreproc']
filenames = ['*.js.in']
mimetypes = []
def __init__(self,... | MozPreprocJavascriptLexer |
python | ray-project__ray | python/ray/data/_internal/issue_detection/detectors/high_memory_detector.py | {
"start": 1295,
"end": 4698
} | class ____(IssueDetector):
# Many nodes have a 4 GiB : 1 core ratio, but this isn't always the case (e.g., for
# high memory nodes).
_MEMORY_PER_CORE_ESTIMATE = 4 * 1024**3
def __init__(
self,
dataset_id: str,
operators: List["PhysicalOperator"],
config: HighMemoryIssueD... | HighMemoryIssueDetector |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict13.py | {
"start": 726,
"end": 853
} | class ____(ParentD):
# This should generate an error because "x" is NotRequired in the parent.
x: NotRequired[int]
| ChildD |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/collective_ops_test.py | {
"start": 52852,
"end": 54185
} | class ____(test.TestCase):
def setUp(self):
super().setUp()
_setup_context()
def testMap(self):
group_size = 2
group_key = 100
instance_key = 100
def create_dataset_and_fetch_one(t):
dataset = dataset_ops.Dataset.from_tensor_slices([t])
def reduce_fn(t):
# A token is ... | InputPipelineTest |
python | pytorch__pytorch | torch/_dynamo/variables/builtin.py | {
"start": 8130,
"end": 127999
} | class ____(VariableTracker):
"""
A VariableTracker that represents a built-in value (functions and operators).
A lot of the code here assumes it will be a function object.
The BuiltinVariable class wraps Python built-in functions (like len, isinstance, etc.)
and operators (like +, -, *, etc.) to en... | BuiltinVariable |
python | kamyu104__LeetCode-Solutions | Python/alternating-groups-i.py | {
"start": 60,
"end": 634
} | class ____(object):
def numberOfAlternatingGroups(self, colors):
"""
:type colors: List[int]
:rtype: int
"""
k = 3
result = curr = left = 0
for right in xrange(len(colors)+k-1):
if right-left+1 == k:
result += int(curr == k-1)
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/replace-all-s-to-avoid-consecutive-repeating-characters.py | {
"start": 29,
"end": 445
} | class ____(object):
def modifyString(self, s):
"""
:type s: str
:rtype: str
"""
s = list(s)
for i in xrange(len(s)):
if s[i] != '?':
continue
for c in ('a', 'b', 'c'):
if (i == 0 or s[i-1] != c) and (i == len(s)-... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super1.py | {
"start": 358,
"end": 651
} | class ____(ClassA):
def __init__(self):
pass
def method3(self):
return self.__class__()
@staticmethod
def aaa():
# This should generate an error because the zero-arg form
# of super is illegal in a static method.
super().method1()
| ClassC |
python | ray-project__ray | python/ray/air/_internal/mlflow.py | {
"start": 315,
"end": 12627
} | class ____:
"""Util class for setting up and logging to MLflow.
Use this util for any library that needs MLflow logging/tracking logic
such as Ray Tune or Ray Train.
"""
def __init__(self):
import mlflow
self._mlflow = mlflow
self.experiment_id = None
def __deepcopy__... | _MLflowLoggerUtil |
python | matplotlib__matplotlib | lib/matplotlib/sphinxext/mathmpl.py | {
"start": 3049,
"end": 7871
} | class ____(Directive):
"""
The ``.. mathmpl::`` directive, as documented in the module's docstring.
"""
has_content = True
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec = {'fontset': fontset_choice,
'fontsize': validate_flo... | MathDirective |
python | pytorch__pytorch | test/distributed/tensor/test_redistribute.py | {
"start": 27305,
"end": 31524
} | class ____(DTensorTestBase):
@property
def world_size(self) -> int:
return 8
@with_comms
def test_multi_dim_mesh(self):
devices = torch.arange(self.world_size)
for mesh_shape in [devices, devices.view(4, 2), devices.view(2, 2, 2)]:
mesh_shape = torch.arange(self.worl... | MultiDimRedistributeTest |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/events.py | {
"start": 3631,
"end": 3681
} | class ____(Event):
__slots__ = ()
| StreamEndEvent |
python | sqlalchemy__sqlalchemy | test/orm/test_cycles.py | {
"start": 42390,
"end": 43900
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"a_table",
metadata,
Column(
"id",
Integer(),
primary_key=True,
test_needs_autoincrement=True,
),
... | SelfReferentialPostUpdateTest2 |
python | lepture__authlib | authlib/jose/drafts/_jwe_algorithms.py | {
"start": 581,
"end": 7199
} | class ____(JWEAlgorithmWithTagAwareKeyAgreement):
EXTRA_HEADERS = ["epk", "apu", "apv", "skid"]
ALLOWED_KEY_CLS = (ECKey, OKPKey)
# https://datatracker.ietf.org/doc/html/draft-madden-jose-ecdh-1pu-04
def __init__(self, key_size=None):
if key_size is None:
self.name = "ECDH-1PU"
... | ECDH1PUAlgorithm |
python | fluentpython__example-code-2e | 24-class-metaprog/autoconst/autoconst_demo.py | {
"start": 742,
"end": 846
} | class ____(AutoConst):
banana
coconut
vanilla
print('Flavor.vanilla ==', Flavor.vanilla) | Flavor |
python | ansible__ansible | test/integration/targets/task-args/action_plugins/echo.py | {
"start": 84,
"end": 244
} | class ____(ActionBase):
def run(self, tmp=None, task_vars=None):
action_args = self._task.args
return dict(action_args=action_args)
| ActionModule |
python | numba__numba | numba/np/ufunc/wrappers.py | {
"start": 24350,
"end": 24997
} | class ____(object):
"""
Handle GFunc argument loading where a scalar type is used in the core
function.
Note: It still has a stride because the input to the gufunc can be an array
for this argument.
"""
def __init__(self, dtype, stride):
self.dtype = dtype
self.stride ... | _ScalarArgLoader |
python | spack__spack | lib/spack/spack/environment/environment.py | {
"start": 119695,
"end": 119807
} | class ____(SpackEnvironmentError):
"""Class for errors regarding view generation."""
| SpackEnvironmentViewError |
python | getsentry__sentry | src/sentry/incidents/endpoints/serializers/workflow_engine_detector.py | {
"start": 1669,
"end": 16136
} | class ____(Serializer):
"""
A temporary serializer to be used by the old alert rule endpoints to return data read from the new ACI models
"""
def __init__(self, expand: list[str] | None = None, prepare_component_fields: bool = False):
self.expand = expand or []
self.prepare_component_fi... | WorkflowEngineDetectorSerializer |
python | pytorch__pytorch | torch/fx/proxy.py | {
"start": 27511,
"end": 30484
} | class ____(Proxy):
"""
A special proxy which lets "shape", "size", "dim", and a few other
attribute accesses pass through to the underlying module parameter object,
so that conditional tests on these attributes will not throw exception during tracing
"""
def __init__(self, tracer: TracerBase, ... | ParameterProxy |
python | doocs__leetcode | solution/1300-1399/1317.Convert Integer to the Sum of Two No-Zero Integers/Solution2.py | {
"start": 0,
"end": 346
} | class ____:
def getNoZeroIntegers(self, n: int) -> List[int]:
def f(x: int) -> bool:
while x:
if x % 10 == 0:
return False
x //= 10
return True
for a in count(1):
b = n - a
if f(a) and f(b):
... | Solution |
python | pytest-dev__pytest-mock | src/pytest_mock/plugin.py | {
"start": 964,
"end": 1972
} | class ____:
"""
Cache MagicMock and Patcher instances so we can undo them later.
"""
cache: list[MockCacheItem] = field(default_factory=list)
def _find(self, mock: MockType) -> MockCacheItem:
for mock_item in self.cache:
if mock_item.mock is mock:
return mock_it... | MockCache |
python | scrapy__scrapy | tests/test_downloadermiddleware_robotstxt.py | {
"start": 800,
"end": 10493
} | class ____:
def setup_method(self):
self.crawler = mock.MagicMock()
self.crawler.settings = Settings()
self.crawler.engine.download_async = mock.AsyncMock()
def teardown_method(self):
del self.crawler
def test_robotstxt_settings(self):
self.crawler.settings = Settin... | TestRobotsTxtMiddleware |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias15.py | {
"start": 243,
"end": 504
} | class ____(Exception):
pass
def func1(errs: MaybeSequence[type[Exception]]):
pass
func1(HttpError)
func1(Exception)
def func2(x: MaybeSequence[type[HttpError]]):
reveal_type(x, expected_text="type[HttpError] | Sequence[type[HttpError]]")
| HttpError |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_organization_detector_index.py | {
"start": 2556,
"end": 27469
} | class ____(OrganizationDetectorIndexBaseTest):
def test_simple(self) -> None:
detector = self.create_detector(
project=self.project, name="Test Detector", type=MetricIssue.slug
)
detector_2 = self.create_detector(
project=self.project, name="Test Detector 2", type=Met... | OrganizationDetectorIndexGetTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/aggregate.py | {
"start": 1074,
"end": 1229
} | class ____:
"""The aggregation result for a text property."""
count: Optional[int]
top_occurrences: List[TopOccurrence]
@dataclass
| AggregateText |
python | Pylons__pyramid | tests/test_i18n.py | {
"start": 17231,
"end": 17427
} | class ____:
def ugettext(self, text):
return text
gettext = ugettext
def ungettext(self, singular, plural, n):
return singular
ngettext = ungettext
| DummyTranslations |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 54718,
"end": 55795
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("dataset.Dataset.to_dict"))
@mock.patch(VERTEX_AI_PATH.format("dataset.DatasetHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = ExportDataOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_ch... | TestVertexAIExportDataOperator |
python | doocs__leetcode | solution/0600-0699/0636.Exclusive Time of Functions/Solution.py | {
"start": 0,
"end": 507
} | class ____:
def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
stk = []
ans = [0] * n
pre = 0
for log in logs:
i, op, t = log.split(":")
i, cur = int(i), int(t)
if op[0] == "s":
if stk:
ans[stk[-1]] +... | Solution |
python | tox-dev__tox | src/tox/tox_env/python/virtual_env/package/pyproject.py | {
"start": 3035,
"end": 17281
} | class ____(PythonPackageToxEnv, ABC):
"""local file system python virtual environment package builder."""
def __init__(self, create_args: ToxEnvCreateArgs) -> None:
super().__init__(create_args)
self._frontend_: Pep517VirtualEnvFrontend | None = None
self.builds: defaultdict[str, list[E... | Pep517VenvPackager |
python | tensorflow__tensorflow | tensorflow/python/ops/control_flow_v2_toggles_test.py | {
"start": 885,
"end": 1604
} | class ____(test.TestCase):
def testOutputAllIntermediates(self):
self.assertIsNone(
control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)
control_flow_util_v2.set_output_all_intermediates(True)
self.assertTrue(
control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OV... | ControlFlowV2TogglesTest |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 31296,
"end": 32642
} | class ____(TestCase):
def setUp(self):
self.patterns = [
path('example/', ManyToManySourceView.as_view()),
]
def test_schema_for_regular_views(self):
"""
Ensure that AutoField many to many fields are output as Integer.
"""
generator = SchemaGenerator(... | TestSchemaGeneratorWithManyToMany |
python | Pylons__pyramid | tests/test_config/pkgs/scannable/another.py | {
"start": 532,
"end": 933
} | class ____:
def __init__(self, context, request):
self.context = context
self.request = request
def __call__(self):
return 'another_stacked_class'
stacked_class = view_config(
name='another_stacked_class1', renderer=null_renderer
)(stacked_class)
stacked_class = view_config(
n... | stacked_class |
python | kamyu104__LeetCode-Solutions | Python/spiral-matrix.py | {
"start": 33,
"end": 944
} | class ____(object):
# @param matrix, a list of lists of integers
# @return a list of integers
def spiralOrder(self, matrix):
result = []
if matrix == []:
return result
left, right, top, bottom = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
while left <= right and t... | Solution |
python | sqlalchemy__sqlalchemy | test/orm/test_events.py | {
"start": 117396,
"end": 125336
} | class ____(fixtures.MappedTest):
"""Test RegistryEvents functionality."""
@testing.variation("scenario", ["direct", "reentrant", "plain"])
@testing.variation("include_optional", [True, False])
@testing.variation(
"type_features",
[
"none",
"plain_pep593",
... | RegistryEventsTest |
python | apache__airflow | providers/apache/drill/tests/unit/apache/drill/hooks/test_drill.py | {
"start": 1850,
"end": 7167
} | class ____:
def setup_method(self):
self.cur = MagicMock(rowcount=0)
self.conn = conn = MagicMock()
self.conn.login = "drill_user"
self.conn.password = "secret"
self.conn.host = "host"
self.conn.port = "8047"
self.conn.conn_type = "drill"
self.conn.ext... | TestDrillHook |
python | huggingface__transformers | tests/generation/test_configuration_utils.py | {
"start": 34137,
"end": 37730
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._token = TOKEN
def test_push_to_hub(self):
with TemporaryHubRepo(token=self._token) as tmp_repo:
config = GenerationConfig(
do_sample=True,
temperature=0.7,
lengt... | ConfigPushToHubTester |
python | PyCQA__pylint | tests/functional/n/not_async_context_manager.py | {
"start": 351,
"end": 425
} | class ____:
def __aenter__(self):
pass
| PartialAsyncContextManager |
python | django__django | tests/timezones/models.py | {
"start": 31,
"end": 92
} | class ____(models.Model):
dt = models.DateTimeField()
| Event |
python | django__django | tests/lookup/models.py | {
"start": 1089,
"end": 1248
} | class ____(models.TextField):
def get_prep_value(self, value):
return None if value == "" else value
@NulledTextField.register_lookup
| NulledTextField |
python | walkccc__LeetCode | solutions/2559. Count Vowel Strings in Ranges/2559.py | {
"start": 0,
"end": 453
} | class ____:
def vowelStrings(
self,
words: list[str],
queries: list[list[int]],
) -> list[int]:
VOWELS = 'aeiou'
# prefix[i] := the number of the first i words that start with and end in a vowel
prefix = [0] * (len(words) + 1)
for i, word in enumerate(words):
prefix[i + 1] +... | Solution |
python | Farama-Foundation__Gymnasium | gymnasium/envs/mujoco/mujoco_rendering.py | {
"start": 5325,
"end": 10714
} | class ____(BaseRender):
"""Offscreen rendering class with opengl context."""
def __init__(
self,
model: "mujoco.MjMujoco",
data: "mujoco.MjData",
width: int,
height: int,
max_geom: int = 1000,
visual_options: dict[int, bool] = {},
):
# We must... | OffScreenViewer |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 34410,
"end": 35760
} | class ____(MixinSequenceOfValues):
"""
x-axis major tick lines
Parameters
----------
theme_element : element_line
"""
def apply_ax(self, ax: Axes):
super().apply_ax(ax)
params = ax.xaxis.get_tick_params(which="major")
# TODO: Remove this code when the minimum matpl... | axis_ticks_major_x |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 7856,
"end": 8093
} | class ____(A18):
@staticmethod
def m(arg):
# Expect an issue
B18.m(arg)
def test_static_methods():
# Expect an issue
C18.m0(_test_source())
# Expect an issue
c = C18()
c.m0(_test_source())
| C18 |
python | paramiko__paramiko | paramiko/agent.py | {
"start": 12035,
"end": 13070
} | class ____(AgentSSH):
"""
Client interface for using private keys from an SSH agent running on the
local machine. If an SSH agent is running, this class can be used to
connect to it and retrieve `.PKey` objects which can be used when
attempting to authenticate to remote SSH servers.
Upon initi... | Agent |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/metadata/base.py | {
"start": 2613,
"end": 21211
} | class ____(Protocol):
@classmethod
def from_directory(cls, directory: str) -> "BaseDistribution":
"""Load the distribution from a metadata directory.
:param directory: Path to a metadata directory, e.g. ``.dist-info``.
"""
raise NotImplementedError()
@classmethod
def fr... | BaseDistribution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 69495,
"end": 74013
} | class ____(SageMakerBaseOperator):
"""
Register a SageMaker model by creating a model version that specifies the model group to which it belongs.
Will create the model group if it does not exist already.
.. seealso::
For more information on how to use this operator, take a look at the guide:
... | SageMakerRegisterModelVersionOperator |
python | doocs__leetcode | solution/0600-0699/0669.Trim a Binary Search Tree/Solution2.py | {
"start": 192,
"end": 864
} | class ____:
def trimBST(
self, root: Optional[TreeNode], low: int, high: int
) -> Optional[TreeNode]:
while root and (root.val < low or root.val > high):
root = root.left if root.val > high else root.right
if root is None:
return None
node = root
w... | Solution |
python | great-expectations__great_expectations | great_expectations/core/batch.py | {
"start": 9274,
"end": 19836
} | class ____(SerializableDictDot):
"""
This class is for internal inter-object protocol purposes only.
As such, it contains all attributes of a batch_request, but does not validate them.
See the BatchRequest class, which extends BatchRequestBase and validates the attributes.
BatchRequestBase is used ... | BatchRequestBase |
python | huggingface__transformers | src/transformers/models/got_ocr2/modeling_got_ocr2.py | {
"start": 8312,
"end": 12284
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, window_size):
super().__init__()
self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.attn = GotOcr2VisionAttention(config, window_size)
self.layer_norm2 = nn.LayerNorm(config.hidden_siz... | GotOcr2VisionLayer |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/launcher/sync_in_memory_run_launcher.py | {
"start": 493,
"end": 1593
} | class ____(RunLauncher, ConfigurableClass):
"""This run launcher launches runs synchronously, in memory, and is intended only for test.
Use the :py:class:`dagster.DefaultRunLauncher`.
"""
def __init__(self, inst_data: Optional[ConfigurableClassData] = None):
self._inst_data = inst_data
... | SyncInMemoryRunLauncher |
python | wandb__wandb | tests/unit_tests/test_internal_api.py | {
"start": 12121,
"end": 22052
} | class ____:
"""Tests `upload_file`."""
class TestSimple:
def test_adds_headers_to_request(
self, mock_responses: RequestsMock, example_file: Path
):
response_callback = Mock(return_value=(200, {}, "success!"))
mock_responses.add_callback(
"PUT... | TestUploadFile |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 30368,
"end": 30434
} | class ____(Operator):
__slots__ = ()
_op = operator.not_
| Not |
python | huggingface__transformers | src/transformers/models/git/processing_git.py | {
"start": 698,
"end": 1394
} | class ____(ProcessorMixin):
r"""
Constructs a GIT processor which wraps a CLIP image processor and a BERT tokenizer into a single processor.
[`GitProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`BertTokenizerFast`]. See the
[`~GitProcessor.__call__`] and [`~GitProcessor.decode... | GitProcessor |
python | apache__airflow | airflow-core/tests/unit/plugins/test_plugin.py | {
"start": 5674,
"end": 5732
} | class ____(AirflowPlugin):
name = "plugin-b"
| MockPluginB |
python | ansible__ansible | lib/ansible/plugins/doc_fragments/backup.py | {
"start": 191,
"end": 507
} | class ____(object):
# Standard documentation fragment
DOCUMENTATION = r"""
options:
backup:
description:
- Create a backup file including the timestamp information so you can get
the original file back if you somehow clobbered it incorrectly.
type: bool
default: no
"""
| ModuleDocFragment |
python | walkccc__LeetCode | solutions/576. Out of Boundary Paths/576.py | {
"start": 0,
"end": 552
} | class ____:
def findPaths(self, m, n, maxMove, startRow, startColumn):
MOD = 1000000007
@functools.lru_cache(None)
def dp(k: int, i: int, j: int) -> int:
"""
Returns the number of paths to move the ball at (i, j) out-of-bounds with
k moves.
"""
if i < 0 or i == m or j < 0 or... | Solution |
python | astropy__astropy | astropy/extern/ply/yacc.py | {
"start": 59253,
"end": 79204
} | class ____(object):
def __init__(self, terminals):
self.Productions = [None] # A list of all of the productions. The first
# entry is always reserved for the purpose of
# building an augmented grammar
self.Prodnames = {} ... | Grammar |
python | jazzband__django-oauth-toolkit | oauth2_provider/backends.py | {
"start": 218,
"end": 974
} | class ____:
"""
Authenticate against an OAuth2 access token
"""
def authenticate(self, request=None, **credentials):
if request is not None:
try:
valid, request = OAuthLibCore.verify_request(request, scopes=[])
except ValueError as error:
... | OAuth2Backend |
python | falconry__falcon | tests/test_response_body.py | {
"start": 2391,
"end": 3463
} | class ____:
def on_get(self, req, resp):
resp.content_type = 'text/x-malbolge'
resp.media = "'&%$#\"!76543210/43,P0).'&%I6"
resp.status = falcon.HTTP_725
def test_unsupported_response_content_type(asgi, util):
app = util.create_app(asgi)
app.add_route('/test.mal', CodeResource())
... | CodeResource |
python | huggingface__transformers | src/transformers/convert_slow_tokenizer.py | {
"start": 60899,
"end": 68433
} | class ____:
def __init__(
self,
vocab_file=None,
pattern=r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""",
add_prefix_space=False,
additional_special_tokens=None,
**kwargs,
):
self.v... | MistralConverter |
python | sanic-org__sanic | sanic/config.py | {
"start": 2418,
"end": 13501
} | class ____(dict, metaclass=DescriptorMeta):
"""Configuration object for Sanic.
You can use this object to both: (1) configure how Sanic will operate, and
(2) manage your application's custom configuration values.
"""
ACCESS_LOG: bool
AUTO_EXTEND: bool
AUTO_RELOAD: bool
EVENT_AUTOREGIST... | Config |
python | google__python-fire | examples/widget/widget_test.py | {
"start": 677,
"end": 1081
} | class ____(testutils.BaseTestCase):
def testWidgetWhack(self):
toy = widget.Widget()
self.assertEqual(toy.whack(), 'whack!')
self.assertEqual(toy.whack(3), 'whack! whack! whack!')
def testWidgetBang(self):
toy = widget.Widget()
self.assertEqual(toy.bang(), 'bang bang!')
self.assertEqual(to... | WidgetTest |
python | apache__airflow | shared/logging/src/airflow_shared/logging/structlog.py | {
"start": 5941,
"end": 6297
} | class ____(structlog.WriteLogger):
__slots__ = ("name",)
def __init__(self, name: str | None = None, file: TextIO | None = None):
self.name = name
if file is not None:
file = make_file_io_non_caching(file)
super().__init__(file)
LogOutputType = TypeVar("LogOutputType", bou... | NamedWriteLogger |
python | tensorflow__tensorflow | tensorflow/python/training/saver_test.py | {
"start": 117398,
"end": 130990
} | class ____(test.TestCase):
def _get_test_dir(self, dirname):
test_dir = os.path.join(self.get_temp_dir(), dirname)
gfile.MakeDirs(test_dir)
return test_dir
def _testScopedSave(self, test_dir, exported_filename, ckpt_filename):
graph = ops_lib.Graph()
with graph.as_default():
# Creates an... | ScopedGraphTest |
python | gevent__gevent | src/greentest/3.11/test_wsgiref.py | {
"start": 9888,
"end": 16643
} | class ____(TestCase):
def checkShift(self,sn_in,pi_in,part,sn_out,pi_out):
env = {'SCRIPT_NAME':sn_in,'PATH_INFO':pi_in}
util.setup_testing_defaults(env)
self.assertEqual(util.shift_path_info(env),part)
self.assertEqual(env['PATH_INFO'],pi_out)
self.assertEqual(env['SCRIPT_N... | UtilityTests |
python | pikepdf__pikepdf | src/pikepdf/codec.py | {
"start": 4763,
"end": 6094
} | class ____(codecs.IncrementalDecoder):
"""Implement PdfDocEncoding incremental decoder."""
def decode(self, input: Any, final: bool = False) -> str: # type: ignore
"""Implement codecs.IncrementalDecoder.decode for pdfdoc."""
return pdfdoc_decode(bytes(input), 'strict')[0]
def find_pdfdoc(enc... | PdfDocIncrementalDecoder |
python | ray-project__ray | python/ray/actor.py | {
"start": 14994,
"end": 18441
} | class ____:
"""A container for the metadata required to invoke an actor method.
This class intentionally does *not* hold a reference to the `ActorHandle`, as that causes
a circular reference that delays `ActorHandle` destruction until the Python GC runs.
Instead, it can be used as a factory to lazily ... | _ActorMethodMetadata |
python | facebookresearch__faiss | tests/test_binary_io.py | {
"start": 3911,
"end": 5454
} | class ____(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
d = 32
nt = 200
nb = 1500
nq = 500
(self.xt, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq)
def test_hnsw(self):
d = self.xq.sh... | TestBinaryHNSW |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.