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 | spack__spack | lib/spack/spack/vendor/ruamel/yaml/scalarint.py | {
"start": 4000,
"end": 4268
} | class ____(ScalarInt):
"""needed if anchor"""
def __new__(cls, value, width=None, underscore=None, anchor=None):
# type: (Any, Any, Any, Any) -> Any
return ScalarInt.__new__(cls, value, width=width, underscore=underscore, anchor=anchor)
| DecimalInt |
python | huggingface__transformers | src/transformers/models/owlvit/processing_owlvit.py | {
"start": 1529,
"end": 12658
} | class ____(ProcessorMixin):
r"""
Constructs an OWL-ViT processor which wraps [`OwlViTImageProcessor`] and [`CLIPTokenizer`]/[`CLIPTokenizerFast`]
into a single processor that inherits both the image processor and tokenizer functionalities. See the
[`~OwlViTProcessor.__call__`] and [`~OwlViTProcessor.dec... | OwlViTProcessor |
python | walkccc__LeetCode | solutions/1540. Can Convert String in K Moves/1540.py | {
"start": 0,
"end": 509
} | class ____:
def canConvertString(self, s: str, t: str, k: int) -> bool:
if len(s) != len(t):
return False
# e.g. s = "aab", t = "bbc", so shiftCount[1] = 3
# 1. a -> b, need 1 move.
# 2. a -> b, need 1 + 26 moves.
# 3. b -> c, need 1 + 26 * 2 moves.
shiftCount = [0] * 26
for a, b i... | Solution |
python | bokeh__bokeh | src/bokeh/models/tickers.py | {
"start": 8614,
"end": 9022
} | class ____(BaseSingleIntervalTicker):
''' Generate ticks spaced apart by specific, even multiples of days.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
days = Seq(Int, default=[], help="""
T... | DaysTicker |
python | pypa__setuptools | setuptools/command/sdist.py | {
"start": 568,
"end": 7426
} | class ____(orig.sdist):
"""Smart sdist that finds anything supported by revision control"""
user_options = [
('formats=', None, "formats for source distribution (comma-separated list)"),
(
'keep-temp',
'k',
"keep the distribution tree around after creating ar... | sdist |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datafusion.py | {
"start": 29445,
"end": 38544
} | class ____(GoogleCloudBaseOperator):
"""
Starts a Cloud Data Fusion pipeline. Works for both batch and stream pipelines.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataFusionStartPipelineOperator`
:param pipeline_n... | CloudDataFusionStartPipelineOperator |
python | langchain-ai__langchain | libs/core/langchain_core/embeddings/fake.py | {
"start": 366,
"end": 1907
} | class ____(Embeddings, BaseModel):
"""Fake embedding model for unit testing purposes.
This embedding model creates embeddings by sampling from a normal distribution.
!!! danger "Toy model"
Do not use this outside of testing, as it is not a real embedding model.
Instantiate:
```python
... | FakeEmbeddings |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/data_table_cell_padding.py | {
"start": 83,
"end": 633
} | class ____(App):
CSS = """
DataTable {
margin: 1;
}
"""
def compose(self) -> ComposeResult:
for cell_padding in range(5):
dt = DataTable(cell_padding=cell_padding)
dt.add_columns("one", "two", "three")
dt.add_row("value", "value", "val")
... | TableApp |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple9.py | {
"start": 439,
"end": 1240
} | class ____(Generic[T]):
def __init__(self, /, result: T) -> None:
self.result = result
TailRec = Call[Unpack[Ts]] | Return[T]
def tail_rec(
fn: Callable[[Unpack[Ts]], TailRec[Unpack[Ts], T]],
) -> Callable[[Unpack[Ts]], T]: ...
@tail_rec
def factorial(n: int, acc: int) -> TailRec[int, int, int]:
... | Return |
python | mlflow__mlflow | mlflow/entities/assessment.py | {
"start": 18883,
"end": 21074
} | class ____(_MlflowObject):
"""Represents an expectation value."""
value: Any
def to_proto(self):
if self._need_serialization():
try:
serialized_value = json.dumps(self.value)
except Exception as e:
raise MlflowException.invalid_parameter_valu... | ExpectationValue |
python | pypa__pipenv | pipenv/vendor/plette/models/packages.py | {
"start": 91,
"end": 378
} | class ____(DataModel):
# TODO: one could add here more validation for path editable
# and more stuff which is currently allowed and undocumented
__SCHEMA__ = {}
__OPTIONAL__ = {
"editable": bool,
"version": str,
"extras": list
}
| PackageSpecfiers |
python | kamyu104__LeetCode-Solutions | Python/maximum-nesting-depth-of-the-parentheses.py | {
"start": 29,
"end": 360
} | class ____(object):
def maxDepth(self, s):
"""
:type s: str
:rtype: int
"""
result = curr = 0
for c in s:
if c == '(':
curr += 1
result = max(result, curr)
elif c == ')':
curr -= 1
return ... | Solution |
python | pandas-dev__pandas | pandas/tests/indexes/test_engines.py | {
"start": 2746,
"end": 4787
} | class ____:
def test_is_monotonic(self, numeric_indexing_engine_type_and_dtype):
engine_type, dtype = numeric_indexing_engine_type_and_dtype
num = 1000
arr = np.array([1] * num + [2] * num + [3] * num, dtype=dtype)
# monotonic increasing
engine = engine_type(arr)
ass... | TestNumericEngine |
python | huggingface__transformers | src/transformers/models/llava_next_video/processing_llava_next_video.py | {
"start": 1158,
"end": 1461
} | class ____(ProcessingKwargs, total=False):
# see processing_utils.ProcessingKwargs documentation for usage.
_defaults = {
"text_kwargs": {
"padding": False,
},
"common_kwargs": {
"return_tensors": "pt",
},
}
| LlavaNextVideoProcessorKwargs |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 18044,
"end": 18466
} | class ____(DelegatingLexer):
"""
Subclass of the `MyghtyLexer` that highlights unlexed data
with the `CssLexer`.
.. versionadded:: 0.6
"""
name = 'CSS+Myghty'
aliases = ['css+myghty']
mimetypes = ['text/css+myghty']
def __init__(self, **options):
super(MyghtyCssLexer, self... | MyghtyCssLexer |
python | jazzband__django-simple-history | simple_history/registry_tests/tests.py | {
"start": 6839,
"end": 7178
} | class ____(TestCase):
"""https://github.com/django-commons/django-simple-history/issues/870"""
def test_custom_attr(self):
field = ModelWithCustomAttrOneToOneField.history.model._meta.get_field("poll")
self.assertFalse(hasattr(field, "attr_name"))
@override_settings(MIGRATION_MODULES={})
| TestCustomAttrOneToOneField |
python | doocs__leetcode | solution/2700-2799/2773.Height of Special Binary Tree/Solution.py | {
"start": 192,
"end": 618
} | class ____:
def heightOfTree(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode], d: int):
nonlocal ans
ans = max(ans, d)
if root.left and root.left.right != root:
dfs(root.left, d + 1)
if root.right and root.right.left != ... | Solution |
python | pytorch__pytorch | torch/_dynamo/guards.py | {
"start": 126054,
"end": 129860
} | class ____:
# Maximum number of times a given expression can be used without being
# replaced by a fresh variable.
USE_THRESHOLD = 1
# Ad-Hoc: AST nodes this pass focuses on.
ALLOWED_NODE_TYPES = (ast.Attribute, ast.Call, ast.Subscript)
@dataclasses.dataclass
class Config:
expr_cou... | PyExprCSEPass |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 57377,
"end": 58286
} | class ____(base_classes.Names):
def __init__(self, parent, xl):
self.parent = parent
self.xl = xl
def __call__(self, name_or_index):
return Name(self.parent, xl=self.xl[name_or_index])
def contains(self, name_or_index):
try:
self.xl[name_or_index].get()
... | Names |
python | huggingface__transformers | src/transformers/models/ovis2/modeling_ovis2.py | {
"start": 3009,
"end": 4516
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the lan... | Ovis2CausalLMOutputWithPast |
python | pydata__xarray | xarray/tests/test_plot.py | {
"start": 96380,
"end": 99643
} | class ____(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self) -> None:
self.darray = DataArray(
np.random.randn(10, 6, 3, 4),
dims=["hue", "x", "col", "row"],
coords=[range(10), range(6), range(3), ["A", "B", "C", "C++"]],
name="Cornelius Ortega ... | TestFacetedLinePlots |
python | doocs__leetcode | solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution2.py | {
"start": 0,
"end": 439
} | class ____:
def countCompleteSubarrays(self, nums: List[int]) -> int:
cnt = len(set(nums))
d = Counter()
ans, n = 0, len(nums)
i = 0
for j, x in enumerate(nums):
d[x] += 1
while len(d) == cnt:
ans += n - j
d[nums[i]] -= ... | Solution |
python | kamyu104__LeetCode-Solutions | Python/maximum-length-of-a-concatenated-string-with-unique-characters.py | {
"start": 152,
"end": 1051
} | class ____(object):
def maxLength(self, arr):
"""
:type arr: List[str]
:rtype: int
"""
def bitset(s):
result = 0
for c in s:
if result & power[ord(c)-ord('a')]:
return 0
result |= power[ord(c)-ord('a'... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E25.py | {
"start": 1620,
"end": 1905
} | class ____[A=int, B =str, C= bool, D:object=int, E: object=str, F: object =bool, G: object= bytes]:
pass
# The last of these should cause us to emit E231,
# but E231 isn't tested by this fixture:
def pep_696_good[A = int, B: object = str, C:object = memoryview]():
pass
| PEP696Bad |
python | django__django | tests/select_related_regress/models.py | {
"start": 1323,
"end": 1495
} | class ____(models.Model):
std = models.ForeignKey(Student, models.CASCADE)
cls = models.ForeignKey(Class, models.CASCADE)
# Models for testing bug #8036.
| Enrollment |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/storage_tests/test_defs_state_storage.py | {
"start": 663,
"end": 1537
} | class ____(TestDefsStateStorage):
"""Tests the blob storage state storage implementation."""
__test__ = True
@pytest.fixture(name="storage", scope="function")
def state_storage(self):
with tempfile.TemporaryDirectory() as temp_dir:
with instance_for_test(
overrides=... | TestExplicitUPathDefsStateStorage |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 34493,
"end": 34864
} | class ____(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('index', types.intp),
('value', fe_type.val_typ),
]
models.StructModel.__init__(self, dmm, fe_type, members)
make_attribute_wrapper(IndexValueType, 'index', 'index')
make_attribute_wr... | IndexValueModel |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column.py | {
"start": 77761,
"end": 86872
} | class ____(object):
"""Handles caching of transformations while building the model.
`_FeatureColumn` specifies how to digest an input column to the network. Some
feature columns require data transformations. This class caches those
transformations.
Some features may be used in more than one place. For examp... | _LazyBuilder |
python | sympy__sympy | sympy/stats/frv_types.py | {
"start": 14454,
"end": 16610
} | class ____(SingleFiniteDistribution):
_argnames = ('N', 'm', 'n')
@staticmethod
def check(n, N, m):
_value_check((N.is_integer, N.is_nonnegative),
"'N' must be nonnegative integer. N = %s." % str(N))
_value_check((n.is_integer, n.is_nonnegative),
"'... | HypergeometricDistribution |
python | kamyu104__LeetCode-Solutions | Python/maximum-length-of-semi-decreasing-subarrays.py | {
"start": 42,
"end": 553
} | class ____(object):
def maxSubarrayLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
stk = []
for i in reversed(xrange(len(nums))):
if not stk or nums[stk[-1]] > nums[i]:
stk.append(i)
result = 0
for left in xran... | Solution |
python | faif__python-patterns | patterns/behavioral/chaining_method.py | {
"start": 242,
"end": 712
} | class ____:
def __init__(self, name: str) -> None:
self.name = name
def amount(self, val: str) -> Action:
print(val, end=" ")
return self
def stop(self) -> None:
print("then stop")
def main():
"""
>>> move = Action('move')
>>> person = Person('Jack')
>>> p... | Action |
python | keras-team__keras | guides/training_with_built_in_methods.py | {
"start": 34792,
"end": 35014
} | class ____ `self.model`.
Make sure to read the
[complete guide to writing custom callbacks](/guides/writing_your_own_callbacks/).
Here's a simple example saving a list of per-batch loss values during training:
"""
| property |
python | django__django | tests/async/test_async_model_methods.py | {
"start": 68,
"end": 1226
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.s1 = SimpleModel.objects.create(field=0)
async def test_asave(self):
self.s1.field = 10
await self.s1.asave()
refetched = await SimpleModel.objects.aget()
self.assertEqual(refetched.field, 10)
async ... | AsyncModelOperationTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-weeks-for-which-you-can-work.py | {
"start": 29,
"end": 325
} | class ____(object):
def numberOfWeeks(self, milestones):
"""
:type milestones: List[int]
:rtype: int
"""
total, max_num = sum(milestones), max(milestones)
other_total = (total-max_num)
return other_total+min(other_total+1, max_num)
| Solution |
python | Pylons__pyramid | src/pyramid/traversal.py | {
"start": 31736,
"end": 31851
} | class ____:
__parent__ = None
__name__ = None
def __init__(self, request):
pass
| DefaultRootFactory |
python | huggingface__transformers | tests/models/glpn/test_modeling_glpn.py | {
"start": 5406,
"end": 13135
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (GLPNModel, GLPNForDepthEstimation) if is_torch_available() else ()
pipeline_model_mapping = (
{"depth-estimation": GLPNForDepthEstimation, "image-feature-extraction": GLPNModel}
if is_torch_available()
... | GLPNModelTest |
python | ray-project__ray | python/ray/_private/thirdparty/pyamdsmi/pyamdsmi.py | {
"start": 4817,
"end": 4984
} | class ____(Structure):
_fields_ = [('page_address', c_uint64),
('page_size', c_uint64),
('status', c_int)]
| rsmi_retired_page_record_t |
python | lxml__lxml | doc/s5/ep2008/atom.py | {
"start": 8053,
"end": 8752
} | class ____(object):
"""
Get/set the parsed date value of the text content of a tag.
"""
def __init__(self, tag, ns=atom_ns):
self.tag = tag
self.ns = ns
self.__doc__ = 'Access the date in %s' % self.tag
def __get__(self, obj, type=None):
if obj is None:
r... | _date_element_property |
python | django__django | tests/postgres_tests/models.py | {
"start": 2645,
"end": 2727
} | class ____(models.Model):
field = models.CharField(max_length=64)
| CharFieldModel |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_named_vectors.py | {
"start": 64617,
"end": 65569
} | class ____:
@staticmethod
def update(
name: str,
*,
vector_index_config: Union[
_VectorIndexConfigHNSWUpdate,
_VectorIndexConfigFlatUpdate,
_VectorIndexConfigDynamicUpdate,
],
) -> _NamedVectorConfigUpdate:
"""Update the vector inde... | _NamedVectorsUpdate |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 3449,
"end": 3966
} | class ____(BaseModel, extra="forbid"):
always_ram: Optional[bool] = Field(default=None, description="")
encoding: Optional["BinaryQuantizationEncoding"] = Field(default=None, description="")
query_encoding: Optional["BinaryQuantizationQueryEncoding"] = Field(
default=None,
description="Asymm... | BinaryQuantizationConfig |
python | numpy__numpy | numpy/random/tests/test_smoke.py | {
"start": 27456,
"end": 27772
} | class ____(RNG):
@classmethod
def _create_rng(cls):
bit_generator = Philox
advance = 2**63 + 2**31 + 2**15 + 1
seed = [12345]
rg = Generator(bit_generator(*seed))
seed_vector_bits = 64
return RNGData(bit_generator, advance, seed, rg, seed_vector_bits)
| TestPhilox |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 64819,
"end": 65829
} | class ____(Response):
"""
Response of queues.get_num_entries endpoint.
:param num: Number of entries
:type num: int
"""
_service = "queues"
_action = "get_num_entries"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {"num": {"description": "Number of ... | GetNumEntriesResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 865018,
"end": 865746
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for PublicKey."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PublicKeyEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sg... | PublicKeyConnection |
python | jazzband__django-model-utils | model_utils/fields.py | {
"start": 7963,
"end": 8838
} | class ____:
def __init__(self, field: SplitField):
self.field = field
self.excerpt_field_name = _excerpt_field_name(self.field.name)
def __get__(self, instance: models.Model, owner: type[models.Model]) -> SplitText:
if instance is None:
raise AttributeError('Can only be acce... | SplitDescriptor |
python | spack__spack | lib/spack/spack/url_buildcache.py | {
"start": 54978,
"end": 55120
} | class ____(spack.error.SpackError):
"""Raised when manifest does have some requested type of requested type"""
pass
| NoSuchBlobException |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 96406,
"end": 102279
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes
def testNames(self):
with ops.name_scope("foo", skip_on_eager=False) as foo:
self.assertEqual("foo/", foo)
with ops.name_scope("foo2", skip_on_eager=False) as foo2:
self.assertEqual("foo/foo2/", foo2)
wi... | OpScopeTest |
python | scipy__scipy | scipy/signal/tests/test_signaltools.py | {
"start": 37982,
"end": 43924
} | class ____:
@pytest.mark.slow()
@pytest.mark.parametrize('shape_a_0, shape_b_0',
gen_oa_shapes_eq(list(range(1, 100, 1)) +
list(range(100, 1000, 23)))
)
def test_real_manylens(self, shape_a_0, shape_b_0, ... | TestOAConvolve |
python | getsentry__sentry | tests/sentry/digests/test_utilities.py | {
"start": 913,
"end": 5281
} | class ____(TestCase, SnubaTestCase):
def test_get_event_from_groups_in_digest(self) -> None:
project = self.create_project(fire_project_created=True)
rule = project.rule_set.all()[0]
events = [
self.store_event(
data={"fingerprint": ["group1"], "timestamp": befor... | UtilitiesHelpersTestCase |
python | astropy__astropy | astropy/io/votable/tree.py | {
"start": 52725,
"end": 54759
} | class ____(Field):
"""
PARAM_ element: constant-valued columns in the data.
:class:`Param` objects are a subclass of :class:`Field`, and have
all of its methods and members. Additionally, it defines :attr:`value`.
"""
_attr_list_11 = Field._attr_list_11 + ["value"]
_attr_list_12 = Field._... | Param |
python | scipy__scipy | scipy/interpolate/tests/test_polyint.py | {
"start": 25268,
"end": 35458
} | class ____:
@staticmethod
def check_correctness(S, bc_start='not-a-knot', bc_end='not-a-knot',
tol=1e-14):
"""Check that spline coefficients satisfy the continuity and boundary
conditions."""
x = S.x
c = S.c
dx = np.diff(x)
dx = dx.reshap... | TestCubicSpline |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modular_glm4v_moe.py | {
"start": 13740,
"end": 16915
} | class ____(Qwen3VLMoeModelOutputWithPast):
pass
def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
"""Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
Explanation:
Multimodal 3D rot... | Glm4vMoeModelOutputWithPast |
python | django-extensions__django-extensions | tests/testapp/jobs/yearly/test_yearly_job.py | {
"start": 122,
"end": 229
} | class ____(YearlyJob):
help = "My sample yearly job."
def execute(self):
YEARLY_JOB_MOCK()
| Job |
python | pytorch__pytorch | test/test_segment_reductions.py | {
"start": 796,
"end": 23174
} | class ____(TestCase):
def _test_common(
self,
reduction,
device,
dtype,
unsafe,
axis,
initial_value,
data_arr,
lengths_arr,
expected_arr,
expected_grad_arr,
check_backward,
lengths_dtype=torch.int,
):
... | TestSegmentReductions |
python | django__django | django/contrib/postgres/search.py | {
"start": 12622,
"end": 12712
} | class ____(TrigramWordBase):
function = ""
arg_joiner = " <<-> "
| TrigramWordDistance |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-tiktok-marketing/unit_tests/integration/test_reports_hourly.py | {
"start": 665,
"end": 8114
} | class ____(TestCase):
stream_name = "ads_reports_hourly"
advertiser_id = "872746382648"
cursor = "2024-01-01"
legacy_cursor = "2024-01-01 10:00:00"
cursor_field = "stat_time_hour"
metrics = [
"campaign_name",
"campaign_id",
"adgroup_name",
"placement_type",
... | TestAdsReportHourly |
python | run-llama__llama_index | llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-mongo/llama_index/storage/chat_store/mongo/base.py | {
"start": 789,
"end": 12021
} | class ____(BaseChatStore):
"""MongoDB chat store implementation."""
mongo_uri: str = Field(
default="mongodb://localhost:27017", description="MongoDB URI."
)
db_name: str = Field(default="default", description="MongoDB database name.")
collection_name: str = Field(
default="sessions... | MongoChatStore |
python | doocs__leetcode | solution/0600-0699/0699.Falling Squares/Solution.py | {
"start": 205,
"end": 1596
} | class ____:
def __init__(self):
self.root = Node(1, int(1e9))
def modify(self, l, r, v, node=None):
if l > r:
return
if node is None:
node = self.root
if node.l >= l and node.r <= r:
node.v = v
node.add = v
return
... | SegmentTree |
python | pypa__warehouse | tests/unit/macaroons/test_caveats.py | {
"start": 9739,
"end": 12540
} | class ____:
def test_verify_no_identity(self):
caveat = OIDCPublisher(oidc_publisher_id="invalid")
result = caveat.verify(
pretend.stub(identity=None, oidc_publisher=None),
pretend.stub(),
pretend.stub(),
)
assert result == Failure(
"O... | TestOIDCPublisherCaveat |
python | aio-libs__aiohttp | aiohttp/payload.py | {
"start": 15004,
"end": 25797
} | class ____(Payload):
_value: io.IOBase
# _consumed = False (inherited) - File can be re-read from the same position
_start_position: int | None = None
# _autoclose = False (inherited) - Has file handle that needs explicit closing
def __init__(
self, value: IO[Any], disposition: str = "attac... | IOBasePayload |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 305641,
"end": 307445
} | class ____:
def _create_data(self):
x = 2 * np.ones((3,), dtype=int)
y = 3 * np.ones((3,), dtype=int)
x2 = 2 * np.ones((2, 3), dtype=int)
y2 = 3 * np.ones((2, 3), dtype=int)
ind = [0, 0, 1]
return x, y, x2, y2, ind
def test_basic(self):
x, y, _, _, ind = ... | TestChoose |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVar7.py | {
"start": 205,
"end": 393
} | class ____:
var1: int
def __call__(self, val: int):
pass
def do_stuff(self) -> int:
return 0
def __add__(self, val: "Foo") -> "Foo":
return val
| Foo |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/multi_provider_mpi/package.py | {
"start": 217,
"end": 1193
} | class ____(Package):
"""This is a fake MPI package used to test packages providing multiple
virtuals at the same version."""
homepage = "http://www.spack-fake-mpi.org"
url = "http://www.spack-fake-mpi.org/downloads/multi-mpi-1.0.tar.gz"
version("2.0.0", md5="0123456789abcdef0123456789abcdef")
... | MultiProviderMpi |
python | numba__numba | numba/cuda/tests/cudapy/test_sm.py | {
"start": 2876,
"end": 14575
} | class ____(CUDATestCase):
def _test_shared(self, arr):
# Use a kernel that copies via shared memory to check loading and
# storing different dtypes with shared memory. All threads in a block
# collaborate to load in values, then the output values are written
# only by the first threa... | TestSharedMemory |
python | catalyst-team__catalyst | catalyst/callbacks/metrics/auc.py | {
"start": 242,
"end": 3563
} | class ____(LoaderMetricCallback):
"""ROC-AUC metric callback.
Args:
input_key: input key to use for auc calculation, specifies our ``y_true``.
target_key: output key to use for auc calculation, specifies our ``y_pred``.
compute_per_class_metrics: boolean flag to compute per-class metri... | AUCCallback |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 15070,
"end": 15230
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
"""Contains the start and end column and row for a symbol."""
uri: str
range: LspRange
| LspLocation |
python | gevent__gevent | src/greentest/3.12/test_threading.py | {
"start": 57599,
"end": 63995
} | class ____(BaseTestCase):
# A RuntimeError should be raised if Thread.start() is called
# multiple times.
def test_start_thread_again(self):
thread = threading.Thread()
thread.start()
self.assertRaises(RuntimeError, thread.start)
thread.join()
def test_joining_current_th... | ThreadingExceptionTests |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 12815,
"end": 13135
} | class ____(Pix2SkyProjection, Zenithal):
r"""
Gnomonic projection - pixel to sky.
Corresponds to the ``TAN`` projection in FITS WCS.
See `Zenithal` for a definition of the full transformation.
.. math::
\theta = \tan^{-1}\left(\frac{180^{\circ}}{\pi R_\theta}\right)
"""
| Pix2Sky_Gnomonic |
python | dagster-io__dagster | python_modules/libraries/dagster-gcp/dagster_gcp/gcs/resources.py | {
"start": 1340,
"end": 2885
} | class ____(ConfigurableResource, IAttachDifferentObjectToOpContext):
"""FileManager that provides abstract access to GCS."""
project: Optional[str] = Field(default=None, description="Project name")
gcs_bucket: str = Field(description="GCS bucket to store files")
gcs_prefix: str = Field(default="dagster... | GCSFileManagerResource |
python | huggingface__transformers | src/transformers/models/led/modeling_led.py | {
"start": 2726,
"end": 3502
} | class ____(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
"""
def __init__(self, num_embeddings: int, embedding_dim: int):
super().__init__(num_embeddings, embedding_dim)
def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0... | LEDLearnedPositionalEmbedding |
python | plotly__plotly.py | plotly/graph_objs/sunburst/_leaf.py | {
"start": 233,
"end": 2332
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sunburst"
_path_str = "sunburst.leaf"
_valid_props = {"opacity"}
@property
def opacity(self):
"""
Sets the opacity of the leaves. With colorscale it is defaulted
to 1; otherwise it is defaulted to 0.7
The 'opa... | Leaf |
python | rq__rq | rq/worker.py | {
"start": 76244,
"end": 76465
} | class ____(Worker):
"""
Modified version of Worker that dequeues jobs from the queues using a random strategy.
"""
def reorder_queues(self, reference_queue):
shuffle(self._ordered_queues)
| RandomWorker |
python | huggingface__transformers | tests/models/depth_pro/test_image_processing_depth_pro.py | {
"start": 2889,
"end": 4453
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = DepthProImageProcessor if is_vision_available() else None
fast_image_processing_class = DepthProImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_... | DepthProImageProcessingTest |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_trace.py | {
"start": 55550,
"end": 59795
} | class ____(OrganizationEventsTraceEndpointBase):
url_name = "sentry-api-0-organization-events-trace-meta"
def test_no_projects(self) -> None:
user = self.create_user()
org = self.create_organization(owner=user)
self.login_as(user=user)
url = reverse(
self.url_name,
... | OrganizationEventsTraceMetaEndpointTest |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 1610,
"end": 3452
} | class ____:
@property
def apps(self):
return Apps()
@property
def name(self):
return "excel"
@property
def type(self):
return "desktop"
@staticmethod
def prepare_xl_data_element(x, options):
if x is None:
return ""
elif pd and pd.isn... | Engine |
python | pytorch__pytorch | torch/_dynamo/utils.py | {
"start": 10564,
"end": 30925
} | class ____:
"""
Helper class for representing adding metadata(i.e. columns) to various compile events.
Use CompileEventLogger to add event data to:
- Chromium events
- PT2 Compile Events
- CompilationMetrics
This should be used in conjunction with dynamo_timed() and metrics contexts, which ... | CompileEventLogger |
python | PyCQA__pylint | doc/data/messages/i/invalid-overridden-method/good.py | {
"start": 74,
"end": 153
} | class ____(Fruit):
async def bore(self, insect):
insect.eat(self)
| Apple |
python | openai__openai-python | src/openai/_response.py | {
"start": 21460,
"end": 29510
} | class ____(Generic[_AsyncAPIResponseT]):
"""Context manager for ensuring that a request is not made
until it is entered and that the response will always be closed
when the context manager exits
"""
def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None:
self._api_request = ... | AsyncResponseContextManager |
python | pandas-dev__pandas | pandas/core/interchange/dataframe_protocol.py | {
"start": 621,
"end": 1279
} | class ____(enum.IntEnum):
"""
Integer enum for data types.
Attributes
----------
INT : int
Matches to signed integer data type.
UINT : int
Matches to unsigned integer data type.
FLOAT : int
Matches to floating point data type.
BOOL : int
Matches to boolea... | DtypeKind |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 18559,
"end": 18656
} | class ____(IterableExportEventsStreamAdjustableRange):
data_field = "smsUsageInfo"
| SmsUsageInfo |
python | realpython__materials | python-all-attribute/shapes/square.py | {
"start": 36,
"end": 164
} | class ____:
def __init__(self, side):
self.side = validate(side)
def area(self):
return self.side**2
| Square |
python | getsentry__sentry | src/sentry/utils/codecs.py | {
"start": 2083,
"end": 2288
} | class ____(Codec[bytes, bytes]):
def encode(self, value: bytes) -> bytes:
return zlib.compress(value)
def decode(self, value: bytes) -> bytes:
return zlib.decompress(value)
| ZlibCodec |
python | huggingface__transformers | src/transformers/models/stablelm/configuration_stablelm.py | {
"start": 881,
"end": 7945
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`~StableLmModel`].
It is used to instantiate an StableLM model according to the specified arguments, defining the model
architecture. Instantiating a configuration with the defaults will yield a similar c... | StableLmConfig |
python | scipy__scipy | scipy/interpolate/_fitpack_repro.py | {
"start": 31173,
"end": 52250
} | class ____:
def __init__(self, **kwargs):
self.__dict__.update(**kwargs)
_iermesg1 = """error. a theoretically impossible result was found during
the iteration process for finding a smoothing spline with
fp = s. probably causes : s too small.
"""
_iermesg = {
1: _iermesg1 + """the weighted sum of squared... | Bunch |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 36653,
"end": 36794
} | class ____(Operator):
__slots__ = ()
_description = "exclusion"
def _op(self, left, right):
return left not in right
| NotIn |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI059.py | {
"start": 635,
"end": 688
} | class ____(Generic, LinkedList): # PYI059
pass
| Foo |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py | {
"start": 31572,
"end": 31966
} | class ____(
MetadataValue[str],
IHaveNew,
):
name: PublicAttr[str]
def __new__(cls, pool: str):
return super().__new__(cls, name=pool)
@public
@property
def value(self) -> str:
"""str: The wrapped pool string."""
return self.pool
@public
@property
def p... | PoolMetadataValue |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 65803,
"end": 66218
} | class ____(TestCase):
def test_simple(self):
assert_(sinc(0) == 1)
w = sinc(np.linspace(-1, 1, 100))
# check symmetry
assert_array_almost_equal(w, np.flipud(w), 7)
def test_array_like(self):
x = [0, 0.5]
y1 = sinc(np.array(x))
y2 = sinc(list(x))
y... | TestSinc |
python | pandas-dev__pandas | pandas/core/dtypes/dtypes.py | {
"start": 39964,
"end": 49122
} | class ____(PandasExtensionDtype):
"""
An ExtensionDtype for Interval data.
**This is not an actual numpy dtype**, but a duck type.
Parameters
----------
subtype : str, np.dtype
The dtype of the Interval bounds.
closed : {'right', 'left', 'both', 'neither'}, default 'right'
... | IntervalDtype |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/assets.py | {
"start": 1663,
"end": 1830
} | class ____(BaseModel):
"""Last asset event response serializer."""
id: NonNegativeInt | None = None
timestamp: datetime | None = None
| LastAssetEventResponse |
python | ZoranPandovski__al-go-rithms | data_structures/trie/Python/trie.py | {
"start": 67,
"end": 281
} | class ____:
# Trie node class
def __init__(self):
self.children = [None]*26
# isEndOfWord is True if node represent the end of the word
self.isEndOfWord = False
| TrieNode |
python | tensorflow__tensorflow | tensorflow/python/distribute/strategy_combinations_test.py | {
"start": 1613,
"end": 3229
} | class ____(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.combine(
strategy=strategy_combinations.two_replica_strategies,
mode=["graph", "eager"]))
def testTwoReplicaStrategy(self, strategy):
with strategy.scope():
@def_function.function
def ... | StrategyCombinationsTest |
python | Lightning-AI__lightning | tests/tests_pytorch/helpers/datamodules.py | {
"start": 3576,
"end": 4277
} | class ____(SklearnDataModule):
def __init__(
self, num_features=32, length=800, num_classes=3, batch_size=10, n_clusters_per_class=1, n_informative=2
):
if not _SKLEARN_AVAILABLE:
raise ImportError(str(_SKLEARN_AVAILABLE))
from sklearn.datasets import make_classification
... | ClassifDataModule |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox26.py | {
"start": 315,
"end": 964
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox26.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | getsentry__sentry | src/sentry/replays/lib/new_query/conditions.py | {
"start": 3931,
"end": 4465
} | class ____(GenericBase):
"""Boolean integer scalar condition class."""
@staticmethod
def visit_eq(expression: Expression, value: int) -> Condition:
if value:
return Condition(expression, Op.GT, 0)
else:
return Condition(expression, Op.EQ, 0)
@staticmethod
de... | BooleanIntegerScalar |
python | PyCQA__pylint | tests/functional/m/multiple_statements_single_line.py | {
"start": 650,
"end": 683
} | class ____(Exception): a='a'
| MyError |
python | tensorflow__tensorflow | tensorflow/python/util/vlog_test.py | {
"start": 1067,
"end": 1447
} | class ____(test.TestCase):
# Runs a simple conv graph to check if VLOG crashes.
def test_simple_conv(self):
height, width = 7, 9
images = random_ops.random_uniform((5, height, width, 3))
w = random_ops.random_normal([5, 5, 3, 32], mean=0, stddev=1)
nn_ops.conv2d(images, w, strides=[1, 1, 1, 1], pad... | VlogTest |
python | streamlit__streamlit | lib/tests/streamlit/data_test_cases.py | {
"start": 3398,
"end": 3486
} | class ____(TypedDict):
name: str
is_widget: bool
usage: float
| ElementTypedDict |
python | pypa__warehouse | warehouse/packaging/interfaces.py | {
"start": 2537,
"end": 2655
} | class ____(ProjectNameUnavailableError):
"""Project name is invalid."""
pass
| ProjectNameUnavailableInvalidError |
python | lepture__authlib | authlib/integrations/starlette_client/integration.py | {
"start": 162,
"end": 2253
} | class ____(FrameworkIntegration):
async def _get_cache_data(self, key: Hashable):
value = await self.cache.get(key)
if not value:
return None
try:
return json.loads(value)
except (TypeError, ValueError):
return None
async def get_state_data(
... | StarletteIntegration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.