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 | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_layout04.py | {
"start": 315,
"end": 1602
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_layout04.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with user defined layout."""
workbook... | TestCompareXLSXFiles |
python | pytorch__pytorch | tools/code_coverage/package/tool/parser/llvm_coverage_segment.py | {
"start": 68,
"end": 1975
} | class ____(NamedTuple):
line: int
col: int
segment_count: int
has_count: int
is_region_entry: int
is_gap_entry: int | None
@property
def has_coverage(self) -> bool:
return self.segment_count > 0
@property
def is_executable(self) -> bool:
return self.has_count > ... | LlvmCoverageSegment |
python | scipy__scipy | scipy/sparse/linalg/_isolve/tests/test_iterative.py | {
"start": 20302,
"end": 26265
} | class ____:
def test_basic(self):
A = np.vander(np.arange(10) + 1)[:, ::-1]
b = np.zeros(10)
b[0] = 1
x_gm, err = gmres(A, b, restart=5, maxiter=1)
assert_allclose(x_gm[0], 0.359, rtol=1e-2)
@pytest.mark.filterwarnings(f"ignore:{CB_TYPE_FILTER}:DeprecationWarning")
... | TestGMRES |
python | getsentry__sentry | src/sentry/rules/conditions/event_attribute.py | {
"start": 14323,
"end": 14833
} | class ____(AttributeHandler):
minimum_path_length = 2
@classmethod
def _handle(cls, path: list[str], event: GroupEvent) -> list[str]:
if path[1] in ("channel", "runtime_version", "update_id"):
contexts = event.data.get("contexts", {})
ota_updates_context = contexts.get("ota_... | ExpoUpdatesAttributeHandler |
python | google__jax | jax/_src/debugger/cli_debugger.py | {
"start": 796,
"end": 4778
} | class ____(cmd.Cmd):
"""A text-based debugger."""
prompt = '(jdb) '
def __init__(self, frames: list[DebuggerFrame], thread_id,
stdin: IO[str] | None = None, stdout: IO[str] | None = None,
completekey: str = "tab"):
super().__init__(stdin=stdin, stdout=stdout, completekey=completekey)
self.use... | CliDebugger |
python | getsentry__sentry | src/social_auth/exceptions.py | {
"start": 1657,
"end": 1835
} | class ____(AuthException):
"""Auth token error."""
def __str__(self) -> str:
msg = super().__str__()
return gettext("Token error: %s") % msg
| AuthTokenError |
python | scipy__scipy | scipy/linalg/tests/test_decomp.py | {
"start": 4394,
"end": 15747
} | class ____:
def test_simple(self):
a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
w, v = eig(a)
exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
v0 = array([1, 1, (1+sqrt(93)/3)/2])
v1 = array([3., 0, -1])
v2 = array([1, 1, (1-sqrt(93)/3)/2])
v0 = v0 / norm(v0)
... | TestEig |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 23699,
"end": 24067
} | class ____(themeable):
"""
How to align the plot title and plot subtitle
Parameters
----------
theme_element : Literal["panel", "plot"], default = "panel"
If "panel", the title / subtitle are aligned with respect
to the panels. If "plot", they are aligned with the plot,
excl... | plot_title_position |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/checkpoint_management.py | {
"start": 21244,
"end": 37839
} | class ____(object):
"""Manages multiple checkpoints by keeping some and deleting unneeded ones.
Example usage:
```python
import tensorflow as tf
checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)
manager = tf.train.CheckpointManager(
checkpoint, directory="/tmp/model", max_to_keep=5)... | CheckpointManager |
python | wandb__wandb | wandb/vendor/promise-2.3.0/tests/test_extra.py | {
"start": 905,
"end": 14574
} | class ____:
def __init__(self, raises=True):
self.raises = raises
def then(self, s=None, f=None):
if self.raises:
raise Exception("FakeThenPromise raises in 'then'")
def df(value, dtime):
p = Promise()
t = DelayedFulfill(dtime, p, value)
t.start()
return p
def d... | FakeThenPromise |
python | joblib__joblib | joblib/memory.py | {
"start": 33811,
"end": 34897
} | class ____(MemorizedFunc):
async def __call__(self, *args, **kwargs):
out = self._cached_call(args, kwargs, shelving=False)
out = await out if asyncio.iscoroutine(out) else out
return out[0] # Don't return metadata
async def call_and_shelve(self, *args, **kwargs):
out = self._c... | AsyncMemorizedFunc |
python | huggingface__transformers | src/transformers/models/textnet/image_processing_textnet_fast.py | {
"start": 1376,
"end": 5491
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
size = {"shortest_edge": 640}
default_to_square = False
crop_size = {"height": 224, "width": 224}
do_resize = True
do_center_crop = False
do_... | TextNetImageProcessorFast |
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/subscribers/cloud_instance_updater.py | {
"start": 393,
"end": 3207
} | class ____(InstanceUpdatedSubscriber):
"""CloudInstanceUpdater is responsible for launching
new instances and terminating cloud instances
It requests the cloud instance provider to launch new instances when
there are new instance requests (with REQUESTED status change).
It requests the cloud insta... | CloudInstanceUpdater |
python | spack__spack | lib/spack/spack/platforms/__init__.py | {
"start": 855,
"end": 1627
} | class ____:
"""Class used to pickle a callable that may substitute either
_platform or _all_platforms. Lambda or nested functions are
not pickleable.
"""
def __init__(self, return_value):
self.return_value = return_value
def __call__(self):
return self.return_value
@contextli... | _PickleableCallable |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/layout.py | {
"start": 19013,
"end": 21627
} | class ____(LayoutOperatorBase):
"""Operator for torch.expand() operation."""
def __init__(self):
"""Initialize ExpandOperator."""
super().__init__("expand")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.expand"
... | ExpandOperator |
python | pypa__pipenv | pipenv/patched/pip/_internal/commands/cache.py | {
"start": 517,
"end": 8197
} | class ____(Command):
"""
Inspect and manage pip's wheel cache.
Subcommands:
- dir: Show the cache directory.
- info: Show information about the cache.
- list: List filenames of packages stored in the cache.
- remove: Remove one or more package from the cache.
- purge: Remove all items ... | CacheCommand |
python | spyder-ide__spyder | spyder/plugins/projects/widgets/projectdialog.py | {
"start": 10517,
"end": 12367
} | class ____(BaseProjectPage):
"""Existing directory project page."""
LOCATION_TEXT = _("Project path")
LOCATION_TIP = _("Select the directory to use for the project")
def get_name(self):
return _("Existing directory")
def get_icon(self):
return self.create_icon("DirClosedIcon")
... | ExistingDirectoryPage |
python | wandb__wandb | wandb/sdk/artifacts/_generated/input_types.py | {
"start": 1429,
"end": 1718
} | class ____(GQLInput):
entity_name: str = Field(alias="entityName")
old_project_name: str = Field(alias="oldProjectName")
new_project_name: str = Field(alias="newProjectName")
client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None)
| RenameProjectInput |
python | huggingface__transformers | src/transformers/models/dpt/modeling_dpt.py | {
"start": 1929,
"end": 2742
} | class ____(ModelOutput):
r"""
last_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
intermediate_activations (`tuple(torch.FloatTensor)`, *optional*):
Intermediate activations th... | BaseModelOutputWithIntermediateActivations |
python | kamyu104__LeetCode-Solutions | Python/minimum-adjacent-swaps-to-reach-the-kth-smallest-number.py | {
"start": 39,
"end": 1641
} | class ____(object):
def getMinSwaps(self, num, k):
"""
:type num: str
:type k: int
:rtype: int
"""
def next_permutation(nums, begin, end):
def reverse(nums, begin, end):
left, right = begin, end-1
while left < right:
... | Solution |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 11098,
"end": 11170
} | class ____(HTTPServerError):
status_code = 500
| HTTPInternalServerError |
python | RaRe-Technologies__gensim | gensim/topic_coherence/indirect_confirmation_measure.py | {
"start": 7495,
"end": 12777
} | class ____:
"""Lazily compute context vectors for topic segments.
Parameters
----------
measure: str
Confirmation measure.
topics: list of numpy.array
Topics.
accumulator : :class:`~gensim.topic_coherence.text_analysis.WordVectorsAccumulator` or
:class:`~gensim... | ContextVectorComputer |
python | lepture__authlib | authlib/jose/errors.py | {
"start": 2981,
"end": 3088
} | class ____(JoseError):
error = "expired_token"
description = "The token is expired"
| ExpiredTokenError |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/components/reward_providers/gail_reward_provider.py | {
"start": 2655,
"end": 11405
} | class ____(torch.nn.Module):
gradient_penalty_weight = 10.0
z_size = 128
alpha = 0.0005
mutual_information = 0.5
EPSILON = 1e-7
initial_beta = 0.0
def __init__(self, specs: BehaviorSpec, settings: GAILSettings) -> None:
super().__init__()
self._use_vail = settings.use_vail
... | DiscriminatorNetwork |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/map_metric_provider/map_metric_provider.py | {
"start": 3413,
"end": 36089
} | class ____(MetricProvider):
"""The base class for defining metrics that are evaluated for every row. An example of a map metric is
`column_values.null` (which is implemented as a `ColumnMapMetricProvider`, a subclass of `MapMetricProvider`).
""" # noqa: E501 # FIXME CoP
condition_domain_keys: tuple[st... | MapMetricProvider |
python | huggingface__transformers | tests/pipelines/test_pipelines_feature_extraction.py | {
"start": 991,
"end": 12200
} | class ____(unittest.TestCase):
model_mapping = MODEL_MAPPING
@require_torch
def test_small_model_pt(self):
feature_extractor = pipeline(task="feature-extraction", model="hf-internal-testing/tiny-random-distilbert")
outputs = feature_extractor("This is a test")
self.assertEqual(
... | FeatureExtractionPipelineTests |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 37261,
"end": 41069
} | class ____(ObjectBaseModel):
"""An ORM representation of deployment data."""
name: Name = Field(default=..., description="The name of the deployment.")
version: Optional[str] = Field(
default=None, description="An optional version for the deployment."
)
version_id: Optional[UUID] = Field(
... | Deployment |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/io.py | {
"start": 3872,
"end": 11342
} | class ____(IR):
"""
Input from a split file.
This class wraps a single-file `Scan` object. At
IO/evaluation time, this class will only perform
a partial read of the underlying file. The range
(skip_rows and n_rows) is calculated at IO time.
"""
__slots__ = (
"base_scan",
... | SplitScan |
python | modin-project__modin | modin/numpy/indexing.py | {
"start": 8056,
"end": 21312
} | class ____(object):
"""
An indexer for modin_arr.__{get|set}item__ functionality.
Parameters
----------
array : modin.numpy.array
Array to operate on.
"""
def __init__(self, array):
self.arr = array
def _get_numpy_object_from_qc_view(
self,
qc_view,
... | ArrayIndexer |
python | mahmoud__glom | glom/reduction.py | {
"start": 356,
"end": 508
} | class ____(GlomError):
"""Error raised when Fold() is called on non-iterable
targets, and possibly other uses in the future."""
pass
| FoldError |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 52344,
"end": 56417
} | class ____(nn.Module):
def __init__(self, config: OneFormerConfig):
super().__init__()
self.embed_dim = config.conv_dim
self.self_attn = OneFormerPixelDecoderEncoderMultiscaleDeformableAttention(
embed_dim=self.embed_dim,
num_heads=config.num_attention_heads,
... | OneFormerPixelDecoderEncoderLayer |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 260735,
"end": 262232
} | class ____(TypedDict, closed=True, total=False): # type: ignore[call-arg]
"""
:class:`altair.StyleConfigIndex` ``TypedDict`` wrapper.
Parameters
----------
arc
Arc-specific Config
area
Area-Specific Config
bar
Bar-Specific Config
circle
Circle-Specific C... | StyleConfigIndexKwds |
python | simonw__datasette | datasette/views/row.py | {
"start": 486,
"end": 5528
} | class ____(DataView):
name = "row"
async def data(self, request, default_labels=False):
resolved = await self.ds.resolve_row(request)
db = resolved.db
database = db.name
table = resolved.table
pk_values = resolved.pk_values
# Ensure user has permission to view t... | RowView |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/external_buildable_with_variant/package.py | {
"start": 217,
"end": 567
} | class ____(Package):
homepage = "http://somewhere.com"
url = "http://somewhere.com/module-1.0.tar.gz"
version("1.0", md5="1234567890abcdef1234567890abcdef")
version("0.9", md5="1234567890abcdef1234567890abcdef")
variant("baz", default=False, description="nope")
depends_on("pkg-c@1.0", when="@... | ExternalBuildableWithVariant |
python | networkx__networkx | networkx/classes/graph.py | {
"start": 2326,
"end": 72354
} | class ____:
"""
Base class for undirected graphs.
A Graph stores nodes and edges with optional data, or attributes.
Graphs hold undirected edges. Self loops are allowed but multiple
(parallel) edges are not.
Nodes can be arbitrary (hashable) Python objects with optional
key/value attribu... | Graph |
python | marshmallow-code__marshmallow | tests/test_fields.py | {
"start": 11737,
"end": 18304
} | class ____:
@pytest.mark.parametrize("param", ("only", "exclude", "dump_only", "load_only"))
def test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested(
self, param
):
class Child(Schema):
name = fields.String()
age = fields.Integer()
class Fa... | TestListNested |
python | google__pytype | pytype/rewrite/flow/state_test.py | {
"start": 2532,
"end": 6220
} | class ____(unittest.TestCase):
def test_merge_into_none(self):
b1 = state.BlockState({})
b2 = b1.merge_into(None)
self.assertIsNot(b1, b2)
self.assertFalse(b2._locals)
self.assertIs(b2._condition, conditions.TRUE)
def test_merge_into_other(self):
c1 = FakeCondition('a')
c2 = FakeCondit... | MergeIntoTest |
python | getsentry__sentry | src/sentry/audit_log/events.py | {
"start": 591,
"end": 1061
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=2, name="MEMBER_ADD", api_name="member.add")
def render(self, audit_log_entry: AuditLogEntry) -> str:
if audit_log_entry.target_user == audit_log_entry.actor:
return "joined the organization"
m... | MemberAddAuditLogEvent |
python | PrefectHQ__prefect | src/prefect/context.py | {
"start": 25966,
"end": 26420
} | class ____(ContextModel):
"""
The context for `prefect.tags` management.
Attributes:
current_tags: A set of current tags in the context
"""
current_tags: set[str] = Field(default_factory=set)
@classmethod
def get(cls) -> Self:
# Return an empty `TagsContext` instead of `No... | TagsContext |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/common/test_exceptions.py | {
"start": 16124,
"end": 18297
} | class ____:
@pytest.mark.parametrize(
"cause",
[
RuntimeError("Error during Dag serialization process"),
KeyError("required_field"),
ValueError("Missing Dag ID in serialized Dag"),
],
ids=[
"RuntimeError",
"KeyError",
... | TestDagErrorHandler |
python | doocs__leetcode | solution/2300-2399/2340.Minimum Adjacent Swaps to Make a Valid Array/Solution.py | {
"start": 0,
"end": 344
} | class ____:
def minimumSwaps(self, nums: List[int]) -> int:
i = j = 0
for k, v in enumerate(nums):
if v < nums[i] or (v == nums[i] and k < i):
i = k
if v >= nums[j] or (v == nums[j] and k > j):
j = k
return 0 if i == j else i + len(nums... | Solution |
python | zarr-developers__zarr-python | src/zarr/core/array_spec.py | {
"start": 504,
"end": 902
} | class ____(TypedDict):
"""
A TypedDict model of the attributes of an ArrayConfig class, but with no required fields.
This allows for partial construction of an ArrayConfig, with the assumption that the unset
keys will be taken from a global configuration.
"""
order: NotRequired[MemoryOrder]
... | ArrayConfigParams |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 825544,
"end": 825751
} | class ____(
sgqlc.types.Type, TeamAuditEntryData
):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ()
| OrgRestoreMemberMembershipTeamAuditEntryData |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/widgets/texteditor.py | {
"start": 857,
"end": 929
} | class ____:
Close = 'close'
Copy = 'copy_action'
| TextEditorActions |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/dagster_run.py | {
"start": 26539,
"end": 26949
} | class ____:
"""Kept here to maintain loading of PipelineRuns from when it was still alive."""
name: str
solid_subset: Optional[Sequence[str]] = None
def assets_are_externally_managed(run: DagsterRun) -> bool:
from dagster._core.storage.tags import EXTERNALLY_MANAGED_ASSETS_TAG
return get_boolean... | ExecutionSelector |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_integration.py | {
"start": 5954,
"end": 7132
} | class ____:
"""Test error handling and edge cases."""
def setup_method(self):
"""Set up test fixtures."""
self.runner = CliRunner()
def test_nonexistent_symbol_error_handling(self):
"""Test error handling for nonexistent symbols."""
result = self.runner.invoke(
... | TestErrorHandling |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_mixed_precision.py | {
"start": 8818,
"end": 20721
} | class ____(FSDPTest):
@property
def world_size(self):
raise ValueError("To be implemented by child classes")
def _get_simple_nested_model(
self, param_dtype, run_checks, *fsdp_args, **fsdp_kwargs
):
model = FSDP(
nn.Sequential(
FSDP(
... | TestFSDPMixedPrecision |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super2.py | {
"start": 964,
"end": 1011
} | class ____:
def __init__(self) -> None: ...
| C |
python | getsentry__sentry | src/sentry/integrations/slack/threads/activity_notifications.py | {
"start": 6364,
"end": 7724
} | class ____(GroupActivityNotification):
metrics_key = "create_issue"
title = "External Issue Created"
def get_description(self) -> tuple[str, str | None, Mapping[str, Any]]:
external_issue = _external_issue_activity_factory(activity=self.activity)
provider = external_issue.get_provider()
... | ExternalIssueCreatedActivityNotification |
python | getsentry__sentry | src/sentry/audit_log/services/log/impl.py | {
"start": 683,
"end": 4037
} | class ____(LogService):
event_id_skip_list_option = "hybrid_cloud.audit_log_event_id_invalid_pass_list"
def record_audit_log(self, *, event: AuditLogEvent) -> None:
entry = AuditLogEntry.from_event(event)
try:
with enforce_constraints(transaction.atomic(router.db_for_write(AuditLogE... | DatabaseBackedLogService |
python | PyCQA__pylint | tests/functional/i/inherit_non_class.py | {
"start": 1990,
"end": 2134
} | class ____(ParentBad[int]): # [inherit-non-class]
pass
# Classes that don't implement '__class_getitem__' are marked as unsubscriptable
| Child2 |
python | Netflix__metaflow | metaflow/datastore/datastore_set.py | {
"start": 2317,
"end": 2614
} | class ____(BlobCache):
def __init__(self, preloaded):
self._preloaded = preloaded
def load_key(self, key):
return self._preloaded.get(key)
def store_key(self, key, blob):
# we cache only preloaded keys, so no need to store anything
pass
| ImmutableBlobCache |
python | openai__openai-python | src/openai/types/responses/response_code_interpreter_tool_call_param.py | {
"start": 331,
"end": 538
} | class ____(TypedDict, total=False):
logs: Required[str]
"""The logs output from the code interpreter."""
type: Required[Literal["logs"]]
"""The type of the output. Always `logs`."""
| OutputLogs |
python | ray-project__ray | python/ray/tests/test_tls_auth.py | {
"start": 2438,
"end": 3943
} | class ____:
def __init__(self, x, y=0):
self.x = x
self.y = y
def method(self, a, b=0):
return self.x, self.y, a, b
a = Actor._remote(
args=[0], kwargs={"y": 1}, num_gpus=1, resources={"Custom": 1})
id1, id2, id3, id4 = a.method._remote(
args=["test"], kwargs={"b": 2}, num_ret... | Actor |
python | pytorch__pytorch | torch/utils/tensorboard/_pytorch_graph.py | {
"start": 1650,
"end": 2528
} | class ____(NodeBase):
def __init__(self, node_cpp, valid_methods) -> None:
super().__init__(node_cpp)
valid_methods = valid_methods[:]
self.inputs = []
for m in valid_methods:
if m == "inputs" or m == "outputs":
list_of_node = list(getattr(node_cpp, m)())... | NodePy |
python | pdm-project__pdm | src/pdm/models/backends.py | {
"start": 2374,
"end": 2853
} | class ____:
def __init__(self, expand: bool = True) -> None:
self.expand = expand
def __format__(self, __format_spec: str) -> str:
name, sep, default = __format_spec.partition(":")
if not self.expand:
return f"${{{name}}}"
if name in os.environ:
return os... | EnvContext |
python | mlflow__mlflow | mlflow/utils/request_utils.py | {
"start": 967,
"end": 10113
} | class ____(Retry):
"""
urllib3 < 2 doesn't support `backoff_jitter`. This class is a workaround for that.
"""
def __init__(self, *args, backoff_jitter=0.0, **kwargs):
super().__init__(*args, **kwargs)
self.backoff_jitter = backoff_jitter
def get_backoff_time(self):
"""
... | JitteredRetry |
python | huggingface__transformers | src/transformers/models/canine/modeling_canine.py | {
"start": 29798,
"end": 30578
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = CaninePredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_s... | CanineLMPredictionHead |
python | getsentry__sentry | src/sentry/integrations/github_enterprise/webhook.py | {
"start": 2113,
"end": 2218
} | class ____(Exception):
"""Signature value does not match the expected format"""
| MalformedSignatureError |
python | doocs__leetcode | solution/3700-3799/3747.Count Distinct Integers After Removing Zeros/Solution.py | {
"start": 0,
"end": 615
} | class ____:
def countDistinct(self, n: int) -> int:
@cache
def dfs(i: int, zero: bool, lead: bool, lim: bool) -> int:
if i >= len(s):
return 1 if (not zero and not lead) else 0
up = int(s[i]) if lim else 9
ans = 0
for j in range(up + 1)... | Solution |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 552318,
"end": 558254
} | class ____(ExprNode):
# Short-circuiting conditional expression.
#
# test ExprNode
# true_val ExprNode
# false_val ExprNode
true_val = None
false_val = None
is_temp = True
subexprs = ['test', 'true_val', 'false_val']
def type_dependencies(self, env):
re... | CondExprNode |
python | huggingface__transformers | tests/models/rag/test_tokenization_rag.py | {
"start": 1532,
"end": 7310
} | class ____(TestCase):
def setUp(self):
self.tmpdirname = tempfile.mkdtemp()
self.retrieval_vector_size = 8
# DPR tok
vocab_tokens = [
"[UNK]",
"[CLS]",
"[SEP]",
"[PAD]",
"[MASK]",
"want",
"##want",
... | RagTokenizerTest |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/contrib/regular_languages/regex_parser.py | {
"start": 869,
"end": 1357
} | class ____(Node):
"""
Union operation (OR operation) between several grammars. You don't
initialize this yourself, but it's a result of a "Grammar1 | Grammar2"
operation.
"""
def __init__(self, children: list[Node]) -> None:
self.children = children
def __or__(self, other_node: Nod... | AnyNode |
python | pytorch__pytorch | torch/_inductor/codecache.py | {
"start": 155580,
"end": 157811
} | class ____:
"""A wrapper for a dynamic library."""
def __init__(
self,
lib_path: str,
) -> None:
self.lib_path = lib_path
self.is_open = False
self.DLL = cdll.LoadLibrary(lib_path)
self.is_open = True
def close(self) -> None:
if self.is_open:
... | DLLWrapper |
python | apache__airflow | airflow-core/tests/unit/plugins/priority_weight_strategy.py | {
"start": 1670,
"end": 2194
} | class ____(AirflowPlugin):
# Without this import, the qualname method will not use the correct classes names
from unit.plugins.priority_weight_strategy import (
DecreasingPriorityStrategy,
FactorPriorityWeightStrategy,
StaticTestPriorityWeightStrategy,
)
name = "priority_weight_... | TestPriorityWeightStrategyPlugin |
python | sqlalchemy__sqlalchemy | test/ext/test_deprecations.py | {
"start": 352,
"end": 1239
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
FixtureTest.define_tables(metadata)
def test_reflect_true(self):
Base = automap_base(metadata=self.tables_test_metadata)
engine_mock = mock.Mock()
with mock.patch.object(Base.metadata, "reflect")... | AutomapTest |
python | pandas-dev__pandas | pandas/tests/reshape/merge/test_merge_ordered.py | {
"start": 362,
"end": 7561
} | class ____:
def test_basic(self, left, right):
result = merge_ordered(left, right, on="key")
expected = DataFrame(
{
"key": ["a", "b", "c", "d", "e", "f"],
"lvalue": [1, np.nan, 2, np.nan, 3, np.nan],
"rvalue": [np.nan, 1, 2, 3, np.nan, 4],... | TestMergeOrdered |
python | huggingface__transformers | src/transformers/models/biogpt/configuration_biogpt.py | {
"start": 811,
"end": 6215
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BioGptModel`]. It is used to instantiate an
BioGPT model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar config... | BioGptConfig |
python | getsentry__sentry | src/sentry/api/authentication.py | {
"start": 6829,
"end": 7735
} | class ____(QuietBasicAuthentication):
token_name: ClassVar[bytes]
def accepts_auth(self, auth: list[bytes]) -> bool:
return bool(auth) and auth[0].lower() == self.token_name
def authenticate_token(self, request: Request, token_str: str) -> tuple[Any, Any]:
raise NotImplementedError
de... | StandardAuthentication |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/dependency.py | {
"start": 28595,
"end": 31243
} | class ____(
NamedTuple("_DynamicCollectDependencyDefinition", [("node_name", str), ("output_name", str)]),
IDependencyDefinition,
):
def get_node_dependencies(self) -> Sequence[DependencyDefinition]:
return [DependencyDefinition(self.node_name, self.output_name)]
def is_fan_in(self) -> bool:
... | DynamicCollectDependencyDefinition |
python | pola-rs__polars | py-polars/src/polars/_typing.py | {
"start": 1135,
"end": 1374
} | class ____(Protocol):
"""Type protocol for Arrow C Data Interface via Arrow PyCapsule Interface."""
def __arrow_c_array__(
self, requested_schema: object | None = None
) -> tuple[object, object]: ...
| ArrowArrayExportable |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_operators_test.py | {
"start": 1025,
"end": 4857
} | class ____(test_util.TensorFlowTestCase):
def testEqualityOperators(self):
a = ragged_factory_ops.constant([[1, 2], [3]])
b = ragged_factory_ops.constant([[4, 5], [3]])
c = 2
if tf2.enabled() and ops.executing_eagerly_outside_functions():
# Value-based equality:
self.assertAllEqual(a == ... | RaggedElementwiseOpsTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/aiomysql.py | {
"start": 1977,
"end": 2232
} | class ____(AsyncAdapt_dbapi_cursor):
__slots__ = ()
def _make_new_cursor(
self, connection: AsyncIODBAPIConnection
) -> AsyncIODBAPICursor:
return connection.cursor(self._adapt_connection.dbapi.Cursor)
| AsyncAdapt_aiomysql_cursor |
python | numpy__numpy | numpy/_core/tests/test_item_selection.py | {
"start": 3769,
"end": 4885
} | class ____:
@pytest.mark.parametrize("dtype", list(np.typecodes["All"]) + ["i,O"])
def test_simple(self, dtype):
if dtype.lower() == "m":
dtype += "8[ns]"
# putmask is weird and doesn't care about value length (even shorter)
vals = np.arange(1001).astype(dtype=dtype)
... | TestPutMask |
python | pytorch__pytorch | test/test_ops.py | {
"start": 101401,
"end": 101742
} | class ____(TestCase):
def test_self_kwargs(self):
"""Verify that we can call the aten ops with all kwargs even if the
argument's name is "self"
"""
torch.ops.aten.reshape.default(self=torch.rand(1, 2), shape=[2])
torch.ops.aten.min.default(self=torch.rand(100))
@unMarkDynam... | TestSelfKwarg |
python | scikit-learn__scikit-learn | sklearn/feature_selection/_sequential.py | {
"start": 828,
"end": 13977
} | class ____(SelectorMixin, MetaEstimatorMixin, BaseEstimator):
"""Transformer that performs Sequential Feature Selection.
This Sequential Feature Selector adds (forward selection) or
removes (backward selection) features to form a feature subset in a
greedy fashion. At each stage, this estimator chooses... | SequentialFeatureSelector |
python | py-pdf__pypdf | pypdf/_doc_common.py | {
"start": 51883,
"end": 52374
} | class ____(Mapping[Any, Any]):
def __init__(self, *args: Any, **kwargs: Any) -> None:
self._raw_dict = dict(*args, **kwargs)
def __getitem__(self, key: str) -> Any:
func, arg = self._raw_dict.__getitem__(key)
return func(arg)
def __iter__(self) -> Iterator[Any]:
return iter... | LazyDict |
python | python__mypy | mypyc/irbuild/for_helpers.py | {
"start": 24779,
"end": 27515
} | class ____(ForGenerator):
"""Generate IR for a for loop over a native generator."""
def need_cleanup(self) -> bool:
# Create a new cleanup block for when the loop is finished.
return True
def init(self, expr_reg: Value, target_type: RType) -> None:
# Define target to contains the g... | ForNativeGenerator |
python | nedbat__coveragepy | coverage/exceptions.py | {
"start": 1172,
"end": 1282
} | class ____(CoverageException):
"""A source file turned out not to be parsable Python."""
pass
| NotPython |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py | {
"start": 7262,
"end": 7588
} | class ____(BaseModel, alias_generator=lambda x: x + '_'):
# MYPY: error: Required dynamic aliases disallowed [pydantic-alias]
x: int
# MYPY: error: Required dynamic aliases disallowed [pydantic-alias]
KwargsAliasGeneratorModel(x=1)
KwargsAliasGeneratorModel(x_=1)
KwargsAliasGeneratorModel(z=1)
| KwargsAliasGeneratorModel |
python | gevent__gevent | src/gevent/tests/test__semaphore.py | {
"start": 11973,
"end": 12249
} | class ____(gevent.Greenlet):
# A greenlet whose switch method will have a low hashcode.
hashcode = 10
def __init__(self, *args, **kwargs):
gevent.Greenlet.__init__(self, *args, **kwargs)
self.switch = SwitchWithFixedHash(self, self.hashcode)
| FirstG |
python | huggingface__transformers | src/transformers/models/git/modeling_git.py | {
"start": 35601,
"end": 36236
} | class ____(nn.Module):
def __init__(self, config: GitConfig):
super().__init__()
self.config = config
self.visual_projection = nn.Sequential(
nn.Linear(config.vision_config.hidden_size, config.hidden_size),
nn.LayerNorm(config.hidden_size, eps=config.vision_config.lay... | GitProjection |
python | pytest-dev__pytest-django | pytest_django_test/app/models.py | {
"start": 60,
"end": 168
} | class ____(models.Model):
name: str = models.CharField(max_length=100)
# Routed to database "second".
| Item |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py | {
"start": 5439,
"end": 7563
} | class ____(TypeTransformer):
"""
Convert arrays of dicts into JSON-formatted string arrays using double quotes only
when the schema defines a (nullable) array of strings. Output strings use no spaces
after commas and a single space after colons for consistent formatting.
Example:
[{'key': 'ca... | DoubleQuotedDictTypeTransformer |
python | dask__distributed | distributed/core.py | {
"start": 55366,
"end": 58069
} | class ____(TypedDict):
status: Literal["OK"]
def error_message(e: BaseException, status: str = "error") -> ErrorMessage:
"""Produce message to send back given an exception has occurred
This does the following:
1. Gets the traceback
2. Truncates the exception and the traceback
3. Serialize... | OKMessage |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/enum1.py | {
"start": 7171,
"end": 7342
} | class ____(Enum):
A = 1
__B = 2
reveal_type(TestEnum19.A, expected_text="Literal[TestEnum19.A]")
reveal_type(TestEnum19.__B, expected_text="Literal[2]")
| TestEnum19 |
python | sqlalchemy__sqlalchemy | test/sql/test_insert_exec.py | {
"start": 23902,
"end": 39202
} | class ____(fixtures.RemovesEvents, fixtures.TablesTest):
__sparse_driver_backend__ = True
__requires__ = ("insertmanyvalues",)
@classmethod
def define_tables(cls, metadata):
Table(
"data",
metadata,
Column("id", Integer, primary_key=True),
Column(... | InsertManyValuesTest |
python | openai__openai-python | src/openai/resources/beta/beta.py | {
"start": 977,
"end": 2236
} | class ____(SyncAPIResource):
@cached_property
def chat(self) -> Chat:
return Chat(self._client)
@cached_property
def realtime(self) -> Realtime:
return Realtime(self._client)
@cached_property
def chatkit(self) -> ChatKit:
return ChatKit(self._client)
@cached_proper... | Beta |
python | joke2k__faker | faker/providers/automotive/da_DK/__init__.py | {
"start": 48,
"end": 270
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``da_DK`` locale.
Source: https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Denmark
"""
license_formats = ("?? ## ###",)
| Provider |
python | walkccc__LeetCode | solutions/1711. Count Good Meals/1711.py | {
"start": 0,
"end": 334
} | class ____:
def countPairs(self, deliciousness: list[int]) -> int:
MOD = 10**9 + 7
MAX_BIT = 20 + 1
ans = 0
count = collections.Counter()
for d in deliciousness:
for i in range(MAX_BIT + 1):
power = 1 << i
ans += count[power - d]
ans %= MOD
count[d] += 1
r... | Solution |
python | doocs__leetcode | solution/2400-2499/2476.Closest Nodes Queries in a Binary Search Tree/Solution.py | {
"start": 192,
"end": 823
} | class ____:
def closestNodes(
self, root: Optional[TreeNode], queries: List[int]
) -> List[List[int]]:
def dfs(root: Optional[TreeNode]):
if root is None:
return
dfs(root.left)
nums.append(root.val)
dfs(root.right)
nums = [... | Solution |
python | arrow-py__arrow | arrow/locales.py | {
"start": 12190,
"end": 13709
} | class ____(Locale):
names = ["es", "es-es"]
past = "hace {0}"
future = "en {0}"
and_word = "y"
timeframes = {
"now": "ahora",
"second": "un segundo",
"seconds": "{0} segundos",
"minute": "un minuto",
"minutes": "{0} minutos",
"hour": "una hora",
... | SpanishLocale |
python | scikit-learn__scikit-learn | sklearn/ensemble/_bagging.py | {
"start": 23682,
"end": 42617
} | class ____(ClassifierMixin, BaseBagging):
"""A Bagging classifier.
A Bagging classifier is an ensemble meta-estimator that fits base
classifiers each on random subsets of the original dataset and then
aggregate their individual predictions (either by voting or by averaging)
to form a final predicti... | BaggingClassifier |
python | langchain-ai__langchain | libs/partners/openai/langchain_openai/chat_models/azure.py | {
"start": 1091,
"end": 44809
} | class ____(BaseChatOpenAI):
r"""Azure OpenAI chat model integration.
Setup:
Head to the Azure [OpenAI quickstart guide](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/chatgpt-quickstart?tabs=keyless%2Ctypescript-keyless%2Cpython-new%2Ccommand-line&pivots=programming-language-python)
... | AzureChatOpenAI |
python | tox-dev__tox | src/tox/execute/local_sub_process/__init__.py | {
"start": 1434,
"end": 1745
} | class ____(Execute):
def build_instance( # noqa: PLR6301
self,
request: ExecuteRequest,
options: ExecuteOptions,
out: SyncWrite,
err: SyncWrite,
) -> ExecuteInstance:
return LocalSubProcessExecuteInstance(request, options, out, err)
| LocalSubProcessExecutor |
python | getsentry__sentry-python | sentry_sdk/integrations/falcon.py | {
"start": 3679,
"end": 9501
} | class ____(Integration):
identifier = "falcon"
origin = f"auto.http.{identifier}"
transaction_style = ""
def __init__(self, transaction_style="uri_template"):
# type: (str) -> None
if transaction_style not in TRANSACTION_STYLE_VALUES:
raise ValueError(
"Inva... | FalconIntegration |
python | PyCQA__pylint | tests/functional/r/regression/regression_4439.py | {
"start": 364,
"end": 479
} | class ____:
name: str = attrib()
age: int = attrib()
occupation = Optional[str] = attrib(default=None)
| User |
python | pydantic__pydantic | pydantic/json_schema.py | {
"start": 3284,
"end": 5077
} | class ____(UserWarning):
"""This class is used to emit warnings produced during JSON schema generation.
See the [`GenerateJsonSchema.emit_warning`][pydantic.json_schema.GenerateJsonSchema.emit_warning] and
[`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_m... | PydanticJsonSchemaWarning |
python | spack__spack | lib/spack/spack/modules/common.py | {
"start": 37858,
"end": 38032
} | class ____(AttributeError, ModulesError):
"""Raised if the attribute ``modulerc_header`` has not been specified
in the derived classes.
"""
| ModulercHeaderNotDefined |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 48056,
"end": 49621
} | class ____(FieldValues):
"""
Valid and invalid values for `DateTimeField`.
"""
valid_inputs = {
'2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc),
'2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=utc),
'2001-01-01T13:00Z': datetime.datetime(200... | TestDateTimeField |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.