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 | openai__openai-python | src/openai/types/completion_usage.py | {
"start": 994,
"end": 1213
} | class ____(BaseModel):
audio_tokens: Optional[int] = None
"""Audio input tokens present in the prompt."""
cached_tokens: Optional[int] = None
"""Cached tokens present in the prompt."""
| PromptTokensDetails |
python | facebookresearch__faiss | tests/test_fast_scan.py | {
"start": 11778,
"end": 12151
} | class ____(TestImplems):
def build_fast_scan_index(self, index, params):
qbs, bbs = params
index2 = faiss.IndexPQFastScan(index, bbs)
index2.qbs = qbs
index2.implem = 15
return index2
def test_1_32(self):
self.do_with_params(32, (1, 32))
def test_2_64(self)... | TestImplem15 |
python | pytorch__pytorch | torch/serialization.py | {
"start": 3566,
"end": 5953
} | class ____(Enum):
NATIVE = 1
LITTLE = 2
BIG = 3
def get_default_load_endianness() -> Optional[LoadEndianness]:
"""
Get fallback byte order for loading files
If byteorder mark is not present in saved checkpoint,
this byte order is used as fallback.
By default, it's "native" byte order.... | LoadEndianness |
python | pandas-dev__pandas | pandas/core/arrays/floating.py | {
"start": 426,
"end": 1721
} | class ____(NumericDtype):
"""
An ExtensionDtype to hold a single size of floating dtype.
These specific implementations are subclasses of the non-public
FloatingDtype. For example we have Float32Dtype to represent float32.
The attributes name & type are set when these subclasses are created.
"... | FloatingDtype |
python | doocs__leetcode | solution/1500-1599/1594.Maximum Non Negative Product in a Matrix/Solution.py | {
"start": 0,
"end": 905
} | class ____:
def maxProductPath(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
mod = 10**9 + 7
dp = [[[grid[0][0]] * 2 for _ in range(n)] for _ in range(m)]
for i in range(1, m):
dp[i][0] = [dp[i - 1][0][0] * grid[i][0]] * 2
for j in range(1, n... | Solution |
python | tensorflow__tensorflow | tensorflow/compiler/tests/spacetobatch_op_test.py | {
"start": 2675,
"end": 6210
} | class ____(xla_test.XLATestCase):
"""Tests input-output pairs for the SpaceToBatch and BatchToSpace ops."""
def _testPad(self, inputs, paddings, block_size, outputs):
with self.session() as sess, self.test_scope():
for dtype in self.float_types:
# outputs = space_to_batch(inputs)
placehol... | SpaceToBatchTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 651085,
"end": 651550
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("begin_indice", "end_indice", "text")
begin_indice = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="beginIndice"
)
end_indice = sgqlc.types.Field(sgql... | TextMatchHighlight |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 6167,
"end": 6252
} | class ____(PydanticTypeError):
msg_template = 'value is not a valid path'
| PathError |
python | tensorflow__tensorflow | tensorflow/python/util/tf_contextlib_test.py | {
"start": 1280,
"end": 2965
} | class ____(test.TestCase):
def testRunsCodeBeforeYield(self):
x = []
with test_yield_append_before_and_after_yield(x, 'before', ''):
self.assertEqual('before', x[-1])
def testRunsCodeAfterYield(self):
x = []
with test_yield_append_before_and_after_yield(x, '', 'after'):
pass
self.a... | TfContextlibTest |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_repr_returned.py | {
"start": 193,
"end": 308
} | class ____:
"""__repr__ returns <type 'str'>"""
def __repr__(self):
return "some repr"
| FirstGoodRepr |
python | donnemartin__interactive-coding-challenges | graphs_trees/graph_shortest_path/priority_queue.py | {
"start": 206,
"end": 957
} | class ____(object):
def __init__(self):
self.queue = []
def insert(self, node):
if node is not None:
self.queue.append(node)
return self.queue[-1]
return None
def extract_min(self):
if not self.queue:
return None
minimum = sys.ma... | PriorityQueue |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_code_interpreter.py | {
"start": 815,
"end": 3236
} | class ____:
def test_extract_output_text_only(self):
response = {
"stream": [
{
"result": {
"content": [
{"type": "text", "text": "Hello"},
{"type": "text", "text": " World"},
... | TestExtractOutputFromStream |
python | getsentry__sentry | src/sentry/testutils/relay.py | {
"start": 377,
"end": 6011
} | class ____(RequiredBaseclass):
"""
Tests that post to the store entry point should use this helper class
(together with RelayStoreHelper) to check the functionality with relay.
Note that any methods defined on this mixin are very slow. Consider whether
your test really needs to test the entire inge... | RelayStoreHelper |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 176758,
"end": 177693
} | class ____(ColumnElement[str]):
__visit_name__ = "collation"
_traverse_internals: _TraverseInternalsType = [
("collation", InternalTraversal.dp_string)
]
@classmethod
@util.preload_module("sqlalchemy.sql.sqltypes")
def _create_collation_expression(
cls, expression: _ColumnExpre... | CollationClause |
python | aio-libs__aiohttp | aiohttp/abc.py | {
"start": 5084,
"end": 6305
} | class ____(ABC):
"""Abstract stream writer."""
buffer_size: int = 0
output_size: int = 0
length: int | None = 0
@abstractmethod
async def write(
self, chunk: "bytes | bytearray | memoryview[int] | memoryview[bytes]"
) -> None:
"""Write chunk into stream."""
@abstractme... | AbstractStreamWriter |
python | huggingface__transformers | src/transformers/models/swin2sr/modeling_swin2sr.py | {
"start": 27215,
"end": 29586
} | class ____(nn.Module):
def __init__(self, config, grid_size):
super().__init__()
self.num_stages = len(config.depths)
self.config = config
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]
self.stages = nn.ModuleList(
... | Swin2SREncoder |
python | ethereum__web3.py | web3/providers/auto.py | {
"start": 1108,
"end": 4044
} | class ____(JSONBaseProvider):
default_providers = (
load_provider_from_environment,
IPCProvider,
HTTPProvider,
)
_active_provider = None
def __init__(
self,
potential_providers: None
| (Sequence[Callable[..., JSONBaseProvider] | type[JSONBaseProvider]]) =... | AutoProvider |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/migrate.py | {
"start": 106,
"end": 265
} | class ____(BaseModel):
enabled: bool
extraContainers: Optional[list[kubernetes.Container]]
initContainers: Optional[list[kubernetes.Container]]
| Migrate |
python | ray-project__ray | rllib/env/env_errors.py | {
"start": 130,
"end": 810
} | class ____(Exception):
"""An exception that signals that the environment step failed and the environment needs to be reset.
This exception may be raised by the environment's `step` method.
It is then caught by the `EnvRunner` and the environment is reset.
This can be useful if your environment is unsta... | StepFailedRecreateEnvError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/cymysql.py | {
"start": 1827,
"end": 3215
} | class ____(MySQLDialect_mysqldb):
driver = "cymysql"
supports_statement_cache = True
description_encoding = None
supports_sane_rowcount = True
supports_sane_multi_rowcount = False
supports_unicode_statements = True
colspecs = util.update_copy(MySQLDialect.colspecs, {BIT: _cymysqlBIT})
... | MySQLDialect_cymysql |
python | Farama-Foundation__Gymnasium | tests/test_core.py | {
"start": 4338,
"end": 7391
} | class ____(ActionWrapper):
"""Example action wrapper for testing."""
def action(self, action: ActType) -> ActType:
"""Action function."""
return np.array([1])
def test_reward_observation_action_wrapper():
"""Tests the observation, action and reward wrapper examples."""
env = GenericTe... | ExampleActionWrapper |
python | pypa__warehouse | warehouse/cache/origin/interfaces.py | {
"start": 78,
"end": 1084
} | class ____(Interface):
def create_service(context, request):
"""
Create the service, given the context and request for which it is being
created for.
"""
def cache(
keys,
request,
response,
*,
seconds=None,
stale_while_revalidate=N... | IOriginCache |
python | huggingface__transformers | tests/models/idefics2/test_modeling_idefics2.py | {
"start": 25245,
"end": 31745
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b-base")
self.image1 = Image.open(
BytesIO(
requests.get(
"https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island... | Idefics2ForConditionalGenerationIntegrationTest |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/cloud/opennebula.py | {
"start": 1094,
"end": 1808
} | class ____(CloudEnvironment):
"""Updates integration test environment after delegation. Will setup the config file as parameter."""
def get_environment_config(self) -> CloudEnvironmentConfig:
"""Return environment configuration for use in the test environment after delegation."""
parser = confi... | OpenNebulaCloudEnvironment |
python | keras-team__keras | keras/src/ops/core.py | {
"start": 22350,
"end": 23189
} | class ____(Operation):
def call(self, variable):
return backend.core.stop_gradient(variable)
def compute_output_spec(self, variable):
return KerasTensor(variable.shape, dtype=variable.dtype)
@keras_export("keras.ops.stop_gradient")
def stop_gradient(variable):
"""Stops gradient computatio... | StopGradient |
python | doocs__leetcode | solution/1000-1099/1096.Brace Expansion II/Solution.py | {
"start": 0,
"end": 433
} | class ____:
def braceExpansionII(self, expression: str) -> List[str]:
def dfs(exp):
j = exp.find('}')
if j == -1:
s.add(exp)
return
i = exp.rfind('{', 0, j - 1)
a, c = exp[:i], exp[j + 1 :]
for b in exp[i + 1 : j].sp... | Solution |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_wxcairo.py | {
"start": 263,
"end": 774
} | class ____(FigureCanvasCairo, _FigureCanvasWxBase):
def draw(self, drawDC=None):
size = self.figure.bbox.size.astype(int)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size)
self._renderer.set_context(cairo.Context(surface))
self._renderer.dpi = self.figure.dpi
self.figu... | FigureCanvasWxCairo |
python | sympy__sympy | sympy/physics/quantum/shor.py | {
"start": 847,
"end": 5504
} | class ____(Gate):
"""A controlled mod gate.
This is black box controlled Mod function for use by shor's algorithm.
TODO: implement a decompose property that returns how to do this in terms
of elementary gates
"""
@classmethod
def _eval_args(cls, args):
# t = args[0]
# a = a... | CMod |
python | pytorch__pytorch | test/inductor/test_efficient_conv_bn_eval.py | {
"start": 780,
"end": 1289
} | class ____(nn.Module):
expected_optimization_count = 1
def __init__(
self,
conv_class,
bn_class,
use_bias,
in_channels,
out_channels,
device,
**kwargs,
):
super().__init__()
self.conv = conv_class(in_channels, out_channels, bia... | ConvOp |
python | pytorch__pytorch | torch/utils/_pytree.py | {
"start": 2522,
"end": 2714
} | class ____(Protocol):
def __hash__(self) -> int: ...
def __eq__(self, other: object) -> bool: ...
def __str__(self) -> str: ...
def get(self, parent: Any) -> Any: ...
| KeyEntry |
python | numba__numba | numba/core/cpu_options.py | {
"start": 1885,
"end": 4131
} | class ____(AbstractOptionValue):
"""
Options for controlling auto parallelization.
"""
__slots__ = ("enabled", "comprehension", "reduction", "inplace_binop",
"setitem", "numpy", "stencil", "fusion", "prange")
def __init__(self, value):
if isinstance(value, bool):
... | ParallelOptions |
python | doocs__leetcode | solution/0700-0799/0752.Open the Lock/Solution3.py | {
"start": 0,
"end": 1325
} | class ____:
def openLock(self, deadends: List[str], target: str) -> int:
def next(s):
res = []
s = list(s)
for i in range(4):
c = s[i]
s[i] = '9' if c == '0' else str(int(c) - 1)
res.append(''.join(s))
s[i] =... | Solution |
python | pytorch__pytorch | test/jit/test_hooks.py | {
"start": 1323,
"end": 14501
} | class ____(JitTestCase):
def test_module_no_forward_input(self):
self.checkModule(create_module_no_forward_input(), ())
def test_submodule_no_forward_input(self):
self.checkModule(create_submodule_no_forward_input(), ())
def test_module_forward_multiple_inputs(self):
self.checkModu... | TestHooks |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType33.py | {
"start": 222,
"end": 539
} | class ____(Protocol[T_contra]):
def f(self) -> Contra[T_contra]: ...
def t1(x: Foo[T_contra]) -> list[T_contra] | None: ...
def t2(x: Foo[object]) -> None: ...
def func1(x: Foo[T_contra]) -> list[T_contra] | None:
# This should generate an error.
t2(x)
def func2(x: Foo[object]) -> None:
t1(x)
| Foo |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydocstyle/sections.py | {
"start": 12022,
"end": 14983
} | class ____: # noqa: D203
"""Test class."""
@expect("D417: Missing argument descriptions in the docstring "
"(argument(s) y are missing descriptions in "
"'test_incorrect_indent' docstring)", arg_count=3)
def test_incorrect_indent(self, x=1, y=2): # noqa: D207, D213, D407
"... | TestIncorrectIndent |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 10514,
"end": 10590
} | class ____(sqltypes.BigInteger):
render_bind_cast = True
| AsyncpgBigInteger |
python | kamyu104__LeetCode-Solutions | Python/successful-pairs-of-spells-and-potions.py | {
"start": 57,
"end": 478
} | class ____(object):
def successfulPairs(self, spells, potions, success):
"""
:type spells: List[int]
:type potions: List[int]
:type success: int
:rtype: List[int]
"""
def ceil_divide(a, b):
return (a+(b-1))//b
potions.sort()
... | Solution |
python | encode__django-rest-framework | tests/test_relations_pk.py | {
"start": 2375,
"end": 2544
} | class ____(serializers.ModelSerializer):
class Meta:
model = OneToOneTarget
fields = ('id', 'name', 'nullable_source')
| NullableOneToOneTargetSerializer |
python | pandas-dev__pandas | pandas/tests/scalar/period/test_period.py | {
"start": 635,
"end": 2063
} | class ____:
@pytest.mark.parametrize(
"freq, freq_msg",
[
(offsets.BYearBegin(), "BYearBegin"),
(offsets.YearBegin(2), "YearBegin"),
(offsets.QuarterBegin(startingMonth=12), "QuarterBegin"),
(offsets.BusinessMonthEnd(2), "BusinessMonthEnd"),
],... | TestPeriodDisallowedFreqs |
python | django__django | tests/utils_tests/test_autoreload.py | {
"start": 36051,
"end": 37965
} | class ____(ReloaderTests, IntegrationTests):
RELOADER_CLS = autoreload.StatReloader
def setUp(self):
super().setUp()
# Shorten the sleep time to speed up tests.
self.reloader.SLEEP_TIME = 0.01
@mock.patch("django.utils.autoreload.StatReloader.notify_file_changed")
def test_tick... | StatReloaderTests |
python | realpython__materials | python-mixins/utils.py | {
"start": 290,
"end": 1208
} | class ____(DebugMixin, UserDict):
def __setitem__(self, key: str, value: str) -> None:
super().__setitem__(key.lower(), value)
def __getitem__(self, key: str) -> str:
return super().__getitem__(key.lower())
def __delitem__(self, key: str) -> None:
super().__delitem__(key.lower())
... | CaseInsensitiveDict |
python | miyuchina__mistletoe | test/test_block_token.py | {
"start": 2916,
"end": 4854
} | class ____(TestToken):
def test_match_fenced_code(self):
lines = ['```sh\n', 'rm dir\n', 'mkdir test\n', '```\n']
arg = 'rm dir\nmkdir test\n'
self._test_match(block_token.CodeFence, lines, arg, language='sh')
def test_match_fenced_code_with_tilde(self):
lines = ['~~~sh\n', 'rm ... | TestCodeFence |
python | getsentry__sentry | tests/sentry/api/endpoints/test_auth.py | {
"start": 632,
"end": 946
} | class ____(APITestCase):
def test_simple(self) -> None:
user = self.create_user(email="a@example.com")
self.login_as(user)
url = reverse("sentry-api-0-auth")
response = self.client.delete(url, format="json")
assert response.status_code == 204, response.content
| LogoutTest |
python | google__jax | jax/_src/pallas/mosaic/tpu_info.py | {
"start": 1137,
"end": 1306
} | class ____:
"""SparseCore-specific information."""
num_cores: int
num_subcores: int
num_lanes: int
@dataclasses.dataclass(frozen=True, kw_only=True)
| SparseCoreInfo |
python | kamyu104__LeetCode-Solutions | Python/implement-router.py | {
"start": 222,
"end": 1554
} | class ____(object):
def __init__(self, memoryLimit):
"""
:type memoryLimit: int
"""
self.__size = memoryLimit
self.__q = collections.deque()
self.__lookup = collections.defaultdict(SortedList)
def addPacket(self, source, destination, timestamp):
"""
... | Router |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 84480,
"end": 85034
} | class ____(SimpleHandlerTestCase):
class Handler(RequestHandler):
def prepare(self):
self.finish("done")
def get(self):
# It's difficult to assert for certain that a method did not
# or will not be called in an asynchronous context, but this
# will be... | FinishInPrepareTest |
python | ansible__ansible | test/lib/ansible_test/_internal/completion.py | {
"start": 4966,
"end": 6781
} | class ____(PythonCompletionConfig):
"""Configuration for Docker containers."""
image: str = ''
seccomp: str = 'default'
cgroup: str = CGroupVersion.V1_V2.value
audit: str = AuditMode.REQUIRED.value # most containers need this, so the default is required, leaving it to be opt-out for containers whi... | DockerCompletionConfig |
python | django__django | tests/handlers/tests_custom_error_handlers.py | {
"start": 1096,
"end": 1406
} | class ____(SimpleTestCase):
def test_handler_renders_template_response(self):
"""
BaseHandler should render TemplateResponse if necessary.
"""
response = self.client.get("/")
self.assertContains(response, "Error handler content", status_code=403)
| CustomErrorHandlerTests |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 69089,
"end": 74307
} | class ____(AST):
verboseStringConversion = False
tokenNames = None
def __init__(self):
self.down = None ## kid
self.right = None ## sibling
def addChild(self,node):
if node:
t = rightmost(self.down)
if t:
t.right = node
else... | BaseAST |
python | walkccc__LeetCode | solutions/2496. Maximum Value of a String in an Array/2496.py | {
"start": 0,
"end": 161
} | class ____:
def maximumValue(self, strs: list[str]) -> int:
return max(len(s) if any(c.isalpha() for c in s) else int(s)
for s in strs)
| Solution |
python | scipy__scipy | scipy/io/matlab/_mio5_params.py | {
"start": 6375,
"end": 6625
} | class ____:
"""Placeholder for holding read data from structs.
We use instances of this class when the user passes False as a value to the
``struct_as_record`` parameter of the :func:`scipy.io.loadmat` function.
"""
pass
| mat_struct |
python | realpython__materials | arcade-platformer/arcade_platformer/06_keyboard_movement.py | {
"start": 621,
"end": 9208
} | class ____(arcade.Window):
def __init__(self) -> None:
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
# These lists will hold different sets of sprites
self.coins = None
self.background = None
self.walls = None
self.ladders = None
self.goals = No... | Platformer |
python | tiangolo__fastapi | fastapi/dependencies/utils.py | {
"start": 11954,
"end": 20715
} | class ____:
type_annotation: Any
depends: Optional[params.Depends]
field: Optional[ModelField]
def analyze_param(
*,
param_name: str,
annotation: Any,
value: Any,
is_path_param: bool,
) -> ParamDetails:
field_info = None
depends = None
type_annotation: Any = Any
use_ann... | ParamDetails |
python | google__jax | jax/_src/pallas/mosaic/error_handling.py | {
"start": 1781,
"end": 5566
} | class ____(MosaicError):
"""Error thrown by Pallas when re-raising a verification error."""
def __init__(self, message: str):
super().__init__(MLIR_ERR_PREFIX + message)
def _handle_xla_runtime_error(
base_err: _jax.JaxRuntimeError,
) -> MosaicError | None:
"""Reformats JaxRuntimeError to include a Pyt... | VerificationError |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 18868,
"end": 19712
} | class ____(DagsterError):
"""Raised when raise_on_error is true, and retries were exceeded, this error should be raised."""
def __init__(self, *args, **kwargs):
from dagster._utils.error import SerializableErrorInfo
self.user_code_process_error_infos = check.list_param(
kwargs.pop(... | DagsterMaxRetriesExceededError |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/core.py | {
"start": 20181,
"end": 22037
} | class ____(Layer):
"""Permutes the dimensions of the input according to a given pattern.
Useful e.g. connecting RNNs and convnets.
Example:
```python
model = Sequential()
model.add(Permute((2, 1), input_shape=(10, 64)))
# now: model.output_shape == (None, 64, 10)
# note: `None` is the batch dimension... | Permute |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 163427,
"end": 163917
} | class ____(sgqlc.types.Input):
"""Ordering options for commit contribution connections."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(CommitContributionOrderField), graphql_name="field")
"""The field by which to order commit co... | CommitContributionOrder |
python | getsentry__sentry | tests/sentry/models/test_groupsearchview.py | {
"start": 104,
"end": 758
} | class ____(TestCase):
def test_create_views(self) -> None:
user = self.create_user("foo@example.com")
org = self.create_organization()
GroupSearchView.objects.create(
name="View 1",
user_id=user.id,
organization=org,
query="some query",
... | GroupSearchViewTestCase |
python | pytest-dev__pytest | src/_pytest/main.py | {
"start": 17846,
"end": 37136
} | class ____(nodes.Collector):
"""The root of the collection tree.
``Session`` collects the initial paths given as arguments to pytest.
"""
Interrupted = Interrupted
Failed = Failed
# Set on the session by runner.pytest_sessionstart.
_setupstate: SetupState
# Set on the session by fixtur... | Session |
python | huggingface__transformers | src/transformers/models/luke/modeling_luke.py | {
"start": 11513,
"end": 12677
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
entity_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidd... | LukeQuestionAnsweringModelOutput |
python | ApeWorX__ape | src/ape/api/config.py | {
"start": 1760,
"end": 6080
} | class ____(BaseSettings):
"""
A base plugin configuration class. Each plugin that includes
a config API must register a subclass of this class.
"""
model_config = SettingsConfigDict(extra="allow", env_prefix="APE_")
@classmethod
def from_overrides(
cls, overrides: dict, plugin_name... | PluginConfig |
python | apache__airflow | providers/apache/beam/src/airflow/providers/apache/beam/operators/beam.py | {
"start": 21985,
"end": 30755
} | class ____(BeamBasePipelineOperator):
"""
Launching Apache Beam pipelines written in Java.
Note that both
``default_pipeline_options`` and ``pipeline_options`` will be merged to specify pipeline
execution parameter, and ``default_pipeline_options`` is expected to save
high-level pipeline_option... | BeamRunJavaPipelineOperator |
python | miyuchina__mistletoe | test/test_span_token.py | {
"start": 7748,
"end": 8001
} | class ____(unittest.TestCase):
def test_parent(self):
token, = span_token.tokenize_inner('**some text**')
self.assertIsInstance(token.children[0], span_token.RawText)
self.assertEqual(token.children[0].parent, token)
| TestParent |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-dashscope/llama_index/llms/dashscope/base.py | {
"start": 1088,
"end": 4099
} | class ____:
"""DashScope Qwen serial models."""
QWEN_TURBO = "qwen-turbo"
QWEN_PLUS = "qwen-plus"
QWEN_MAX = "qwen-max"
QWEN_MAX_1201 = "qwen-max-1201"
QWEN_MAX_LONGCONTEXT = "qwen-max-longcontext"
DASHSCOPE_MODEL_META = {
DashScopeGenerationModels.QWEN_TURBO: {
"context_window": ... | DashScopeGenerationModels |
python | conda__conda | conda/auxlib/decorators.py | {
"start": 5272,
"end": 6388
} | class ____: # pylint: disable=C0103
# from celery.five
def __init__(self, getter=None, setter=None):
if getter is not None and not isinstance(getter, classmethod):
getter = classmethod(getter)
if setter is not None and not isinstance(setter, classmethod):
setter = class... | classproperty |
python | pypa__warehouse | tests/unit/manage/test_forms.py | {
"start": 13818,
"end": 14980
} | class ____:
def test_validate(self, monkeypatch):
verify_totp = pretend.call_recorder(lambda *a: True)
monkeypatch.setattr(otp, "verify_totp", verify_totp)
totp_secret = pretend.stub()
form = forms.ProvisionTOTPForm(
formdata=MultiDict({"totp_value": "000000"}), totp_sec... | TestProvisionTOTPForm |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 13580,
"end": 16639
} | class ____(SQLAlchemyError):
"""An error occurred during execution of a SQL statement.
:class:`StatementError` wraps the exception raised
during execution, and features :attr:`.statement`
and :attr:`.params` attributes which supply context regarding
the specifics of the statement which had an issue... | StatementError |
python | kennethreitz__tablib | src/tablib/formats/_tsv.py | {
"start": 84,
"end": 186
} | class ____(CSVFormat):
title = 'tsv'
extensions = ('tsv',)
DEFAULT_DELIMITER = '\t'
| TSVFormat |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 30951,
"end": 31740
} | class ____(Field[str]):
"""A string field.
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
#: Default error messages.
default_error_messages = {
"invalid": "Not a valid string.",
"invalid_utf8": "Not a valid utf-8 string.",
}
def _serialize(self... | String |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1291656,
"end": 1293286
} | class ____(sgqlc.types.Type, HovercardContext):
"""An organization list hovercard context"""
__schema__ = github_schema
__field_names__ = ("relevant_organizations", "total_organization_count")
relevant_organizations = sgqlc.types.Field(
sgqlc.types.non_null(OrganizationConnection),
grap... | OrganizationsHovercardContext |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/opensearch_serverless.py | {
"start": 1462,
"end": 5508
} | class ____(AwsBaseSensor[OpenSearchServerlessHook]):
"""
Poll the state of the Collection until it reaches a terminal state; fails if the query fails.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:OpenSearchServerlessCollectionAvai... | OpenSearchServerlessCollectionActiveSensor |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 6867,
"end": 7150
} | class ____(_VectorizerConfigCreate):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.TEXT2COLBERT_JINAAI, frozen=True, exclude=True
)
vectorizeClassName: bool
model: Optional[str]
dimensions: Optional[int]
| _Text2ColbertJinaAIConfig |
python | django__django | tests/template_tests/syntax_tests/test_filter_tag.py | {
"start": 116,
"end": 1794
} | class ____(SimpleTestCase):
@setup({"filter01": "{% filter upper %}{% endfilter %}"})
def test_filter01(self):
output = self.engine.render_to_string("filter01")
self.assertEqual(output, "")
@setup({"filter02": "{% filter upper %}django{% endfilter %}"})
def test_filter02(self):
... | FilterTagTests |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/event_backport.py | {
"start": 154,
"end": 902
} | class ____(object):
def __init__(self,):
self.__cond = Condition(Lock())
self.__flag = False
def isSet(self):
return self.__flag
is_set = isSet
def set(self):
self.__cond.acquire()
try:
self.__flag = True
self.__cond.notify_all()
... | Event |
python | apache__airflow | providers/microsoft/psrp/tests/unit/microsoft/psrp/hooks/test_psrp.py | {
"start": 3928,
"end": 8355
} | class ____:
def test_get_conn(self, runspace_pool, powershell, ws_man):
hook = PsrpHook(CONNECTION_ID)
assert hook.get_conn() is runspace_pool.return_value
def test_get_conn_unexpected_extra(self, runspace_pool, powershell, ws_man):
hook = PsrpHook(CONNECTION_ID)
conn = hook.get... | TestPsrpHook |
python | encode__django-rest-framework | tests/test_generics.py | {
"start": 1618,
"end": 1771
} | class ____(generics.RetrieveUpdateDestroyAPIView):
queryset = ForeignKeySource.objects.all()
serializer_class = ForeignKeySerializer
| FKInstanceView |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/networks.py | {
"start": 28725,
"end": 29185
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.__global_step = nn.Parameter(
torch.Tensor([0]).to(torch.int64), requires_grad=False
)
@property
def current_step(self):
return int(self.__global_step.item())
@current_step.setter
def cur... | GlobalSteps |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 49792,
"end": 50985
} | class ____(TestCase):
def test_issue_651(self):
# Exercise the code path to make sure this does not fail
@vectorize(["(float64,float64)"])
def foo(x1, x2):
return np.add(x1, x2) + np.add(x1, x2)
a = np.arange(10, dtype='f8')
b = np.arange(10, dtype='f8')
... | TestUfuncIssues |
python | huggingface__transformers | src/transformers/models/swin/modeling_swin.py | {
"start": 11162,
"end": 13345
} | class ____(nn.Module):
"""
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
Transformer.
"""
def __init__(self, config):
super()._... | SwinPatchEmbeddings |
python | huggingface__transformers | tests/models/clip/test_modeling_clip.py | {
"start": 5781,
"end": 7672
} | class ____(ModelTesterMixin):
"""
Subclass of ModelTesterMixin with methods specific to testing CLIP models.
The SDPA equivalence test is overridden here because CLIP models may have test/vision/text+vision inputs,
different output logits, and are not supposed to be used or tested with padding_side="lef... | CLIPModelTesterMixin |
python | doocs__leetcode | solution/3000-3099/3076.Shortest Uncommon Substring in an Array/Solution.py | {
"start": 0,
"end": 535
} | class ____:
def shortestSubstrings(self, arr: List[str]) -> List[str]:
ans = [""] * len(arr)
for i, s in enumerate(arr):
m = len(s)
for j in range(1, m + 1):
for l in range(m - j + 1):
sub = s[l : l + j]
if not ans[i] or... | Solution |
python | getsentry__sentry | src/sentry/api/permissions.py | {
"start": 4628,
"end": 9324
} | class ____(ScopedPermission):
def is_not_2fa_compliant(
self, request: Request, organization: RpcOrganization | Organization
) -> bool:
return False
def needs_sso(self, request: Request, organization: Organization | RpcOrganization) -> bool:
return False
def is_member_disabled_... | SentryPermission |
python | huggingface__transformers | src/transformers/models/moshi/configuration_moshi.py | {
"start": 922,
"end": 7332
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MoshiDepthDecoder`]. It is used to instantiate a
Moshi depth decoder model according to the specified arguments, defining the Moshi depth decoder config.
Configuration objects inherit from [`PreTrainedC... | MoshiDepthConfig |
python | justquick__django-activity-stream | actstream/feeds.py | {
"start": 7615,
"end": 7831
} | class ____:
def get_object(self, request, content_type_id):
return get_object_or_404(ContentType, pk=content_type_id).model_class()
def get_stream(self):
return model_stream
| ModelActivityMixin |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/unscoped_css.py | {
"start": 477,
"end": 689
} | class ____(App):
def compose(self) -> ComposeResult:
yield MyWidget()
yield MyWidget()
yield Label("This will be styled")
if __name__ == "__main__":
app = MyApp()
app.run()
| MyApp |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 58105,
"end": 58357
} | class ____(_LoopTypesTester):
_ufuncs = [np.subtract, np.negative]
_required_types = '?bBhHiIlLqQfdFD'
_skip_types = 'mMO' + _LoopTypesTester._skip_types + '?'
TestLoopTypesSubtractAndNegative.autogenerate()
| TestLoopTypesSubtractAndNegative |
python | python__mypy | mypy/checker.py | {
"start": 6866,
"end": 7993
} | class ____(NamedTuple):
node: FineGrainedDeferredNodeType
active_typeinfo: TypeInfo | None
# Data structure returned by find_isinstance_check representing
# information learned from the truth or falsehood of a condition. The
# dict maps nodes representing expressions like 'a[0].x' to their
# refined types un... | FineGrainedDeferredNode |
python | kamyu104__LeetCode-Solutions | Python/word-pattern-ii.py | {
"start": 304,
"end": 1497
} | class ____(object):
def wordPatternMatch(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
w2p, p2w = {}, {}
return self.match(pattern, str, 0, 0, w2p, p2w)
def match(self, pattern, str, i, j, w2p, p2w):
is_match = False... | Solution |
python | huggingface__transformers | src/transformers/models/mask2former/image_processing_mask2former_fast.py | {
"start": 3514,
"end": 32349
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
size = {"shortest_edge": 800, "longest_edge": 1333}
default_to_square = False
do_resize = True
do_rescale = True
rescale_factor = 1 / 255
do_... | Mask2FormerImageProcessorFast |
python | wandb__wandb | wandb/sdk/launch/agent/config.py | {
"start": 990,
"end": 1132
} | class ____(str, Enum):
"""Enum of valid target platforms."""
linux_amd64 = "linux/amd64"
linux_arm64 = "linux/arm64"
| TargetPlatform |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 72377,
"end": 73003
} | class ____(FieldValues):
"""
Values for `FileField` with a filename output instead of URLs.
"""
valid_inputs = {}
invalid_inputs = {}
outputs = [
(MockFile(name='example.txt', url='/example.txt'), 'example.txt')
]
field = serializers.FileField(use_url=False)
def ext_validator(v... | TestFieldFieldWithName |
python | bokeh__bokeh | tests/unit/bokeh/models/test_glyph_renderer.py | {
"start": 5091,
"end": 8965
} | class ____:
def test_web_data_source(self) -> None:
renderer = bmr.GlyphRenderer(data_source=WebDataSource())
assert renderer._check_bad_column_name() == []
def test_non_cds_data_source(self) -> None:
renderer = bmr.GlyphRenderer(data_source=GeoJSONDataSource())
assert render... | TestGlyphRenderer_check_bad_column_name |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 56879,
"end": 57609
} | class ____(WebTestCase):
def get_app_kwargs(self):
return dict(
static_path=relpath("static"),
static_handler_args=dict(default_filename="index.html"),
)
def get_handlers(self):
return []
def test_static_default_filename(self):
response = self.fetch(... | StaticDefaultFilenameTest |
python | langchain-ai__langchain | libs/partners/prompty/langchain_prompty/parsers.py | {
"start": 237,
"end": 642
} | class ____:
_ROLE_MAP: dict[str, type[BaseMessage]] = {
"system": SystemMessage,
"user": HumanMessage,
"human": HumanMessage,
"assistant": AIMessage,
"ai": AIMessage,
"function": FunctionMessage,
}
ROLES = _ROLE_MAP.keys()
@classmethod
def get_message... | RoleMap |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 4425,
"end": 4615
} | class ____:
def a():
pass
# wrongly indented comment
def b():
pass
# end
# no error
def test():
pass
# Wrongly indented comment
pass
# end
# no error
| Test |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_exceptions.py | {
"start": 74517,
"end": 78336
} | class ____(__TestCase):
def tearDown(self):
unlink(TESTFN)
@force_not_colorized
def test_assertion_error_location(self):
cases = [
('assert None',
[
' assert None',
' ^^^^',
'AssertionError'... | AssertionErrorTests |
python | getsentry__sentry | src/sentry/seer/fetch_issues/utils.py | {
"start": 659,
"end": 1157
} | class ____(TypedDict):
error: str
def handle_fetch_issues_exceptions[R](
func: Callable[..., R],
) -> Callable[..., R | SeerResponseError]:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> R | SeerResponseError:
try:
return func(*args, **kwargs)
except Exception as e:... | SeerResponseError |
python | walkccc__LeetCode | solutions/1036. Escape a Large Maze/1036.py | {
"start": 0,
"end": 782
} | class ____:
def isEscapePossible(
self,
blocked: list[list[int]],
source: list[int],
target: list[int]
) -> bool:
def dfs(i: int, j: int, target: list[int], seen: set) -> bool:
if i < 0 or i >= 10**6 or j < 0 or j >= 10**6:
return False
if (i, j) in blocked or (i, j) ... | Solution |
python | django__django | tests/auth_tests/models/custom_user.py | {
"start": 3559,
"end": 3783
} | class ____(AbstractBaseUser):
username = models.CharField(max_length=150, unique=True)
email = models.EmailField(unique=True)
objects = UserManager()
USERNAME_FIELD = "username"
| CustomUserWithoutIsActiveField |
python | pypa__warehouse | tests/unit/admin/views/test_journals.py | {
"start": 294,
"end": 3419
} | class ____:
def test_no_query(self, db_request):
journals = sorted(
JournalEntryFactory.create_batch(30),
key=lambda j: (j.submitted_date, j.id),
reverse=True,
)
result = views.journals_list(db_request)
assert result == {"journals": journals[:25],... | TestProjectList |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.