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 | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/__init__.py | {
"start": 9969,
"end": 10488
} | class ____(NetworkTargetParser):
"""Composite argument parser for a network SSH target."""
@property
def option_name(self) -> str:
"""The option name used for this parser."""
return '--target-network'
@property
def allow_inventory(self) -> bool:
"""True if inventory is allo... | NetworkSshTargetParser |
python | gevent__gevent | src/greentest/3.11/test_subprocess.py | {
"start": 80531,
"end": 145863
} | class ____(BaseTestCase):
def setUp(self):
super().setUp()
self._nonexistent_dir = "/_this/pa.th/does/not/exist"
def _get_chdir_exception(self):
try:
os.chdir(self._nonexistent_dir)
except OSError as e:
# This avoids hard coding the errno value or the OS... | POSIXProcessTestCase |
python | encode__django-rest-framework | tests/test_request.py | {
"start": 5225,
"end": 5514
} | class ____(APIView):
authentication_classes = (SessionAuthentication,)
def post(self, request):
if request.POST.get('example') is not None:
return Response(status=status.HTTP_200_OK)
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
| MockView |
python | walkccc__LeetCode | solutions/1390. Four Divisors/1390.py | {
"start": 0,
"end": 417
} | class ____:
def sumFourDivisors(self, nums: list[int]) -> int:
ans = 0
for num in nums:
divisor = 0
for i in range(2, math.isqrt(num) + 1):
if num % i == 0:
if divisor == 0:
divisor = i
else:
divisor = 0
break
if divisor > 0 an... | Solution |
python | kamyu104__LeetCode-Solutions | Python/find-all-the-lonely-nodes.py | {
"start": 803,
"end": 1345
} | class ____(object):
def getLonelyNodes(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def dfs(node, result):
if not node:
return
if node.left and not node.right:
result.append(node.left.val)
elif... | Solution2 |
python | explosion__spaCy | spacy/lang/ga/__init__.py | {
"start": 350,
"end": 819
} | class ____(Language):
lang = "ga"
Defaults = IrishDefaults
@Irish.factory(
"lemmatizer",
assigns=["token.lemma"],
default_config={"model": None, "mode": "pos_lookup", "overwrite": False},
default_score_weights={"lemma_acc": 1.0},
)
def make_lemmatizer(
nlp: Language, model: Optional[Model]... | Irish |
python | sqlalchemy__sqlalchemy | test/sql/test_defaults.py | {
"start": 29300,
"end": 31604
} | class ____(fixtures.TestBase):
__requires__ = ("subqueries",)
__sparse_driver_backend__ = True
@testing.fixture
def table_fixture(self, metadata, connection):
def go(implicit_returning):
t2 = Table(
"t2",
metadata,
Column("nextid", Int... | PKDefaultTest |
python | plotly__plotly.py | plotly/graph_objs/histogram/marker/_pattern.py | {
"start": 233,
"end": 15300
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram.marker"
_path_str = "histogram.marker.pattern"
_valid_props = {
"bgcolor",
"bgcolorsrc",
"fgcolor",
"fgcolorsrc",
"fgopacity",
"fillmode",
"path",
"pathsrc",
"shape",
... | Pattern |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs_auto_attribs.py | {
"start": 1838,
"end": 1912
} | class ____:
a: str = 0
b = field()
c: int = foo()
d = list()
| C |
python | gevent__gevent | src/greentest/3.10/test_subprocess.py | {
"start": 140471,
"end": 150888
} | class ____(BaseTestCase):
def test_startupinfo(self):
# startupinfo argument
# We uses hardcoded constants, because we do not want to
# depend on win32all.
STARTF_USESHOWWINDOW = 1
SW_MAXIMIZE = 3
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = S... | Win32ProcessTestCase |
python | walkccc__LeetCode | solutions/1742. Maximum Number of Balls in a Box/1742.py | {
"start": 0,
"end": 421
} | class ____:
def countBalls(self, lowLimit: int, highLimit: int) -> int:
maxDigitSum = 9 * 5 # 99999
ans = 0
count = [0] * (maxDigitSum + 1)
for num in range(lowLimit, highLimit + 1):
digitSum = self._getDigitSum(num)
count[digitSum] += 1
ans = max(ans, count[digitSum])
return ... | Solution |
python | ansible__ansible | lib/ansible/plugins/loader.py | {
"start": 57707,
"end": 58222
} | class ____(PluginLoader):
"""Customized loader for cache plugins that wraps the requested plugin with an interposer that schema-qualifies keys and JSON encodes the values."""
def get(self, name: str, *args, **kwargs) -> BaseCacheModule:
plugin = super().get(name, *args, **kwargs)
if not plugin... | _CacheLoader |
python | kamyu104__LeetCode-Solutions | Python/check-if-all-the-integers-in-a-range-are-covered.py | {
"start": 662,
"end": 1035
} | class ____(object):
def isCovered(self, ranges, left, right):
"""
:type ranges: List[List[int]]
:type left: int
:type right: int
:rtype: bool
"""
ranges.sort()
for l, r in ranges:
if l <= left <= r:
left = r+1
return... | Solution2 |
python | Textualize__textual | src/textual/css/styles.py | {
"start": 44924,
"end": 51104
} | class ____(StylesBase):
"""Presents a combined view of two Styles object: a base Styles and inline Styles."""
def __init__(self, node: DOMNode, base: Styles, inline_styles: Styles) -> None:
self.node = node
self._base_styles = base
self._inline_styles = inline_styles
self._anima... | RenderStyles |
python | scrapy__scrapy | tests/test_utils_spider.py | {
"start": 164,
"end": 214
} | class ____(Spider):
name = "myspider1"
| MySpider1 |
python | django__django | django/db/models/functions/math.py | {
"start": 4416,
"end": 5040
} | class ____(NumericOutputFieldMixin, Func):
function = "RANDOM"
arity = 0
def as_mysql(self, compiler, connection, **extra_context):
return super().as_sql(compiler, connection, function="RAND", **extra_context)
def as_oracle(self, compiler, connection, **extra_context):
return super().a... | Random |
python | pytorch__pytorch | torch/_dynamo/bytecode_transformation.py | {
"start": 23502,
"end": 67371
} | class ____:
start: int
end: int
target: int
depth: int
lasti: bool
def encode_exception_table_varint(n: int) -> list[int]:
"""
Similar to `encode_varint`, but the 6-bit chunks are ordered in reverse.
"""
assert n >= 0
b = [n & 63]
n >>= 6
while n > 0:
b.append(n... | ExceptionTableEntry |
python | kamyu104__LeetCode-Solutions | Python/find-the-index-of-permutation.py | {
"start": 68,
"end": 1285
} | class ____(object):
def getPermutationIndex(self, perm):
"""
:type perm: List[int]
:rtype: int
"""
MOD = 10**9+7
class BIT(object): # 0-indexed.
def __init__(self, n):
self.__bit = [0]*(n+1) # Extra one for dummy node.
def ad... | Solution |
python | astropy__astropy | astropy/io/fits/hdu/streaming.py | {
"start": 322,
"end": 7586
} | class ____:
"""
A class that provides the capability to stream data to a FITS file
instead of requiring data to all be written at once.
The following pseudocode illustrates its use::
header = astropy.io.fits.Header()
for all the cards you need in the header:
header[key] = ... | StreamingHDU |
python | allegroai__clearml | clearml/hyperdatasets/management.py | {
"start": 321,
"end": 8319
} | class ____:
@classmethod
def get(
cls: Type[HD],
dataset_name: Optional[str] = None,
version_name: Optional[str] = None,
project_name: Optional[str] = None,
*,
dataset_id: Optional[str] = None,
version_id: Optional[str] = None,
) -> HD:
"""
... | HyperDatasetManagement |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/vector.py | {
"start": 2504,
"end": 5584
} | class ____:
"""Define the configuration for Oracle VECTOR Index.
See :ref:`oracle_vector_datatype` for background.
.. versionadded:: 2.0.41
:param index_type: Enum value from :class:`.VectorIndexType`
Specifies the indexing method. For HNSW, this must be
:attr:`.VectorIndexType.HNSW`.
... | VectorIndexConfig |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/models/test_anonymous_user.py | {
"start": 908,
"end": 1226
} | class ____:
def test_roles(self):
roles = ["role1"]
user = AnonymousUser()
user.roles = roles
assert user.roles == roles
def test_perms(self):
perms = {"perms1"}
user = AnonymousUser()
user._perms = perms
assert user.perms == perms
| TestAnonymousUser |
python | huggingface__transformers | src/transformers/models/informer/modular_informer.py | {
"start": 21781,
"end": 30676
} | class ____(TimeSeriesTransformerModel):
def __init__(self, config: InformerConfig):
PreTrainedModel.__init__(self, config)
if config.scaling == "mean" or config.scaling is True:
self.scaler = InformerMeanScaler(config)
elif config.scaling == "std":
self.scaler = Info... | InformerModel |
python | jina-ai__jina | jina/serve/monitoring.py | {
"start": 173,
"end": 1739
} | class ____(Summary):
"""
This is a small wrapper around prometheus Summary that allow to deprecate an old metrics by renaming it.
"""
def __init__(
self,
name: str,
documentation: str,
labelnames: Iterable[str] = (),
namespace: str = '',
subsystem: str = ... | _SummaryDeprecated |
python | ApeWorX__ape | src/ape/managers/converters.py | {
"start": 2454,
"end": 2705
} | class ____(ConverterAPI):
def is_convertible(self, value: Any) -> bool:
return isinstance(value, str) and not is_0x_prefixed(value) and value.isnumeric()
def convert(self, value: str) -> int:
return int(value)
| StringIntConverter |
python | pytorch__pytorch | torch/_functorch/autograd_function.py | {
"start": 23162,
"end": 27174
} | class ____(WrappedCtx):
_pt_reserved_attrs = (
"_pt_saved_tensors_bdims",
"_pt_current_level",
*WrappedCtx._pt_reserved_attrs,
)
def __init__(self, ctx, current_level):
super().__init__(ctx)
self._pt_saved_tensors_bdims = ()
self._pt_current_level = current_l... | CtxCustomSave |
python | justquick__django-activity-stream | actstream/feeds.py | {
"start": 581,
"end": 3999
} | class ____:
"""
Abstract base class for all stream rendering.
Supports hooks for fetching streams and formatting actions.
"""
def get_stream(self, *args, **kwargs):
"""
Returns a stream method to use.
"""
raise NotImplementedError
def get_object(self, *args, **k... | AbstractActivityStream |
python | ray-project__ray | rllib/utils/metrics/stats.py | {
"start": 427,
"end": 44884
} | class ____:
"""A container class holding a number of values and executing reductions over them.
The individual values in a Stats object may be of any type, for example python int
or float, numpy arrays, or more complex structured (tuple, dict) and are stored in
a list under `self.values`. This class is... | Stats |
python | pytorch__pytorch | torch/cuda/_sanitizer.py | {
"start": 17523,
"end": 19968
} | class ____:
def __init__(self) -> None:
self.dataptrs_read: set[DataPtr] = set()
self.dataptrs_written: set[DataPtr] = set()
self.tensor_aliases: dict[DataPtr, list[str]] = {}
self.outputs: set[DataPtr] = set()
def _handle_argument(
self,
value: Any,
is_w... | ArgumentHandler |
python | plotly__plotly.py | plotly/graph_objs/violin/box/_line.py | {
"start": 233,
"end": 2955
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "violin.box"
_path_str = "violin.box.line"
_valid_props = {"color", "width"}
@property
def color(self):
"""
Sets the inner box plot bounding line color.
The 'color' property is a color and may be specified as:
... | Line |
python | bokeh__bokeh | src/bokeh/document/events.py | {
"start": 4960,
"end": 5080
} | class ____:
def _session_callback_removed(self, event: SessionCallbackRemoved) -> None: ...
| SessionCallbackRemovedMixin |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/workspace/workspace.py | {
"start": 830,
"end": 1363
} | class ____:
origin: Annotated[
"CodeLocationOrigin",
ImportFrom("dagster._core.remote_origin"),
]
code_location: Optional[
Annotated[
"CodeLocation",
ImportFrom("dagster._core.remote_representation.code_location"),
]
]
load_error: Optional[Seri... | CodeLocationEntry |
python | mlflow__mlflow | mlflow/legacy_databricks_cli/configure/provider.py | {
"start": 14327,
"end": 16881
} | class ____:
def __init__(
self,
host,
username,
password,
token,
refresh_token=None,
insecure=None,
jobs_api_version=None,
client_id=None,
client_secret=None,
auth_type=None,
):
self.host = host
self.username... | DatabricksConfig |
python | doocs__leetcode | solution/1200-1299/1298.Maximum Candies You Can Get from Boxes/Solution.py | {
"start": 0,
"end": 1014
} | class ____:
def maxCandies(
self,
status: List[int],
candies: List[int],
keys: List[List[int]],
containedBoxes: List[List[int]],
initialBoxes: List[int],
) -> int:
q = deque()
has, took = set(initialBoxes), set()
ans = 0
for box in... | Solution |
python | bokeh__bokeh | src/bokeh/models/labeling.py | {
"start": 1520,
"end": 1750
} | class ____(Model):
""" Base class for labeling policies. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| LabelingPolicy |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 695016,
"end": 695552
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "base_ref_name", "created_at", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
base_ref_name = sgqlc.types.Field(String, graphql_name="ba... | BaseRefDeletedEvent |
python | spyder-ide__spyder | external-deps/spyder-kernels/spyder_kernels/comms/frontendcomm.py | {
"start": 990,
"end": 7474
} | class ____(CommBase):
"""Mixin to implement the spyder_shell_api."""
def __init__(self, kernel):
super(FrontendComm, self).__init__()
# Comms
self.kernel = kernel
self.kernel.comm_manager.register_target(
self._comm_name, self._comm_open)
self.comm_lock = th... | FrontendComm |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_audio.py | {
"start": 7625,
"end": 11005
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Opti... | Data2VecAudioAttention |
python | plotly__plotly.py | plotly/graph_objs/ohlc/hoverlabel/_font.py | {
"start": 233,
"end": 17128
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "ohlc.hoverlabel"
_path_str = "ohlc.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
... | Font |
python | fluentpython__example-code-2e | 11-pythonic-obj/vector2d_v3_prophash.py | {
"start": 1863,
"end": 3496
} | class ____:
typecode = 'd'
def __init__(self, x, y):
self.__x = float(x) # <1>
self.__y = float(y)
@property # <2>
def x(self): # <3>
return self.__x # <4>
@property # <5>
def y(self):
return self.__y
def __iter__(self):
return (i for i in (se... | Vector2d |
python | huggingface__transformers | src/transformers/models/bart/modeling_bart.py | {
"start": 70348,
"end": 70952
} | class ____(BartPreTrainedModel):
"""
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
used in combination with the [`EncoderDecoderModel`] framework.
"""
def __init__(self, config):
super().__init__(config)
self.decoder ... | BartDecoderWrapper |
python | numba__numba | numba/tests/test_random.py | {
"start": 61223,
"end": 63074
} | class ____(TestCase):
# Enough iterations for:
# 1. Mersenne-Twister state shuffles to occur (once every 624)
# 2. Race conditions to be plausible
# 3. Nice statistical properties to emerge
_extract_iterations = 100000
def setUp(self):
# Warm up, to avoid compiling in the threads
... | ConcurrencyBaseTest |
python | google__pytype | pytype/pytd/visitors.py | {
"start": 52645,
"end": 53898
} | class ____(Visitor):
"""Expand to Cartesian product of parameter types.
For example, this transforms
def f(x: Union[int, float], y: Union[int, float]) -> Union[str, unicode]
to
def f(x: int, y: int) -> Union[str, unicode]
def f(x: int, y: float) -> Union[str, unicode]
def f(x: float, y: int) -> U... | ExpandSignatures |
python | huggingface__transformers | src/transformers/models/llama4/modeling_llama4.py | {
"start": 3504,
"end": 4202
} | class ____(nn.Module):
def __init__(self, config, intermediate_size=None):
super().__init__()
if intermediate_size is None:
intermediate_size = config.intermediate_size
self.config = config
self.gate_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
... | Llama4TextMLP |
python | getsentry__sentry | src/sentry/backup/services/import_export/model.py | {
"start": 8253,
"end": 9091
} | class ____(RpcModel, Finding):
"""
A Pydantic and RPC friendly error container that also inherits from the base `Finding` class.
"""
is_err: Literal[True] = True
kind: RpcExportErrorKind = RpcExportErrorKind.Unknown
# Include fields from `Finding` in this `RpcModel` derivative.
on: Instanc... | RpcExportError |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_class_instantiated.py | {
"start": 1435,
"end": 1550
} | class ____(Structure):
@abc.abstractmethod
def length(self):
pass
__len__ = length
| AbstractSizable |
python | huggingface__transformers | src/transformers/trainer_utils.py | {
"start": 29723,
"end": 36806
} | class ____:
"""Wrap the data collator to remove unused columns before they are passed to the collator."""
def __init__(
self,
data_collator,
signature_columns,
logger=None,
model_name: str | None = None,
description: str | None = None,
):
self.data_co... | RemoveColumnsCollator |
python | chardet__chardet | chardet/jpcntx.py | {
"start": 26325,
"end": 27089
} | class ____(JapaneseContextAnalysis):
def get_order(self, byte_str: Union[bytes, bytearray]) -> Tuple[int, int]: # type: ignore[reportIncompatibleMethodOverride]
if not byte_str:
return -1, 1
# find out current char's byte length
first_char = byte_str[0]
if (first_char ==... | EUCJPContextAnalysis |
python | coleifer__peewee | tests/extra_fields.py | {
"start": 191,
"end": 267
} | class ____(TestModel):
key = TextField()
data = CompressedField()
| Comp |
python | milvus-io__pymilvus | pymilvus/exceptions.py | {
"start": 3548,
"end": 3629
} | class ____(MilvusException):
"""Raise when autoID is invalid"""
| AutoIDException |
python | kamyu104__LeetCode-Solutions | Python/kth-largest-sum-in-a-binary-tree.py | {
"start": 45,
"end": 158
} | class ____(object):
def __init__(self, val=0, left=None, right=None):
pass
# bfs, quick select
| TreeNode |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/class_as_data_structure.py | {
"start": 1115,
"end": 1257
} | class ____:
spam = "ham"
def __init__(self, foo:int, bar:list):
self.foo = foo
self.bar = bar
| NoWarningsClassAttributes |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_unittest.py | {
"start": 1588,
"end": 2336
} | class ____(unittest.TestCase):
@given(s=st.text())
@settings(deadline=None)
def test_subtest(self, s):
with self.subTest(text=s):
self.assertIsInstance(s, str)
if __name__ == "__main__":
unittest.main()
"""
@skipif_emscripten
@pytest.mark.parametrize("err", [[], ["-Werror"]])
def ... | MyTest |
python | huggingface__transformers | src/transformers/tokenization_python.py | {
"start": 10825,
"end": 15034
} | class ____(Trie):
def __init__(self, *args):
super().__init__(*args)
def extensions(self, prefix: str):
"""
Generates all extensions of a given prefix token in the Trie.
Example:
```python
>>> trie = Trie()
>>> trie.add("apple")
>>> trie.add("ap... | ExtensionsTrie |
python | Lightning-AI__lightning | src/lightning/fabric/utilities/types.py | {
"start": 2287,
"end": 2620
} | class ____(Steppable, Protocol):
"""To structurally type ``optimizer``"""
param_groups: list[dict[Any, Any]]
defaults: dict[Any, Any]
state: defaultdict[Tensor, Any]
def state_dict(self) -> dict[str, dict[Any, Any]]: ...
def load_state_dict(self, state_dict: dict[str, dict[Any, Any]]) -> None... | Optimizable |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/sqlite/aiosqlite.py | {
"start": 3873,
"end": 3960
} | class ____(AsyncAdapt_dbapi_ss_cursor):
__slots__ = ()
| AsyncAdapt_aiosqlite_ss_cursor |
python | scikit-learn__scikit-learn | sklearn/linear_model/_stochastic_gradient.py | {
"start": 31423,
"end": 50449
} | class ____(BaseSGDClassifier):
"""Linear classifiers (SVM, logistic regression, etc.) with SGD training.
This estimator implements regularized linear models with stochastic
gradient descent (SGD) learning: the gradient of the loss is estimated
each sample at a time and the model is updated along the wa... | SGDClassifier |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 207973,
"end": 212777
} | class ____:
def test_eq(self, backend):
sct = (
_load_cert(
os.path.join("x509", "badssl-sct.pem"),
x509.load_pem_x509_certificate,
)
.extensions.get_extension_for_class(
x509.PrecertificateSignedCertificateTimestamps
... | TestSignedCertificateTimestamps |
python | GoogleCloudPlatform__python-docs-samples | functions/v2/typed/greeting/main.py | {
"start": 997,
"end": 1355
} | class ____:
message: str
# Required to serialize the response
def to_dict(self) -> dict:
return {
"message": self.message,
}
@functions_framework.typed
def greeting(req: GreetingRequest):
return GreetingResponse(message=f"Hello {req.first_name} {req.last_name}!")
# [END ... | GreetingResponse |
python | numpy__numpy | numpy/_core/tests/test_unicode.py | {
"start": 8098,
"end": 8255
} | class ____(AssignValues):
"""Check the assignment of valued arrays (size 1, UCS2 values)"""
ulen = 1
ucs_value = ucs2_value
| TestAssignValues_1_UCS2 |
python | apache__airflow | providers/http/tests/unit/http/operators/test_http.py | {
"start": 1536,
"end": 14215
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="http_default", conn_type="http", host="test:8080/", extra='{"bearer": "test"}'
)
)
def test_respons... | TestHttpOperator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image05.py | {
"start": 315,
"end": 1041
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | fastapi__sqlmodel | docs_src/tutorial/offset_and_limit/tutorial003.py | {
"start": 100,
"end": 1628
} | 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)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_u... | Hero |
python | getsentry__sentry | src/sentry/identity/services/identity/model.py | {
"start": 1065,
"end": 1238
} | class ____(TypedDict, total=False):
id: int
user_id: int
identity_ext_id: str
provider_id: int
provider_ext_id: str
provider_type: str
| IdentityFilterArgs |
python | huggingface__transformers | tests/models/clip/test_modeling_clip.py | {
"start": 1751,
"end": 5781
} | class ____:
def __init__(
self,
parent,
batch_size=12,
image_size=30,
patch_size=2,
num_channels=3,
is_training=True,
hidden_size=32,
projection_dim=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
... | CLIPVisionModelTester |
python | facebook__pyre-check | scripts/setup.py | {
"start": 1203,
"end": 15729
} | class ____(Enum):
EXTERNAL = "external"
FACEBOOK = "facebook"
def _custom_linker_option(pyre_directory: Path, build_type: BuildType) -> str:
# HACK: This is a temporary workaround for inconsistent OS installations
# in FB-internal CI. Can be removed once all fleets are upgraded.
if build_type == B... | BuildType |
python | astropy__astropy | astropy/table/groups.py | {
"start": 10558,
"end": 13971
} | class ____(BaseGroups):
def __init__(self, parent_table, indices=None, keys=None):
self.parent_table = parent_table # parent Table
self._indices = indices
self._keys = keys
@property
def key_colnames(self):
"""
Return the names of columns in the parent table that we... | TableGroups |
python | google__pytype | pytype/imports/pickle_utils.py | {
"start": 1593,
"end": 5316
} | class ____(Exception):
"""Errors when loading a pickled pytd file."""
def __init__(self, filename: Path):
self.filename = os.fspath(filename)
msg = f"Error loading pickle file: {self.filename}"
super().__init__(msg)
Encoder = msgspec.msgpack.Encoder(order="deterministic")
AstDecoder = msgspec.msgpack... | LoadPickleError |
python | gevent__gevent | src/gevent/tests/test__api_timeout.py | {
"start": 1404,
"end": 1685
} | class ____(object):
update_now_calls = 0
def __init__(self, loop):
self.loop = loop
def __getattr__(self, name):
return getattr(self.loop, name)
def update_now(self):
self.update_now_calls += 1
self.loop.update_now()
| _UpdateNowProxy |
python | doocs__leetcode | solution/0300-0399/0393.UTF-8 Validation/Solution.py | {
"start": 0,
"end": 524
} | class ____:
def validUtf8(self, data: List[int]) -> bool:
cnt = 0
for v in data:
if cnt > 0:
if v >> 6 != 0b10:
return False
cnt -= 1
elif v >> 7 == 0:
cnt = 0
elif v >> 5 == 0b110:
... | Solution |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/sparse/csr_sparse_matrix_grad_test.py | {
"start": 1802,
"end": 6324
} | class ____(test.TestCase):
@classmethod
def setUpClass(cls):
super(CSRSparseMatrixGradTest, cls).setUpClass()
cls._gpu_available = test_util.is_gpu_available()
# TODO(penporn): Make these tests runnable on eager mode.
# (tf.gradients and gradient_checker only run in graph mode.)
@test_util.run_depre... | CSRSparseMatrixGradTest |
python | getsentry__sentry | tests/sentry/autofix/test_utils.py | {
"start": 4154,
"end": 9254
} | class ____(TestCase):
@patch("requests.post")
def test_get_autofix_state_success_with_group_id(self, mock_post: MagicMock) -> None:
# Setup mock response
mock_response = mock_post.return_value
mock_response.raise_for_status = lambda: None
mock_response.json.return_value = {
... | TestGetAutofixState |
python | dagster-io__dagster | python_modules/libraries/dagster-deltalake/dagster_deltalake/config.py | {
"start": 4451,
"end": 6545
} | class ____(Config):
"""Configuration for http client interacting with storage APIs."""
allow_http: Optional[bool] = None
"""Allow non-TLS, i.e. non-HTTPS connections"""
allow_invalid_certificates: Optional[bool] = None
"""Skip certificate validation on https connections.
## Warning
You s... | ClientConfig |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_size.py | {
"start": 5253,
"end": 5464
} | class ____(MaxExtent):
"""
Size whose absolute part is the largest height of the given *artist_list*.
"""
def __init__(self, artist_list):
super().__init__(artist_list, "height")
| MaxHeight |
python | fluentpython__example-code | 10-seq-hacking/vector_v5.py | {
"start": 4470,
"end": 7188
} | class ____:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('[')... | Vector |
python | ray-project__ray | python/ray/util/state/common.py | {
"start": 39870,
"end": 40600
} | class ____:
#: The name of this task group
name: str
#: A unique identifier for this group
key: str
#: The type of the class. Equivalent to protobuf TaskType,
#: "ACTOR" if it represents an Actor, or "GROUP" if it's a grouping of tasks.
type: str
#: Unix timestamp to use to sort the task... | NestedTaskSummary |
python | getsentry__sentry | src/sentry/notifications/platform/templates/sample.py | {
"start": 7519,
"end": 9408
} | class ____(NotificationTemplate[SlowLoadMetricAlertData]):
category = NotificationCategory.DEBUG
example_data = SlowLoadMetricAlertData(
alert_type="Slow Product Load",
severity="critical",
project_name="example-app",
measurement="5152.0 p50(measurements.lc)",
threshold="... | SlowLoadMetricAlertNotificationTemplate |
python | huggingface__transformers | src/transformers/models/qwen3_vl/modular_qwen3_vl.py | {
"start": 15204,
"end": 15594
} | class ____(Qwen2_5_VLVisionBlock):
def __init__(self, config, attn_implementation: str = "sdpa") -> None:
super().__init__()
self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6)
self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6)
self.attn = Qwen3VLVisionAttention(config=confi... | Qwen3VLVisionBlock |
python | google__jax | tests/pallas/tpu_pallas_memory_space_test.py | {
"start": 3773,
"end": 8280
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.is_device_tpu_at_least(5):
self.skipTest('Needs a newer TPU')
@parameterized.parameters(
(pltpu.VMEM, 1),
(pltpu.SMEM, 4),
(pltpu.HBM, 0),
(pltpu.ANY, None),
)
def test_basic_ref_memory_space_constra... | TPUCoreMapMemorySpaceTest |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_state.py | {
"start": 337,
"end": 3197
} | class ____(FSDPTestMultiThread):
@property
def world_size(self) -> int:
return 1
@skip_if_lt_x_gpu(1)
def test_fully_shard_state(self):
"""
Tests the ability to get the state object from a fully sharded module.
"""
num_mlps = 3
model = nn.Sequential(*[MLP... | TestFullyShardState |
python | django-haystack__django-haystack | test_haystack/core/models.py | {
"start": 228,
"end": 579
} | class ____(models.Model):
author = models.CharField(max_length=255)
foo = models.CharField(max_length=255, blank=True)
pub_date = models.DateTimeField(default=datetime.datetime.now)
tag = models.ForeignKey(MockTag, models.CASCADE)
def __str__(self):
return self.author
def hello(self):
... | MockModel |
python | celery__celery | t/unit/utils/test_saferepr.py | {
"start": 2045,
"end": 2135
} | class ____(frozenset):
def __repr__(self):
return super().__repr__()
| frozenset3 |
python | django__django | tests/requests_tests/tests.py | {
"start": 1138,
"end": 39706
} | class ____(SimpleTestCase):
def test_httprequest(self):
request = HttpRequest()
self.assertEqual(list(request.GET), [])
self.assertEqual(list(request.POST), [])
self.assertEqual(list(request.COOKIES), [])
self.assertEqual(list(request.META), [])
# .GET and .POST shou... | RequestsTests |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 23076,
"end": 23614
} | class ____:
"""A definition of a directed edge in the logical asset graph.
An upstream asset that's depended on, and the corresponding input name in the downstream asset
that depends on it.
"""
parent_asset_key: AssetKey
input_name: Optional[str] = None
output_name: Optional[str] = None
... | AssetParentEdgeSnap |
python | pyenv__pyenv | plugins/python-build/scripts/add_miniconda.py | {
"start": 4158,
"end": 6806
} | class ____(NamedTuple):
flavor: Flavor
suffix: Suffix
version_str: VersionStr
py_version: Optional[PyVersion]
@classmethod
def from_str(cls, s):
"""
Convert a string of the form "miniconda_n-ver" or "miniconda_n-py_ver-ver" to a :class:`CondaVersion` object.
"""
... | CondaVersion |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol53.py | {
"start": 1058,
"end": 1131
} | class ____(Proto_CoSelf):
def m(self) -> Self: ...
| Impl_CoSelfExplicit2 |
python | huggingface__transformers | src/transformers/models/vilt/modeling_vilt.py | {
"start": 1462,
"end": 2584
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Classification (or regression if config.num_labels==1) loss.
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
Classification (or regression if con... | ViltForImagesAndTextClassificationOutput |
python | getsentry__sentry | src/sentry/models/organization.py | {
"start": 2315,
"end": 3368
} | class ____(IntEnum):
ACTIVE = 0
PENDING_DELETION = 1
DELETION_IN_PROGRESS = 2
RELOCATION_PENDING_APPROVAL = 3
# alias for OrganizationStatus.ACTIVE
VISIBLE = 0
def __str__(self) -> str:
return self.name
@property
def label(self):
return OrganizationStatus_labels[se... | OrganizationStatus |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadCall6.py | {
"start": 2507,
"end": 2811
} | class ____(Generic[_T]):
@overload
def m1(self: "ClassA[int]") -> "ClassA[int]": ...
@overload
def m1(self: "ClassA[str]") -> "ClassA[str]": ...
def m1(self) -> "ClassA[Any]":
return self
def func7(a: ClassA[Any]):
reveal_type(a.m1(), expected_text="ClassA[int]")
| ClassA |
python | readthedocs__readthedocs.org | readthedocs/core/forms.py | {
"start": 2255,
"end": 2376
} | class ____(forms.ModelForm):
class Meta:
model = UserProfile
fields = ["allow_ads"]
| UserAdvertisingForm |
python | pytorch__pytorch | torch/utils/data/distributed.py | {
"start": 293,
"end": 6451
} | class ____(Sampler[_T_co]):
r"""Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with
:class:`torch.nn.parallel.DistributedDataParallel`. In such a case, each
process can pass a :class:`~torch.utils.data.DistributedSampler` instance as a
:class:... | DistributedSampler |
python | plotly__plotly.py | plotly/graph_objs/indicator/delta/_increasing.py | {
"start": 233,
"end": 3044
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "indicator.delta"
_path_str = "indicator.delta.increasing"
_valid_props = {"color", "symbol"}
@property
def color(self):
"""
Sets the color for increasing value.
The 'color' property is a color and may be specified as:... | Increasing |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 265827,
"end": 266102
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id",)
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| DeleteBranchProtectionRulePayload |
python | tensorflow__tensorflow | tensorflow/python/training/input_test.py | {
"start": 85855,
"end": 104649
} | class ____(test_lib.TestCase):
def _testTwoThreadsHelper(self, use_dict):
with ops.Graph().as_default(), self.cached_session():
# Two threads, the first generates (0..24, "a").
num_a = 25
zero64 = constant_op.constant(0, dtype=dtypes.int64)
examples = variables.Variable(zero64)
coun... | ShuffleBatchJoinTest |
python | apache__airflow | providers/google/tests/unit/google/marketing_platform/operators/test_campaign_manager.py | {
"start": 7424,
"end": 9082
} | class ____:
@mock.patch(
"airflow.providers.google.marketing_platform.operators.campaign_manager.GoogleCampaignManagerHook"
)
@mock.patch("airflow.providers.google.marketing_platform.operators.campaign_manager.BaseOperator")
def test_execute(self, mock_base_op, hook_mock):
report = {"rep... | TestGoogleCampaignManagerInsertReportOperator |
python | google__pytype | pytype/overlays/special_builtins.py | {
"start": 19334,
"end": 21054
} | class ____(BuiltinFunction):
"""For debugging. assert_type(x, t) asserts that the type of "x" is "t"."""
# Minimal signature, only used for constructing exceptions.
_SIGNATURE = function.Signature.from_param_names(
"assert_type", ("variable", "type")
)
_NAME = "assert_type"
def call(self, node, func... | AssertType |
python | rapidsai__cudf | python/cudf/cudf/core/column/numerical.py | {
"start": 1679,
"end": 40840
} | class ____(NumericalBaseColumn):
"""
A Column object for Numeric types.
Parameters
----------
data : Buffer
dtype : np.dtype
The dtype associated with the data Buffer
mask : Buffer, optional
"""
_VALID_BINARY_OPERATIONS = BinaryOperand._SUPPORTED_BINARY_OPERATIONS
_VALI... | NumericalColumn |
python | neetcode-gh__leetcode | python/0230-kth-smallest-element-in-a-bst.py | {
"start": 164,
"end": 534
} | class ____:
def kthSmallest(self, root: TreeNode, k: int) -> int:
stack = []
curr = root
while stack or curr:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
k -= 1
if k == 0:
... | Solution |
python | django__django | django/db/migrations/questioner.py | {
"start": 3478,
"end": 11902
} | class ____(MigrationQuestioner):
def __init__(
self, defaults=None, specified_apps=None, dry_run=None, prompt_output=None
):
super().__init__(
defaults=defaults, specified_apps=specified_apps, dry_run=dry_run
)
self.prompt_output = prompt_output or OutputWrapper(sys.s... | InteractiveMigrationQuestioner |
python | bottlepy__bottle | test/test_router.py | {
"start": 73,
"end": 6562
} | class ____(unittest.TestCase):
CGI = False
def setUp(self):
self.r = bottle.Router()
def add(self, path, target, method='GET', **ka):
with warnings.catch_warnings() as r:
warnings.simplefilter("ignore")
self.r.add(path, method, target, **ka)
def match(s... | TestRouter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.