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 | doocs__leetcode | solution/3500-3599/3528.Unit Conversion I/Solution.py | {
"start": 0,
"end": 450
} | class ____:
def baseUnitConversions(self, conversions: List[List[int]]) -> List[int]:
def dfs(s: int, mul: int) -> None:
ans[s] = mul
for t, w in g[s]:
dfs(t, mul * w % mod)
mod = 10**9 + 7
n = len(conversions) + 1
g = [[] for _ in range(n)]
... | Solution |
python | pytorch__pytorch | test/test_sparse.py | {
"start": 195900,
"end": 198194
} | class ____(TestCase):
exact_dtype = True
fp16_low_precision_list = {
'masked.prod',
}
@ops(sparse_masked_reduction_ops)
def test_future_empty_dim(self, device, dtype, op):
"""Currently, `dim=()` in reductions operations means "reduce over
all dimensions" while in future, it... | TestSparseMaskedReductions |
python | getsentry__sentry | src/sentry/replays/lib/event_linking.py | {
"start": 216,
"end": 566
} | class ____(TypedDict):
type: str
start_time: int
replay_id: str
project_id: int
segment_id: None
payload: (
EventLinkPayloadDebugId
| EventLinkPayloadInfoId
| EventLinkPayloadWarningId
| EventLinkPayloadErrorId
| EventLinkPayloadFatalId
)
retention... | EventLinkKafkaMessage |
python | neetcode-gh__leetcode | python/1472-design-browser-history.py | {
"start": 793,
"end": 1438
} | class ____:
def __init__(self, homepage: str):
self.i = 0
self.len = 1
self.history = [homepage]
# O(1)
def visit(self, url: str) -> None:
if len(self.history) < self.i + 2:
self.history.append(url)
else:
self.history[self.i + 1] = url
... | BrowserHistory |
python | jazzband__django-waffle | waffle/migrations/0003_update_strings_for_i18n.py | {
"start": 152,
"end": 6755
} | class ____(migrations.Migration):
dependencies = [
('waffle', '0002_auto_20161201_0958'),
]
operations = [
migrations.AlterModelOptions(
name='flag',
options={'verbose_name': 'Flag', 'verbose_name_plural': 'Flags'},
),
migrations.AlterModelOptions(
... | Migration |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 42508,
"end": 43258
} | class ____(TestCase):
@override_settings(LANGUAGE_CODE='pl')
def test_to_internal_value(self):
field = serializers.DecimalField(max_digits=2, decimal_places=1, localize=True)
assert field.to_internal_value('1,1') == Decimal('1.1')
@override_settings(LANGUAGE_CODE='pl')
def test_to_repre... | TestLocalizedDecimalField |
python | google__jax | jax/_src/lib/triton.py | {
"start": 710,
"end": 839
} | class ____(Protocol):
asm: str
smem_bytes: int
cluster_dim_x: int
cluster_dim_y: int
cluster_dim_z: int
| CompilationResult |
python | doocs__leetcode | lcci/16.05.Factorial Zeros/Solution.py | {
"start": 0,
"end": 154
} | class ____:
def trailingZeroes(self, n: int) -> int:
ans = 0
while n:
n //= 5
ans += n
return ans
| Solution |
python | pytorch__pytorch | torch/_logging/_internal.py | {
"start": 39025,
"end": 44249
} | class ____(logging.StreamHandler):
"""Like FileHandler, but the file is allocated lazily only upon the first log message"""
def __init__(self, root_dir: Optional[str]) -> None:
# This is implemented in the same way that delay is implemented on
# FileHandler
self.root_dir = root_dir
... | LazyTraceHandler |
python | pytest-dev__pytest | testing/test_warnings.py | {
"start": 19151,
"end": 22642
} | class ____:
@staticmethod
def assert_result_warns(result, msg) -> None:
result.stdout.fnmatch_lines([f"*PytestAssertRewriteWarning: {msg}*"])
def test_tuple_warning(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""\
def test_foo():
assert (1... | TestAssertionWarnings |
python | scikit-learn__scikit-learn | sklearn/datasets/_openml.py | {
"start": 6738,
"end": 41840
} | class ____(ValueError):
"""HTTP 412 is a specific OpenML error code, indicating a generic error"""
pass
def _get_json_content_from_openml_api(
url: str,
error_message: Optional[str],
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> Dict:
"""
Loads json data f... | OpenMLError |
python | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 56643,
"end": 57297
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_f... | BigBirdIntermediate |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 33944,
"end": 34145
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("ORGANIZATION", "REPOSITORY", "USER")
| RepositoryInteractionLimitOrigin |
python | walkccc__LeetCode | solutions/63. Unique Paths II/63-2.py | {
"start": 0,
"end": 349
} | class ____:
def uniquePathsWithObstacles(self, obstacleGrid: list[list[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [0] * n
dp[0] = 1
for i in range(m):
for j in range(n):
if obstacleGrid[i][j]:
dp[j] = 0
elif j > 0:
dp[j] += dp[j - ... | Solution |
python | pyparsing__pyparsing | examples/inv_regex.py | {
"start": 1565,
"end": 2133
} | class ____:
def __init__(self, exprs):
self.exprs = ParseResults(exprs)
def make_generator(self):
def group_gen():
def recurse_list(elist):
if len(elist) == 1:
yield from elist[0].make_generator()()
else:
for s ... | GroupEmitter |
python | davidhalter__parso | test/normalizer_issue_files/E29.py | {
"start": 40,
"end": 144
} | class ____(object):
bang = 12
#: W291+1:34
'''multiline
string with trailing whitespace'''
| Foo |
python | uqfoundation__dill | dill/_dill.py | {
"start": 36074,
"end": 36237
} | class ____(object):
def __init__(self):
self.items = []
def __getitem__(self, item):
self.items.append(item)
return
| _itemgetter_helper |
python | coleifer__peewee | tests/regressions.py | {
"start": 62526,
"end": 65943
} | class ____(ModelTestCase):
@requires_models(Character, Shape, ShapeDetail)
def test_delete_instance_dfs_nullable(self):
c1, c2 = [Character.create(name=name) for name in ('c1', 'c2')]
for c in (c1, c2):
s = Shape.create(character=c)
ShapeDetail.create(shape=s)
# ... | TestDeleteInstanceDFS |
python | milvus-io__pymilvus | tests/test_bulk_writer_buffer.py | {
"start": 14540,
"end": 31347
} | class ____:
"""Extended tests to cover additional edge cases and error paths in buffer.py"""
@pytest.fixture
def schema_with_array(self):
"""Schema with array field for testing array error handling"""
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
... | TestBufferExtended |
python | huggingface__transformers | src/transformers/models/funnel/modeling_funnel.py | {
"start": 46166,
"end": 49573
} | class ____(FunnelPreTrainedModel):
def __init__(self, config: FunnelConfig) -> None:
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.funnel = FunnelBaseModel(config)
self.classifier = FunnelClassificationHead(config, config.num_labels)
... | FunnelForSequenceClassification |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 8884,
"end": 9231
} | class ____(AtomicRule):
"""integrate(1/sqrt(a+b*x+c*x**2), x) -> log(2*sqrt(c)*sqrt(a+b*x+c*x**2)+b+2*c*x)/sqrt(c)"""
a: Expr
b: Expr
c: Expr
def eval(self) -> Expr:
a, b, c, x = self.a, self.b, self.c, self.variable
return log(2*sqrt(c)*sqrt(a+b*x+c*x**2)+b+2*c*x)/sqrt(c)
@datacl... | ReciprocalSqrtQuadraticRule |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 243930,
"end": 244080
} | class ____(Structure):
_fields_ = [
("shortName", c_char_p),
("longName", c_char_p),
("unit", c_char_p),
]
| c_metricInfo_t |
python | pypa__hatch | tests/backend/metadata/test_core.py | {
"start": 43189,
"end": 46010
} | class ____:
def test_dynamic(self, isolation):
metadata = ProjectMetadata(
str(isolation), None, {"project": {"entry-points": 9000, "dynamic": ["entry-points"]}}
)
with pytest.raises(
ValueError,
match=(
"Metadata field `entry-points` cann... | TestEntryPoints |
python | ray-project__ray | python/ray/llm/tests/common/cloud/test_utils.py | {
"start": 9477,
"end": 11059
} | class ____:
"""Tests for the is_remote_path utility function."""
def test_s3_paths(self):
"""Test S3 path detection."""
assert is_remote_path("s3://bucket/path") is True
assert is_remote_path("s3://bucket") is True
assert is_remote_path("s3://anonymous@bucket/path") is True
... | TestIsRemotePath |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/refurb/FURB180.py | {
"start": 718,
"end": 783
} | class ____(abc.ABC):
@abstractmethod
def foo(self): pass
| A6 |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 72327,
"end": 72436
} | class ____(BaseModel, extra="forbid"):
mult: List["Expression"] = Field(..., description="")
| MultExpression |
python | django__django | tests/auth_tests/test_middleware.py | {
"start": 3207,
"end": 8620
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user(
"test_user", "test@example.com", "test_password"
)
def setUp(self):
self.middleware = LoginRequiredMiddleware(lambda req: HttpResponse())
self.request = HttpRequest()
... | TestLoginRequiredMiddleware |
python | numba__numba | numba/core/types/function_type.py | {
"start": 4028,
"end": 4630
} | class ____(Type):
"""
Represents the prototype of a first-class function type.
Used internally.
"""
cconv = None
def __init__(self, rtype, atypes):
self.rtype = rtype
self.atypes = tuple(atypes)
assert isinstance(rtype, Type), (rtype)
lst = []
for atype ... | FunctionPrototype |
python | Lightning-AI__lightning | src/lightning/pytorch/plugins/layer_sync.py | {
"start": 3516,
"end": 3948
} | class ____(torch.nn.modules.batchnorm._BatchNorm):
@override
def _check_input_dim(self, input: Tensor) -> None:
# The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc
# is this method that is overwritten by the subclass.
# Here, we are bypassing some tensor sanity check... | _BatchNormXd |
python | doocs__leetcode | solution/2200-2299/2278.Percentage of Letter in String/Solution.py | {
"start": 0,
"end": 123
} | class ____:
def percentageLetter(self, s: str, letter: str) -> int:
return s.count(letter) * 100 // len(s)
| Solution |
python | getsentry__sentry | tests/sentry/notifications/models/test_notificationsettingoption.py | {
"start": 570,
"end": 2543
} | class ____(TestCase):
def test_remove_for_user(self) -> None:
NotificationSettingOption.objects.create(
user_id=self.user.id,
scope_type="user",
scope_identifier=self.user.id,
type="alerts",
value="never",
)
# Refresh user for acto... | NotificationSettingTest |
python | sqlalchemy__sqlalchemy | test/orm/test_eager_relations.py | {
"start": 124725,
"end": 130218
} | class ____(
fixtures.MappedTest, testing.AssertsCompiledSQL
):
"""test for issue 11449"""
__dialect__ = "default"
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"kind",
metadata,
Column("id", Integer, primary_k... | InnerJoinSplicingWSecondarySelfRefTest |
python | pyinstaller__pyinstaller | bootloader/waflib/Errors.py | {
"start": 757,
"end": 1123
} | class ____(WafError):
def __init__(self, error_tasks=[]):
self.tasks = error_tasks
WafError.__init__(self, self.format_error())
def format_error(self):
lst = ['Build failed']
for tsk in self.tasks:
txt = tsk.format_error()
if txt:
lst.appe... | BuildError |
python | getsentry__sentry | src/sentry/snuba/metrics/naming_layer/public.py | {
"start": 5864,
"end": 6053
} | class ____(Enum):
HTTP_STATUS_CODE = "span.status_code"
# TODO: these tag keys and values below probably don't belong here, and should
# be moved to another more private file.
| SpanTagsKey |
python | tiangolo__fastapi | docs_src/dependencies/tutorial003_py310.py | {
"start": 141,
"end": 603
} | class ____:
def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons=Depends(CommonQueryParams)):
response = {}
if commons.q:
response.update({"q": commons.q})
... | CommonQueryParams |
python | getsentry__sentry | src/sentry/tasks/assemble.py | {
"start": 1765,
"end": 2356
} | class ____:
DIF = "project.dsym" # Debug file upload
RELEASE_BUNDLE = "organization.artifacts" # Release file upload
ARTIFACT_BUNDLE = "organization.artifact_bundle" # Artifact bundle upload
PREPROD_ARTIFACT = "organization.preprod_artifact_bundle" # Preprod artifact upload
PREPROD_ARTIFACT_SIZE... | AssembleTask |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 78472,
"end": 80404
} | class ____:
"""Test sk_SK address provider methods"""
def test_street_suffix_short(self, faker, num_samples):
for _ in range(num_samples):
street_suffix_short = faker.street_suffix_short()
assert isinstance(street_suffix_short, str)
assert street_suffix_short in SkSk... | TestSkSk |
python | numba__numba | numba/tests/test_typeinfer.py | {
"start": 29052,
"end": 30223
} | class ____(numba.core.compiler.CompilerBase):
"""A compiler pipeline that skips passes after typing (provides partial typing info
but not lowering).
"""
def define_pipelines(self):
pm = numba.core.compiler_machinery.PassManager("custom_pipeline")
pm.add_pass(TranslateByteCode, "analyzin... | TyperCompiler |
python | numpy__numpy | numpy/f2py/tests/test_character.py | {
"start": 19833,
"end": 20501
} | class ____(util.F2PyTest):
sources = [util.getpath("tests", "src", "string", "scalar_string.f90")]
def test_char(self):
for out in (self.module.string_test.string,
self.module.string_test.string77):
expected = ()
assert out.shape == expected
expec... | TestStringScalarArr |
python | kamyu104__LeetCode-Solutions | Python/number-of-subarrays-with-gcd-equal-to-k.py | {
"start": 56,
"end": 690
} | class ____(object):
def subarrayGCD(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
result = 0
dp = collections.Counter()
for x in nu... | Solution |
python | huggingface__transformers | tests/models/mt5/test_modeling_mt5.py | {
"start": 33763,
"end": 35807
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (MT5EncoderModel, MT5ForTokenClassification) if is_torch_available() else ()
test_resize_embeddings = False
pipeline_model_mapping = (
{
"token-classification": MT5ForTokenClassification,
}... | MT5EncoderOnlyModelTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 13585,
"end": 13885
} | class ____(_VectorizerConfigCreate):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.TEXT2VEC_JINAAI, frozen=True, exclude=True
)
baseURL: Optional[str]
dimensions: Optional[int]
model: Optional[str]
vectorizeClassName: bool
| _Text2VecJinaConfig |
python | pypa__pipenv | pipenv/patched/pip/_internal/resolution/resolvelib/reporter.py | {
"start": 2201,
"end": 3275
} | class ____(BaseReporter[Requirement, Candidate, str]):
"""A reporter that does an info log for every event it sees."""
def starting(self) -> None:
logger.info("Reporter.starting()")
def starting_round(self, index: int) -> None:
logger.info("Reporter.starting_round(%r)", index)
def end... | PipDebuggingReporter |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/llama_index/readers/confluence/event.py | {
"start": 1122,
"end": 1334
} | class ____(BaseEvent):
"""Event emitted when a page is skipped due to callback decision."""
page_id: str
@classmethod
def class_name(cls) -> str:
return "PageSkippedEvent"
| PageSkippedEvent |
python | pytorch__pytorch | torch/distributed/tensor/_ops/_view_ops.py | {
"start": 1136,
"end": 1218
} | class ____(DimSpec):
"""Output dimension is a singleton."""
@dataclass
| Singleton |
python | coleifer__peewee | tests/regressions.py | {
"start": 55556,
"end": 55662
} | class ____(TestModel):
dfc = ForeignKeyField(DFC)
name = TextField()
value = IntegerField()
| DFGC |
python | pytest-dev__pytest | testing/test_argcomplete.py | {
"start": 991,
"end": 2239
} | class ____:
"""File completer class, optionally takes a list of allowed extensions."""
def __init__(self, allowednames=(), directories=True):
# Fix if someone passes in a string instead of a list
if type(allowednames) is str:
allowednames = [allowednames]
self.allowednames ... | FilesCompleter |
python | bokeh__bokeh | src/bokeh/models/widgets/tables.py | {
"start": 19762,
"end": 19996
} | class ____(CellEditor):
''' Calendar-based date cell editor.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| DateEditor |
python | django__django | django/db/models/functions/math.py | {
"start": 2781,
"end": 2875
} | class ____(NumericOutputFieldMixin, Transform):
function = "EXP"
lookup_name = "exp"
| Exp |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict1.py | {
"start": 1114,
"end": 1254
} | class ____(TD3, NotATD):
pass
# This should generate an error because non-TypeDict
# base classes shouldn't be allowed for TD classes.
| TD6 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/types.py | {
"start": 884,
"end": 1546
} | class ____(sqltypes.Numeric, sqltypes.Integer):
__visit_name__ = "NUMBER"
def __init__(self, precision=None, scale=None, asdecimal=None):
if asdecimal is None:
asdecimal = bool(scale and scale > 0)
super().__init__(precision=precision, scale=scale, asdecimal=asdecimal)
def ada... | NUMBER |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 72436,
"end": 72502
} | class ____(str, Enum):
MAX_SIM = "max_sim"
| MultiVectorComparator |
python | pytorch__pytorch | torch/distributed/elastic/multiprocessing/tail_log.py | {
"start": 1460,
"end": 5320
} | class ____:
"""
Tail the given log files.
The log files do not have to exist when the ``start()`` method is called. The tail-er will gracefully wait until
the log files are created by the producer and will tail the contents of the
log files until the ``stop()`` method is called.
.. warning:: `... | TailLog |
python | celery__celery | examples/stamping/visitors.py | {
"start": 385,
"end": 649
} | class ____(StampingVisitor):
def on_signature(self, sig: Signature, **headers) -> dict:
mtask_id = str(uuid4())
logger.critical(f"Visitor: Sig '{sig}' is stamped with: {mtask_id}")
return {"mtask_id": mtask_id}
| MonitoringIdStampingVisitor |
python | django__django | tests/m2m_regress/models.py | {
"start": 173,
"end": 391
} | class ____(models.Model):
name = models.CharField(max_length=10)
references = models.ManyToManyField("self")
related = models.ManyToManyField("self")
def __str__(self):
return self.name
| SelfRefer |
python | getsentry__sentry | src/sentry/uptime/endpoints/validators.py | {
"start": 16444,
"end": 21088
} | class ____(BaseDetectorTypeValidator):
enforce_single_datasource = True
data_sources = serializers.ListField(child=UptimeMonitorDataSourceValidator(), required=False)
def validate_config(self, config: dict[str, Any]) -> dict[str, Any]:
"""
Validate that only superusers can change mode to no... | UptimeDomainCheckFailureValidator |
python | automl__auto-sklearn | autosklearn/pipeline/components/classification/__init__.py | {
"start": 852,
"end": 5857
} | class ____(AutoSklearnChoice):
@classmethod
def get_components(cls):
components = OrderedDict()
components.update(_classifiers)
components.update(additional_components.components)
return components
def get_available_components(
cls, dataset_properties=None, include=N... | ClassifierChoice |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 3552,
"end": 4247
} | class ____(enum.Enum):
UNINITIALIZED = 0
ZERO_ON_CALL = 1 # kernel may leave workspace dirty
ZERO_PER_GRAPH = 2 # must be re-zeroed by kernel
@staticmethod
def combine(a: WorkspaceZeroMode, b: WorkspaceZeroMode) -> WorkspaceZeroMode:
if a == b or b == WorkspaceZeroMode.UNINITIALIZED:
... | WorkspaceZeroMode |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/transfers/oracle_to_azure_data_lake.py | {
"start": 1238,
"end": 4537
} | class ____(BaseOperator):
"""
Runs the query against Oracle and stores the file locally before loading it into Azure Data Lake.
:param filename: file name to be used by the csv file.
:param azure_data_lake_conn_id: destination azure data lake connection.
:param azure_data_lake_path: destination pat... | OracleToAzureDataLakeOperator |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/tf_trt_integration_test_base.py | {
"start": 4168,
"end": 4243
} | class ____(object):
ORIGINAL = 0
CALIBRATE = 1
INFERENCE = 2
| GraphState |
python | django__django | django/utils/text.py | {
"start": 2803,
"end": 4531
} | class ____(HTMLParser):
class TruncationCompleted(Exception):
pass
def __init__(self, *, length, replacement, convert_charrefs=True):
super().__init__(convert_charrefs=convert_charrefs)
self.tags = deque()
self.output = []
self.remaining = length
self.replacement... | TruncateHTMLParser |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_port_status.py | {
"start": 383,
"end": 6010
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1IngressPortStatus |
python | sqlalchemy__sqlalchemy | test/orm/test_session.py | {
"start": 49843,
"end": 52039
} | class ____(_fixtures.FixtureTest):
__sparse_driver_backend__ = True
def test_autoflush_rollback(self):
Address, addresses, users, User = (
self.classes.Address,
self.tables.addresses,
self.tables.users,
self.classes.User,
)
self.mapper_re... | SessionStateWFixtureTest |
python | huggingface__transformers | src/transformers/models/falcon_h1/modeling_falcon_h1.py | {
"start": 55069,
"end": 57348
} | class ____(PreTrainedModel):
config: FalconH1Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["FalconH1DecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_sdpa = True
_is_stateful = True
@... | FalconH1PreTrainedModel |
python | google__python-fire | fire/console/console_attr.py | {
"start": 4225,
"end": 4615
} | class ____(ProgressTrackerSymbols):
"""Characters used by progress trackers."""
@property
def spin_marks(self):
return ['⠏', '⠛', '⠹', '⠼', '⠶', '⠧']
success = text.TypedText(['✓'], text_type=text.TextTypes.PT_SUCCESS)
failed = text.TypedText(['X'], text_type=text.TextTypes.PT_FAILURE)
interrupted = '... | ProgressTrackerSymbolsUnicode |
python | google__jax | jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py | {
"start": 4086,
"end": 4591
} | class ____(Mask):
left: Mask
right: Mask
def __init__(self, left: Mask, right: Mask):
if left.shape != right.shape:
raise ValueError('Masks must have the same shape')
self.left = left
self.right = right
@property
def shape(self) -> tuple[int, ...]:
return self.left.shape
def __getit... | LogicalOr |
python | spack__spack | lib/spack/spack/fetch_strategy.py | {
"start": 40632,
"end": 44490
} | class ____(VCSFetchStrategy):
"""Fetch strategy that gets source code from a CVS repository.
Use like this in a package::
version("name", cvs=":pserver:anonymous@www.example.com:/cvsroot%module=modulename")
Optionally, you can provide a branch and/or a date for the URL::
version(
... | CvsFetchStrategy |
python | getsentry__sentry | src/sentry/sentry_metrics/configuration.py | {
"start": 1319,
"end": 6565
} | class ____:
db_backend: IndexerStorage
db_backend_options: Mapping[str, Any]
output_topic: Topic
use_case_id: UseCaseKey
internal_metrics_tag: str | None
writes_limiter_cluster_options: Mapping[str, Any]
writes_limiter_namespace: str
should_index_tag_values: bool
schema_validation_r... | MetricsIngestConfiguration |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datacatalog.py | {
"start": 40830,
"end": 44865
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a tag template and all tags using the template.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataCatalogDeleteTagTemplateOperator`
:param location: Required. The locat... | CloudDataCatalogDeleteTagTemplateOperator |
python | plotly__plotly.py | plotly/graph_objs/layout/yaxis/_minor.py | {
"start": 235,
"end": 20338
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.yaxis"
_path_str = "layout.yaxis.minor"
_valid_props = {
"dtick",
"gridcolor",
"griddash",
"gridwidth",
"nticks",
"showgrid",
"tick0",
"tickcolor",
"ticklen",
"tic... | Minor |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_powerbi_list.py | {
"start": 5136,
"end": 8022
} | class ____:
@mock.patch.object(BaseHook, "get_connection", side_effect=get_airflow_connection)
def test_powerbi_operator_async_get_workspace_list_success(self, connection):
"""Assert that get_workspace_list log success message"""
operator = PowerBIWorkspaceListOperator(
**CONFIG_WORK... | TestPowerBIWorkspaceListOperator |
python | mitmproxy__pdoc | test/testdata/demo.py | {
"start": 33,
"end": 360
} | class ____:
"""🐕"""
name: str
"""The name of our dog."""
friends: list["Dog"]
"""The friends of our dog."""
def __init__(self, name: str):
"""Make a Dog without any friends (yet)."""
self.name = name
self.friends = []
def bark(self, loud: bool = True):
"""*... | Dog |
python | spyder-ide__spyder | spyder/plugins/updatemanager/workers.py | {
"start": 9508,
"end": 13935
} | class ____(BaseWorker):
"""
Worker that checks for releases using either the Anaconda
default channels or the Github Releases page without
blocking the Spyder user interface, in case of connection
issues.
"""
def __init__(self, stable_only):
super().__init__()
self.stable_on... | WorkerUpdate |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 11597,
"end": 11774
} | class ____(models.Model):
random_char_field = RandomCharField(length=8, include_digits=False)
class Meta:
app_label = "django_extensions"
| RandomCharTestModelAlpha |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/ecs/tasks.py | {
"start": 906,
"end": 10888
} | class ____(
NamedTuple(
"_DagsterEcsTaskDefinitionConfig",
[
("family", str),
("image", str),
("container_name", str),
("command", Optional[Sequence[str]]),
("log_configuration", Optional[Mapping[str, Any]]),
("secrets", Sequenc... | DagsterEcsTaskDefinitionConfig |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/quantization/tensorflow/calibrator/integration_test/custom_aggregator_op_test.py | {
"start": 1351,
"end": 5757
} | class ____(test.TestCase):
def setUp(self):
super(CustomAggregatorTest, self).setUp()
ops.disable_eager_execution()
def testBypassAndMinMax(self):
with self.session():
input_tensor = array_ops.constant(
[1.0, 2.0, 3.0, 4.0, 5.0], dtypes.float32
)
aggregator = custom_aggreg... | CustomAggregatorTest |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/condition/test_event_frequency_query_handlers.py | {
"start": 15735,
"end": 18650
} | class ____(BaseEventFrequencyPercentTest, EventFrequencyQueryTestBase):
handler = PercentSessionsQueryHandler
@patch(
"sentry.workflow_engine.handlers.condition.event_frequency_query_handlers.MIN_SESSIONS_TO_FIRE",
1,
)
def test_batch_query_percent(self) -> None:
self._make_sess... | PercentSessionsQueryTest |
python | automl__auto-sklearn | test/test_metalearning/pyMetaLearn/metalearning/test_kND.py | {
"start": 244,
"end": 4580
} | class ____(unittest.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
self.anneal = pd.Series(
{
"number_of_instances": 898.0,
"number_of_classes": 5.0,
"number_of_features": 38.0,
},
name=232,
)
... | kNDTest |
python | sympy__sympy | sympy/testing/runtests.py | {
"start": 67264,
"end": 70770
} | class ____(DocTestRunner):
"""
A class used to run DocTest test cases, and accumulate statistics.
The ``run`` method is used to process a single DocTest case. It
returns a tuple ``(f, t)``, where ``t`` is the number of test cases
tried, and ``f`` is the number of test cases that failed.
Modifi... | SymPyDocTestRunner |
python | getsentry__sentry | src/sentry/plugins/providers/dummy/repository.py | {
"start": 69,
"end": 1016
} | class ____(RepositoryProvider):
name = "Example"
auth_provider = "dummy"
def get_config(self):
return [
{
"name": "name",
"label": "Repository Name",
"type": "text",
"placeholder": "e.g. getsentry/sentry",
"... | DummyRepositoryProvider |
python | walkccc__LeetCode | solutions/3003. Maximize the Number of Partitions After Operations/3003.py | {
"start": 0,
"end": 973
} | class ____:
def maxPartitionsAfterOperations(self, s: str, k: int) -> int:
@functools.lru_cache(None)
def dp(i: int, canChange: bool, mask: int) -> int:
"""
Returns the maximum number of partitions of s[i..n), where `canChange` is
True if we can still change a letter, and `mask` is the bitma... | Solution |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 16812,
"end": 16872
} | class ____(SingleAggregation):
groupby_chunk = M.last
| Last |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 36883,
"end": 37061
} | class ____(axis_ticks_minor_x, axis_ticks_minor_y):
"""
x & y axis minor tick lines
Parameters
----------
theme_element : element_line
"""
| axis_ticks_minor |
python | pennersr__django-allauth | allauth/account/forms.py | {
"start": 2388,
"end": 9853
} | class ____(forms.Form):
password = PasswordField(label=_("Password"), autocomplete="current-password")
remember = forms.BooleanField(label=_("Remember Me"), required=False)
user = None
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
super().__init__(*arg... | LoginForm |
python | fastai__fastai | fastai/text/core.py | {
"start": 4602,
"end": 5262
} | class ____():
"Spacy tokenizer for `lang`"
def __init__(self, lang='en', special_toks=None, buf_sz=5000):
import spacy
from spacy.symbols import ORTH
self.special_toks = ifnone(special_toks, defaults.text_spec_tok)
nlp = spacy.blank(lang)
for w in self.special_toks: nlp.t... | SpacyTokenizer |
python | kamyu104__LeetCode-Solutions | Python/ipo.py | {
"start": 48,
"end": 575
} | class ____(object):
def findMaximizedCapital(self, k, W, Profits, Capital):
"""
:type k: int
:type W: int
:type Profits: List[int]
:type Capital: List[int]
:rtype: int
"""
curr = []
future = sorted(zip(Capital, Profits), reverse=True)
f... | Solution |
python | pypa__pip | src/pip/_vendor/pyproject_hooks/_in_process/_in_process.py | {
"start": 1204,
"end": 2201
} | class ____(Exception):
"""Raised if a hook is missing and we are not executing the fallback"""
def __init__(self, hook_name=None):
super().__init__(hook_name)
self.hook_name = hook_name
def _build_backend():
"""Find and load the build backend"""
backend_path = os.environ.get("_PYPROJE... | HookMissing |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/latest_release_handler.py | {
"start": 1182,
"end": 1637
} | class ____(CacheAccess[Release | Literal[False]]):
"""
If we have a release for a project in an environment, we cache it.
If we don't, we cache False.
"""
def __init__(self, event: GroupEvent, environment: Environment | None):
self._key = latest_release_cache_key(
event.group.pr... | _LatestReleaseCacheAccess |
python | sympy__sympy | sympy/plotting/pygletplot/plot_curve.py | {
"start": 117,
"end": 2838
} | class ____(PlotModeBase):
style_override = 'wireframe'
def _on_calculate_verts(self):
self.t_interval = self.intervals[0]
self.t_set = list(self.t_interval.frange())
self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
[S.Infinity, S.NegativeInfinity, 0],
... | PlotCurve |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 17849,
"end": 20788
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.pos_conv_embed = UniSpeechSatPositionalConvEmbedding(config)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_d... | UniSpeechSatEncoder |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 17981,
"end": 20200
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
catalog: Optional[str] = Field(
None,
description=(
"Optional name of the catalog to use. The value is the top level in the"
" 3... | DbtTask |
python | pallets__click | examples/repo/repo.py | {
"start": 54,
"end": 4717
} | class ____:
def __init__(self, home):
self.home = home
self.config = {}
self.verbose = False
def set_config(self, key, value):
self.config[key] = value
if self.verbose:
click.echo(f" config[{key}] = {value}", file=sys.stderr)
def __repr__(self):
... | Repo |
python | huggingface__transformers | src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py | {
"start": 44345,
"end": 57335
} | class ____(FastSpeech2ConformerPreTrainedModel):
"""
FastSpeech 2 module.
This is a module of FastSpeech 2 described in 'FastSpeech 2: Fast and High-Quality End-to-End Text to Speech'
https://huggingface.co/papers/2006.04558. Instead of quantized pitch and energy, we use token-averaged value introduced... | FastSpeech2ConformerModel |
python | bokeh__bokeh | src/bokeh/models/ranges.py | {
"start": 6288,
"end": 10208
} | class ____(DataRange):
''' An auto-fitting range in a continuous scalar dimension.
By default, the ``start`` and ``end`` of the range automatically
assume min and max values of the data for associated renderers.
'''
def __init__(self, *args, **kwargs) -> None:
if kwargs.get('follow') is n... | DataRange1d |
python | joke2k__faker | tests/providers/test_date_time.py | {
"start": 43484,
"end": 43840
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("zh-CN")
Faker.seed(0)
def test_day(self):
day = self.fake.day_of_week()
assert day in ZhCnProvider.DAY_NAMES.values()
def test_month(self):
month = self.fake.month_name()
assert month in ZhCn... | TestZhCn |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 25409,
"end": 27600
} | class ____:
def test_basic(self, xp):
_, h = freqs(xp.asarray([1.0]), xp.asarray([1.0]), worN=8)
assert_array_almost_equal(h, xp.ones(8))
def test_output(self, xp):
# 1st order low-pass filter: H(s) = 1 / (s + 1)
w = xp.asarray([0.1, 1, 10, 100])
num = xp.asarray([1.])
... | TestFreqs |
python | fsspec__filesystem_spec | fsspec/json.py | {
"start": 1252,
"end": 3768
} | class ____(json.JSONDecoder):
def __init__(
self,
*,
object_hook: Callable[[dict[str, Any]], Any] | None = None,
parse_float: Callable[[str], Any] | None = None,
parse_int: Callable[[str], Any] | None = None,
parse_constant: Callable[[str], Any] | None = None,
... | FilesystemJSONDecoder |
python | pytorch__pytorch | test/distributed/_shard/sharded_optim/test_sharded_optim.py | {
"start": 1375,
"end": 2520
} | class ____(torch.nn.Module):
def __init__(self, rank=None):
super().__init__()
# Use same seed.
torch.manual_seed(0)
self.linear1 = torch.nn.Linear(17, 12)
self.linear2 = torch.nn.Linear(12, 29)
self.gelu = torch.nn.GELU()
if rank:
self.linear1.cu... | MyShardedLinear |
python | pytorch__pytorch | torch/_higher_order_ops/out_dtype.py | {
"start": 856,
"end": 5566
} | class ____(HigherOrderOperator):
"""
The out_dtype operator takes an existing ATen functional operator, an
`out_dtype` argument, and arguments to the original operator, and executes
the original operator and returns a Tensor with the `out_dtype` precision.
This operator does not mandate a compute pr... | OutDtypeOperator |
python | ray-project__ray | ci/ray_ci/bisect/bisector.py | {
"start": 174,
"end": 2127
} | class ____:
def __init__(
self,
test: Test,
passing_revision: str,
failing_revision: str,
validator: Validator,
git_dir: str,
) -> None:
self.test = test
self.passing_revision = passing_revision
self.failing_revision = failing_revision
... | Bisector |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.