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 | run-llama__llama_index | llama-index-core/llama_index/core/indices/query/query_transform/base.py | {
"start": 6873,
"end": 8410
} | class ____(BaseQueryTransform):
"""
Image output query transform.
Adds instructions for formatting image output.
By default, this prompts the LLM to format image output as an HTML <img> tag,
which can be displayed nicely in jupyter notebook.
"""
def __init__(
self,
width: i... | ImageOutputQueryTransform |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 181897,
"end": 182714
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"project_id",
"title",
"short_description",
"readme",
"closed",
"public",
"client_mutation_id",
)
project_id = sgqlc.... | UpdateProjectV2Input |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 8634,
"end": 8763
} | class ____:
xlAutomaticAllocation = 2 # from enum XlAllocation
xlManualAllocation = 1 # from enum XlAllocation
| Allocation |
python | pytorch__pytorch | torch/nn/modules/pooling.py | {
"start": 4963,
"end": 8504
} | class ____(_MaxPoolNd):
r"""Applies a 2D max pooling over an input signal composed of several input planes.
In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`,
output :math:`(N, C, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kH, kW)`
can be precisely describ... | MaxPool2d |
python | django__django | django/db/models/constraints.py | {
"start": 10195,
"end": 28124
} | class ____(BaseConstraint):
def __init__(
self,
*expressions,
fields=(),
name=None,
condition=None,
deferrable=None,
include=None,
opclasses=(),
nulls_distinct=None,
violation_error_code=None,
violation_error_message=None,
)... | UniqueConstraint |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 5027,
"end": 8746
} | class ____(BuiltinFunctionT):
_id = "convert"
def fetch_call_return(self, node):
_, target_typedef = self.infer_arg_types(node)
# note: more type conversion validation happens in convert.py
return target_typedef.typedef
# TODO: push this down into convert.py for more consistency
... | Convert |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/svd_op_test.py | {
"start": 10015,
"end": 12134
} | class ____(test.TestCase):
pass # Filled in below
def _NormalizingSvd(tf_a, full_matrices_):
tf_s, tf_u, tf_v = linalg_ops.svd(
tf_a, compute_uv=True, full_matrices=full_matrices_)
# Singular vectors are only unique up to an arbitrary phase. We normalize
# the vectors such that the first component of u... | SvdGradOpTest |
python | jamielennox__requests-mock | requests_mock/response.py | {
"start": 3075,
"end": 4210
} | class ____(object):
"""An object that can mock the necessary parts of a socket interface."""
def send(self, request, **kwargs):
msg = 'This response was created without a connection. You are ' \
'therefore unable to make a request directly on that connection.'
raise exceptions.Inv... | _FakeConnection |
python | Textualize__textual | tests/animations/test_switch_animation.py | {
"start": 218,
"end": 2369
} | class ____(App[None]):
def compose(self) -> ComposeResult:
yield Switch()
async def test_switch_animates_on_full() -> None:
app = SwitchApp()
app.animation_level = "full"
async with app.run_test() as pilot:
switch = app.query_one(Switch)
animator = app.animator
# Freez... | SwitchApp |
python | joke2k__faker | faker/providers/internet/sv_SE/__init__.py | {
"start": 46,
"end": 475
} | class ____(InternetProvider):
free_email_domains = (
"telia.com",
"gmail.com",
"swipnet.se",
"googlemail.com",
"live.se",
"spray.se",
"yahoo.de",
)
tlds = ("com", "com", "com", "se", "se", "se", "net", "org")
replacements = (
("å", "a"),
... | Provider |
python | scikit-learn__scikit-learn | sklearn/kernel_approximation.py | {
"start": 836,
"end": 8651
} | class ____(
ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator
):
"""Polynomial kernel approximation via Tensor Sketch.
Implements Tensor Sketch, which approximates the feature map
of the polynomial kernel::
K(X, Y) = (gamma * <X, Y> + coef0)^degree
by efficiently computing ... | PolynomialCountSketch |
python | pypa__pipenv | pipenv/vendor/click/_termui_impl.py | {
"start": 15625,
"end": 24069
} | class ____:
def __init__(
self,
editor: t.Optional[str] = None,
env: t.Optional[t.Mapping[str, str]] = None,
require_save: bool = True,
extension: str = ".txt",
) -> None:
self.editor = editor
self.env = env
self.require_save = require_save
... | Editor |
python | modin-project__modin | modin/utils.py | {
"start": 1982,
"end": 2215
} | class ____(Protocol): # noqa: PR01
"""Structural type for objects with a ``to_pandas`` method (without a leading underscore)."""
def to_pandas(self) -> Any: # noqa: GL08
pass
@runtime_checkable
| SupportsPublicToPandas |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 38960,
"end": 41520
} | class ____(rv_continuous):
r"""A Burr (Type XII) continuous random variable.
%(before_notes)s
See Also
--------
fisk : a special case of either `burr` or `burr12` with ``d=1``
burr : Burr Type III distribution
Notes
-----
The probability density function for `burr12` is:
.. m... | burr12_gen |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 12286,
"end": 13912
} | class ____(TestCase):
def test_len(self):
source = TensorDataset(torch.randn(15, 10, 2, 3, 4, 5), torch.randperm(15))
self.assertEqual(len(source), 15)
def test_getitem(self):
t = torch.randn(15, 10, 2, 3, 4, 5)
l = torch.randn(15, 10)
source = TensorDataset(t, l)
... | TestTensorDataset |
python | streamlit__streamlit | lib/streamlit/web/server/oidc_mixin.py | {
"start": 4092,
"end": 4641
} | class ____(BaseOAuth):
oauth2_client_cls = TornadoOAuth2App
framework_integration_cls = TornadoIntegration
def __init__(
self,
config: dict[str, Any] | None = None,
cache: AuthCache | None = None,
fetch_token: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
... | TornadoOAuth |
python | apache__thrift | test/crossrunner/report.py | {
"start": 7203,
"end": 16880
} | class ____(TestReporter):
def __init__(self, basedir, testdir_relative, concurrent=True):
super(SummaryReporter, self).__init__()
self._basedir = basedir
self._testdir_rel = testdir_relative
self.logdir = os.path.join(self.testdir, LOG_DIR)
self.out_path = os.path.join(self.t... | SummaryReporter |
python | plotly__plotly.py | plotly/graph_objs/histogram2d/_colorbar.py | {
"start": 233,
"end": 61565
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram2d"
_path_str = "histogram2d.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"minexponent",... | ColorBar |
python | django__django | tests/fixtures_regress/models.py | {
"start": 5516,
"end": 5721
} | class ____(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.circle6"]
| Circle5 |
python | automl__auto-sklearn | autosklearn/experimental/selector.py | {
"start": 129,
"end": 1014
} | class ____:
def fit(
self,
X: pd.DataFrame,
y: pd.DataFrame,
minima: typing.Dict[int, typing.Dict[str, float]],
maxima: typing.Dict[int, typing.Dict[str, float]],
) -> None:
raise NotImplementedError()
def predict(
self, X: pd.DataFrame, y: typing.Opt... | AbstractSelector |
python | numpy__numpy | numpy/_core/tests/test_deprecations.py | {
"start": 4909,
"end": 5026
} | class ____(_DeprecationTestCase):
warning_cls = np.exceptions.VisibleDeprecationWarning
| _VisibleDeprecationTestCase |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/relationship.py | {
"start": 1915,
"end": 2486
} | class ____(Base):
__tablename__ = "address"
id = mapped_column(Integer, primary_key=True)
user_id = mapped_column(ForeignKey("user.id"))
email: Mapped[str]
email_name: Mapped[str] = mapped_column("email_name")
user_style_one: Mapped[User] = relationship()
user_style_two: Mapped["User"] = r... | Address |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 32220,
"end": 33778
} | class ____(WrapperLine):
"""
Given a MultiOutputLayout buffer, indexes actual buffer(s) from the result.
"""
wrapper: PythonWrapperCodegen
result_name: str
arg_name: str
indices: Sequence[Any]
def codegen(self, code: IndentedBuffer) -> None:
def codegen_list_tuple_access(basena... | MultiOutputLine |
python | Netflix__metaflow | metaflow/plugins/airflow/exception.py | {
"start": 191,
"end": 287
} | class ____(MetaflowException):
headline = "Not yet supported with Airflow"
| NotSupportedException |
python | PyCQA__flake8 | src/flake8/api/legacy.py | {
"start": 1858,
"end": 6900
} | class ____:
"""Public facing object that mimic's Flake8 2.0's StyleGuide.
.. note::
There are important changes in how this object behaves compared to
the StyleGuide object provided in Flake8 2.x.
.. warning::
This object should not be instantiated directly by users.
.. vers... | StyleGuide |
python | pypa__pip | src/pip/_vendor/rich/prompt.py | {
"start": 10414,
"end": 12447
} | class ____(PromptBase[bool]):
"""A yes / no confirmation prompt.
Example:
>>> if Confirm.ask("Continue"):
run_job()
"""
response_type = bool
validate_error_message = "[prompt.invalid]Please enter Y or N"
choices: List[str] = ["y", "n"]
def render_default(self, def... | Confirm |
python | tensorflow__tensorflow | tensorflow/python/training/saver.py | {
"start": 25689,
"end": 76501
} | class ____:
# pylint: disable=line-too-long
"""Saves and restores variables.
@compatibility(TF2)
`tf.compat.v1.train.Saver` is not supported for saving and restoring
checkpoints in TF2. Please switch to `tf.train.Checkpoint` or
`tf.keras.Model.save_weights`, which perform a more robust [object-based
savi... | Saver |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 62193,
"end": 62402
} | class ____(IP):
"""A IPv4 address field.
.. versionadded:: 3.8.0
"""
default_error_messages = {"invalid_ip": "Not a valid IPv4 address."}
DESERIALIZATION_CLASS = ipaddress.IPv4Address
| IPv4 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/executor_definition.py | {
"start": 9985,
"end": 21829
} | class ____:
def __init__(self, name=None, config_schema=None, requirements=None):
self.name = check.opt_str_param(name, "name")
self.config_schema = config_schema # type check in definition
self.requirements = requirements
def __call__(self, fn: ExecutorCreationFunction) -> ExecutorDef... | _ExecutorDecoratorCallable |
python | redis__redis-py | redis/multidb/command_executor.py | {
"start": 1255,
"end": 2037
} | class ____(CommandExecutor):
def __init__(
self,
auto_fallback_interval: float = DEFAULT_AUTO_FALLBACK_INTERVAL,
):
self._auto_fallback_interval = auto_fallback_interval
self._next_fallback_attempt: datetime
@property
def auto_fallback_interval(self) -> float:
re... | BaseCommandExecutor |
python | Lightning-AI__lightning | tests/tests_fabric/helpers/dataloaders.py | {
"start": 1208,
"end": 1650
} | class ____(CustomInfDataloader):
def __len__(self):
"""Raise NotImplementedError."""
raise NotImplementedError
def __next__(self):
if self.count >= 2:
raise StopIteration
self.count = self.count + 1
try:
return next(self.iter)
except StopI... | CustomNotImplementedErrorDataloader |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_translate.py | {
"start": 36072,
"end": 37754
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.translate.TranslateHook")
def test_minimal_green_path(self, mock_hook):
DELETION_RESULT_SAMPLE = {
"submit_time": "2024-11-17T14:05:00Z",
"end_time": "2024-11-17T17:09:03Z",
"name": f"projects/{PROJECT_... | TestTranslateDeleteGlossary |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 81624,
"end": 85587
} | class ____(MoeCausalLMOutputWithPast):
r"""
Args:
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
The rope index difference between sequence length and multimodal rope.
"""
rope_deltas: Optional[torch.LongTensor] = None
def load_balancing_loss_func(
gat... | Qwen3OmniMoeThinkerCausalLMOutputWithPast |
python | django__django | django/contrib/messages/storage/cookie.py | {
"start": 2238,
"end": 8678
} | class ____(BaseStorage):
"""
Store messages in a cookie.
"""
cookie_name = "messages"
# uwsgi's default configuration enforces a maximum size of 4kb for all the
# HTTP headers. In order to leave some room for other cookies and headers,
# restrict the session cookie to 1/2 of 4kb. See #18781... | CookieStorage |
python | sanic-org__sanic | sanic/http/http1.py | {
"start": 763,
"end": 21365
} | class ____(Stream, metaclass=TouchUpMeta):
""" "Internal helper for managing the HTTP/1.1 request/response cycle.
Raises:
BadRequest: If the request body is malformed.
Exception: If the request is malformed.
ExpectationFailed: If the request is malformed.
PayloadTooLarge: If the... | Http |
python | pandas-dev__pandas | pandas/tests/indexes/numeric/test_indexing.py | {
"start": 3203,
"end": 15986
} | class ____:
def test_get_indexer(self):
index1 = Index([1, 2, 3, 4, 5])
index2 = Index([2, 4, 6])
r1 = index1.get_indexer(index2)
e1 = np.array([1, 3, -1], dtype=np.intp)
tm.assert_almost_equal(r1, e1)
@pytest.mark.parametrize("reverse", [True, False])
@pytest.mark.... | TestGetIndexer |
python | spack__spack | lib/spack/spack/util/gcs.py | {
"start": 7464,
"end": 7552
} | class ____(BaseHandler):
def gs_open(self, req):
return gcs_open(req)
| GCSHandler |
python | django__django | tests/model_meta/tests.py | {
"start": 8854,
"end": 9246
} | class ____(SimpleTestCase):
def test_string(self):
# Clear cached property.
Relation._meta.__dict__.pop("verbose_name_raw", None)
self.assertEqual(Relation._meta.verbose_name_raw, "relation")
def test_gettext(self):
Person._meta.__dict__.pop("verbose_name_raw", None)
sel... | VerboseNameRawTests |
python | walkccc__LeetCode | solutions/1551. Minimum Operations to Make Array Equal/1551.py | {
"start": 0,
"end": 690
} | class ____:
def minOperations(self, n: int) -> int:
def arr(self, i: int) -> int:
"""Returns the i-th element of `arr`, where 1 <= i <= n."""
return (i - 1) * 2 + 1
# median := median of arr
# diffs[i] := median - arr[i] where i <= i <= n // 2
# ans := sum(diffs)
# e.g.
... | Solution |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 14911,
"end": 15637
} | class ____(models.Model):
char_field = models.CharField(max_length=10)
integer_field = models.IntegerField()
foreign_key_field = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
def has_self_only(self):
pass
def has_one_extra_argument(self, arg_one):
pass
def has_... | MultipleFieldsAndMethods |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 634359,
"end": 634676
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("Sponsorship", graphql_name="node")
| SponsorshipEdge |
python | weaviate__weaviate-python-client | weaviate/cluster/replicate/async_.py | {
"start": 179,
"end": 248
} | class ____(_ReplicateExecutor[ConnectionAsync]):
pass
| _ReplicateAsync |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1523513,
"end": 1523892
} | class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, TeamAuditEntryData):
"""Audit log entry for a team.add_member event."""
__schema__ = github_schema
__field_names__ = ("is_ldap_mapped",)
is_ldap_mapped = sgqlc.types.Field(Boolean, graphql_name="isLdapMapped")
"""Whether the... | TeamAddMemberAuditEntry |
python | scipy__scipy | scipy/stats/tests/test_discrete_distns.py | {
"start": 26622,
"end": 27016
} | class ____:
def test_gh19759(self):
# test zero PMF values within the support reported by gh-19759
a = -354
max_range = abs(a)
all_b_1 = [a + 2 ** 31 + i for i in range(max_range)]
res = randint.pmf(325, a, all_b_1)
assert (res > 0).all()
ref = 1 / (np.asarray... | TestRandInt |
python | has2k1__plotnine | plotnine/_utils/yippie.py | {
"start": 1566,
"end": 1944
} | class ____:
"""
Position Legends
"""
@property
def left(self):
return theme(legend_position="left")
@property
def bottom(self):
return theme(legend_position="bottom")
@property
def right(self):
return theme(legend_position="right")
@property
def to... | _Legend |
python | FactoryBoy__factory_boy | factory/errors.py | {
"start": 224,
"end": 321
} | class ____(FactoryError):
"""Raised when a factory uses an unknown strategy."""
| UnknownStrategy |
python | neetcode-gh__leetcode | python/1091-shortest-path-in-binary-matrix.py | {
"start": 0,
"end": 730
} | class ____:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
N = len(grid)
q = deque([(0, 0, 1)]) # r, c, length
visit = set((0, 0))
direct = [[0, 1], [1, 0], [0, -1], [-1, 0],
[1, 1], [-1, -1], [1, -1], [-1, 1]]
while q:
r, c, l... | Solution |
python | Textualize__textual | tests/css/test_screen_css.py | {
"start": 418,
"end": 774
} | class ____(Screen):
SCOPED_CSS = False
CSS = """
#screen-css {
background: #ff0000;
}
"""
CSS_PATH = "test_screen_css.tcss"
def compose(self):
yield Label("Hello, world!", id="app-css")
yield Label("Hello, world!", id="screen-css-path")
yield Label("Hello, w... | ScreenWithCSS |
python | huggingface__transformers | src/transformers/models/sam2_video/modeling_sam2_video.py | {
"start": 18274,
"end": 20696
} | class ____(nn.Module):
"""
SAM2_VIDEO's attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and
values.
"""
def __init__(self, config, downsample_rate=None):
super().__init__()
downsample_rate = config.attention_downsample_rate if... | Sam2VideoAttention |
python | getsentry__sentry | src/sentry/preprod/migrations/0011_add_preprod_artifact_app_name_and_app_id_fields.py | {
"start": 155,
"end": 1661
} | 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 | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-document360/llama_index/readers/document360/entities/article_slim.py | {
"start": 181,
"end": 600
} | class ____(BaseModel):
id: Optional[str]
title: Optional[str]
modified_at: Optional[str]
public_version: Optional[int]
latest_version: Optional[int]
language_code: Optional[str]
hidden: Optional[bool]
status: Optional[int]
order: Optional[int]
slug: Optional[str]
content_type... | ArticleSlim |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 87528,
"end": 88264
} | class ____(nn.Module):
"""
RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
"""
def __init__(self, config: DFineConfig, in_channels: int, out_channels: int):
super().__init__()
activation = config.activation_function
hidden_chann... | DFineRepVggBlock |
python | getsentry__sentry | src/sentry/core/endpoints/organization_member_utils.py | {
"start": 2088,
"end": 2165
} | class ____(serializers.ValidationError):
pass
| MemberConflictValidationError |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/ir.py | {
"start": 98603,
"end": 99416
} | class ____(IR):
"""Filter a dataframe with a boolean mask."""
__slots__ = ("mask",)
_non_child = ("schema", "mask")
mask: expr.NamedExpr
"""Expression to produce the filter mask."""
def __init__(self, schema: Schema, mask: expr.NamedExpr, df: IR):
self.schema = schema
self.mask... | Filter |
python | vyperlang__vyper | vyper/evm/address_space.py | {
"start": 204,
"end": 2201
} | class ____:
"""
Object representing info about the "address space", analogous to the
LLVM concept. It includes some metadata so that codegen can be
written in a more generic way.
Attributes:
name: human-readable nickname for the address space
word_scale: a constant which helps calcu... | AddrSpace |
python | django__django | tests/mail/tests.py | {
"start": 86939,
"end": 87992
} | class ____(SimpleTestCase):
"""
Tests for #12422 -- Django smarts (#2472/#11212) with charset of utf-8 text
parts shouldn't pollute global email Python package charset registry when
django.mail.message is imported.
"""
def test_utf8(self):
txt = MIMEText("UTF-8 encoded body", "plain", "... | PythonGlobalState |
python | getsentry__sentry | tests/sentry/tasks/test_llm_issue_detection.py | {
"start": 740,
"end": 10693
} | class ____(TestCase):
@patch("sentry.tasks.llm_issue_detection.detection.detect_llm_issues_for_project.delay")
def test_run_detection_dispatches_sub_tasks(self, mock_delay):
"""Test run_detection spawns sub-tasks for each project."""
project = self.create_project()
with self.options(
... | LLMIssueDetectionTest |
python | conda__conda | conda/models/records.py | {
"start": 7861,
"end": 18409
} | class ____(DictSafeMixin, Entity):
"""Representation of a concrete package archive (tarball or .conda file).
It captures all the relevant information about a given package archive, including its source,
in the following attributes.
Note that there are three subclasses, :class:`SolvedRecord`, :class:`P... | PackageRecord |
python | django__django | tests/model_indexes/tests.py | {
"start": 339,
"end": 11649
} | class ____(SimpleTestCase):
def test_suffix(self):
self.assertEqual(models.Index.suffix, "idx")
def test_repr(self):
index = models.Index(fields=["title"])
named_index = models.Index(fields=["title"], name="title_idx")
multi_col_index = models.Index(fields=["title", "author"])
... | SimpleIndexesTests |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 133819,
"end": 146998
} | class ____:
@pytest.mark.parametrize('dtype', [None, 'float32', 'float64'])
def test_basic(self, dtype, xp):
x = np.arange(8) * 0.5
np.random.shuffle(x)
dtype = xp_default_dtype(xp) if dtype is None else getattr(xp, dtype)
xp_assert_equal(stats.iqr(xp.asarray(x, dtype=dtype)),
... | TestIQR |
python | tornadoweb__tornado | tornado/test/routing_test.py | {
"start": 1812,
"end": 1979
} | class ____(RequestHandler):
def get(self, path):
if path not in resources:
raise HTTPError(404)
self.finish(resources[path])
| GetResource |
python | faif__python-patterns | patterns/structural/adapter.py | {
"start": 1520,
"end": 1649
} | class ____:
def __init__(self) -> None:
self.name = "Human"
def speak(self) -> str:
return "'hello'"
| Human |
python | ray-project__ray | rllib/algorithms/sac/sac_tf_model.py | {
"start": 533,
"end": 12619
} | class ____(TFModelV2):
"""Extension of the standard TFModelV2 for SAC.
To customize, do one of the following:
- sub-class SACTFModel and override one or more of its methods.
- Use SAC's `q_model_config` and `policy_model` keys to tweak the default model
behaviors (e.g. fcnet_hiddens, conv_filters... | SACTFModel |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_name/invalid_name_enum.py | {
"start": 165,
"end": 826
} | class ____(Enum):
"""Represents colors as (red, green, blue) tuples."""
YELLOW = 250, 250, 0
KHAKI = 250, 250, 125
MAGENTA = 250, 0, 250
VIOLET = 250, 125, 250
CYAN = 0, 250, 250
aquamarine = 125, 250, 250 # [invalid-name]
red: int
green: int
... | Color |
python | fluentpython__example-code | attic/iterables/paragraph.py | {
"start": 841,
"end": 1209
} | class ____:
def __init__(self, text):
self.text = text
def __repr__(self):
return 'Paragraph(%s)' % reprlib.repr(self.text)
def __iter__(self):
for match in RE_SENTENCE.finditer(self.text):
yield Sentence(match.group().strip())
def words(self):
for sentenc... | Paragraph |
python | ethereum__web3.py | web3/_utils/threads.py | {
"start": 340,
"end": 2595
} | class ____(Exception):
"""
A limited subset of the `gevent.Timeout` context manager.
"""
seconds = None
exception = None
begun_at = None
is_running = None
def __init__(
self,
seconds: float = None,
exception: type[BaseException] = None,
*args: Any,
... | Timeout |
python | jazzband__django-redis | django_redis/compressors/gzip.py | {
"start": 124,
"end": 516
} | class ____(BaseCompressor):
min_length = 15
def compress(self, value: bytes) -> bytes:
if len(value) > self.min_length:
return gzip.compress(value)
return value
def decompress(self, value: bytes) -> bytes:
try:
return gzip.decompress(value)
except gz... | GzipCompressor |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 70132,
"end": 70576
} | class ____(BaseModel):
"""
Message send failures for a particular peer
"""
count: int = Field(..., description="Message send failures for a particular peer")
latest_error: Optional[str] = Field(default=None, description="Message send failures for a particular peer")
latest_error_timestamp: Opti... | MessageSendErrors |
python | huggingface__transformers | tests/models/marian/test_modeling_marian.py | {
"start": 22748,
"end": 23265
} | class ____(MarianIntegrationTest):
src = "fi"
tgt = "en"
src_text = [
"minä tykkään kirjojen lukemisesta",
"Pidän jalkapallon katsomisesta",
]
expected_text = ["I like to read books", "I like watching football"]
@classmethod
def setUpClass(cls) -> None:
cls.model_nam... | TestMarian_FI_EN_V2 |
python | pytorch__pytorch | test/inductor/test_split_cat_fx_passes.py | {
"start": 849,
"end": 52864
} | class ____(TestCase):
@torch._inductor.config.patch(
pre_grad_fusion_options={
"normalization_pass": {},
},
post_grad_fusion_options={},
)
def test_split_normalization(self):
def arg_only(x):
return [torch.relu(s) for s in torch.split(x, 2, 1)]
... | TestSplitCatFxPasses |
python | PrefectHQ__prefect | tests/utilities/test_callables.py | {
"start": 15724,
"end": 19529
} | class ____:
def test_methods_with_no_arguments(self):
class Foo:
def f(self):
pass
@classmethod
def g(cls):
pass
@staticmethod
def h():
pass
for method in [Foo().f, Foo.g, Foo.h]:
... | TestMethodToSchema |
python | celery__celery | celery/utils/objects.py | {
"start": 167,
"end": 1423
} | class ____:
"""Object that enables you to modify attributes."""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def mro_lookup(cls, attr, stop=None, monkey_patched=None):
"""Return the first node by MRO order that defines an attribute.
Arguments:
cls (Any): Child class to ... | Bunch |
python | simonw__sqlite-utils | sqlite_utils/utils.py | {
"start": 5545,
"end": 5620
} | class ____(enum.Enum):
CSV = 1
TSV = 2
JSON = 3
NL = 4
| Format |
python | pyinstaller__pyinstaller | PyInstaller/archive/writers.py | {
"start": 4250,
"end": 14825
} | class ____:
"""
Writer for PyInstaller's CArchive (PKG) archive.
This archive contains all files that are bundled within an executable; a PYZ (ZlibArchive), DLLs, Python C
extensions, and other data files that are bundled in onefile mode.
The archive can be read from either C (bootloader code at a... | CArchiveWriter |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 60423,
"end": 61486
} | class ____:
RETRY_ARGS = dict(
wait=tenacity.wait_fixed(0.1),
stop=tenacity.stop_after_attempt(5),
)
def _fail(self):
raise NotImplementedError()
@retry(**RETRY_ARGS)
def _decorated_fail(self):
self._fail()
@pytest.fixture()
def mock_sleep(self, monkeypatch... | TestMockingSleep |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydoclint/DOC403_numpy.py | {
"start": 345,
"end": 1290
} | class ____:
# DOC403
def foo(self) -> str:
"""
Do something
Parameters
----------
num : int
A number
Yields
-------
str
A string
"""
print('test')
# OK
def bar(self) -> str:
"""
D... | Bar |
python | numpy__numpy | numpy/f2py/tests/test_array_from_pyobj.py | {
"start": 4434,
"end": 6994
} | class ____:
_type_cache = {}
def __new__(cls, name):
if isinstance(name, np.dtype):
dtype0 = name
name = None
for n, i in c_names_dict.items():
if not isinstance(i, type) and dtype0.type is i.type:
name = n
brea... | Type |
python | html5lib__html5lib-python | html5lib/html5parser.py | {
"start": 104428,
"end": 105628
} | class ____(Phase):
__slots__ = tuple()
def processEOF(self):
pass
def processComment(self, token):
self.tree.insertComment(token, self.tree.document)
def processSpaceCharacters(self, token):
return self.parser.phases["inBody"].processSpaceCharacters(token)
def processChar... | AfterAfterBodyPhase |
python | django-extensions__django-extensions | django_extensions/management/commands/drop_test_database.py | {
"start": 588,
"end": 9268
} | class ____(BaseCommand):
help = "Drops test database for this project."
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--noinput",
"--no-input",
action="store_false",
dest="interactive",
default=Tr... | Command |
python | tensorflow__tensorflow | tensorflow/python/ops/autograph_ops_test.py | {
"start": 874,
"end": 1423
} | class ____(test.TestCase):
def test_wrap_py_func_dummy_return(self):
side_counter = [0]
def test_fn(_):
side_counter[0] += 1
with self.cached_session():
result = autograph_ops.wrap_py_func(test_fn, (5,))
self.assertEqual(1, self.evaluate(result))
self.assertEqual([1], side_count... | AutographOpsTest |
python | ansible__ansible | test/lib/ansible_test/_util/controller/sanity/validate-modules/validate_modules/module_args.py | {
"start": 1515,
"end": 6301
} | class ____:
def __init__(self):
self.args = tuple()
self.kwargs = {}
self.called = False
def __call__(self, *args, **kwargs):
if args and isinstance(args[0], AnsibleModule):
# Make sure, due to creative calling, that we didn't end up with
# ``self`` in ``... | _FakeAnsibleModuleInit |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-gaudi/llama_index/embeddings/gaudi/base.py | {
"start": 1762,
"end": 4704
} | class ____(BaseEmbedding):
max_length: int = Field(
default=DEFAULT_HUGGINGFACE_LENGTH, description="Maximum length of input.", gt=0
)
normalize: bool = Field(default=True, description="Normalize embeddings or not.")
query_instruction: Optional[str] = Field(
description="Instruction to p... | GaudiEmbedding |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/spark_datasource.py | {
"start": 2206,
"end": 6142
} | class ____(Datasource):
# instance attributes
spark_config: Union[SparkConfig, None] = None
force_reuse_spark_context: bool = True
persist: bool = True
# private attrs
_spark: Union[SparkSession, None] = pydantic.PrivateAttr(None)
@pydantic.validator("force_reuse_spark_context")
@class... | _SparkDatasource |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_config_types.py | {
"start": 3734,
"end": 27388
} | class ____(NonLaunchableGraphQLContextTestMatrix):
def test_pipeline_not_found(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="nope",
run_config={},
)
assert not result.errors
assert res... | TestConfigTypes |
python | tensorflow__tensorflow | tensorflow/python/debug/wrappers/framework.py | {
"start": 5342,
"end": 5719
} | class ____:
"""Request to an on-session-init callback.
This callback is invoked during the __init__ call to a debug-wrapper session.
"""
def __init__(self, sess):
"""Constructor.
Args:
sess: A tensorflow Session object.
"""
_check_type(sess, (session.BaseSession, monitored_session.Moni... | OnSessionInitRequest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/dynamic.py | {
"start": 3450,
"end": 3528
} | class ____(_WriteOnlyLoader):
impl_class = _DynamicAttributeImpl
| _DynaLoader |
python | sqlalchemy__sqlalchemy | test/engine/test_execute.py | {
"start": 50095,
"end": 57544
} | class ____(fixtures.TestBase):
def test_engine_level_options(self):
eng = engines.testing_engine(
options={"execution_options": {"foo": "bar"}}
)
with eng.connect() as conn:
eq_(conn._execution_options["foo"], "bar")
eq_(
conn.execution_opt... | ExecutionOptionsTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 1767,
"end": 1964
} | class ____(IncrementalShopifyStreamWithDeletedEvents):
cursor_field = "id"
order_field = "id"
data_field = "blogs"
filter_field = "since_id"
deleted_events_api_name = "Blog"
| Blogs |
python | django-haystack__django-haystack | test_haystack/core/models.py | {
"start": 1690,
"end": 1910
} | class ____(models.Model):
author = models.CharField(max_length=255)
deleted = models.BooleanField(default=False)
objects = SoftDeleteManager()
def __str__(self):
return self.author
| AFifthMockModel |
python | doocs__leetcode | solution/1900-1999/1958.Check if Move is Legal/Solution.py | {
"start": 0,
"end": 638
} | class ____:
def checkMove(
self, board: List[List[str]], rMove: int, cMove: int, color: str
) -> bool:
for a in range(-1, 2):
for b in range(-1, 2):
if a == 0 and b == 0:
continue
i, j = rMove, cMove
cnt = 0
... | Solution |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_pprint.py | {
"start": 3845,
"end": 4723
} | class ____(BaseEstimator):
def __init__(
self,
C=1.0,
kernel="rbf",
degree=3,
gamma="auto_deprecated",
coef0=0.0,
shrinking=True,
probability=False,
tol=1e-3,
cache_size=200,
class_weight=None,
verbose=False,
max... | SVC |
python | django-extensions__django-extensions | tests/management/commands/test_sqldsn.py | {
"start": 1262,
"end": 1616
} | class ____(TestCase):
"""Tests for sqldsn management command exceptions."""
@override_settings(DATABASES={})
def test_should_raise_CommandError_if_unknown_database_does_not_exist(self):
with self.assertRaisesRegex(CommandError, "Unknown database unknown"):
call_command("sqldsn", "--data... | SqlDsnExceptionsTests |
python | huggingface__transformers | src/transformers/models/dpt/configuration_dpt.py | {
"start": 942,
"end": 13976
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DPTModel`]. It is used to instantiate an DPT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuratio... | DPTConfig |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 35895,
"end": 36077
} | class ____(BoringModel):
def on_train_batch_end(self, outputs, batch, batch_idx):
if batch_idx == 1:
raise RuntimeError("Trouble!")
| TroubledModelOnTrainBatchEnd |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modular_glm4v_moe.py | {
"start": 2133,
"end": 2191
} | class ____(Glm4vVisionConfig):
pass
| Glm4vMoeVisionConfig |
python | falconry__falcon | tests/test_cmd_inspect_app.py | {
"start": 1049,
"end": 3021
} | class ____:
@pytest.mark.parametrize(
'args, exp',
(
(
['foo'],
Namespace(
app_module='foo', route_only=False, verbose=False, internal=False
),
),
(
['foo', '-r'],
... | TestMakeParser |
python | doocs__leetcode | solution/2400-2499/2463.Minimum Total Distance Traveled/Solution.py | {
"start": 0,
"end": 668
} | class ____:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
@cache
def dfs(i, j):
if i == len(robot):
return 0
if j == len(factory):
return inf
ans = dfs(i, j + 1)
t = 0
for... | Solution |
python | scipy__scipy | scipy/stats/tests/test_multivariate.py | {
"start": 20068,
"end": 49511
} | class ____:
def test_input_shape(self):
mu = np.arange(3)
cov = np.identity(2)
assert_raises(ValueError, multivariate_normal.pdf, (0, 1), mu, cov)
assert_raises(ValueError, multivariate_normal.pdf, (0, 1, 2), mu, cov)
assert_raises(ValueError, multivariate_normal.cdf, (0, 1),... | TestMultivariateNormal |
python | pyinstaller__pyinstaller | PyInstaller/lib/modulegraph/modulegraph.py | {
"start": 26357,
"end": 26740
} | class ____(BaseModule):
def __init__(self, *args, **kwds):
warnings.warn(
"This class will be removed in a future version of modulegraph",
DeprecationWarning)
super(FlatPackage, *args, **kwds)
#FIXME: Safely removable. We don't actually use this anywhere. After removing
#th... | FlatPackage |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py | {
"start": 5706,
"end": 6053
} | class ____:
@classmethod
def good_cls_method_with_mixed_annotations(cls: "type[Self]", arg: str) -> Self: ...
@staticmethod
def good_static_method_with_string_annotations(arg: "_S") -> "_S": ...
@classmethod
def good_class_method_with_args_string_annotations(cls, arg1: "_S", arg2: "_S") -> "_S":... | GoodClassWiStringTypeHints |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.