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 | python-poetry__poetry | src/poetry/layouts/layout.py | {
"start": 1359,
"end": 7340
} | class ____:
def __init__(
self,
project: str,
version: str = "0.1.0",
description: str = "",
readme_format: str = "md",
author: str | None = None,
license: str | None = None,
python: str | None = None,
dependencies: Mapping[str, str | Mapping[s... | Layout |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context_creation_job.py | {
"start": 10173,
"end": 13721
} | class ____(ExecutionContextManager[PlanOrchestrationContext]):
def __init__(
self,
context_event_generator: Callable[
...,
Iterator[Union[DagsterEvent, PlanOrchestrationContext]],
],
job: IJob,
execution_plan: ExecutionPlan,
run_config: Mapping... | PlanOrchestrationContextManager |
python | huggingface__transformers | src/transformers/models/olmo2/modeling_olmo2.py | {
"start": 13606,
"end": 15384
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: Olmo2Config, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = Olmo2Attention(config=config, layer_idx=layer_idx)
self.mlp = Olmo2MLP(config)
self.post_attention_layer... | Olmo2DecoderLayer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 467078,
"end": 467575
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of AddProjectV2DraftIssue"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "project_item")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performin... | AddProjectV2DraftIssuePayload |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1124855,
"end": 1125297
} | class ____(sgqlc.types.Type, RepositoryNode):
"""A Dependabot Update for a dependency in a repository"""
__schema__ = github_schema
__field_names__ = ("error", "pull_request")
error = sgqlc.types.Field(DependabotUpdateError, graphql_name="error")
"""The error from a dependency update"""
pull_r... | DependabotUpdate |
python | ray-project__ray | rllib/utils/framework.py | {
"start": 7056,
"end": 7249
} | class ____:
def __init__(self) -> None:
self.keras = _KerasStub()
def __bool__(self):
# if tf should return False
return False
# Fake module for tf.keras.
| _TFStub |
python | spyder-ide__spyder | spyder/plugins/debugger/widgets/framesbrowser.py | {
"start": 13061,
"end": 14581
} | class ____(QStyledItemDelegate):
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self._margin = None
def paint(self, painter, option, index):
"""Paint the item."""
options = QStyleOptionViewItem(option)
self.initStyleOption(options, index)
... | ItemDelegate |
python | apache__airflow | task-sdk/tests/task_sdk/bases/test_sensor.py | {
"start": 2316,
"end": 2660
} | class ____(BaseSensorOperator):
def __init__(self, return_value=False, xcom_value=None, **kwargs):
super().__init__(**kwargs)
self.xcom_value = xcom_value
self.return_value = return_value
def poke(self, context: Context):
return PokeReturnValue(self.return_value, self.xcom_value... | DummySensorWithXcomValue |
python | fastapi__sqlmodel | docs_src/tutorial/many_to_many/tutorial002_py310.py | {
"start": 544,
"end": 3125
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
teams: list[Team] = Relationship(back_populates="heroes", link_model=HeroTeamLink)
sqlite_file_name = "database... | Hero |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/bitstring.py | {
"start": 410,
"end": 10603
} | class ____(str):
"""Represent a PostgreSQL bit string in python.
This object is used by the :class:`_postgresql.BIT` type when returning
values. :class:`_postgresql.BitString` values may also be constructed
directly and used with :class:`_postgresql.BIT` columns::
from sqlalchemy.dialects.po... | BitString |
python | lepture__mistune | src/mistune/directives/_rst.py | {
"start": 486,
"end": 1025
} | class ____(DirectiveParser):
name = "rst_directive"
@staticmethod
def parse_type(m: Match[str]) -> str:
return m.group("type")
@staticmethod
def parse_title(m: Match[str]) -> str:
return m.group("title")
@staticmethod
def parse_content(m: Match[str]) -> str:
full_c... | RSTParser |
python | getsentry__sentry | tests/sentry/event_manager/test_event_manager_grouping.py | {
"start": 14885,
"end": 23684
} | class ____(TestCase):
"""
Tests for a bug where error events were interpreted as default-type events and therefore all
came out with a placeholder title.
"""
def test_fixes_broken_title_data(self) -> None:
# An event before the bug was introduced
event1 = save_new_event(
... | PlaceholderTitleTest |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/metrics_utils.py | {
"start": 9812,
"end": 36030
} | class ____(Enum):
"""Type of AUC summation method.
https://en.wikipedia.org/wiki/Riemann_sum)
Contains the following values:
* 'interpolation': Applies mid-point summation scheme for `ROC` curve. For
`PR` curve, interpolates (true/false) positives but not the ratio that is
precision (see Davis & Goadr... | AUCSummationMethod |
python | spack__spack | lib/spack/spack/util/package_hash.py | {
"start": 855,
"end": 1669
} | class ____(ast.NodeTransformer):
"""Transformer that removes docstrings from a Python AST.
This removes *all* strings that aren't on the RHS of an assignment statement from
the body of functions, classes, and modules -- even if they're not directly after
the declaration.
"""
def remove_docstr... | RemoveDocstrings |
python | huggingface__transformers | tests/models/sam_hq/test_modeling_sam_hq.py | {
"start": 9673,
"end": 10725
} | class ____:
def __init__(
self,
hidden_size=32,
input_image_size=24,
patch_size=2,
mask_input_channels=4,
num_point_embeddings=4,
hidden_act="gelu",
):
self.hidden_size = hidden_size
self.input_image_size = input_image_size
self.pat... | SamHQPromptEncoderTester |
python | weaviate__weaviate-python-client | weaviate/collections/queries/near_image/generate/sync.py | {
"start": 314,
"end": 461
} | class ____(
Generic[Properties, References],
_NearImageGenerateExecutor[ConnectionSync, Properties, References],
):
pass
| _NearImageGenerate |
python | dask__distributed | distributed/comm/tcp.py | {
"start": 15770,
"end": 17091
} | class ____:
def _check_encryption(self, address, connection_args):
if not self.encrypted and connection_args.get("require_encryption"):
# XXX Should we have a dedicated SecurityError class?
raise RuntimeError(
"encryption required by Dask configuration, "
... | RequireEncryptionMixin |
python | zarr-developers__zarr-python | tests/package_with_entrypoint/__init__.py | {
"start": 1924,
"end": 2847
} | class ____(Bool):
"""
This is a "data type" that serializes to "test"
"""
_zarr_v3_name: ClassVar[Literal["test"]] = "test" # type: ignore[assignment]
@classmethod
def from_json(cls, data: DTypeJSON, *, zarr_format: Literal[2, 3]) -> Self:
if zarr_format == 2 and data == {"name": cls.... | TestDataType |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/rich/prompt.py | {
"start": 737,
"end": 8774
} | class ____(Generic[PromptType]):
"""Ask the user for input until a valid response is received. This is the base class, see one of
the concrete classes for examples.
Args:
prompt (TextType, optional): Prompt text. Defaults to "".
console (Console, optional): A Console instance or None to use... | PromptBase |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyflakes/F811_30.py | {
"start": 209,
"end": 292
} | class ____:
"""B."""
def baz(self) -> None:
"""Baz."""
baz = 1
| B |
python | pypa__warehouse | warehouse/utils/html.py | {
"start": 99,
"end": 2281
} | class ____(Extension):
"""
This extension adds support for a "Client side Include", which will be
included into the final page using javascript instead of on the server. It
is used like:
{% csi "/some/url/" %}
{% endcsi %}
Which will render as an empty div that will be replaced usi... | ClientSideIncludeExtension |
python | lxml__lxml | src/lxml/tests/test_http_io.py | {
"start": 441,
"end": 4489
} | class ____(HelperTestCase):
etree = etree
def _parse_from_http(self, data, code=200, headers=None):
parser = self.etree.XMLParser(no_network=False)
handler = HTTPRequestCollector(data, code, headers)
with webserver(handler) as host_url:
tree = self.etree.parse(host_url + 'TE... | HttpIOTestCase |
python | django__django | tests/tasks/test_dummy_backend.py | {
"start": 7067,
"end": 7659
} | class ____(TransactionTestCase):
available_apps = []
@override_settings(
TASKS={
"default": {
"BACKEND": "django.tasks.backends.dummy.DummyBackend",
}
}
)
def test_doesnt_wait_until_transaction_commit_by_default(self):
with transaction.ato... | DummyBackendTransactionTestCase |
python | numpy__numpy | benchmarks/benchmarks/bench_core.py | {
"start": 6330,
"end": 7156
} | class ____(Benchmark):
params = [['int64', 'uint64', 'float32', 'float64',
'complex64', 'bool_'],
[100, 10000]]
param_names = ['dtype', 'size']
def setup(self, dtype, size):
self.data = np.ones(size, dtype=dtype)
if dtype.startswith('complex'):
self.... | StatsMethods |
python | getsentry__sentry | src/sentry/api/serializers/release_details_types.py | {
"start": 260,
"end": 360
} | class ____(TypedDict, total=False):
dateStarted: str | None
url: str | None
| LastDeployOptional |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 90307,
"end": 92732
} | class ____(Request):
"""
Get all 'plot' events for this task
:param task: Task ID
:type task: str
:param iters: Max number of latest iterations for which to return debug images
:type iters: int
:param scroll_id: Scroll ID of previous call (used for getting more results)
:type scroll_id:... | GetTaskPlotsRequest |
python | django__django | tests/defer/models.py | {
"start": 70,
"end": 192
} | class ____(models.Model):
first = models.CharField(max_length=50)
second = models.CharField(max_length=50)
| Secondary |
python | huggingface__transformers | src/transformers/models/wav2vec2/tokenization_wav2vec2.py | {
"start": 3303,
"end": 4365
} | class ____(ModelOutput):
"""
Output type of [` Wav2Vec2CTCTokenizer`], with transcription.
Args:
text (list of `str` or `str`):
Decoded logits in text from. Usually the speech transcription.
char_offsets (list of `list[dict[str, Union[int, str]]]` or `list[dict[str, Union[int, s... | Wav2Vec2CTCTokenizerOutput |
python | ansible__ansible | test/units/plugins/connection/test_connection.py | {
"start": 943,
"end": 1493
} | class ____(ConnectionBase):
@property
def transport(self):
"""This method is never called by unit tests."""
def _connect(self):
"""This method is never called by unit tests."""
def exec_command(self):
"""This method is never called by unit tests."""
def put_file(self):
... | NoOpConnection |
python | kamyu104__LeetCode-Solutions | Python/binary-tree-zigzag-level-order-traversal.py | {
"start": 154,
"end": 787
} | class ____(object):
# @param root, a tree node
# @return a list of lists of integers
def zigzagLevelOrder(self, root):
if root is None:
return []
result, current = [], [root]
while current:
next_level, vals = [], []
for node in current:
... | Solution |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/evaluator.py | {
"start": 3932,
"end": 5617
} | class ____(object):
"""Evaluates Python expressions using debug tensor values from a dump."""
def __init__(self, dump):
"""Constructor of ExpressionEvaluator.
Args:
dump: an instance of `DebugDumpDir`.
"""
self._dump = dump
self._cached_tensor_values = {}
def evaluate(self, expression... | ExpressionEvaluator |
python | huggingface__transformers | tests/models/sam3_video/test_modeling_sam3_video.py | {
"start": 1213,
"end": 23879
} | class ____(unittest.TestCase):
def setUp(self):
super().setUp()
checkpoint_path = "facebook/sam3"
self.video_model = Sam3VideoModel.from_pretrained(checkpoint_path).to(torch.float32)
self.processor = Sam3VideoProcessor.from_pretrained(checkpoint_path)
self.video_model.to(torc... | Sam3VideoModelIntegrationTest |
python | fluentpython__example-code | 14-it-generator/isis2json/iso2709.py | {
"start": 1126,
"end": 2215
} | class ____(object):
def __init__(self, filename, encoding = DEFAULT_ENCODING):
self.file = open(filename, 'rb')
self.encoding = encoding
def __iter__(self):
return self
def next(self):
return IsoRecord(self)
__next__ = next # Python 3 compatibility
def read(self,... | IsoFile |
python | scrapy__scrapy | scrapy/exceptions.py | {
"start": 960,
"end": 1354
} | class ____(Exception):
"""
Stop the download of the body for a given response.
The 'fail' boolean parameter indicates whether or not the resulting partial response
should be handled by the request errback. Note that 'fail' is a keyword-only argument.
"""
def __init__(self, *, fail: bool = True)... | StopDownload |
python | apache__avro | lang/py/avro/schema.py | {
"start": 27712,
"end": 30380
} | class ____(EqualByJsonMixin, Schema):
"""
names is a dictionary of schema objects
"""
def __init__(self, schemas, names=None, validate_names: bool = True):
# Ensure valid ctor args
if not isinstance(schemas, list):
fail_msg = "Union schema requires a list of schemas."
... | UnionSchema |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 28782,
"end": 29251
} | class ____:
"""Holds counter state for invoking a method several times in a row."""
def __init__(self, count):
self.counter = 0
self.count = count
def go(self):
"""Raise a NameError until after count threshold has been crossed.
Then return True.
"""
if self... | NoNameErrorAfterCount |
python | kamyu104__LeetCode-Solutions | Python/removing-minimum-number-of-magic-beans.py | {
"start": 40,
"end": 275
} | class ____(object):
def minimumRemoval(self, beans):
"""
:type beans: List[int]
:rtype: int
"""
beans.sort()
return sum(beans) - max(x*(len(beans)-i)for i, x in enumerate(beans))
| Solution |
python | pandas-dev__pandas | pandas/core/indexes/period.py | {
"start": 2003,
"end": 18813
} | class ____(DatetimeIndexOpsMixin):
"""
Immutable ndarray holding ordinal values indicating regular periods in time.
Index keys are boxed to Period objects which carries the metadata (eg,
frequency information).
Parameters
----------
data : array-like (1d int np.ndarray or PeriodArray), opt... | PeriodIndex |
python | openai__openai-python | src/openai/types/responses/response_computer_tool_call_param.py | {
"start": 1484,
"end": 1631
} | class ____(TypedDict, total=False):
x: Required[int]
"""The x-coordinate."""
y: Required[int]
"""The y-coordinate."""
| ActionDragPath |
python | spack__spack | lib/spack/spack/cmd/__init__.py | {
"start": 20998,
"end": 21246
} | class ____(spack.error.SpackError):
"""Exception class thrown for impermissible python names"""
def __init__(self, name):
self.name = name
super().__init__("{0} is not a permissible Python name.".format(name))
| PythonNameError |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/branch/ai.py | {
"start": 6658,
"end": 8905
} | class ____:
"""Output channel that prints to stdout using click.echo."""
def write(self, text: str) -> None:
click.echo(text)
@contextmanager
def enter_waiting_phase(phase_name: str, spin: bool = True) -> Iterator["OutputChannel"]:
"""Enter a phase of non interactivity where we wait for the CLI a... | PrintOutputChannel |
python | sympy__sympy | sympy/utilities/decorator.py | {
"start": 3055,
"end": 11184
} | class ____:
"""Don't 'inherit' certain attributes from a base class
>>> from sympy.utilities.decorator import no_attrs_in_subclass
>>> class A(object):
... x = 'test'
>>> A.x = no_attrs_in_subclass(A, A.x)
>>> class B(A):
... pass
>>> hasattr(A, 'x')
True
>>> hasattr... | no_attrs_in_subclass |
python | pypa__setuptools | setuptools/msvc.py | {
"start": 917,
"end": 3900
} | class ____:
"""
Current and Target Architectures information.
Parameters
----------
arch: str
Target architecture.
"""
current_cpu = environ.get('processor_architecture', '').lower()
def __init__(self, arch: str) -> None:
self.arch = arch.lower().replace('x64', 'amd64'... | PlatformInfo |
python | gevent__gevent | src/greentest/3.10/test_smtpd.py | {
"start": 35548,
"end": 37185
} | class ____(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
self.server = DummyServer((socket_helper.HOST, 0), ('b', 0),
decode_... | SMTPDChannelWithDecodeDataTrue |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 15672,
"end": 17320
} | class ____(graphene.Mutation):
"""Deletes partitions from a dynamic partition set."""
Output = graphene.NonNull(GrapheneDeleteDynamicPartitionsResult)
class Arguments:
repositorySelector = graphene.NonNull(GrapheneRepositorySelector)
partitionsDefName = graphene.NonNull(graphene.String)
... | GrapheneDeleteDynamicPartitionsMutation |
python | streamlit__streamlit | lib/tests/streamlit/elements/heading_test.py | {
"start": 16211,
"end": 17370
} | class ____(DeltaGeneratorTestCase):
"""Test st.title text_alignment parameter."""
@parameterized.expand(
[
("left", 1),
("center", 2),
("right", 3),
("justify", 4),
(None, 1), # Default case
]
)
def test_st_title_text_alignmen... | StTitleTextAlignmentTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-deepset/destination_deepset/writer.py | {
"start": 371,
"end": 452
} | class ____:
"""Raised when an error is encountered by the writer"""
| WriterError |
python | ray-project__ray | rllib/algorithms/tests/test_algorithm_config.py | {
"start": 568,
"end": 17297
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
ray.init()
@classmethod
def tearDownClass(cls):
ray.shutdown()
def test_running_specific_algo_with_generic_config(self):
"""Tests, whether some algo can be run with the generic AlgorithmConfig."""
conf... | TestAlgorithmConfig |
python | django__django | tests/composite_pk/test_get.py | {
"start": 91,
"end": 5049
} | class ____(TestCase):
maxDiff = None
@classmethod
def setUpTestData(cls):
cls.tenant_1 = Tenant.objects.create()
cls.tenant_2 = Tenant.objects.create()
cls.user_1 = User.objects.create(
tenant=cls.tenant_1,
id=1,
email="user0001@example.com",
... | CompositePKGetTests |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 4108,
"end": 20639
} | class ____:
"""
A base class for tests that need to validate the ModelBackend
with different User models. Subclasses should define a class
level UserModel attribute, and a create_users() method to
construct two users for test purposes.
"""
backend = "django.contrib.auth.backends.ModelBacken... | BaseModelBackendTest |
python | getsentry__sentry | src/sentry/release_health/base.py | {
"start": 5577,
"end": 5762
} | class ____(TypedDict):
sessions: int
sessions_healthy: int
sessions_crashed: int
sessions_abnormal: int
sessions_unhandled: int
sessions_errored: int
| SessionCounts |
python | walkccc__LeetCode | solutions/658. Find K Closest Elements/658.py | {
"start": 0,
"end": 274
} | class ____:
def findClosestElements(self, arr: list[int], k: int, x: int) -> list[int]:
l = 0
r = len(arr) - k
while l < r:
m = (l + r) // 2
if x - arr[m] <= arr[m + k] - x:
r = m
else:
l = m + 1
return arr[l:l + k]
| Solution |
python | kamyu104__LeetCode-Solutions | Python/sum-of-squares-of-special-elements.py | {
"start": 51,
"end": 447
} | class ____(object):
def sumOfSquares(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for i in xrange(1, int(len(nums)**0.5)+1):
if len(nums)%i:
continue
result += nums[i-1]**2
if len(nums)//i != i:
... | Solution |
python | rapidsai__cudf | python/cudf/cudf/core/udf/groupby_typing.py | {
"start": 6800,
"end": 8523
} | class ____(AbstractTemplate):
def make_error_string(self, args):
fname = self.key.split(".")[-1]
args = (self.this, *args)
dtype_err = ", ".join([str(g.group_scalar_type) for g in args])
sr_err = ", ".join(["Series" for _ in range(len(args) - 1)])
return (
f"Serie... | GroupAttrBase |
python | getsentry__sentry | src/sentry/models/group.py | {
"start": 10378,
"end": 21522
} | class ____(BaseManager["Group"]):
use_for_related_fields = True
def get_queryset(self):
return (
super()
.get_queryset()
.with_post_update_signal(options.get("groups.enable-post-update-signal"))
)
def by_qualified_short_id(self, organization_id: int, sho... | GroupManager |
python | django-import-export__django-import-export | tests/core/models.py | {
"start": 3885,
"end": 3976
} | class ____(models.Model):
role = models.ForeignKey(Role, on_delete=models.CASCADE)
| Person |
python | pytorch__pytorch | torch/distributed/_functional_collectives.py | {
"start": 23452,
"end": 32116
} | class ____(torch.Tensor):
r"""
A Tensor wrapper subclass that is used to trigger a call to wait
prior to first use of the underlying tensor.
Use it inside functional collective pytorch wrappers like the following:
def functional_collective(self, group, tag):
tag, rankset, group_size = _expan... | AsyncCollectiveTensor |
python | doocs__leetcode | lcof2/剑指 Offer II 038. 每日温度/Solution2.py | {
"start": 0,
"end": 391
} | class ____:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
stk = []
ans = [0] * n
for i in range(n - 1, -1, -1):
while stk and temperatures[stk[-1]] <= temperatures[i]:
stk.pop()
if stk:
... | Solution |
python | scrapy__scrapy | scrapy/spidermiddlewares/depth.py | {
"start": 660,
"end": 3153
} | class ____(BaseSpiderMiddleware):
crawler: Crawler
def __init__( # pylint: disable=super-init-not-called
self,
maxdepth: int,
stats: StatsCollector,
verbose_stats: bool = False,
prio: int = 1,
):
self.maxdepth = maxdepth
self.stats = stats
se... | DepthMiddleware |
python | matplotlib__matplotlib | tools/gh_api.py | {
"start": 402,
"end": 9526
} | class ____(dict):
"""Dictionary with attribute access to names."""
def __getattr__(self, name):
try:
return self[name]
except KeyError as err:
raise AttributeError(name) from err
def __setattr__(self, name, val):
self[name] = val
token = None
def get_auth_to... | Obj |
python | qdrant__qdrant-client | tests/congruence_tests/test_scroll.py | {
"start": 341,
"end": 2817
} | class ____:
@classmethod
def scroll_all(cls, client: QdrantBase) -> list[models.Record]:
all_records = []
records, next_page = client.scroll(
collection_name=COLLECTION_NAME,
limit=10,
with_payload=True,
)
all_records.extend(records)
... | TestSimpleScroller |
python | walkccc__LeetCode | solutions/1966. Binary Searchable Numbers in an Unsorted Array/1966.py | {
"start": 0,
"end": 600
} | class ____:
def binarySearchableNumbers(self, nums: list[int]) -> int:
n = len(nums)
# prefixMaxs[i] := max(nums[0..i))
prefixMaxs = [0] * n
# suffixMins[i] := min(nums[i + 1..n))
suffixMins = [0] * n
# Fill in `prefixMaxs`.
prefixMaxs[0] = -math.inf
for i in range(1, n):
prefix... | Solution |
python | python__mypy | mypy/dmypy/client.py | {
"start": 8774,
"end": 25061
} | class ____(Exception):
"""Exception raised when there is something wrong with the status file.
For example:
- No status file found
- Status file malformed
- Process whose pid is in the status file does not exist
"""
def main(argv: list[str]) -> None:
"""The code is top-down."""
check_... | BadStatus |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_bytes.py | {
"start": 299,
"end": 485
} | class ____:
def __bytes__(self):
print("ruff") # [invalid-bytes-return]
# TODO: Once Ruff has better type checking
def return_bytes():
return "some string"
| BytesNoReturn |
python | sympy__sympy | sympy/stats/matrix_distributions.py | {
"start": 5088,
"end": 7087
} | class ____:
"""Returns the sample from pymc of the given distribution"""
def __new__(cls, dist, size, seed=None):
return cls._sample_pymc(dist, size, seed)
@classmethod
def _sample_pymc(cls, dist, size, seed):
"""Sample from PyMC."""
try:
import pymc
except... | SampleMatrixPymc |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/regression.py | {
"start": 2829,
"end": 4271
} | class ____(Regression):
"""Linear model.
Parameters:
-----------
n_iterations: float
The number of training iterations the algorithm will tune the weights for.
learning_rate: float
The step length that will be used when updating the weights.
gradient_descent: boolean
True... | LinearRegression |
python | doocs__leetcode | solution/1200-1299/1249.Minimum Remove to Make Valid Parentheses/Solution.py | {
"start": 0,
"end": 581
} | class ____:
def minRemoveToMakeValid(self, s: str) -> str:
stk = []
x = 0
for c in s:
if c == ')' and x == 0:
continue
if c == '(':
x += 1
elif c == ')':
x -= 1
stk.append(c)
x = 0
... | Solution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/glue.py | {
"start": 7181,
"end": 8652
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger when a AWS Glue data quality evaluation run complete.
:param evaluation_run_id: The AWS Glue data quality ruleset evaluation run identifier.
:param waiter_delay: The amount of time in seconds to wait between attempts. (default: 60)
:param waiter_max_att... | GlueDataQualityRuleSetEvaluationRunCompleteTrigger |
python | django__django | tests/utils_tests/test_decorators.py | {
"start": 734,
"end": 1479
} | class ____:
def __init__(self, get_response):
self.get_response = get_response
def process_request(self, request):
request.process_request_reached = True
def process_view(self, request, view_func, view_args, view_kwargs):
request.process_view_reached = True
def process_templat... | FullMiddleware |
python | pypa__pip | src/pip/_vendor/pygments/lexer.py | {
"start": 1104,
"end": 1457
} | class ____(type):
"""
This metaclass automagically converts ``analyse_text`` methods into
static methods which always return float values.
"""
def __new__(mcs, name, bases, d):
if 'analyse_text' in d:
d['analyse_text'] = make_analysator(d['analyse_text'])
return type.__n... | LexerMeta |
python | mlflow__mlflow | mlflow/models/model.py | {
"start": 61006,
"end": 68196
} | class ____(NamedTuple):
requirements: Path
conda: Path
def get_model_requirements_files(resolved_uri: str) -> Files:
requirements_txt_file = _download_artifact_from_uri(
artifact_uri=append_to_uri_path(resolved_uri, _REQUIREMENTS_FILE_NAME)
)
conda_yaml_file = _download_artifact_from_uri(
... | Files |
python | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 2780,
"end": 3414
} | class ____(models.Model):
value_limit_field = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)])
length_limit_field = models.CharField(validators=[MinLengthValidator(3)], max_length=12)
blank_field = models.CharField(blank=True, max_length=10)
null_field = models.IntegerField(... | FieldOptionsModel |
python | spack__spack | lib/spack/spack/builder.py | {
"start": 9054,
"end": 9224
} | class ____(
spack.phase_callbacks.PhaseCallbacksMeta,
spack.multimethod.MultiMethodMeta,
type(collections.abc.Sequence), # type: ignore
):
pass
| BuilderMeta |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 2435,
"end": 3446
} | class ____(ActionBaseModel):
active: bool = Field(
default=True, description="Whether or not the schedule is active."
)
schedule: schemas.schedules.SCHEDULE_TYPES = Field(
default=..., description="The schedule for the deployment."
)
max_scheduled_runs: Optional[PositiveInteger] = Fi... | DeploymentScheduleCreate |
python | pyca__cryptography | tests/test_fernet.py | {
"start": 1042,
"end": 6071
} | class ____:
@json_parametrize(
("secret", "now", "iv", "src", "token"),
"generate.json",
)
def test_generate(self, secret, now, iv, src, token, backend):
f = Fernet(secret.encode("ascii"), backend=backend)
actual_token = f._encrypt_from_parts(
src.encode("ascii"),... | TestFernet |
python | spyder-ide__spyder | spyder/api/utils.py | {
"start": 1668,
"end": 1970
} | class ____(property):
"""
Decorator to declare class constants as properties that require additional
computation.
Taken from: https://stackoverflow.com/a/7864317/438386
"""
def __get__(self, cls, owner):
return classmethod(self.fget).__get__(None, owner)()
| classproperty |
python | huggingface__transformers | src/transformers/models/siglip2/modular_siglip2.py | {
"start": 4912,
"end": 4975
} | class ____(SiglipVisionModelOutput):
pass
| Siglip2VisionOutput |
python | django__django | tests/admin_widgets/tests.py | {
"start": 26401,
"end": 32208
} | class ____(TestCase):
def test_render(self):
band = Band.objects.create(name="Linkin Park")
band.album_set.create(
name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg"
)
rel_uuid = Album._meta.get_field("band").remote_field
w = widgets.ForeignKeyRawIdWidget... | ForeignKeyRawIdWidgetTest |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/panels/sql/tracking.py | {
"start": 4195,
"end": 10129
} | class ____(DjDTCursorWrapperMixin):
"""
Wraps a cursor and logs queries.
"""
def _decode(self, param):
if PostgresJson and isinstance(param, PostgresJson):
# psycopg3
if hasattr(param, "obj"):
return param.dumps(param.obj)
# psycopg2
... | NormalCursorMixin |
python | pytorch__pytorch | torch/_inductor/scheduler.py | {
"start": 51617,
"end": 51866
} | class ____(BaseSchedulerNode):
def __init__(self, scheduler: Scheduler, node: ir.Operation) -> None:
super().__init__(scheduler)
self._init_from_node(node)
self.set_read_writes(node.get_read_writes())
| NopKernelSchedulerNode |
python | django__django | tests/auth_tests/urls_custom_user_admin.py | {
"start": 209,
"end": 680
} | class ____(UserAdmin):
def log_change(self, request, obj, message):
# LogEntry.user column doesn't get altered to expect a UUID, so set an
# integer manually to avoid causing an error.
original_pk = request.user.pk
request.user.pk = 1
super().log_change(request, obj, message)... | CustomUserAdmin |
python | mlflow__mlflow | mlflow/store/tracking/dbmodels/models.py | {
"start": 27421,
"end": 34746
} | class ____(Base):
__tablename__ = "assessments"
assessment_id = Column(String(50), nullable=False)
"""
Assessment ID: `String` (limit 50 characters). *Primary Key* for ``assessments`` table.
"""
trace_id = Column(
String(50), ForeignKey("trace_info.request_id", ondelete="CASCADE"), null... | SqlAssessments |
python | openai__openai-python | src/openai/types/realtime/response_output_item_done_event.py | {
"start": 252,
"end": 717
} | class ____(BaseModel):
event_id: str
"""The unique ID of the server event."""
item: ConversationItem
"""A single item within a Realtime conversation."""
output_index: int
"""The index of the output item in the Response."""
response_id: str
"""The ID of the Response to which the item b... | ResponseOutputItemDoneEvent |
python | getsentry__sentry | src/sentry/api/authentication.py | {
"start": 24050,
"end": 26688
} | class ____(StandardAuthentication):
"""
Authentication for cross-region RPC requests.
Requests are sent with an HMAC signed by a shared private key.
"""
token_name = b"rpcsignature"
def accepts_auth(self, auth: list[bytes]) -> bool:
if not auth or len(auth) < 2:
return Fals... | RpcSignatureAuthentication |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 1037431,
"end": 1047304
} | class ____(DatumChannelMixin, core.ScaleDatumDef):
"""
XOffsetDatum schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to... | XOffsetDatum |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table31.py | {
"start": 315,
"end": 1358
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table31.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | pikepdf__pikepdf | src/pikepdf/objects.py | {
"start": 5140,
"end": 5883
} | class ____(Object, metaclass=_ObjectMeta):
"""Construct an operator for use in a content stream.
An Operator is one of a limited set of commands that can appear in PDF content
streams (roughly the mini-language that draws objects, lines and text on a
virtual PDF canvas). The commands :func:`parse_conte... | Operator |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/multiple_models/tutorial001_py39.py | {
"start": 433,
"end": 1358
} | class ____(SQLModel):
id: int
name: str
secret_name: str
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
def create_db_and_tab... | HeroPublic |
python | run-llama__llama_index | llama-index-core/llama_index/core/query_engine/citation_query_engine.py | {
"start": 3177,
"end": 12998
} | class ____(BaseQueryEngine):
"""
Citation query engine.
Args:
retriever (BaseRetriever): A retriever object.
response_synthesizer (Optional[BaseSynthesizer]):
A BaseSynthesizer object.
citation_chunk_size (int):
Size of citation chunks, default=512. Useful fo... | CitationQueryEngine |
python | getsentry__sentry | src/sentry/integrations/msteams/card_builder/block.py | {
"start": 2535,
"end": 2661
} | class ____(_ColumnBlockNotRequired):
type: Literal["Column"]
items: list[Block]
width: ColumnWidth | str
| ColumnBlock |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_emr_serverless_job.py | {
"start": 2448,
"end": 3150
} | class ____(TestEmrServerlessJobSensor):
@pytest.mark.parametrize("state", ["FAILED", "CANCELLING", "CANCELLED"])
def test_poke_raises_airflow_exception_with_specified_states(self, state):
state_details = f"mock {state}"
exception_msg = f"EMR Serverless job failed: {state_details}"
get_jo... | TestPokeRaisesAirflowException |
python | plotly__plotly.py | plotly/io/_base_renderers.py | {
"start": 12232,
"end": 13031
} | class ____(HtmlRenderer):
"""
Renderer to display interactive figures in Azure Notebooks.
Same as NotebookRenderer but with connected=True so that the plotly.js
bundle is loaded from a CDN rather than being embedded in the notebook.
This renderer is enabled by default when running in an Azure note... | AzureRenderer |
python | python__mypy | mypyc/analysis/attrdefined.py | {
"start": 10724,
"end": 12417
} | class ____(BaseAnalysisVisitor[str]):
"""Find attributes that may have been defined via some code path.
Consider initializations in class body and assignments to 'self.x'
and calls to base class '__init__'.
"""
def __init__(self, self_reg: Register) -> None:
self.self_reg = self_reg
d... | AttributeMaybeDefinedVisitor |
python | realpython__materials | python-guitar-synthesizer/source_code_step_1/src/digitar/temporal.py | {
"start": 217,
"end": 1032
} | class ____:
seconds: Decimal
@classmethod
def from_milliseconds(cls, milliseconds: Numeric) -> Self:
return cls(Decimal(str(float(milliseconds))) / 1000)
def __init__(self, seconds: Numeric) -> None:
match seconds:
case int() | float():
object.__setattr__(se... | Time |
python | getsentry__sentry | tests/sentry/apidocs/test_extensions.py | {
"start": 931,
"end": 1130
} | class ____(Serializer):
def serialize(
self, obj: Any, attrs: Mapping[Any, Any], user: Any, **kwargs: Any
) -> BasicSerializerResponse:
raise NotImplementedError
| BasicSerializer |
python | numba__numba | numba/tests/npyufunc/test_gufunc.py | {
"start": 14786,
"end": 18511
} | class ____(MemoryLeakMixin, TestCase):
def test_pickle_gufunc_non_dyanmic(self):
"""Non-dynamic gufunc.
"""
@guvectorize(["f8,f8[:]"], "()->()")
def double(x, out):
out[:] = x * 2
# pickle
ser = pickle.dumps(double)
cloned = pickle.loads(ser)
... | TestGUVectorizePickling |
python | pyodide__pyodide | src/py/_pyodide/_core_docs.py | {
"start": 14889,
"end": 15300
} | class ____(JsProxy, Generic[T]):
"""A double proxy created with :py:func:`create_proxy`."""
_js_type_flags = ["IS_DOUBLE_PROXY"]
def destroy(self) -> None:
"""Destroy the proxy."""
pass
def unwrap(self) -> T:
"""Unwrap a double proxy created with :py:func:`create_proxy` into t... | JsDoubleProxy |
python | mlflow__mlflow | tests/pytorch/iris_data_module.py | {
"start": 154,
"end": 1040
} | class ____(pl.LightningDataModule):
def __init__(self):
super().__init__()
self.columns = None
def _get_iris_as_tensor_dataset(self):
iris = load_iris()
df = iris.data
self.columns = iris.feature_names
target = iris["target"]
data = torch.Tensor(df).float... | IrisDataModuleBase |
python | mkdocs__mkdocs | mkdocs/tests/structure/file_tests.py | {
"start": 223,
"end": 34458
} | class ____(PathAssertionMixin, unittest.TestCase):
@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
def test_src_path_windows(self):
f = File('foo\\a.md', '/path/to/docs', '/path/to/site', use_directory_urls=False)
self.assertEqual(f.src_uri, 'foo/a.md')
self.asse... | TestFiles |
python | huggingface__transformers | src/transformers/models/encodec/feature_extraction_encodec.py | {
"start": 953,
"end": 9877
} | class ____(SequenceFeatureExtractor):
r"""
Constructs an EnCodec feature extractor.
This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
most of the main methods. Users should refer to this superclass for more information regarding those me... | EncodecFeatureExtractor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.