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 | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1501452,
"end": 1501788
} | class ____(sgqlc.types.Type, GitSignature):
"""Represents an SSH signature on a Commit or Tag."""
__schema__ = github_schema
__field_names__ = ("key_fingerprint",)
key_fingerprint = sgqlc.types.Field(String, graphql_name="keyFingerprint")
"""Hex-encoded fingerprint of the key that signed this objec... | SshSignature |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 8519,
"end": 8639
} | class ____(Message):
message = "'...'.format(...) mixes automatic and manual numbering"
| StringDotFormatMixingAutomatic |
python | kamyu104__LeetCode-Solutions | Python/find-indices-of-stable-mountains.py | {
"start": 37,
"end": 300
} | class ____(object):
def stableMountains(self, height, threshold):
"""
:type height: List[int]
:type threshold: int
:rtype: List[int]
"""
return [i for i in xrange(1, len(height)) if height[i-1] > threshold]
| Solution |
python | PrefectHQ__prefect | src/prefect/_experimental/sla/objects.py | {
"start": 1549,
"end": 1995
} | class ____(ServiceLevelAgreement):
"""An SLA that triggers when a completed flow run is not detected in the specified time.
For example, if stale_after is 1 hour, if a flow run does not complete
within an hour of the previous flow run, the SLA will trigger.
"""
stale_after: timedelta = Field(
... | FrequencySla |
python | realpython__materials | python-maze-solver/source_code_final/src/maze_solver/persistence/file_format.py | {
"start": 146,
"end": 794
} | class ____:
format_version: int
width: int
height: int
@classmethod
def read(cls, file: BinaryIO) -> "FileHeader":
assert file.read(len(MAGIC_NUMBER)) == MAGIC_NUMBER, (
"Unknown file type"
)
(format_version,) = struct.unpack("B", file.read(1))
width, hei... | FileHeader |
python | python-openxml__python-docx | src/docx/image/png.py | {
"start": 7115,
"end": 8214
} | class ____(_Chunk):
"""PYHs chunk, contains the image dpi information."""
def __init__(self, chunk_type, horz_px_per_unit, vert_px_per_unit, units_specifier):
super(_pHYsChunk, self).__init__(chunk_type)
self._horz_px_per_unit = horz_px_per_unit
self._vert_px_per_unit = vert_px_per_unit... | _pHYsChunk |
python | django__django | django/db/models/fields/__init__.py | {
"start": 1915,
"end": 3025
} | class ____:
pass
# The values to use for "blank" in SelectFields. Will be appended to the start
# of most "choices" lists.
BLANK_CHOICE_DASH = [("", "---------")]
def _load_field(app_label, model_name, field_name):
return apps.get_model(app_label, model_name)._meta.get_field(field_name)
# A guide to Field... | NOT_PROVIDED |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_numeric_tower.py | {
"start": 867,
"end": 1323
} | class ____(int):
"""Dummy Integral class to test conversion of the Rational to float."""
def __mul__(self, other):
return DummyIntegral(super().__mul__(other))
__rmul__ = __mul__
def __truediv__(self, other):
return NotImplemented
__rtruediv__ = __truediv__
@property
def n... | DummyIntegral |
python | Lightning-AI__lightning | src/lightning/pytorch/plugins/layer_sync.py | {
"start": 1189,
"end": 3516
} | class ____(LayerSync):
"""A plugin that wraps all batch normalization layers of a model with synchronization logic for multiprocessing.
This plugin has no effect in single-device operation.
"""
@override
def apply(self, model: Module) -> Module:
"""Add global batchnorm for a model spread ... | TorchSyncBatchNorm |
python | fastai__fastai | fastai/data/transforms.py | {
"start": 12050,
"end": 13050
} | class ____(Categorize):
"Reversible transform of multi-category strings to `vocab` id"
loss_func,order=BCEWithLogitsLossFlat(),1
def __init__(self, vocab=None, add_na=False): super().__init__(vocab=vocab,add_na=add_na,sort=vocab==None)
def setups(self, dsets):
if not dsets: return
if se... | MultiCategorize |
python | mlflow__mlflow | mlflow/legacy_databricks_cli/configure/provider.py | {
"start": 11591,
"end": 14327
} | class ____(DatabricksConfigProvider):
"""Loads from OAuth credentials in the Databricks Model Serving environment."""
def get_config(self):
from mlflow.utils.databricks_utils import should_fetch_model_serving_environment_oauth
try:
if should_fetch_model_serving_environment_oauth():... | DatabricksModelServingConfigProvider |
python | OmkarPathak__pygorithm | tests/test_geometry.py | {
"start": 16747,
"end": 22527
} | class ____(unittest.TestCase):
def setUp(self):
self.vec_1_1 = vector2.Vector2(1, 1)
def test_constructor(self):
_aal = axisall.AxisAlignedLine(self.vec_1_1, 0, 1)
self.assertIsNotNone(_aal.axis)
self.assertIsNotNone(_aal.min)
self.assertIsNotNone(_aal.m... | TestAxisAlignedLine |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 10392,
"end": 10561
} | class ____(models.Model):
random_char_field = RandomCharField(length=8, unique=True)
class Meta:
app_label = "django_extensions"
| RandomCharTestModelUnique |
python | dask__dask | dask/dataframe/dask_expr/_rolling.py | {
"start": 4475,
"end": 4830
} | class ____(Blockwise):
_parameters = [
"frame",
"window",
"kwargs",
"how",
"how_args",
"how_kwargs",
"groupby_kwargs",
"groupby_slice",
]
operation = staticmethod(_rolling_agg)
@functools.cached_property
def _meta(self):
retur... | RollingAggregation |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_relationship.py | {
"start": 19981,
"end": 29213
} | class ____(fixtures.MappedTest, AssertsCompiledSQL):
__dialect__ = "default"
@classmethod
def define_tables(cls, metadata):
Table(
"secondary",
metadata,
Column(
"left_id", Integer, ForeignKey("parent.id"), nullable=False
),
... | SelfReferentialM2MTest |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 60460,
"end": 66191
} | class ____(StatNode):
# C variable definition or forward/extern function declaration.
#
# visibility 'private' or 'public' or 'extern'
# base_type CBaseTypeNode
# declarators [CDeclaratorNode]
# in_pxd boolean
# api boolean
# overridable boolean ... | CVarDefNode |
python | davidhalter__jedi | test/completion/generators.py | {
"start": 685,
"end": 1031
} | class ____():
def __iter__(self):
if random.choice([0, 1]):
yield 1
else:
yield ""
b = []
for a in Get():
#? int() str()
a
b += [a]
#? list()
b
#? int() str()
b[0]
g = iter(Get())
#? int() str()
next(g)
g = iter([1.0])
#? float()
next(g)
x, y = Get()
#? int()... | Get |
python | walkccc__LeetCode | solutions/2282. Number of People That Can Be Seen in a Grid/2282.py | {
"start": 0,
"end": 994
} | class ____:
def seePeople(self, heights: list[list[int]]) -> list[list[int]]:
m = len(heights)
n = len(heights[0])
ans = [[0] * n for _ in range(m)]
for i, row in enumerate(heights):
stack = []
for j, height in enumerate(row):
hasEqualHeight = False
while stack and row[sta... | Solution |
python | python-poetry__poetry | src/poetry/repositories/lockfile_repository.py | {
"start": 188,
"end": 549
} | class ____(Repository):
"""
Special repository that distinguishes packages not only by name and version,
but also by source type, url, etc.
"""
def __init__(self) -> None:
super().__init__("poetry-lockfile")
def has_package(self, package: Package) -> bool:
return any(p == packa... | LockfileRepository |
python | spyder-ide__spyder | spyder/widgets/reporterror.py | {
"start": 4062,
"end": 4652
} | class ____(TracebackLinksMixin, ConsoleBaseWidget, BaseEditMixin,
SpyderFontsMixin):
"""Widget to show errors as they appear in the Internal console."""
QT_CLASS = QPlainTextEdit
sig_go_to_error_requested = Signal(str)
def __init__(self, parent=None):
ConsoleBaseWidget.__i... | ShowErrorWidget |
python | rapidsai__cudf | python/cudf/cudf/core/column/column.py | {
"start": 3712,
"end": 4204
} | class ____:
# A wrapper that exposes the __cuda_array_interface__ of a mask that accounts for
# the mask being a bitmask in the mask size calculation.
def __init__(self, mask: Any) -> None:
self._mask = mask
@property
def __cuda_array_interface__(self) -> Mapping:
cai = self._mask.... | MaskCAIWrapper |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 87309,
"end": 88028
} | class ____(INT8MMTemplateConfigMixin, ROCmConfigHeuristic):
"""Int8 MM template heuristic for ROCm"""
def __init__(self) -> None:
super().__init__()
# Override mm_configs to use int8_mm_configs
self.mm_configs = self.int8_mm_configs
# NOTE: overriding exhaustive configs here to ... | ROCmInt8MMTemplateConfigHeuristic |
python | coleifer__peewee | playhouse/cockroachdb.py | {
"start": 7472,
"end": 9083
} | class ____(_atomic):
def __enter__(self):
if self.db.transaction_depth() > 0:
if not isinstance(self.db.top_transaction(), _manual):
raise NotImplementedError(TXN_ERR_MSG)
return super(_crdb_atomic, self).__enter__()
def run_transaction(db, callback, max_attempts=None, ... | _crdb_atomic |
python | pypa__warehouse | tests/unit/admin/views/test_projects.py | {
"start": 31448,
"end": 34888
} | class ____:
def test_add_role(self, db_request):
role_name = "Maintainer"
project = ProjectFactory.create(name="foo")
UserFactory.create(username="admin")
user = UserFactory.create(username="bar")
db_request.route_path = pretend.call_recorder(lambda *a, **kw: "/the-redirect/... | TestAddRole |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/dynamic_rendezvous.py | {
"start": 10329,
"end": 10918
} | class ____(ABC):
"""Hold the shared rendezvous state synced with other nodes."""
@property
@abstractmethod
def state(self) -> _RendezvousState:
"""Get the local state."""
@abstractmethod
def sync(self) -> bool | None:
"""Read or writes the latest state.
Returns:
... | _RendezvousStateHolder |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_asyncio.py | {
"start": 2014,
"end": 2686
} | class ____(TestCase):
# In principle, these tests could indeed run on emscripten if we grab the existing
# event loop and run them there. However, that seems to have hit an infinite loop
# and so we're just skipping them for now and will revisit later.
def execute_example(self, f):
asyncio.run... | TestAsyncioRun |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 48823,
"end": 50599
} | class ____(fixtures.MappedTest):
"""Syncrules on foreign keys that are also primary"""
@classmethod
def define_tables(cls, metadata):
Table(
"tableA",
metadata,
Column("id", Integer, primary_key=True),
Column("foo", Integer),
test_needs_fk... | SynonymsAsFKsTest |
python | pallets__jinja | src/jinja2/ext.py | {
"start": 20565,
"end": 20931
} | class ____(Extension):
"""Adds a `do` tag to Jinja that works like the print statement just
that it doesn't print the return value.
"""
tags = {"do"}
def parse(self, parser: "Parser") -> nodes.ExprStmt:
node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
node.node = parser.par... | ExprStmtExtension |
python | kamyu104__LeetCode-Solutions | Python/convert-a-number-to-hexadecimal.py | {
"start": 32,
"end": 510
} | class ____(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if not num:
return "0"
result = []
while num and len(result) != 8:
h = num & 15
if h < 10:
result.append(str(chr(ord('0') + h)))
... | Solution |
python | numba__numba | numba/tests/test_globals.py | {
"start": 2586,
"end": 7329
} | class ____(unittest.TestCase):
def check_global_ndarray(self, **jitargs):
# (see github issue #448)
ctestfunc = jit(**jitargs)(global_ndarray_func)
self.assertEqual(ctestfunc(1), 11)
def test_global_ndarray(self):
# This also checks we can access an unhashable global value
... | TestGlobals |
python | getsentry__sentry | tests/sentry/api/serializers/test_fields.py | {
"start": 618,
"end": 1620
} | class ____(unittest.TestCase):
def test_simple(self) -> None:
data = {"a_field": [{"b_field": "abcdefg", "d_field": "gfedcba"}]}
serializer = DummySerializer(data=data)
assert serializer.is_valid()
assert serializer.validated_data == {
"a_field": [{"b_field": "abcdefg", ... | TestListField |
python | doocs__leetcode | solution/1700-1799/1774.Closest Dessert Cost/Solution.py | {
"start": 0,
"end": 866
} | class ____:
def closestCost(
self, baseCosts: List[int], toppingCosts: List[int], target: int
) -> int:
def dfs(i, t):
if i >= len(toppingCosts):
arr.append(t)
return
dfs(i + 1, t)
dfs(i + 1, t + toppingCosts[i])
arr = ... | Solution |
python | openai__openai-python | src/openai/types/file_create_params.py | {
"start": 1021,
"end": 1394
} | class ____(TypedDict, total=False):
anchor: Required[Literal["created_at"]]
"""Anchor timestamp after which the expiration policy applies.
Supported anchors: `created_at`.
"""
seconds: Required[int]
"""The number of seconds after the anchor time that the file will expire.
Must be between ... | ExpiresAfter |
python | mahmoud__glom | glom/grouping.py | {
"start": 7948,
"end": 9163
} | class ____:
"""
Limits the number of values passed to sub-accumulator
>>> glom([1, 2, 3], Group(Limit(2)))
[1, 2]
To override the default untransformed list output, set the subspec kwarg:
>>> glom(range(10), Group(Limit(3, subspec={(lambda x: x % 2): [T]})))
{0: [0, 2], 1: [1]}
You c... | Limit |
python | ray-project__ray | python/ray/dag/tests/experimental/test_compiled_graphs.py | {
"start": 16401,
"end": 29749
} | class ____:
def test_multi_args_basic(self, ray_start_regular):
a1 = Actor.remote(0)
a2 = Actor.remote(0)
c = Collector.remote()
with InputNode() as i:
branch1 = a1.inc.bind(i[0])
branch2 = a2.inc.bind(i[1])
dag = c.collect_two.bind(branch2, branch... | TestMultiArgs |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/abc.py | {
"start": 22,
"end": 905
} | class ____(ABC):
"""An abstract base class for Rich renderables.
Note that there is no need to extend this class, the intended use is to check if an
object supports the Rich renderable protocol. For example::
if isinstance(my_object, RichRenderable):
console.print(my_object)
"""
... | RichRenderable |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchExhaustion1.py | {
"start": 1173,
"end": 1383
} | class ____:
def method1(self) -> str:
match self:
case ClassA():
return ""
def func7() -> int:
match [10]:
case [*values]:
return values[0]
| ClassA |
python | walkccc__LeetCode | solutions/1272. Remove Interval/1272.py | {
"start": 0,
"end": 476
} | class ____:
def removeInterval(self, intervals: list[list[int]],
toBeRemoved: list[int]) -> list[list[int]]:
ans = []
for a, b in intervals:
if a >= toBeRemoved[1] or b <= toBeRemoved[0]:
ans.append([a, b])
else: # a < toBeRemoved[1] and b > toBeRemoved[0]
if... | Solution |
python | huggingface__transformers | src/transformers/models/smolvlm/modeling_smolvlm.py | {
"start": 12023,
"end": 14604
} | class ____(SmolVLMPreTrainedModel):
config: SmolVLMVisionConfig
input_modalities = ("image",)
_supports_sdpa = True
_supports_flash_attn = True
_supports_flex_attn = True
_can_record_outputs = {
"hidden_states": SmolVLMEncoderLayer,
"attentions": SmolVLMVisionAttention,
}
... | SmolVLMVisionTransformer |
python | Lightning-AI__lightning | tests/tests_fabric/helpers/datasets.py | {
"start": 132,
"end": 429
} | class ____(Dataset):
def __init__(self, size: int, length: int) -> None:
self.len = length
self.data = torch.randn(length, size)
def __getitem__(self, index: int) -> Tensor:
return self.data[index]
def __len__(self) -> int:
return self.len
| RandomDataset |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_sql.py | {
"start": 29972,
"end": 34072
} | class ____(CloudSQLBaseOperator):
"""
Update resource containing information about a database using patch semantics.
See: https://cloud.google.com/sql/docs/mysql/admin-api/how-tos/performance#patch
.. seealso::
For more information on how to use this operator, take a look at the guide:
... | CloudSQLPatchInstanceDatabaseOperator |
python | huggingface__transformers | tests/models/olmo/test_modeling_olmo.py | {
"start": 1500,
"end": 5835
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=False,
use_labels=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=2,
num_attention_hea... | OlmoModelTester |
python | getsentry__sentry | src/sentry/utils/marketo_client.py | {
"start": 151,
"end": 220
} | class ____(TypedDict):
errors: list[ErrorDict]
| MarketoErrorResponse |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-modelscope/llama_index/embeddings/modelscope/base.py | {
"start": 725,
"end": 3753
} | class ____(BaseEmbedding):
"""ModelScope Embedding."""
model_name: str = Field(
default=DEFAULT_MODELSCOPE_MODEL,
description=(
"The model name to use from ModelScope. "
"Unused if `model` is passed in directly."
),
)
model_revision: str = Field(
... | ModelScopeEmbedding |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 120225,
"end": 120411
} | class ____(Numeric[_N]):
"""The SQL NUMERIC type.
.. seealso::
:class:`_types.Numeric` - documentation for the base type.
"""
__visit_name__ = "NUMERIC"
| NUMERIC |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 24653,
"end": 24794
} | class ____(models.Model):
name = models.CharField(max_length=15, unique=True)
history = HistoricalRecords()
| TestOrganizationWithHistory |
python | PrefectHQ__prefect | tests/server/models/test_saved_searches.py | {
"start": 2174,
"end": 2918
} | class ____:
async def test_read_saved_search_by_id(self, session):
saved_search = await models.saved_searches.create_saved_search(
session=session,
saved_search=schemas.core.SavedSearch(
name="My SavedSearch",
),
)
read_saved_search = awai... | TestReadSavedSearch |
python | ray-project__ray | python/ray/serve/_private/benchmarks/streaming/streaming_handle_throughput.py | {
"start": 175,
"end": 240
} | class ____(Endpoint):
pass
@serve.deployment
| EndpointDeployment |
python | django__django | django/views/generic/edit.py | {
"start": 6280,
"end": 6479
} | class ____(SingleObjectTemplateResponseMixin, BaseCreateView):
"""
View for creating a new object, with a response rendered by a template.
"""
template_name_suffix = "_form"
| CreateView |
python | vyperlang__vyper | vyper/semantics/types/primitives.py | {
"start": 3536,
"end": 8120
} | class ____(_PrimT):
_is_signed: bool
_bits: int
_invalid_ops: tuple
# the type this can assume in the AST
ast_type: type
@property
def ast_bounds(self):
raise NotImplementedError("should be overridden!")
# get the integer bounds on IR values of this type.
# note the distin... | NumericT |
python | falconry__falcon | examples/things_advanced_asgi.py | {
"start": 2803,
"end": 4693
} | class ____:
# NOTE: Normally you would simply use req.get_media() and resp.media for
# this particular use case; this example serves only to illustrate
# what is possible.
async def process_request(self, req, resp):
# NOTE: Test explicitly for 0, since this property could be None in
# t... | JSONTranslator |
python | oauthlib__oauthlib | oauthlib/openid/connect/core/endpoints/pre_configured.py | {
"start": 1069,
"end": 5449
} | class ____(
AuthorizationEndpoint,
IntrospectEndpoint,
TokenEndpoint,
ResourceEndpoint,
RevocationEndpoint,
UserInfoEndpoint,
):
"""
An all-in-one endpoint featuring all four major grant types
and extension grants.
"""
def __init__(
self,
request_validator,
... | Server |
python | sqlalchemy__sqlalchemy | test/sql/test_selectable.py | {
"start": 94730,
"end": 97270
} | class ____(fixtures.TestBase, AssertsExecutionResults):
def test_table(self):
meta = MetaData()
t1 = Table(
"t1",
meta,
Column("c1", Integer, primary_key=True),
Column("c2", String(30)),
)
t2 = Table(
"t2",
meta... | DerivedTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 533427,
"end": 534176
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CreateAttributionInvitation"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "owner", "source", "target")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for th... | CreateAttributionInvitationPayload |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_autofit04.py | {
"start": 315,
"end": 945
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("autofit04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_fil... | TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/1639. Number of Ways to Form a Target String Given a Dictionary/1639-2.py | {
"start": 0,
"end": 951
} | class ____:
def numWays(self, words: list[str], target: str) -> int:
MOD = 1_000_000_007
wordLength = len(words[0])
# dp[i][j] := the number of ways to form the first i characters of the
# `target` using the j first characters in each word
dp = [[0] * (wordLength + 1) for _ in range(len(target) + ... | Solution |
python | plotly__plotly.py | plotly/graph_objs/scatterpolar/marker/colorbar/_title.py | {
"start": 233,
"end": 4056
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolar.marker.colorbar"
_path_str = "scatterpolar.marker.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance... | Title |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py | {
"start": 12155,
"end": 15915
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen2_5_VLModel`]. It is used to instantiate a
Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar c... | Qwen2_5_VLConfig |
python | ray-project__ray | python/ray/_private/runtime_env/_clonevirtualenv.py | {
"start": 365,
"end": 10970
} | class ____(Exception):
pass
def _dirmatch(path, matchwith):
"""Check if path is within matchwith's tree.
>>> _dirmatch('/home/foo/bar', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/etc', '/home/foo/bar')
True
>>> _dirmatch... | UserError |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 75696,
"end": 77266
} | class ____:
def test_timeframes(self):
assert self.locale._format_timeframe("hours", 2) == "2 ore"
assert self.locale._format_timeframe("months", 2) == "2 luni"
assert self.locale._format_timeframe("days", 2) == "2 zile"
assert self.locale._format_timeframe("years", 2) == "2 ani"
... | TestRomanianLocale |
python | numba__numba | numba/tests/test_svml.py | {
"start": 6474,
"end": 11118
} | class ____(TestCase):
""" Tests all SVML-generating functions produce desired calls """
# env mutating, must not run in parallel
_numba_parallel_test_ = False
# RE for a generic symbol reference and for each particular SVML function
asm_filter = re.compile('|'.join([r'\$[a-z_]\w+,']+list(svml_funcs... | TestSVMLGeneration |
python | tiangolo__fastapi | docs_src/schema_extra_example/tutorial005.py | {
"start": 110,
"end": 1386
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
@app.put("/items/{item_id}")
async def update_item(
*,
item_id: int,
item: Item = Body(
openapi_examples={
"normal": {
"summary": "A normal ... | Item |
python | walkccc__LeetCode | solutions/1943. Describe the Painting/1943.py | {
"start": 42,
"end": 500
} | class ____:
def splitPainting(self, segments: list[list[int]]) -> list[list[int]]:
ans = []
prevIndex = 0
runningMix = 0
line = SortedDict()
for start, end, color in segments:
line[start] = line.get(start, 0) + color
line[end] = line.get(end, 0) - color
for i, mix in line.items()... | Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/publish/pipeline.py | {
"start": 6630,
"end": 8608
} | class ____(Step):
context: PublishConnectorContext
title = "Push connector image to registry"
@property
def latest_docker_image_name(self) -> str:
return f"{self.context.docker_repository}:latest"
@property
def should_push_latest_tag(self) -> bool:
"""
We don't want to ... | PushConnectorImageToRegistry |
python | spack__spack | lib/spack/docs/conf.py | {
"start": 7969,
"end": 20377
} | class ____(RSTParser):
def parse(self, inputstring, document):
if isinstance(inputstring, str):
lines = inputstring.splitlines()
inputstring = StringList(lines, document.current_source)
super().parse(inputstring, document)
def add_package_api_version_line(app, what, name: s... | NoTabExpansionRSTParser |
python | wandb__wandb | wandb/sdk/internal/thread_local_settings.py | {
"start": 197,
"end": 527
} | class ____(threading.local):
api_key: Optional[str]
cookies: Optional[Dict]
headers: Optional[Dict]
def __init__(self) -> None:
self.api_key = None
self.cookies = None
self.headers = None
_thread_local_api_settings: _ThreadLocalApiSettings = _ThreadLocalApiSettings()
| _ThreadLocalApiSettings |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/rnn_test.py | {
"start": 26943,
"end": 32577
} | class ____(test.Benchmark):
def benchmarkGraphCreationStaticVsDynamicLSTM(self):
print("Graph Creation: Static Unroll vs. Dynamic Unroll LSTM")
print("max_t \t dt(static) \t dt(dynamic) \t dt(dynamic)/dt(static)")
for max_time in (1, 25, 50):
s_dt, d_dt = graph_creation_static_vs_dynamic_rnn_benchm... | BenchmarkRNN |
python | google__pytype | pytype/tests/test_utils.py | {
"start": 6369,
"end": 6833
} | class ____:
"""Mixin providing a method to check in-place operators."""
_HAS_DYNAMIC_ATTRIBUTES = True
def _check_inplace(self, op, assignments, expected_return):
"""Check the inplace operator."""
assignments = "; ".join(assignments)
src = f"""
def f(x, y):
{assignments}
x {op}... | InplaceTestMixin |
python | keras-team__keras | keras/src/losses/losses_test.py | {
"start": 17942,
"end": 20256
} | class ____(testing.TestCase):
def test_unweighted(self):
y_true = np.array([[0.0, 1.0], [0.0, 0.0]])
y_pred = np.array([[0.6, 0.4], [0.4, 0.6]])
# Reduction = "sum_over_batch_size"
hinge_obj = losses.CategoricalHinge(reduction="sum_over_batch_size")
loss = hinge_obj(y_true, ... | CategoricalHingeTest |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_url_is_available.py | {
"start": 883,
"end": 1870
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.url_is_available"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas... | ColumnValuesUrlIsAvailable |
python | ray-project__ray | python/ray/tests/test_runtime_env_plugin.py | {
"start": 11308,
"end": 11941
} | class ____(RuntimeEnvPlugin):
name = PRIORITY_TEST_PLUGIN1_NAME
priority = 11
env_value = " world"
@staticmethod
def validate(runtime_env_dict: dict) -> str:
return None
def modify_context(
self,
uris: List[str],
plugin_config_dict: dict,
ctx: RuntimeEnv... | PriorityTestPlugin1 |
python | plotly__plotly.py | codegen/utils.py | {
"start": 31597,
"end": 32793
} | class ____(PlotlyNode):
"""
Class representing datatypes in the frames hierarchy
"""
# Constructor
def __init__(self, plotly_schema, node_path=(), parent=None):
super().__init__(plotly_schema, node_path, parent)
@property
def name_base_datatype(self):
return "BaseFrameHiera... | FrameNode |
python | huggingface__transformers | tests/models/dpt/test_image_processing_dpt.py | {
"start": 1157,
"end": 3537
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_normalize=True,
image_mean=[0.5, 0.5, 0.5],
image_std=[0.5, 0.5, 0... | DPTImageProcessingTester |
python | redis__redis-py | redis/multidb/failover.py | {
"start": 1796,
"end": 3575
} | class ____(FailoverStrategyExecutor):
"""
Executes given failover strategy.
"""
def __init__(
self,
strategy: FailoverStrategy,
failover_attempts: int = DEFAULT_FAILOVER_ATTEMPTS,
failover_delay: float = DEFAULT_FAILOVER_DELAY,
):
self._strategy = strategy
... | DefaultFailoverStrategyExecutor |
python | astropy__astropy | astropy/io/votable/tree.py | {
"start": 60716,
"end": 64610
} | class ____(SimpleElement):
"""
TIMESYS_ element: defines a time system.
The keyword arguments correspond to setting members of the same
name, documented below.
"""
_attr_list = ["ID", "timeorigin", "timescale", "refposition"]
_element_name = "TIMESYS"
def __init__(
self,
... | TimeSys |
python | apache__airflow | providers/teradata/src/airflow/providers/teradata/utils/constants.py | {
"start": 822,
"end": 3090
} | class ____:
"""Define constants for Teradata Provider."""
CC_CREATE_OPR = "CREATE"
CC_CREATE_SUSPEND_OPR = "CREATE_SUSPEND"
CC_DROP_OPR = "DROP"
CC_SUSPEND_OPR = "SUSPEND"
CC_RESUME_OPR = "RESUME"
CC_INITIALIZE_DB_STATUS = "Initializing"
CC_SUSPEND_DB_STATUS = "Suspended"
CC_RESUME_... | Constants |
python | ray-project__ray | rllib/examples/_old_api_stack/policy/cliff_walking_wall_policy.py | {
"start": 500,
"end": 4181
} | class ____(Policy):
"""Optimal RLlib policy for the CliffWalkingWallEnv environment, defined in
ray/rllib/examples/env/cliff_walking_wall_env.py, with epsilon-greedy exploration.
The policy takes a random action with probability epsilon, specified
by `config["epsilon"]`, and the optimal action with pro... | CliffWalkingWallPolicy |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_supervisor.py | {
"start": 4580,
"end": 6294
} | class ____:
@pytest.mark.parametrize(
("server", "dry_run", "expectation"),
[
("/execution/", False, pytest.raises(ValueError, match="Invalid execution API server URL")),
("", False, pytest.raises(ValueError, match="Invalid execution API server URL")),
("http://lo... | TestSupervisor |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 88802,
"end": 89321
} | class ____(_PrintableStructure):
_fields_ = [("version", c_uint),
("revision", c_uint),
("hostDriverVersion", c_char * NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE),
("pgpuVirtualizationCaps", c_uint),
("reserved", c_uint * 5),
("hostSupporte... | c_nvmlVgpuPgpuMetadata_t |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 87807,
"end": 88421
} | class ____:
xlPivotCellBlankCell = 9 # from enum XlPivotCellType
xlPivotCellCustomSubtotal = 7 # from enum XlPivotCellType
xlPivotCellDataField = 4 # from enum XlPivotCellType
xlPivotCellDataPivotField = 8 # from enum XlPivotCellType
xlPivotCellGrandTotal = 3 # from enum XlPivotCellType
xlP... | PivotCellType |
python | lazyprogrammer__machine_learning_examples | hmm_class/hmmd_theano2.py | {
"start": 803,
"end": 4851
} | class ____:
def __init__(self, M):
self.M = M # number of hidden states
def fit(self, X, learning_rate=0.001, max_iter=10, V=None, print_period=1):
# train the HMM model using stochastic gradient descent
# print "X to train:", X
# determine V, the vocabulary size
# ... | HMM |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 16847,
"end": 16955
} | class ____(PydanticValueError):
msg_template = 'could not interpret byte unit: {unit}'
| InvalidByteSizeUnit |
python | vyperlang__vyper | vyper/venom/passes/cfg_normalization.py | {
"start": 251,
"end": 4826
} | class ____(IRPass):
"""
This pass splits basic blocks when there are multiple conditional predecessors.
The code generator expect a normalized CFG, that has the property that
each basic block has at most one conditional predecessor.
"""
cfg: CFGAnalysis
changes = 0
def _get_phi_instru... | CFGNormalization |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/rebatch_dataset_test.py | {
"start": 1499,
"end": 6511
} | class ____(test_base.DatasetTestBase,
parameterized.TestCase):
def _test(self, global_batch_size, num_workers, num_replicas_per_worker,
is_batch_size_static):
"""Test that all constraints are met for given parameters."""
if not is_batch_size_static:
# Adding a ... | BatchSizesForWorkerTest |
python | huggingface__transformers | src/transformers/models/mobilevitv2/modeling_mobilevitv2.py | {
"start": 6037,
"end": 6801
} | class ____(nn.Module):
def __init__(
self, config: MobileViTV2Config, in_channels: int, out_channels: int, stride: int = 1, num_stages: int = 1
) -> None:
super().__init__()
self.layer = nn.ModuleList()
for i in range(num_stages):
layer = MobileViTV2InvertedResidual(... | MobileViTV2MobileNetLayer |
python | buildout__buildout | src/zc/buildout/buildout.py | {
"start": 59017,
"end": 90057
} | class ____(DictMixin):
def __init__(self, buildout, section, data):
self.buildout = buildout
self.name = section
self._raw = data
self._cooked = {}
self._data = {}
def _initialize(self):
name = self.name
__doing__ = 'Initializing section %s.', name
... | Options |
python | viewflow__viewflow | viewflow/conf.py | {
"start": 889,
"end": 1743
} | class ____(object):
def __init__(self, custom=None):
if custom is None:
custom = getattr(django_settings, "VIEWFLOW", {})
self.settings = deepcopy(DEFAULTS)
for key, value in custom.get("WIDGET_RENDERERS", {}).items():
widget_class, renderer_class = import_string(key... | Settings |
python | sympy__sympy | sympy/vector/deloperator.py | {
"start": 93,
"end": 3191
} | class ____(Basic):
"""
Represents the vector differential operator, usually represented in
mathematical expressions as the 'nabla' symbol.
"""
def __new__(cls):
obj = super().__new__(cls)
obj._name = "delop"
return obj
def gradient(self, scalar_field, doit=False):
... | Del |
python | PyCQA__pylint | doc/exts/pylint_options.py | {
"start": 795,
"end": 8140
} | class ____(NamedTuple):
name: str
optdict: OptionDict
checker: BaseChecker
extension: bool
OptionsDataDict = dict[str, list[OptionsData]]
PYLINT_BASE_PATH = Path(__file__).resolve().parent.parent.parent
"""Base path to the project folder."""
PYLINT_USERGUIDE_PATH = PYLINT_BASE_PATH / "doc" / "user_g... | OptionsData |
python | getsentry__sentry | tests/sentry/rules/filters/test_latest_adopted_release.py | {
"start": 187,
"end": 7588
} | class ____(RuleTestCase):
rule_cls = LatestAdoptedReleaseFilter
def test_semver(self) -> None:
event = self.get_event()
now = datetime.now(UTC)
prod = self.create_environment(name="prod")
test = self.create_environment(name="test")
newest_release = self.create_release(
... | LatestAdoptedReleaseFilterTest |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 52896,
"end": 57890
} | class ____(BaseConfigHeuristic):
"""
Placeholder child class for Intel GPU specific overrides.
"""
def __init__(self) -> None:
super().__init__()
self.xpu_default_flex_config = {
(torch.float32, 64): FlexConfig(128, 32, 1, 16),
(torch.float32, 128): FlexConfig(12... | XPUConfigHeuristic |
python | pyinstaller__pyinstaller | PyInstaller/archive/writers.py | {
"start": 14825,
"end": 20744
} | class ____:
"""
Writer for the splash screen resources archive.
The resulting archive is added as an entry into the CArchive with the typecode PKG_ITEM_SPLASH.
"""
# This struct describes the splash resources as it will be in an buffer inside the bootloader. All necessary parts
# are bundled, t... | SplashWriter |
python | google__jax | tests/debug_nans_test.py | {
"start": 959,
"end": 7091
} | class ____(jtu.JaxTestCase):
def testSinc(self):
# Regression test for #6936
self.assertEqual(jnp.sinc(0.0), 1.0)
def testSingleResultPrimitiveNoNaN(self):
A = jnp.array([[1., 2.], [2., 3.]])
ans = jnp.tanh(A)
ans.block_until_ready()
def testMultipleResultPrimitiveNoNaN(self):
A = jnp.a... | DebugNaNsTest |
python | catalyst-team__catalyst | examples/detection/dataset.py | {
"start": 8272,
"end": 12795
} | class ____(Dataset):
def __init__(self, coco_json_path, images_dir=None, transforms=None, down_ratio=4):
self.file = coco_json_path
self.img_dir = images_dir
self.transforms = transforms
self.down_ratio = down_ratio
self.images, self.categories = load_coco_json(coco_json_pat... | CenterNetDataset |
python | huggingface__transformers | tests/models/sam2/test_modeling_sam2.py | {
"start": 4630,
"end": 10832
} | class ____(ModelTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as SAM's vision encoder does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (Sam2VisionModel,) if is_torch_available() else ()
tes... | Sam2VisionModelTest |
python | getsentry__sentry | src/sentry/sentry_apps/external_requests/issue_link_requester.py | {
"start": 1159,
"end": 1251
} | class ____(StrEnum):
CREATE = "create"
LINK = "link"
@dataclass
| IssueRequestActionType |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 12542,
"end": 12802
} | class ____(sgqlc.types.Enum):
"""The possible sides of a diff.
Enumeration Choices:
* `LEFT`: The left side of the diff.
* `RIGHT`: The right side of the diff.
"""
__schema__ = github_schema
__choices__ = ("LEFT", "RIGHT")
| DiffSide |
python | huggingface__transformers | src/transformers/models/xlm_roberta/modeling_xlm_roberta.py | {
"start": 22270,
"end": 23682
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([XLMRobertaLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: ... | XLMRobertaEncoder |
python | pypa__warehouse | warehouse/cache/interfaces.py | {
"start": 78,
"end": 802
} | class ____(Interface):
"""
A cache for expensive/slow database query results.
Example usage:
>>> some_expensive_query = request.db.query(...)
>>> cache_service = request.find_service(IQueryResultsCache)
>>> cache_service.set("some_key_name", some_expensive_query)
# Later, retrieve the cac... | IQueryResultsCache |
python | allegroai__clearml | clearml/backend_api/services/v2_20/workers.py | {
"start": 84968,
"end": 85221
} | class ____(Response):
"""
Response of workers.status_report endpoint.
"""
_service = "workers"
_action = "status_report"
_version = "2.20"
_schema = {"definitions": {}, "properties": {}, "type": "object"}
| StatusReportResponse |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.