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 | huggingface__transformers | tests/models/reformer/test_modeling_reformer.py | {
"start": 31452,
"end": 39316
} | class ____(
ReformerTesterMixin, ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase
):
all_model_classes = (
(ReformerModel, ReformerModelWithLMHead, ReformerForSequenceClassification, ReformerForQuestionAnswering)
if is_torch_available()
else ()
)
pi... | ReformerLSHAttnModelTest |
python | Pylons__pyramid | tests/test_scripts/dummy.py | {
"start": 3540,
"end": 4827
} | class ____:
def __init__(
self, settings=None, app_settings=None, app=None, server=None
):
if not settings:
settings = {}
if not app_settings:
app_settings = {}
self.settings = settings
self.app_settings = app_settings
self.app = app
... | DummyLoader |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/exc.py | {
"start": 2236,
"end": 2361
} | class ____(sa_exc.InvalidRequestError):
"""Base for exceptions that involve expected mappings not present."""
| UnmappedError |
python | getsentry__sentry | src/sentry/monitors/endpoints/organization_monitor_details.py | {
"start": 868,
"end": 3075
} | class ____(MonitorEndpoint, MonitorDetailsMixin):
publish_status = {
"DELETE": ApiPublishStatus.PUBLIC,
"GET": ApiPublishStatus.PUBLIC,
"PUT": ApiPublishStatus.PUBLIC,
}
owner = ApiOwner.CRONS
@extend_schema(
operation_id="Retrieve a Monitor",
parameters=[
... | OrganizationMonitorDetailsEndpoint |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/big_query.py | {
"start": 736,
"end": 1541
} | class ____(DataSourceTestConfig):
@property
@override
def label(self) -> str:
return "big-query"
@property
@override
def pytest_mark(self) -> pytest.MarkDecorator:
return pytest.mark.bigquery
@override
def create_batch_setup(
self,
request: pytest.Fixtur... | BigQueryDatasourceTestConfig |
python | facelessuser__soupsieve | tests/test_extra/test_attribute.py | {
"start": 54,
"end": 1491
} | class ____(util.TestCase):
"""Test attribute selectors."""
MARKUP = """
<div id="div">
<p id="0">Some text <span id="1"> in a paragraph</span>.</p>
<a id="2" href="http://google.com">Link</a>
<span id="3">Direct child</span>
<pre id="pre">
<span id="4">Child 1</span>
<span id="5">Ch... | TestAttribute |
python | django__django | django/contrib/gis/db/backends/oracle/operations.py | {
"start": 2047,
"end": 9120
} | class ____(BaseSpatialOperations, DatabaseOperations):
name = "oracle"
oracle = True
disallowed_aggregates = (models.Collect, models.Extent3D, models.MakeLine)
Adapter = OracleSpatialAdapter
extent = "SDO_AGGR_MBR"
unionagg = "SDO_AGGR_UNION"
from_text = "SDO_GEOMETRY"
function_names... | OracleOperations |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 42161,
"end": 42455
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
full_refresh: Optional[bool] = Field(
None, description="If true, triggers a full refresh on the delta live table."
)
| PipelineParams |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/choose_from_datasets_test.py | {
"start": 1345,
"end": 6136
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(test_base.default_test_combinations())
def testChooseFromDatasets(self):
words = [b"foo", b"bar", b"baz"]
datasets = [dataset_ops.Dataset.from_tensors(w).repeat() for w in words]
choice_array = np.random.randint(3, si... | ChooseFromDatasetsTest |
python | django__django | tests/base/models.py | {
"start": 261,
"end": 318
} | class ____(models.base.ModelBase):
pass
| CustomBaseModel |
python | pandas-dev__pandas | pandas/tests/computation/test_eval.py | {
"start": 63522,
"end": 73045
} | class ____:
def test_global_scope(self, engine, parser):
e = "_var_s * 2"
tm.assert_numpy_array_equal(
_var_s * 2, pd.eval(e, engine=engine, parser=parser)
)
def test_no_new_locals(self, engine, parser):
x = 1
lcls = locals().copy()
pd.eval("x + 1", l... | TestScope |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 191287,
"end": 191445
} | class ____(InputsKernel):
def is_no_op(self) -> bool:
return True
def get_reads(self) -> OrderedSet[Dep]:
return OrderedSet()
| NopKernel |
python | rushter__MLAlgorithms | mla/neuralnet/regularizers.py | {
"start": 410,
"end": 508
} | class ____(Regularizer):
def _penalty(self, weights):
return self.C * np.abs(weights)
| L1 |
python | celery__celery | t/unit/app/test_registry.py | {
"start": 558,
"end": 2349
} | class ____:
def setup_method(self):
self.mytask = self.app.task(name='A', shared=False)(returns)
self.missing_name_task = self.app.task(
name=None, shared=False)(returns)
self.missing_name_task.name = None # name is overridden with path
self.myperiodic = self.app.task(
... | test_TaskRegistry |
python | doocs__leetcode | lcof/面试题37. 序列化二叉树/Solution.py | {
"start": 172,
"end": 1441
} | class ____:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if root is None:
return ""
q = deque([root])
ans = []
while q:
node = q.popleft()
if node:
... | Codec |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_comprehend.py | {
"start": 1711,
"end": 4365
} | class ____:
@pytest.mark.parametrize("aws_conn_id", [None, NOTSET, "aws_test_conn"])
@pytest.mark.parametrize("region_name", [None, NOTSET, "ca-central-1"])
def test_initialize_comprehend_base_operator(self, aws_conn_id, region_name):
op_kw = {"aws_conn_id": aws_conn_id, "region_name": region_name}
... | TestComprehendBaseOperator |
python | kamyu104__LeetCode-Solutions | Python/divide-two-integers.py | {
"start": 39,
"end": 1187
} | class ____(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
result, dvd, dvs = 0, abs(dividend), abs(divisor)
while dvd >= dvs:
inc = dvs
i = 0
while dvd >= inc:
... | Solution |
python | PyCQA__pylint | pylint/checkers/variables.py | {
"start": 17967,
"end": 47319
} | class ____:
"""A simple class to handle consumed, to consume and scope type info of node locals."""
node: nodes.NodeNG
scope_type: str
to_consume: Consumption
consumed: Consumption
consumed_uncertain: Consumption
"""Retrieves nodes filtered out by get_next_to_consume() that may not
hav... | NamesConsumer |
python | great-expectations__great_expectations | tests/datasource/fluent/test_spark_azure_blob_storage_datasource.py | {
"start": 1251,
"end": 10358
} | class ____:
# noinspection PyMethodMayBeStatic,PyUnusedLocal
def get_container_client(self, container: str) -> azure.ContainerClient:
return cast("azure.ContainerClient", MockContainerClient())
def _build_spark_abs_datasource(
azure_options: Dict[str, Any] | None = None,
) -> SparkAzureBlobStorage... | MockBlobServiceClient |
python | pytorch__pytorch | torchgen/_autoheuristic/pad_mm/gen_data_pad_mm.py | {
"start": 537,
"end": 4717
} | class ____(BenchmarkRunner): # type: ignore[misc, no-any-unimported]
"""
BenchmarkRunner for pad_mm. Used to generate collect training data with AutoHeuristic to learn a heuristic.
"""
def __init__(self) -> None:
super().__init__("pad_mm")
def create_input(self) -> tuple[Any, ...]:
... | BenchmarkRunnerPadMM |
python | huggingface__transformers | tests/models/qwen2_audio/test_modeling_qwen2_audio.py | {
"start": 1319,
"end": 4715
} | class ____:
def __init__(
self,
parent,
ignore_index=-100,
audio_token_index=0,
seq_length=25,
feat_seq_length=60,
text_config={
"model_type": "qwen2",
"intermediate_size": 36,
"initializer_range": 0.02,
"hidden_... | Qwen2AudioModelTester |
python | run-llama__llama_index | llama-index-core/llama_index/core/objects/tool_node_mapping.py | {
"start": 3033,
"end": 3873
} | class ____(BaseObjectNodeMapping[QueryEngineTool]):
"""Base query tool node mapping."""
@classmethod
def from_persist_dir(
cls,
persist_dir: str = DEFAULT_PERSIST_DIR,
obj_node_mapping_fname: str = DEFAULT_PERSIST_FNAME,
) -> "BaseQueryToolNodeMapping":
raise NotImplemen... | BaseQueryToolNodeMapping |
python | Textualize__textual | src/textual/reactive.py | {
"start": 16065,
"end": 18056
} | class ____(Reactive[ReactiveType]):
"""Create a reactive attribute (with no auto-refresh).
Args:
default: A default value or callable that returns a default.
init: Call watchers on initialize (post mount).
always_update: Call watchers even when the new value equals the old value.
... | var |
python | ansible__ansible | lib/ansible/module_utils/facts/network/aix.py | {
"start": 856,
"end": 5892
} | class ____(GenericBsdIfconfigNetwork):
"""
This is the AIX Network Class.
It uses the GenericBsdIfconfigNetwork unchanged.
"""
platform = 'AIX'
def get_default_interfaces(self, route_path):
interface = dict(v4={}, v6={})
netstat_path = self.module.get_bin_path('netstat')
... | AIXNetwork |
python | eventlet__eventlet | tests/mock.py | {
"start": 3852,
"end": 9801
} | class ____:
__slots__ = ['a']
DescriptorTypes = (
type(_slotted.a),
property,
)
def _getsignature(func, skipfirst, instance=False):
if inspect is None:
raise ImportError('inspect module not available')
if isinstance(func, ClassTypes) and not instance:
try:
func = fun... | _slotted |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jina-ai-reader/source_jina_ai_reader/config_migration.py | {
"start": 439,
"end": 3071
} | class ____:
"""
This class stands for migrating the search prompt config at runtime to encode characters.
"""
message_repository: MessageRepository = InMemoryMessageRepository()
@classmethod
def should_migrate(cls, config: Mapping[str, Any]) -> bool:
"""
based on the source spe... | JinaAiReaderConfigMigration |
python | tornadoweb__tornado | demos/websocket/chatdemo.py | {
"start": 1400,
"end": 1536
} | class ____(tornado.web.RequestHandler):
def get(self):
self.render("index.html", messages=ChatSocketHandler.cache)
| MainHandler |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 69364,
"end": 70760
} | class ____(rv_continuous):
r"""An exponential power continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `exponpow` is:
.. math::
f(x, b) = b x^{b-1} \exp(1 + x^b - \exp(x^b))
for :math:`x \ge 0`, :math:`b > 0`. Note that this is a diffe... | exponpow_gen |
python | huggingface__transformers | src/transformers/models/smollm3/modular_smollm3.py | {
"start": 13153,
"end": 13196
} | class ____(Qwen2Model):
pass
| SmolLM3Model |
python | spyder-ide__spyder | spyder/plugins/plots/plugin.py | {
"start": 426,
"end": 2730
} | class ____(SpyderDockablePlugin, ShellConnectPluginMixin):
"""
Plots plugin.
"""
NAME = 'plots'
REQUIRES = [Plugins.IPythonConsole]
TABIFY = [Plugins.VariableExplorer, Plugins.Help]
WIDGET_CLASS = PlotsWidget
CONF_SECTION = NAME
CONF_FILE = False
DISABLE_ACTIONS_WHEN_HIDDEN = Fal... | Plots |
python | xlwings__xlwings | xlwings/conversion/framework.py | {
"start": 664,
"end": 1092
} | class ____(dict):
def __init__(self, original):
super(Options, self).__init__(original)
def override(self, **overrides):
self.update(overrides)
return self
def erase(self, keys):
for key in keys:
self.pop(key, None)
return self
def defaults(self, **... | Options |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc8628/errors.py | {
"start": 1564,
"end": 1684
} | class ____(OAuth2Error):
"""
The authorization request was denied.
"""
error = "access_denied"
| AccessDenied |
python | sphinx-doc__sphinx | sphinx/domains/cpp/__init__.py | {
"start": 16629,
"end": 16694
} | class ____(CPPObject):
object_type = 'concept'
| CPPConceptObject |
python | jina-ai__jina | jina/clients/mixin.py | {
"start": 2822,
"end": 3709
} | class ____(MutateMixin):
"""The async GraphQL Mutation Mixin for Client and Flow"""
async def mutate(
self,
mutation: str,
variables: Optional[dict] = None,
timeout: Optional[float] = None,
headers: Optional[dict] = None,
):
"""Perform a GraphQL mutation, asy... | AsyncMutateMixin |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/mesh_util_test.py | {
"start": 1205,
"end": 10709
} | class ____(test_util.DTensorBaseTest):
"""Tests for mesh_util that do not require accelerator initialization."""
def test_mesh_creation(self):
self.skipForDeviceType(
['TPU'], reason='Test is intended for CPUs and GPUs.'
)
mesh = mesh_util.create_mesh()
num_devices = len(test_util.list_loca... | MeshUtilTest |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable_py30.py | {
"start": 2500,
"end": 2658
} | class ____(type):
def __new__(mcs, *args, parameter=None, **kwargs):
print(parameter)
return super().__new__(mcs, *args, **kwargs)
| MetaClass |
python | huggingface__transformers | src/transformers/models/idefics2/processing_idefics2.py | {
"start": 1565,
"end": 11531
} | class ____(ProcessorMixin):
r"""
Constructs a IDEFICS2 processor which wraps a LLama tokenizer and IDEFICS2 image processor into a single processor.
[`IdeficsProcessor`] offers all the functionalities of [`Idefics2ImageProcessor`] and [`LlamaTokenizerFast`]. See
the docstring of [`~IdeficsProcessor.__c... | Idefics2Processor |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_redirects.py | {
"start": 4167,
"end": 5798
} | class ____(TestCase):
fixtures = ["eric", "test_data"]
def setUp(self):
self.proj = Project.objects.get(slug="read-the-docs")
self.redirect = get(Redirect, project=self.proj)
def test_http_filenames_return_themselves(self):
# If the crossdomain flag is False (default), then we don'... | GetFullPathTests |
python | google__jax | jax/_src/pallas/core.py | {
"start": 13044,
"end": 13685
} | class ____:
"""Helper class that checks for index_map equality."""
def __init__(self, index_map):
self.index_map = index_map
functools.update_wrapper(self, self.index_map)
def __eq__(self, other: object):
if not isinstance(other, _IndexMapFunc):
return NotImplemented
return self.index_map ... | _IndexMapFunc |
python | astropy__astropy | astropy/nddata/mixins/ndio.py | {
"start": 1880,
"end": 3395
} | class ____(registry.UnifiedReadWrite):
"""Write this CCDData object out in the specified format.
This function provides the NDData interface to the astropy unified I/O
layer. This allows easily writing a file in many supported data formats
using syntax such as::
>>> from astropy.nddata import C... | NDDataWrite |
python | doocs__leetcode | solution/1600-1699/1664.Ways to Make a Fair Array/Solution.py | {
"start": 0,
"end": 417
} | class ____:
def waysToMakeFair(self, nums: List[int]) -> int:
s1, s2 = sum(nums[::2]), sum(nums[1::2])
ans = t1 = t2 = 0
for i, v in enumerate(nums):
ans += i % 2 == 0 and t2 + s1 - t1 - v == t1 + s2 - t2
ans += i % 2 == 1 and t2 + s1 - t1 == t1 + s2 - t2 - v
... | Solution |
python | pandas-dev__pandas | asv_bench/benchmarks/multiindex_object.py | {
"start": 10819,
"end": 11532
} | class ____:
def setup(self):
N = 10**5
level1 = range(1_000)
level2 = date_range(start="1/1/2000", periods=N // 1000)
self.midx = MultiIndex.from_product([level1, level2])
level1 = range(1_000, 2_000)
self.midx_values = MultiIndex.from_product([level1, level2])
... | Putmask |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_audio.py | {
"start": 4543,
"end": 5067
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.layers = nn.ModuleList(
[Data2VecAudioPositionalConvLayer(config) for _ in range(config.num_conv_pos_embeddings)]
)
def forward(self, hidden_states):
hidden_states = hidden_states.transpose(1,... | Data2VecAudioPositionalConvEmbedding |
python | pypa__warehouse | warehouse/manage/forms.py | {
"start": 19913,
"end": 21802
} | class ____(wtforms.Form):
__params__ = ["display_name", "link_url", "description", "orgtype"]
display_name = wtforms.StringField(
validators=[
wtforms.validators.InputRequired(message="Specify your organization name"),
wtforms.validators.Length(
max=100,
... | SaveOrganizationForm |
python | pytorch__pytorch | torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py | {
"start": 17267,
"end": 17683
} | class ____(RpcAgentTestFixture):
@property
def world_size(self) -> int:
return NUM_TRAINERS
def trainer_name(self, rank):
# The name has to be consistent with that in 'dist_init' decorator.
return f"worker{rank}"
@staticmethod
def get_remote_grads(rref, context_id):
... | CommonDdpComparisonTest |
python | tensorflow__tensorflow | tensorflow/python/autograph/operators/py_builtins_test.py | {
"start": 1595,
"end": 27219
} | class ____(test.TestCase):
def test_abs(self):
self.assertEqual(py_builtins.abs_(-1), 1)
with self.cached_session() as sess:
t = py_builtins.abs_(constant_op.constant(-1))
self.assertEqual(self.evaluate(t), 1)
t = py_builtins.abs_(constant_op.constant([-1, 2, -3]))
self.assertAllEqual... | PyBuiltinsTest |
python | django__django | django/template/base.py | {
"start": 13173,
"end": 15841
} | class ____:
def __init__(self, template_string):
self.template_string = template_string
self.verbatim = False
def __repr__(self):
return '<%s template_string="%s...", verbatim=%s>' % (
self.__class__.__qualname__,
self.template_string[:20].replace("\n", ""),
... | Lexer |
python | keras-team__keras | keras/src/quantizers/gptq.py | {
"start": 11166,
"end": 20175
} | class ____:
def __init__(self, layer, config=GPTQConfig(tokenizer=None, dataset=None)):
self.original_layer = layer
self.num_samples = 0
self.config = config
self.quantizer = GPTQQuantizer(
config, compute_dtype=layer.variable_dtype
)
# Explicitly handle ... | GPTQ |
python | django__django | tests/generic_views/test_base.py | {
"start": 15540,
"end": 22347
} | class ____(LoggingAssertionMixin, SimpleTestCase):
rf = RequestFactory()
def test_no_url(self):
"Without any configuration, returns HTTP 410 GONE"
response = RedirectView.as_view()(self.rf.get("/foo/"))
self.assertEqual(response.status_code, 410)
def test_default_redirect(self):
... | RedirectViewTest |
python | pytorch__pytorch | torch/_subclasses/_fake_tensor_utils.py | {
"start": 5458,
"end": 6567
} | class ____:
"""
Represents a SymInt in the cached output.
"""
# This is either an `int` which represents the index in the key to copy the
# SymNode from or it's the deconstructed SymNode itself.
value: Union[int, _DeconstructedSymNode]
def __init__(self, value: SymInt, key_path: Optional[i... | _SymIntOutputStub |
python | numba__numba | numba/cpython/listobj.py | {
"start": 4090,
"end": 4809
} | class ____(_ListPayloadMixin):
"""
A helper object to access the list attributes given the pointer to the
payload type.
"""
def __init__(self, context, builder, list_type, payload_ptr):
self._context = context
self._builder = builder
self._ty = list_type
self._datamod... | ListPayloadAccessor |
python | kamyu104__LeetCode-Solutions | Python/house-robber-iv.py | {
"start": 822,
"end": 1467
} | class ____(object):
def minCapability(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def check(x):
cnt = i = 0
while i < len(nums):
if nums[i] <= x:
cnt += 1
i += 2... | Solution2 |
python | pyca__cryptography | src/cryptography/x509/certificate_transparency.py | {
"start": 438,
"end": 797
} | class ____(utils.Enum):
"""
Signature algorithms that are valid for SCTs.
These are exactly the same as SignatureAlgorithm in RFC 5246 (TLS 1.2).
See: <https://datatracker.ietf.org/doc/html/rfc5246#section-7.4.1.4.1>
"""
ANONYMOUS = 0
RSA = 1
DSA = 2
ECDSA = 3
SignedCertificateT... | SignatureAlgorithm |
python | getsentry__sentry | src/sentry/hybridcloud/services/tombstone/impl.py | {
"start": 446,
"end": 674
} | class ____(ControlTombstoneService):
def record_remote_tombstone(self, *, tombstone: RpcTombstone) -> None:
ControlTombstone.record_delete(tombstone.table_name, tombstone.identifier)
| DatabaseBackedControlTombstoneService |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_slots/SLOT000.py | {
"start": 198,
"end": 237
} | class ____(str, SubEnum): # Ok
pass
| Ok |
python | Textualize__textual | docs/examples/how-to/render_compose.py | {
"start": 974,
"end": 1173
} | class ____(App):
"""Simple app to show our custom widget."""
def compose(self) -> ComposeResult:
yield Splash()
if __name__ == "__main__":
app = SplashApp()
app.run()
| SplashApp |
python | celery__celery | t/unit/utils/test_platforms.py | {
"start": 1059,
"end": 2161
} | class ____:
def test_long_opt(self):
assert _find_option_with_arg(
['--foo=bar'], long_opts=['--foo']) == 'bar'
def test_short_opt(self):
assert _find_option_with_arg(
['-f', 'bar'], short_opts=['-f']) == 'bar'
@t.skip.if_win32
def test_fd_by_path():
test_file = t... | test_find_option_with_arg |
python | pytorch__pytorch | test/test_cpp_extensions_stream_and_event.py | {
"start": 1047,
"end": 3792
} | class ____(common.TestCase):
"""Tests Stream and Event with C++ extensions."""
module = None
def setUp(self):
super().setUp()
# cpp extensions use relative paths. Those paths are relative to
# this file, so we'll change the working directory temporarily
self.old_working_dir... | TestCppExtensionStreamAndEvent |
python | wandb__wandb | wandb/sdk/launch/errors.py | {
"start": 121,
"end": 207
} | class ____(Error):
"""Raised when Docker daemon is not running."""
| LaunchDockerError |
python | google__jax | docs/autodidax.py | {
"start": 10204,
"end": 14770
} | class ____(ShapedArray):
array_abstraction_level = 2
val: np.ndarray
def __init__(self, val):
self.val = val
self.shape = val.shape
self.dtype = val.dtype
@staticmethod
def _bool(tracer):
return bool(tracer.aval.val)
@staticmethod
def _nonzero(tracer):
return bool(tracer.aval.val)
... | ConcreteArray |
python | PrefectHQ__prefect | tests/test_context.py | {
"start": 1455,
"end": 5603
} | class ____(ContextModel):
__var__: ContextVar = ContextVar("test")
x: int
def test_context_enforces_types():
with pytest.raises(ValueError):
ExampleContext(x="hello")
def test_context_get_outside_context_is_null():
assert ExampleContext.get() is None
def test_single_context_object_cannot_... | ExampleContext |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 114554,
"end": 114670
} | class ____(MaybeAlignPartitions):
_parameters = ["frame", "cond", "other"]
_expr_cls: AnyType = Mask
| MaskAlign |
python | pandas-dev__pandas | pandas/plotting/_matplotlib/core.py | {
"start": 72200,
"end": 75297
} | class ____(MPLPlot):
@property
def _kind(self) -> Literal["pie"]:
return "pie"
_layout_type = "horizontal"
def __init__(self, data: Series | DataFrame, kind=None, **kwargs) -> None:
data = data.fillna(value=0)
lt_zero = data < 0
if isinstance(data, ABCDataFrame) and lt_... | PiePlot |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_bytes.py | {
"start": 1898,
"end": 3168
} | class ____(BaseTestZDType):
test_cls = RawBytes
valid_dtype = (np.dtype("|V10"),)
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.float64),
np.dtype("|S10"),
)
valid_json_v2 = ({"name": "|V10", "object_codec_id": None},)
valid_json_v3 = (
{"name": "raw_bytes", "c... | TestRawBytes |
python | doocs__leetcode | solution/1100-1199/1160.Find Words That Can Be Formed by Characters/Solution.py | {
"start": 0,
"end": 286
} | class ____:
def countCharacters(self, words: List[str], chars: str) -> int:
cnt = Counter(chars)
ans = 0
for w in words:
wc = Counter(w)
if all(cnt[c] >= v for c, v in wc.items()):
ans += len(w)
return ans
| Solution |
python | spyder-ide__spyder | external-deps/python-lsp-server/test/plugins/test_completion.py | {
"start": 1418,
"end": 20771
} | class ____(NamedTuple):
document: str
position: dict
label: str
expected: lsp.CompletionItemKind
# fmt: off
TYPE_CASES: dict[str, TypeCase] = {
"variable": TypeCase(
document="test = 1\ntes",
position={"line": 1, "character": 3},
label="test",
expected=lsp.Completio... | TypeCase |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/yaml_utils/source_position.py | {
"start": 6056,
"end": 6354
} | class ____(NamedTuple):
"""A tree-like object (like a JSON-structured dict) and an accompanying SourcePositionTree.
Each tree node in the SourcePositionTree is expected to correspond to in value.
"""
value: Any
source_position_tree: SourcePositionTree
| ValueAndSourcePositionTree |
python | run-llama__llama_index | llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-elasticsearch/llama_index/storage/kvstore/elasticsearch/base.py | {
"start": 2132,
"end": 9780
} | class ____(BaseKVStore):
"""
Elasticsearch Key-Value store.
Args:
index_name: Name of the Elasticsearch index.
es_client: Optional. Pre-existing AsyncElasticsearch client.
es_url: Optional. Elasticsearch URL.
es_cloud_id: Optional. Elasticsearch cloud ID.
es_api_key:... | ElasticsearchKVStore |
python | pytorch__pytorch | test/distributed/test_local_tensor.py | {
"start": 20130,
"end": 21119
} | class ____(LocalTensorTestBase):
world_size = 8
def test_dtensor_addmm(self):
with LocalTensorMode(self.world_size):
device_mesh = self.build_device_mesh()
shard_spec = [Shard(0)]
replica_spec = [Replicate()]
tensor_to_shard = torch.randn(12, 8)
... | TestLocalTensorWorld8 |
python | PrefectHQ__prefect | src/prefect/server/events/actions.py | {
"start": 55957,
"end": 57357
} | class ____(WorkQueueAction, ExternalDataAction):
_action_description: ClassVar[str]
async def act(self, triggered_action: "TriggeredAction") -> None:
work_queue_id = await self.work_queue_id_to_use(triggered_action)
self._resulting_related_resources += [
RelatedResource.model_valid... | WorkQueueCommandAction |
python | davidhalter__jedi | test/refactor/extract_function.py | {
"start": 3298,
"end": 3466
} | class ____(int):
@staticmethod
def f(x):
#? 16 text {'new_name': 'ab'}
return ab()
# -------------------------------------------------- in-class-1
| X |
python | pytorch__pytorch | torch/nn/parallel/_functions.py | {
"start": 1233,
"end": 1778
} | class ____(Function):
@staticmethod
def forward(ctx, destination, num_inputs, *grads):
ctx.target_gpus = [
grads[i].get_device() for i in range(0, len(grads), num_inputs)
]
grads_ = [grads[i : i + num_inputs] for i in range(0, len(grads), num_inputs)]
return comm.red... | ReduceAddCoalesced |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets_tests/snippet_checks/utils.py | {
"start": 9793,
"end": 17964
} | class ____:
def __init__(
self,
snapshot_base_dir: Path,
should_update_snippets: bool,
global_snippet_replace_regexes: Sequence[tuple[str, str]],
) -> None:
self._should_update_snippets = should_update_snippets
self._snip_number = 0
self._snapshot_base_dir... | SnippetGenerationContext |
python | aio-libs__aiohttp | aiohttp/client_exceptions.py | {
"start": 7018,
"end": 7992
} | class ____(ClientError, ValueError):
"""Invalid URL.
URL used for fetching is malformed, e.g. it doesn't contains host
part.
"""
# Derive from ValueError for backward compatibility
def __init__(self, url: StrOrURL, description: str | None = None) -> None:
# The type of url is not yarl... | InvalidURL |
python | networkx__networkx | networkx/exception.py | {
"start": 2446,
"end": 2560
} | class ____(NetworkXException):
"""Exception raised if requested node is not present in the graph"""
| NodeNotFound |
python | huggingface__transformers | src/transformers/models/csm/modeling_csm.py | {
"start": 16534,
"end": 18438
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: CsmConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = CsmAttention(config=config, layer_idx=layer_idx)
self.mlp = CsmMLP(config)
self.input_layernorm = CsmRMSN... | CsmDecoderLayer |
python | django__django | tests/serializers/models/data.py | {
"start": 2983,
"end": 3165
} | class ____(models.Model):
"""This is a model that can be used as
something for other models to point at"""
data = models.CharField(unique=True, max_length=30)
| UniqueAnchor |
python | dask__distributed | distributed/variable.py | {
"start": 4587,
"end": 8956
} | class ____:
"""Distributed Global Variable
This allows multiple clients to share futures and data between each other
with a single mutable variable. All metadata is sequentialized through the
scheduler. Race conditions can occur.
Values must be either Futures or msgpack-encodable data (ints, lis... | Variable |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/check_ops_test.py | {
"start": 16201,
"end": 21225
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_doesnt_raise_when_equal(self):
x = constant_op.constant(1., name="x")
y = constant_op.constant(1., name="y")
with ops.control_dependencies(
[check_ops.assert_near(x, y, message="failure message")]):
out = array_op... | AssertAllCloseTest |
python | pytorch__pytorch | torch/utils/data/datapipes/iter/combining.py | {
"start": 10869,
"end": 15224
} | class ____(IterDataPipe):
r"""
Iterable Datapipe that is a child of a main DataPipe.
The instance of this class will pass its instance_id to get the next value from its main DataPipe.
Note:
ChildDataPipe, like all other IterDataPipe, follows the single iterator per IterDataPipe constraint.
... | _ChildDataPipe |
python | coleifer__peewee | tests/postgres.py | {
"start": 1148,
"end": 1300
} | class ____(TestModel):
key = CharField(max_length=100, primary_key=True)
timestamps = ArrayField(TimestampField, convert_values=True)
| ArrayTSModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 756,
"end": 1025
} | class ____(sgqlc.types.Enum):
"""Properties by which Audit Log connections can be ordered.
Enumeration Choices:
* `CREATED_AT`: Order audit log entries by timestamp
"""
__schema__ = github_schema
__choices__ = ("CREATED_AT",)
| AuditLogOrderField |
python | getsentry__sentry | tests/sentry/uptime/subscriptions/test_tasks.py | {
"start": 15327,
"end": 15701
} | class ____(ConfigPusherTestMixin):
def test_with_region(self) -> None:
subscription_id = uuid4().hex
region_slug = "default"
send_uptime_config_deletion(region_slug, subscription_id)
self.assert_redis_config(
region_slug, UptimeSubscription(subscription_id=subscription_id... | SendUptimeConfigDeletionTest |
python | great-expectations__great_expectations | great_expectations/metrics/batch/batch.py | {
"start": 241,
"end": 398
} | class ____(Metric[_MetricResult], kw_only=True):
row_condition: Optional[StrictStr] = None
condition_parser: Optional[ConditionParser] = None
| BatchMetric |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 111736,
"end": 113354
} | class ____(MeanMetricWrapper):
"""Computes the crossentropy metric between the labels and predictions.
This is the crossentropy metric class to be used when there are only two
label classes (0 and 1).
Args:
name: (Optional) string name of the metric instance.
dtype: (Optional) data type of the metric ... | BinaryCrossentropy |
python | astropy__astropy | astropy/convolution/tests/test_convolve_kernels.py | {
"start": 1566,
"end": 4403
} | class ____:
@pytest.mark.parametrize("kernel", KERNELS)
def test_centered_makekernel(self, kernel):
"""
Test smoothing of an image with a single positive pixel
"""
shape = kernel.array.shape
x = np.zeros(shape)
xslice = tuple(slice(sh // 2, sh // 2 + 1) for sh i... | Test2DConvolutions |
python | pennersr__django-allauth | allauth/account/forms.py | {
"start": 20463,
"end": 20626
} | class ____(forms.Form):
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(UserForm, self).__init__(*args, **kwargs)
| UserForm |
python | doocs__leetcode | solution/2800-2899/2898.Maximum Linear Stock Score/Solution.py | {
"start": 0,
"end": 190
} | class ____:
def maxScore(self, prices: List[int]) -> int:
cnt = Counter()
for i, x in enumerate(prices):
cnt[x - i] += x
return max(cnt.values())
| Solution |
python | huggingface__transformers | tests/models/patchtsmixer/test_modeling_patchtsmixer.py | {
"start": 2057,
"end": 7349
} | class ____:
def __init__(
self,
context_length: int = 32,
patch_length: int = 8,
num_input_channels: int = 3,
patch_stride: int = 8,
# d_model: int = 128,
hidden_size: int = 8,
# num_layers: int = 8,
num_hidden_layers: int = 2,
expansio... | PatchTSMixerModelTester |
python | ijl__orjson | test/test_ujson.py | {
"start": 93,
"end": 10730
} | class ____:
def test_doubleLongIssue(self):
sut = {"a": -4342969734183514}
encoded = orjson.dumps(sut)
decoded = orjson.loads(encoded)
assert sut == decoded
encoded = orjson.dumps(sut)
decoded = orjson.loads(encoded)
assert sut == decoded
def test_doubleL... | TestUltraJSON |
python | huggingface__transformers | src/transformers/models/metaclip_2/modular_metaclip_2.py | {
"start": 953,
"end": 4616
} | class ____(CLIPTextConfig):
r"""
This is the configuration class to store the configuration of a [`MetaClip2TextModel`]. It is used to instantiate
a MetaClip2 text encoder according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a ... | MetaClip2TextConfig |
python | getsentry__sentry | src/sentry/utils/imports.py | {
"start": 25,
"end": 690
} | class ____(dict[str, object]):
def __missing__(self, key: str) -> object:
if "." not in key:
return __import__(key)
module_name, class_name = key.rsplit(".", 1)
module = __import__(module_name, {}, {}, [class_name])
handler = getattr(module, class_name)
# We ca... | ModuleProxyCache |
python | justquick__django-activity-stream | actstream/tests/test_drf.py | {
"start": 1299,
"end": 5166
} | class ____(BaseDRFTestCase):
def test_actstream(self):
actions = self.get(reverse('action-list'))
assert len(actions) == 11
follows = self.get(reverse('follow-list'))
assert len(follows) == 6
@skipUnless(DRF_SETTINGS['HYPERLINK_FIELDS'], 'Related hyperlinks disabled')
def t... | DRFActionTestCase |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/llm.py | {
"start": 4491,
"end": 5121
} | class ____(BaseEvent):
"""
LLMChatInProgressEvent.
Args:
messages (List[ChatMessage]): List of chat messages.
response (ChatResponse): Chat response currently being streamed.
"""
messages: List[ChatMessage]
response: ChatResponse
@classmethod
def class_name(cls) -> st... | LLMChatInProgressEvent |
python | Textualize__textual | src/textual/css/tokenize.py | {
"start": 5563,
"end": 6965
} | class ____:
EXPECT: ClassVar[Expect] = expect_root_scope
STATE_MAP: ClassVar[dict[str, Expect]] = {}
STATE_PUSH: ClassVar[dict[str, Expect]] = {}
STATE_POP: ClassVar[dict[str, str]] = {}
def __init__(self) -> None:
self._expect: Expect = self.EXPECT
super().__init__()
def expec... | TokenizerState |
python | fastai__fastai | fastai/layers.py | {
"start": 6957,
"end": 9492
} | class ____(nn.Sequential):
"Module grouping `BatchNorm1d`, `Dropout` and `Linear` layers"
def __init__(self, n_in, n_out, bn=True, p=0., act=None, lin_first=False):
layers = [BatchNorm(n_out if lin_first else n_in, ndim=1)] if bn else []
if p != 0: layers.append(nn.Dropout(p))
lin = [nn.... | LinBnDrop |
python | bokeh__bokeh | src/bokeh/models/map_plots.py | {
"start": 3435,
"end": 4771
} | class ____(MapOptions):
''' Options for ``GMapPlot`` objects.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
map_type = Enum(MapType, default="roadmap", help="""
The `map type`_ to use for the... | GMapOptions |
python | ray-project__ray | rllib/utils/replay_buffers/multi_agent_replay_buffer.py | {
"start": 1865,
"end": 16374
} | class ____(ReplayBuffer):
"""A replay buffer shard for multiagent setups.
This buffer is meant to be run in parallel to distribute experiences
across `num_shards` shards. Unlike simpler buffers, it holds a set of
buffers - one for each policy ID.
"""
def __init__(
self,
capacit... | MultiAgentReplayBuffer |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 219073,
"end": 219926
} | class ____(unittest.TestCase):
def testRDM(self):
srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
self.addCleanup(srv.close)
self.addCleanup(cli.close)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
... | TIPCTest |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 36565,
"end": 36999
} | class ____(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
action: Annotated[
Literal["create"], Field(description="The action to be performed on the entities.", title="Action")
]
entities: Annotated[
list[PoolBody], Field(description="A list of entities to be create... | BulkCreateActionPoolBody |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.