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 | pydantic__pydantic | tests/mypy/modules/plugin_fail_baseConfig.py | {
"start": 1374,
"end": 1510
} | class ____(BaseModel):
class Config:
from_attributes = list # not sensible, but should still be handled gracefully
| BadConfig2 |
python | ipython__ipython | tests/test_zzz_autoreload.py | {
"start": 2985,
"end": 5387
} | class ____(TestCase):
"""Fixture for creating test module files"""
test_dir = None
old_sys_path = None
filename_chars = "abcdefghijklmopqrstuvwxyz0123456789"
def setUp(self):
self.test_dir = tempfile.mkdtemp()
self.old_sys_path = list(sys.path)
sys.path.insert(0, self.test_... | Fixture |
python | python-markdown__markdown | tests/test_apis.py | {
"start": 31931,
"end": 32344
} | class ____(unittest.TestCase):
""" Tests escape character append. """
def testAppend(self):
""" Test that appended escapes are only in the current instance. """
md = markdown.Markdown()
md.ESCAPED_CHARS.append('|')
self.assertEqual('|' in md.ESCAPED_CHARS, True)
md2 = ma... | TestEscapeAppend |
python | conda__conda | conda/exceptions.py | {
"start": 36612,
"end": 37594
} | class ____(CondaError):
def __init__(self, environment_location: PathType, **kwargs):
kwargs.update(
{
"environment_location": environment_location,
}
)
if on_win:
message = dals(
"""
The current user does not ha... | EnvironmentNotWritableError |
python | pikepdf__pikepdf | tests/test_canvas.py | {
"start": 7835,
"end": 10443
} | class ____:
def test_basic(self):
canvas = Canvas(page_size=(100, 100))
assert canvas.page_size == (100, 100)
with canvas.do.save_state(cm=Matrix().scaled(2, 2)):
canvas.do.stroke_color(Color(1, 0, 0, 1)).line_width(2).dashes(1, 1).line(
0, 0, 10, 10
)... | TestCanvas |
python | vyperlang__vyper | tests/functional/builtins/codegen/abi_decode.py | {
"start": 407,
"end": 4203
} | class ____(Exception):
pass
def _strict_slice(payload, start, length):
if start < 0:
raise DecodeError(f"OOB {start}")
end = start + length
if end > len(payload):
raise DecodeError(f"OOB {start} + {length} (=={end}) > {len(payload)}")
return payload[start:end]
def _read_int(payl... | DecodeError |
python | Lightning-AI__lightning | src/lightning/pytorch/serve/servable_module.py | {
"start": 110,
"end": 3288
} | class ____(ABC, torch.nn.Module):
"""The ServableModule provides a simple API to make your model servable.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
Here is an example of how to use the ``ServableModule`` module.
.. code-block:: python
from typing im... | ServableModule |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict1.py | {
"start": 249,
"end": 299
} | class ____(TypedDict, total=not_total):
pass
| TD1 |
python | readthedocs__readthedocs.org | readthedocs/sso/models.py | {
"start": 140,
"end": 1548
} | class ____(models.Model):
"""Single Sign-On integration for an Organization."""
PROVIDER_ALLAUTH = "allauth"
PROVIDER_EMAIL = "email"
PROVIDER_SAML = "saml"
PROVIDER_CHOICES = (
(PROVIDER_ALLAUTH, "AllAuth"),
(PROVIDER_EMAIL, "Email"),
(PROVIDER_SAML, "SAML"),
)
nam... | SSOIntegration |
python | astropy__astropy | astropy/time/tests/test_methods.py | {
"start": 597,
"end": 2143
} | class ____:
def setup_class(cls):
mjd = np.arange(50000, 50010)
frac = np.arange(0.0, 0.999, 0.2)
frac_masked = np.ma.array(frac)
frac_masked[1] = np.ma.masked
cls.t0 = {
"not_masked": Time(mjd[:, np.newaxis] + frac, format="mjd", scale="utc"),
"maske... | ShapeSetup |
python | donnemartin__interactive-coding-challenges | stacks_queues/stack/test_stack.py | {
"start": 18,
"end": 1158
} | class ____(unittest.TestCase):
# TODO: It would be better if we had unit tests for each
# method in addition to the following end-to-end test
def test_end_to_end(self):
print('Test: Empty stack')
stack = Stack()
self.assertEqual(stack.peek(), None)
self.assertEqual(stack.pop... | TestStack |
python | run-llama__llama_index | llama-index-integrations/graph_stores/llama-index-graph-stores-nebula/tests/test_property_graph.py | {
"start": 548,
"end": 3652
} | class ____(TestCase):
@classmethod
def setUp(self) -> None:
try:
g = get_store()
except RuntimeError:
raise SkipTest("NebulaGraph service is not available")
def test_add(self) -> None:
g = get_store()
e1 = EntityNode(name="e1")
e2 = EntityNod... | TestPropertyGraphStore |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 58400,
"end": 60347
} | class ____:
def test_matrix_rank(self):
# Full rank matrix
assert_equal(4, matrix_rank(np.eye(4)))
# rank deficient matrix
I = np.eye(4)
I[-1, -1] = 0.
assert_equal(matrix_rank(I), 3)
# All zeros - zero rank
assert_equal(matrix_rank(np.zeros((4, 4))),... | TestMatrixRank |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/_line.py | {
"start": 233,
"end": 21814
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d"
_path_str = "scatter3d.line"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"color",
"coloraxis",
"colorbar",
"colorscale",
"colorsrc",
... | Line |
python | davidhalter__jedi | jedi/inference/gradual/typing.py | {
"start": 7524,
"end": 8802
} | class ____(ProxyWithGenerics, _TypingClassMixin):
def infer_type_vars(self, value_set):
type_var_dict = {}
annotation_generics = self.get_generics()
if not annotation_generics:
return type_var_dict
annotation_name = self.py__name__()
if annotation_name == 'Type'... | TypingClassWithGenerics |
python | sympy__sympy | sympy/stats/stochastic_process_types.py | {
"start": 10183,
"end": 10854
} | class ____(StochasticProcess):
"""
Base class for all continuous time stochastic process.
"""
def __call__(self, time):
"""
For indexing continuous time stochastic processes.
Returns
=======
RandomIndexedSymbol
"""
time = sympify(time)
if... | ContinuousTimeStochasticProcess |
python | gevent__gevent | src/greentest/3.11/test_ftplib.py | {
"start": 3551,
"end": 9037
} | class ____(asynchat.async_chat):
dtp_handler = DummyDTPHandler
def __init__(self, conn, encoding=DEFAULT_ENCODING):
asynchat.async_chat.__init__(self, conn)
# tells the socket to handle urgent data inline (ABOR command)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1)
... | DummyFTPHandler |
python | python-poetry__poetry | src/poetry/publishing/publisher.py | {
"start": 345,
"end": 2933
} | class ____:
"""
Registers and publishes packages to remote repositories.
"""
def __init__(self, poetry: Poetry, io: IO, dist_dir: Path | None = None) -> None:
self._poetry = poetry
self._package = poetry.package
self._io = io
self._uploader = Uploader(poetry, io, dist_di... | Publisher |
python | tiangolo__fastapi | docs_src/response_model/tutorial006.py | {
"start": 104,
"end": 848
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: float = 10.5
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz",
"description": ... | Item |
python | apache__airflow | providers/databricks/tests/unit/databricks/sensors/test_databricks_sql.py | {
"start": 1704,
"end": 3853
} | class ____:
def setup_method(self):
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
self.dag = DAG("test_dag_id", schedule=None, default_args=args)
self.sensor = DatabricksSqlSensor(
task_id=TASK_ID,
databricks_conn_id=DEFAULT_CONN_ID,
sql_warehou... | TestDatabricksSqlSensor |
python | huggingface__transformers | src/transformers/models/pix2struct/modeling_pix2struct.py | {
"start": 8873,
"end": 10188
} | class ____(nn.Module):
def __init__(self, config: Pix2StructVisionConfig):
super().__init__()
self.wi_0 = nn.Linear(config.hidden_size, config.d_ff, bias=False)
self.wi_1 = nn.Linear(config.hidden_size, config.d_ff, bias=False)
self.wo = nn.Linear(config.d_ff, config.hidden_size, bia... | Pix2StructVisionMlp |
python | has2k1__plotnine | plotnine/composition/_stack.py | {
"start": 217,
"end": 1493
} | class ____(Compose):
"""
Place plots or compositions on top of each other
**Usage**
plot / plot
plot / composition
composition / plot
composition / composition
Typically, you will use this class through the `/` operator.
See Also
--------
plotnine.composit... | Stack |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 2986,
"end": 3228
} | class ____(RootModel[dict[str, Any]]):
model_config = {
"json_schema_extra": {
"$ref": create_definition_ref("io.k8s.api.core.v1.ResourceRequirements"),
"additionalProperties": True,
}
}
| Resources |
python | bokeh__bokeh | tests/unit/bokeh/core/property/_util_property.py | {
"start": 1749,
"end": 1921
} | class ____(HasProps):
x = Int(12)
y = String("hello")
z = List(Int, default=[1, 2, 3])
zz = Dict(String, Int)
s = Nullable(String ,default=None)
| _TestModel |
python | getsentry__sentry-python | sentry_sdk/profiler/transaction_profiler.py | {
"start": 6035,
"end": 17661
} | class ____:
def __init__(
self,
sampled, # type: Optional[bool]
start_ns, # type: int
hub=None, # type: Optional[sentry_sdk.Hub]
scheduler=None, # type: Optional[Scheduler]
):
# type: (...) -> None
self.scheduler = _scheduler if scheduler is None else ... | Profile |
python | huggingface__transformers | src/transformers/models/mpt/modeling_mpt.py | {
"start": 15252,
"end": 19835
} | class ____(MptPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"}
def __init__(self, config: MptConfig):
super().__init__(config)
self.transformer = MptModel(config)
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=Fal... | MptForCausalLM |
python | modin-project__modin | modin/config/envvars.py | {
"start": 6151,
"end": 7012
} | class ____(
EnvironmentVariable,
type=EnvironmentVariable.type,
abstract=True,
):
"""Subclass to disallow getting this variable from the environment when both execution and backend are set in the environment."""
@classmethod
@doc(EnvironmentVariable._get_value_from_config.__doc__)
def _get_... | EnvironmentVariableDisallowingExecutionAndBackendBothSet |
python | numpy__numpy | numpy/typing/tests/data/pass/scalars.py | {
"start": 393,
"end": 3725
} | class ____:
def __float__(self) -> float:
return 4.0
np.complex64(3j)
np.complex64(A())
np.complex64(C())
np.complex128(3j)
np.complex128(C())
np.complex128(None)
np.complex64("1.2")
np.complex128(b"2j")
np.int8(4)
np.int16(3.4)
np.int32(4)
np.int64(-1)
np.uint8(B())
np.uint32()
np.int32("1")
np.int64(b"... | A |
python | run-llama__llama_index | llama-index-integrations/memory/llama-index-memory-bedrock-agentcore/llama_index/memory/bedrock_agentcore/base.py | {
"start": 4893,
"end": 14346
} | class ____(BaseAgentCoreMemory):
search_msg_limit: int = Field(
default=5,
description="Limit of chat history messages to use for context in search API",
)
insert_method: InsertMethod = Field(
default=InsertMethod.SYSTEM,
description="Whether to inject memory blocks into a sy... | AgentCoreMemory |
python | sanic-org__sanic | sanic/server/async_server.py | {
"start": 180,
"end": 3475
} | class ____:
"""Wraps an asyncio server with functionality that might be useful to a user who needs to manage the server lifecycle manually.""" # noqa: E501
__slots__ = ("app", "connections", "loop", "serve_coro", "server")
def __init__(
self,
app: Sanic,
loop,
serve_coro,
... | AsyncioServer |
python | apache__airflow | airflow-core/src/airflow/serialization/serialized_objects.py | {
"start": 48858,
"end": 97756
} | class ____(DAGNode, BaseSerialization):
"""
A JSON serializable representation of operator.
All operators are casted to SerializedBaseOperator after deserialization.
Class specific attributes used by UI are move to object attributes.
Creating a SerializedBaseOperator is a three-step process:
... | SerializedBaseOperator |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 13942,
"end": 14064
} | class ____(OpcodeWithArg): # Arg: Number of args with default values
_FLAGS = HAS_ARGUMENT
__slots__ = ()
| MAKE_FUNCTION |
python | davidhalter__parso | parso/cache.py | {
"start": 2707,
"end": 8452
} | class ____:
def __init__(self, node, lines, change_time=None):
self.node = node
self.lines = lines
if change_time is None:
change_time = time.time()
self.change_time = change_time
self.last_used = change_time
def load_module(hashed_grammar, file_io, cache_path=N... | _NodeCacheItem |
python | google__jax | jax/_src/pallas/core.py | {
"start": 3640,
"end": 3784
} | class ____(semaphore_dtype):
"""Barrier semaphore dtype.
Like its superclass, this class should never be instantiated.
"""
| barrier_semaphore |
python | hyperopt__hyperopt | hyperopt/mongoexp.py | {
"start": 34662,
"end": 39822
} | class ____:
poll_interval = 3.0 # -- seconds
workdir = None
def __init__(
self,
mj,
poll_interval=poll_interval,
workdir=workdir,
exp_key=None,
logfilename="logfile.txt",
):
"""
mj - MongoJobs interface to jobs collection
poll_int... | MongoWorker |
python | huggingface__transformers | src/transformers/models/pegasus_x/modeling_pegasus_x.py | {
"start": 42236,
"end": 53077
} | class ____(PegasusXPreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`PegasusDecoderLayer`]
Args:
config: PegasusXConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(self, config: PegasusXConfig):
supe... | PegasusXDecoder |
python | Lightning-AI__lightning | src/lightning/pytorch/strategies/model_parallel.py | {
"start": 2533,
"end": 16072
} | class ____(ParallelStrategy):
"""Enables user-defined parallelism applied to a model.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
Currently supports up to 2D parallelism. Specifically, it supports the combination of
Fully Sharded Data-Parallel 2 (FSDP2) with Ten... | ModelParallelStrategy |
python | django__django | django/core/files/uploadedfile.py | {
"start": 3467,
"end": 4207
} | class ____(InMemoryUploadedFile):
"""
A simple representation of a file, which just has content, size, and a
name.
"""
def __init__(self, name, content, content_type="text/plain"):
content = content or b""
super().__init__(
BytesIO(content), None, name, content_type, len... | SimpleUploadedFile |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 148813,
"end": 149403
} | class ____(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1):
super().__init__()
self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=stride)
pad = kernel_size - stride
self.left_pad = math.ceil(pad)
self.right_pad = pa... | Qwen3OmniMoeCausalTransConvNet |
python | prabhupant__python-ds | data_structures/binary_trees/boundary_traversal.py | {
"start": 126,
"end": 1561
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def print_leaves(root):
if root:
print_leaves(root.left)
if not root.left and not root.right:
print(root.val, end=' ')
print_leaves(root.right)
def print_left... | Node |
python | encode__django-rest-framework | tests/test_validators.py | {
"start": 35904,
"end": 36044
} | class ____(serializers.ModelSerializer):
class Meta:
model = UniqueForYearModel
fields = '__all__'
| UniqueForYearSerializer |
python | google__jax | jax/_src/interpreters/partial_eval.py | {
"start": 5778,
"end": 24612
} | class ____(Trace['JaxprTracer']):
def __init__(self, parent_trace:Trace, name_stack: source_info_util.NameStack, tag:TraceTag):
super().__init__()
self.name_stack = name_stack
self.tag = tag
self.parent_trace = parent_trace
self.requires_low = False
self.effect_handles : list[EffectHandle] = ... | JaxprTrace |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 1913,
"end": 2041
} | class ____( # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP
):
...
@dataclass
| AltCLIPOutput |
python | keon__algorithms | algorithms/queues/priority_queue.py | {
"start": 125,
"end": 332
} | class ____:
def __init__(self, data, priority):
self.data = data
self.priority = priority
def __repr__(self):
return "{}: {}".format(self.data, self.priority)
| PriorityQueueNode |
python | streamlit__streamlit | lib/tests/streamlit/runtime/scriptrunner/script_runner_test.py | {
"start": 3219,
"end": 43506
} | class ____(AsyncTestCase):
def setUp(self) -> None:
super().setUp()
mock_runtime = MagicMock(spec=Runtime)
mock_runtime.media_file_mgr = MediaFileManager(
MemoryMediaFileStorage("/mock/media")
)
mock_runtime.media_file_mgr.clear_session_refs = MagicMock()
... | ScriptRunnerTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/util.py | {
"start": 74616,
"end": 82311
} | class ____(Exception):
pass
def _cleanup_mapped_str_annotation(
annotation: str, originating_module: str
) -> str:
# fix up an annotation that comes in as the form:
# 'Mapped[List[Address]]' so that it instead looks like:
# 'Mapped[List["Address"]]' , which will allow us to get
# "Address" as... | _CleanupError |
python | jmcnamara__XlsxWriter | xlsxwriter/test/vml/test_write_stroke.py | {
"start": 289,
"end": 742
} | class ____(unittest.TestCase):
"""
Test the Vml _write_stroke() method.
"""
def setUp(self):
self.fh = StringIO()
self.vml = Vml()
self.vml._set_filehandle(self.fh)
def test_write_stroke(self):
"""Test the _write_stroke() method"""
self.vml._write_stroke()... | TestWriteVstroke |
python | ray-project__ray | python/ray/util/client/worker.py | {
"start": 2826,
"end": 37514
} | class ____:
def __init__(
self,
conn_str: str = "",
secure: bool = False,
metadata: List[Tuple[str, str]] = None,
connection_retries: int = 3,
_credentials: Optional[grpc.ChannelCredentials] = None,
):
"""Initializes the worker side grpc client.
A... | Worker |
python | PyCQA__pylint | tests/functional/s/singledispatch/singledispatch_method.py | {
"start": 1155,
"end": 2020
} | class ____:
@singledispatch # [singledispatch-method]
@staticmethod
def convert_position(position):
pass
@convert_position.register # [singledispatch-method]
@staticmethod
def _(position: str) -> tuple:
position_a, position_b = position.split(",")
return (int(position_... | Board3 |
python | PrefectHQ__prefect | tests/server/orchestration/test_policies.py | {
"start": 226,
"end": 2909
} | class ____:
def test_policies_return_rules_in_priority_order(self):
class FirstRuleOfFightClub(BaseOrchestrationRule):
TO_STATES = ALL_ORCHESTRATION_STATES
FROM_STATES = ALL_ORCHESTRATION_STATES
def before_transition(self, initial_state, proposed_state, context):
... | TestPoliciesRespectOrdering |
python | sympy__sympy | sympy/core/exprtools.py | {
"start": 9678,
"end": 26677
} | class ____:
"""Efficient representation of ``f_1*f_2*...*f_n``."""
__slots__ = ('factors', 'gens')
def __init__(self, factors=None): # Factors
"""Initialize Factors from dict or expr.
Examples
========
>>> from sympy.core.exprtools import Factors
>>> from sympy.a... | Factors |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/shape_output_test.py | {
"start": 5390,
"end": 6450
} | class ____(trt_test.TfTrtIntegrationTestBase):
"""Two inputs, one of the is pruned."""
def setUp(self):
super().setUp()
self.DisableNonTrtOptimizers()
def GraphFn(self, x, y):
q = array_ops.shape(x)
z = y * y + y
z = gen_array_ops.reshape(z, q)
out_0 = array_ops.identity(q, name="output_... | PrunedInputTest2 |
python | kamyu104__LeetCode-Solutions | Python/find-k-length-substrings-with-no-repeated-characters.py | {
"start": 29,
"end": 441
} | class ____(object):
def numKLenSubstrNoRepeats(self, S, K):
"""
:type S: str
:type K: int
:rtype: int
"""
result, i = 0, 0
lookup = set()
for j in xrange(len(S)):
while S[j] in lookup:
lookup.remove(S[i])
i +... | Solution |
python | spyder-ide__spyder | spyder/plugins/debugger/widgets/main_widget.py | {
"start": 1889,
"end": 2001
} | class ____:
Display = 'excludes_section'
Highlight = 'highlight_section'
| DebuggerWidgetOptionsMenuSections |
python | ray-project__ray | rllib/examples/rl_modules/classes/vpg_torch_rlm.py | {
"start": 116,
"end": 2746
} | class ____(TorchRLModule):
"""A simple VPG (vanilla policy gradient)-style RLModule for testing purposes.
Use this as a minimum, bare-bones example implementation of a custom TorchRLModule.
"""
def setup(self):
"""Use this method to create all the model components that you require.
Fe... | VPGTorchRLModule |
python | Lightning-AI__lightning | src/lightning/pytorch/loops/optimization/automatic.py | {
"start": 1442,
"end": 3612
} | class ____(OutputResult):
"""A container to hold the result of a :class:`Closure` call.
It is created from the output of :meth:`~lightning.pytorch.core.LightningModule.training_step`.
Attributes:
closure_loss: The loss with a graph attached.
loss: A detached copy of the closure loss.
... | ClosureResult |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1178808,
"end": 1179006
} | class ____(VegaLiteSchema):
"""SelectionType schema wrapper."""
_schema = {"$ref": "#/definitions/SelectionType"}
def __init__(self, *args):
super().__init__(*args)
| SelectionType |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/llm_config.py | {
"start": 1961,
"end": 2055
} | class ____(str, Enum):
"""Enum that represents an LLMEngine."""
vLLM = "vLLM"
| LLMEngine |
python | joblib__joblib | joblib/externals/loky/backend/queues.py | {
"start": 705,
"end": 6145
} | class ____(mp_Queue):
def __init__(self, maxsize=0, reducers=None, ctx=None):
super().__init__(maxsize=maxsize, ctx=ctx)
self._reducers = reducers
# Use custom queue set/get state to be able to reduce the custom reducers
def __getstate__(self):
assert_spawning(self)
return (... | Queue |
python | PrefectHQ__prefect | tests/cli/test_start_server.py | {
"start": 8354,
"end": 12184
} | class ____:
def test_start_and_stop_background_server(self, unused_tcp_port: int):
invoke_and_assert(
command=[
"server",
"start",
"--port",
str(unused_tcp_port),
"--background",
],
expected_o... | TestBackgroundServer |
python | pydantic__pydantic | pydantic/warnings.py | {
"start": 4417,
"end": 4585
} | class ____(CoreSchemaGenerationWarning):
"""A warning raised when a `Field()` attribute isn't supported in the context it is used."""
| UnsupportedFieldAttributeWarning |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 69926,
"end": 72191
} | class ____(SimpleHandlerTestCase):
class Handler(RequestHandler):
def get(self):
for v in self.get_arguments("vary"):
self.add_header("Vary", v)
# Must write at least MIN_LENGTH bytes to activate compression.
self.write("hello world" + ("!" * GZipContentEn... | GzipTestCase |
python | ray-project__ray | python/ray/serve/tests/test_metrics_2.py | {
"start": 1545,
"end": 23228
} | class ____:
def _generate_metrics_summary(self, metrics: List[Dict]):
"""Generate "route" and "application" information from metrics.
Args:
metrics: List of metric dictionaries, each generated by the
get_metric_dictionaries function.
Returns:
Tuple[di... | TestRequestContextMetrics |
python | django__django | tests/defer/tests.py | {
"start": 14620,
"end": 16347
} | class ____(SimpleTestCase):
def test_invalid_defer(self):
msg = "Primary has no field named 'missing'"
with self.assertRaisesMessage(FieldDoesNotExist, msg):
list(Primary.objects.defer("missing"))
with self.assertRaisesMessage(FieldError, "missing"):
list(Primary.obje... | InvalidDeferTests |
python | getsentry__sentry | src/sentry/relay/config/__init__.py | {
"start": 49012,
"end": 50980
} | class ____(TypedDict):
version: int
extractCustomTags: list[str]
customMeasurements: CustomMeasurementSettings
acceptTransactionNames: TransactionNameStrategy
def _should_extract_transaction_metrics(project: Project) -> bool:
return features.has(
"organizations:transaction-metrics-extracti... | TransactionMetricsSettings |
python | encode__django-rest-framework | rest_framework/versioning.py | {
"start": 5953,
"end": 6801
} | class ____(BaseVersioning):
"""
GET /something/?version=0.1 HTTP/1.1
Host: example.com
Accept: application/json
"""
invalid_version_message = _('Invalid version in query parameter.')
def determine_version(self, request, *args, **kwargs):
version = request.query_params.get(self.versi... | QueryParameterVersioning |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/tags.py | {
"start": 4400,
"end": 4989
} | class ____(Enum):
# Custom tag provided by a user
USER_PROVIDED = "USER_PROVIDED"
# Tags used by Dagster to manage execution that should be surfaced to users.
SYSTEM = "SYSTEM"
# Metadata used by Dagster for execution but isn't useful for users to see.
# For example, metadata about the gRPC se... | TagType |
python | pypa__pipenv | pipenv/vendor/importlib_metadata/__init__.py | {
"start": 9667,
"end": 22069
} | class ____(metaclass=abc.ABCMeta):
"""
An abstract Python distribution package.
Custom providers may derive from this class and define
the abstract methods to provide a concrete implementation
for their environment. Some providers may opt to override
the default implementation of some propertie... | Distribution |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/links/test_sagemaker_unified_studio.py | {
"start": 1195,
"end": 2035
} | class ____(BaseAwsLinksTestCase):
link_class = SageMakerUnifiedStudioLink
def test_extra_link(self, mock_supervisor_comms):
if AIRFLOW_V_3_0_PLUS and mock_supervisor_comms:
mock_supervisor_comms.send.return_value = XComResult(
key=self.link_class.key,
value={... | TestSageMakerUnifiedStudioLink |
python | pandas-dev__pandas | asv_bench/benchmarks/io/json.py | {
"start": 2105,
"end": 2811
} | class ____(BaseIO):
fname = "__test__.json"
params = [
["split", "columns", "index", "values", "records"],
["df", "df_date_idx", "df_td_int_ts", "df_int_floats", "df_int_float_str"],
]
param_names = ["orient", "frame"]
def setup(self, orient, frame):
data = {
"he... | NormalizeJSON |
python | walkccc__LeetCode | solutions/1534. Count Good Triplets/1534.py | {
"start": 0,
"end": 299
} | class ____:
def countGoodTriplets(self, arr: list[int], a: int, b: int, c: int) -> int:
return sum(abs(arr[i] - arr[j]) <= a and
abs(arr[j] - arr[k]) <= b and
abs(arr[i] - arr[k]) <= c
for i, j, k in itertools.combinations(range(len(arr)), 3))
| Solution |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 6184,
"end": 7366
} | class ____(PrefectOperatorFilterBaseModel):
"""Filter for flows. Only flows matching all criteria will be returned."""
id: Optional[FlowFilterId] = Field(
default=None, description="Filter criteria for `Flow.id`"
)
deployment: Optional[FlowFilterDeployment] = Field(
default=None, descri... | FlowFilter |
python | kamyu104__LeetCode-Solutions | Python/sum-of-largest-prime-substrings.py | {
"start": 89,
"end": 2157
} | class ____(object):
def sumOfLargestPrimes(self, s):
"""
:type s: str
:rtype: int
"""
COUNT = 3
def nth_element(nums, n, left=0, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
mid = left
... | Solution |
python | apache__airflow | providers/teradata/tests/unit/teradata/transfers/test_s3_to_teradata.py | {
"start": 1232,
"end": 2918
} | class ____:
def test_init(self):
operator = S3ToTeradataOperator(
s3_source_key=S3_SOURCE_KEY,
teradata_table=TERADATA_TABLE,
aws_conn_id=AWS_CONN_ID,
teradata_conn_id=TERADATA_CONN_ID,
task_id=TASK_ID,
dag=None,
)
asse... | TestS3ToTeradataTransfer |
python | doocs__leetcode | solution/2300-2399/2358.Maximum Number of Groups Entering a Competition/Solution.py | {
"start": 0,
"end": 173
} | class ____:
def maximumGroups(self, grades: List[int]) -> int:
n = len(grades)
return bisect_right(range(n + 1), n * 2, key=lambda x: x * x + x) - 1
| Solution |
python | has2k1__plotnine | plotnine/stats/stat_quantile.py | {
"start": 275,
"end": 2635
} | class ____(stat):
"""
Compute quantile regression lines
{usage}
Parameters
----------
{common_parameters}
quantiles : tuple, default=(0.25, 0.5, 0.75)
Quantiles of y to compute
formula : str, default="y ~ x"
Formula relating y variables to x variables
method_args : ... | stat_quantile |
python | python__mypy | mypyc/ir/ops.py | {
"start": 50605,
"end": 51463
} | class ____(RegisterOp):
"""Set the value of a struct element.
This evaluates to a new struct with the changed value.
Use together with Undef to initialize a fresh struct value
(see Undef for more details).
"""
error_kind = ERR_NEVER
def __init__(self, src: Value, field: str, item: Value,... | SetElement |
python | huggingface__transformers | tests/quantization/autoawq/test_awq.py | {
"start": 23086,
"end": 24178
} | class ____(unittest.TestCase):
def test_quantized_model_ipex(self):
"""
Simple test that checks if the quantized model is working properly with ipex backend
"""
quantization_config = AwqConfig(version="ipex")
model = AutoModelForCausalLM.from_pretrained(
"TheBlok... | AwqIPEXTest |
python | coleifer__peewee | tests/schema.py | {
"start": 1224,
"end": 1353
} | class ____(TestModel):
key = TextField(unique=True)
value = TextField()
class Meta:
schema = 'cache'
| CacheData |
python | getsentry__sentry | src/sentry/db/models/fields/bounded.py | {
"start": 734,
"end": 1011
} | class ____(models.PositiveIntegerField):
MAX_VALUE = I32_MAX
def get_prep_value(self, value: int) -> int:
if value:
value = int(value)
assert value <= self.MAX_VALUE
return super().get_prep_value(value)
| BoundedPositiveIntegerField |
python | django__django | tests/model_enums/tests.py | {
"start": 8485,
"end": 8640
} | class ____(datetime.datetime, models.Choices):
A = 2010, 10, 10, 10, 10, 10
B = 2011, 11, 11, 11, 11, 11
C = 2012, 12, 12, 12, 12, 12
| DateAndTime |
python | google__python-fire | fire/test_components.py | {
"start": 3020,
"end": 3146
} | class ____:
def sum(self, Delta=1.0, Gamma=2.0): # pylint: disable=invalid-name
return Delta + Gamma
| CapitalizedArgNames |
python | kamyu104__LeetCode-Solutions | Python/binary-subarrays-with-sum.py | {
"start": 53,
"end": 739
} | class ____(object):
def numSubarraysWithSum(self, A, S):
"""
:type A: List[int]
:type S: int
:rtype: int
"""
result = 0
left, right, sum_left, sum_right = 0, 0, 0, 0
for i, a in enumerate(A):
sum_left += a
while left < i and sum... | Solution |
python | huggingface__transformers | src/transformers/models/cvt/modeling_cvt.py | {
"start": 11474,
"end": 11932
} | class ____(nn.Module):
def __init__(self, embed_dim, mlp_ratio, drop_rate):
super().__init__()
self.dense = nn.Linear(int(embed_dim * mlp_ratio), embed_dim)
self.dropout = nn.Dropout(drop_rate)
def forward(self, hidden_state, input_tensor):
hidden_state = self.dense(hidden_state... | CvtOutput |
python | Pylons__pyramid | docs/tutorials/wiki/src/basiclayout/tutorial/models/__init__.py | {
"start": 51,
"end": 284
} | class ____(PersistentMapping):
__parent__ = __name__ = None
def appmaker(zodb_root):
if 'app_root' not in zodb_root:
app_root = MyModel()
zodb_root['app_root'] = app_root
return zodb_root['app_root']
| MyModel |
python | doocs__leetcode | lcp/LCP 07. 传递信息/Solution.py | {
"start": 0,
"end": 285
} | class ____:
def numWays(self, n: int, relation: List[List[int]], k: int) -> int:
f = [[0] * n for _ in range(k + 1)]
f[0][0] = 1
for i in range(1, k + 1):
for a, b in relation:
f[i][b] += f[i - 1][a]
return f[-1][-1]
| Solution |
python | gevent__gevent | src/greentest/3.13/test_queue.py | {
"start": 27240,
"end": 27340
} | class ____(FailingQueueTest, unittest.TestCase):
queue = py_queue
@need_c_queue
| PyFailingQueueTest |
python | doocs__leetcode | solution/1200-1299/1297.Maximum Number of Occurrences of a Substring/Solution2.py | {
"start": 532,
"end": 1187
} | class ____:
def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
freq = Counter()
hashing = Hashing(s)
cnt = Counter()
ans = k = 0
for i, c in enumerate(s, 1):
freq[c] += 1
if freq[c] == 1:
k += 1
i... | Solution |
python | apache__airflow | airflow-core/src/airflow/task/priority_strategy.py | {
"start": 1079,
"end": 2850
} | class ____(ABC):
"""
Priority weight strategy interface.
This feature is experimental and subject to change at any time.
Currently, we don't serialize the priority weight strategy parameters. This means that
the priority weight strategy must be stateless, but you can add class attributes, and
... | PriorityWeightStrategy |
python | facebook__pyre-check | client/json_rpc.py | {
"start": 1852,
"end": 2006
} | class ____(JSONRPCException):
"""
Invalid method parameter(s).
"""
def error_code(self) -> int:
return -32602
| InvalidParameterError |
python | tqdm__tqdm | tqdm/std.py | {
"start": 944,
"end": 987
} | class ____(TypeError):
pass
| TqdmTypeError |
python | hyperopt__hyperopt | hyperopt/mongoexp.py | {
"start": 8855,
"end": 21476
} | class ____:
"""
# Interface to a Jobs database structured like this
#
# Collections:
#
# db.jobs - structured {config_name, 'cmd', 'owner', 'book_time',
# 'refresh_time', 'state', 'exp_key', 'owner', 'result'}
# This is the collection that the worker nodes write to
... | MongoJobs |
python | google__python-fire | fire/core.py | {
"start": 6840,
"end": 7053
} | class ____(Exception):
"""Exception used by Fire when a Fire command cannot be executed.
These exceptions are not raised by the Fire function, but rather are caught
and added to the FireTrace.
"""
| FireError |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 69508,
"end": 69874
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc = torch.nn.Linear(5, 5).to(dtype=torch.float)
self.relu = torch.nn.ReLU()
def forward(self, x):
x = self.relu(self.fc(x))
return x
def get_example_inputs(self) -> tuple[Any, ...]:
... | LinearReluModel |
python | apache__airflow | task-sdk/tests/task_sdk/bases/test_sensor.py | {
"start": 26530,
"end": 27034
} | class ____:
@pytest.mark.parametrize(
("soft_fail", "expected_exception"),
[
(True, AirflowSkipException),
(False, AirflowException),
],
)
def test_fail_after_resuming_deferred_sensor(self, soft_fail, expected_exception):
async_sensor = DummyAsyncSenso... | TestAsyncSensor |
python | ray-project__ray | rllib/algorithms/marwil/marwil_torch_policy.py | {
"start": 796,
"end": 5350
} | class ____(ValueNetworkMixin, PostprocessAdvantages, TorchPolicyV2):
"""PyTorch policy class used with Marwil."""
def __init__(self, observation_space, action_space, config):
TorchPolicyV2.__init__(
self,
observation_space,
action_space,
config,
... | MARWILTorchPolicy |
python | zarr-developers__zarr-python | tests/test_store/test_wrapper.py | {
"start": 537,
"end": 759
} | class ____(TypedDict):
store_cls: type[LocalStore]
root: str
# TODO: fix this warning
@pytest.mark.filterwarnings(
"ignore:coroutine 'ClientCreatorContext.__aexit__' was never awaited:RuntimeWarning"
)
| OpenKwargs |
python | Netflix__metaflow | test/core/tests/project_production.py | {
"start": 72,
"end": 838
} | class ____(MetaflowTest):
PRIORITY = 1
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"recursive_switch",
"recursive_switch_inside_foreach",
]
HEADER = """... | ProjectProductionTest |
python | huggingface__transformers | src/transformers/models/rembert/modeling_rembert.py | {
"start": 20570,
"end": 20909
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = RemBertLMPredictionHead(config)
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
prediction_scores = self.predictions(sequence_output)
return prediction_scores
@auto_docst... | RemBertOnlyMLMHead |
python | doocs__leetcode | lcof2/剑指 Offer II 017. 含有所有字符的最短字符串/Solution2.py | {
"start": 0,
"end": 1043
} | 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)
needCount, windowCount = 0, 0
for c in t:
if need[c] == 0:
needCount += 1
ne... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.