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 | pydantic__pydantic | pydantic/types.py | {
"start": 16161,
"end": 16665
} | class ____(BaseModel):
strict_float: StrictFloat
try:
StrictFloatModel(strict_float='1.0')
except ValidationError as e:
print(e)
'''
1 validation error for StrictFloatModel
strict_float
Input should be a valid number [type=float_type, input_value='1.0', input_type=str]
'''
```
"""
Fin... | StrictFloatModel |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/stack.py | {
"start": 152,
"end": 1467
} | class ____:
parent: Optional["EvaluationStackEntry"]
@property
def entries(self) -> Sequence["EvaluationStackEntry"]:
return list(self.iter_entries())
def iter_entries(self) -> Iterator["EvaluationStackEntry"]:
if self.parent:
yield from self.parent.iter_entries()
... | EvaluationStackEntry |
python | numba__numba | numba/cuda/cudadecl.py | {
"start": 5501,
"end": 5671
} | class ____(ConcreteTemplate):
key = cuda.fp16.hfma
cases = [
signature(types.float16, types.float16, types.float16, types.float16)
]
@register
| Cuda_hfma |
python | gevent__gevent | src/greentest/3.14/test_urllib2.py | {
"start": 74306,
"end": 79603
} | class ____(unittest.TestCase):
def opener_has_handler(self, opener, handler_class):
self.assertTrue(any(h.__class__ == handler_class
for h in opener.handlers))
def test_build_opener(self):
class MyHTTPHandler(urllib.request.HTTPHandler):
pass
cl... | MiscTests |
python | Textualize__textual | tests/deadlock.py | {
"start": 134,
"end": 323
} | class ____(App[None]):
BINDINGS = [
Binding(key="q", action="quit", description="Quit the app"),
]
def compose(self):
yield Footer()
app = MyApp()
app.run()
| MyApp |
python | h5py__h5py | h5py/tests/test_h5p.py | {
"start": 4194,
"end": 5262
} | class ____(TestCase):
'''
Feature: setting/getting mdc config on a file access property list
'''
def test_mdc_config(self):
'''test get/set mdc config '''
falist = h5p.create(h5p.FILE_ACCESS)
config = falist.get_mdc_config()
falist.set_mdc_config(config)
def test_se... | TestFA |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/client/utils.py | {
"start": 1475,
"end": 2018
} | class ____(NamedTuple):
"""This class gives information about the result of shutting down the server for
a Dagster repository location using a GraphQL mutation.
Args:
status (ShutdownRepositoryLocationStatus) Whether the shutdown succeeded or failed.
message (Optional[str], optional): the f... | ShutdownRepositoryLocationInfo |
python | lazyprogrammer__machine_learning_examples | rl3/es_flappy.py | {
"start": 1805,
"end": 6111
} | class ____:
def __init__(self, D, M, K, f=relu):
self.D = D
self.M = M
self.K = K
self.f = f
def init(self):
D, M, K = self.D, self.M, self.K
self.W1 = np.random.randn(D, M) / np.sqrt(D)
# self.W1 = np.zeros((D, M))
self.b1 = np.zeros(M)
self.W2 = np.random.randn(M, K) / np.sqrt... | ANN |
python | PrefectHQ__prefect | tests/blocks/test_abstract.py | {
"start": 2020,
"end": 3875
} | class ____:
def test_job_block_is_abstract(self):
with pytest.raises(
TypeError, match="Can't instantiate abstract class JobBlock"
):
JobBlock()
def test_job_block_implementation(self, caplog):
class AJobRun(JobRun):
def __init__(self):
... | TestJobBlock |
python | allegroai__clearml | clearml/backend_config/config.py | {
"start": 1080,
"end": 1461
} | class ____(Entry):
logger = None
def __init__(self, config: "Config", *keys: Text, **kwargs: Any) -> None:
super(ConfigEntry, self).__init__(*keys, **kwargs)
self.config = config
def _get(self, key: Text) -> Any:
return self.config.get(key, NotSet)
def error(self, message: Tex... | ConfigEntry |
python | tornadoweb__tornado | tornado/test/routing_test.py | {
"start": 1535,
"end": 1812
} | class ____(AsyncHTTPTestCase):
def get_app(self):
return BasicRouter()
def test_basic_router(self):
response = self.fetch("/any_request")
self.assertEqual(response.body, b"OK")
resources = {} # type: typing.Dict[str, bytes]
| BasicRouterTestCase |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 77432,
"end": 79093
} | class ____(Request):
"""
Delete dataviews
:param ids: IDs of the dataviews to delete
:type ids: Sequence[str]
:param force: Allow deletion of published dataviews
:type force: bool
"""
_service = "dataviews"
_action = "delete_many"
_version = "2.23"
_schema = {
"defi... | DeleteManyRequest |
python | sanic-org__sanic | sanic/touchup/service.py | {
"start": 77,
"end": 907
} | class ____:
_registry: set[tuple[type, str]] = set()
@classmethod
def run(cls, app):
for target, method_name in cls._registry:
method = getattr(target, method_name)
if app.test_mode:
placeholder = f"_{method_name}"
if hasattr(target, placehol... | TouchUp |
python | apache__airflow | providers/snowflake/tests/unit/snowflake/hooks/test_snowflake_sql_api.py | {
"start": 6726,
"end": 60056
} | class ____:
@pytest.mark.parametrize(
("sql", "statement_count", "expected_response", "expected_query_ids"),
[
(SINGLE_STMT, 1, {"statementHandle": "uuid"}, ["uuid"]),
(SQL_MULTIPLE_STMTS, 4, {"statementHandles": ["uuid", "uuid1"]}, ["uuid", "uuid1"]),
],
)
@m... | TestSnowflakeSqlApiHook |
python | pytorch__pytorch | test/dynamo/test_subclasses.py | {
"start": 95301,
"end": 96977
} | class ____(torch.nn.Module):
def forward(
self,
primals_1: "Sym(s47)", # PlainAOTInput(idx=0)
primals_2: "Sym(s16)", # PlainAOTInput(idx=1)
primals_3: "f32[s47, s16]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=2), attr='a')
primals_4: "f32[s47, s16]", # SubclassGet... | GraphModule |
python | getsentry__sentry | src/sentry/plugins/base/v2.py | {
"start": 10732,
"end": 11045
} | class ____(IPlugin2, metaclass=PluginMount):
"""
A plugin should be treated as if it were a singleton. The owner does not
control when or how the plugin gets instantiated, nor is it guaranteed that
it will happen, or happen more than once.
"""
__version__ = 2
__all__ = ("Plugin2",)
| Plugin2 |
python | getsentry__sentry | src/sentry/api/endpoints/artifact_bundles.py | {
"start": 1148,
"end": 1357
} | class ____(SentryAPIException):
status_code = status.HTTP_400_BAD_REQUEST
code = "invalid_sort_by_parameter"
message = "You can either sort via 'date_added' or 'date_modified'"
| InvalidSortByParameter |
python | huggingface__transformers | src/transformers/models/ovis2/modeling_ovis2.py | {
"start": 5946,
"end": 8023
} | class ____(nn.Module):
def __init__(self, config: Ovis2VisionConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.image_size = config.image_size
self.patch_size = config.patch_size
self.patch_embedding = nn.Conv2d(
in_... | Ovis2VisionEmbeddings |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_union.py | {
"start": 29325,
"end": 39049
} | class ____:
def __init__(self, type_: Literal['alien']) -> None:
self.type_ = 'alien'
@pytest.fixture
def model_a_b_union_schema() -> core_schema.UnionSchema:
return core_schema.union_schema(
[
core_schema.model_schema(
cls=ModelA,
schema=core_schema... | ModelAlien |
python | pytorch__pytorch | torch/distributed/_local_tensor/__init__.py | {
"start": 67491,
"end": 71858
} | class ____:
"""
LocalTensor-aware version of _PhiloxState that manages per-rank RNG states.
This class handles the case where the generator state is a LocalTensor, allowing
different offsets and seeds for different virtual ranks.
Note: This is designed to be used as a drop-in replacement for _Philo... | _LocalPhiloxState |
python | scipy__scipy | scipy/linalg/tests/test_decomp_update.py | {
"start": 66420,
"end": 68424
} | class ____(BaseQRupdate):
dtype = np.dtype('D')
def test_form_qTu():
# We want to ensure that all of the code paths through this function are
# tested. Most of them should be hit with the rest of test suite, but
# explicit tests make clear precisely what is being tested.
#
# This function expec... | TestQRupdate_D |
python | protocolbuffers__protobuf | python/google/protobuf/internal/type_checkers.py | {
"start": 9374,
"end": 10048
} | class ____(object):
"""Checker used for double fields.
Performs type-check and range check.
"""
def CheckValue(self, proposed_value):
"""Check and convert proposed_value to float."""
if (not hasattr(proposed_value, '__float__') and
not hasattr(proposed_value, '__index__')) or (
typ... | DoubleValueChecker |
python | streamlit__streamlit | lib/tests/streamlit/config_util_test.py | {
"start": 1458,
"end": 10665
} | class ____(unittest.TestCase):
def test_clean(self):
result = config_util._clean(" clean this text ")
assert result == " clean this text "
def test_clean_empty_string(self):
result = config_util._clean("")
assert result == ""
def test_clean_paragraphs(self):
... | ConfigUtilTest |
python | django__django | tests/admin_inlines/models.py | {
"start": 7141,
"end": 7424
} | class ____(models.Model):
my_own_pk = models.CharField(max_length=100, primary_key=True)
name = models.CharField(max_length=100)
parent = models.ForeignKey(ParentModelWithCustomPk, models.CASCADE)
def get_absolute_url(self):
return "/child_model1/"
| ChildModel1 |
python | psf__requests | tests/test_utils.py | {
"start": 8044,
"end": 8295
} | class ____:
def test_valid(self):
assert is_ipv4_address("8.8.8.8")
@pytest.mark.parametrize("value", ("8.8.8.8.8", "localhost.localdomain"))
def test_invalid(self, value):
assert not is_ipv4_address(value)
| TestIsIPv4Address |
python | bokeh__bokeh | src/bokeh/models/css.py | {
"start": 3544,
"end": 3966
} | class ____(ImportedStyleSheet):
""" An imported stylesheet that's appended to the ``<head>`` element.
.. note::
A stylesheet will be appended only once, regardless of how
many times it's being used in other models.
"""
# explicit __init__ to support Init signatures
def __init__(sel... | GlobalImportedStyleSheet |
python | doocs__leetcode | solution/3200-3299/3205.Maximum Array Hopping Score I/Solution.py | {
"start": 0,
"end": 257
} | class ____:
def maxScore(self, nums: List[int]) -> int:
@cache
def dfs(i: int) -> int:
return max(
[(j - i) * nums[j] + dfs(j) for j in range(i + 1, len(nums))] or [0]
)
return dfs(0)
| Solution |
python | ipython__ipython | IPython/core/display.py | {
"start": 17791,
"end": 20455
} | class ____(DisplayObject):
"""JSON expects a JSON-able dict or list
not an already-serialized JSON string.
Scalar types (None, number, string) are not allowed, only dict or list containers.
"""
# wrap data in a property, which warns about passing already-serialized JSON
_data = None
def __... | JSON |
python | ray-project__ray | python/ray/train/v2/_internal/execution/context.py | {
"start": 1616,
"end": 2578
} | class ____:
"""Holds the metadata and context for the current training run."""
# The unique ID of the training run.
run_id: str = field(init=False, default_factory=lambda: uuid.uuid4().hex)
# The run configuration for the current training run.
run_config: RunConfig
# The configuration passed ... | TrainRunContext |
python | xlwings__xlwings | xlwings/expansion.py | {
"start": 1269,
"end": 1729
} | class ____(Expander):
def expand(self, rng):
if rng(2, 1).raw_value in _empty:
return Range(rng(1, 1), rng(1, rng.shape[1]))
elif rng(3, 1).raw_value in _empty:
return Range(rng(1, 1), rng(2, rng.shape[1]))
else:
end_row = rng(2, 1).end("down").row - rng.r... | VerticalExpander |
python | realpython__materials | fastapi-url-shortener/source_code_final/shortener_app/schemas.py | {
"start": 182,
"end": 234
} | class ____(URL):
url: str
admin_url: str
| URLInfo |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1186338,
"end": 1187524
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'head_ref_force_pushed' event on a given pull
request.
"""
__schema__ = github_schema
__field_names__ = ("actor", "after_commit", "before_commit", "created_at", "pull_request", "ref")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
... | HeadRefForcePushedEvent |
python | huggingface__transformers | tests/models/oneformer/test_modeling_oneformer.py | {
"start": 1592,
"end": 8633
} | class ____:
def __init__(
self,
parent,
batch_size=2,
is_training=True,
vocab_size=99,
use_auxiliary_loss=False,
num_queries=10,
num_channels=3,
min_size=32 * 8,
max_size=32 * 8,
num_labels=4,
hidden_dim=64,
sequ... | OneFormerModelTester |
python | numba__numba | numba/core/types/misc.py | {
"start": 8389,
"end": 8663
} | class ____(Type):
def __init__(self, name, members):
assert members in (2, 3)
self.members = members
self.has_step = members >= 3
super(SliceType, self).__init__(name)
@property
def key(self):
return self.members
| SliceType |
python | getsentry__sentry | src/sentry/integrations/discord/spec.py | {
"start": 778,
"end": 3291
} | class ____(MessagingIntegrationSpec):
@property
def provider_slug(self) -> str:
return IntegrationProviderSlug.DISCORD.value
@property
def action_service(self) -> ActionService:
return ActionService.DISCORD
@property
def integration_provider(self) -> type[IntegrationProvider]:
... | DiscordMessagingSpec |
python | kubernetes-client__python | kubernetes/e2e_test/test_utils.py | {
"start": 28221,
"end": 33599
} | class ____(unittest.TestCase):
def test_parse_quantity(self):
# == trivial returns ==
self.assertEqual(quantity.parse_quantity(Decimal(1)), Decimal(1))
self.assertEqual(quantity.parse_quantity(float(1)), Decimal(1))
self.assertEqual(quantity.parse_quantity(1), Decimal(1))
#... | TestUtilsUnitTests |
python | huggingface__transformers | tests/models/arcee/test_modeling_arcee.py | {
"start": 1241,
"end": 2468
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = ArceeModelTester
# Need to use `0.8` instead of `0.9` for `test_cpu_offload`
# This is because we are hitting edge cases with the causal_mask buffer
model_split_percents = [0.5, 0.7, 0.8]
# used in `test_torch_compile_for_train... | ArceeModelTest |
python | kamyu104__LeetCode-Solutions | Python/construct-the-minimum-bitwise-array-i.py | {
"start": 48,
"end": 301
} | class ____(object):
def minBitwiseArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return [x-(((x+1)&~x)>>1) if x&1 else -1 for x in nums]
# Time: O(n * r)
# Space: O(1)
# brute force
| Solution |
python | ray-project__ray | python/ray/data/_internal/issue_detection/issue_detector_manager.py | {
"start": 711,
"end": 3767
} | class ____:
def __init__(self, executor: "StreamingExecutor"):
ctx = executor._data_context
self._issue_detectors: List[IssueDetector] = [
cls.from_executor(executor) for cls in ctx.issue_detectors_config.detectors
]
self._last_detection_times: Dict[IssueDetector, float] ... | IssueDetectorManager |
python | doocs__leetcode | solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.py | {
"start": 722,
"end": 1162
} | class ____:
def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:
trie = Trie()
nums.sort()
j, n = 0, len(queries)
ans = [-1] * n
for i, (x, m) in sorted(zip(range(n), queries), key=lambda x: x[1][1]):
while j < len(nums) and nums[j] <= m:... | Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/special_math_ops_test.py | {
"start": 14211,
"end": 16184
} | class ____(test.TestCase, parameterized.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_spence_boundary(self):
self.assertAllClose(np.pi**2 / 6., special_math_ops.spence(0.))
self.assertAllClose(0., special_math_ops.spence(1.))
self.assertTrue(np.isnan(self.evaluate(special_math_ops.spence(... | SpenceTest |
python | openai__openai-python | src/openai/lib/streaming/chat/_completions.py | {
"start": 8642,
"end": 10139
} | class ____(Generic[ResponseFormatT]):
"""Context manager over a `AsyncChatCompletionStream` that is returned by `.stream()`.
This context manager ensures the response cannot be leaked if you don't read
the stream to completion.
Usage:
```py
async with client.chat.completions.stream(...) as str... | AsyncChatCompletionStreamManager |
python | walkccc__LeetCode | solutions/735. Asteroid Collision/735.py | {
"start": 0,
"end": 587
} | class ____:
def asteroidCollision(self, asteroids: list[int]) -> list[int]:
stack = []
for a in asteroids:
if a > 0:
stack.append(a)
else: # a < 0
# Destroy the previous positive one(s).
while stack and stack[-1] > 0 and stack[-1] < -a:
stack.pop()
if no... | Solution |
python | coleifer__peewee | peewee.py | {
"start": 163458,
"end": 163690
} | class ____(CharField):
field_type = 'CHAR'
def python_value(self, value):
value = super(FixedCharField, self).python_value(value)
if value:
value = value.strip()
return value
| FixedCharField |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 23551,
"end": 26238
} | class ____(Request):
"""
Create a new queue
:param name: Queue name Unique within the company.
:type name: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: System tags list. This field is reserved for system use, please don't use it.
:type system_tag... | CreateRequest |
python | realpython__materials | hashtable/01_hashtable_prototype/07_use_defensive_copying/hashtable.py | {
"start": 107,
"end": 1109
} | class ____:
def __init__(self, capacity):
self._pairs = capacity * [None]
def __len__(self):
return len(self._pairs)
def __delitem__(self, key):
if key in self:
self._pairs[self._index(key)] = None
else:
raise KeyError(key)
def __setitem__(self,... | HashTable |
python | walkccc__LeetCode | solutions/1252. Cells with Odd Values in a Matrix/1252-2.py | {
"start": 0,
"end": 524
} | class ____:
def oddCells(self, m: int, n: int, indices: list[list[int]]) -> int:
# rows[i] and cols[i] :=
# 1. True (flipped even times)
# 2. False (flipped odd times)
rows = [False] * m
cols = [False] * n
for r, c in indices:
rows[r] ^= True
cols[c] ^= True
oddRowsCount ... | Solution |
python | allegroai__clearml | clearml/utilities/proxy_object.py | {
"start": 2048,
"end": 3598
} | class ____(dict):
"""Dictionary wrapper that prevents modifications to the dictionary"""
def __init__(
self,
update_obj: Any,
update_func: Callable,
*args: Any,
**kwargs: Any,
) -> None:
super(ProxyDictPreWrite, self).__init__(*args, **kwargs)
self._u... | ProxyDictPreWrite |
python | redis__redis-py | redis/maint_notifications.py | {
"start": 322,
"end": 843
} | class ____(enum.Enum):
"""Valid endpoint types used in CLIENT MAINT_NOTIFICATIONS command."""
INTERNAL_IP = "internal-ip"
INTERNAL_FQDN = "internal-fqdn"
EXTERNAL_IP = "external-ip"
EXTERNAL_FQDN = "external-fqdn"
NONE = "none"
def __str__(self):
"""Return the string value of the e... | EndpointType |
python | cython__cython | Cython/Compiler/Code.py | {
"start": 47062,
"end": 47513
} | class ____:
"""Global info about a Python number constant held by GlobalState.
cname string
value string
py_type string int, long, float
value_code string evaluation code if different from value
"""
def __init__(self, cname, value, py_type, value_code=None):
... | NumConst |
python | rapidsai__cudf | python/pylibcudf/tests/test_column_from_device.py | {
"start": 704,
"end": 3689
} | class ____:
def __init__(self, obj, dtype):
self.obj = rmm.DeviceBuffer.to_device(obj, plc.utils._get_stream())
self.dtype = dtype
self.shape = (int(len(self.obj) / self.dtype.itemsize),)
self.strides = (self.dtype.itemsize,)
self.typestr = self.dtype.str
@property
d... | DataBuffer |
python | kamyu104__LeetCode-Solutions | Python/find-resultant-array-after-removing-anagrams.py | {
"start": 947,
"end": 1196
} | class ____(object):
def removeAnagrams(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
return [words[i] for i in xrange(len(words)) if i == 0 or sorted(words[i-1]) != sorted(words[i])]
| Solution3 |
python | aio-libs__aiohttp | aiohttp/client.py | {
"start": 4755,
"end": 5957
} | class ____:
total: float | None = None
connect: float | None = None
sock_read: float | None = None
sock_connect: float | None = None
ceil_threshold: float = 5
# pool_queue_timeout: Optional[float] = None
# dns_resolution_timeout: Optional[float] = None
# socket_connect_timeout: Optional... | ClientTimeout |
python | dask__dask | dask/dataframe/io/orc/arrow.py | {
"start": 159,
"end": 4485
} | class ____:
@classmethod
def read_metadata(
cls,
fs,
paths,
columns,
index,
split_stripes,
aggregate_files,
**kwargs,
):
# Convert root directory to file list.
# TODO: Handle hive-partitioned data
if len(paths) == 1 and ... | ArrowORCEngine |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 312658,
"end": 319237
} | class ____:
# Simple, 1d test: stacking 2 constant-padded neigh iterators
def test_simple_const(self):
dt = np.float64
# Test zero and one padding for simple data type
x = np.array([1, 2, 3], dtype=dt)
r = [np.array([0], dtype=dt),
np.array([0], dtype=dt),
... | TestStackedNeighborhoodIter |
python | wandb__wandb | wandb/sdk/data_types/plotly.py | {
"start": 729,
"end": 3357
} | class ____(Media):
"""W&B class for Plotly plots."""
_log_type = "plotly-file"
@classmethod
def make_plot_media(
cls: Type["Plotly"], val: Union["plotly.Figure", "matplotlib.artist.Artist"]
) -> Union[Image, "Plotly"]:
"""Create a Plotly object from a Plotly figure or a matplotlib ... | Plotly |
python | apache__airflow | providers/standard/tests/unit/standard/decorators/test_python_virtualenv.py | {
"start": 1959,
"end": 12617
} | class ____:
@CLOUDPICKLE_MARKER
def test_add_cloudpickle(self, dag_maker):
@task.virtualenv(serializer="cloudpickle", system_site_packages=False)
def f():
"""Ensure cloudpickle is correctly installed."""
import cloudpickle # noqa: F401
with dag_maker(serialized=... | TestPythonVirtualenvDecorator |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 32521,
"end": 34853
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: Qwen2_5OmniAudioEncoderConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = Qwen2_5OmniAudioAttention(config)
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.dropout = con... | Qwen2_5OmniAudioEncoderLayer |
python | scipy__scipy | scipy/integrate/tests/test_cubature.py | {
"start": 35540,
"end": 36604
} | class ____:
@pytest.mark.parametrize(("a", "b", "points"), [
(
[0, 1, -math.inf],
[1, math.inf, math.inf],
[
[1, 1, 1],
[0.5, 10, 10],
]
)
])
def test_infinite_limits_maintains_points(self, a, b, points, xp):
... | TestTransformations |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_coding_agents.py | {
"start": 1403,
"end": 1919
} | class ____(CodingAgentIntegration):
"""Mock coding agent installation for tests."""
def get_client(self):
return MockCodingAgentClient()
def launch(self, request: CodingAgentLaunchRequest) -> CodingAgentState:
return CodingAgentState(
id="mock-123",
status=CodingAge... | MockCodingAgentInstallation |
python | bokeh__bokeh | src/bokeh/models/widgets/tables.py | {
"start": 2638,
"end": 2901
} | class ____(Model):
''' Abstract base class for data table's cell formatters.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@abstract
| CellFormatter |
python | wandb__wandb | wandb/sdk/artifacts/_generated/artifact_collection_membership_files.py | {
"start": 1212,
"end": 1569
} | class ____(
GQLResult
):
page_info: PageInfoFragment = Field(alias="pageInfo")
edges: List[
ArtifactCollectionMembershipFilesProjectArtifactCollectionArtifactMembershipFilesEdges
]
total_count: Optional[int] = Field(alias="totalCount", default=None)
| ArtifactCollectionMembershipFilesProjectArtifactCollectionArtifactMembershipFiles |
python | huggingface__transformers | src/transformers/models/mixtral/modeling_mixtral.py | {
"start": 30835,
"end": 30938
} | class ____(GenericForTokenClassification, MixtralPreTrainedModel):
pass
| MixtralForTokenClassification |
python | psf__black | tests/data/cases/allow_empty_first_line.py | {
"start": 1524,
"end": 1794
} | class ____:
def method(self):
pass
async def async_fn():
"""Docstring."""
@decorated
async def async_fn():
"""Docstring."""
def top_level(
a: int,
b: str,
) -> Whatever[Generic, Something]:
def nested(x: int) -> int:
pass
| Cls |
python | pytorch__pytorch | test/test_jit_disabled.py | {
"start": 2113,
"end": 2396
} | class ____(torch.nn.Module):
def forward(self, input):
pass
sm = torch.jit.script(AModule())
print("Didn't throw exception")
"""
self.compare_enabled_disabled(_program_string)
if __name__ == '__main__':
if sys.version_info < (3, 14):
run_tests()
| AModule |
python | ray-project__ray | release/ray_release/tests/test_glue.py | {
"start": 1745,
"end": 1833
} | class ____(Test):
def get_anyscale_byod_image(self) -> str:
return ""
| MockTest |
python | cherrypy__cherrypy | cherrypy/process/win32.py | {
"start": 4380,
"end": 5348
} | class ____(dict):
"""Control codes used to "signal" a service via ControlService.
User-defined control codes are in the range 128-255. We generally use
the standard Python value for the Linux signal and add 128. Example:
>>> signal.SIGUSR1
10
control_codes['graceful'] = 128 + 10
... | _ControlCodes |
python | huggingface__transformers | src/transformers/models/esm/modeling_esm.py | {
"start": 37719,
"end": 39114
} | class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.out_proj = nn.Linear(config.hidden_... | EsmClassificationHead |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/build_systems/perl.py | {
"start": 638,
"end": 1253
} | class ____(BuilderWithDefaults):
phases = ("configure", "build", "install")
package_methods = ("check", "test_use")
package_attributes = ()
build_time_test_callbacks = ["check"]
def configure(self, pkg: PerlPackage, spec: Spec, prefix: Prefix) -> None:
pass
def build(self, pkg: PerlPac... | PerlBuilder |
python | pytest-dev__pytest | testing/test_junitxml.py | {
"start": 946,
"end": 2543
} | class ____:
def __init__(self, pytester: Pytester, schema: xmlschema.XMLSchema) -> None:
self.pytester = pytester
self.schema = schema
def __call__(
self, *args: str | os.PathLike[str], family: str | None = "xunit1"
) -> tuple[RunResult, DomDocument]:
if family:
... | RunAndParse |
python | streamlit__streamlit | lib/tests/streamlit/data_test_cases.py | {
"start": 3617,
"end": 3966
} | class ____:
"""A dummy dataframe-like class that supports the dataframe interchange protocol
(__dataframe__ method).
"""
def __init__(self, data: pd.DataFrame):
self._data: pd.DataFrame = data
def __dataframe__(self, allow_copy: bool = True):
return self._data.__dataframe__(allow_c... | CustomDataframe |
python | django-guardian__django-guardian | guardian/exceptions.py | {
"start": 718,
"end": 860
} | class ____(GuardianError):
"""Raised when an operation is attempted on both user/group and object."""
pass
| MultipleIdentityAndObjectError |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/logging_ops_test.py | {
"start": 13491,
"end": 14505
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def testPrintShape(self):
inp = constant_op.constant(2.0, shape=[100, 32])
inp_printed = logging_ops.Print(inp, [inp])
self.assertEqual(inp.get_shape(), inp_printed.get_shape())
def testPrintString(self):
inp = constant_op.consta... | PrintGradientTest |
python | jazzband__django-simple-history | simple_history/tests/tests/test_commands.py | {
"start": 784,
"end": 6689
} | class ____(TestCase):
command_name = "populate_history"
command_error = (management.CommandError, SystemExit)
def test_no_args(self):
out = StringIO()
management.call_command(self.command_name, stdout=out, stderr=StringIO())
self.assertIn(populate_history.Command.COMMAND_HINT, out.g... | TestPopulateHistory |
python | tensorflow__tensorflow | tensorflow/python/training/experimental/loss_scale_optimizer_test.py | {
"start": 4336,
"end": 13974
} | class ____(test.TestCase,
parameterized.TestCase):
def _run_if_in_graph_mode(self, val):
# Running only in graph mode is useful, because optimizers sometimes return
# a value that, in Graph mode, is runnable with self.evaluate. But in Eager
# mode, the optimizer... | MixedPrecisionLossScaleOptimizerTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/ranges.py | {
"start": 30448,
"end": 30578
} | class ____(AbstractSingleRange[int]):
"""Represent the PostgreSQL INT8RANGE type."""
__visit_name__ = "INT8RANGE"
| INT8RANGE |
python | Pylons__pyramid | tests/test_events.py | {
"start": 4223,
"end": 4845
} | class ____(ContextFoundEventTests):
def _getTargetClass(self):
from pyramid.events import AfterTraversal
return AfterTraversal
def test_class_conforms_to_IAfterTraversal(self):
from zope.interface.verify import verifyClass
from pyramid.interfaces import IAfterTraversal
... | AfterTraversalEventTests |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_benchmark.py | {
"start": 99,
"end": 5855
} | class ____:
"""
Defines a global optimization benchmark problem.
This abstract class defines the basic structure of a global
optimization problem. Subclasses should implement the ``fun`` method
for a particular optimization problem.
Attributes
----------
N : int
The dimensiona... | Benchmark |
python | pytorch__pytorch | torch/ao/nn/quantized/dynamic/modules/rnn.py | {
"start": 45702,
"end": 48059
} | class ____(RNNCellBase):
r"""An Elman RNN cell with tanh or ReLU non-linearity.
A dynamic quantized RNNCell module with floating point tensor as inputs and outputs.
Weights are quantized to 8 bits. We adopt the same interface as `torch.nn.RNNCell`,
please see https://pytorch.org/docs/stable/nn.html#torc... | RNNCell |
python | RobertCraigie__pyright-python | src/pyright/errors.py | {
"start": 499,
"end": 545
} | class ____(NodeError):
pass
| VersionCheckFailed |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/job_index.py | {
"start": 403,
"end": 4391
} | class ____:
job_snapshot: JobSnap
parent_job_snapshot: Optional[JobSnap]
_node_defs_snaps_index: Mapping[str, Union[OpDefSnap, GraphDefSnap]]
_dagster_type_snaps_by_name_index: Mapping[str, DagsterTypeSnap]
dep_structure_index: DependencyStructureIndex
_comp_dep_structures: Mapping[str, Dependen... | JobIndex |
python | huggingface__transformers | tests/models/vaultgemma/test_modeling_vaultgemma.py | {
"start": 1446,
"end": 1585
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = VaultGemmaModel
@require_torch
| VaultGemmaModelTester |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/common/parameters.py | {
"start": 5345,
"end": 6732
} | class ____(BaseParam[str]):
"""Search on attribute."""
def __init__(self, attribute: ColumnElement, skip_none: bool = True) -> None:
super().__init__(skip_none=skip_none)
self.attribute: ColumnElement = attribute
def to_orm(self, select: Select) -> Select:
if self.value is None and... | _SearchParam |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 72410,
"end": 75778
} | class ____(Response):
"""
Response of events.get_task_events endpoint.
:param events: Events list
:type events: Sequence[dict]
:param returned: Number of results returned
:type returned: int
:param total: Total number of results available for this query
:type total: float
:param scr... | GetTaskEventsResponse |
python | huggingface__transformers | src/transformers/models/omdet_turbo/processing_omdet_turbo.py | {
"start": 1245,
"end": 1499
} | class ____(TextKwargs, total=False):
task: Optional[Union[str, list[str], TextInput, PreTokenizedInput]]
if is_torch_available():
import torch
if is_torchvision_available():
from torchvision.ops.boxes import batched_nms
| OmDetTurboTextKwargs |
python | pytorch__pytorch | torch/__init__.py | {
"start": 87574,
"end": 100754
} | class ____:
def __init__(self, backend, mode, options, dynamic):
from torch._dynamo.backends.registry import lookup_backend
if isinstance(backend, str):
self.compiler_name = backend
elif hasattr(backend, "__name__"):
self.compiler_name = backend.__name__
else... | _TorchCompileWrapper |
python | django__django | tests/queries/tests.py | {
"start": 2218,
"end": 52028
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.nc1 = generic = NamedCategory.objects.create(name="Generic")
cls.t1 = Tag.objects.create(name="t1", category=generic)
cls.t2 = Tag.objects.create(name="t2", parent=cls.t1, category=generic)
cls.t3 = Tag.objects.create... | Queries1Tests |
python | coleifer__peewee | examples/anomaly_detection.py | {
"start": 68,
"end": 329
} | class ____(Model):
key = TextField()
value = IntegerField()
class Meta:
database = db
db.create_tables([Reg])
# Create a user-defined aggregate function suitable for computing the standard
# deviation of a series.
@db.aggregate('stddev')
| Reg |
python | kamyu104__LeetCode-Solutions | Python/flip-game-ii.py | {
"start": 1183,
"end": 2293
} | class ____(object):
def canWin(self, s):
"""
:type s: str
:rtype: bool
"""
lookup = {}
def canWinHelper(consecutives): # O(2^c) time
consecutives = tuple(sorted(c for c in consecutives if c >= 2)) # O(clogc) tim... | Solution2 |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_tensor_shape.py | {
"start": 1399,
"end": 26661
} | class ____:
"""A collection of tensors encoding the shape of a potentially ragged tensor.
Each `RaggedTensorDynamicShape` consists of an ordered list of dimension
sizes. There are two dimension types:
* "Uniform dimensions" are dimensions where all slices have the same
length. `RaggedTensorDynamicSh... | RaggedTensorDynamicShape |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 114637,
"end": 115706
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("model_service.Model.to_dict"))
@mock.patch(VERTEX_AI_PATH.format("model_service.ModelServiceHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = ListModelVersionsOperator(
task_id=TASK_ID,
model_id=TEST_MODEL_NAME,
... | TestVertexAIListModelVersionsOperator |
python | getsentry__sentry | tests/sentry/auth_v2/utils/test_session.py | {
"start": 802,
"end": 2538
} | class ____(TestCase):
def setUp(self) -> None:
self.serializer = SessionSerializer()
def test_serialize_with_full_session_data(self) -> None:
request = self.make_request(method="GET")
request.session = MockSession()
request.session.data = {
"todo_email_verification":... | SessionSerializerTest |
python | has2k1__plotnine | plotnine/typing.py | {
"start": 3617,
"end": 3754
} | class ____(Protocol):
"""
Transform function
"""
def __call__(self, x: TFloatArrayLike) -> TFloatArrayLike: ...
| PTransform |
python | marshmallow-code__marshmallow | src/marshmallow/validate.py | {
"start": 17390,
"end": 18589
} | class ____(Validator):
"""Call the specified ``method`` of the ``value`` object. The
validator succeeds if the invoked method returns an object that
evaluates to True in a Boolean context. Any additional keyword
argument will be passed to the method.
:param method: The name of the method to invoke.... | Predicate |
python | sympy__sympy | sympy/functions/elementary/exponential.py | {
"start": 1556,
"end": 4411
} | class ____(DefinedFunction):
unbranched = True
_singularities = (S.ComplexInfinity,)
@property
def kind(self):
return self.exp.kind
def inverse(self, argindex=1):
"""
Returns the inverse function of ``exp(x)``.
"""
return log
def as_numer_denom(self):
... | ExpBase |
python | pytorch__pytorch | torch/ao/nn/quantizable/modules/rnn.py | {
"start": 9863,
"end": 14636
} | class ____(torch.nn.Module):
r"""A single bi-directional LSTM layer."""
def __init__(
self,
input_dim: int,
hidden_dim: int,
bias: bool = True,
batch_first: bool = False,
bidirectional: bool = False,
device=None,
dtype=None,
*,
spl... | _LSTMLayer |
python | huggingface__transformers | src/transformers/models/sam_hq/modeling_sam_hq.py | {
"start": 26574,
"end": 29671
} | class ____(nn.Module):
"""
SAM_HQ's attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and
values.
"""
def __init__(self, config, downsample_rate=None):
super().__init__()
self.config = config
self.hidden_size = config.hi... | SamHQAttention |
python | huggingface__transformers | src/transformers/models/opt/modeling_opt.py | {
"start": 1805,
"end": 3708
} | class ____(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
"""
def __init__(self, num_embeddings: int, embedding_dim: int):
# OPT is set up so that if padding_idx is specified then offset the embedding ids by 2
# and adjust num_embeddings appropri... | OPTLearnedPositionalEmbedding |
python | keras-team__keras | guides/training_with_built_in_methods.py | {
"start": 20330,
"end": 23512
} | class ____(keras.utils.PyDataset):
def __init__(self, x, y, batch_size, **kwargs):
super().__init__(**kwargs)
self.x = x
self.y = y
self.batch_size = batch_size
def __len__(self):
return int(np.ceil(len(self.x) / float(self.batch_size)))
def __getitem__(self, idx):
... | ExamplePyDataset |
python | pypa__warehouse | tests/unit/forklift/test_legacy.py | {
"start": 6384,
"end": 14865
} | class ____:
def test_defaults_to_true(self):
assert legacy._is_valid_dist_file("", "") == (True, None)
@pytest.mark.parametrize(
("filename", "filetype"),
[
("test.zip", "sdist"),
("test.whl", "bdist_wheel"),
],
)
def test_bails_with_invalid_zipfi... | TestFileValidation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.