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 | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 713505,
"end": 714161
} | class ____(sgqlc.types.Type, Node, UniformResourceLocatable):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "closable", "closer", "created_at", "state_reason")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
closable = sgqlc.types.Fiel... | ClosedEvent |
python | walkccc__LeetCode | solutions/785. Is Graph Bipartite?/785-2.py | {
"start": 24,
"end": 79
} | class ____(Enum):
WHITE = 0
RED = 1
GREEN = 2
| Color |
python | huggingface__transformers | src/transformers/models/bart/modeling_bart.py | {
"start": 18676,
"end": 19481
} | class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(
self,
input_dim: int,
inner_dim: int,
num_classes: int,
pooler_dropout: float,
):
super().__init__()
self.dense = nn.Linear(input_dim, inner_dim)
self.dro... | BartClassificationHead |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_twodim_base.py | {
"start": 17543,
"end": 18692
} | class ____(TestCase):
def test_basic(self):
c = np.array([0, 1, -2, 3])
v = vander(c)
powers = np.array(
[[0, 0, 0, 0, 1], [1, 1, 1, 1, 1], [16, -8, 4, -2, 1], [81, 27, 9, 3, 1]]
)
# Check default value of N:
assert_array_equal(v, powers[:, 1:])
# ... | TestVander |
python | ray-project__ray | release/llm_tests/serve/benchmark/benchmark_vllm.py | {
"start": 972,
"end": 8683
} | class ____:
HEADER = "\033[95m"
SERVER = "\033[94m"
CLIENT = "\033[92m"
WARNING = "\033[93m"
ERROR = "\033[91m"
ENDC = "\033[0m"
@staticmethod
def log_server(msg):
print(
f"{ColoredLogger.SERVER}[SERVER {get_timestamp()}] {msg}{ColoredLogger.ENDC}"
)
@st... | ColoredLogger |
python | astropy__astropy | astropy/coordinates/builtin_frames/ecliptic.py | {
"start": 5852,
"end": 6978
} | class ____(BaseEclipticFrame):
"""
Barycentric true ecliptic coordinates. These origin of the coordinates are the
barycenter of the solar system, with the x axis pointing in the direction of
the *true* (not mean) equinox as at the time specified by the ``equinox``
attribute (as seen from Earth), an... | BarycentricTrueEcliptic |
python | getsentry__sentry | src/sentry/api/serializers/models/groupsearchview.py | {
"start": 893,
"end": 3251
} | class ____(Serializer):
def __init__(self, *args, **kwargs):
self.organization = kwargs.pop("organization", None)
super().__init__(*args, **kwargs)
def get_attrs(self, item_list, user, **kwargs) -> MutableMapping[Any, Any]:
attrs: MutableMapping[Any, Any] = {}
last_visited_view... | GroupSearchViewSerializer |
python | PrefectHQ__prefect | src/prefect/server/utilities/schemas/bases.py | {
"start": 1871,
"end": 7151
} | class ____(BaseModel):
"""A base pydantic.BaseModel for all Prefect schemas and pydantic models.
As the basis for most Prefect schemas, this base model ignores extra
fields that are passed to it at instantiation. Because adding new fields to
API payloads is not considered a breaking change, this ensure... | PrefectBaseModel |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_write_filter_column.py | {
"start": 301,
"end": 880
} | class ____(unittest.TestCase):
"""
Test the Worksheet _write_filter_column() method.
"""
def setUp(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
def test_write_filter_column(self):
"""Test the _write_filter_column(... | TestWriteFilterColumn |
python | huggingface__transformers | tests/models/vivit/test_modeling_vivit.py | {
"start": 12561,
"end": 14852
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return VivitImageProcessor() if is_vision_available() else None
@slow
def test_inference_for_video_classification(self):
model = VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics40... | VivitModelIntegrationTest |
python | wandb__wandb | tests/unit_tests/test_launch/test_runner/test_vertex.py | {
"start": 301,
"end": 7313
} | class ____:
"""Mock of the CustomJob class from the Vertex SDK.
This is used to test the VertexSubmittedRun class which uses that object
to poll on the status of the job.
"""
def __init__(self, statuses: List[str]):
self.statuses = statuses
self.status_index = 0
@property
... | MockCustomJob |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/router/base.py | {
"start": 1657,
"end": 4777
} | class ____(Chain):
"""Use a single chain to route an input to one of multiple candidate chains."""
router_chain: RouterChain
"""Chain that routes inputs to destination chains."""
destination_chains: Mapping[str, Chain]
"""Chains that return final answer to inputs."""
default_chain: Chain
""... | MultiRouteChain |
python | ray-project__ray | python/ray/train/v2/_internal/metrics/controller.py | {
"start": 247,
"end": 2360
} | class ____:
"""Factory for creating controller-specific metrics.
This class defines all metrics used to track the state and performance of the
training controller. Each metric is defined with its name, type, default value,
description, and required tags.
"""
# ===== Metric Names =====
CONT... | ControllerMetrics |
python | python-markdown__markdown | markdown/blockprocessors.py | {
"start": 25505,
"end": 27013
} | class ____(BlockProcessor):
""" Process Paragraph blocks. """
def test(self, parent: etree.Element, block: str) -> bool:
return True
def run(self, parent: etree.Element, blocks: list[str]) -> None:
block = blocks.pop(0)
if block.strip():
# Not a blank block. Add to pare... | ParagraphProcessor |
python | graphql-python__graphene | examples/context_example.py | {
"start": 18,
"end": 105
} | class ____(graphene.ObjectType):
id = graphene.ID()
name = graphene.String()
| User |
python | tensorflow__tensorflow | tensorflow/python/ops/weak_tensor_math_ops_test.py | {
"start": 11124,
"end": 11581
} | class ____(test_util.TensorFlowTestCase):
def testRounding(self):
x = np.arange(-5.0, 5.0, .25)
for dtype in [np.float32, np.double, np.int32]:
x_np = np.array(x, dtype=dtype)
with test_util.device(use_gpu=True):
x_tf = _get_weak_tensor(x_np, shape=x_np.shape)
y_tf = math_ops.roun... | RoundTest |
python | huggingface__transformers | src/transformers/models/omdet_turbo/processing_omdet_turbo.py | {
"start": 2104,
"end": 7725
} | class ____(dict):
message = (
"The `classes` key is deprecated for `OmDetTurboProcessor.post_process_grounded_object_detection` "
"output dict and will be removed in a 4.51.0 version. Please use `text_labels` instead."
)
def __getitem__(self, key):
if key == "classes":
w... | DictWithDeprecationWarning |
python | readthedocs__readthedocs.org | readthedocs/organizations/views/private.py | {
"start": 6445,
"end": 6618
} | class ____(PrivateViewMixin, OrganizationTeamView, UpdateView):
template_name = "organizations/team_edit.html"
success_message = _("Team updated")
| EditOrganizationTeam |
python | pypa__warehouse | tests/unit/oidc/models/test_gitlab.py | {
"start": 35837,
"end": 38170
} | class ____:
def test_reify_does_not_exist_yet(self, db_request):
pending_publisher = PendingGitLabPublisherFactory.create()
assert (
db_request.db.query(gitlab.GitLabPublisher)
.filter_by(
project=pending_publisher.project,
namespace=pending_pu... | TestPendingGitLabPublisher |
python | huggingface__transformers | src/transformers/models/tvp/modeling_tvp.py | {
"start": 35041,
"end": 37920
} | class ____(TvpPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.model = TvpModel(config)
self.video_grounding_head = TvpVideoGroundingHead(config)
self.post_init()
@auto_docstring
def forward(
self,
inpu... | TvpForVideoGrounding |
python | etianen__django-reversion | reversion/admin.py | {
"start": 1108,
"end": 1218
} | class ____(Exception):
def __init__(self, response):
self.response = response
| _RollBackRevisionView |
python | kubernetes-client__python | kubernetes/client/models/v2_external_metric_status.py | {
"start": 383,
"end": 4471
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V2ExternalMetricStatus |
python | ray-project__ray | release/release_logs/fetch_release_logs.py | {
"start": 1990,
"end": 2067
} | class ____:
build: Build
id: str
name: Optional[str]
@dataclass
| Job |
python | numpy__numpy | benchmarks/benchmarks/bench_reduce.py | {
"start": 1063,
"end": 1725
} | class ____(Benchmark):
params = ['int64', 'uint64', 'float32', 'float64', 'complex64', 'bool_'],
param_names = ['dtype']
def setup(self, dtype):
self.data = np.ones(200, dtype=dtype)
if dtype.startswith('complex'):
self.data = self.data * self.data.T * 1j
def time_min(self,... | StatsReductions |
python | PyCQA__pylint | tests/functional/r/regression_02/regression_8109.py | {
"start": 191,
"end": 393
} | class ____:
amount: int | float
round: int = 2
def __str__(self):
number_format = "{:,.%sf}" % self.round
return number_format.format(self.amount).rstrip("0").rstrip(".")
| Number |
python | getsentry__sentry | src/sentry/migrations/1009_add_date_updated_to_organizationmapping.py | {
"start": 249,
"end": 2082
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | kamyu104__LeetCode-Solutions | Python/max-sum-of-sub-matrix-no-larger-than-k.py | {
"start": 1234,
"end": 3314
} | class ____(object):
def maxSumSubmatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
class BST(object): # not avl, rbtree
def __init__(self, val):
self.val = val
self.left = None
... | Solution_TLE |
python | kamyu104__LeetCode-Solutions | Python/longest-common-prefix.py | {
"start": 527,
"end": 897
} | class ____(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix = ""
for chars in zip(*strs):
if all(c == chars[0] for c in chars):
prefix += chars[0]
else:
retu... | Solution2 |
python | great-expectations__great_expectations | great_expectations/profile/base.py | {
"start": 2466,
"end": 2707
} | class ____(Enum):
"""Useful data types for building profilers."""
INT = "int"
FLOAT = "float"
NUMERIC = "numeric"
STRING = "string"
BOOLEAN = "boolean"
DATETIME = "datetime"
UNKNOWN = "unknown"
| ProfilerDataType |
python | encode__django-rest-framework | rest_framework/test.py | {
"start": 9450,
"end": 10012
} | class ____(ClientHandler):
"""
A patched version of ClientHandler that can enforce authentication
on the outgoing requests.
"""
def __init__(self, *args, **kwargs):
self._force_user = None
self._force_token = None
super().__init__(*args, **kwargs)
def get_response(self,... | ForceAuthClientHandler |
python | streamlit__streamlit | lib/tests/streamlit/web/cli_test.py | {
"start": 1396,
"end": 26394
} | class ____(unittest.TestCase):
"""Unit tests for the cli."""
def setUp(self):
# Credentials._singleton should be None here, but a mis-behaving
# test may have left it intact.
Credentials._singleton = None
cli.name = "streamlit"
self.runner = CliRunner()
self.pa... | CliTest |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 7233,
"end": 7799
} | class ____(LTComponent):
def __init__(self, bbox):
LTComponent.__init__(self, bbox)
self._objs = []
return
def __iter__(self):
return iter(self._objs)
def __len__(self):
return len(self._objs)
def add(self, obj):
self._objs.append(obj)
return
... | LTContainer |
python | tornadoweb__tornado | tornado/test/options_test.py | {
"start": 278,
"end": 516
} | class ____:
def __init__(self, value):
if isinstance(value, str) and "@" in value:
self._value = value
else:
raise ValueError()
@property
def value(self):
return self._value
| Email |
python | apache__airflow | providers/databricks/tests/unit/databricks/hooks/test_databricks_azure_workload_identity_async.py | {
"start": 1696,
"end": 3179
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=DEFAULT_CONN_ID,
conn_type="databricks",
host=HOST,
extra=json.dumps(
... | TestDatabricksHookAadTokenWorkloadIdentityAsync |
python | joke2k__faker | faker/providers/color/de_AT/__init__.py | {
"start": 44,
"end": 83
} | class ____(BaseProvider):
pass
| Provider |
python | conda__conda | conda/common/configuration.py | {
"start": 4239,
"end": 4653
} | class ____(ValidationError):
def __init__(self, parameter_name, parameter_value, source, custom_message):
super().__init__(
parameter_name,
parameter_value,
source,
msg=(
f"Parameter {parameter_name} = {parameter_value!r} declared in "
... | CustomValidationError |
python | google__jax | jax/_src/source_info_util.py | {
"start": 6784,
"end": 7187
} | class ____(Exception): pass
_message = (
'The preceding stack trace is the source of the JAX operation that, once '
'transformed by JAX, triggered the following exception.\n'
'\n--------------------')
def has_user_context(e):
while e is not None:
if isinstance(e, JaxStackTraceBeforeTransformation):
... | JaxStackTraceBeforeTransformation |
python | more-itertools__more-itertools | tests/test_recipes.py | {
"start": 22982,
"end": 24793
} | class ____(TestCase):
def test_r_less_than_n(self):
iterable = 'abcde'
r = 4
for index, expected in enumerate(permutations(iterable, r)):
actual = mi.nth_permutation(iterable, r, index)
self.assertEqual(actual, expected)
def test_r_equal_to_n(self):
itera... | NthPermutationTests |
python | jina-ai__jina | tests/unit/serve/executors/metas_executors.py | {
"start": 53,
"end": 171
} | class ____(Executor):
@requests
def process(self, docs: DocumentArray, **kwargs):
return docs
| TestExecutor |
python | pydata__xarray | asv_bench/benchmarks/rolling.py | {
"start": 4352,
"end": 5133
} | class ____(RollingMemory):
@parameterized(["func", "use_bottleneck"], (["sum", "max", "mean"], [True, False]))
def peakmem_ndrolling_reduce(self, func, use_bottleneck):
with xr.set_options(use_bottleneck=use_bottleneck):
roll = self.ds.rolling(x=10, y=4)
getattr(roll, func)()
... | DatasetRollingMemory |
python | sympy__sympy | sympy/printing/cxx.py | {
"start": 5524,
"end": 6123
} | class ____(_CXXCodePrinterBase, C99CodePrinter):
standard = 'C++17'
reserved_words = set(reserved['C++17'])
_kf = dict(C99CodePrinter._kf, **_math_functions['C++17'])
def _print_beta(self, expr):
return self._print_math_func(expr)
def _print_Ei(self, expr):
return self._print_math... | CXX17CodePrinter |
python | plotly__plotly.py | plotly/graph_objs/funnelarea/_marker.py | {
"start": 233,
"end": 4749
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "funnelarea"
_path_str = "funnelarea.marker"
_valid_props = {"colors", "colorssrc", "line", "pattern"}
@property
def colors(self):
"""
Sets the color of each sector. If not specified, the default
trace color set is used... | Marker |
python | networkx__networkx | networkx/generators/tests/test_nonisomorphic_trees.py | {
"start": 1075,
"end": 2945
} | class ____:
def test_tree_structure(self):
# test for tree structure for nx.nonisomorphic_trees()
def f(x):
return list(nx.nonisomorphic_trees(x))
for i in f(6):
assert nx.is_tree(i)
for i in f(8):
assert nx.is_tree(i)
def test_nonisomorphism... | TestGeneratorNonIsomorphicTrees |
python | django__django | tests/staticfiles_tests/test_storage.py | {
"start": 28510,
"end": 31087
} | class ____(CollectionTestCase):
hashed_file_path = hashed_file_path
def test_module_import(self):
relpath = self.hashed_file_path("cached/module.js")
self.assertEqual(relpath, "cached/module.4326210cf0bd.js")
tests = [
# Relative imports.
b'import testConst from ... | TestCollectionJSModuleImportAggregationManifestStorage |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 8102,
"end": 8540
} | class ____(_Permission[AliasAction]):
alias: str
collection: str
def _to_weaviate(self) -> List[WeaviatePermission]:
return [
{
"action": action,
"aliases": {
"alias": _capitalize_first_letter(self.alias),
"collecti... | _AliasPermission |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/return_statements.py | {
"start": 5964,
"end": 13067
} | class ____(converter.Base):
"""Lowers return statements into variables and conditionals.
Specifically, the following pattern:
<block 1>
return val
<block 2>
is converted to:
do_return = False
retval = None
<block 1>
do_return = True
retval = val
if not ... | ReturnStatementsTransformer |
python | readthedocs__readthedocs.org | readthedocs/search/models.py | {
"start": 501,
"end": 3031
} | class ____(TimeStampedModel):
"""Information about the search queries."""
project = models.ForeignKey(
Project,
related_name="search_queries",
on_delete=models.CASCADE,
)
version = models.ForeignKey(
Version,
verbose_name=_("Version"),
related_name="searc... | SearchQuery |
python | mlflow__mlflow | dev/set_matrix.py | {
"start": 1348,
"end": 2169
} | class ____(OriginalVersion):
def __init__(self, version: str, release_date: datetime | None = None):
self._is_dev = version == DEV_VERSION
self._release_date = release_date
super().__init__(DEV_NUMERIC if self._is_dev else version)
def __str__(self):
return DEV_VERSION if self._... | Version |
python | python-poetry__poetry | src/poetry/utils/env/generic_env.py | {
"start": 348,
"end": 3162
} | class ____(VirtualEnv):
def __init__(
self, path: Path, base: Path | None = None, child_env: Env | None = None
) -> None:
self._child_env = child_env
super().__init__(path, base=base)
def find_executables(self) -> None:
patterns = [("python*", "pip*")]
if self._chi... | GenericEnv |
python | pytest-dev__pytest | testing/test_junitxml.py | {
"start": 5936,
"end": 35630
} | class ____:
@parametrize_families
def test_summing_simple(
self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str
) -> None:
pytester.makepyfile(
"""
import pytest
def test_pass():
pass
def test_fail():
... | TestPython |
python | django__django | tests/model_forms/test_uuid.py | {
"start": 242,
"end": 1501
} | class ____(TestCase):
def test_create_save_error(self):
form = UUIDPKForm({})
self.assertFalse(form.is_valid())
msg = "The UUIDPK could not be created because the data didn't validate."
with self.assertRaisesMessage(ValueError, msg):
form.save()
def test_update_save_... | ModelFormBaseTest |
python | mlflow__mlflow | mlflow/store/model_registry/dbmodels/models.py | {
"start": 5738,
"end": 6631
} | class ____(Base):
__tablename__ = "registered_model_aliases"
name = Column(
String(256),
ForeignKey(
"registered_models.name",
onupdate="cascade",
ondelete="cascade",
name="registered_model_alias_name_fkey",
),
)
alias = Column(Stri... | SqlRegisteredModelAlias |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/tests/test_new_features.py | {
"start": 6429,
"end": 10970
} | class ____:
"""Test event system functionality."""
def test_event_system_subscription_and_notification(self):
"""Test that event system can handle event subscriptions and notifications."""
reader = ConfluenceReader(
base_url="https://example.atlassian.net/wiki", api_token="test_toke... | TestEventSystem |
python | getsentry__sentry | tests/sentry/workflow_engine/test_task.py | {
"start": 4950,
"end": 16158
} | class ____(TestCase):
def setUp(self) -> None:
self.group = self.create_group(project=self.project, type=MetricIssue.type_id)
self.activity = Activity(
project=self.project,
group=self.group,
type=ActivityType.SET_RESOLVED.value,
data={"fingerprint": [... | TestProcessWorkflowActivity |
python | fastapi__sqlmodel | docs_src/tutorial/many_to_many/tutorial001.py | {
"start": 608,
"end": 2434
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
teams: List[Team] = Relationship(back_populates="heroes", link_model=HeroTeamLink)
sqlite_file_name = "da... | Hero |
python | scipy__scipy | scipy/linalg/tests/test_fblas.py | {
"start": 16371,
"end": 16443
} | class ____(BaseGer):
blas_func = fblas.sger
dtype = float32
| TestSger |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 26997,
"end": 28402
} | class ____(MeanMetricWrapper):
"""Calculates how often predictions match binary labels.
This metric creates two local variables, `total` and `count` that are used to
compute the frequency with which `y_pred` matches `y_true`. This frequency is
ultimately returned as `binary accuracy`: an idempotent operation t... | BinaryAccuracy |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/links/test_batch.py | {
"start": 2977,
"end": 3858
} | class ____(BaseAwsLinksTestCase):
link_class = BatchJobQueueLink
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={
... | TestBatchJobQueueLink |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/anno.py | {
"start": 1003,
"end": 1347
} | class ____(enum.Enum):
"""Base class for different types of AST annotations."""
def of(self, node, default=None):
return getanno(node, self, default=default)
def add_to(self, node, value):
setanno(node, self, value)
def exists(self, node):
return hasanno(node, self)
def __repr__(self):
ret... | NoValue |
python | pytorch__pytorch | torchgen/local.py | {
"start": 768,
"end": 2167
} | class ____(threading.local):
use_const_ref_for_mutable_tensors: bool | None = None
use_ilistref_for_tensor_lists: bool | None = None
_locals = Locals()
def use_const_ref_for_mutable_tensors() -> bool:
assert _locals.use_const_ref_for_mutable_tensors is not None, (
"need to initialize local.use_c... | Locals |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 11717,
"end": 11926
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
uri: str
def document_uri(self) -> DocumentUri:
return DocumentUri.parse(self.uri)
@dataclasses.dataclass(frozen=True)
| TextDocumentIdentifier |
python | Lightning-AI__lightning | src/lightning/pytorch/strategies/parallel.py | {
"start": 1163,
"end": 5093
} | class ____(Strategy, ABC):
"""Strategy for training with multiple processes in parallel."""
def __init__(
self,
accelerator: Optional["pl.accelerators.Accelerator"] = None,
parallel_devices: Optional[list[torch.device]] = None,
cluster_environment: Optional[ClusterEnvironment] =... | ParallelStrategy |
python | doocs__leetcode | solution/1700-1799/1756.Design Most Recently Used Queue/Solution2.py | {
"start": 362,
"end": 937
} | class ____:
def __init__(self, n: int):
self.q = list(range(n + 1))
self.tree = BinaryIndexedTree(n + 2010)
def fetch(self, k: int) -> int:
l, r = 1, len(self.q)
while l < r:
mid = (l + r) >> 1
if mid - self.tree.query(mid) >= k:
r = mid
... | MRUQueue |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 13667,
"end": 13973
} | class ____(PydanticTypeError):
code = 'arbitrary_type'
msg_template = 'instance of {expected_arbitrary_type} expected'
def __init__(self, *, expected_arbitrary_type: Type[Any]) -> None:
super().__init__(expected_arbitrary_type=display_as_type(expected_arbitrary_type))
| ArbitraryTypeError |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_returned.py | {
"start": 685,
"end": 840
} | class ____:
""" __getnewargs__ returns an integer """
def __getnewargs__(self): # [invalid-getnewargs-returned]
return 1
| FirstBadGetNewArgs |
python | django__django | tests/model_fields/models.py | {
"start": 5236,
"end": 6681
} | class ____(models.Model):
id = models.AutoField("verbose pk", primary_key=True)
field1 = models.BigIntegerField("verbose field1")
field2 = models.BooleanField("verbose field2", default=False)
field3 = models.CharField("verbose field3", max_length=10)
field4 = models.DateField("verbose field4")
f... | VerboseNameField |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 23406,
"end": 23588
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("DONE", "IN_PROGRESS", "TODO")
| ProjectColumnPurpose |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_project_forms.py | {
"start": 36531,
"end": 39400
} | class ____(TestCase):
def setUp(self):
self.project = get(Project)
def test_webhookform(self):
self.assertEqual(self.project.webhook_notifications.all().count(), 0)
data = {
"url": "http://www.example.com/",
"payload": "{}",
"events": [WebHookEvent.o... | TestWebhookForm |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-gemini-live/llama_index/voice_agents/gemini_live/events.py | {
"start": 93,
"end": 154
} | class ____(BaseVoiceAgentEvent):
data: bytes
| AudioSentEvent |
python | jazzband__django-model-utils | tests/models.py | {
"start": 12725,
"end": 13046
} | class ____(models.Model):
custom_field = CustomDescriptorField()
tracked_custom_field = CustomDescriptorField()
regular_field = models.IntegerField()
tracked_regular_field = models.IntegerField()
tracker = FieldTracker(fields=['tracked_custom_field', 'tracked_regular_field'])
| ModelWithCustomDescriptor |
python | allegroai__clearml | clearml/backend_api/services/v2_9/models.py | {
"start": 38180,
"end": 40031
} | class ____(Response):
"""
Response of models.edit endpoint.
:param updated: Number of models updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "models"
_action = "edit"
_version = "2.9"
_schema = {
"... | EditResponse |
python | huggingface__transformers | src/transformers/models/afmoe/modular_afmoe.py | {
"start": 1740,
"end": 1780
} | class ____(Qwen2MoeMLP):
pass
| AfmoeMLP |
python | Textualize__textual | docs/examples/how-to/center02.py | {
"start": 80,
"end": 440
} | class ____(App):
"""How to center things."""
CSS = """
Screen {
align: center middle;
}
#hello {
background: blue 50%;
border: wide white;
}
"""
def compose(self) -> ComposeResult:
yield Static("Hello, World!", id="hello")
if __name__ == "__main__":
... | CenterApp |
python | django__django | tests/select_related/models.py | {
"start": 1879,
"end": 1999
} | class ____(models.Model):
name = models.CharField(max_length=100)
toppings = models.ManyToManyField(Topping)
| Pizza |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/configurable.py | {
"start": 1040,
"end": 9832
} | class ____(RunnableSerializable[Input, Output]):
"""Serializable `Runnable` that can be dynamically configured.
A `DynamicRunnable` should be initiated using the `configurable_fields` or
`configurable_alternatives` method of a `Runnable`.
"""
default: RunnableSerializable[Input, Output]
"""The... | DynamicRunnable |
python | getsentry__sentry | tests/sentry/incidents/endpoints/test_organization_alert_rule_details.py | {
"start": 8438,
"end": 29370
} | class ____(AlertRuleDetailsBase):
def test_simple(self) -> None:
self.create_team(organization=self.organization, members=[self.user])
self.login_as(self.user)
with self.feature("organizations:incidents"):
resp = self.get_success_response(self.organization.slug, self.alert_rule.i... | AlertRuleDetailsGetEndpointTest |
python | huggingface__transformers | src/transformers/models/rag/modeling_rag.py | {
"start": 15762,
"end": 22328
} | class ____(PreTrainedModel):
config: RagConfig
base_model_prefix = "rag"
_supports_flash_attn = True
_supports_sdpa = True
@classmethod
def from_pretrained_question_encoder_generator(
cls,
question_encoder_pretrained_model_name_or_path: Optional[str] = None,
generator_pr... | RagPreTrainedModel |
python | walkccc__LeetCode | solutions/2179. Count Good Triplets in an Array/2179.py | {
"start": 421,
"end": 1374
} | class ____:
def goodTriplets(self, nums1: list[int], nums2: list[int]) -> int:
n = len(nums1)
numToIndex = {num: i for i, num in enumerate(nums1)}
# Remap each number in `nums2` to the according index in `nums1` as `arr`.
# So the problem is to find the number of increasing tripets in `arr`.
arr =... | Solution |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax.py | {
"start": 1662,
"end": 1746
} | class ____:
my_var: int | str
@my_decorator
@dataclasses.dataclass
| CustomDataClass3 |
python | keras-team__keras | keras/src/layers/preprocessing/feature_space.py | {
"start": 2498,
"end": 30082
} | class ____(Layer):
"""One-stop utility for preprocessing and encoding structured data.
Arguments:
feature_names: Dict mapping the names of your features to their
type specification, e.g. `{"my_feature": "integer_categorical"}`
or `{"my_feature": FeatureSpace.integer_categorical(... | FeatureSpace |
python | wandb__wandb | wandb/sdk/artifacts/_generated/artifact_collection_membership_file_urls.py | {
"start": 1243,
"end": 1533
} | class ____(
GQLResult
):
page_info: PageInfoFragment = Field(alias="pageInfo")
edges: List[
ArtifactCollectionMembershipFileUrlsProjectArtifactCollectionArtifactMembershipFilesEdges
]
| ArtifactCollectionMembershipFileUrlsProjectArtifactCollectionArtifactMembershipFiles |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0116_mark_fields_as_null.py | {
"start": 150,
"end": 7982
} | class ____(migrations.Migration):
safe = Safe.before_deploy()
dependencies = [
("projects", "0115_add_addonsconfig_history"),
]
operations = [
migrations.AlterField(
model_name="historicalproject",
name="conf_py_file",
field=models.CharField(
... | Migration |
python | kamyu104__LeetCode-Solutions | Python/sum-of-all-subset-xor-totals.py | {
"start": 29,
"end": 506
} | class ____(object):
def subsetXORSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# given there are k (k >= 1) nums of which ith bit is 1,
# the bit contributes to sum is:
# (nCr(k, 1) + nCr(k, 3) + ...) * (nCr(n - k, 0) + nCr(n - k, 1) + ...) * 2^i
... | Solution |
python | PyCQA__pylint | doc/data/messages/n/not-async-context-manager/bad.py | {
"start": 0,
"end": 200
} | class ____:
def __enter__(self):
pass
def __exit__(self, *exc):
pass
async def foo():
async with ContextManager(): # [not-async-context-manager]
pass
| ContextManager |
python | huggingface__transformers | src/transformers/models/blenderbot/configuration_blenderbot.py | {
"start": 810,
"end": 7551
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BlenderbotModel`]. It is used to instantiate an
Blenderbot model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a simila... | BlenderbotConfig |
python | doocs__leetcode | solution/0700-0799/0731.My Calendar II/Solution2.py | {
"start": 0,
"end": 215
} | class ____:
def __init__(self, l: int, r: int):
self.left = None
self.right = None
self.l = l
self.r = r
self.mid = (l + r) >> 1
self.v = 0
self.add = 0
| Node |
python | vyperlang__vyper | vyper/venom/passes/literals_codesize.py | {
"start": 334,
"end": 1985
} | class ____(IRPass):
def run_pass(self):
for bb in self.function.get_basic_blocks():
self._process_bb(bb)
def _process_bb(self, bb):
for inst in bb.instructions:
if inst.opcode != "assign":
continue
(op,) = inst.operands
if not isi... | ReduceLiteralsCodesize |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_astype.py | {
"start": 30972,
"end": 31099
} | class ____(pd.core.arrays.IntegerArray):
# GH 42501
def copy(self):
raise NotImplementedError
| IntegerArrayNoCopy |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1261079,
"end": 1283593
} | class ____(
sgqlc.types.Type,
Node,
Actor,
PackageOwner,
ProjectOwner,
ProjectV2Owner,
ProjectV2Recent,
RepositoryDiscussionAuthor,
RepositoryDiscussionCommentAuthor,
RepositoryOwner,
UniformResourceLocatable,
MemberStatusable,
ProfileOwner,
Sponsorable,
Annou... | Organization |
python | kamyu104__LeetCode-Solutions | Python/minimum-amount-of-time-to-fill-cups.py | {
"start": 36,
"end": 276
} | class ____(object):
def fillCups(self, amount):
"""
:type amount: List[int]
:rtype: int
"""
return max(max(amount), (sum(amount)+1)//2)
# Time: O(1)
# Space: O(1)
# constructive algorithms
| Solution |
python | nedbat__coveragepy | tests/test_html.py | {
"start": 15191,
"end": 16878
} | class ____(HtmlTestHelpers, CoverageTest):
"""Tests of the HTML title support."""
def test_default_title(self) -> None:
self.create_initial_files()
self.run_coverage()
index = self.get_html_index_content()
assert "<title>Coverage report</title>" in index
assert "<h1>Cove... | HtmlTitleTest |
python | doocs__leetcode | solution/2200-2299/2232.Minimize Result by Adding Parentheses to Expression/Solution.py | {
"start": 0,
"end": 543
} | class ____:
def minimizeResult(self, expression: str) -> str:
l, r = expression.split("+")
m, n = len(l), len(r)
mi = inf
ans = None
for i in range(m):
for j in range(n):
c = int(l[i:]) + int(r[: j + 1])
a = 1 if i == 0 else int(l[:... | Solution |
python | walkccc__LeetCode | solutions/544. Output Contest Matches/544-2.py | {
"start": 0,
"end": 262
} | class ____:
def findContestMatch(self, n: int) -> str:
matches = [str(i + 1) for i in range(n)]
while n > 1:
for i in range(n // 2):
matches[i] = '(' + matches[i] + ',' + matches[n - 1 - i] + ')'
n //= 2
return matches[0]
| Solution |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_format_returned.py | {
"start": 597,
"end": 662
} | class ____:
"""Format through the metaclass."""
| ThirdGoodFormat |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py | {
"start": 33343,
"end": 38594
} | class ____:
"""Comprehensive tests for the PrefixTreeActor"""
async def test_tree_structure_multiple_insertions_actor(
self, tree_actor: PrefixTreeActor
) -> None:
# Add tenants and insert strings in specified order
ray.get(tree_actor.add_tenants.remote(["tenant_1", "tenant_2"], 0))... | TestPrefixTreeActorComprehensive |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/openai_api_models.py | {
"start": 1364,
"end": 1482
} | class ____(vLLMChatCompletionRequest):
model_config = ConfigDict(arbitrary_types_allowed=True)
| ChatCompletionRequest |
python | kamyu104__LeetCode-Solutions | Python/check-if-there-is-a-valid-path-in-a-grid.py | {
"start": 33,
"end": 1098
} | class ____(object):
def hasValidPath(self, grid):
"""
:type grid: List[List[int]]
:rtype: bool
"""
E, S, W, N = [(0, 1), (1, 0), (0, -1), (-1, 0)]
directions = [
[W, E], [N, S],
[W, S], [S, E],
[W, N], [N, E]
]
for ... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-genesys/source_genesys/source.py | {
"start": 6123,
"end": 8710
} | class ____(AbstractSource):
def build_refresh_request_body(self) -> Mapping[str, Any]:
return {
"grant_type": "client_credentials",
"client_id": self.get_client_id(),
"client_secret": self.get_client_secret(),
}
def check_connection(self, logger, config) -> T... | SourceGenesys |
python | django__django | tests/check_framework/test_security.py | {
"start": 8281,
"end": 9723
} | class ____(SimpleTestCase):
@override_settings(
MIDDLEWARE=["django.middleware.security.SecurityMiddleware"],
SECURE_HSTS_INCLUDE_SUBDOMAINS=False,
SECURE_HSTS_SECONDS=3600,
)
def test_no_sts_subdomains(self):
"""
Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True.
... | CheckStrictTransportSecuritySubdomainsTest |
python | pypa__warehouse | tests/unit/oidc/models/test_gitlab.py | {
"start": 2381,
"end": 35837
} | class ____:
@pytest.mark.parametrize("environment", [None, "some_environment"])
def test_lookup_fails_invalid_ci_config_ref_uri(self, environment):
signed_claims = {
"iss": "https://gitlab.com",
"project_path": "foo/bar",
"ci_config_ref_uri": ("gitlab.com/foo/bar//exa... | TestGitLabPublisher |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.