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 | pytorch__pytorch | test/inductor/test_max_autotune.py | {
"start": 118154,
"end": 133292
} | class ____(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._stack = contextlib.ExitStack()
cls._stack.enter_context(
config.patch(
{
"max_autotune": True,
"prologue_fusion": True,
... | TestPrologueFusion |
python | ray-project__ray | python/ray/data/_internal/logical/operators/all_to_all_operator.py | {
"start": 4217,
"end": 5874
} | class ____(AbstractAllToAll, LogicalOperatorSupportsPredicatePassThrough):
"""Logical operator for repartition."""
def __init__(
self,
input_op: LogicalOperator,
num_outputs: int,
shuffle: bool,
keys: Optional[List[str]] = None,
sort: bool = False,
):
... | Repartition |
python | getsentry__sentry | src/sentry/models/grouphashmetadata.py | {
"start": 3065,
"end": 8088
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
# IMPORTANT:
# If you make changes to this schema, increment GROUPHASH_METADATA_SCHEMA_VERSION above so
# existing records will get updated with the new data.
# GENERAL
grouphash = models.OneToOneField(
"sentry.GroupHa... | GroupHashMetadata |
python | walkccc__LeetCode | solutions/221. Maximal Square/221.py | {
"start": 0,
"end": 521
} | class ____:
def maximalSquare(self, matrix: list[list[str]]) -> int:
m = len(matrix)
n = len(matrix[0])
dp = [[0] * n for _ in range(m)]
maxLength = 0
for i in range(m):
for j in range(n):
if i == 0 or j == 0 or matrix[i][j] == '0':
dp[i][j] = 1 if matrix[i][j] == '1' else... | Solution |
python | nedbat__coveragepy | tests/test_process.py | {
"start": 59958,
"end": 62935
} | class ____(CoverageTest):
"""Show that we can configure {[run]source} during process-level coverage.
There are three interesting variables, for a total of eight tests:
1. -m versus a simple script argument (for example, `python myscript`),
2. filtering for the top-level (main.py) or second-le... | ProcessStartupWithSourceTest |
python | pytorch__pytorch | torch/ao/quantization/quantizer/xnnpack_quantizer.py | {
"start": 8443,
"end": 16304
} | class ____(Quantizer):
"""
!!! DEPRECATED !!!
XNNPACKQuantizer is a marked as deprecated. It will be removed in the future.
It has been moved to executorch.backends.xnnpack.quantizer.xnnpack_quantizer.XNNPACKQuantizer.
Please use the new quantizer instead.
"""
supported_config_and_operators... | XNNPACKQuantizer |
python | openai__openai-python | src/openai/types/responses/response_input_file.py | {
"start": 222,
"end": 717
} | class ____(BaseModel):
type: Literal["input_file"]
"""The type of the input item. Always `input_file`."""
file_data: Optional[str] = None
"""The content of the file to be sent to the model."""
file_id: Optional[str] = None
"""The ID of the file to be sent to the model."""
file_url: Option... | ResponseInputFile |
python | urllib3__urllib3 | src/urllib3/contrib/emscripten/fetch.py | {
"start": 2851,
"end": 2900
} | class ____(_RequestError):
pass
| _StreamingError |
python | getsentry__sentry | src/sentry/utils/json.py | {
"start": 1922,
"end": 5843
} | class ____(JSONEncoder):
# Our variant of JSONEncoderForHTML that also accounts for apostrophes
# See: https://github.com/simplejson/simplejson/blob/master/simplejson/encoder.py
def encode(self, o: object) -> str:
# Override JSONEncoder.encode because it has hacks for
# performance that make... | JSONEncoderForHTML |
python | hynek__structlog | src/structlog/_output.py | {
"start": 3395,
"end": 5754
} | class ____:
"""
Write events into a file.
Args:
file: File to print to. (default: `sys.stdout`)
>>> from structlog import WriteLogger
>>> WriteLogger().info("hello")
hello
Useful if you follow
`current logging best practices <logging-best-practices>`.
Also very useful for... | WriteLogger |
python | google__jax | docs/autodidax.py | {
"start": 73279,
"end": 73326
} | class ____(NamedTuple):
pass
| LambdaBindingRecipe |
python | facebook__pyre-check | client/commands/tests/source_code_context_test.py | {
"start": 339,
"end": 4564
} | class ____(testslide.TestCase):
def test_source_code_context_for_position(self) -> None:
self.assertEqual(
SourceCodeContext.from_source_and_position(
source="\n".join(f"line {i}" for i in range(1, 10)),
position=lsp.LspPosition(line=2, character=5),
)... | SourceCodeContextTest |
python | Textualize__rich | examples/repr.py | {
"start": 35,
"end": 589
} | class ____:
def __init__(self, name, eats=None, fly=True, extinct=False):
self.name = name
self.eats = list(eats) if eats else []
self.fly = fly
self.extinct = extinct
# Note that the repr is still generated without Rich
# Try commenting out the following line
from rich import pri... | Bird |
python | kamyu104__LeetCode-Solutions | Python/design-most-recently-used-queue.py | {
"start": 581,
"end": 1808
} | class ____(object): # 0-indexed.
def __init__(self, n):
MAX_CALLS = 2000
self.__bit = [0]*(n+MAX_CALLS+1) # Extra one for dummy node.
for i in xrange(1, len(self.__bit)):
self.__bit[i] = (1 if i-1 < n else 0) + self.__bit[i-1]
for i in reversed(xrange(1, len(self.__bit)... | BIT |
python | getsentry__sentry | tests/sentry/integrations/discord/test_utils.py | {
"start": 1404,
"end": 4710
} | class ____(TestCase):
guild_id = "guild-id"
channel_id = "channel-id"
channel_type = 0 # text
integration_id = 1234
guild_name = "server name"
@mock.patch("sentry.integrations.discord.utils.channel.DiscordClient.get_channel")
def test_happy_path(self, mock_get_channel: mock.MagicMock) -> N... | ValidateChannelTest |
python | cython__cython | Cython/Compiler/Visitor.py | {
"start": 16429,
"end": 26290
} | class ____(EnvTransform):
"""
Base class for transformations that want to intercept on specific
builtin functions or methods of builtin types, including special
methods triggered by Python operators. Must run after declaration
analysis when entries were assigned.
Naming pattern for handler met... | MethodDispatcherTransform |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 1499,
"end": 2056
} | class ____(BaseModel):
model_config = ConfigDict(extra="allow")
type: str
@model_validator(mode="after")
def check_type(self) -> "Annotation":
if self.type == "file_citation":
AnnotationFileCitation(**self.model_dump())
elif self.type == "url_citation":
Annotatio... | Annotation |
python | py-pdf__pypdf | pypdf/generic/_data_structures.py | {
"start": 40675,
"end": 54338
} | class ____(DecodedStreamObject):
"""
In order to be fast, this data structure can contain either:
* raw data in ._data
* parsed stream operations in ._operations.
At any time, ContentStream object can either have both of those fields defined,
or one field defined and the other set to None.
... | ContentStream |
python | gevent__gevent | src/greentest/3.10/test_threading.py | {
"start": 44391,
"end": 50029
} | class ____(BaseTestCase):
# A RuntimeError should be raised if Thread.start() is called
# multiple times.
def test_start_thread_again(self):
thread = threading.Thread()
thread.start()
self.assertRaises(RuntimeError, thread.start)
thread.join()
def test_joining_current_th... | ThreadingExceptionTests |
python | kamyu104__LeetCode-Solutions | Python/put-boxes-into-the-warehouse-ii.py | {
"start": 33,
"end": 547
} | class ____(object):
def maxBoxesInWarehouse(self, boxes, warehouse):
"""
:type boxes: List[int]
:type warehouse: List[int]
:rtype: int
"""
boxes.sort(reverse=True)
left, right = 0, len(warehouse)-1
for h in boxes:
if h <= warehouse[left]:
... | Solution |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_indexing.py | {
"start": 21683,
"end": 23026
} | class ____(TestCase):
@xpassIfTorchDynamo_np # (
# reason="XXX: low-prio to support assigning complex values on floating arrays"
# )
def test_boolean_index_cast_assign(self):
# Setup the boolean index and float arrays.
shape = (8, 63)
bool_index = np.zeros(shape).astype(bool)... | TestFancyIndexingCast |
python | doocs__leetcode | solution/1900-1999/1954.Minimum Garden Perimeter to Collect Enough Apples/Solution2.py | {
"start": 0,
"end": 310
} | class ____:
def minimumPerimeter(self, neededApples: int) -> int:
l, r = 1, 100000
while l < r:
mid = (l + r) >> 1
if 2 * mid * (mid + 1) * (2 * mid + 1) >= neededApples:
r = mid
else:
l = mid + 1
return l * 8
| Solution |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeature.py | {
"start": 1258,
"end": 1412
} | class ____(AbstractMetaFeature):
def __init__(self):
super(HelperFunction, self).__init__()
self.type_ = "HELPERFUNCTION"
| HelperFunction |
python | jupyterlab__jupyterlab | jupyterlab/tests/test_jupyterlab.py | {
"start": 4664,
"end": 31250
} | class ____(AppHandlerTest):
def test_install_extension(self):
assert install_extension(self.mock_extension) is True
path = pjoin(self.app_dir, "extensions", "*.tgz")
assert glob.glob(path)
extensions = get_app_info()["extensions"]
name = self.pkg_names["extension"]
as... | TestExtension |
python | Netflix__metaflow | metaflow/plugins/argo/exit_hooks.py | {
"start": 699,
"end": 1406
} | class ____(JsonSerializable):
# https://argoproj.github.io/argo-workflows/fields/#template
def __init__(self, name):
tree = lambda: defaultdict(tree)
self.name = name
self.payload = tree()
self.payload["name"] = name
def http(self, http):
self.payload["http"] = http... | _Template |
python | sqlalchemy__sqlalchemy | test/orm/test_transaction.py | {
"start": 72707,
"end": 73975
} | class ____:
"""Test the "join into an external transaction" examples"""
def setup_test(self):
self.engine = engines.testing_engine(
options={"use_reaper": False, "sqlite_savepoint": True}
)
self.connection = self.engine.connect()
self.metadata = MetaData()
s... | JoinIntoAnExternalTransactionFixture |
python | fluentpython__example-code-2e | 24-class-metaprog/slots/slots_timing.py | {
"start": 24,
"end": 117
} | class ____:
def __init_subclass__(subclass):
subclass.__slots__ = ('x', 'y')
| Wrong |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_G.py | {
"start": 3960,
"end": 5244
} | class ____(Benchmark):
r"""
Griewank objective function.
This class defines the Griewank global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Griewank}}(x) = \frac{1}{4000}\sum_{i=1}^n x_i^2
- \prod_{i=1}^n\cos\left(\frac{x... | Griewank |
python | pytorch__pytorch | test/test_cuda.py | {
"start": 195708,
"end": 207988
} | class ____(TestCase):
@property
def expandable_segments(self):
return EXPANDABLE_SEGMENTS
def checkCheckpointedBlock(self, before_block, after_block):
for field in ("size", "state"):
self.assertEqual(before_block[field], after_block[field])
def checkCheckpointedState(self, ... | TestBlockStateAbsorption |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_database_backend.py | {
"start": 24996,
"end": 28238
} | class ____(ExampleDatabase):
def __init__(self):
super().__init__()
self.starts = 0
self.ends = 0
def save(self, key: bytes, value: bytes) -> None: ...
def fetch(self, key: bytes) -> Iterable[bytes]: ...
def delete(self, key: bytes, value: bytes) -> None: ...
def _start_lis... | TracksListens |
python | Pylons__pyramid | src/pyramid/events.py | {
"start": 7302,
"end": 8098
} | class ____:
"""An instance of this class is emitted as an :term:`event` when
the :meth:`pyramid.config.Configurator.make_wsgi_app` is
called. The instance has an attribute, ``app``, which is an
instance of the :term:`router` that will handle WSGI requests.
This class implements the
:class:`pyra... | ApplicationCreated |
python | doocs__leetcode | solution/1500-1599/1561.Maximum Number of Coins You Can Get/Solution.py | {
"start": 0,
"end": 136
} | class ____:
def maxCoins(self, piles: List[int]) -> int:
piles.sort()
return sum(piles[len(piles) // 3 :][::2])
| Solution |
python | google__jax | tests/multiprocess/multihost_utils_test.py | {
"start": 929,
"end": 18691
} | class ____(jt_multiprocess.MultiProcessTest):
def test_process_allgather_stacked(self):
elems_per_host = 4
num_processes = jax.process_count()
x = jnp.ones((4,)).reshape((2, 2))
out = multihost_utils.process_allgather(x, tiled=False)
self.assertEqual(out.shape, (num_processes, 2, 2))
np.test... | MultiHostUtilsTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/scoped_resources_builder.py | {
"start": 1392,
"end": 5149
} | class ____(
NamedTuple(
"_ScopedResourcesBuilder",
[("resource_instance_dict", Mapping[str, object]), ("contains_generator", bool)],
)
):
"""There are concepts in the codebase (e.g. ops, system storage) that receive
only the resources that they have specified in required_resource_keys.
... | ScopedResourcesBuilder |
python | coleifer__peewee | tests/sql.py | {
"start": 43074,
"end": 48287
} | class ____(BaseTestCase):
def test_insert_simple(self):
query = User.insert({
User.c.username: 'charlie',
User.c.superuser: False,
User.c.admin: True})
self.assertSQL(query, (
'INSERT INTO "users" ("admin", "superuser", "username") '
'VALUE... | TestInsertQuery |
python | huggingface__transformers | src/transformers/models/swiftformer/modeling_swiftformer.py | {
"start": 15073,
"end": 16560
} | class ____(SwiftFormerPreTrainedModel):
def __init__(self, config: SwiftFormerConfig):
super().__init__(config)
self.config = config
self.patch_embed = SwiftFormerPatchEmbedding(config)
self.encoder = SwiftFormerEncoder(config)
# Initialize weights and apply final processin... | SwiftFormerModel |
python | numba__llvmlite | llvmlite/binding/object_file.py | {
"start": 141,
"end": 832
} | class ____(ffi.ObjectRef):
def name(self):
return ffi.lib.LLVMPY_GetSectionName(self)
def is_text(self):
return ffi.lib.LLVMPY_IsSectionText(self)
def size(self):
return ffi.lib.LLVMPY_GetSectionSize(self)
def address(self):
return ffi.lib.LLVMPY_GetSectionAddress(self... | SectionIteratorRef |
python | scikit-learn__scikit-learn | sklearn/gaussian_process/kernels.py | {
"start": 30113,
"end": 33369
} | class ____(KernelOperator):
"""The `Product` kernel takes two kernels :math:`k_1` and :math:`k_2`
and combines them via
.. math::
k_{prod}(X, Y) = k_1(X, Y) * k_2(X, Y)
Note that the `__mul__` magic method is overridden, so
`Product(RBF(), RBF())` is equivalent to using the * operator
... | Product |
python | django__django | tests/staticfiles_tests/test_management.py | {
"start": 7478,
"end": 7955
} | class ____(AdminScriptTestCase):
@override_settings(STATIC_ROOT=None)
def test_missing_settings_dont_prevent_help(self):
"""
Even if the STATIC_ROOT setting is not set, one can still call the
`manage.py help collectstatic` command.
"""
self.write_settings("settings.py", a... | TestCollectionHelpSubcommand |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/visitors/query_expression.py | {
"start": 2767,
"end": 3094
} | class ____(QueryExpressionVisitor[QueryExpression]):
"""
Visitor that recursively validates the `QueryExpression`.
"""
def _visit_timeseries(self, timeseries: Timeseries) -> QueryExpression:
# This visitor has been kept in case we need future validations.
return timeseries
| QueryValidationVisitor |
python | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 140895,
"end": 158569
} | class ____(VariableTracker):
def __init__(self, fwd_graph, bwd_graph, parent_source, **kwargs) -> None:
super().__init__(**kwargs)
self.fwd_graph = fwd_graph
self.bwd_graph = bwd_graph
self.parent_source = parent_source
def call_function(
self,
tx: "InstructionTr... | AutogradFunctionApplyVariable |
python | doocs__leetcode | solution/0800-0899/0825.Friends Of Appropriate Ages/Solution.py | {
"start": 0,
"end": 391
} | class ____:
def numFriendRequests(self, ages: List[int]) -> int:
cnt = [0] * 121
for x in ages:
cnt[x] += 1
ans = 0
for ax, x in enumerate(cnt):
for ay, y in enumerate(cnt):
if not (ay <= 0.5 * ax + 7 or ay > ax or (ay > 100 and ax < 100)):
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/ugly-number.py | {
"start": 39,
"end": 297
} | class ____(object):
# @param {integer} num
# @return {boolean}
def isUgly(self, num):
if num == 0:
return False
for i in [2, 3, 5]:
while num % i == 0:
num /= i
return num == 1
| Solution |
python | cython__cython | Cython/Compiler/ParseTreeTransforms.py | {
"start": 123018,
"end": 125553
} | class ____(EnvTransform):
def visit_InPlaceAssignmentNode(self, node):
lhs = node.lhs
rhs = node.rhs
if lhs.type.is_cpp_class:
# No getting around this exact operator here.
return node
if isinstance(lhs, ExprNodes.BufferIndexNode):
# There is code... | ExpandInplaceOperators |
python | huggingface__transformers | src/transformers/models/wav2vec2_bert/processing_wav2vec2_bert.py | {
"start": 933,
"end": 6252
} | class ____(ProcessorMixin):
r"""
Constructs a Wav2Vec2-BERT processor which wraps a Wav2Vec2-BERT feature extractor and a Wav2Vec2 CTC tokenizer into a single
processor.
[`Wav2Vec2Processor`] offers all the functionalities of [`SeamlessM4TFeatureExtractor`] and [`PreTrainedTokenizer`].
See the docs... | Wav2Vec2BertProcessor |
python | pydantic__pydantic | pydantic/types.py | {
"start": 40592,
"end": 45265
} | class ____(BaseModel):
f: DirectoryPath
path = Path('directory/')
path.mkdir()
m = Model(f='directory/')
print(m.model_dump())
#> {'f': PosixPath('directory')}
path.rmdir()
path = Path('file.txt')
path.touch()
try:
Model(f='file.txt') # file
except ValidationError as e:
print(e)
'''
1 validation ... | Model |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/error/located_error.py | {
"start": 80,
"end": 757
} | class ____(GraphQLError):
def __init__(self, nodes, original_error=None):
if original_error:
try:
message = str(original_error)
except UnicodeEncodeError:
message = original_error.message.encode('utf-8')
else:
message = 'An unknown... | GraphQLLocatedError |
python | django__django | tests/migrations/test_autodetector.py | {
"start": 1130,
"end": 8372
} | class ____(TestCase):
def repr_changes(self, changes, include_dependencies=False):
output = ""
for app_label, migrations_ in sorted(changes.items()):
output += " %s:\n" % app_label
for migration in migrations_:
output += " %s\n" % migration.name
... | BaseAutodetectorTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 558629,
"end": 559105
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of DeleteProjectV2Item"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "deleted_item_id")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performin... | DeleteProjectV2ItemPayload |
python | dask__dask | dask/dataframe/dask_expr/io/_delayed.py | {
"start": 593,
"end": 5230
} | class ____(PartitionsFiltered, BlockwiseIO):
_parameters = [
"delayed_container",
"meta",
"user_divisions",
"verify_meta",
"_partitions",
"prefix",
]
_defaults = {
"meta": None,
"_partitions": None,
"user_divisions": None,
"veri... | FromDelayed |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constrainedTypeVar2.py | {
"start": 168,
"end": 835
} | class ____(Foo):
pass
T1 = TypeVar("T1", Foo, str)
T2 = TypeVar("T2", bound=Foo)
def test1(x: T1) -> T1:
return x
def test2(x: T2) -> T2:
return x
# This should generate an error because test1(Bar())
# should evaluate to type Foo, not Bar.
aa1: Bar = test1(Bar())
aa2: Foo = test1(Bar())
bb1: Bar =... | Bar |
python | kamyu104__LeetCode-Solutions | Python/valid-permutations-for-di-sequence.py | {
"start": 31,
"end": 512
} | class ____(object):
def numPermsDISequence(self, S):
"""
:type S: str
:rtype: int
"""
dp = [1]*(len(S)+1)
for c in S:
if c == "I":
dp = dp[:-1]
for i in xrange(1, len(dp)):
dp[i] += dp[i-1]
el... | Solution |
python | milvus-io__pymilvus | pymilvus/client/types.py | {
"start": 7379,
"end": 7627
} | class ____:
def __init__(self, sources: list, target: int) -> None:
self.sources = sources
self.target = target
def __repr__(self) -> str:
return f"""
Plan:
- sources: {self.sources}
- target: {self.target}
"""
| Plan |
python | redis__redis-py | redis/exceptions.py | {
"start": 5602,
"end": 5791
} | class ____(RedisClusterException):
"""
Raised on unexpected response length on pipelines. This is
most likely a handling error on the stack.
"""
pass
| InvalidPipelineStack |
python | dagster-io__dagster | examples/docs_projects/project_ask_ai_dagster/src/project_ask_ai_dagster/defs/scraper.py | {
"start": 144,
"end": 2063
} | class ____(dg.ConfigurableResource):
sitemap_url: str
headers: dict = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
# start_sitemap
def parse_sitemap(self) -> list[str]:
"""Extract URLs from sitemap XML."""
response = requests.get(self.sitemap_url, heade... | SitemapScraper |
python | Pylons__pyramid | tests/test_i18n.py | {
"start": 538,
"end": 965
} | class ____(unittest.TestCase):
def _makeOne(self, *arg, **kw):
from pyramid.i18n import TranslationStringFactory
return TranslationStringFactory(*arg, **kw)
def test_it(self):
# this is part of the API, we don't actually need to test much more
# than that it's importable
... | TestTranslationStringFactory |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/deep_learning/layers.py | {
"start": 1404,
"end": 3307
} | class ____(Layer):
"""A fully-connected NN layer.
Parameters:
-----------
n_units: int
The number of neurons in the layer.
input_shape: tuple
The expected input shape of the layer. For dense layers a single digit specifying
the number of features of the input. Must be specifi... | Dense |
python | google__pytype | pytype/pyc/pyc_test.py | {
"start": 168,
"end": 664
} | class ____(unittest.TestCase):
def test_error_matches_re(self):
e = pyc.CompileError("some error (foo.py, line 123)")
self.assertEqual("foo.py", e.filename)
self.assertEqual(123, e.line)
self.assertEqual("some error", e.error)
def test_error_does_not_match_re(self):
e = pyc.CompileError("some ... | TestCompileError |
python | fastai__fastai | dev_nbs/course/crappify.py | {
"start": 245,
"end": 859
} | class ____():
def __init__(self, path_lr, path_hr):
self.path_lr = path_lr
self.path_hr = path_hr
def __call__(self, fn):
dest = self.path_lr/fn.relative_to(self.path_hr)
dest.parent.mkdir(parents=True, exist_ok=True)
img = Image.open(fn)
targ_sz = resize_to(img,... | crappifier |
python | Lightning-AI__lightning | src/lightning/fabric/plugins/precision/deepspeed.py | {
"start": 1240,
"end": 3587
} | class ____(Precision):
"""Precision plugin for DeepSpeed integration.
Args:
precision: Full precision (32-true), half precision (16-true, bf16-true) or
mixed precision (16-mixed, bf16-mixed).
Raises:
ValueError:
If unsupported ``precision`` is provided.
"""
... | DeepSpeedPrecision |
python | ray-project__ray | python/ray/data/_internal/actor_autoscaler/base_actor_autoscaler.py | {
"start": 308,
"end": 918
} | class ____(ABC):
"""Abstract interface for Ray Data actor autoscaler."""
def __init__(
self,
topology: "Topology",
resource_manager: "ResourceManager",
):
self._topology = topology
self._resource_manager = resource_manager
@abstractmethod
def try_trigger_sca... | ActorAutoscaler |
python | ray-project__ray | python/ray/_private/worker.py | {
"start": 45210,
"end": 48214
} | class ____(metaclass=ABCMeta):
"""
Base class for RayContext and ClientContext
"""
dashboard_url: Optional[str]
python_version: str
ray_version: str
@abstractmethod
def disconnect(self):
"""
If this context is for directly attaching to a cluster, disconnect
will... | BaseContext |
python | facebook__pyre-check | client/language_server/code_navigation_request.py | {
"start": 712,
"end": 1022
} | class ____:
paths: List[str]
client_id: str
def to_json(self) -> List[object]:
return [
"GetTypeErrors",
{
"paths": self.paths,
"client_id": self.client_id,
},
]
@dataclasses.dataclass(frozen=True)
| TypeErrorsRequest |
python | kamyu104__LeetCode-Solutions | Python/count-non-decreasing-subarrays-after-k-operations.py | {
"start": 93,
"end": 832
} | class ____(object):
def countNonDecreasingSubarrays(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result = cnt = 0
dq = collections.deque()
right = len(nums)-1
for left in reversed(xrange(len(nums))):
while ... | Solution |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 45293,
"end": 52002
} | class ____(_TestNormBase):
def test_empty(self):
assert_equal(norm([]), 0.0)
assert_equal(norm(array([], dtype=self.dt)), 0.0)
assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0)
def test_vector_return_type(self):
a = np.array([1, 0, 1])
exact_types = np.type... | _TestNormGeneral |
python | google__jax | jax/experimental/jax2tf/tests/control_flow_ops_test.py | {
"start": 857,
"end": 10073
} | class ____(tf_test_util.JaxToTfTestCase):
@jtu.ignore_warning(category=UserWarning,
message="Explicitly requested dtype .* requested in array is not available")
def test_cond(self):
def f_jax(pred, x):
return lax.cond(pred, lambda t: t + 1., lambda f: f, x)
self.ConvertAndCompa... | ControlFlowOpsTest |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/organizationmemberinvite.py | {
"start": 6382,
"end": 7043
} | class ____(serializers.Serializer):
approve = serializers.BooleanField(required=True, write_only=True)
def validate_approve(self, approve):
invited_member = self.context["invited_member"]
allowed_roles = self.context["allowed_roles"]
# you can't reject an invite request via a PUT reques... | ApproveInviteRequestValidator |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/resource_annotation.py | {
"start": 630,
"end": 1619
} | class ____(ABC):
"""Marker class for types that can be used as a parameter on an annotated
function like `@asset`. Any type marked with this class does not require
a ResourceParam when used on an asset.
Example:
class YourClass(TreatAsResourceParam):
...
@asset
def ... | TreatAsResourceParam |
python | readthedocs__readthedocs.org | readthedocs/oauth/migrations/0011_add_default_branch.py | {
"start": 149,
"end": 636
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("oauth", "0010_index_full_name"),
]
operations = [
migrations.AddField(
model_name="remoterepository",
name="default_branch",
field=models.CharField(
blank=... | Migration |
python | doocs__leetcode | solution/0700-0799/0775.Global and Local Inversions/Solution.py | {
"start": 0,
"end": 232
} | class ____:
def isIdealPermutation(self, nums: List[int]) -> bool:
mx = 0
for i in range(2, len(nums)):
if (mx := max(mx, nums[i - 2])) > nums[i]:
return False
return True
| Solution |
python | huggingface__transformers | src/transformers/models/efficientloftr/modeling_efficientloftr.py | {
"start": 22203,
"end": 23622
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: EfficientLoFTRConfig, layer_idx: int):
super().__init__()
self.self_attention = EfficientLoFTRAggregatedAttention(config, layer_idx)
self.cross_attention = EfficientLoFTRAggregatedAttention(config, layer_idx)
def forwar... | EfficientLoFTRLocalFeatureTransformerLayer |
python | scipy__scipy | scipy/stats/_distribution_infrastructure.py | {
"start": 20310,
"end": 21858
} | class ____(_Interval):
r""" Represents a simply-connected subset of the real line; i.e., an interval
Completes the implementation of the `_Interval` class for intervals
on the real line.
Methods
-------
define_parameters(*parameters)
(Inherited) Records any parameters used to define th... | _RealInterval |
python | google__pytype | pytype/tests/test_cmp2.py | {
"start": 1137,
"end": 1870
} | class ____(test_base.BaseTest):
"""Tests handling of the NotImplemented builtin."""
def test_return_annotation(self):
self.Check("""
class Foo:
def __eq__(self, other) -> bool:
if isinstance(other, Foo):
return id(self) == id(other)
else:
return NotImpl... | NotImplementedTest |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/utils/pod_manager.py | {
"start": 37897,
"end": 38762
} | class ____(str, enum.Enum):
"""Action to take when the pod finishes."""
KEEP_POD = "keep_pod"
DELETE_POD = "delete_pod"
DELETE_SUCCEEDED_POD = "delete_succeeded_pod"
def is_log_group_marker(line: str) -> bool:
"""Check if the line is a log group marker like `::group::` or `::endgroup::`."""
r... | OnFinishAction |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_line02.py | {
"start": 315,
"end": 1314
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_line02.xlsx")
self.ignore_elements = {"xl/workbook.xml": ["<fileVersion", "<calcPr"]}
def test_create_file(self):
"""Test th... | TestCompareXLSXFiles |
python | google__jax | jax/experimental/_private_mm/examples/example_overlap.py | {
"start": 1051,
"end": 6494
} | class ____:
fwd: Callable[[Any, Any], Any] # (params, acts) -> acts
mesh: Mesh
def transfer(arr, stage):
sharding = NamedSharding(stage.mesh, P()) # just replicate
return mm.device_put(arr, device=sharding)
def stages_step_fn(stages, num_mubatches, params_by_stage, xs):
# One task per mubatch ... | Stage |
python | django__django | tests/model_formsets/test_uuid.py | {
"start": 309,
"end": 4727
} | class ____(TestCase):
def test_inlineformset_factory_nulls_default_pks(self):
"""
#24377 - If we're adding a new object, a parent's auto-generated pk
from the model field default should be ignored as it's regenerated on
the save request.
Tests the case where both the parent ... | InlineFormsetTests |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 7000,
"end": 9213
} | class ____(Operation):
def __init__(self, axis=None, keepdims=False, *, name=None):
super().__init__(name=name)
if isinstance(axis, int):
self.axis = [axis]
else:
self.axis = axis
self.keepdims = keepdims
def call(self, x):
return backend.numpy.al... | All |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 2974,
"end": 5149
} | class ____:
"""Used for checking GraphModule Node"""
def __init__(self, op, target):
"""
op: call_function | call_module
target:
for call_function, target would be a function
for call_module, target would be the type of PyTorch module
"""
self.op = op... | NodeSpec |
python | getsentry__sentry-python | sentry_sdk/integrations/loguru.py | {
"start": 1481,
"end": 3233
} | class ____(Integration):
identifier = "loguru"
level = DEFAULT_LEVEL # type: Optional[int]
event_level = DEFAULT_EVENT_LEVEL # type: Optional[int]
breadcrumb_format = DEFAULT_FORMAT
event_format = DEFAULT_FORMAT
sentry_logs_level = DEFAULT_LEVEL # type: Optional[int]
def __init__(
... | LoguruIntegration |
python | neetcode-gh__leetcode | python/0673-number-of-longest-increasing-subsequence.py | {
"start": 0,
"end": 1894
} | class ____:
def findNumberOfLIS(self, nums: List[int]) -> int:
# 1. O(n^2) Recursive solution with Caching
dp = {} # key = index, value = [length of LIS, count]
lenLIS, res = 0, 0 # length of LIS, count of LIS
def dfs(i):
if i in dp:
return dp[i]
... | Solution |
python | zarr-developers__zarr-python | src/zarr/abc/codec.py | {
"start": 5950,
"end": 7286
} | class ____:
"""Mixin for array-to-bytes codecs that implement partial decoding."""
async def _decode_partial_single(
self, byte_getter: ByteGetter, selection: SelectorTuple, chunk_spec: ArraySpec
) -> NDBuffer | None:
raise NotImplementedError
async def decode_partial(
self,
... | ArrayBytesCodecPartialDecodeMixin |
python | doocs__leetcode | solution/3100-3199/3159.Find Occurrences of an Element in an Array/Solution.py | {
"start": 0,
"end": 253
} | class ____:
def occurrencesOfElement(
self, nums: List[int], queries: List[int], x: int
) -> List[int]:
ids = [i for i, v in enumerate(nums) if v == x]
return [ids[i - 1] if i - 1 < len(ids) else -1 for i in queries]
| Solution |
python | patrick-kidger__equinox | equinox/nn/_shared.py | {
"start": 183,
"end": 337
} | class ____:
"""Placeholder value for nodes that have been removed by `eqx.nn.Shared`."""
def __repr__(self):
return "SharedNode"
| SharedNode |
python | jazzband__django-pipeline | pipeline/storage.py | {
"start": 3077,
"end": 3146
} | class ____(PipelineMixin, StaticFilesStorage):
pass
| PipelineStorage |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/comprehend.py | {
"start": 1457,
"end": 2856
} | class ____(AwsBaseSensor[ComprehendHook]):
"""
General sensor behavior for Amazon Comprehend.
Subclasses must implement following methods:
- ``get_state()``
Subclasses must set the following fields:
- ``INTERMEDIATE_STATES``
- ``FAILURE_STATES``
- ``SUCCESS_STATES``
... | ComprehendBaseSensor |
python | redis__redis-py | redis/cluster.py | {
"start": 60066,
"end": 61441
} | class ____:
"""
Round-Robin Load Balancing
"""
def __init__(self, start_index: int = 0) -> None:
self.primary_to_idx = {}
self.start_index = start_index
def get_server_index(
self,
primary: str,
list_size: int,
load_balancing_strategy: LoadBalancingS... | LoadBalancer |
python | pytest-dev__pytest | src/_pytest/python.py | {
"start": 32771,
"end": 42158
} | class ____:
"""Make IDs for a parametrization."""
__slots__ = (
"argnames",
"config",
"idfn",
"ids",
"nodeid",
"parametersets",
)
# The argnames of the parametrization.
argnames: Sequence[str]
# The ParameterSets of the parametrization.
param... | IdMaker |
python | doocs__leetcode | lcof2/剑指 Offer II 077. 链表排序/Solution.py | {
"start": 151,
"end": 835
} | class ____:
def sortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
t = slow.next
slow.next = None
l1, l2 = ... | Solution |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/relationship.py | {
"start": 3233,
"end": 3583
} | class ____(Base):
__tablename__ = "employee"
id: Mapped[int] = mapped_column(primary_key=True)
team_id: Mapped[int] = mapped_column(ForeignKey("team.id"))
team: Mapped["Team"] = relationship(back_populates="employees")
__mapper_args__ = {
"polymorphic_on": "type",
"polymorphic_ident... | Employee |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride6.py | {
"start": 1603,
"end": 1895
} | class ____(Parent1[bytes]):
@overload
def m1(self, x: Literal[True]) -> int: ...
@overload
def m1(self, x: Literal[False]) -> float: ...
@overload
def m1(self, x: bytes) -> bytes: ...
def m1(self, x: bool | bytes) -> int | float | bytes:
return x
| Child1_6 |
python | fluentpython__example-code-2e | 24-class-metaprog/slots/slots_timing.py | {
"start": 472,
"end": 612
} | class ____(metaclass=Correct1):
pass
o = Klass1()
try:
o.z = 3
except AttributeError as e:
print('Raised as expected:', e)
| Klass1 |
python | getsentry__sentry | tests/symbolicator/test_minidump_full.py | {
"start": 1500,
"end": 9167
} | class ____(RelayStoreHelper, TransactionTestCase):
@pytest.fixture(autouse=True)
def initialize(self, live_server, reset_snuba):
self.project.update_option("sentry:builtin_symbol_sources", [])
with (
patch("sentry.auth.system.is_internal_ip", return_value=True),
self.opt... | SymbolicatorMinidumpIntegrationTest |
python | davidhalter__jedi | test/completion/pep0484_typing.py | {
"start": 4822,
"end": 5903
} | class ____(typing.DefaultDict[str, int]):
def setdud(self):
pass
def testdict(x: TestDefaultDict):
#? ["setdud", "setdefault"]
x.setd
for key in x.keys():
#? str()
key
for value in x.values():
#? int()
value
x = TestDefaultDict()
#? ["setdud", "setdefault"]
... | TestDefaultDict |
python | django__django | tests/db_functions/math/test_atan2.py | {
"start": 182,
"end": 1730
} | class ____(TestCase):
def test_null(self):
IntegerModel.objects.create(big=100)
obj = IntegerModel.objects.annotate(
null_atan2_sn=ATan2("small", "normal"),
null_atan2_nb=ATan2("normal", "big"),
null_atan2_bn=ATan2("big", "normal"),
).first()
self.... | ATan2Tests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 580801,
"end": 581205
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("DiscussionPollOption", gr... | DiscussionPollOptionEdge |
python | gevent__gevent | src/gevent/_interfaces.py | {
"start": 9396,
"end": 9985
} | class ____(Interface):
"""
Represents a function that will be run some time in the future.
Callback functions run in the hub, and as such they cannot use
gevent's blocking API; any exception they raise cannot be caught.
"""
pending = schema.Bool(description=u"Has this callback run yet?",
... | ICallback |
python | python__mypy | test-data/unit/plugins/class_attr_hook.py | {
"start": 156,
"end": 585
} | class ____(Plugin):
def get_class_attribute_hook(
self, fullname: str
) -> Callable[[AttributeContext], MypyType] | None:
if fullname == "__main__.Cls.attr":
return my_hook
return None
def my_hook(ctx: AttributeContext) -> MypyType:
return ctx.api.named_generic_type("bu... | ClassAttrPlugin |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/losses_test.py | {
"start": 22784,
"end": 29628
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testAllCorrectSigmoid(self):
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
l... | SigmoidCrossEntropyLossTest |
python | plotly__plotly.py | plotly/graph_objs/layout/selection/_line.py | {
"start": 235,
"end": 4166
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.selection"
_path_str = "layout.selection.line"
_valid_props = {"color", "dash", "width"}
@property
def color(self):
"""
Sets the line color.
The 'color' property is a color and may be specified as:
-... | Line |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.