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 | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 13114,
"end": 14063
} | class ____(_Test_random_ball):
def setup_method(self):
super().setup_method()
self.p = np.inf
def test_random_ball_vectorized(kdtree_type):
n = 20
m = 5
np.random.seed(1234)
T = kdtree_type(np.random.randn(n, m))
r = T.query_ball_point(np.random.randn(2, 3, m), 1)
assert_... | _Test_random_ball_linf |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/exc.py | {
"start": 1910,
"end": 2013
} | class ____(sa_exc.SQLAlchemyError):
"""A invalid condition was detected during flush()."""
| FlushError |
python | scikit-learn__scikit-learn | sklearn/model_selection/_search_successive_halving.py | {
"start": 14323,
"end": 29126
} | class ____(BaseSuccessiveHalving):
"""Search over specified parameter values with successive halving.
The search strategy starts evaluating all the candidates with a small
amount of resources and iteratively selects the best candidates, using
more and more resources.
Read more in the :ref:`User gu... | HalvingGridSearchCV |
python | lepture__authlib | authlib/jose/drafts/_jwe_enc_cryptography.py | {
"start": 308,
"end": 1731
} | class ____(JWEEncAlgorithm):
# Use of an IV of size 96 bits is REQUIRED with this algorithm.
# https://datatracker.ietf.org/doc/html/draft-amringer-jose-chacha-02#section-4.1
IV_SIZE = 96
def __init__(self, key_size):
self.name = "C20P"
self.description = "ChaCha20-Poly1305"
sel... | C20PEncAlgorithm |
python | vyperlang__vyper | vyper/warnings.py | {
"start": 1475,
"end": 1579
} | class ____(VyperWarning):
"""
Warn about using `enum` instead of `flag
"""
pass
| EnumUsage |
python | walkccc__LeetCode | solutions/951. Flip Equivalent Binary Trees/951.py | {
"start": 0,
"end": 447
} | class ____:
def flipEquiv(self, root1: TreeNode | None, root2: TreeNode | None) -> bool:
if not root1:
return not root2
if not root2:
return not root1
if root1.val != root2.val:
return False
return (self.flipEquiv(root1.left, root2.left) and
self.flipEquiv(root1.right, ro... | Solution |
python | doocs__leetcode | solution/2100-2199/2104.Sum of Subarray Ranges/Solution.py | {
"start": 0,
"end": 325
} | class ____:
def subArrayRanges(self, nums: List[int]) -> int:
ans, n = 0, len(nums)
for i in range(n - 1):
mi = mx = nums[i]
for j in range(i + 1, n):
mi = min(mi, nums[j])
mx = max(mx, nums[j])
ans += mx - mi
return ans... | Solution |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 4253,
"end": 4647
} | class ____:
def foo():
some_func_call(
'xxxxxxxxxx',
(
"xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x "
"\"xxxx xxxxxxx xxxxxx xxxx; xxxx xxxxxx_xxxxx xxxxxx xxxx; "
"xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" ... | A |
python | ansible__ansible | lib/ansible/module_utils/facts/network/hpux.py | {
"start": 3290,
"end": 3390
} | class ____(NetworkCollector):
_fact_class = HPUXNetwork
_platform = 'HP-UX'
| HPUXNetworkCollector |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/conv2d_test.py | {
"start": 5935,
"end": 6994
} | class ____(trt_test.TfTrtIntegrationTestBase):
"""Testing conversion of conv2d_transpose (AKA Conv2DBackpropInput)"""
def GraphFn(self, inp):
np.random.seed(1234)
dtype = inp.dtype
n, c, h, w = 13, 3, 7, 11
num_filters = 8
weights_shape = [2, 2, num_filters, c]
weights = constant_op.constan... | Conv2DTranposeTest |
python | kamyu104__LeetCode-Solutions | Python/check-if-word-can-be-placed-in-crossword.py | {
"start": 1388,
"end": 2005
} | class ____(object):
def placeWordInCrossword(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
words = [word, word[::-1]]
for mat in (board, zip(*board)):
for row in mat:
blocks = ''.join(row).spl... | Solution2 |
python | getsentry__sentry | src/sentry/deletions/base.py | {
"start": 1599,
"end": 1945
} | class ____:
def __init__(self, params: Mapping[str, Any], task: type[BaseDeletionTask[Any]] | None) -> None:
self.task = task
self.params = params
def __repr__(self) -> str:
class_type = type(self)
return f"<{class_type.__module__}.{class_type.__name__}: task={self.task} params=... | BaseRelation |
python | numpy__numpy | numpy/matrixlib/tests/test_defmatrix.py | {
"start": 1961,
"end": 6411
} | class ____:
def test_sum(self):
"""Test whether matrix.sum(axis=1) preserves orientation.
Fails in NumPy <= 0.9.6.2127.
"""
M = matrix([[1, 2, 0, 0],
[3, 4, 0, 0],
[1, 2, 1, 2],
[3, 4, 3, 4]])
sum0 = matrix([8, 12, 4, 6... | TestProperties |
python | pytorch__pytorch | torch/fx/experimental/proxy_tensor.py | {
"start": 72185,
"end": 85023
} | class ____(PythonKeyTracer):
r"""Customized version of PythonKeyTracer that retains module stack
information in node.meta["nn_module_stack"].
FX symbolic trace actually does this already, but it relies on `self.root`
being the actual module being traced. Since make_fx traces a lambda of our
creatio... | _ModuleStackTracer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/styles/test_write_fills.py | {
"start": 295,
"end": 884
} | class ____(unittest.TestCase):
"""
Test the Styles _write_fills() method.
"""
def setUp(self):
self.fh = StringIO()
self.styles = Styles()
self.styles._set_filehandle(self.fh)
def test_write_fills(self):
"""Test the _write_fills() method"""
self.styles.fil... | TestWriteFills |
python | great-expectations__great_expectations | tests/metrics/test_metric.py | {
"start": 929,
"end": 1114
} | class ____:
@pytest.mark.unit
def test_metric_instantiation_raises(self):
with pytest.raises(AbstractClassInstantiationError):
Metric(column=COLUMN)
| TestMetric |
python | RaRe-Technologies__gensim | gensim/corpora/dictionary.py | {
"start": 525,
"end": 30226
} | class ____(utils.SaveLoad, Mapping):
"""Dictionary encapsulates the mapping between normalized words and their integer ids.
Notable instance attributes:
Attributes
----------
token2id : dict of (str, int)
token -> token_id. I.e. the reverse mapping to `self[token_id]`.
cfs : dict of (i... | Dictionary |
python | celery__celery | t/unit/app/test_beat.py | {
"start": 496,
"end": 657
} | class ____(dict):
closed = False
synced = False
def close(self):
self.closed = True
def sync(self):
self.synced = True
| MockShelve |
python | astropy__astropy | astropy/io/fits/tests/test_util.py | {
"start": 2449,
"end": 7060
} | class ____(FitsTestCase):
"""
The high-level tests are partially covered by
test_core.TestConvenienceFunctions.test_fileobj_mode_guessing
but added some low-level tests as well.
"""
def test_mode_strings(self):
# A string signals that the file should be opened so the function
# ... | TestUtilMode |
python | walkccc__LeetCode | solutions/101. Symmetric Tree/101.py | {
"start": 0,
"end": 348
} | class ____:
def isSymmetric(self, root: TreeNode | None) -> bool:
def isSymmetric(p: TreeNode | None, q: TreeNode | None) -> bool:
if not p or not q:
return p == q
return (p.val == q.val and
isSymmetric(p.left, q.right) and
isSymmetric(p.right, q.left))
return ... | Solution |
python | joke2k__faker | faker/providers/credit_card/zh_CN/__init__.py | {
"start": 184,
"end": 1481
} | class ____(CreditCardProvider):
"""Custom credit card provider for the zh_CN locale."""
prefix_unionpay = ["62"] # UnionPay cards typically start with 62
prefix_visa = ["4"]
prefix_mastercard = ["51", "52", "53", "54", "55"]
credit_card_types = OrderedDict(
(
("unionpay", Cred... | Provider |
python | getsentry__sentry | src/sentry/migrations/0977_commitfilechange_break_commit_fk.py | {
"start": 222,
"end": 2473
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | spack__spack | lib/spack/spack/variant.py | {
"start": 8661,
"end": 17705
} | class ____:
"""A VariantValue is a key-value pair that represents a variant. It can have zero or more
values. Values have set semantics, so they are unordered and unique. The variant type can
be narrowed from multi to single to boolean, this limits the number of values that can be
stored in the variant.... | VariantValue |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/compute.py | {
"start": 35186,
"end": 42622
} | class ____(ComputeEngineBaseOperator):
"""
Creates an Instance Template using specified fields.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:ComputeEngineInsertInstanceTemplateOperator`
:param body: Instance template repr... | ComputeEngineInsertInstanceTemplateOperator |
python | pytorch__pytorch | test/distributed/pipelining/test_unflatten.py | {
"start": 915,
"end": 1264
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.block0 = Block()
self.block1 = Block()
def forward(self, x: torch.Tensor, constant=None) -> torch.Tensor:
x = self.block0(x, constant=constant)
pipe_split()
x = self.block1(x, consta... | M |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/op_concurrency_limits_counter.py | {
"start": 2500,
"end": 11441
} | class ____:
def __init__(
self,
instance: DagsterInstance,
runs: Sequence[DagsterRun],
in_progress_run_records: Sequence[RunRecord],
concurrency_keys: set[str],
pool_limits: Sequence[PoolLimit],
slot_count_offset: int = 0,
pool_granularity: Optional[Po... | GlobalOpConcurrencyLimitsCounter |
python | modin-project__modin | modin/tests/core/storage_formats/pandas/test_internals.py | {
"start": 60105,
"end": 60820
} | class ____:
"""
A dummy object emulating future's behaviour, this class is used in ``test_call_queue_serialization``.
It stores a random numeric value representing its data and `was_materialized` state.
Initially this object is considered to be serialized, the state can be changed by calling
the ``... | DummyFuture |
python | pytorch__pytorch | torch/testing/_internal/common_device_type.py | {
"start": 62563,
"end": 62719
} | class ____(dtypes):
def __init__(self, *args):
super().__init__(*args, device_type="cuda")
# Overrides specified dtypes on Intel GPU.
| dtypesIfCUDA |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/glue_databrew.py | {
"start": 1455,
"end": 6169
} | class ____(AwsBaseOperator[GlueDataBrewHook]):
"""
Start an AWS Glue DataBrew job.
AWS Glue DataBrew is a visual data preparation tool that makes it easier
for data analysts and data scientists to clean and normalize data
to prepare it for analytics and machine learning (ML).
.. seealso::
... | GlueDataBrewStartJobOperator |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 25171,
"end": 26118
} | class ____(TestCase):
"""
The model backend can accept a credentials kwarg labeled with
custom user model's USERNAME_FIELD.
"""
def test_authenticate(self):
test_user = CustomUser._default_manager.create_user(
email="test@example.com", password="test", date_of_birth=date(2006, 4... | CustomUserModelBackendAuthenticateTest |
python | openai__openai-python | tests/lib/schema_types/query.py | {
"start": 778,
"end": 935
} | class ____(BaseModel):
name: Optional[str] = None
table_name: Table
columns: List[Column]
conditions: List[Condition]
order_by: OrderBy
| Query |
python | Textualize__textual | docs/examples/styles/text_align.py | {
"start": 301,
"end": 718
} | class ____(App):
CSS_PATH = "text_align.tcss"
def compose(self):
yield Grid(
Label("[b]Left aligned[/]\n" + TEXT, id="one"),
Label("[b]Center aligned[/]\n" + TEXT, id="two"),
Label("[b]Right aligned[/]\n" + TEXT, id="three"),
Label("[b]Justified[/]\n" + T... | TextAlign |
python | pytorch__pytorch | torch/_inductor/scheduler.py | {
"start": 16507,
"end": 47978
} | class ____:
ancestors: OrderedSet[str]
group: tuple[torch.device, tuple[tuple[sympy.Expr, ...], ...]]
last_usage: OrderedSet[str]
# .min_order and .max_order are only relevant for "grouped" nodes such as FusedSchedulerNode.
# e.g. if the FusedSchedulerNode includes nodes (op_1, op_2, op_3), and op_X... | BaseSchedulerNode |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/combine_documents/reduce.py | {
"start": 5102,
"end": 14286
} | class ____(BaseCombineDocumentsChain):
"""Combine documents by recursively reducing them.
This involves
- `combine_documents_chain`
- `collapse_documents_chain`
`combine_documents_chain` is ALWAYS provided. This is final chain that is called.
We pass all previous results to this chain, and t... | ReduceDocumentsChain |
python | sympy__sympy | sympy/printing/codeprinter.py | {
"start": 966,
"end": 1086
} | class ____(Exception):
"""
Raised if an assignment variable for a loop is missing.
"""
pass
| AssignmentError |
python | catalyst-team__catalyst | examples/catalyst_rl/misc.py | {
"start": 3040,
"end": 7083
} | class ____(dl.Callback):
def __init__(
self,
*,
sampler_fn: Callable,
env,
replay_buffer: "OffpolicyReplayBuffer",
db_server: "IRLDatabase",
actor_key: str,
num_samplers: int = 1,
min_transactions_num: int = int(1e3),
):
super().__i... | GameCallback |
python | kamyu104__LeetCode-Solutions | Python/preimage-size-of-factorial-zeroes-function.py | {
"start": 36,
"end": 638
} | class ____(object):
def preimageSizeFZF(self, K):
"""
:type K: int
:rtype: int
"""
def count_of_factorial_primes(n, p):
cnt = 0
while n > 0:
cnt += n//p
n //= p
return cnt
p = 5
left, right =... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_build.py | {
"start": 19434,
"end": 22806
} | class ____(GoogleCloudBaseOperator):
"""
Returns information about a previously requested build.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudBuildGetBuildOperator`
:param id_: The ID of the build.
:param project... | CloudBuildGetBuildOperator |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/test/airflow_test_instance.py | {
"start": 619,
"end": 923
} | class ____(AirflowAuthBackend):
def get_session(self) -> requests.Session:
raise NotImplementedError("This shouldn't be called from this mock context.")
def get_webserver_url(self) -> str:
return "http://dummy.domain"
DEFAULT_FAKE_INSTANCE_NAME = "test_instance"
| DummyAuthBackend |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 70491,
"end": 73064
} | class ____(fixtures.MappedTest):
"""test that syncrules compile properly on custom inherit conds"""
@classmethod
def define_tables(cls, metadata):
global _a_table, _b_table, _c_table
_a_table = Table(
"a",
metadata,
Column(
"id", Integer,... | SyncCompileTest |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/lists.py | {
"start": 2318,
"end": 2705
} | class ____:
def __repr__(self) -> str:
return ""
def inconsistent_redirect_expressions_in_condition(l: List[HasRepr]) -> None:
# Demonstrate a (fixed) inconsistency in how we handle generators.
# Call graph, forward and backward analysis need to agree on whether
# `str(x)` resolves to `x.__str... | HasRepr |
python | wandb__wandb | wandb/vendor/pygments/lexers/haskell.py | {
"start": 18941,
"end": 21348
} | class ____(Lexer):
"""
Base class for lexers of literate file formats based on LaTeX or Bird-style
(prefixing each code line with ">").
Additional options accepted:
`litstyle`
If given, must be ``"bird"`` or ``"latex"``. If not given, the style
is autodetected: if the first non-wh... | LiterateLexer |
python | google__jax | tests/pmap_test.py | {
"start": 120549,
"end": 127610
} | class ____(jtu.JaxTestCase):
@jtu.ignore_warning(category=DeprecationWarning)
def test_pmap_input_array_output_array(self):
input_shape = (jax.device_count(), 2)
input_array, input_data = create_input_array_for_pmap(input_shape)
f = jax.pmap(lambda x, y: x * y)
out = f(input_array, input_array)
... | ArrayPmapTest |
python | cython__cython | Cython/Compiler/StringEncoding.py | {
"start": 2391,
"end": 3891
} | class ____(str):
# unicode string subclass to keep track of the original encoding.
# 'encoding' is None for unicode strings and the source encoding
# otherwise
encoding = None
def __deepcopy__(self, memo):
return self
def byteencode(self):
assert self.encoding is not None
... | EncodedString |
python | zarr-developers__zarr-python | tests/package_with_entrypoint/__init__.py | {
"start": 1686,
"end": 1924
} | class ____:
class Codec(BytesCodec):
pass
class Buffer(zarr.core.buffer.Buffer):
pass
class NDBuffer(zarr.core.buffer.NDBuffer):
pass
class Pipeline(CodecPipeline):
pass
| TestEntrypointGroup |
python | getsentry__sentry | src/sentry/grouping/fingerprinting/rules.py | {
"start": 340,
"end": 414
} | class ____(TypedDict):
title: NotRequired[str]
| FingerprintRuleAttributes |
python | numba__numba | numba/core/typing/cmathdecl.py | {
"start": 896,
"end": 971
} | class ____(CMath_predicate):
pass
@infer_global(cmath.log)
| CMath_isfinite |
python | pytorch__pytorch | test/test_legacy_vmap.py | {
"start": 770,
"end": 32817
} | class ____(TestCase):
def test_non_tensor_output_raises(self):
with self.assertRaisesRegex(
ValueError, "got type <class 'float'> as the return"
):
output = vmap(lambda x: 3.14)(torch.ones(3))
def multiple_outputs(x):
return x, 3
with self.assert... | TestVmapAPILegacy |
python | Textualize__textual | src/textual/_node_list.py | {
"start": 531,
"end": 647
} | class ____(AttributeError):
"""Raise if you try to mutate the list."""
@rich.repr.auto(angular=True)
| ReadOnlyError |
python | walkccc__LeetCode | solutions/1849. Splitting a String Into Descending Consecutive Values/1849.py | {
"start": 0,
"end": 493
} | class ____:
def splitString(self, s: str) -> bool:
def isValid(s: str, start: int, prev: int, segment: int) -> bool:
if start == len(s) and segment > 1:
return True
curr = 0
for i in range(start, len(s)):
curr = curr * 10 + int(s[i])
if curr > 9999999999:
retur... | Solution |
python | huggingface__transformers | src/transformers/models/led/modeling_led.py | {
"start": 53460,
"end": 55677
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss.
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores ... | LEDSeq2SeqLMOutput |
python | langchain-ai__langchain | libs/langchain/langchain_classic/callbacks/tracers/logging.py | {
"start": 333,
"end": 1694
} | class ____(FunctionCallbackHandler):
"""Tracer that logs via the input Logger."""
name: str = "logging_callback_handler"
def __init__(
self,
logger: logging.Logger,
log_level: int = logging.INFO,
extra: dict | None = None,
**kwargs: Any,
) -> None:
"""In... | LoggingCallbackHandler |
python | scrapy__scrapy | tests/test_scheduler_base.py | {
"start": 1463,
"end": 1748
} | class ____(Spider):
name = "paths"
def __init__(self, mockserver, *args, **kwargs):
super().__init__(*args, **kwargs)
self.start_urls = map(mockserver.url, PATHS)
def parse(self, response):
return {"path": urlparse_cached(response).path}
| PathsSpider |
python | google__jax | docs/autodidax.py | {
"start": 62772,
"end": 71490
} | class ____:
buf: Any
aval: ShapedArray
def __init__(self, aval, buf):
self.aval = aval
self.buf = buf
dtype = property(lambda self: self.aval.dtype)
shape = property(lambda self: self.aval.shape)
ndim = property(lambda self: self.aval.ndim)
def __array__(self): return np.asarray(self.buf)
de... | Array |
python | sanic-org__sanic | sanic/worker/process.py | {
"start": 404,
"end": 7105
} | class ____:
"""A worker process."""
THRESHOLD = 300 # == 30 seconds
SERVER_LABEL = "Server"
SERVER_IDENTIFIER = "Srv"
def __init__(
self,
factory,
name,
ident,
target,
kwargs,
worker_state,
restartable: bool = False,
):
s... | WorkerProcess |
python | ethereum__web3.py | tests/ens/test_offchain_resolution.py | {
"start": 2899,
"end": 3465
} | class ____:
status_code = 200
def __init__(self, request_type, *args, **_kwargs):
# validate the expected urls
if request_type == "get":
assert args[1] == EXPECTED_GET_URL
elif request_type == "post":
assert args[1] == EXPECTED_POST_URL
@staticmethod
def... | AsyncMockHttpSuccessResponse |
python | ApeWorX__ape | src/ape/contracts/base.py | {
"start": 5831,
"end": 10429
} | class ____(ManagerAccessMixin):
contract: "ContractInstance"
abis: list["MethodABI"]
def __init__(self, contract: "ContractInstance", abis: list["MethodABI"]) -> None:
super().__init__()
self.contract = contract
self.abis = abis
# If there is a natspec, inject it as the "do... | ContractMethodHandler |
python | PrefectHQ__prefect | src/prefect/_vendor/croniter/croniter.py | {
"start": 4809,
"end": 49664
} | class ____(object):
MONTHS_IN_YEAR = 12
# This helps with expanding `*` fields into `lower-upper` ranges. Each item
# in this tuple maps to the corresponding field index
RANGES = (
(0, 59),
(0, 23),
(1, 31),
(1, 12),
(0, 6),
(0, 59),
(1970, 2099),... | croniter |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_compiler.py | {
"start": 63625,
"end": 65279
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
def test_basic(self):
seq = Sequence("my_seq_no_schema")
dialect = oracle.OracleDialect()
assert (
dialect.identifier_preparer.format_sequence(seq)
== "my_seq_no_schema"
)
seq = Sequence("my_seq", sche... | SequenceTest |
python | ray-project__ray | python/ray/train/_internal/worker_group.py | {
"start": 522,
"end": 1078
} | class ____:
"""A class to execute arbitrary functions. Does not hold any state."""
def __execute(self, func: Callable[..., T], *args, **kwargs) -> T:
"""Executes the input function and returns the output.
Args:
func: The function to execute.
args, kwargs: The arguments ... | RayTrainWorker |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 38369,
"end": 40764
} | class ____(TestReferrerOnRedirect):
"""
Strict Origin policy will always send the "origin" as referrer
(think of it as the parent URL without the path part),
unless the security level is lower and no "Referer" is sent.
Redirections from secure to non-secure URLs should have the
"Referrer" heade... | TestReferrerOnRedirectStrictOrigin |
python | instagram__MonkeyType | monkeytype/typing.py | {
"start": 15996,
"end": 16079
} | class ____(TypeRewriter):
def rewrite(self, typ):
return typ
| NoOpRewriter |
python | huggingface__transformers | src/transformers/models/glpn/modeling_glpn.py | {
"start": 17605,
"end": 19392
} | class ____(nn.Module):
"""
Selective Feature Fusion module, as explained in the [paper](https://huggingface.co/papers/2201.07436) (section 3.4). This
module adaptively selects and integrates local and global features by attaining an attention map for each feature.
"""
def __init__(self, in_channel=... | GLPNSelectiveFeatureFusion |
python | realpython__materials | python-copy/emoji.py | {
"start": 21,
"end": 446
} | class ____:
def __init__(self, name):
self.name = name
def __repr__(self):
return self._glyph
@property
def name(self):
return unicodedata.name(self._glyph).title()
@name.setter
def name(self, value):
self._glyph = unicodedata.lookup(value)
if __name__ == "__... | Emoji |
python | ray-project__ray | python/ray/data/_internal/datasource/mcap_datasource.py | {
"start": 1580,
"end": 9923
} | class ____(FileBasedDatasource):
"""MCAP (Message Capture) datasource for Ray Data.
This datasource provides reading of MCAP files with predicate pushdown
optimization for filtering by topics, time ranges, and message types.
MCAP is a standardized format for storing timestamped messages from robotics ... | MCAPDatasource |
python | numba__numba | numba/cuda/tests/cudapy/test_cffi.py | {
"start": 294,
"end": 938
} | class ____(CUDATestCase):
def test_from_buffer(self):
import cffi
ffi = cffi.FFI()
link = str(test_data_dir / 'jitlink.ptx')
sig = types.void(types.CPointer(types.int32))
array_mutator = cuda.declare_device('array_mutator', sig)
@cuda.jit(link=[link])
def mu... | TestCFFI |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/snap/execution_plan_snapshot.py | {
"start": 5076,
"end": 5534
} | class ____(
NamedTuple("_ExecutionPlanSnapshotErrorData", [("error", Optional[SerializableErrorInfo])])
):
def __new__(cls, error: Optional[SerializableErrorInfo]):
return super().__new__(
cls,
error=check.opt_inst_param(error, "error", SerializableErrorInfo),
)
@whitel... | ExecutionPlanSnapshotErrorData |
python | spyder-ide__spyder | spyder/utils/stylesheet.py | {
"start": 24340,
"end": 25921
} | class ____(SpecialTabBarStyleSheet):
"""Style for horizontal dockwidget tab bars."""
def set_stylesheet(self):
super().set_stylesheet()
# Main constants
css = self.get_stylesheet()
margin_size = AppStyle.MarginSize
# Tabs style
css['QTabBar::tab'].setValues(
... | HorizontalDockTabBarStyleSheet |
python | django-extensions__django-extensions | django_extensions/management/commands/runserver_plus.py | {
"start": 6139,
"end": 27261
} | class ____(BaseCommand):
help = "Starts a lightweight Web server for development."
# Validation is called explicitly each time the server is reloaded.
requires_system_checks: List[str] = []
DEFAULT_CRT_EXTENSION = ".crt"
DEFAULT_KEY_EXTENSION = ".key"
def add_arguments(self, parser):
s... | Command |
python | PrefectHQ__prefect | src/prefect/server/database/orm_models.py | {
"start": 38838,
"end": 40130
} | class ____(Base):
"""SQLAlchemy model of an worker"""
name: Mapped[str]
description: Mapped[Optional[str]]
type: Mapped[str] = mapped_column(index=True)
base_job_template: Mapped[dict[str, Any]] = mapped_column(
JSON, server_default="{}", default={}
)
is_paused: Mapped[bool] = mappe... | WorkPool |
python | django__django | tests/contenttypes_tests/test_management.py | {
"start": 478,
"end": 5365
} | class ____(TestCase):
# Speed up tests by avoiding retrieving ContentTypes for all test apps.
available_apps = [
"contenttypes_tests",
"empty_models",
"no_models",
"django.contrib.contenttypes",
]
@classmethod
def setUpTestData(cls):
with captured_stdout():
... | RemoveStaleContentTypesTests |
python | run-llama__llama_index | llama-index-core/llama_index/core/schema.py | {
"start": 7200,
"end": 7600
} | class ____(BaseComponent):
node_id: str
node_type: Annotated[ObjectType, EnumNameSerializer] | str | None = None
metadata: Dict[str, Any] = Field(default_factory=dict)
hash: Optional[str] = None
@classmethod
def class_name(cls) -> str:
return "RelatedNodeInfo"
RelatedNodeType = Union[... | RelatedNodeInfo |
python | django__django | tests/generic_relations_regress/models.py | {
"start": 4192,
"end": 4336
} | class ____(models.Model):
b = models.ForeignKey(B, models.SET_NULL, null=True)
class Meta:
ordering = ("id",)
# Ticket #22998
| D |
python | apache__airflow | airflow-core/src/airflow/models/callback.py | {
"start": 2201,
"end": 2560
} | class ____(str, Enum):
"""Methods used to fetch callback at runtime."""
# For future use once Dag Processor callbacks (on_success_callback/on_failure_callback) get moved to executors
DAG_ATTRIBUTE = "dag_attribute"
# For deadline callbacks since they import callbacks through the import path
IMPORT... | CallbackFetchMethod |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_shape_base.py | {
"start": 3758,
"end": 4736
} | class ____(TestCase):
def test_0D_array(self):
a = array(1)
b = array(2)
res = [atleast_3d(a), atleast_3d(b)]
desired = [array([[[1]]]), array([[[2]]])]
assert_array_equal(res, desired)
def test_1D_array(self):
a = array([1, 2])
b = array([2, 3])
... | TestAtleast3d |
python | pyinstaller__pyinstaller | PyInstaller/utils/win32/versioninfo.py | {
"start": 5560,
"end": 11050
} | class ____:
"""
DWORD dwSignature; //Contains the value 0xFEEFO4BD
DWORD dwStrucVersion; // binary version number of this structure.
// The high-order word of this member contains
// the major version number, and the low-order
... | FixedFileInfo |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py | {
"start": 6653,
"end": 8329
} | class ____(object):
def __init__(self, abstract_type, field_asts, context=None, info=None):
self.abstract_type = abstract_type
self.field_asts = field_asts
self.context = context
self.info = info
self._fragments = {}
@cached_property
def possible_types(self):
... | AbstractFragment |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py | {
"start": 26034,
"end": 32870
} | class ____(LayerRNNCell):
"""DEPRECATED: Please use `tf.compat.v1.nn.rnn_cell.LSTMCell` instead.
Basic LSTM recurrent network cell.
The implementation is based on
We add forget_bias (default: 1) to the biases of the forget gate in order to
reduce the scale of forgetting in the beginning of the training.
... | BasicLSTMCell |
python | kubernetes-client__python | kubernetes/client/models/v1_priority_level_configuration_list.py | {
"start": 383,
"end": 7283
} | 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... | V1PriorityLevelConfigurationList |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 37720,
"end": 59006
} | class ____:
def check_promotion_cases(self, promote_func):
# tests that the scalars get coerced correctly.
b = np.bool(0)
i8, i16, i32, i64 = np.int8(0), np.int16(0), np.int32(0), np.int64(0)
u8, u16, u32, u64 = np.uint8(0), np.uint16(0), np.uint32(0), np.uint64(0)
f32, f64, ... | TestTypes |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/exception.py | {
"start": 109,
"end": 242
} | class ____(UnityException):
"""
Related to errors starting and closing environment.
"""
pass
| UnityEnvironmentException |
python | apache__airflow | airflow-core/src/airflow/models/taskinstancehistory.py | {
"start": 1891,
"end": 8398
} | class ____(Base):
"""
Store old tries of TaskInstances.
:meta private:
"""
__tablename__ = "task_instance_history"
task_instance_id: Mapped[str] = mapped_column(
String(36).with_variant(postgresql.UUID(as_uuid=False), "postgresql"),
nullable=False,
primary_key=True,
... | TaskInstanceHistory |
python | walkccc__LeetCode | solutions/1214. Two Sum BSTs/1214.py | {
"start": 0,
"end": 572
} | class ____:
def __init__(self, root: TreeNode | None, leftToRight: bool):
self.stack = []
self.leftToRight = leftToRight
self._pushUntilNone(root)
def hasNext(self) -> bool:
return len(self.stack) > 0
def next(self) -> int:
node = self.stack.pop()
if self.leftToRight:
self._pushUnt... | BSTIterator |
python | walkccc__LeetCode | solutions/1602. Find Nearest Right Node in Binary Tree/1602.py | {
"start": 0,
"end": 525
} | class ____:
def findNearestRightNode(
self,
root: TreeNode,
u: TreeNode,
) -> TreeNode | None:
ans = None
targetDepth = -1
def dfs(root: TreeNode, depth: int) -> None:
nonlocal ans
nonlocal targetDepth
if not root:
return
if root == u:
targetDep... | Solution |
python | pallets__click | examples/complex/complex/cli.py | {
"start": 666,
"end": 1608
} | class ____(click.Group):
def list_commands(self, ctx):
rv = []
for filename in os.listdir(cmd_folder):
if filename.endswith(".py") and filename.startswith("cmd_"):
rv.append(filename[4:-3])
rv.sort()
return rv
def get_command(self, ctx, name):
... | ComplexCLI |
python | gevent__gevent | src/gevent/tests/test__threadpool.py | {
"start": 9637,
"end": 10109
} | class ____(TestPool):
size = 10
# class TestJoinSleep(greentest.GenericGetTestCase):
#
# def wait(self, timeout):
# pool = ThreadPool(1)
# pool.spawn(gevent.sleep, 10)
# pool.join(timeout=timeout)
#
#
# class TestJoinSleep_raise_error(greentest.GenericWaitTestCase):
#
# def wait(s... | TestPool10 |
python | great-expectations__great_expectations | great_expectations/expectations/legacy_row_conditions.py | {
"start": 2770,
"end": 5841
} | class ____(SerializableDictDot):
"""Condition that can be used to filter rows in a data set.
Attributes:
condition: String of the condition
condition_type: Format of the condition e.g. for parsing
"""
condition: str
condition_type: RowConditionParserType
@override
def to_d... | RowCondition |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 9697,
"end": 10687
} | class ____(PredictableInstr, Terminator):
def __init__(self, parent, opname, val, default):
super(SwitchInstr, self).__init__(parent, opname, [val])
self.default = default
self.cases = []
@property
def value(self):
return self.operands[0]
def add_case(self, val, block)... | SwitchInstr |
python | coleifer__peewee | peewee.py | {
"start": 39300,
"end": 40166
} | class ____(WrappedNode):
c = _DynamicEntity()
def __init__(self, node, alias):
super(Alias, self).__init__(node)
self._alias = alias
def __hash__(self):
return hash(self._alias)
@property
def name(self):
return self._alias
@name.setter
def name(self, value)... | Alias |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/composite_dc.py | {
"start": 331,
"end": 424
} | class ____:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
| Point |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/batchnorm_test.py | {
"start": 1211,
"end": 2754
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device, training, cudnn):
self.inputs = {
"input_one": torch.rand(
M, N, K, device=device, requires_grad=self.auto_set()
),
"mean": torch.rand(N, device=device),
"var": torch.rand... | BatchNormBenchmark |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/dep_with_variants_if_develop/package.py | {
"start": 216,
"end": 466
} | class ____(Package):
"""Package that adds a dependency with many variants only at @develop"""
homepage = "https://dev.null"
version("develop")
version("1.0")
depends_on("dep-with-variants", when="@develop")
| DepWithVariantsIfDevelop |
python | scrapy__scrapy | scrapy/core/downloader/handlers/http11.py | {
"start": 4477,
"end": 4581
} | class ____(Exception):
"""An HTTP CONNECT tunnel could not be established by the proxy."""
| TunnelError |
python | ray-project__ray | python/ray/_private/thirdparty/dacite/config.py | {
"start": 115,
"end": 407
} | class ____:
type_hooks: Dict[Type, Callable[[Any], Any]] = field(default_factory=dict)
cast: List[Type] = field(default_factory=list)
forward_references: Optional[Dict[str, Any]] = None
check_types: bool = True
strict: bool = False
strict_unions_match: bool = False
| Config |
python | Lightning-AI__lightning | src/lightning/pytorch/loggers/tensorboard.py | {
"start": 1464,
"end": 10417
} | class ____(Logger, FabricTensorBoardLogger):
r"""Log to local or remote file system in `TensorBoard <https://www.tensorflow.org/tensorboard>`_ format.
Implemented using :class:`~tensorboardX.SummaryWriter`. Logs are saved to
``os.path.join(save_dir, name, version)``. This is the default logger in Lightning... | TensorBoardLogger |
python | huggingface__transformers | src/transformers/integrations/integration_utils.py | {
"start": 91487,
"end": 96190
} | class ____(TrainerCallback):
"""
A [`TrainerCallback`] that sends the logs to [DVCLive](https://www.dvc.org/doc/dvclive).
Use the environment variables below in `setup` to configure the integration. To customize this callback beyond
those environment variables, see [here](https://dvc.org/doc/dvclive/ml... | DVCLiveCallback |
python | psf__black | tests/data/cases/no_blank_line_before_docstring.py | {
"start": 217,
"end": 312
} | class ____:
"""I want to be treated the same as if I were closer"""
| TwoLinesBeforeDocstring |
python | django__django | tests/bulk_create/models.py | {
"start": 4636,
"end": 4824
} | class ____(models.Model):
id = models.DateTimeField(primary_key=True, db_default=Now())
class Meta:
required_db_features = {"supports_expression_defaults"}
| DbDefaultPrimaryKey |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/bijector_test.py | {
"start": 6841,
"end": 7024
} | class ____(BijectorCachingTestBase, test.TestCase):
"""Test caching with BrokenBijector."""
@property
def broken_bijector_cls(self):
return BrokenBijector
| BijectorCachingTest |
python | getsentry__sentry | src/sentry/organizations/services/organization/model.py | {
"start": 12700,
"end": 13081
} | class ____(RpcUserOrganizationContext):
"""
A context containing an intended organization member object as a potential invite, and the true
inner organization member state as found for a given user_id if it exists, or just the organization
member state of the invite if none such exists.
"""
inv... | RpcUserInviteContext |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.