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/exceptions.py | {
"start": 9231,
"end": 10036
} | class ____(PipenvException):
def __init__(self, package, command, return_values, return_code, **kwargs):
extra = [
"{} {}".format(
"[cyan]Attempting to run command: [/cyan]",
f"[bold yellow]$ {command!r}[/bold yellow]",
)
]
extra.extend... | UninstallError |
python | doocs__leetcode | solution/3100-3199/3119.Maximum Number of Potholes That Can Be Fixed/Solution.py | {
"start": 0,
"end": 612
} | class ____:
def maxPotholes(self, road: str, budget: int) -> int:
road += "."
n = len(road)
cnt = [0] * n
k = 0
for c in road:
if c == "x":
k += 1
elif k:
cnt[k] += 1
k = 0
ans = 0
for k i... | Solution |
python | wandb__wandb | wandb/sdk/lib/preinit.py | {
"start": 59,
"end": 1450
} | class ____:
def __init__(self, name: str, destination: Optional[Any] = None) -> None:
self._name = name
if destination is not None:
self.__doc__ = destination.__doc__
def __getitem__(self, key: str) -> None:
raise wandb.Error(f"You must call wandb.init() before {self._name}... | PreInitObject |
python | lepture__authlib | authlib/oauth2/rfc6749/errors.py | {
"start": 6826,
"end": 6954
} | class ____(OAuth2Error):
error = "missing_token"
description = "Missing 'access_token' in response."
| MissingTokenException |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess4.py | {
"start": 205,
"end": 255
} | class ____(Protocol):
item: int
| HasItemProtocol1 |
python | sympy__sympy | sympy/physics/units/dimensions.py | {
"start": 10002,
"end": 21151
} | class ____(Basic, _QuantityMapper):
r"""
DimensionSystem represents a coherent set of dimensions.
The constructor takes three parameters:
- base dimensions;
- derived dimensions: these are defined in terms of the base dimensions
(for example velocity is defined from the division of length by... | DimensionSystem |
python | sympy__sympy | sympy/core/add.py | {
"start": 2712,
"end": 43211
} | class ____(Expr, AssocOp):
"""
Expression representing addition operation for algebraic group.
.. deprecated:: 1.7
Using arguments that aren't subclasses of :class:`~.Expr` in core
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
deprecated. See :ref:`non-expr-args-de... | Add |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_device_allocation_configuration.py | {
"start": 383,
"end": 6291
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1beta2DeviceAllocationConfiguration |
python | facebook__pyre-check | tools/typeshed_patcher/typeshed.py | {
"start": 3310,
"end": 3882
} | class ____(Typeshed):
"""
A typeshed backed up by in-memory content. Essentially a wrapper around
a dictonary from paths to their contents.
This class is mostly useful for testing.
"""
contents: Mapping[pathlib.Path, str]
def __init__(self, contents: Mapping[pathlib.Path, str]) -> None:
... | MemoryBackedTypeshed |
python | huggingface__transformers | src/transformers/models/flava/modeling_flava.py | {
"start": 2074,
"end": 4091
} | class ____(ModelOutput):
r"""
image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `pixel_values` are present):
The image embeddings which are basically the pooled output of [`FlavaImageModel`].
image_output (`BaseModelOutputWithPooling`, *optional*, r... | FlavaModelOutput |
python | encode__django-rest-framework | tests/test_middleware.py | {
"start": 3946,
"end": 4779
} | class ____(APITestCase):
"""
Django's 5.1+ LoginRequiredMiddleware should NOT apply to DRF views.
Instead, users should put IsAuthenticated in their
DEFAULT_PERMISSION_CLASSES setting.
"""
def test_class_based_view(self):
response = self.client.get('/get')
assert response.status... | TestLoginRequiredMiddlewareCompat |
python | pandas-dev__pandas | pandas/tests/extension/base/__init__.py | {
"start": 2398,
"end": 2870
} | class ____(
BaseAccumulateTests,
BaseCastingTests,
BaseConstructorsTests,
BaseDtypeTests,
BaseGetitemTests,
BaseGroupbyTests,
BaseIndexTests,
BaseInterfaceTests,
BaseParsingTests,
BaseMethodsTests,
BaseMissingTests,
BaseArithmeticOpsTests,
BaseComparisonOpsTests,
... | ExtensionTests |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/bijector_test.py | {
"start": 5293,
"end": 6841
} | class ____(metaclass=abc.ABCMeta):
@abc.abstractproperty
def broken_bijector_cls(self):
# return a BrokenBijector type Bijector, since this will test the caching.
raise IntentionallyMissingError("Not implemented")
def testCachingOfForwardResults(self):
broken_bijector = self.broken_bijector_cls(inve... | BijectorCachingTestBase |
python | pytorch__pytorch | torch/_dynamo/eval_frame.py | {
"start": 11768,
"end": 21757
} | class ____(torch.nn.Module):
"""
Wraps the original nn.Module object and later patches its
forward method to optimized self.forward method.
"""
_torchdynamo_orig_callable: Callable[..., Any]
get_compiler_config: Callable[[], Any]
_opt_mod_attributes = {
"_orig_mod",
"dynamo... | OptimizedModule |
python | ipython__ipython | IPython/core/autocall.py | {
"start": 1593,
"end": 1983
} | class ____(ExitAutocall):
"""Exit IPython. Autocallable, so it needn't be explicitly called.
Parameters
----------
keep_kernel : bool
If True, leave the kernel alive. Otherwise, tell the kernel to exit too
(default).
"""
def __call__(self, keep_kernel=False):
self._ip.ke... | ZMQExitAutocall |
python | tiangolo__fastapi | tests/test_tuples.py | {
"start": 190,
"end": 253
} | class ____(BaseModel):
items: List[Tuple[str, str]]
| ItemGroup |
python | tensorflow__tensorflow | tensorflow/python/ops/lookup_ops.py | {
"start": 67590,
"end": 79931
} | class ____(LookupInterface):
"""A generic mutable hash table implementation.
Data can be inserted by calling the `insert` method and removed by calling the
`remove` method. It does not support initialization via the init method.
`MutableHashTable` requires additional memory during checkpointing and restore
... | MutableHashTable |
python | lazyprogrammer__machine_learning_examples | nlp_class2/glove_svd.py | {
"start": 758,
"end": 6791
} | class ____:
def __init__(self, D, V, context_sz):
self.D = D
self.V = V
self.context_sz = context_sz
def fit(self, sentences, cc_matrix=None):
# build co-occurrence matrix
# paper calls it X, so we will call it X, instead of calling
# the training data X
... | Glove |
python | encode__django-rest-framework | tests/test_renderers.py | {
"start": 2538,
"end": 2655
} | class ____(APIView):
def post(self, request, **kwargs):
return Response({'foo': request.data})
| MockPOSTView |
python | openai__gym | gym/envs/mujoco/half_cheetah.py | {
"start": 111,
"end": 1840
} | class ____(MuJocoPyEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
],
"render_fps": 20,
}
def __init__(self, **kwargs):
observation_space = Box(low=-np.inf, high=np.inf, shape=(17,), dtype=np.float... | HalfCheetahEnv |
python | simonw__datasette | datasette/views/special.py | {
"start": 2264,
"end": 2635
} | class ____(View):
async def get(self, request, datasette):
await datasette.ensure_permission(action="view-instance", actor=request.actor)
return Response.html(
await datasette.render_template(
"patterns.html",
request=request,
view_name="pa... | PatternPortfolioView |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/serializable_types/pyspark.py | {
"start": 99,
"end": 1629
} | class ____(dict):
"""Custom type implementing pydantic validation."""
struct_type: pyspark.sql.types.StructType
def __init__(
self,
fields_or_struct_type: pyspark.sql.types.StructType
| list[pyspark.sql.types.StructField]
| None,
):
# Store a copy of the instant... | SerializableStructType |
python | ray-project__ray | python/ray/tests/test_network_failure_e2e.py | {
"start": 8043,
"end": 10091
} | class ____:
def __init__(self, counter):
self.counter = counter
async def run(self):
count = await self.counter.get.remote()
if count == 0:
# first attempt
await self.counter.inc.remote()
while len(list_tasks(
filters=[("name", "=", "AsyncActor.run")])) < 2:
# wait... | AsyncActor |
python | pytorch__pytorch | .github/scripts/gitutils.py | {
"start": 1694,
"end": 3644
} | class ____:
commit_hash: str
title: str
body: str
author: str
author_date: datetime
commit_date: Optional[datetime]
def __init__(
self,
commit_hash: str,
author: str,
author_date: datetime,
title: str,
body: str,
commit_date: Optional[... | GitCommit |
python | doocs__leetcode | solution/2700-2799/2728.Count Houses in a Circular Street/Solution.py | {
"start": 252,
"end": 576
} | class ____:
def houseCount(self, street: Optional["Street"], k: int) -> int:
for _ in range(k):
street.openDoor()
street.moveLeft()
ans = 0
while street.isDoorOpen():
street.closeDoor()
street.moveLeft()
ans += 1
return ans
| Solution |
python | facebook__pyre-check | client/commands/infer.py | {
"start": 14582,
"end": 15090
} | class ____:
name: str
return_annotation: TypeAnnotation
parameters: Sequence[Parameter]
is_async: bool
def to_stub(self) -> str:
name = _sanitize_name(self.name)
async_ = "async " if self.is_async else ""
parameters = ", ".join(parameter.to_stub() for parameter in self.param... | FunctionAnnotation |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 5893,
"end": 7419
} | class ____(fixtures.DeclarativeMappedTest):
run_setup_mappers = "once"
__dialect__ = "default"
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(ComparableEntity, Base):
__tablename__ = "a"
id = Column(
Integer, primary_ke... | PolyExpressionEagerLoad |
python | pandas-dev__pandas | pandas/io/pytables.py | {
"start": 149949,
"end": 156936
} | class ____(Table):
"""support the new appendable table formats"""
table_type = "appendable"
# error: Signature of "write" incompatible with supertype "Fixed"
def write( # type: ignore[override]
self,
obj,
axes=None,
append: bool = False,
complib=None,
c... | AppendableTable |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/camera/_center.py | {
"start": 235,
"end": 2877
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.camera"
_path_str = "layout.scene.camera.center"
_valid_props = {"x", "y", "z"}
@property
def x(self):
"""
The 'x' property is a number and may be specified as:
- An int or float
Returns
... | Center |
python | django__django | django/contrib/admin/widgets.py | {
"start": 12787,
"end": 12946
} | class ____(forms.Textarea):
def __init__(self, attrs=None):
super().__init__(attrs={"class": "vLargeTextField", **(attrs or {})})
| AdminTextareaWidget |
python | readthedocs__readthedocs.org | readthedocs/oauth/services/github.py | {
"start": 841,
"end": 22348
} | class ____(UserService):
"""Provider service for GitHub."""
vcs_provider_slug = GITHUB
allauth_provider = GitHubProvider
base_api_url = "https://api.github.com"
# TODO replace this with a less naive check
url_pattern = re.compile(r"github\.com")
supports_build_status = True
def sync_re... | GitHubService |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 32880,
"end": 33070
} | class ____(Rank):
"""Minimum of multiple ranks"""
ranks: List[Rank]
def to_dict(self) -> Dict[str, Any]:
return {"$min": [r.to_dict() for r in self.ranks]}
@dataclass
| Min |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 407810,
"end": 410428
} | class ____(Request):
"""
Unarchive tasks
:param ids: IDs of the tasks to unarchive
:type ids: Sequence[str]
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding status change
:type status_message: str
"""
_se... | UnarchiveManyRequest |
python | tensorflow__tensorflow | tensorflow/python/training/server_lib_test.py | {
"start": 19418,
"end": 25375
} | class ____(test.TestCase):
def testStringConversion(self):
cluster_spec = server_lib.ClusterSpec(
{"ps": ["ps0:1111"], "worker": ["worker0:3333", "worker1:4444"]}
)
expected_str = (
"ClusterSpec({'ps': ['ps0:1111'], 'worker': ['worker0:3333', "
"'worker1:4444']})"
)
self.... | ClusterSpecTest |
python | numba__numba | numba/tests/test_parallel_backend.py | {
"start": 13910,
"end": 15628
} | class ____(TestCase):
"""
Helper class for running an isolated piece of code based on a template
"""
# sys path injection and separate usecase module to make sure everything
# is importable by children of multiprocessing
_here = "%r" % os.path.dirname(__file__)
template = """if 1:
impor... | ThreadLayerTestHelper |
python | tensorflow__tensorflow | tensorflow/python/ops/math_grad_test.py | {
"start": 19911,
"end": 21892
} | class ____(test.TestCase):
def _xlogy_gradients(self, x, y):
xlogy_xgrad = self.evaluate(gradients.gradients(math_ops.xlogy(x, y), x)[0])
xlogy_ygrad = self.evaluate(gradients.gradients(math_ops.xlogy(x, y), y)[0])
return xlogy_xgrad, xlogy_ygrad
@test_util.run_deprecated_v1
def testNonZeroValuesGra... | XlogyTest |
python | mlflow__mlflow | tests/dspy/test_save.py | {
"start": 1263,
"end": 17526
} | class ____(dspy.Module):
def __init__(self):
super().__init__()
self.prog = dspy.ChainOfThought("question -> answer: int")
def forward(self, question):
return self.prog(question=question).answer
@pytest.fixture(autouse=True)
def reset_dspy_settings():
yield
dspy.settings.conf... | NumericalCoT |
python | pandas-dev__pandas | pandas/tests/series/test_constructors.py | {
"start": 82044,
"end": 83917
} | class ____:
def test_series_constructor_datetimelike_index_coercion(self):
idx = date_range("2020-01-01", periods=5)
ser = Series(
np.random.default_rng(2).standard_normal(len(idx)), idx.astype(object)
)
# as of 2.0, we no longer silently cast the object-dtype index
... | TestSeriesConstructorIndexCoercion |
python | weaviate__weaviate-python-client | weaviate/connect/base.py | {
"start": 1137,
"end": 6514
} | class ____(BaseModel):
http: ProtocolParams
grpc: ProtocolParams
@classmethod
def from_url(cls, url: str, grpc_port: int, grpc_secure: bool = False) -> "ConnectionParams":
parsed_url = urlparse(url)
if parsed_url.scheme not in ["http", "https"]:
raise ValueError(f"Unsupporte... | ConnectionParams |
python | ray-project__ray | python/ray/train/v2/_internal/callbacks/tpu_reservation_callback.py | {
"start": 231,
"end": 1662
} | class ____(ControllerCallback):
"""A callback to handle TPU slice reservation for multi-host training."""
def on_controller_start_worker_group(
self, *, scaling_config: ScalingConfig, num_workers: int
) -> Optional[Dict[str, str]]:
"""Reserves a multi-host TPU slice before the worker group ... | TPUReservationCallback |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/components.py | {
"start": 23762,
"end": 31956
} | class ____(UserComponent):
"""
A Value Box component for displaying key metrics with styling and change indicators.
Inspired by Shiny's value box component, this displays a primary value with optional
title, subtitle, theme, and change indicators.
Example:
```
# Basic value box
value_b... | ValueBox |
python | fluentpython__example-code | 20-descriptor/bulkfood/bulkfood_v5.py | {
"start": 1746,
"end": 2094
} | class ____:
description = model.NonBlank() # <2>
weight = model.Quantity()
price = model.Quantity()
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.... | LineItem |
python | coleifer__peewee | playhouse/sqlite_udf.py | {
"start": 10309,
"end": 10860
} | class ____(_heap_agg):
def finalize(self):
if self.ct == 0:
return
elif self.ct == 1:
return 0
total = ct = 0
prev = None
while self.heap:
if total == 0:
if prev is None:
prev = heapq.heappop(self.heap)
... | avgrange |
python | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 51626,
"end": 52262
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_f... | ClapTextIntermediate |
python | paramiko__paramiko | paramiko/ecdsakey.py | {
"start": 3154,
"end": 11653
} | class ____(PKey):
"""
Representation of an ECDSA key which can be used to sign and verify SSH2
data.
"""
_ECDSA_CURVES = _ECDSACurveSet(
[
_ECDSACurve(ec.SECP256R1, "nistp256"),
_ECDSACurve(ec.SECP384R1, "nistp384"),
_ECDSACurve(ec.SECP521R1, "nistp521"),... | ECDSAKey |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 58470,
"end": 58609
} | class ____(fixtures.TestBase):
def test_interval(self):
is_(postgresql.INTERVAL().python_type, datetime.timedelta)
| PythonTypeTest |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_colors.py | {
"start": 27211,
"end": 80194
} | class ____:
"""
Tests for `~.colors.AsinhNorm`
"""
def test_init(self):
norm0 = mcolors.AsinhNorm()
assert norm0.linear_width == 1
norm5 = mcolors.AsinhNorm(linear_width=5)
assert norm5.linear_width == 5
def test_norm(self):
norm = mcolors.AsinhNorm(2, vmin... | TestAsinhNorm |
python | spack__spack | lib/spack/spack/test/llnl/util/lock.py | {
"start": 26203,
"end": 37441
} | class ____(lk.Lock):
"""Test lock class that marks acquire/release events."""
def __init__(self, lock_path, vals):
super().__init__(lock_path)
self.vals = vals
# assert hooks for subclasses
assert_acquire_read = lambda self: None
assert_acquire_write = lambda self: None
assert_... | AssertLock |
python | joke2k__faker | tests/providers/test_internet.py | {
"start": 32515,
"end": 32817
} | class ____:
"""Tests for the es_ES locale."""
def test_tld(self, faker):
tld = faker.tld()
assert tld in EsEsInternetProvider.tlds
def test_slug(self, faker):
num_of_samples = 100
for _ in range(num_of_samples):
assert faker.slug() != ""
| TestEsEs |
python | run-llama__llama_index | llama-index-core/llama_index/core/data_structs/data_structs.py | {
"start": 5189,
"end": 6440
} | class ____(IndexStruct):
"""A simple dictionary of documents."""
# TODO: slightly deprecated, should likely be a list or set now
# mapping from vector store id to node doc_id
nodes_dict: Dict[str, str] = field(default_factory=dict)
# TODO: deprecated, not used
# mapping from node doc_id to vec... | IndexDict |
python | keon__algorithms | tests/test_dp.py | {
"start": 6358,
"end": 7551
} | class ____(unittest.TestCase):
def test_none_0(self):
s = ""
p = ""
self.assertTrue(regex_matching.is_match(s, p))
def test_none_1(self):
s = ""
p = "a"
self.assertFalse(regex_matching.is_match(s, p))
def test_no_symbol_equal(self):
s = "abcd"
... | TestRegexMatching |
python | celery__celery | t/unit/backends/test_base.py | {
"start": 54216,
"end": 61486
} | class ____:
def test_should_retry_exception(self):
assert not BaseBackend(app=self.app).exception_safe_to_retry(Exception("test"))
def test_get_failed_never_retries(self):
self.app.conf.result_backend_always_retry, prev = False, self.app.conf.result_backend_always_retry
expected_exc =... | test_backend_retries |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/data/parsing.py | {
"start": 738,
"end": 3468
} | class ____:
"""
Represents a parser which is responsible for generating queries given a list of MQLQuery(s).
"""
def __init__(
self,
projects: Sequence[Project],
environments: Sequence[Environment],
mql_queries: Sequence[MQLQuery],
):
self._projects = project... | QueryParser |
python | eth-brownie__brownie | brownie/_gui/source.py | {
"start": 5615,
"end": 8676
} | class ____(tk.Frame):
def __init__(self, root, text, suffix):
super().__init__(root)
self._text = tk.Text(self, width=90, yscrollcommand=self._text_scroll)
self._scroll = ttk.Scrollbar(self)
self._scroll.pack(side="left", fill="y")
self._scroll.config(command=self._scrollbar_... | SourceFrame |
python | django__django | tests/model_fields/test_foreignkey.py | {
"start": 320,
"end": 5921
} | class ____(TestCase):
def test_callable_default(self):
"""A lazy callable may be used for ForeignKey.default."""
a = Foo.objects.create(id=1, a="abc", d=Decimal("12.34"))
b = Bar.objects.create(b="bcd")
self.assertEqual(b.a, a)
@skipIfDBFeature("interprets_empty_strings_as_nulls... | ForeignKeyTests |
python | wandb__wandb | wandb/vendor/pygments/util.py | {
"start": 809,
"end": 9123
} | class ____(Exception):
pass
def get_choice_opt(options, optname, allowed, default=None, normcase=False):
string = options.get(optname, default)
if normcase:
string = string.lower()
if string not in allowed:
raise OptionError('Value for option %s must be one of %s' %
... | OptionError |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 58672,
"end": 58985
} | class ____(unittest.TestCase):
def test_retry_error_is_pickleable(self):
import pickle
expected = RetryError(last_attempt=123)
pickled = pickle.dumps(expected)
actual = pickle.loads(pickled)
self.assertEqual(expected.last_attempt, actual.last_attempt)
| TestRetryException |
python | django__django | tests/auth_tests/test_management.py | {
"start": 3413,
"end": 3587
} | class ____:
"""
A fake stdin object that pretends to be a TTY to be used in conjunction
with mock_inputs.
"""
def isatty(self):
return True
| MockTTY |
python | sympy__sympy | sympy/physics/quantum/spin.py | {
"start": 9327,
"end": 10541
} | class ____(SpinOpBase, HermitianOperator):
"""The Jy operator."""
_coord = 'y'
basis = 'Jy'
def _eval_commutator_JzOp(self, other):
return I*hbar*JxOp(self.name)
def _eval_commutator_JxOp(self, other):
return -I*hbar*J2Op(self.name)
def _apply_operator_JzKet(self, ket, **opt... | JyOp |
python | doocs__leetcode | solution/3200-3299/3229.Minimum Operations to Make Array Equal to Target/Solution.py | {
"start": 0,
"end": 439
} | class ____:
def minimumOperations(self, nums: List[int], target: List[int]) -> int:
n = len(nums)
f = abs(target[0] - nums[0])
for i in range(1, n):
x = target[i] - nums[i]
y = target[i - 1] - nums[i - 1]
if x * y > 0:
d = abs(x) - abs(y)
... | Solution |
python | django-crispy-forms__django-crispy-forms | crispy_forms/bootstrap.py | {
"start": 11646,
"end": 13254
} | class ____(Field):
"""
Layout object for rendering radiobuttons inline.
Attributes
----------
template : str
The default template which this Layout Object will be rendered
with.
attrs : dict
Attributes to be applied to the field. These are converted into html
att... | InlineRadios |
python | google__pytype | pytype/directors/parser.py | {
"start": 1493,
"end": 1609
} | class ____(LineRange):
name: str
annotations: dict[str, str]
@dataclasses.dataclass(frozen=True)
| _ParamAnnotations |
python | kamyu104__LeetCode-Solutions | Python/count-increasing-quadruplets.py | {
"start": 642,
"end": 1313
} | class ____(object):
def countQuadruplets(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
right = [[0]*(len(nums)+1) for _ in xrange(len(nums))]
for j in xrange(len(nums)):
for i in reversed(xrange(j+1, len(nums))):
right[j][i] = righ... | Solution2 |
python | numba__numba | numba/cuda/tests/cudapy/test_record_dtype.py | {
"start": 2858,
"end": 8725
} | class ____(CUDATestCase):
def _createSampleArrays(self):
self.sample1d = np.recarray(3, dtype=recordtype)
self.samplerec1darr = np.recarray(1, dtype=recordwitharray)[0]
self.samplerec2darr = np.recarray(1, dtype=recordwith2darray)[0]
def setUp(self):
super().setUp()
sel... | TestRecordDtype |
python | django__django | django/core/management/templates.py | {
"start": 585,
"end": 15458
} | class ____(BaseCommand):
"""
Copy either a Django application layout template or a Django project
layout template into the specified directory.
:param style: A color style object (see django.core.management.color).
:param app_or_project: The string 'app' or 'project'.
:param name: The name of t... | TemplateCommand |
python | allegroai__clearml | clearml/utilities/process/mp.py | {
"start": 3992,
"end": 5146
} | class ____(_ForkSafeThreadSyncObject):
def __init__(self, value: int = 1) -> None:
super(ForkSemaphore, self).__init__(functor=partial(Semaphore, value))
def acquire(self, *args: Any, **kwargs: Any) -> Optional[bool]:
try:
self._create()
except BaseException: # noqa
... | ForkSemaphore |
python | milvus-io__pymilvus | tests/test_grpc_handler.py | {
"start": 20467,
"end": 23657
} | class ____:
def test_setup_grpc_channel_with_tls(self) -> None:
with patch('pymilvus.client.grpc_handler.grpc.secure_channel') as mock_secure:
with patch('pymilvus.client.grpc_handler.grpc.ssl_channel_credentials') as mock_creds:
with patch('pymilvus.client.grpc_handler.Path') as... | TestGrpcHandlerSecureConnection |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/base_streams.py | {
"start": 5137,
"end": 7389
} | class ____(ShopifyStream):
data_field = "events"
primary_key = "id"
cursor_field = "deleted_at"
def __init__(self, config: Dict, deleted_events_api_name: str) -> None:
self.deleted_events_api_name = deleted_events_api_name
super().__init__(config)
@property
def availability_str... | ShopifyDeletedEventsStream |
python | PyCQA__pylint | tests/functional/n/none_dunder_protocols.py | {
"start": 507,
"end": 607
} | class ____(metaclass=MetaContainer):
__len__, __iter__ = [None, None]
| MultipleAssignmentNonesClass |
python | eventlet__eventlet | tests/asyncio_test.py | {
"start": 552,
"end": 7777
} | class ____(_TestBase):
"""
High-level tests for using ``asyncio``-based code inside greenlets.
For this functionality to be useful, users need to be able to use 3rd party
libraries that use sockets etc.. Merely hooking up futures to greenlets
doesn't help if you can't use the asyncio library ecosy... | CallingAsyncFunctionsFromGreenletsHighLevelTests |
python | scipy__scipy | scipy/stats/tests/test_continuous.py | {
"start": 82121,
"end": 85361
} | class ____:
# Adds tests just to get to 100% test coverage; this way it's more obvious
# if new lines are untested.
def test_Domain(self):
with pytest.raises(NotImplementedError):
_Domain.contains(None, 1.)
with pytest.raises(NotImplementedError):
_Domain.get_numerica... | TestFullCoverage |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/types.py | {
"start": 1939,
"end": 2049
} | class ____(_NetworkAddressTypeMixin, sqltypes.TypeEngine[str]):
__visit_name__ = "INET"
PGInet = INET
| INET |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/quality/test_poisoned_lists.py | {
"start": 771,
"end": 1121
} | class ____(SearchStrategy):
def __init__(self, poison_chance):
super().__init__()
self.__poison_chance = poison_chance
self.__ints = st.integers(0, 10)
def do_draw(self, data):
if data.draw_boolean(self.__poison_chance):
return POISON
else:
return... | Poisoned |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict13.py | {
"start": 298,
"end": 429
} | class ____(ParentA):
# This should generate an error because the type of "age" is redefined.
age: float
name: str
| ChildA |
python | h5py__h5py | h5py/tests/test_vds/test_highlevel_vds.py | {
"start": 6527,
"end": 9094
} | class ____(ut.TestCase):
def setUp(self):
self.working_dir = tempfile.mkdtemp()
self.fname = ['raw_file_1.h5','raw_file_2.h5','raw_file_3.h5']
k = 0
for outfile in self.fname:
filename = osp.join(self.working_dir, outfile)
f = h5.File(filename,'w')
... | TestPercivalHighLevel |
python | PrefectHQ__prefect | tests/server/utilities/test_server.py | {
"start": 175,
"end": 765
} | class ____:
@pytest.fixture
def client(self):
app = FastAPI()
router = PrefectRouter()
@router.get("/{x}")
def echo(x: str):
return x
app.include_router(router)
client = TestClient(app)
return client
def test_url_encoded_variables(self, ... | TestParsing |
python | walkccc__LeetCode | solutions/1584. Min Cost to Connect All Points/1584.py | {
"start": 0,
"end": 739
} | class ____:
def minCostConnectPoints(self, points: list[int]) -> int:
# dist[i] := the minimum distance to connect the points[i]
dist = [math.inf] * len(points)
ans = 0
for i in range(len(points) - 1):
for j in range(i + 1, len(points)):
# Try to connect the points[i] with the points[j]... | Solution |
python | huggingface__transformers | conftest.py | {
"start": 4657,
"end": 5688
} | class ____(OutputChecker):
def check_output(self, want, got, optionflags):
if IGNORE_RESULT & optionflags:
return True
return OutputChecker.check_output(self, want, got, optionflags)
doctest.OutputChecker = CustomOutputChecker
_pytest.doctest.DoctestModule = HfDoctestModule
doctest.Doc... | CustomOutputChecker |
python | pytransitions__transitions | transitions/core.py | {
"start": 7666,
"end": 13081
} | class ____(object):
"""Representation of a transition managed by a ``Machine`` instance.
Attributes:
source (str): Source state of the transition.
dest (str): Destination state of the transition.
prepare (list): Callbacks executed before conditions checks.
conditions (list): Cal... | Transition |
python | python-attrs__attrs | tests/test_functional.py | {
"start": 1317,
"end": 1380
} | class ____(metaclass=Meta):
pass
@attr.s(slots=True)
| WithMeta |
python | python-excel__xlwt | tests/test_biff_records.py | {
"start": 506,
"end": 872
} | class ____(unittest.TestCase):
def test_intersheets_ref(self):
book = xlwt.Workbook()
sheet_a = book.add_sheet('A')
sheet_a.write(0, 0, 'A1')
sheet_a.write(0, 1, 'A2')
sheet_b = book.add_sheet('B')
sheet_b.write(0, 0, xlwt.Formula("'A'!$A$1&'A'!$A$2"))
out = B... | TestIntersheetsRef |
python | encode__django-rest-framework | rest_framework/fields.py | {
"start": 27521,
"end": 27862
} | class ____(CharField):
default_error_messages = {
'invalid': _('This value does not match the required pattern.')
}
def __init__(self, regex, **kwargs):
super().__init__(**kwargs)
validator = RegexValidator(regex, message=self.error_messages['invalid'])
self.validators.appen... | RegexField |
python | lepture__authlib | authlib/integrations/sqla_oauth2/tokens_mixins.py | {
"start": 1218,
"end": 2261
} | class ____(TokenMixin):
client_id = Column(String(48))
token_type = Column(String(40))
access_token = Column(String(255), unique=True, nullable=False)
refresh_token = Column(String(255), index=True)
scope = Column(Text, default="")
issued_at = Column(Integer, nullable=False, default=lambda: int(... | OAuth2TokenMixin |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 53388,
"end": 54866
} | class ____(PrefectOperatorFilterBaseModel):
"""Filter logs. Only logs matching all criteria will be returned"""
level: Optional[LogFilterLevel] = Field(
default=None, description="Filter criteria for `Log.level`"
)
timestamp: Optional[LogFilterTimestamp] = Field(
default=None, descripti... | LogFilter |
python | huggingface__transformers | tests/models/speecht5/test_modeling_speecht5.py | {
"start": 6922,
"end": 12426
} | class ____:
def __init__(
self,
parent,
batch_size=13,
encoder_seq_length=1024, # speech is longer
decoder_seq_length=7,
is_training=False,
hidden_size=24,
num_hidden_layers=2,
num_attention_heads=2,
intermediate_size=4,
conv_d... | SpeechT5ForSpeechToTextTester |
python | numba__numba | numba/tests/test_dictobject.py | {
"start": 35488,
"end": 36339
} | class ____(TestCase, DictIterableCtor):
def setUp(self):
self.jit_enabled = False
def test_exception_nargs(self):
msg = 'Dict expect at most 1 argument, got 2'
with self.assertRaisesRegex(TypingError, msg):
Dict(1, 2)
def test_exception_mapping_ctor(self):
msg ... | TestDictIterableCtorNoJit |
python | Textualize__textual | src/textual/app.py | {
"start": 6812,
"end": 6915
} | class ____(ModeError):
"""Raised when attempting to use a mode that is not known."""
| UnknownModeError |
python | django__django | django/contrib/gis/geos/prototypes/geom.py | {
"start": 1249,
"end": 3400
} | class ____(GEOSFuncFactory):
"Argument is a Geometry, return type is a string."
argtypes = [GEOM_PTR]
restype = geos_char_p
errcheck = staticmethod(check_string)
# ### ctypes prototypes ###
# The GEOS geometry type, typeid, num_coordinates and number of geometries
geos_makevalid = GeomOutput("GEOSMa... | StringFromGeom |
python | pypa__warehouse | warehouse/organizations/models.py | {
"start": 7843,
"end": 9240
} | class ____:
def __init__(self, request):
self.request = request
def __getitem__(self, organization):
# Try returning organization with matching name.
try:
return (
self.request.db.query(Organization)
.filter(
Organization.n... | OrganizationFactory |
python | getsentry__sentry | src/sentry/monitors/system_incidents.py | {
"start": 14090,
"end": 21997
} | class ____(StrEnum):
"""
A metric is similar to a tick decision, however it represents a decision
made on the volume metric. The metric we current consider is percent mean
deviation from historic volumes.
"""
NORMAL = "normal"
"""
The metric is below the abnormal threshold.
"""
... | Metric |
python | aimacode__aima-python | utils.py | {
"start": 10045,
"end": 13241
} | class ____:
"""Dependency injection of temporary values for global functions/classes/etc.
E.g., `with injection(DataBase=MockDataBase): ...`"""
def __init__(self, **kwds):
self.new = kwds
def __enter__(self):
self.old = {v: globals()[v] for v in self.new}
globals().update(self.... | injection |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_struct.py | {
"start": 1431,
"end": 6701
} | class ____:
def test_init(self) -> None:
with pytest.raises(ValueError):
bcps.Struct()
def test_valid(self) -> None:
prop0 = bcps.Struct(a=Int, b=List(Int), c=Dict(Instance(_TestModel), String))
assert prop0.is_valid(dict(a=0, b=[1], c={_TestModel(): "x"}))
assert p... | Test_Struct |
python | python-poetry__poetry | src/poetry/config/source.py | {
"start": 249,
"end": 1154
} | class ____:
name: str
url: str = ""
priority: Priority = (
Priority.PRIMARY
) # cheating in annotation: str will be converted to Priority in __post_init__
def __post_init__(self) -> None:
if isinstance(self.priority, str):
self.priority = Priority[self.priority.upper()]... | Source |
python | ray-project__ray | python/ray/data/context.py | {
"start": 8436,
"end": 11505
} | class ____:
"""Configuration for autoscaling of Ray Data.
Args:
actor_pool_util_upscaling_threshold: Actor Pool utilization threshold for upscaling.
Once Actor Pool exceeds this utilization threshold it will start adding new actors.
Actor Pool utilization is defined as ratio of ... | AutoscalingConfig |
python | ray-project__ray | rllib/env/tests/test_multi_agent_env.py | {
"start": 11106,
"end": 13762
} | class ____(MultiAgentEnv):
"""Env of N independent agents, each of which exits after 5 steps.
On each step() of the env, only one agent takes an action."""
def __init__(self, num, increment_obs=False):
super().__init__()
if increment_obs:
# Observations are 0, 1, 2, 3... etc. a... | RoundRobinMultiAgent |
python | MongoEngine__mongoengine | tests/utils.py | {
"start": 413,
"end": 2955
} | class ____(unittest.TestCase):
"""Base class for tests that need a mongodb connection
It ensures that the db is clean at the beginning and dropped at the end automatically
"""
@classmethod
def setUpClass(cls):
disconnect_all()
cls._connection = connect(db=MONGO_TEST_DB)
cls.... | MongoDBTestCase |
python | getsentry__sentry | src/sentry/models/transaction_threshold.py | {
"start": 1873,
"end": 3069
} | class ____(DefaultFieldsModelExisting):
__relocation_scope__ = RelocationScope.Excluded
# max_length here is based on the maximum for transactions in relay
transaction = models.CharField(max_length=200)
project = FlexibleForeignKey("sentry.Project", db_constraint=False)
organization = FlexibleForei... | ProjectTransactionThresholdOverride |
python | getsentry__sentry | src/sentry/explore/models.py | {
"start": 4970,
"end": 10352
} | class ____(BaseManager["ExploreSavedQueryStarred"]):
def get_last_position(self, organization: Organization, user_id: int) -> int:
"""
Returns the last position of a user's starred queries in an organization.
"""
last_starred_query = (
self.filter(
organi... | ExploreSavedQueryStarredManager |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 95612,
"end": 96508
} | class ____(MeanMetricWrapper):
"""Computes the hinge metric between `y_true` and `y_pred`.
`y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are
provided we will convert them to -1 or 1.
Args:
name: (Optional) string name of the metric instance.
dtype: (Optional) data type of the m... | Hinge |
python | walkccc__LeetCode | solutions/1730. Shortest Path to Get Food/1730.py | {
"start": 0,
"end": 843
} | class ____:
def getFood(self, grid: list[list[str]]) -> int:
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
m = len(grid)
n = len(grid[0])
ans = 0
q = collections.deque([self._getStartLocation(grid)])
while q:
for _ in range(len(q)):
i, j = q.popleft()
for dx, dy in DIRS:
... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.