language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | huggingface__transformers | src/transformers/models/cohere/modular_cohere.py | {
"start": 8659,
"end": 11669
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: CohereConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = CohereAttention(config=config, layer_idx=layer_idx)
self.mlp = CohereMLP(config)
self.input_layernorm = ... | CohereDecoderLayer |
python | astropy__astropy | astropy/utils/masked/core.py | {
"start": 14672,
"end": 17015
} | class ____(MaskedInfoBase, ParentDtypeInfo):
"""
Container for meta information like name, description, format.
"""
# Add `serialize_method` attribute to the attrs that MaskedNDArrayInfo knows
# about. This allows customization of the way that MaskedColumn objects
# get written to file dependi... | MaskedNDArrayInfo |
python | ipython__ipython | IPython/core/display.py | {
"start": 26743,
"end": 36323
} | class ____(DisplayObject):
_read_flags = "rb"
_FMT_JPEG = "jpeg"
_FMT_PNG = "png"
_FMT_GIF = "gif"
_FMT_WEBP = "webp"
_ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF, _FMT_WEBP]
_MIMETYPES = {
_FMT_PNG: "image/png",
_FMT_JPEG: "image/jpeg",
_FMT_GIF: "image/g... | Image |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_chartarea05.py | {
"start": 315,
"end": 1501
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_chartarea05.xlsx")
def test_create_file(self):
"""Test XlsxWriter chartarea properties."""
workbook = Workbook(self.got_file... | TestCompareXLSXFiles |
python | doocs__leetcode | solution/2400-2499/2449.Minimum Number of Operations to Make Arrays Similar/Solution.py | {
"start": 0,
"end": 242
} | class ____:
def makeSimilar(self, nums: List[int], target: List[int]) -> int:
nums.sort(key=lambda x: (x & 1, x))
target.sort(key=lambda x: (x & 1, x))
return sum(abs(a - b) for a, b in zip(nums, target)) // 4
| Solution |
python | Pylons__pyramid | tests/test_static.py | {
"start": 8888,
"end": 15671
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.static import static_view
return static_view
def _makeOne(self, *arg, **kw):
kw['use_subpath'] = True
return self._getTargetClass()(*arg, **kw)
def _makeRequest(self, kw=None):
from pyramid.requ... | Test_static_view_use_subpath_True |
python | great-expectations__great_expectations | versioneer.py | {
"start": 15899,
"end": 18888
} | class ____(Exception):
"""Exception raised if a method is not valid for the current scenario."""
# these dictionaries contain VCS-specific tools
LONG_VERSION_PY = {}
HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
d... | NotThisMethod |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py | {
"start": 3623,
"end": 4336
} | class ____:
"""Test AllEcsConfigKeys class."""
def test_all_config_keys_values(self):
"""Test that all config keys have correct values."""
# Test inherited keys
assert AllEcsConfigKeys.ASSIGN_PUBLIC_IP == "assign_public_ip"
assert AllEcsConfigKeys.CLUSTER == "cluster"
#... | TestAllEcsConfigKeys |
python | sphinx-doc__sphinx | tests/test_util/test_util_typing.py | {
"start": 1790,
"end": 1865
} | class ____:
__args__ = int
@dataclasses.dataclass(frozen=True)
| BrokenType |
python | getsentry__sentry | src/sentry/identity/services/identity/model.py | {
"start": 487,
"end": 1065
} | class ____(RpcModel):
id: int
idp_id: int # IdentityProvider id
user_id: int
external_id: str
data: dict[str, Any]
def get_identity(self) -> "Provider":
from sentry.identity import get
from sentry.identity.services.identity import identity_service
from sentry.users.mode... | RpcIdentity |
python | getsentry__sentry | src/sentry/users/services/usersocialauth/model.py | {
"start": 722,
"end": 838
} | class ____(TypedDict, total=False):
id: int
user_id: int
provider: str
uid: str
| UserSocialAuthFilterArgs |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/cloud_storage_transfer_service.py | {
"start": 2348,
"end": 4306
} | class ____:
"""Google Cloud Transfer operation status."""
IN_PROGRESS = "IN_PROGRESS"
PAUSED = "PAUSED"
SUCCESS = "SUCCESS"
FAILED = "FAILED"
ABORTED = "ABORTED"
# A list of keywords used to build a request or response
ACCESS_KEY_ID = "accessKeyId"
ALREADY_EXISTING_IN_SINK = "overwriteObjects... | GcpTransferOperationStatus |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 18044,
"end": 18143
} | class ____(BaseModel):
message: str = Field(..., description="Warning message")
| CollectionWarning |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 18495,
"end": 19438
} | class ____(ThreadSafeCleanupTestCase, SocketTestBase,
ThreadableTest):
"""Mixin to add client socket and allow client/server tests.
Client socket is self.cli and its address is self.cli_addr. See
ThreadableTest for usage information.
"""
def __init__(self, *args, **k... | ThreadedSocketTestMixin |
python | davidhalter__parso | parso/tree.py | {
"start": 15021,
"end": 15333
} | class ____(BaseNode):
"""Concrete implementation for interior nodes."""
__slots__ = ('type',)
def __init__(self, type, children):
super().__init__(children)
self.type = type
def __repr__(self):
return "%s(%s, %r)" % (self.__class__.__name__, self.type, self.children)
| Node |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/output/win32.py | {
"start": 2799,
"end": 17362
} | class ____(Output):
"""
I/O abstraction for rendering to Windows consoles.
(cmd.exe and similar.)
"""
def __init__(
self,
stdout: TextIO,
use_complete_width: bool = False,
default_color_depth: ColorDepth | None = None,
) -> None:
self.use_complete_width =... | Win32Output |
python | walkccc__LeetCode | solutions/129. Sum Root to Leaf Numbers/129.py | {
"start": 0,
"end": 406
} | class ____:
def sumNumbers(self, root: TreeNode | None) -> int:
ans = 0
def dfs(root: TreeNode | None, path: int) -> None:
nonlocal ans
if not root:
return
if not root.left and not root.right:
ans += path * 10 + root.val
return
dfs(root.left, path * 10 + root.... | Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/forms.py | {
"start": 6083,
"end": 6139
} | class ____(forms.BooleanField):
pass
| BroadBooleanField |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/scheduler.py | {
"start": 548,
"end": 778
} | class ____(
BaseModel,
extra="forbid",
json_schema_extra={
"allOf": create_json_schema_conditionals({SchedulerType.CUSTOM: "customScheduler"})
},
):
type: SchedulerType
config: SchedulerConfig
| Scheduler |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/inputs.py | {
"start": 4735,
"end": 5378
} | class ____(graphene.InputObjectType):
pipelineName = graphene.String()
jobName = graphene.String()
repositoryName = graphene.NonNull(graphene.String)
repositoryLocationName = graphene.NonNull(graphene.String)
solidSelection = graphene.List(graphene.NonNull(graphene.String))
assetSelection = grap... | GrapheneJobOrPipelineSelector |
python | pytorch__pytorch | test/test_indexing.py | {
"start": 919,
"end": 87998
} | class ____(TestCase):
def test_index(self, device):
def consec(size, start=1):
sequence = torch.ones(torch.tensor(size).prod(0)).cumsum(0)
sequence.add_(start - 1)
return sequence.view(*size)
reference = consec((3, 3, 3)).to(device)
# empty tensor indexi... | TestIndexing |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 3513,
"end": 3625
} | class ____(Variadic_TA[T_contra]): ...
Variadic_TA2 = Variadic[Unpack[tuple[int, T]]]
| VariadicChildContra_WithTA |
python | pypa__warehouse | warehouse/accounts/models.py | {
"start": 1695,
"end": 1854
} | class ____(enum.Enum):
CompromisedPassword = "password compromised"
AccountFrozen = "account frozen"
AdminInitiated = "admin initiated"
| DisableReason |
python | python__mypy | mypyc/ir/class_ir.py | {
"start": 3329,
"end": 22038
} | class ____:
"""Intermediate representation of a class.
This also describes the runtime structure of native instances.
"""
def __init__(
self,
name: str,
module_name: str,
is_trait: bool = False,
is_generated: bool = False,
is_abstract: bool = False,
... | ClassIR |
python | pandas-dev__pandas | pandas/tests/io/test_stata.py | {
"start": 1168,
"end": 100374
} | class ____:
def read_dta(self, file):
# Legacy default reader configuration
return read_stata(file, convert_dates=True)
def read_csv(self, file):
return read_csv(file, parse_dates=True)
@pytest.mark.parametrize("version", [114, 117, 118, 119, None])
def test_read_empty_dta(self... | TestStata |
python | vyperlang__vyper | vyper/warnings.py | {
"start": 1368,
"end": 1475
} | class ____(VyperWarning):
"""
Warn if past the EIP-170 size limit
"""
pass
| ContractSizeLimit |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_variable_command.py | {
"start": 3525,
"end": 23013
} | class ____:
@classmethod
def setup_class(cls):
cls.dagbag = models.DagBag(include_examples=True)
cls.parser = cli_parser.get_parser()
def setup_method(self):
clear_db_variables()
def teardown_method(self):
clear_db_variables()
def test_variables_set(self):
... | TestCliVariables |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 79895,
"end": 83256
} | class ____(Response):
"""
Response of projects.get_by_id endpoint.
:param project: Project info
:type project: Project
"""
_service = "projects"
_action = "get_by_id"
_version = "2.23"
_schema = {
"definitions": {
"project": {
"properties": {
... | GetByIdResponse |
python | gevent__gevent | src/gevent/events.py | {
"start": 8317,
"end": 8448
} | class ____(_AbstractMemoryEvent):
"""
Implementation of `IMemoryUsageThresholdExceeded`.
"""
| MemoryUsageThresholdExceeded |
python | uqfoundation__dill | dill/_dill.py | {
"start": 12415,
"end": 16407
} | class ____(StockPickler):
"""python's Pickler extended to interpreter sessions"""
dispatch: typing.Dict[type, typing.Callable[[Pickler, typing.Any], None]] \
= MetaCatchingDict(StockPickler.dispatch.copy())
"""The dispatch table, a dictionary of serializing functions used
by Pickler to save ... | Pickler |
python | pytorch__pytorch | torch/_inductor/runtime/hints.py | {
"start": 3193,
"end": 3394
} | class ____(Enum):
PERSISTENT_REDUCTION = auto()
POINTWISE = auto()
REDUCTION = auto()
SPLIT_SCAN = auto()
TEMPLATE = auto()
USER_AUTOTUNE = auto()
FIXED = auto()
| HeuristicType |
python | pandas-dev__pandas | pandas/tests/scalar/timestamp/test_constructors.py | {
"start": 7367,
"end": 11645
} | class ____:
def test_constructor_positional(self):
# see GH#10758
msg = "'NoneType' object cannot be interpreted as an integer"
with pytest.raises(TypeError, match=msg):
Timestamp(2000, 1)
msg = "month must be in 1..12"
with pytest.raises(ValueError, match=msg):
... | TestTimestampConstructorPositionalAndKeywordSupport |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 43306,
"end": 43658
} | class ____(Element):
proto: ToastProto = field(repr=False)
icon: str
def __init__(self, proto: ToastProto, root: ElementTree) -> None:
self.proto = proto
self.key = None
self.root = root
self.type = "toast"
@property
def value(self) -> str:
return self.proto... | Toast |
python | getsentry__sentry | tests/sentry/auth/test_access.py | {
"start": 2163,
"end": 3237
} | class ____(TestCase):
def from_user(self, *args, **kwds):
if SiloMode.get_current_mode() == SiloMode.MONOLITH:
return access.from_user(*args, **kwds)
return silo_from_user(*args, **kwds)
def from_request(self, *args, **kwds):
if SiloMode.get_current_mode() == SiloMode.MONOLI... | AccessFactoryTestCase |
python | jazzband__pip-tools | piptools/resolver.py | {
"start": 6258,
"end": 19485
} | class ____(BaseResolver):
"""
Wrapper for the (deprecated) legacy dependency resolver.
"""
def __init__(
self,
constraints: Iterable[InstallRequirement],
existing_constraints: dict[str, InstallRequirement],
repository: BaseRepository,
cache: DependencyCache,
... | LegacyResolver |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 91283,
"end": 91396
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING
| AutoModelForTextToWaveform |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol32.py | {
"start": 301,
"end": 392
} | class ____(Base1[Value], Protocol):
def method2(self, default: Value) -> Value: ...
| Base2 |
python | aio-libs__aiohttp | aiohttp/helpers.py | {
"start": 33257,
"end": 34647
} | class ____:
value: str
is_weak: bool = False
def validate_etag_value(value: str) -> None:
if value != ETAG_ANY and not _ETAGC_RE.fullmatch(value):
raise ValueError(
f"Value {value!r} is not a valid etag. Maybe it contains '\"'?"
)
def parse_http_date(date_str: str | None) -> ... | ETag |
python | spyder-ide__spyder | spyder/plugins/pylint/main_widget.py | {
"start": 2164,
"end": 2299
} | class ____:
Global = "global_section"
Section = "section_section"
History = "history_section"
| PylintWidgetOptionsMenuSections |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/expect_queried_table_row_count_to_be.py | {
"start": 948,
"end": 6760
} | class ____(QueryExpectation):
# </snippet>
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/expect_queried_table_row_count_to_be.py docstring">
"""Expect the expect the number of rows returned from a queried table to equal a specified value."""
# </snippet>
... | ExpectQueriedTableRowCountToBe |
python | huggingface__transformers | src/transformers/models/data2vec/modular_data2vec_audio.py | {
"start": 6352,
"end": 7524
} | class ____(Data2VecAudioPreTrainedModel, Wav2Vec2Model):
def __init__(self, config: Data2VecAudioConfig):
Data2VecAudioPreTrainedModel.__init__(self, config)
self.config = config
self.feature_extractor = Data2VecAudioFeatureEncoder(config)
self.feature_projection = Data2VecAudioFeatu... | Data2VecAudioModel |
python | django__django | tests/fixtures/tests.py | {
"start": 944,
"end": 1405
} | class ____(TestCase):
fixtures = ["fixture1.json", "fixture2.json"]
def test_class_fixtures(self):
"Test case has installed 3 fixture objects"
self.assertSequenceEqual(
Article.objects.values_list("headline", flat=True),
[
"Django conquers world!",
... | TestCaseFixtureLoadingTests |
python | pydantic__pydantic | tests/typechecking/misc.py | {
"start": 79,
"end": 567
} | class ____(BaseModel):
subs: list[Sub]
def func(model: Model) -> None:
model.model_dump(
include={'a': {1: True}},
)
model.model_dump(
include={'a': {'__all__': True}},
)
model.model_dump(
include={'a': {1: {'a'}}},
)
model.model_dump(
include={'a': {1, ... | Model |
python | run-llama__llama_index | llama-index-core/tests/storage/chat_store/test_sql_schema.py | {
"start": 252,
"end": 4362
} | class ____:
"""Test schema functionality in SQLAlchemyChatStore."""
def test_schema_parameter_initialization(self):
"""Test schema parameter initialization."""
# Without schema
store_no_schema = SQLAlchemyChatStore(
table_name="test_messages",
async_database_uri=... | TestSQLAlchemyChatStoreSchema |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_ismn.py | {
"start": 1842,
"end": 4481
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid ISMN (International Standard Music Number)."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_v... | ExpectColumnValuesToBeValidIsmn |
python | kennethreitz__tablib | src/tablib/core.py | {
"start": 2253,
"end": 23780
} | class ____:
"""The :class:`Dataset` object is the heart of Tablib. It provides all core
functionality.
Usually you create a :class:`Dataset` instance in your main module, and append
rows as you collect data. ::
data = tablib.Dataset()
data.headers = ('name', 'age')
for (name, ... | Dataset |
python | celery__celery | celery/apps/multi.py | {
"start": 3218,
"end": 8155
} | class ____:
"""Represents a node in a cluster."""
def __init__(self, name,
cmd=None, append=None, options=None, extra_args=None):
self.name = name
self.cmd = cmd or f"-m {celery_exe('worker', '--detach')}"
self.append = append
self.extra_args = extra_args or ''
... | Node |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/emitter.py | {
"start": 1485,
"end": 2856
} | class ____:
# replacement for the list based stack of None/int
def __init__(self):
# type: () -> None
self.values = [] # type: List[Tuple[Any, bool]]
def append(self, val, seq):
# type: (Any, Any) -> None
self.values.append((val, seq))
def pop(self):
# type: ()... | Indents |
python | tiangolo__fastapi | docs_src/security/tutorial003_an_py310.py | {
"start": 776,
"end": 914
} | class ____(BaseModel):
username: str
email: str | None = None
full_name: str | None = None
disabled: bool | None = None
| User |
python | sqlalchemy__sqlalchemy | test/ext/test_horizontal_shard.py | {
"start": 29916,
"end": 31497
} | class ____(fixtures.DeclarativeMappedTest):
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
data = Column(String(30))
deferred_data = deferred(Column(String... | RefreshDeferExpireTest |
python | scipy__scipy | scipy/signal/tests/test_windows.py | {
"start": 37536,
"end": 40879
} | class ____:
def test_basic(self, xp):
# Test against hardcoded data
for k, v in dpss_data.items():
win, ratios = windows.dpss(*k, return_ratios=True, xp=xp)
xp_assert_close(win, v[0], atol=1e-7, err_msg=k)
xp_assert_close(ratios, v[1], rtol=1e-5, atol=1e-7, err_m... | TestDPSS |
python | rq__rq | rq/repeat.py | {
"start": 287,
"end": 4303
} | class ____:
"""Defines repeat behavior for scheduled jobs.
Attributes:
times (int): The number of times to repeat the job. Must be greater than 0.
intervals (Union[int, List[int]]): The intervals between job executions in seconds.
Can be a single integer value or a list of intervals... | Repeat |
python | EpistasisLab__tpot | tpot/builtin_modules/arithmetictransformer.py | {
"start": 11483,
"end": 12152
} | class ____(TransformerMixin, BaseEstimator):
def __init__(self):
"""
A transformer that takes checks if all elements in a row are less than 0.
"""
pass
def fit(self, X, y=None):
return self
def transform(self, X):
transformed_X = np.array(self.transform_help... | LTTransformer |
python | kamyu104__LeetCode-Solutions | Python/longest-palindromic-subsequence-ii.py | {
"start": 31,
"end": 837
} | class ____(object):
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
dp = [[[0]*26 for _ in xrange(len(s))] for _ in xrange(2)]
for i in reversed(xrange(len(s))):
for j in xrange(i+1, len(s)):
if i == j-1:
... | Solution |
python | pypa__hatch | tests/backend/builders/hooks/test_version.py | {
"start": 6246,
"end": 8966
} | class ____:
def test_default(self, temp_dir, helpers):
config = {"path": "baz.py", "pattern": True}
metadata = ProjectMetadata(
str(temp_dir),
PluginManager(),
{
"project": {"name": "foo", "dynamic": ["version"]},
"tool": {"hatch": ... | TestPattern |
python | huggingface__transformers | src/transformers/models/ijepa/modular_ijepa.py | {
"start": 4462,
"end": 5541
} | class ____(IJepaPreTrainedModel, ViTModel):
def __init__(self, config: IJepaConfig, add_pooling_layer: bool = False, use_mask_token: bool = False):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
use_mask_token (`bool`, *optional*, de... | IJepaModel |
python | huggingface__transformers | src/transformers/models/reformer/modeling_reformer.py | {
"start": 80334,
"end": 90087
} | class ____(ReformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
assert self.config.num_hidden_layers > 0, (
"`config.attn_layers` is empty. Select at least one attn layer form ['lsh', 'local']"
)
self.embeddings = Re... | ReformerModel |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 15870,
"end": 15975
} | class ____(PydanticValueError):
msg_template = 'value is not a valid IPv4 interface'
| IPv4InterfaceError |
python | spack__spack | lib/spack/spack/cmd/style.py | {
"start": 17117,
"end": 28392
} | class ____(TokenBase):
"""Reconstructs the tokens for previous specs, so we can reuse code to rotate them"""
# Dependency
START_EDGE_PROPERTIES = r"(?:\^\[)"
END_EDGE_PROPERTIES = r"(?:\])"
DEPENDENCY = r"(?:\^)"
# Version
VERSION_HASH_PAIR = SpecTokens.VERSION_HASH_PAIR.regex
GIT_VERSI... | _LegacySpecTokens |
python | sqlalchemy__sqlalchemy | examples/vertical/dictlike.py | {
"start": 1765,
"end": 5093
} | class ____:
"""Adds obj[key] access to a mapped class.
This class basically proxies dictionary access to an attribute
called ``_proxied``. The class which inherits this class
should have an attribute called ``_proxied`` which points to a dictionary.
"""
def __len__(self):
return len(... | ProxiedDictMixin |
python | weaviate__weaviate-python-client | weaviate/collections/batch/client.py | {
"start": 8019,
"end": 13742
} | class ____(_BatchWrapper):
def __init__(
self,
connection: ConnectionSync,
config: "_Collections",
consistency_level: Optional[ConsistencyLevel],
):
super().__init__(connection, consistency_level)
self.__config = config
self._vectorizer_batching: Optional[... | _BatchClientWrapper |
python | allegroai__clearml | examples/frameworks/pytorch/pytorch_mnist.py | {
"start": 334,
"end": 5610
} | class ____(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5, 1)
self.conv2 = nn.Conv2d(20, 50, 5, 1)
self.fc1 = nn.Linear(4 * 4 * 50, 500)
self.fc2 = nn.Linear(500, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
... | Net |
python | justquick__django-activity-stream | actstream/drf/views.py | {
"start": 7118,
"end": 10574
} | class ____(DefaultModelViewSet):
queryset = models.Follow.objects.order_by('-started', '-id').prefetch_related()
serializer_class = serializers.FollowSerializer
permission_classes = [permissions.IsAuthenticated]
@action(detail=False, permission_classes=[permissions.IsAuthenticated], methods=['POST'])
... | FollowViewSet |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_managers.py | {
"start": 8133,
"end": 10761
} | class ____(TestBuildManagerBase):
"""
Queries using External Manager should only include External Version builds.
It will only include pull/merge request Version builds in the queries.
"""
def test_all(self):
query = Build.external.all()
external_builds = {
self.build_... | TestExternalBuildManager |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper_fxir.py | {
"start": 2800,
"end": 3910
} | class ____:
"""
Stores metadata about Triton kernels for use in FX.
"""
tuner: CachingAutotuner
wrapped: TraceableTritonKernelWrapper
def replace_floor_div(expr: sympy.Expr) -> sympy.Expr:
"""
Replace sympy.floor with FloorDiv.
"""
def replace(expr: sympy.Expr) -> sympy.Expr:
... | TritonKernel |
python | wandb__wandb | wandb/errors/errors.py | {
"start": 782,
"end": 889
} | class ____(UsageError):
"""Raised when trying to use a feature that is not supported."""
| UnsupportedError |
python | tensorflow__tensorflow | tensorflow/core/function/transform/transform_test.py | {
"start": 1904,
"end": 2398
} | class ____(module_lib.Module):
@def_function.function
def f(self, x, y, add_2):
r = math_ops.add(x, y, name="x_plus_y")
if add_2:
return r + 2
else:
return r
def apply_transform(f, transform_fn):
"""Wrapper to apply a transformation on every traced tf.function."""
@def_function.funct... | Model |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/trivial_install_test_package/package.py | {
"start": 216,
"end": 686
} | class ____(Package):
"""This package is a stub with a trivial install method. It allows us
to test the install and uninstall logic of spack."""
homepage = "http://www.example.com/trivial_install"
url = "http://www.unit-test-should-replace-this-url/trivial_install-1.0.tar.gz"
version("1.0", md5="0... | TrivialInstallTestPackage |
python | huggingface__transformers | src/transformers/models/convnextv2/modeling_convnextv2.py | {
"start": 7743,
"end": 9327
} | class ____(nn.Module):
"""ConvNeXTV2 stage, consisting of an optional downsampling layer + multiple residual blocks.
Args:
config ([`ConvNextV2Config`]): Model configuration class.
in_channels (`int`): Number of input channels.
out_channels (`int`): Number of output channels.
de... | ConvNextV2Stage |
python | vyperlang__vyper | vyper/semantics/types/function.py | {
"start": 1363,
"end": 1434
} | class ____(_FunctionArg):
pass
@dataclass(kw_only=True)
| PositionalArg |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/lambda15.py | {
"start": 279,
"end": 519
} | class ____:
def __new__(cls, *args: Any, **kwargs: Any) -> "ClassA":
return super().__new__(*args, **kwargs)
def __init__(self, x: Callable[[float], float]) -> None:
self.x = x
ClassA(lambda r: identity(r) + 1)
| ClassA |
python | modin-project__modin | modin/core/dataframe/pandas/metadata/dtypes.py | {
"start": 38609,
"end": 44586
} | class ____(pandas.CategoricalDtype):
"""
A lazy proxy representing ``pandas.CategoricalDtype``.
Parameters
----------
categories : list-like, optional
ordered : bool, default: False
Notes
-----
Important note! One shouldn't use the class' constructor to instantiate a proxy instance... | LazyProxyCategoricalDtype |
python | pypa__warehouse | tests/unit/manage/test_forms.py | {
"start": 25107,
"end": 27719
} | class ____:
def test_validate(self):
macaroon_service = pretend.stub(
find_macaroon=pretend.call_recorder(lambda id: pretend.stub())
)
request = pretend.stub()
user_service = pretend.stub(
find_userid=lambda *a, **kw: 1, check_password=lambda *a, **kw: True
... | TestDeleteMacaroonForm |
python | huggingface__transformers | tests/utils/test_import_structure.py | {
"start": 1213,
"end": 9716
} | class ____(unittest.TestCase):
base_transformers_path = Path(__file__).parent.parent.parent
models_path = base_transformers_path / "src" / "transformers" / "models"
models_import_structure = spread_import_structure(define_import_structure(models_path))
def test_definition(self):
import_structur... | TestImportStructures |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 8475,
"end": 8542
} | class ____(HTTPClientError):
status_code = 411
| HTTPLengthRequired |
python | redis__redis-py | tests/test_asyncio/test_connection_pool.py | {
"start": 23410,
"end": 28215
} | class ____:
async def test_on_connect_error(self):
"""
An error in Connection.on_connect should disconnect from the server
see for details: https://github.com/andymccurdy/redis-py/issues/368
"""
# this assumes the Redis server being tested against doesn't have
# 9999 ... | TestConnection |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/llm.py | {
"start": 2243,
"end": 2759
} | class ____(BaseEvent):
"""
LLMCompletionStartEvent.
Args:
prompt (str): The prompt to be completed.
additional_kwargs (dict): Additional keyword arguments.
model_dict (dict): Model dictionary.
"""
model_config = ConfigDict(protected_namespaces=("pydantic_model_",))
pro... | LLMCompletionStartEvent |
python | getsentry__sentry | tests/sentry/test_no_create_or_update_usage.py | {
"start": 2013,
"end": 5954
} | class ____(ast.NodeVisitor):
def __init__(self, module_qualname: str) -> None:
self.module_qualname = module_qualname
self.context_stack: list[str] = []
self.usages: list[Usage] = []
def visit_ClassDef(self, node: ast.ClassDef) -> Any:
self.context_stack.append(node.name)
... | CreateOrUpdateVisitor |
python | ansible__ansible | test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/deprecation.py | {
"start": 156,
"end": 331
} | class ____(object):
DOCUMENTATION = r"""
options: {}
deprecated:
alternative: Use some other module
why: Test deprecation
removed_in: '3.0.0'
"""
| ModuleDocFragment |
python | mkdocs__mkdocs | mkdocs/tests/livereload_tests.py | {
"start": 271,
"end": 1841
} | class ____:
def __init__(self, content):
self.in_file = io.BytesIO(content.encode())
self.out_file = io.BytesIO()
self.out_file.close = lambda: None
def makefile(self, *args, **kwargs):
return self.in_file
def sendall(self, data):
self.out_file.write(data)
@contex... | FakeRequest |
python | huggingface__transformers | tests/models/phimoe/test_modeling_phimoe.py | {
"start": 2856,
"end": 2987
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = PhimoeModel
@require_torch
| PhimoeModelTester |
python | PyCQA__pycodestyle | tests/test_E901.py | {
"start": 137,
"end": 913
} | class ____(unittest.TestCase):
def test_closing_brace(self):
errors = errors_from_src('}\n')
if sys.version_info < (3, 12): # pragma: <3.12 cover
self.assertEqual(errors, ['E901:2:1'])
else: # pragma: >=3.12 cover
self.assertEqual(errors, [])
def test_unclosed_... | E901Test |
python | pytorch__pytorch | torch/_inductor/runtime/triton_heuristics.py | {
"start": 1790,
"end": 2062
} | class ____(Config):
"""Inductor-specific Triton config with additional control flags"""
def __init__(self, *args, dynamic_scale_rblock=True, **kwargs):
super().__init__(*args, **kwargs)
self.dynamic_scale_rblock = dynamic_scale_rblock
| InductorConfig |
python | kubernetes-client__python | kubernetes/client/models/v1_certificate_signing_request.py | {
"start": 383,
"end": 7800
} | 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... | V1CertificateSigningRequest |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/debug_graphs_test.py | {
"start": 1360,
"end": 1880
} | class ____(test_util.TensorFlowTestCase):
def testParseTensorNameInputWorks(self):
self.assertEqual("a", debug_graphs.get_node_name("a:0"))
self.assertEqual(0, debug_graphs.get_output_slot("a:0"))
self.assertEqual("_b", debug_graphs.get_node_name("_b:1"))
self.assertEqual(1, debug_graphs.get_output_... | GetNodeNameAndOutputSlotTest |
python | numba__llvmlite | llvmlite/tests/test_binding.py | {
"start": 84605,
"end": 84866
} | class ____(BaseTest):
def test_inlineasm(self):
llvm.initialize_native_asmparser()
m = self.module(asm=asm_inlineasm)
tm = self.target_machine(jit=False)
asm = tm.emit_assembly(m)
self.assertIn('nop', asm)
| TestInlineAsm |
python | pola-rs__polars | py-polars/src/polars/interchange/protocol.py | {
"start": 3311,
"end": 3805
} | class ____(Protocol):
"""Interchange buffer object."""
@property
def bufsize(self) -> int:
"""Buffer size in bytes."""
@property
def ptr(self) -> int:
"""Pointer to start of the buffer as an integer."""
def __dlpack__(self) -> Any:
"""Represent this structure as DLPack... | Buffer |
python | pytorch__pytorch | torch/ao/quantization/fx/custom_config.py | {
"start": 1454,
"end": 15949
} | class ____:
"""
Custom configuration for :func:`~torch.ao.quantization.quantize_fx.prepare_fx` and
:func:`~torch.ao.quantization.quantize_fx.prepare_qat_fx`.
Example usage::
prepare_custom_config = PrepareCustomConfig() \
.set_standalone_module_name("module1", qconfig_mapping, exam... | PrepareCustomConfig |
python | charliermarsh__ruff | crates/ruff_benchmark/resources/pydantic/types.py | {
"start": 9488,
"end": 12475
} | class ____:
path_type: Literal['file', 'dir', 'new']
def __pydantic_modify_json_schema__(self, field_schema: dict[str, Any]) -> None:
format_conversion = {'file': 'file-path', 'dir': 'directory-path'}
field_schema.update(format=format_conversion.get(self.path_type, 'path'), type='string')
... | PathType |
python | apache__airflow | providers/trino/src/airflow/providers/trino/hooks/trino.py | {
"start": 2678,
"end": 2986
} | class ____(Exception):
"""Trino exception."""
def _boolify(value):
if isinstance(value, bool):
return value
if isinstance(value, str):
if value.lower() == "false":
return False
if value.lower() == "true":
return True
return value
| TrinoException |
python | huggingface__transformers | src/transformers/models/emu3/modeling_emu3.py | {
"start": 15305,
"end": 16318
} | class ____(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
):
super().__init__()
self.norm_layer = nn.GroupNorm(
num_channels=out_channels,
num_groups=32,
eps=1e-6,
affine=True,
)
self.c... | Emu3VQVAESpatialNorm |
python | modin-project__modin | modin/tests/config/docs_module/classes.py | {
"start": 911,
"end": 1031
} | class ____:
def isna(self):
"""This is a test of the documentation module for Series."""
return
| Series |
python | allegroai__clearml | clearml/hyperdatasets/data_entry_image.py | {
"start": 19498,
"end": 31936
} | class ____(DataEntry):
def __init__(
self,
data_entry_id: Optional[str] = None,
metadata: Optional[dict] = None,
) -> None:
super(DataEntryImage, self).__init__(data_entry_id=data_entry_id, metadata=metadata)
# optional global annotations storage for the entry level
... | DataEntryImage |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-asana/source_asana/config_migration.py | {
"start": 419,
"end": 3046
} | class ____:
"""
This class stands for migrating the config at runtime,
while providing the backward compatibility when falling back to the previous source version.
"""
message_repository: MessageRepository = InMemoryMessageRepository()
@classmethod
def should_migrate(cls, config: Mapping[s... | AsanaConfigMigration |
python | celery__celery | celery/backends/rpc.py | {
"start": 778,
"end": 942
} | class ____(Exception):
"""Too much state history to fast-forward."""
def _on_after_fork_cleanup_backend(backend):
backend._after_fork()
| BacklogLimitExceeded |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_to_be_nonempty_geometries.py | {
"start": 992,
"end": 1696
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.nonempty_geometries"
condition_value_keys = ()
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=Panda... | ColumnValuesNonemptyGeometries |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 207863,
"end": 208067
} | class ____(InMemoryNetCDFWithGroups):
engine: T_NetcdfEngine = "h5netcdf"
@requires_h5netcdf
@requires_dask
@pytest.mark.filterwarnings("ignore:deallocating CachingFileManager")
| TestH5NetCDFInMemoryData |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_django/DJ001.py | {
"start": 2391,
"end": 2682
} | class ____(models.Model):
charfield: models.CharField = models.CharField(max_length=255, null=True)
textfield: models.TextField = models.TextField(max_length=255, null=True)
slugfield: models.SlugField = models.SlugField(max_length=255, null=True)
| IncorrectModelWithSimpleAnnotations |
python | pytorch__pytorch | test/test_fake_tensor.py | {
"start": 48891,
"end": 60788
} | class ____(TestCase):
def get_aten_op(self, schema):
namespace, name = schema.name.split("::")
overload = schema.overload_name if schema.overload_name else "default"
assert namespace == "aten"
return getattr(getattr(torch.ops.aten, name), overload)
def get_all_aten_schemas(self)... | FakeTensorOperatorInvariants |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/index1.py | {
"start": 1898,
"end": 1983
} | class ____:
def __call__(self, *args, **kwargs) -> Self:
return self
| ClassH |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.