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 | pypa__pipenv | pipenv/patched/pip/_vendor/rich/box.py | {
"start": 341,
"end": 10239
} | class ____:
"""Defines characters to render boxes.
โโโฌโ top
โ โโ head
โโโผโค head_row
โ โโ mid
โโโผโค row
โโโผโค foot_row
โ โโ foot
โโโดโ bottom
Args:
box (str): Characters making up box.
ascii (bool, optional): True if this box uses ascii characters only. Default is F... | Box |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/advanced_activations.py | {
"start": 2810,
"end": 5826
} | class ____(Layer):
"""Parametric Rectified Linear Unit.
It follows:
```
f(x) = alpha * x for x < 0
f(x) = x for x >= 0
```
where `alpha` is a learned array with the same shape as x.
Input shape:
Arbitrary. Use the keyword argument `input_shape`
(tuple of integers, does not include the sa... | PReLU |
python | skorch-dev__skorch | skorch/tests/callbacks/test_logging.py | {
"start": 8513,
"end": 12866
} | class ____:
@pytest.fixture
def net_cls(self):
from skorch import NeuralNetClassifier
return NeuralNetClassifier
@pytest.fixture
def data(self, classifier_data):
X, y = classifier_data
# accelerate training since we don't care for the loss
X, y = X[:40], y[:40]
... | TestSacred |
python | has2k1__plotnine | tests/test_layout.py | {
"start": 8282,
"end": 12804
} | class ____:
g = (
ggplot(data)
+ geom_point(aes("x", "y", color="x"))
+ annotate(
"point", x=5, y=5, color="green", shape="s", size=10, alpha=0.5
)
+ annotate("vline", xintercept=5, color="green", size=0.5, alpha=0.5)
+ annotate("hline", yintercept=5, colo... | TestPlotTagLayout |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassDescriptors2.py | {
"start": 992,
"end": 1599
} | class ____:
x: Desc[int]
y: Desc[str]
z: Desc[str] = Desc()
reveal_type(B.x, expected_text="A[int]")
reveal_type(B.y, expected_text="A[str]")
reveal_type(B.z, expected_text="A[str]")
reveal_type(C.x, expected_text="A[int]")
reveal_type(C.y, expected_text="A[str]")
reveal_type(C.z, expected_text="A[str]")
... | C |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 5993,
"end": 6809
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
missing = helper_functions.get_value("MissingValues")
num_missing = missing.sum(axis=1)
return float(np.sum([1 if num > 0 else 0 for num in num_missing]))
def _calculate_sparse(self, X, y, logger, feat_type):
... | NumberOfInstancesWithMissingValues |
python | pytorch__pytorch | test/inductor/test_smoke.py | {
"start": 314,
"end": 637
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.l1 = torch.nn.Linear(1, 6)
self.l2 = torch.nn.Linear(6, 1)
def forward(self, x=None):
x = torch.relu(self.l1(x))
x = torch.relu(self.l2(x))
return x
def _test_f(x):
return x * ... | MLP |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 14126,
"end": 16973
} | class ____(ModelOutput):
"""
Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last... | BaseModelOutputWithPastAndCrossAttentions |
python | aio-libs__aiohttp | tests/test_streams.py | {
"start": 1754,
"end": 34986
} | class ____:
DATA: bytes = b"line1\nline2\nline3\n"
def _make_one(self, limit: int = 2**16) -> streams.StreamReader:
loop = asyncio.get_event_loop()
return streams.StreamReader(mock.Mock(_reading_paused=False), limit, loop=loop)
async def test_create_waiter(self) -> None:
loop = asy... | TestStreamReader |
python | doocs__leetcode | lcof2/ๅๆ Offer II 016. ไธๅซ้ๅคๅญ็ฌฆ็ๆ้ฟๅญๅญ็ฌฆไธฒ/Solution.py | {
"start": 0,
"end": 305
} | class ____:
def lengthOfLongestSubstring(self, s: str) -> int:
ss = set()
ans = j = 0
for i, c in enumerate(s):
while c in ss:
ss.remove(s[j])
j += 1
ans = max(ans, i - j + 1)
ss.add(c)
return ans
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels27.py | {
"start": 315,
"end": 1573
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels27.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/examples/parameter_server_test.py | {
"start": 830,
"end": 2350
} | class ____:
def __init__(self, batch_update_size):
self.model = nn.Linear(in_features, out_features)
self.lock = threading.Lock()
self.future_model = torch.futures.Future()
self.batch_update_size = batch_update_size
self.curr_update_size = 0
self.optimizer = optim.SGD... | BatchUpdateParameterServer |
python | spack__spack | lib/spack/spack/test/repo.py | {
"start": 18053,
"end": 18269
} | class ____(PackageBase):
pass
"""
)
(repo_dir / "packages" / "UPPERCASE").mkdir()
(repo_dir / "packages" / "UPPERCASE" / "package.py").write_text(
"""
from spack.package import PackageBase
| ZlibNg |
python | sympy__sympy | sympy/stats/stochastic_process_types.py | {
"start": 57316,
"end": 61470
} | class ____(ContinuousTimeStochasticProcess, MarkovProcess):
"""
Represents continuous time Markov chain.
Parameters
==========
sym : Symbol/str
state_space : Set
Optional, by default, S.Reals
gen_mat : Matrix/ImmutableMatrix/MatrixSymbol
Optional, by default, None
Exam... | ContinuousMarkovChain |
python | conda__conda | conda/plugins/types.py | {
"start": 15090,
"end": 15616
} | class ____(CondaPlugin):
"""
Define new loaders to expose non-conda packages in a given prefix
as ``PrefixRecord`` objects.
:param name: name of the loader
:param loader: a function that takes a prefix and a dictionary that maps
package names to ``PrefixRecord`` objects. The newly loaded pa... | CondaPrefixDataLoader |
python | numpy__numpy | numpy/_core/tests/test_scalarinherit.py | {
"start": 281,
"end": 368
} | class ____:
def __new__(cls, *args, **kwargs):
return cls, args, kwargs
| HasNew |
python | run-llama__llama_index | llama-index-core/llama_index/core/base/base_query_engine.py | {
"start": 707,
"end": 3319
} | class ____(PromptMixin, DispatcherSpanMixin):
"""Base query engine."""
def __init__(
self,
callback_manager: Optional[CallbackManager],
) -> None:
self.callback_manager = callback_manager or CallbackManager([])
def _get_prompts(self) -> Dict[str, Any]:
"""Get prompts.""... | BaseQueryEngine |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/freshness_tests/test_freshness_evaluation.py | {
"start": 2073,
"end": 14289
} | class ____:
@pytest.mark.asyncio
async def test_freshness_pass(self, instance: DagsterInstance):
"""Test that an asset with a time window freshness policy is evaluated as fresh if its last materialization was within the fail window."""
def create_defs() -> dg.Definitions:
@dg.asset(... | TestTimeWindowFreshnessPolicyEvaluator |
python | tensorflow__tensorflow | tensorflow/python/training/monitored_session_test.py | {
"start": 18929,
"end": 19255
} | class ____:
def __init__(self, between_graph, should_init, should_checkpoint,
should_save_summary):
self.experimental_between_graph = between_graph
self.experimental_should_init = should_init
self.should_checkpoint = should_checkpoint
self.should_save_summary = should_save_summary
| MockExtended |
python | ray-project__ray | rllib/evaluation/tests/test_postprocessing.py | {
"start": 227,
"end": 9137
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_n_step_3(self):
"""Tests, whether n-step adjustments of trajectories work."""
# n-step = 3
gamma = 0.9
... | TestPostprocessing |
python | miyuchina__mistletoe | test/test_contrib/test_xwiki20_renderer.py | {
"start": 235,
"end": 4766
} | class ____(BaseRendererTest):
def setUp(self):
super().setUp()
self.renderer = XWiki20Renderer()
self.renderer.__enter__()
self.addCleanup(self.renderer.__exit__, None, None, None)
self.sampleOutputExtension = 'xwiki20'
def genRandomString(self, n, hasWhitespace=False):... | TestXWiki20Renderer |
python | pytorch__pytorch | torch/nn/parallel/data_parallel.py | {
"start": 1752,
"end": 11878
} | class ____(Module, Generic[T]):
r"""Implements data parallelism at the module level.
This container parallelizes the application of the given :attr:`module` by
splitting the input across the specified devices by chunking in the batch
dimension (other objects will be copied once per device). In the forw... | DataParallel |
python | django-extensions__django-extensions | django_extensions/collision_resolvers.py | {
"start": 5949,
"end": 6262
} | class ____(AppNamePrefixCR, InstalledAppsOrderCR):
"""
Collision resolver which is mixin of AppNamePrefixCR and InstalledAppsOrderCR.
In case of collisions he sets aliases like AppNamePrefixCR, but sets default model using InstalledAppsOrderCR.
""" # noqa: E501
pass
| AppNamePrefixCustomOrderCR |
python | keras-team__keras | keras/src/layers/convolutional/conv1d.py | {
"start": 205,
"end": 7321
} | class ____(BaseConv):
"""1D convolution layer (e.g. temporal convolution).
This layer creates a convolution kernel that is convolved with the layer
input over a single spatial (or temporal) dimension to produce a tensor of
outputs. If `use_bias` is True, a bias vector is created and added to the
ou... | Conv1D |
python | astropy__astropy | astropy/samp/web_profile.py | {
"start": 428,
"end": 4228
} | class ____(SAMPSimpleXMLRPCRequestHandler):
"""
Handler of XMLRPC requests performed through the Web Profile.
"""
def _send_CORS_header(self):
if self.headers.get("Origin") is not None:
method = self.headers.get("Access-Control-Request-Method")
if method and self.command... | WebProfileRequestHandler |
python | google__jax | tests/jet_test.py | {
"start": 1755,
"end": 17051
} | class ____(jtu.JaxTestCase):
def check_jet(self, fun, primals, series, atol=1e-5, rtol=1e-5,
check_dtypes=True):
# Convert to jax arrays to ensure dtype canonicalization.
primals = jax.tree.map(jnp.asarray, primals)
series = jax.tree.map(jnp.asarray, series)
y, terms = jet(fun, prima... | JetTest |
python | lepture__authlib | authlib/integrations/requests_client/oauth1_session.py | {
"start": 722,
"end": 2324
} | class ____(OAuth1Client, Session):
auth_class = OAuth1Auth
def __init__(
self,
client_id,
client_secret=None,
token=None,
token_secret=None,
redirect_uri=None,
rsa_key=None,
verifier=None,
signature_method=SIGNATURE_HMAC_SHA1,
sign... | OAuth1Session |
python | mlflow__mlflow | tests/pyfunc/test_pyfunc_exceptions.py | {
"start": 77,
"end": 579
} | class ____(mlflow.pyfunc.PythonModel):
def __init__(self, path):
with open(path, "w+") as f:
pass
self.not_a_file = f
def test_pyfunc_unpicklable_exception(tmp_path):
model = UnpicklableModel(tmp_path / "model.pkl")
with pytest.raises(
MlflowException,
match="... | UnpicklableModel |
python | pypa__warehouse | tests/unit/manage/test_views.py | {
"start": 235832,
"end": 239552
} | class ____:
def test_archive(self, db_request):
project = ProjectFactory.create(name="foo")
user = UserFactory.create(username="testuser")
db_request.route_path = pretend.call_recorder(lambda *a, **kw: "/the-redirect")
db_request.method = "POST"
db_request.user = user
... | TestArchiveProject |
python | ray-project__ray | python/ray/serve/_private/common.py | {
"start": 6090,
"end": 7982
} | class ____(str, Enum):
HEALTHY = "HEALTHY"
CONFIG_UPDATE = "CONFIG_UPDATE"
AUTOSCALE_UP = "AUTOSCALE_UP"
AUTOSCALE_DOWN = "AUTOSCALE_DOWN"
# MANUALLY_INCREASE_NUM_REPLICAS and MANUALLY_DECREASE_NUM_REPLICAS are used
# instead of CONFIG_UPDATE when the config update only scales
# the number o... | DeploymentStatusInternalTrigger |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 57988,
"end": 58109
} | class ____:
xlX = -4168 # from enum XlErrorBarDirection
xlY = 1 # from enum XlErrorBarDirection
| ErrorBarDirection |
python | kamyu104__LeetCode-Solutions | Python/count-of-range-sum.py | {
"start": 33,
"end": 1528
} | class ____(object):
def countRangeSum(self, nums, lower, upper):
"""
:type nums: List[int]
:type lower: int
:type upper: int
:rtype: int
"""
def countAndMergeSort(sums, start, end, lower, upper):
if end - start <= 1: # The size of range [start, en... | Solution |
python | jackfrued__Python-100-Days | Day31-35/code/example17.py | {
"start": 563,
"end": 885
} | class ____(SetOnceMappingMixin, dict):
"""่ชๅฎไนๅญๅ
ธ"""
pass
def main():
print(D.mro())
# print(D.__mro__)
D().say_hello()
print(SetOnceDict.__mro__)
my_dict= SetOnceDict()
my_dict['username'] = 'jackfrued'
my_dict['username'] = 'hellokitty'
if __name__ == '__main__':
main()
| SetOnceDict |
python | kamyu104__LeetCode-Solutions | Python/house-robber.py | {
"start": 29,
"end": 330
} | class ____(object):
# @param num, a list of integer
# @return an integer
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
last, now = 0, 0
for i in nums:
last, now = now, max(last + i, now)
return now
| Solution |
python | has2k1__plotnine | plotnine/composition/_beside.py | {
"start": 217,
"end": 1475
} | class ____(Compose):
"""
Place plots or compositions side by side
**Usage**
plot | plot
plot | composition
composition | plot
composition | composition
Typically, you will use this class through the `|` operator.
See Also
--------
plotnine.composition.Stac... | Beside |
python | django__django | tests/force_insert_update/tests.py | {
"start": 2151,
"end": 2818
} | class ____(TestCase):
def test_force_update_on_inherited_model(self):
a = InheritedCounter(name="count", value=1, tag="spam")
a.save()
a.save(force_update=True)
def test_force_update_on_proxy_model(self):
a = ProxyCounter(name="count", value=1)
a.save()
a.save(fo... | InheritanceTests |
python | sqlalchemy__sqlalchemy | test/aaa_profiling/test_memusage.py | {
"start": 8434,
"end": 9060
} | class ____(fixtures.ORMTest):
def setup_test(self):
_sessions.clear()
clear_mappers()
# enable query caching, however make the cache small so that
# the tests don't take too long. issues w/ caching include making
# sure sessions don't get stuck inside of it. However it wil... | EnsureZeroed |
python | readthedocs__readthedocs.org | readthedocs/config/tests/test_validation.py | {
"start": 791,
"end": 1400
} | class ____:
def test_it_accepts_valid_choice(self):
result = validate_choice("choice", ("choice", "another_choice"))
assert result == "choice"
with raises(ConfigValidationError) as excinfo:
validate_choice("c", "abc")
assert excinfo.value.message_id == ConfigValidationEr... | TestValidateChoice |
python | ethereum__web3.py | tests/core/providers/test_provider_init.py | {
"start": 387,
"end": 1145
} | class ____(BaseProvider):
pass
@pytest.mark.parametrize(
"provider_class",
(
AsyncBaseProvider,
ExtendsAsyncBaseProvider,
AsyncHTTPProvider,
AsyncIPCProvider,
WebSocketProvider,
AsyncEthereumTesterProvider,
),
)
def test_init_web3_with_async_provider(pro... | ExtendsBaseProvider |
python | huggingface__transformers | src/transformers/models/llava_next_video/modular_llava_next_video.py | {
"start": 1331,
"end": 7992
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`LlavaNextVideoForConditionalGeneration`]. It is used to instantiate an
Llava-NeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defau... | LlavaNextVideoConfig |
python | pytorch__pytorch | torch/numa/binding.py | {
"start": 519,
"end": 777
} | class ____(str, Enum):
"""
See behavior description for each affinity mode
in torch.distributed.run.
"""
NODE = "node"
SOCKET = "socket"
EXCLUSIVE = "exclusive"
CORE_COMPLEX = "core-complex"
@dataclass(frozen=True)
| AffinityMode |
python | huggingface__transformers | src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py | {
"start": 30221,
"end": 32663
} | class ____(nn.Module):
"""
Convolutional backbone, using either the AutoBackbone API or one from the timm library.
nn.BatchNorm2d layers are replaced by MMGroundingDinoFrozenBatchNorm2d as defined above.
"""
def __init__(self, config):
super().__init__()
self.config = config
... | MMGroundingDinoConvEncoder |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/normalize_op_test.py | {
"start": 1775,
"end": 3489
} | class ____(test_lib.TestCase):
pass
def _GetNormalizeOpTest(dtype_, shape_, ord_, axis_):
@test_util.run_in_graph_and_eager_modes
def Test(self):
is_matrix_norm = (isinstance(axis_, tuple) or
isinstance(axis_, list)) and len(axis_) == 2
is_fancy_p_norm = np.isreal(ord_) and np.flo... | NormalizeOpTest |
python | ansible__ansible | test/units/module_utils/datatag/test_datatag.py | {
"start": 1767,
"end": 1976
} | class ____(AnsibleSingletonTagBase):
def _get_tag_to_propagate(self, src: t.Any, value: object, *, value_type: t.Optional[type] = None) -> t.Self | None:
return None
| ExampleTagThatPreventsPropagation |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_glue.py | {
"start": 16324,
"end": 22453
} | class ____:
RULE_SET_NAME = "TestRuleSet"
RULE_SET = 'Rules=[ColumnLength "review_id" = 15]'
TARGET_TABLE = {"TableName": "TestTable", "DatabaseName": "TestDB"}
@pytest.fixture
def glue_data_quality_hook(self) -> Generator[GlueDataQualityHook, None, None]:
with mock_aws():
hook ... | TestGlueDataQualityOperator |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/unit_tests/test_unresolvable_component.py | {
"start": 246,
"end": 1352
} | class ____(dg.Component, dg.Model):
"""This component class does not subclass Resolvable."""
some_field: str
def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: ...
def test_unresolvable_component():
with create_defs_folder_sandbox() as sandbox:
defs_path = sandbox.scaf... | UnresolvableComponent |
python | run-llama__llama_index | llama-index-core/llama_index/core/query_engine/pandas/pandas_query_engine.py | {
"start": 404,
"end": 1115
} | class ____:
"""
Pandas query engine.
DEPRECATED: Use `PandasQueryEngine` from `llama-index-experimental` instead.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
raise DeprecationWarning(
"PandasQueryEngine has been moved to `llama-index-experimental`.\n"
... | PandasQueryEngine |
python | huggingface__transformers | src/transformers/models/zamba2/modeling_zamba2.py | {
"start": 56525,
"end": 60031
} | class ____(GradientCheckpointingLayer):
def __init__(
self, shared_transformer: Zamba2AttentionDecoderLayer, linear: nn.Linear, mamba: Zamba2MambaDecoderLayer
):
super().__init__()
self.linear = linear
self.mamba_decoder = mamba
self.shared_transformer = shared_transforme... | Zamba2HybridLayer |
python | ray-project__ray | python/ray/data/_internal/execution/backpressure_policy/concurrency_cap_backpressure_policy.py | {
"start": 630,
"end": 9866
} | class ____(BackpressurePolicy):
"""A backpressure policy that caps the concurrency of each operator.
This policy dynamically limits the number of concurrent tasks per operator
based on the output queue growth rate.
- Maintain asymmetric EWMA of total enqueued output bytes as the
typical level... | ConcurrencyCapBackpressurePolicy |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_checks/asset_check_evaluation.py | {
"start": 1837,
"end": 5164
} | class ____(
NamedTuple(
"_AssetCheckEvaluation",
[
("asset_key", AssetKey),
("check_name", str),
("passed", bool),
("metadata", Mapping[str, MetadataValue]),
(
"target_materialization_data",
Optional[AssetChe... | AssetCheckEvaluation |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/translate.py | {
"start": 12018,
"end": 17847
} | class ____(GoogleCloudBaseOperator):
"""
Translate large volumes of text content, by the inputs provided.
Wraps the Google cloud Translate Text (Advanced) functionality.
See https://cloud.google.com/translate/docs/advanced/batch-translation
For more information on how to use this operator, take a ... | TranslateTextBatchOperator |
python | ray-project__ray | release/nightly_tests/dask_on_ray/large_scale_test.py | {
"start": 1365,
"end": 3093
} | class ____:
def __init__(
self,
num_workers: int,
worker_obj_store_size_in_gb: int,
trigger_object_spill: bool,
error_rate: float,
):
"""
`batch_size` is the # of Dask graphs sent to the cluster
simultaneously for processing.
One element i... | TestSpec |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 23256,
"end": 25203
} | class ____(AttributeTemplate):
key = types.NumberClass
def resolve___call__(self, classty):
"""
Resolve a NumPy number class's constructor (e.g. calling numpy.int32(...))
"""
ty = classty.instance_type
def typer(val):
if isinstance(val, (types.BaseTuple, typ... | NumberClassAttribute |
python | Pylons__pyramid | src/pyramid/config/predicates.py | {
"start": 2932,
"end": 9079
} | class ____:
def __init__(self):
self.sorter = TopologicalSorter()
self.last_added = None
def add(self, name, factory, weighs_more_than=None, weighs_less_than=None):
# Predicates should be added to a predicate list in (presumed)
# computation expense order.
# if weighs_mo... | PredicateList |
python | ansible__ansible | lib/ansible/module_utils/facts/network/darwin.py | {
"start": 845,
"end": 1853
} | class ____(GenericBsdIfconfigNetwork):
"""
This is the Mac macOS Darwin Network Class.
It uses the GenericBsdIfconfigNetwork unchanged
"""
platform = 'Darwin'
# media line is different to the default FreeBSD one
def parse_media_line(self, words, current_if, ips):
# not sure if this ... | DarwinNetwork |
python | streamlit__streamlit | lib/tests/streamlit/elements/data_editor_test.py | {
"start": 2036,
"end": 18484
} | class ____(unittest.TestCase):
@parameterized.expand(
[
(None, ColumnDataKind.STRING, None),
("hello", ColumnDataKind.STRING, "hello"),
(123, ColumnDataKind.STRING, "123"),
(123.1234, ColumnDataKind.STRING, "123.1234"),
(None, ColumnDataKind.INTEGE... | DataEditorUtilTest |
python | pypa__pipenv | pipenv/vendor/tomlkit/items.py | {
"start": 53299,
"end": 53725
} | class ____(Item):
"""
A null item.
"""
def __init__(self) -> None:
super().__init__(Trivia(trail=""))
def unwrap(self) -> None:
return None
@property
def discriminant(self) -> int:
return -1
@property
def value(self) -> None:
return None
def a... | Null |
python | numpy__numpy | numpy/random/tests/test_smoke.py | {
"start": 28380,
"end": 28702
} | class ____(RNG):
@classmethod
def _create_rng(cls):
bit_generator = PCG64DXSM
advance = 2**63 + 2**31 + 2**15 + 1
seed = [12345]
rg = Generator(bit_generator(*seed))
seed_vector_bits = 64
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
| TestPCG64DXSM |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/summary_ops/summary_ops_test.py | {
"start": 49243,
"end": 61292
} | class ____(test_util.TensorFlowTestCase):
def tearDown(self):
summary_ops.trace_off()
super().tearDown()
def exec_summary_op(self, summary_op_fn):
assert context.executing_eagerly()
logdir = self.get_temp_dir()
writer = summary_ops.create_file_writer_v2(logdir)
with writer.as_default():
... | SummaryOpsTest |
python | google__jax | tests/random_lax_test.py | {
"start": 7986,
"end": 56664
} | class ____(RandomTestBase):
"""
Tests of distribution statistics that need only be run with the default PRNG.
We limit this to the default PRNG to avoid repeated execution of very costly
tests. So long as the input bits are valid (as tested in BasicRandomTest) then
the distribution logic tested here will app... | DistributionsTest |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/plugins/pylint_lint.py | {
"start": 1441,
"end": 12372
} | class ____:
last_diags = collections.defaultdict(list)
@classmethod
def lint(cls, document, is_saved, flags=""):
"""Plugin interface to pylsp linter.
Args:
document: The document to be linted.
is_saved: Whether or not the file has been saved to disk.
fla... | PylintLinter |
python | lepture__authlib | authlib/oauth2/rfc6749/authenticate_client.py | {
"start": 626,
"end": 3985
} | class ____:
def __init__(self, query_client):
self.query_client = query_client
self._methods = {
"none": authenticate_none,
"client_secret_basic": authenticate_client_secret_basic,
"client_secret_post": authenticate_client_secret_post,
}
def register(... | ClientAuthentication |
python | django__django | django/urls/converters.py | {
"start": 189,
"end": 339
} | class ____:
regex = "[^/]+"
def to_python(self, value):
return value
def to_url(self, value):
return value
| StringConverter |
python | jazzband__tablib | tests/test_tablib.py | {
"start": 29107,
"end": 36856
} | class ____(BaseTestCase):
def test_csv_format_detect(self):
"""Test CSV format detection."""
_csv = StringIO(
'1,2,3\n'
'4,5,6\n'
'7,8,9\n'
)
_bunk = StringIO(
'ยกยกยกยกยกยกยกยกยฃโขโยขยฃยงโยงยถโขยถยชโยถโขยชยบโขโขยชโยบยงโขโ โขยงยบยถโขโ ยฅยชโยบโขยงฦรธยฅยจยฉฯฦรธโ หยฅรงยฉยจโรธหยฅโโ ฦยฅรงยฉรธยจรงหยฅ... | CSVTests |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 40681,
"end": 42348
} | class ____(ModelOutput):
"""
Base class for causal language model (or autoregressive) outputs.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of sha... | CausalLMOutput |
python | numba__numba | numba/tests/test_extending.py | {
"start": 1510,
"end": 3967
} | class ____(types.Opaque):
def can_convert_to(self, context, toty):
if isinstance(toty, types.Number):
from numba.core.typeconv import Conversion
return Conversion.safe
mydummy_type = MyDummyType("mydummy")
mydummy = MyDummy()
@typeof_impl.register(MyDummy)
def typeof_mydummy(val... | MyDummyType |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 191077,
"end": 193791
} | class ____(Response):
"""
Response of tasks.dequeue endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
:param dequeued: Number of tasks dequeued (0 or 1)
:type dequeued: int
"""
_servic... | DequeueResponse |
python | davidhalter__jedi | jedi/inference/names.py | {
"start": 21358,
"end": 21408
} | class ____(ImportName):
_level = 1
| SubModuleName |
python | keras-team__keras | keras/src/metrics/hinge_metrics.py | {
"start": 2342,
"end": 3255
} | class ____(reduction_metrics.MeanMetricWrapper):
"""Computes the categorical hinge metric between `y_true` and `y_pred`.
Args:
name: (Optional) string name of the metric instance.
dtype: (Optional) data type of the metric result.
Example:
>>> m = keras.metrics.CategoricalHinge()
>>... | CategoricalHinge |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 6054,
"end": 9094
} | class ____(fixtures.TablesTest, AssertsExecutionResults):
__only_on__ = "postgresql"
__dialect__ = postgresql.dialect()
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"data_table",
metadata,
Column("id", Integer, primary_key=True... | FloatCoercionTest |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 198819,
"end": 199062
} | class ____:
_col_type = INT4MULTIRANGE
_col_str = "INT4MULTIRANGE"
def _data_str(self):
return "{[1,2), [3, 5), [9, 12)}"
def _data_obj(self):
return [Range(1, 2), Range(3, 5), Range(9, 12)]
| _Int4MultiRangeTests |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 3426,
"end": 10377
} | class ____(NonStrictDataModel):
"""
:param binary: Binary to use when running the script
:type binary: str
:param repository: Name of the repository where the script is located
:type repository: str
:param tag: Repository tag
:type tag: str
:param branch: Repository branch ID If not prov... | Script |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 255984,
"end": 256785
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of MoveProjectCard"""
__schema__ = github_schema
__field_names__ = ("card_id", "column_id", "after_card_id", "client_mutation_id")
card_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="cardId")
"""The id of the card to move.""... | MoveProjectCardInput |
python | facebook__pyre-check | tools/generate_taint_models/model.py | {
"start": 895,
"end": 1204
} | class ____(abc.ABC):
def __lt__(self, other: "Model") -> bool:
return str(self) < str(other)
@abc.abstractmethod
def __eq__(self) -> int:
...
@abc.abstractmethod
def __hash__(self) -> int:
...
@abc.abstractmethod
def __str__(self) -> str:
...
| Model |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/ecs/utils.py | {
"start": 681,
"end": 5389
} | class ____(Exception): ...
def run_ecs_task(ecs, run_task_kwargs) -> Mapping[str, Any]:
response = ecs.run_task(**run_task_kwargs)
tasks = response["tasks"]
if not tasks:
failures = response["failures"]
failure_messages = []
for failure in failures:
arn = failure.get(... | RetryableEcsException |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 33036,
"end": 33208
} | class ____(Reduction):
# Only supported for Series objects
reduction_aggregate = sum
@staticmethod
def reduction_chunk(ser):
return ser.nbytes
| NBytes |
python | gevent__gevent | src/gevent/resolver/_addresses.py | {
"start": 1243,
"end": 4795
} | class ____(ValueError):
pass
def _ipv4_inet_aton(text):
"""
Convert an IPv4 address in text form to binary struct.
*text*, a ``text``, the IPv4 address in textual form.
Returns a ``binary``.
"""
if not isinstance(text, bytes):
text = text.encode()
parts = text.split(b'.')
... | AddressSyntaxError |
python | takluyver__flit | flit_core/flit_core/vendor/tomli/_parser.py | {
"start": 6341,
"end": 7369
} | class ____:
def __init__(self) -> None:
# The parsed content of the TOML document
self.dict: Dict[str, Any] = {}
def get_or_create_nest(
self,
key: Key,
*,
access_lists: bool = True,
) -> dict:
cont: Any = self.dict
for k in key:
i... | NestedDict |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 7774,
"end": 8008
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("ALL", "DISABLED", "NO_POLICY", "PRIVATE", "PUBLIC")
| EnterpriseMembersCanCreateRepositoriesSettingValue |
python | pytorch__pytorch | test/fx/test_fx_split.py | {
"start": 494,
"end": 4203
} | class ____(TestCase):
def test_split_preserve_node_meta(self):
class TestModule(torch.nn.Module):
def forward(self, x, y):
x = x + x
y = y * y
return x - y
gm = torch.fx.symbolic_trace(TestModule())
for node in gm.graph.nodes:
... | TestFXSplit |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mixpanel/source_mixpanel/components.py | {
"start": 15443,
"end": 15812
} | class ____(DpathExtractor):
def extract_records(self, response: requests.Response) -> List[Mapping[str, Any]]:
# We prefer response.iter_lines() to response.text.split_lines() as the later can missparse text properties embeding linebreaks
records = list(iter_dicts(response.iter_lines(decode_unicode=... | ExportDpathExtractor |
python | huggingface__transformers | src/transformers/models/glm46v/modeling_glm46v.py | {
"start": 26056,
"end": 39600
} | class ____(Glm46VPreTrainedModel, GenerationMixin):
_checkpoint_conversion_mapping = {}
_tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
# Reference: fix gemma3 grad acc #37208
accepts_loss_kwargs = False
def __init__(self, config):
super().__init__(config... | Glm46VForConditionalGeneration |
python | getsentry__sentry | src/sentry/integrations/slack/message_builder/issues.py | {
"start": 9025,
"end": 17091
} | class ____(TypedDict):
label: Mapping[str, str]
options: Sequence[Mapping[str, Any]]
def get_option_groups(group: Group) -> Sequence[OptionGroup]:
all_members = group.project.get_members_as_rpc_users()
members = list({m.id: m for m in all_members}.values())
teams = group.project.teams.all()
o... | OptionGroup |
python | Pylons__pyramid | src/pyramid/authentication.py | {
"start": 12550,
"end": 14572
} | class ____(CallbackAuthenticationPolicy):
"""A :app:`Pyramid` :term:`authentication policy` which
obtains data from the ``REMOTE_USER`` WSGI environment variable.
Constructor Arguments
``environ_key``
Default: ``REMOTE_USER``. The key in the WSGI environ which
provides the userid.
... | RemoteUserAuthenticationPolicy |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py | {
"start": 1598,
"end": 1700
} | class ____(notabc.ABC, metaclass=abc.ABCMeta): # safe
def method(self):
foo()
| multi_super_2 |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 11600,
"end": 12079
} | class ____(PrefectBaseModel, OperatorMixin):
"""Filter by `TaskRun.tags`."""
all_: Optional[List[str]] = Field(
default=None,
examples=[["tag-1", "tag-2"]],
description=(
"A list of tags. Task runs will be returned only if their tags are a"
" superset of the list... | TaskRunFilterTags |
python | huggingface__transformers | src/transformers/models/mllama/modeling_mllama.py | {
"start": 21440,
"end": 24446
} | class ____(nn.Module):
def __init__(self, config: MllamaTextConfig, layer_idx: int):
super().__init__()
self.config = config
self.num_heads = config.num_attention_heads
self.dropout = config.dropout
self.hidden_size = config.hidden_size
self.num_key_value_heads = conf... | MllamaTextSelfAttention |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 6958,
"end": 9287
} | class ____:
def test_invalid_oid(self):
with pytest.raises(TypeError):
x509.UnrecognizedExtension(
"notanoid", # type:ignore[arg-type]
b"somedata",
)
def test_eq(self):
ext1 = x509.UnrecognizedExtension(
x509.ObjectIdentifier(... | TestUnrecognizedExtension |
python | dagster-io__dagster | python_modules/libraries/dagster-mysql/dagster_mysql/storage.py | {
"start": 731,
"end": 3847
} | class ____(DagsterStorage, ConfigurableClass):
"""MySQL-backed dagster storage.
Users should not directly instantiate this class; it is instantiated by internal machinery when
``dagster-webserver`` and ``dagster-graphql`` load, based on the values in the ``dagster.yaml`` file in
``$DAGSTER_HOME``. Conf... | DagsterMySQLStorage |
python | django__django | tests/model_fields/tests.py | {
"start": 14130,
"end": 15957
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.foo1 = Foo.objects.create(a="a", d="12.35")
cls.foo2 = Foo.objects.create(a="b", d="12.34")
cls.bar1 = Bar.objects.create(a=cls.foo1, b="b")
cls.bar2 = Bar.objects.create(a=cls.foo2, b="a")
cls.field = Bar._me... | GetChoicesOrderingTests |
python | dagster-io__dagster | python_modules/libraries/dagster-wandb/dagster_wandb/types.py | {
"start": 239,
"end": 646
} | class ____(TypedDict, total=False):
"""W&B Artifacts IO Manager configuration. Useful for type checking."""
name: str
type: str
description: str
aliases: list[str]
add_dirs: list[dict[str, Any]]
add_files: list[dict[str, Any]]
add_references: list[dict[str, Any]]
serialization_modul... | WandbArtifactConfiguration |
python | ray-project__ray | python/ray/experimental/gpu_object_manager/gpu_object_manager.py | {
"start": 1761,
"end": 3573
} | class ____(NamedTuple):
src_actor: "ray.actor.ActorHandle"
dst_actor: "ray.actor.ActorHandle"
send_ref: Optional[ObjectRef]
recv_ref: ObjectRef
communicator_meta: "CommunicatorMetadata"
backend: str
obj_id: str
timeout: float
# TODO(swang): Uncomment and add an API docs page and exampl... | TransferMetadata |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/tokens.py | {
"start": 7519,
"end": 8147
} | class ____:
__slots__ = ()
def __call__(self, request, refresh_token=False):
raise NotImplementedError('Subclasses must implement this method.')
def validate_request(self, request):
"""
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
... | TokenBase |
python | getsentry__sentry | tests/sentry/api/test_api_owners.py | {
"start": 76,
"end": 694
} | class ____(TestCase):
teams: set[str] = set()
def setUp(self) -> None:
super().setUp()
code_owners_file = open(".github/CODEOWNERS")
lines = code_owners_file.readlines()
code_owners_file.close()
for line in lines:
if line.startswith("/src/"):
... | APIOwnersTestCase |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/namedTuple4.py | {
"start": 243,
"end": 397
} | class ____(Class1):
some_class_member = 1
reveal_type(Class2(name="a"), expected_text="Class2")
Class3 = NamedTuple("Class3", [("name", str)])
| Class2 |
python | doocs__leetcode | lcof2/ๅๆ Offer II 011. 0 ๅ 1 ไธชๆฐ็ธๅ็ๅญๆฐ็ป/Solution.py | {
"start": 0,
"end": 304
} | class ____:
def findMaxLength(self, nums: List[int]) -> int:
d = {0: -1}
ans = s = 0
for i, x in enumerate(nums):
s += 1 if x else -1
if s in d:
ans = max(ans, i - d[s])
else:
d[s] = i
return ans
| Solution |
python | huggingface__transformers | src/transformers/models/wav2vec2_bert/modeling_wav2vec2_bert.py | {
"start": 54642,
"end": 58022
} | class ____(Wav2Vec2BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, "add_adapter") and config.add_adapter:
raise ValueError(
"Audio frame classification does not support the use of Wav2Vec2Bert adapters (config.add_adapter=Tru... | Wav2Vec2BertForAudioFrameClassification |
python | graphql-python__graphene | graphene/relay/id_type.py | {
"start": 146,
"end": 539
} | class ____:
"""
Base class that define the required attributes/method for a type.
"""
graphene_type: Type[BaseType] = ID
@classmethod
def resolve_global_id(cls, info, global_id):
# return _type, _id
raise NotImplementedError
@classmethod
def to_global_id(cls, _type, _i... | BaseGlobalIDType |
python | scipy__scipy | scipy/stats/_distn_infrastructure.py | {
"start": 19254,
"end": 19471
} | class ____(rv_frozen):
def pmf(self, k):
return self.dist.pmf(k, *self.args, **self.kwds)
def logpmf(self, k): # No error
return self.dist.logpmf(k, *self.args, **self.kwds)
| rv_discrete_frozen |
python | pypa__pip | src/pip/_internal/utils/logging.py | {
"start": 4178,
"end": 4712
} | class ____(Console):
def on_broken_pipe(self) -> None:
# Reraise the original exception, rich 13.8.0+ exits by default
# instead, preventing our handler from firing.
raise BrokenPipeError() from None
def get_console(*, stderr: bool = False) -> Console:
if stderr:
assert _stderr... | PipConsole |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.