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 | astropy__astropy | astropy/modeling/rotations.py | {
"start": 8834,
"end": 10027
} | class ____(_EulerRotation, Model):
"""
Base class for RotateNative2Celestial and RotateCelestial2Native.
"""
lon = Parameter(
default=0, getter=_to_orig_unit, setter=_to_radian, description="Latitude"
)
lat = Parameter(
default=0, getter=_to_orig_unit, setter=_to_radian, descrip... | _SkyRotation |
python | fastai__fastai | fastai/vision/augment.py | {
"start": 43711,
"end": 44567
} | class ____():
def __init__(self, max_lighting=0.2, p=0.75, draw=None, batch=False): store_attr()
def _def_draw(self, x):
if not self.batch: return x.new_empty(x.size(0)).uniform_(0.5*(1-self.max_lighting), 0.5*(1+self.max_lighting))
return x.new_zeros(x.size(0)) + random.uniform(0.5*(1-self.max... | _BrightnessLogit |
python | doocs__leetcode | solution/1500-1599/1513.Number of Substrings With Only 1s/Solution.py | {
"start": 0,
"end": 270
} | class ____:
def numSub(self, s: str) -> int:
mod = 10**9 + 7
ans = cur = 0
for c in s:
if c == "0":
cur = 0
else:
cur += 1
ans = (ans + cur) % mod
return ans
| Solution |
python | pytorch__pytorch | test/dynamo/test_graph_deduplication.py | {
"start": 12943,
"end": 17221
} | class ____(torch.nn.Module):
def forward(self, primals_1: "f32[10, 10]", primals_2: "f32[10, 20]"):
cos: "f32[10, 10]" = torch.ops.aten.cos.default(primals_1)
sin: "f32[10, 20]" = torch.ops.aten.sin.default(primals_2)
partitioned_fw_subgraph_0_0 = self.partitioned_fw_subgraph_0_0
i... | GraphModule |
python | django-mptt__django-mptt | mptt/templatetags/mptt_tags.py | {
"start": 973,
"end": 9202
} | class ____(template.Node):
def __init__(
self,
node,
context_var,
foreign_key=None,
count_attr=None,
cumulative=False,
all_descendants=False,
):
self.node = template.Variable(node)
self.context_var = context_var
self.foreign_key = f... | DrilldownTreeForNodeNode |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_v3_utils.py | {
"start": 5575,
"end": 6168
} | class ____(trackable_base.Trackable):
"""Trackable for sparsecore layouts used in training."""
def __init__(self, proto_str_tensor: tensor.Tensor):
self.value = proto_str_tensor
def _serialize_to_tensors(self) -> Dict[str, tensor.Tensor]:
return {trackable_base.VARIABLE_VALUE_KEY: self.value}
def _re... | SparseCoreLayoutsTrackable |
python | numba__numba | numba/core/datamodel/packer.py | {
"start": 4973,
"end": 6645
} | class ____(object):
"""
An object used to unflatten nested sequences after a given pattern
(an arbitrarily nested sequence).
The pattern shows the nested sequence shape desired when unflattening;
the values it contains are irrelevant.
"""
def __init__(self, pattern):
self._code = se... | _Unflattener |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_integration_details.py | {
"start": 2196,
"end": 3728
} | class ____(OrganizationIntegrationDetailsTest):
method = "post"
def test_update_config(self) -> None:
config = {"setting": "new_value", "setting2": "baz"}
self.get_success_response(self.organization.slug, self.integration.id, **config)
org_integration = OrganizationIntegration.objects.... | OrganizationIntegrationDetailsPostTest |
python | sympy__sympy | sympy/tensor/functions.py | {
"start": 267,
"end": 3749
} | class ____(Expr):
"""
Generic class for tensor products.
"""
is_number = False
def __new__(cls, *args, **kwargs):
from sympy.tensor.array import NDimArray, tensorproduct, Array
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.matrixbase import Ma... | TensorProduct |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_vision.py | {
"start": 16983,
"end": 18163
} | class ____(nn.Module):
def __init__(self, config: Data2VecVisionConfig, window_size: Optional[tuple] = None) -> None:
super().__init__()
self.attention = DATA2VEC_VISION_SELF_ATTENTION_CLASSES[config._attn_implementation](
config, window_size=window_size
)
self.output = D... | Data2VecVisionAttention |
python | google__jax | jax/experimental/mosaic/gpu/tcgen05.py | {
"start": 32678,
"end": 39009
} | class ____(fa.TiledLayout):
"""Represents the way a shape is laid out in TMEM.
The layout describes how the shape is split across the 128 rows (lanes) of
TMEM. We reinterpret warp_dims as the partitioning of TMEM into 4 banks, each
accessible from a single warp. The 32 lanes inside each bank are assigned
con... | TMEMLayout |
python | django__django | django/contrib/gis/db/models/lookups.py | {
"start": 314,
"end": 440
} | class ____(Transform):
def as_sql(self, compiler, connection):
return compiler.compile(self.lhs)
| RasterBandTransform |
python | Textualize__textual | tests/tree/test_tree_messages.py | {
"start": 6235,
"end": 7064
} | class ____(Vertical):
"""Testing widget related to https://github.com/Textualize/textual/issues/3869"""
def __init__(self, auto_expand: bool) -> None:
super().__init__()
self._auto_expand = auto_expand
def compose(self) -> ComposeResult:
"""Compose the child widgets."""
yie... | TreeWrapper |
python | mwaskom__seaborn | tests/test_categorical.py | {
"start": 6058,
"end": 23700
} | class ____(SharedAxesLevelTests):
"""Tests functionality common to stripplot and swarmplot."""
def get_last_color(self, ax):
colors = ax.collections[-1].get_facecolors()
unique_colors = np.unique(colors, axis=0)
assert len(unique_colors) == 1
return to_rgba(unique_colors.squeez... | SharedScatterTests |
python | readthedocs__readthedocs.org | readthedocs/search/api/v3/views.py | {
"start": 5625,
"end": 5715
} | class ____(SettingsOverrideObject):
_default_class = BaseProxiedSearchAPI
| ProxiedSearchAPI |
python | getsentry__sentry | src/sentry/conf/types/kafka_definition.py | {
"start": 5261,
"end": 6686
} | class ____(TypedDict, total=False):
# Default topic
topic: Required[Topic]
# Schema validation will be run if true
validate_schema: bool | None
strategy_factory: Required[str]
# Additional CLI options the consumer should accept. These arguments are
# passed as kwargs to the strategy_facto... | ConsumerDefinition |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_array_formula01.py | {
"start": 315,
"end": 2507
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("array_formula01.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.... | TestCompareXLSXFiles |
python | scipy__scipy | benchmarks/benchmarks/linalg.py | {
"start": 2829,
"end": 3650
} | class ____(Benchmark):
params = [
[(100, 10, 10), (100, 20, 20), (100, 100)],
["gen", "pos", "sym"],
["scipy", "numpy"]
]
param_names = ["shape", "structure" ,"module"]
def setup(self, shape, structure, module):
a = random(shape)
# larger diagonal ensures non-sin... | BatchedSolveBench |
python | pennersr__django-allauth | allauth/socialaccount/providers/globus/views.py | {
"start": 181,
"end": 1169
} | class ____(OAuth2Adapter):
provider_id = "globus"
provider_default_url = "https://auth.globus.org/v2/oauth2"
provider_base_url = "https://auth.globus.org/v2/oauth2"
access_token_url = "{0}/token".format(provider_base_url)
authorize_url = "{0}/authorize".format(provider_base_url)
profile_url = ... | GlobusOAuth2Adapter |
python | django__django | tests/gis_tests/distapp/models.py | {
"start": 1157,
"end": 1269
} | class ____(NamedModel):
"Geodetic model for U.S. Interstates."
path = models.LineStringField()
| Interstate |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_validation.py | {
"start": 40603,
"end": 40671
} | class ____:
def cache(self, func):
return func
| DummyMemory |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/styles/style_transformation.py | {
"start": 4199,
"end": 7838
} | class ____(StyleTransformation):
"""
Adjust the brightness to improve the rendering on either dark or light
backgrounds.
For dark backgrounds, it's best to increase `min_brightness`. For light
backgrounds it's best to decrease `max_brightness`. Usually, only one
setting is adjusted.
This w... | AdjustBrightnessStyleTransformation |
python | scipy__scipy | scipy/ndimage/tests/test_interpolation.py | {
"start": 40295,
"end": 48508
} | class ____:
@pytest.mark.parametrize('order', range(0, 6))
def test_shift01(self, order, xp):
data = xp.asarray([1])
out = ndimage.shift(data, [1], order=order)
assert_array_almost_equal(out, xp.asarray([0]))
@pytest.mark.parametrize('order', range(0, 6))
def test_shift02(self,... | TestShift |
python | graphql-python__graphene | graphene/types/tests/test_definition.py | {
"start": 977,
"end": 1063
} | class ____(ObjectType):
article_subscribe = Field(Article, id=String())
| Subscription |
python | django__django | tests/fixtures_regress/models.py | {
"start": 3987,
"end": 4230
} | class ____(Parent):
data = models.CharField(max_length=10, unique=True)
objects = NKManager()
def natural_key(self):
return (self.data,)
def __str__(self):
return "NKChild %s:%s" % (self.name, self.data)
| NKChild |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 42622,
"end": 43780
} | class ____(base_classes.Characters):
def __init__(self, parent, xl):
self.parent = parent
self.xl = xl
@property
def api(self):
return self.xl
@property
def text(self):
return self.xl.content.get()
@property
def font(self):
return Font(self, self.xl... | Characters |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1212086,
"end": 1212290
} | class ____(Sort):
"""AllSortString schema wrapper."""
_schema = {"$ref": "#/definitions/AllSortString"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| AllSortString |
python | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 67940,
"end": 68428
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = BigBirdLMPredictionHead(config)
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, sequence_output, pooled_output):
prediction_scores = self.predictions(sequence_outp... | BigBirdPreTrainingHeads |
python | numpy__numpy | benchmarks/benchmarks/bench_itemselection.py | {
"start": 1201,
"end": 1730
} | class ____(Benchmark):
params = [
[True, False],
TYPES1 + ["O", "i,O"]]
param_names = ["values_is_scalar", "dtype"]
def setup(self, values_is_scalar, dtype):
if values_is_scalar:
self.vals = np.array(1., dtype=dtype)
else:
self.vals = np.ones(1000, dt... | Put |
python | weaviate__weaviate-python-client | weaviate/backup/async_.py | {
"start": 165,
"end": 228
} | class ____(_BackupExecutor[ConnectionAsync]):
pass
| _BackupAsync |
python | ZoranPandovski__al-go-rithms | data_structures/check_bipartite/python/bipartite.py | {
"start": 117,
"end": 2323
} | class ____():
def __init__(self, V):
self.V = V
self.graph = [[0 for column in range(V)]
for row in range(V)]
# This function returns true if graph G[V][V]
# is Bipartite, else false
def isBipartite(self, src):
# Create a color arra... | Graph |
python | pytorch__pytorch | torch/distributed/algorithms/model_averaging/averagers.py | {
"start": 1036,
"end": 5417
} | class ____(ModelAverager):
r"""
Averages parameters periodically after the warm-up stage.
This can be used for running `post-local SGD <https://arxiv.org/abs/1808.07217>`_,
by running :class:`~torch.nn.DistributedDataParallel` (DDP)
using the subgroups created by :meth:`~torch.distributed.new_subgr... | PeriodicModelAverager |
python | great-expectations__great_expectations | tests/checkpoint/test_checkpoint.py | {
"start": 6109,
"end": 15785
} | class ____:
@pytest.fixture
def in_memory_context(self) -> EphemeralDataContext:
return gx.get_context(mode="ephemeral")
@pytest.fixture
def validation_definition_1(
self, in_memory_context: EphemeralDataContext, mocker: MockerFixture
):
name = "my_first_validation"
... | TestCheckpointSerialization |
python | ethereum__web3.py | web3/_utils/module_testing/persistent_connection_provider.py | {
"start": 5673,
"end": 34754
} | class ____:
@pytest.fixture(autouse=True)
def clear_caches(self, async_w3: "AsyncWeb3[Any]") -> Generator[None, None, None]:
yield
async_w3.provider._request_processor.clear_caches()
async_w3.subscription_manager.total_handler_calls = 0
@staticmethod
async def seed_transactions_... | PersistentConnectionProviderTest |
python | celery__celery | t/unit/tasks/test_stamping.py | {
"start": 241,
"end": 779
} | class ____(StampingVisitor):
def on_signature(self, actual_sig: Signature, **headers) -> dict:
link_workflow = chain(
group(signature("task1"), signature("task2")),
signature("task3"),
)
link = signature(f"{actual_sig.name}_link") | link_workflow.clone()
actua... | LinkingVisitor |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 33704,
"end": 34323
} | class ____(TestCase):
"""
Tests for an inactive user
"""
@classmethod
def setUpTestData(cls):
cls.user1 = User.objects.create_user("test", "test@example.com", "test")
cls.user1.is_active = False
cls.user1.save()
def test_has_perm(self):
self.assertIs(self.user1.... | InActiveUserBackendTest |
python | plotly__plotly.py | plotly/graph_objs/scattergeo/selected/_marker.py | {
"start": 233,
"end": 3599
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattergeo.selected"
_path_str = "scattergeo.selected.marker"
_valid_props = {"color", "opacity", "size"}
@property
def color(self):
"""
Sets the marker color of selected points.
The 'color' property is a color and ma... | Marker |
python | huggingface__transformers | src/transformers/models/rt_detr_v2/modular_rt_detr_v2.py | {
"start": 27950,
"end": 28019
} | class ____(RTDetrMLPPredictionHead):
pass
| RTDetrV2MLPPredictionHead |
python | python__mypy | mypy/test/testtypes.py | {
"start": 1361,
"end": 6868
} | class ____(Suite):
def setUp(self) -> None:
self.x = UnboundType("X") # Helpers
self.y = UnboundType("Y")
self.fx = TypeFixture()
self.function = self.fx.function
def test_any(self) -> None:
assert_equal(str(AnyType(TypeOfAny.special_form)), "Any")
def test_simple_... | TypesSuite |
python | google__pytype | pytype/rewrite/function_call_helper_test.py | {
"start": 154,
"end": 438
} | class ____(test_utils.ContextfulTestBase):
def setUp(self):
super().setUp()
frame = frame_lib.Frame(
self.ctx,
'__main__',
test_utils.parse(''),
initial_locals={},
initial_globals={},
)
self.helper = frame._call_helper
| TestBase |
python | fastapi__sqlmodel | docs_src/tutorial/connect/select/tutorial005.py | {
"start": 254,
"end": 2217
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
sqlite_file_name = "database.db"
sqli... | Hero |
python | docker__docker-py | tests/unit/auth_test.py | {
"start": 200,
"end": 503
} | class ____(unittest.TestCase):
def test_803_urlsafe_encode(self):
auth_data = {
'username': 'root',
'password': 'GR?XGR?XGR?XGR?X'
}
encoded = auth.encode_header(auth_data)
assert b'/' not in encoded
assert b'_' in encoded
| RegressionTest |
python | pytest-dev__pytest | src/_pytest/legacypath.py | {
"start": 8903,
"end": 9355
} | class ____:
@staticmethod
@fixture
def testdir(pytester: Pytester) -> Testdir:
"""
Identical to :fixture:`pytester`, and provides an instance whose methods return
legacy ``LEGACY_PATH`` objects instead when applicable.
New code should avoid using :fixture:`testdir` in favor ... | LegacyTestdirPlugin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/mccabe/C901.py | {
"start": 1563,
"end": 2112
} | class ____:
def handle(self, *args, **options):
if args:
return
class ServiceProvider:
def a(self):
pass
def b(self, data):
if not args:
pass
class Logger:
def c(*args, **kwargs):
... | Class |
python | facebookresearch__faiss | faiss/gpu/test/test_gpu_index_ivfflat.py | {
"start": 231,
"end": 780
} | class ____(unittest.TestCase):
def test_reconstruct_n(self):
index = faiss.index_factory(4, "IVF10,Flat")
x = np.random.RandomState(123).rand(10, 4).astype('float32')
index.train(x)
index.add(x)
res = faiss.StandardGpuResources()
res.noTempMemory()
config = fa... | TestGpuIndexIvfflat |
python | facebookresearch__faiss | tests/test_index.py | {
"start": 18180,
"end": 20047
} | class ____(unittest.TestCase):
def test_shard_flag_propagation(self):
d = 64 # dimension
nb = 1000
rs = np.random.RandomState(1234)
xb = rs.rand(nb, d).astype('float32')
nlist = 10
quantizer1 = faiss.IndexFlatL2(d)
quantizer2 = faiss.... | TestShardReplicas |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/metadata/pipeline.py | {
"start": 991,
"end": 1951
} | class ____(SimpleDockerStep):
def __init__(self, context: ConnectorContext) -> None:
super().__init__(
title=f"Validate metadata for {context.connector.technical_name}",
context=context,
paths_to_mount=[
MountPath(context.connector.code_directory),
... | MetadataValidation |
python | pydantic__pydantic | tests/mypy/outputs/mypy-default_ini/metaclass_args.py | {
"start": 40,
"end": 267
} | class ____(BaseModel):
i: int = Field(2, alias='j')
class Config:
validate_by_name = True
ConfigClassUsed(i=None)
# MYPY: error: Unexpected keyword argument "i" for "ConfigClassUsed" [call-arg]
| ConfigClassUsed |
python | numba__numba | numba/np/ufunc/ufunc_base.py | {
"start": 66,
"end": 585
} | class ____:
'''Callable class responsible for lowering calls to a specific gufunc.
'''
def __init__(self, ufunc, make_kernel_fn, make_ufunc_kernel_fn):
self.ufunc = ufunc
self.make_ufunc_kernel_fn = make_ufunc_kernel_fn
self.kernel = make_kernel_fn(ufunc)
self.libs = []
... | UfuncLowererBase |
python | django__django | tests/admin_inlines/models.py | {
"start": 6606,
"end": 6769
} | class ____(models.Model):
name = models.CharField(max_length=100)
capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE, related_name="+")
| SottoCapo |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/delete/tutorial001_py39.py | {
"start": 469,
"end": 2603
} | class ____(SQLModel):
name: Optional[str] = None
secret_name: Optional[str] = None
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
... | HeroUpdate |
python | getsentry__sentry | src/sentry/integrations/slack/unfurl/discover.py | {
"start": 2591,
"end": 12237
} | class ____(Exception):
pass
def get_double_period(period: str) -> str:
m = re.match(r"^(\d+)([hdmsw]?)$", period)
if not m:
m = re.match(r"^(\d+)([hdmsw]?)$", DEFAULT_PERIOD)
value, unit = m.groups() # type: ignore[union-attr]
value = int(value)
return f"{value * 2}{unit}"
def get... | IntervalException |
python | pypa__warehouse | warehouse/manage/forms.py | {
"start": 3629,
"end": 3713
} | class ____(TeamProjectRoleNameMixin, wtforms.Form):
pass
| ChangeTeamProjectRoleForm |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_method.py | {
"start": 1164,
"end": 1514
} | class ____(metaclass=abc.ABCMeta):
@abc.abstractmethod
def __iter__(self):
pass
@abc.abstractmethod
def __len__(self):
pass
@abc.abstractmethod
def __contains__(self, _):
pass
@abc.abstractmethod
def __hash__(self):
pass
# +1: [abstract-method, abstract-... | Structure |
python | numba__numba | numba/tests/test_parfors_passes.py | {
"start": 1011,
"end": 4650
} | class ____(TestCase):
@classmethod
def _run_parfor(cls, test_func, args, swap_map=None):
# TODO: refactor this with get_optimized_numba_ir() where this is
# copied from
typingctx = cpu_target.typing_context
targetctx = cpu_target.target_context
test_ir = compiler.ru... | BaseTest |
python | google__pytype | pytype/constant_folding.py | {
"start": 7086,
"end": 7396
} | class ____:
"""Mapping from a folded opcode to the top level constant that replaces it."""
def __init__(self):
self.folds = {}
def add(self, op):
self.folds[id(op)] = op.folded
def resolve(self, op):
f = op
while id(f) in self.folds:
f = self.folds[id(f)]
return f
| _FoldedOps |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_mutating_admission_policy_spec.py | {
"start": 383,
"end": 14812
} | 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... | V1beta1MutatingAdmissionPolicySpec |
python | catalyst-team__catalyst | catalyst/contrib/models/mnist.py | {
"start": 92,
"end": 1074
} | class ____(nn.Module):
"""Simple MNIST convolutional network for test purposes."""
def __init__(self, out_features: int, normalize: bool = True):
"""
Args:
out_features: size of the output tensor
normalize: boolean flag to add normalize layer
"""
super().... | MnistSimpleNet |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/markdown.py | {
"start": 11426,
"end": 11537
} | class ____(TypedDict):
"""Line type as typed dict."""
metadata: dict[str, str]
content: str
| LineType |
python | Textualize__textual | src/textual/events.py | {
"start": 4750,
"end": 4923
} | class ____(Event, bubble=False, verbose=False):
"""Sent when a widget is unmounted and may no longer receive messages.
- [ ] Bubbles
- [ ] Verbose
"""
| Unmount |
python | django__django | tests/admin_widgets/models.py | {
"start": 332,
"end": 380
} | class ____(models.FileField):
pass
| MyFileField |
python | pytorch__pytorch | torch/_inductor/fx_passes/group_batch_fusion.py | {
"start": 14912,
"end": 19915
} | class ____(BatchPointwiseOpsFusionFactory):
"""
Batch pointwise math operator (e.g., add, mul) in post grad pass.
"""
def __init__(self, op, **kwargs) -> None:
super().__init__(op, **kwargs)
self.op = op
def _pointwise_node_can_be_fused(self, node: torch.fx.Node):
# note: w... | BatchPointwiseMathOpsPostGradFusion |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 439280,
"end": 440584
} | class ____(Fit):
"""
GeoJsonFeatureCollection schema wrapper.
A collection of feature objects. https://tools.ietf.org/html/rfc7946#section-3.3
Parameters
----------
features : Sequence[dict, :class:`FeatureGeometryGeoJsonProperties`]
type : Literal['FeatureCollection']
Specifies ... | GeoJsonFeatureCollection |
python | huggingface__transformers | src/transformers/models/idefics/modeling_idefics.py | {
"start": 19738,
"end": 21158
} | class ____(nn.Module):
def __init__(
self,
hidden_size: int,
intermediate_size: int,
hidden_act: str,
):
super().__init__()
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
self.down_proj = nn.Linear(intermediate_size, hidden_size, bi... | IdeficsMLP |
python | wandb__wandb | wandb/sdk/internal/sender_config.py | {
"start": 325,
"end": 7133
} | class ____:
"""The configuration of a run."""
def __init__(self, tree: Optional[Dict[str, Any]] = None) -> None:
self._tree: Dict[str, Any] = tree or {}
"""A tree with string-valued nodes and JSON leaves.
Leaves are Python objects that are valid JSON values:
* Primitives like ... | ConfigState |
python | numba__numba | numba/core/types/npytypes.py | {
"start": 13173,
"end": 13598
} | class ____(SimpleIteratorType):
"""
Type class for `np.ndindex()` objects.
"""
def __init__(self, ndim):
from . import UniTuple, intp
self.ndim = ndim
yield_type = UniTuple(intp, self.ndim)
name = "ndindex(ndim={ndim})".format(ndim=ndim)
super(NumpyNdIndexType, s... | NumpyNdIndexType |
python | openai__openai-python | src/openai/types/fine_tuning/reinforcement_method_param.py | {
"start": 824,
"end": 1090
} | class ____(TypedDict, total=False):
grader: Required[Grader]
"""The grader used for the fine-tuning job."""
hyperparameters: ReinforcementHyperparametersParam
"""The hyperparameters used for the reinforcement fine-tuning job."""
| ReinforcementMethodParam |
python | huggingface__transformers | tests/models/sam_hq/test_modeling_sam_hq.py | {
"start": 19620,
"end": 30379
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as SAM-HQ's vision encoder does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (SamHQModel,) if is_torch_available... | SamHQModelTest |
python | astropy__astropy | astropy/io/ascii/basic.py | {
"start": 2540,
"end": 3219
} | class ____(BasicHeader):
"""
Header class for which the column definition line starts with the
comment character. See the :class:`CommentedHeader` class for an example.
"""
def process_lines(self, lines):
"""
Return only lines that start with the comment regexp. For these
... | CommentedHeaderHeader |
python | ethereum__web3.py | web3/geth.py | {
"start": 512,
"end": 708
} | class ____(Protocol):
def __call__(
self,
account: ChecksumAddress,
passphrase: str,
duration: int | None = None,
) -> bool:
pass
| UnlockAccountWrapper |
python | getsentry__sentry | src/sentry/integrations/github/types.py | {
"start": 27,
"end": 178
} | class ____(StrEnum):
ASSIGNED = "assigned"
UNASSIGNED = "unassigned"
CLOSED = "closed"
REOPENED = "reopened"
| IssueEvenntWebhookActionType |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-valyu/llama_index/tools/valyu/base.py | {
"start": 187,
"end": 14003
} | class ____(BaseToolSpec):
"""Valyu tool spec."""
spec_functions = [
"search",
"get_contents",
]
def __init__(
self,
api_key: str,
verbose: bool = False,
# Search API parameters
max_price: Optional[float] = 100,
relevance_threshold: float ... | ValyuToolSpec |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 68795,
"end": 69023
} | class ____(BaseModel):
"""
DAG Collection serializer for responses.
"""
dags: Annotated[list[DAGResponse], Field(title="Dags")]
total_entries: Annotated[int, Field(title="Total Entries")]
| DAGCollectionResponse |
python | getsentry__sentry | src/sentry/deletions/defaults/project.py | {
"start": 241,
"end": 5090
} | class ____(ModelDeletionTask[Project]):
def get_child_relations(self, instance: Project) -> list[BaseRelation]:
from sentry.discover.models import DiscoverSavedQueryProject
from sentry.incidents.models.alert_rule import AlertRule, AlertRuleProjects
from sentry.incidents.models.incident impor... | ProjectDeletionTask |
python | PrefectHQ__prefect | src/prefect/server/orchestration/rules.py | {
"start": 39932,
"end": 44390
} | class ____(
contextlib.AbstractAsyncContextManager[OrchestrationContext[T, RP]]
):
"""
An abstract base class used to implement privileged bookkeeping logic.
Warning:
In almost all cases, use the `BaseOrchestrationRule` base class instead.
Beyond the orchestration rules implemented with th... | BaseUniversalTransform |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 47001,
"end": 108769
} | class ____(TestCase):
sort_kinds = ["quicksort", "heapsort", "stable"]
@xpassIfTorchDynamo_np # (reason="all(..., where=...)")
def test_all_where(self):
a = np.array([[True, False, True], [False, False, False], [True, True, True]])
wh_full = np.array(
[[True, False, True], [Fal... | TestMethods |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/common.py | {
"start": 1249,
"end": 1671
} | class ____(BaseModel):
"""Base Node serializer for responses."""
id: str
label: str
type: Literal[
"join",
"task",
"asset-condition",
"asset",
"asset-alias",
"asset-name-ref",
"asset-uri-ref",
"dag",
"sensor",
"trigger",
... | BaseNodeResponse |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 136415,
"end": 138067
} | class ____(test_util.TensorFlowTestCase):
def setUpInputShapes(self, pre_add_input_shapes):
test_tensor_shape = [None, 1, 1, 1]
@def_function.function(input_signature=[
tensor_lib.TensorSpec(shape=test_tensor_shape, dtype=dtypes.float32)
])
def f(x):
return array_ops.identity(x, name=... | GraphDefInputShapesTest |
python | keon__algorithms | tests/test_queues.py | {
"start": 2722,
"end": 3189
} | class ____(unittest.TestCase):
"""Test suite for the PriorityQueue data structures.
"""
def test_PriorityQueue(self):
queue = PriorityQueue([3, 4, 1, 6])
self.assertEqual(4, queue.size())
self.assertEqual(1, queue.pop())
self.assertEqual(3, queue.size())
queue.push(2... | TestPriorityQueue |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/grid_finder.py | {
"start": 1591,
"end": 3748
} | class ____:
"""
A helper class to figure out the range of grid lines that need to be drawn.
"""
def __init__(self, nx, ny):
"""
Parameters
----------
nx, ny : int
The number of samples in each direction.
"""
self.nx = nx
self.ny = ny
... | ExtremeFinderSimple |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 158918,
"end": 159520
} | class ____(Operation):
def call(self, x):
return backend.numpy.nonzero(x)
def compute_output_spec(self, x):
return tuple(
[KerasTensor((None,), dtype="int32") for _ in range(len(x.shape))]
)
@keras_export(["keras.ops.nonzero", "keras.ops.numpy.nonzero"])
def nonzero(x):
... | Nonzero |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/yaml_utils/source_position.py | {
"start": 624,
"end": 6056
} | class ____(NamedTuple):
"""Represents a tree where every node has a SourcePosition."""
position: SourcePosition
children: Mapping[KeyPathSegment, "SourcePositionTree"]
def __hash__(self) -> int:
return hash((self.position, tuple(sorted(self.children.items()))))
def lookup(self, key_path: ... | SourcePositionTree |
python | readthedocs__readthedocs.org | readthedocs/api/v2/serializers.py | {
"start": 9900,
"end": 10229
} | class ____(BuildAdminSerializer):
"""
Build serializer to retrieve Build objects from the dashboard.
It uses `BuildCommandReadOnlySerializer` to automatically parse the command
and trim the useless path.
"""
commands = BuildCommandReadOnlySerializer(many=True, read_only=True)
| BuildAdminReadOnlySerializer |
python | Pylons__pyramid | tests/test_testing.py | {
"start": 16773,
"end": 18185
} | class ____(unittest.TestCase):
def _makeOne(self, name, factory):
from pyramid.testing import DummyRendererFactory
return DummyRendererFactory(name, factory)
def test_add_no_colon(self):
f = self._makeOne('name', None)
f.add('spec', 'renderer')
self.assertEqual(f.render... | TestDummyRendererFactory |
python | google__jax | jax/experimental/roofline/roofline.py | {
"start": 1494,
"end": 1846
} | class ____:
name_stack: source_info_util.NameStack
primitive: core.Primitive
avals_in: Sequence[core.AbstractValue]
avals_out: Sequence[core.AbstractValue]
jaxpr_eqn_ctx: core.JaxprEqnContext
mesh: Mesh | AbstractMesh | None
pin_lhs_in_vmem: bool
pin_rhs_in_vmem: bool
@dataclass(frozen=True, slots=Tru... | RooflineRuleContext |
python | jmcnamara__XlsxWriter | xlsxwriter/chart.py | {
"start": 661,
"end": 132067
} | class ____(xmlwriter.XMLwriter):
"""
A class for writing the Excel XLSX Chart file.
"""
###########################################################################
#
# Public API.
#
###########################################################################
def __init__(self) -> ... | Chart |
python | oauthlib__oauthlib | tests/oauth2/rfc6749/clients/test_backend_application.py | {
"start": 226,
"end": 3248
} | class ____(TestCase):
client_id = "someclientid"
client_secret = 'someclientsecret'
scope = ["/profile"]
kwargs = {
"some": "providers",
"require": "extra arguments"
}
body = "not=empty"
body_up = "not=empty&grant_type=client_credentials"
body_kwargs = body_up + "&some... | BackendApplicationClientTest |
python | huggingface__transformers | src/transformers/models/vits/modeling_vits.py | {
"start": 14256,
"end": 17587
} | class ____(torch.nn.Module):
def __init__(self, config: VitsConfig, num_layers: int):
super().__init__()
self.hidden_size = config.hidden_size
self.num_layers = num_layers
self.in_layers = torch.nn.ModuleList()
self.res_skip_layers = torch.nn.ModuleList()
self.dropou... | VitsWaveNet |
python | spack__spack | lib/spack/spack/test/llnl/util/filesystem.py | {
"start": 7356,
"end": 28263
} | class ____:
"""Tests for ``filesystem.install_tree``"""
def test_existing_dir(self, stage):
"""Test installing to an existing directory."""
with fs.working_dir(str(stage)):
fs.install_tree("source", "dest")
assert os.path.exists("dest/a/b/2")
check_added_ex... | TestInstallTree |
python | pytorch__pytorch | test/test_testing.py | {
"start": 18602,
"end": 22316
} | class ____(TestCase):
def test_trivial_passing_test(self, device):
x1 = torch.tensor([0., 1.], device=device)
x2 = torch.tensor([0., 1.], device='cpu')
self.assertEqual(x1, x2)
instantiate_device_type_tests(
TestEnvironmentVariable,
globals(),
)
if __name__ == '__main__':
run_... | TestEnvironmentVariable |
python | pytorch__pytorch | torch/testing/_internal/common_device_type.py | {
"start": 62719,
"end": 62830
} | class ____(dtypes):
def __init__(self, *args):
super().__init__(*args, device_type="xpu")
| dtypesIfXPU |
python | huggingface__transformers | src/transformers/models/hunyuan_v1_moe/modular_hunyuan_v1_moe.py | {
"start": 8190,
"end": 8428
} | class ____(LlamaForSequenceClassification):
pass
__all__ = [
"HunYuanMoEV1ForCausalLM",
"HunYuanMoEV1Model",
"HunYuanMoEV1PreTrainedModel",
"HunYuanMoEV1ForSequenceClassification",
]
| HunYuanMoEV1ForSequenceClassification |
python | wandb__wandb | wandb/automations/_generated/fragments.py | {
"start": 372,
"end": 526
} | class ____(GQLResult):
typename__: Typename[Literal["ArtifactPortfolio"]] = "ArtifactPortfolio"
id: GQLId
name: str
| ArtifactPortfolioScopeFields |
python | getsentry__sentry | src/sentry/organizations/services/organization/model.py | {
"start": 1156,
"end": 1773
} | class ____:
"""Helper functions to avoid importing sentry.models globally"""
@staticmethod
def get_default_team_status_value() -> int:
from sentry.models.team import TeamStatus
return TeamStatus.ACTIVE
@staticmethod
def get_default_invite_status_value() -> int:
from sentry... | _DefaultEnumHelpers |
python | apache__airflow | airflow-core/tests/unit/dag_processing/bundles/test_base.py | {
"start": 6216,
"end": 6458
} | class ____(BaseDagBundle):
@property
def path(self) -> Path:
assert self.version
return self.versions_dir / self.version
def get_current_version(self) -> str | None: ...
def refresh(self) -> None: ...
| FakeBundle |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_responses/profiles_response_builder.py | {
"start": 197,
"end": 409
} | class ____(HttpResponseBuilder):
@classmethod
def profiles_response(cls) -> "ProfilesResponseBuilder":
return cls(find_template("profiles", __file__), ListTemplatePath(), None)
| ProfilesResponseBuilder |
python | modin-project__modin | modin/experimental/core/storage_formats/pandas/parsers.py | {
"start": 1326,
"end": 3755
} | class ____(PandasCSVParser):
@staticmethod
@doc(
_doc_parse_func,
parameters="""chunks : list
List, where each element of the list is a list of tuples. The inner lists
of tuples contains the data file name of the chunk, chunk start offset, and
chunk end offsets for its corresponding ... | ExperimentalPandasCSVGlobParser |
python | doocs__leetcode | solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution.py | {
"start": 0,
"end": 311
} | class ____:
def removeSubfolders(self, folder: List[str]) -> List[str]:
folder.sort()
ans = [folder[0]]
for f in folder[1:]:
m, n = len(ans[-1]), len(f)
if m >= n or not (ans[-1] == f[:m] and f[m] == '/'):
ans.append(f)
return ans
| Solution |
python | django__django | django/utils/feedgenerator.py | {
"start": 3168,
"end": 8496
} | class ____:
"Base class for all syndication feeds. Subclasses should provide write()"
def __init__(
self,
title,
link,
description,
language=None,
author_email=None,
author_name=None,
author_link=None,
subtitle=None,
categories=Non... | SyndicationFeed |
python | tensorflow__tensorflow | tensorflow/core/function/polymorphism/function_cache_test.py | {
"start": 8153,
"end": 13577
} | class ____(test.Benchmark):
def benchmarkCacheHit50thKeyMiss(self):
# If there are 50 keys and we get a new key that the cache has no concrete
# functions for.
cache = function_cache.FunctionCache()
args_per_call = 5
num_total_checks = 50
keys = []
for i in range(num_total_checks):
... | FunctionCacheBenchmark |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.