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 | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 7577,
"end": 7722
} | class ____(TrigRule):
"""integrate(sec(x)**2, x) -> tan(x)"""
def eval(self) -> Expr:
return tan(self.variable)
@dataclass
| Sec2Rule |
python | davidhalter__jedi | test/completion/descriptors.py | {
"start": 915,
"end": 1148
} | class ____():
@property
def r(self):
return 1
@r.setter
def r(self, value):
return ''
def t(self):
return ''
p = property(t)
#? []
B().r().
#? int()
B().r
#? str()
B().p
#? []
B().p().
| B |
python | PyCQA__pylint | pylint/checkers/spelling.py | {
"start": 3316,
"end": 3624
} | class ____(RegExFilter):
r"""Filter skipping over camelCasedWords.
This filter skips any words matching the following regular expression:
^([a-z]\w+[A-Z]+\w+)
That is, any words that are camelCasedWords.
"""
_pattern = re.compile(r"^([a-z]+(\d|[A-Z])(?:\w+)?)")
| CamelCasedWord |
python | sqlalchemy__sqlalchemy | examples/versioned_rows/versioned_map.py | {
"start": 6674,
"end": 9194
} | class ____(Base):
"""Represent an individual key/value pair at a given point in time.
ConfigValue is immutable.
"""
__tablename__ = "config_value"
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
originating_config_id = Column(
Integer, ForeignKey(... | ConfigValue |
python | wandb__wandb | wandb/sdk/artifacts/_generated/delete_registry_members.py | {
"start": 272,
"end": 376
} | class ____(GQLResult):
success: bool
DeleteRegistryMembers.model_rebuild()
| DeleteRegistryMembersResult |
python | pyinstaller__pyinstaller | tests/functional/specs/several-scripts/main-script1.py | {
"start": 44,
"end": 366
} | class ____(basemod.Popen):
def __init__(self, *args, **kw):
print(inspect.getfile(self.__init__))
print(inspect.getfile(super().__init__))
super().__init__(*args, **kw)
# Reduce recursion limit to shorten the traceback.
sys.setrecursionlimit(50)
basemod.Popen = _Popen
p = basemod.Popen()
| _Popen |
python | kamyu104__LeetCode-Solutions | Python/count-vowels-permutation.py | {
"start": 51,
"end": 955
} | class ____(object):
def countVowelPermutation(self, n):
"""
:type n: int
:rtype: int
"""
def matrix_expo(A, K):
result = [[int(i==j) for j in xrange(len(A))] \
for i in xrange(len(A))]
while K:
if K % 2:
... | Solution |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 52506,
"end": 58003
} | class ____(TypedDict, total=False):
type: Required[Literal['list']]
items_schema: CoreSchema
min_length: int
max_length: int
fail_fast: bool
strict: bool
ref: str
metadata: dict[str, Any]
serialization: IncExSeqOrElseSerSchema
def list_schema(
items_schema: CoreSchema | None = ... | ListSchema |
python | MongoEngine__mongoengine | tests/all_warnings/test_warnings.py | {
"start": 273,
"end": 1214
} | class ____(unittest.TestCase):
def setUp(self):
connect(db="mongoenginetest")
self.warning_list = []
self.showwarning_default = warnings.showwarning
warnings.showwarning = self.append_to_warning_list
def append_to_warning_list(self, message, category, *args):
self.warnin... | TestAllWarnings |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 23403,
"end": 23695
} | class ____(BlasNotFoundError):
"""
Blas (http://www.netlib.org/blas/) sources not found.
Directories to search for the sources can be specified in the
numpy/distutils/site.cfg file (section [blas_src]) or by setting
the BLAS_SRC environment variable."""
| BlasSrcNotFoundError |
python | django__django | django/template/smartif.py | {
"start": 4551,
"end": 6426
} | class ____:
error_class = ValueError
def __init__(self, tokens):
# Turn 'is','not' and 'not','in' into single tokens.
num_tokens = len(tokens)
mapped_tokens = []
i = 0
while i < num_tokens:
token = tokens[i]
if token == "is" and i + 1 < num_tokens... | IfParser |
python | h5py__h5py | h5py/tests/test_dataset_getitem.py | {
"start": 4955,
"end": 7245
} | class ____(TestCase):
def setUp(self):
TestCase.setUp(self)
self.data = np.array((42.5, -118, "Hello"), dtype=[('a', 'f'), ('b', 'i'), ('c', '|S10')])
self.dset = self.f.create_dataset('x', data=self.data)
def test_ndim(self):
""" Verify number of dimensions """
self.as... | TestScalarCompound |
python | getsentry__sentry | src/sentry/issues/issue_occurrence.py | {
"start": 573,
"end": 1222
} | class ____(TypedDict):
id: str
project_id: int
event_id: str
fingerprint: Sequence[str]
issue_title: str
subtitle: str
resource_id: str | None
evidence_data: Mapping[str, Any]
evidence_display: Sequence[IssueEvidenceData]
type: int
detection_time: float
level: str | None
... | IssueOccurrenceData |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_embed_image13.py | {
"start": 315,
"end": 1477
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("embed_image13.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Wo... | TestCompareXLSXFiles |
python | ray-project__ray | python/ray/dag/tests/experimental/test_torch_tensor_transport.py | {
"start": 11872,
"end": 14598
} | class ____:
"""Tests worker to worker tensor transport with CPU device."""
def test_src_cpu_tensor_dst_cpu_node(self, ray_start_regular):
sender = Actor.remote()
receiver = Actor.remote()
ref = run_worker_to_worker_dag(sender, receiver, "cpu", "cpu")
assert ray.get(ref) == "cpu"... | TestWorkerToWorkerDeviceCPU |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink28.py | {
"start": 315,
"end": 1670
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink28.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Wor... | TestCompareXLSXFiles |
python | python-openxml__python-docx | tests/oxml/test__init__.py | {
"start": 282,
"end": 1195
} | class ____:
def it_returns_an_lxml_element_with_matching_tag_name(self):
element = OxmlElement("a:foo")
assert isinstance(element, etree._Element)
assert element.tag == ("{http://schemas.openxmlformats.org/drawingml/2006/main}foo")
def it_adds_supplied_attributes(self):
element ... | DescribeOxmlElement |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 36544,
"end": 37068
} | class ____(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server, while acting as a gateway or proxy,
did not receive a timely response from the upstream server specified
by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server
(e.g. DNS) it needed t... | HTTPGatewayTimeout |
python | django__django | tests/backends/test_ddl_references.py | {
"start": 3035,
"end": 3774
} | class ____(ColumnsTests):
def setUp(self):
def create_index_name(table_name, column_names, suffix):
return ", ".join(
"%s_%s_%s" % (table_name, column_name, suffix)
for column_name in column_names
)
self.reference = IndexName(
"tab... | IndexNameTests |
python | dask__distributed | distributed/comm/tcp.py | {
"start": 4873,
"end": 14755
} | class ____(Comm):
"""
An established communication based on an underlying Tornado IOStream.
"""
max_shard_size: ClassVar[int] = dask.utils.parse_bytes(
dask.config.get("distributed.comm.shard")
)
stream: IOStream | None
def __init__(
self,
stream: IOStream,
... | TCP |
python | tensorflow__tensorflow | tensorflow/python/util/nest_test.py | {
"start": 1935,
"end": 2146
} | class ____(collections.abc.Sequence):
def __len__(self):
return 1
def __getitem__(self, item):
raise ValueError("Cannot get item: %s" % item)
@dataclasses.dataclass
| _CustomSequenceThatRaisesException |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/vector/vectorize_reward.py | {
"start": 3094,
"end": 4304
} | class ____(VectorizeTransformReward):
"""A wrapper that clips the rewards for an environment between an upper and lower bound.
Example with clipped rewards:
>>> import numpy as np
>>> import gymnasium as gym
>>> envs = gym.make_vec("MountainCarContinuous-v0", num_envs=3)
>>> env... | ClipReward |
python | PyCQA__pylint | doc/data/messages/a/access-member-before-definition/bad.py | {
"start": 0,
"end": 243
} | class ____:
def __init__(self, fluffiness_level):
if self.fluffiness_level > 9000: # [access-member-before-definition]
print("It's OVER-FLUFFYYYY ! *crush glasses*")
self.fluffiness_level = fluffiness_level
| Unicorn |
python | numba__numba | numba/pycc/cc.py | {
"start": 9463,
"end": 10626
} | class ____(Extension):
"""
A Numba-specific Extension subclass to LLVM-compile pure Python code
to an extension module.
"""
_cc = None
_distutils_monkey_patched = False
def _prepare_object_files(self, build_ext):
cc = self._cc
dir_util.mkpath(os.path.join(build_ext.build_te... | _CCExtension |
python | realpython__materials | wordcount/tests/realpython/exceptions.py | {
"start": 0,
"end": 197
} | class ____(AssertionError):
def __init__(self, expected, actual, message=None):
self.expected = expected
self.actual = actual
self.message = message
| RealPythonAssertionError |
python | scikit-learn__scikit-learn | sklearn/linear_model/_logistic.py | {
"start": 26598,
"end": 50992
} | class ____(LinearClassifierMixin, SparseCoefMixin, BaseEstimator):
"""
Logistic Regression (aka logit, MaxEnt) classifier.
This class implements regularized logistic regression using a set of available
solvers. **Note that regularization is applied by default**. It can handle both
dense and sparse ... | LogisticRegression |
python | openai__openai-python | src/openai/types/realtime/realtime_tools_config_union_param.py | {
"start": 2450,
"end": 4595
} | class ____(TypedDict, total=False):
server_label: Required[str]
"""A label for this MCP server, used to identify it in tool calls."""
type: Required[Literal["mcp"]]
"""The type of the MCP tool. Always `mcp`."""
allowed_tools: Optional[McpAllowedTools]
"""List of allowed tool names or a filter ... | Mcp |
python | apache__airflow | airflow-core/src/airflow/exceptions.py | {
"start": 5786,
"end": 5894
} | class ____(AirflowNotFoundException):
"""Raise when a Pool is not available in the system."""
| PoolNotFound |
python | django__django | django/contrib/gis/gdal/field.py | {
"start": 6410,
"end": 6886
} | class ____(Field):
pass
# Class mapping dictionary for OFT Types and reverse mapping.
OGRFieldTypes = {
0: OFTInteger,
1: OFTIntegerList,
2: OFTReal,
3: OFTRealList,
4: OFTString,
5: OFTStringList,
6: OFTWideString,
7: OFTWideStringList,
8: OFTBinary,
9: OFTDate,
10: OF... | OFTInteger64List |
python | huggingface__transformers | src/transformers/models/dia/modeling_dia.py | {
"start": 5345,
"end": 11684
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: DiaConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.con... | DiaRotaryEmbedding |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/non_slot_assignment.py | {
"start": 924,
"end": 1121
} | class ____(StudentD):
def __init__(self, name, middle_name):
self.name = name
self.middle_name = middle_name # OK
self.setup()
def setup(self):
pass
| StudentE |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_v3_utils.py | {
"start": 6168,
"end": 10270
} | class ____(trackable_base.Trackable):
"""Trackable for stacked tables generated from sparse core."""
def __init__(self, stacked_layouts, table_to_config):
self.vars = {}
self._stacked_layouts = stacked_layouts
for table_layout in stacked_layouts:
variable_shape = tuple(table_layout.unsharded_shap... | SparseCoreStackedTableTrackable |
python | openai__openai-python | src/openai/types/beta/thread_update_params.py | {
"start": 387,
"end": 1174
} | class ____(TypedDict, total=False):
metadata: Optional[Metadata]
"""Set of 16 key-value pairs that can be attached to an object.
This can be useful for storing additional information about the object in a
structured format, and querying for objects via API or the dashboard.
Keys are strings with a... | ThreadUpdateParams |
python | mahmoud__boltons | boltons/cacheutils.py | {
"start": 22025,
"end": 22954
} | class ____:
"""The ``cachedproperty`` is used similar to :class:`property`, except
that the wrapped method is only called once. This is commonly used
to implement lazy attributes.
After the property has been accessed, the value is stored on the
instance itself, using the same name as the cachedprop... | cachedproperty |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_overlap.py | {
"start": 774,
"end": 10297
} | class ____(FSDPTest):
"""
NOTE: Testing stream overlap in PyTorch CI is tricky.
One approach is to use CUDA sleeps to emulate kernels in each stream;
however, ``torch.cuda._sleep`` requires inputs in units of cycles. The
``get_cycles_per_ms`` function to convert from ms to cycles is computed
on... | TestFullyShardOverlap |
python | getsentry__sentry | tests/sentry/utils/test_auth.py | {
"start": 1903,
"end": 5043
} | class ____(TestCase):
def _make_request(self, next=None):
request = HttpRequest()
request.META["SERVER_NAME"] = "testserver"
request.META["SERVER_PORT"] = "80"
request.session = SessionBase()
request.user = self.user
if next:
request.session["_next"] = nex... | GetLoginRedirectTest |
python | PrefectHQ__prefect | src/prefect/server/services/base.py | {
"start": 1858,
"end": 4510
} | class ____(ABC):
name: str
logger: Logger
@classmethod
@abstractmethod
def service_settings(cls) -> ServicesBaseSetting:
"""The Prefect setting that controls whether the service is enabled"""
...
@classmethod
def environment_variable_name(cls) -> str:
return canonic... | Service |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_gdm.py | {
"start": 1146,
"end": 3980
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
new=mock_init,
):
self.gdm_hook = GoogleDeploymentManagerHook(gcp_conn_id="test")
@mock.patch("airflow.providers.google.cloud.hoo... | TestDeploymentManagerHook |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_gcs.py | {
"start": 2071,
"end": 7705
} | class ____:
@mock.patch("airflow.providers.google.cloud.sensors.gcs.GCSHook")
@mock.patch("airflow.providers.google.cloud.sensors.gcs.GCSObjectExistenceSensor.defer")
def test_gcs_object_existence_sensor_return_value(self, mock_defer, mock_hook):
task = GCSObjectExistenceSensor(
task_id=... | TestGoogleCloudStorageObjectSensor |
python | kamyu104__LeetCode-Solutions | Python/minimize-hamming-distance-after-swap-operations.py | {
"start": 2083,
"end": 2868
} | class ____(object):
def minimumHammingDistance(self, source, target, allowedSwaps):
"""
:type source: List[int]
:type target: List[int]
:type allowedSwaps: List[List[int]]
:rtype: int
"""
uf = UnionFind(len(source))
for x, y in allowedSwaps:
... | Solution2 |
python | bokeh__bokeh | tests/unit/bokeh/core/test_properties.py | {
"start": 15667,
"end": 18790
} | class ____(HasProps):
pass
def test_HasProps_equals() -> None:
class Foo(HasProps):
x = Int(12)
y = String("hello")
z = List(Int, default=[1,2,3])
class FooUnrelated(HasProps):
x = Int(12)
y = String("hello")
z = List(Int, default=[1,2,3])
v = Foo().equ... | Baz |
python | kamyu104__LeetCode-Solutions | Python/my-calendar-i.py | {
"start": 663,
"end": 1048
} | class ____(object):
def __init__(self):
self.__root = None
def book(self, start, end):
"""
:type start: int
:type end: int
:rtype: bool
"""
if self.__root is None:
self.__root = Node(start, end)
return True
return self.roo... | MyCalendar |
python | sqlalchemy__sqlalchemy | test/engine/test_execute.py | {
"start": 30371,
"end": 35753
} | class ____(fixtures.TestBase):
__sparse_driver_backend__ = True
def test_cache(self, connection, metadata):
users = Table(
"users",
metadata,
Column(
"user_id", INT, primary_key=True, test_needs_autoincrement=True
),
Column("us... | CompiledCacheTest |
python | PyCQA__pylint | tests/functional/g/generic_class_syntax.py | {
"start": 616,
"end": 702
} | class ____(Generic[_T]):
def __init__(self):
self.update_interval = 0
| Parent |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-square-free-subsets.py | {
"start": 1723,
"end": 3442
} | class ____(object):
def squareFreeSubsets(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def linear_sieve_of_eratosthenes(n): # Time: O(n), Space: O(n)
primes = []
spf = [-1]*(n+1) # the smallest prime factor
for i in xrange(2, n+... | Solution2 |
python | scikit-learn__scikit-learn | sklearn/gaussian_process/kernels.py | {
"start": 33369,
"end": 39522
} | class ____(Kernel):
"""The Exponentiation kernel takes one base kernel and a scalar parameter
:math:`p` and combines them via
.. math::
k_{exp}(X, Y) = k(X, Y) ^p
Note that the `__pow__` magic method is overridden, so
`Exponentiation(RBF(), 2)` is equivalent to using the ** operator
wi... | Exponentiation |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/dataflow.py | {
"start": 35161,
"end": 40426
} | class ____(BaseTrigger):
"""
Trigger that monitors if a Dataflow job has reached any of successful terminal state meant for that job.
:param job_id: Required. ID of the job.
:param project_id: Required. The Google Cloud project ID in which the job was started.
:param location: Optional. The locatio... | DataflowJobStateCompleteTrigger |
python | django-mptt__django-mptt | mptt/models.py | {
"start": 16237,
"end": 45669
} | class ____(models.Model, metaclass=MPTTModelBase):
"""
Base class for tree models.
"""
class Meta:
abstract = True
objects = TreeManager()
def __init__(self, *args, **kwargs):
if hasattr(self, "_check_no_testing_generators"):
self._check_no_testing_generators()
... | MPTTModel |
python | django__django | tests/modeladmin/tests.py | {
"start": 898,
"end": 34455
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.band = Band.objects.create(
name="The Doors",
bio="",
sign_date=date(1965, 1, 1),
)
def setUp(self):
self.site = AdminSite()
def test_modeladmin_str(self):
ma = ModelAdmin... | ModelAdminTests |
python | doocs__leetcode | solution/0500-0599/0548.Split Array with Equal Sum/Solution.py | {
"start": 0,
"end": 538
} | class ____:
def splitArray(self, nums: List[int]) -> bool:
n = len(nums)
s = [0] * (n + 1)
for i, v in enumerate(nums):
s[i + 1] = s[i] + v
for j in range(3, n - 3):
seen = set()
for i in range(1, j - 1):
if s[i] == s[j] - s[i + 1]:... | Solution |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/tokens.py | {
"start": 9452,
"end": 9697
} | class ____(Token):
__slots__ = ('value',)
id = '<alias>'
def __init__(self, value, start_mark, end_mark):
# type: (Any, Any, Any) -> None
Token.__init__(self, start_mark, end_mark)
self.value = value
| AliasToken |
python | walkccc__LeetCode | solutions/3095. Shortest Subarray With OR at Least K I/3095.py | {
"start": 0,
"end": 835
} | class ____:
def minimumSubarrayLength(self, nums: list[int], k: int) -> int:
ans = len(nums) + 1
ors = 0
count = collections.Counter()
l = 0
for r, num in enumerate(nums):
ors = self._orNum(ors, num, count)
while ors >= k and l <= r:
ans = min(ans, r - l + 1)
ors = sel... | Solution |
python | huggingface__transformers | src/transformers/models/clip/processing_clip.py | {
"start": 699,
"end": 1445
} | class ____(ProcessorMixin):
r"""
Constructs a CLIP processor which wraps a CLIP image processor and a CLIP tokenizer into a single processor.
[`CLIPProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`CLIPTokenizerFast`]. See the
[`~CLIPProcessor.__call__`] and [`~CLIPProcessor.de... | CLIPProcessor |
python | sqlalchemy__sqlalchemy | test/engine/test_execute.py | {
"start": 125831,
"end": 134979
} | class ____(fixtures.TablesTest):
__backend__ = True
__requires__ = ("independent_connections", "insert_returning")
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column("user_id", INT, primary_key=True, autoincrement=False),
... | SetInputSizesTest |
python | sympy__sympy | sympy/parsing/sym_expr.py | {
"start": 458,
"end": 8895
} | class ____: # type: ignore
"""Class to store and handle SymPy expressions
This class will hold SymPy Expressions and handle the API for the
conversion to and from different languages.
It works with the C and the Fortran Parser to generate SymPy expressions
which are stored here and which can be c... | SymPyExpression |
python | numba__numba | numba/tests/test_pipeline.py | {
"start": 2760,
"end": 5254
} | class ____(TestCase):
def _create_pipeline_w_del(self, base=None, inject_after=None):
"""
Creates a new compiler pipeline with the _InjectDelsPass injected after
the pass supplied in kwarg 'inject_after'.
"""
self.assertTrue(inject_after is not None)
self.assertTrue(... | TestPassManagerFunctionality |
python | huggingface__transformers | src/transformers/image_utils.py | {
"start": 2658,
"end": 20402
} | class ____(ExplicitEnum):
PIL = "pillow"
TORCH = "torch"
NUMPY = "numpy"
def get_image_type(image):
if is_pil_image(image):
return ImageType.PIL
if is_torch_tensor(image):
return ImageType.TORCH
if is_numpy_array(image):
return ImageType.NUMPY
raise ValueError(f"Unr... | ImageType |
python | Pylons__pyramid | src/pyramid/i18n.py | {
"start": 8435,
"end": 13918
} | class ____(gettext.GNUTranslations):
"""An extended translation catalog class (ripped off from Babel)"""
DEFAULT_DOMAIN = 'messages'
def __init__(self, fileobj=None, domain=DEFAULT_DOMAIN):
"""Initialize the translations catalog.
:param fileobj: the file-like object the translation should... | Translations |
python | Textualize__textual | src/textual/_parser.py | {
"start": 268,
"end": 323
} | class ____(ParseError):
"""End of Stream."""
| ParseEOF |
python | pytorch__pytorch | benchmarks/instruction_counts/execution/runner.py | {
"start": 409,
"end": 707
} | class ____(Exception):
"""Raised in the main process when a worker failure is detected."""
def __init__(self, cmd: str, wrapped_trace: Optional[str] = None) -> None:
self.cmd: str = cmd
self.wrapped_trace: Optional[str] = wrapped_trace
super().__init__()
| WorkerFailed |
python | spack__spack | lib/spack/spack/llnl/util/lang.py | {
"start": 28906,
"end": 29770
} | class ____(collections.abc.MutableSequence):
"""Base class that behaves like a list, just with a different type.
Client code can inherit from this base class::
class Foo(TypedMutableSequence):
pass
and later perform checks based on types::
if isinstance(l, Foo):
#... | TypedMutableSequence |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/base.py | {
"start": 45597,
"end": 45924
} | class ____(sqltypes.Text):
"""MSSQL XML type.
This is a placeholder type for reflection purposes that does not include
any Python-side datatype support. It also does not currently support
additional arguments, such as "CONTENT", "DOCUMENT",
"xml_schema_collection".
"""
__visit_name__ = ... | XML |
python | keras-team__keras | keras/src/layers/merging/maximum.py | {
"start": 166,
"end": 2142
} | class ____(Merge):
"""Computes element-wise maximum on a list of inputs.
It takes as input a list of tensors, all of the same shape,
and returns a single tensor (also of the same shape).
Examples:
>>> input_shape = (2, 3, 4)
>>> x1 = np.random.rand(*input_shape)
>>> x2 = np.random.rand(*i... | Maximum |
python | pydantic__pydantic | pydantic/_internal/_generics.py | {
"start": 3377,
"end": 22976
} | class ____(TypedDict):
origin: type[BaseModel] | None # analogous to typing._GenericAlias.__origin__
args: tuple[Any, ...] # analogous to typing._GenericAlias.__args__
parameters: tuple[TypeVar, ...] # analogous to typing.Generic.__parameters__
def create_generic_submodel(
model_name: str, origin: ... | PydanticGenericMetadata |
python | gevent__gevent | src/gevent/tests/test__threadpool.py | {
"start": 20069,
"end": 21383
} | class ____(greentest.TestCase):
def test_exception_in_on_async_doesnt_crash(self):
# Issue 1482. An FFI-based loop could crash the whole process
# by dereferencing a handle after it was closed.
called = []
class MyException(Exception):
pass
def bad_when_ready():... | TestThreadResult |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 35825,
"end": 36069
} | class ____(BaseCategories):
params = [get_benchmark_shapes("TimeSetCategories")]
param_names = ["shape"]
def time_set_categories(self, shape):
execute(self.ts.cat.set_categories(self.ts.cat.categories[::2]))
| TimeSetCategories |
python | bokeh__bokeh | src/bokeh/core/property/numeric.py | {
"start": 2115,
"end": 2659
} | class ____(SingleParameterizedProperty[T]):
""" A property accepting a value of some other type while having undefined default. """
def __init__(self, type_param: TypeOrInst[Property[T]], *, default: Init[T] = Intrinsic, help: str | None = None) -> None:
super().__init__(type_param, default=default, he... | Positive |
python | apache__airflow | providers/standard/tests/unit/standard/sensors/test_time_delta.py | {
"start": 5274,
"end": 8641
} | class ____:
def setup_method(self):
self.dagbag = DagBag(dag_folder=DEV_NULL, include_examples=True)
self.args = {"owner": "airflow", "start_date": DEFAULT_DATE}
self.dag = DAG(TEST_DAG_ID, schedule=timedelta(days=1), default_args=self.args)
@pytest.mark.parametrize(
"should_def... | TestTimeDeltaSensorAsync |
python | plotly__plotly.py | plotly/io/_base_renderers.py | {
"start": 13031,
"end": 13648
} | class ____(HtmlRenderer):
"""
Renderer to display interactive figures in Google Colab Notebooks.
This renderer is enabled by default when running in a Colab notebook.
mime type: 'text/html'
"""
def __init__(
self, config=None, auto_play=False, post_script=None, animation_opts=None
... | ColabRenderer |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_units.py | {
"start": 480,
"end": 10483
} | class ____:
def __init__(self, data, units):
self.magnitude = data
self.units = units
def to(self, new_units):
factors = {('hours', 'seconds'): 3600, ('minutes', 'hours'): 1 / 60,
('minutes', 'seconds'): 60, ('feet', 'miles'): 1 / 5280.,
('feet', 'i... | Quantity |
python | walkccc__LeetCode | solutions/3411. Maximum Subarray With Equal Products/3411.py | {
"start": 0,
"end": 352
} | class ____:
def maxLength(self, nums: list[int]) -> int:
n = len(nums)
ans = 0
for i in range(n):
prod = 1
l = 1
g = 0
for j in range(i, n):
prod *= nums[j]
l = math.lcm(l, nums[j])
g = math.gcd(g, nums[j])
if prod == l * g:
ans = max(ans,... | Solution |
python | fsspec__filesystem_spec | fsspec/tests/test_async.py | {
"start": 4494,
"end": 7125
} | class ____(fsspec.asyn.AbstractAsyncStreamedFile):
def __init__(self, fs, path, mode, block_size, autocommit, **kwargs):
super().__init__(fs, path, mode, block_size, autocommit, **kwargs)
self.temp_buffer = io.BytesIO(b"foo-bar" * 20)
async def _fetch_range(self, start, end):
return sel... | DummyAsyncStreamedFile |
python | django__django | tests/unmanaged_models/models.py | {
"start": 1286,
"end": 1607
} | class ____(models.Model):
class Meta:
db_table = "b01"
managed = False
fk_a = models.ForeignKey(A02, models.CASCADE)
f_a = models.CharField(max_length=10, db_index=True)
f_b = models.IntegerField()
# To re-use the many-to-many intermediate table, we need to manually set up
# things up... | B02 |
python | doocs__leetcode | lcci/01.02.Check Permutation/Solution.py | {
"start": 0,
"end": 116
} | class ____:
def CheckPermutation(self, s1: str, s2: str) -> bool:
return Counter(s1) == Counter(s2)
| Solution |
python | getsentry__sentry | src/sentry/tsdb/redissnuba.py | {
"start": 3483,
"end": 4702
} | class ____(BaseTSDB, metaclass=RedisSnubaTSDBMeta):
def __init__(self, switchover_timestamp=None, **options):
"""
A TSDB backend that uses the Snuba outcomes and events datasets as far
as possible instead of reading/writing to redis. Reading will trigger a
Snuba query, while writing ... | RedisSnubaTSDB |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/widgets/menus.py | {
"start": 12785,
"end": 13419
} | class ____:
def __init__(
self,
text: str = "",
handler: Callable[[], None] | None = None,
children: list[MenuItem] | None = None,
shortcut: Sequence[Keys | str] | None = None,
disabled: bool = False,
) -> None:
self.text = text
self.handler = hand... | MenuItem |
python | getsentry__sentry | src/sentry/integrations/gitlab/integration.py | {
"start": 3814,
"end": 7855
} | class ____(RepositoryIntegration, GitlabIssuesSpec, CommitContextIntegration):
codeowners_locations = ["CODEOWNERS", ".gitlab/CODEOWNERS", "docs/CODEOWNERS"]
@property
def integration_name(self) -> str:
return IntegrationProviderSlug.GITLAB
def get_client(self) -> GitLabApiClient:
try:... | GitlabIntegration |
python | joke2k__faker | tests/providers/test_phone_number.py | {
"start": 2677,
"end": 3866
} | class ____:
"""Test az_AZ phone number provider methods"""
@classmethod
def setup_class(cls):
cls.cellphone_patterns = re.compile(
r"\+994\d{9}|0\d{2}-\d{3}-\d{2}-\d{2}|0\d{2} \d{3} \d{2} \d{2}",
)
cls.landline_patterns = re.compile(
r"0\d{2} \d{3} \d{2} \d{2... | TestAzAz |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 19609,
"end": 20010
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear1 = torch.nn.Linear(10, 10)
self.scale = torch.nn.Parameter(torch.randn(10, 10))
self.scale_dup = self.scale
def forward(self, x):
counter = 0
for _param in self.parameters():
... | ParametersModule5 |
python | wandb__wandb | wandb/automations/_generated/create_generic_webhook_integration.py | {
"start": 314,
"end": 542
} | class ____(GQLResult):
create_generic_webhook_integration: Optional[
CreateGenericWebhookIntegrationCreateGenericWebhookIntegration
] = Field(alias="createGenericWebhookIntegration")
| CreateGenericWebhookIntegration |
python | pytest-dev__pytest | src/_pytest/recwarn.py | {
"start": 5481,
"end": 8650
} | class ____(warnings.catch_warnings):
"""A context manager to record raised warnings.
Each recorded warning is an instance of :class:`warnings.WarningMessage`.
Adapted from `warnings.catch_warnings`.
.. note::
``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated
differe... | WarningsRecorder |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/descriptors.py | {
"start": 15264,
"end": 15686
} | class ____:
"""Describes where an output from an AOTAutograd produced FX graph will
eventually be bundled into the final output"""
def expr(self) -> str:
raise NotImplementedError("Subclasses must implement expr()")
def is_grad(self) -> bool:
"""True if this output is a grad or derived... | AOTOutput |
python | marshmallow-code__marshmallow | tests/base.py | {
"start": 6327,
"end": 6411
} | class ____(UserSchema):
homepage = fields.Url(relative=True)
| UserRelativeUrlSchema |
python | walkccc__LeetCode | solutions/847. Shortest Path Visiting All Nodes/847.py | {
"start": 0,
"end": 546
} | class ____:
def shortestPathLength(self, graph: list[list[int]]) -> int:
n = len(graph)
goal = (1 << n) - 1
q = collections.deque() # (u, state)
seen = set()
for i in range(n):
q.append((i, 1 << i))
step = 0
while q:
for _ in range(len(q)):
u, state = q.popleft()
... | Solution |
python | facebook__pyre-check | client/tests/dataclasses_merge_test.py | {
"start": 727,
"end": 889
} | class ____:
x: List[int] = field(
default_factory=list, metadata={"merge_policy": Policy.PREPEND}
)
@dataclass_merge
@dataclass(frozen=True)
| Prepend |
python | openai__openai-python | src/openai/types/responses/response_computer_tool_call_param.py | {
"start": 1105,
"end": 1484
} | class ____(TypedDict, total=False):
type: Required[Literal["double_click"]]
"""Specifies the event type.
For a double click action, this property is always set to `double_click`.
"""
x: Required[int]
"""The x-coordinate where the double click occurred."""
y: Required[int]
"""The y-coo... | ActionDoubleClick |
python | encode__django-rest-framework | rest_framework/authentication.py | {
"start": 702,
"end": 866
} | class ____(CsrfViewMiddleware):
def _reject(self, request, reason):
# Return the failure reason instead of an HttpResponse
return reason
| CSRFCheck |
python | dagster-io__dagster | python_modules/libraries/dagster-powerbi/dagster_powerbi/resource.py | {
"start": 3475,
"end": 16716
} | class ____(ConfigurableResource):
"""Represents a workspace in PowerBI and provides utilities
to interact with the PowerBI API.
"""
credentials: ResourceDependency[PowerBICredentials]
workspace_id: str = Field(..., description="The ID of the PowerBI group to use.")
refresh_poll_interval: int = ... | PowerBIWorkspace |
python | mlflow__mlflow | mlflow/tracing/export/async_export_queue.py | {
"start": 465,
"end": 959
} | class ____:
"""A dataclass to represent a simple task."""
handler: Callable[..., Any]
args: Sequence[Any]
error_msg: str = ""
def handle(self) -> None:
"""Handle the task execution. This method must not raise any exception."""
try:
self.handler(*self.args)
excep... | Task |
python | joblib__joblib | joblib/externals/loky/backend/popen_loky_posix.py | {
"start": 496,
"end": 685
} | class ____:
def __init__(self, fd):
self.fd = reduction._mk_inheritable(fd)
def detach(self):
return self.fd
#
# Start child process using subprocess.Popen
#
| _DupFd |
python | ansible__ansible | lib/ansible/module_utils/urls.py | {
"start": 13546,
"end": 25337
} | class ____(urllib.request.HTTPRedirectHandler):
"""This is an implementation of a RedirectHandler to match the
functionality provided by httplib2. It will utilize the value of
``follow_redirects`` to determine how redirects should be handled in
urllib.
"""
def __init__(self, follow_redirects=No... | HTTPRedirectHandler |
python | huggingface__transformers | src/transformers/models/glm4v/modular_glm4v.py | {
"start": 33056,
"end": 33307
} | class ____(Qwen2_5_VLPreTrainedModel):
_no_split_modules = ["Glm4vTextDecoderLayer", "Glm4vVisionBlock"]
_can_record_outputs = {
"hidden_states": Glm4vTextDecoderLayer,
"attentions": Glm4vTextAttention,
}
| Glm4vPreTrainedModel |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 30654,
"end": 30714
} | class ____(IdxMin):
_reduction_attribute = "idxmax"
| IdxMax |
python | realpython__materials | solid-principles-python/shapes_lsp.py | {
"start": 579,
"end": 662
} | class ____(ABC):
@abstractmethod
def calculate_area(self):
pass
| Shape |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py | {
"start": 11772,
"end": 16220
} | class ____:
def test_prefix_match_empty_tree(self, tree: PrefixTree) -> None:
"""Test prefix_match on an empty tree returns empty string and None tenants."""
matched_text, matched_tenants = tree.prefix_match("hello")
assert matched_text == ""
assert matched_tenants is None
def t... | TestPrefixTreeMatch |
python | apache__airflow | providers/apache/kylin/src/airflow/providers/apache/kylin/hooks/kylin.py | {
"start": 971,
"end": 2822
} | class ____(BaseHook):
"""
Interact with Kylin to run CubeSource commands and get job status.
:param kylin_conn_id: The connection id as configured in Airflow administration.
:param project: project name
:param dsn: dsn
"""
conn_name_attr = "kylin_conn_id"
default_conn_name = "kylin_def... | KylinHook |
python | getsentry__sentry | tests/sentry/preprod/api/endpoints/test_project_preprod_artifact_update.py | {
"start": 17140,
"end": 18416
} | class ____(TestCase):
def test_exact_version_matching_prevents_incorrect_matches(self):
package = "com.hackernews"
version = "1.2.3"
self.create_release(project=self.project, version=f"{package}@{version}333333")
self.create_release(project=self.project, version=f"{package}@{version... | FindOrCreateReleaseTest |
python | chroma-core__chroma | chromadb/config.py | {
"start": 3983,
"end": 4597
} | class ____(Enum):
"""
Routing mode for the segment directory
node - Assign based on the node name, used in production with multi-node settings with the assumption that
there is one query service pod per node. This is useful for when there is a disk based cache on the
node that we want to route to.
... | RoutingMode |
python | kennethreitz__tablib | tests/test_tablib.py | {
"start": 30592,
"end": 31662
} | class ____(BaseTestCase):
def test_xls_format_detect(self):
"""Test the XLS format detection."""
in_stream = self.founders.xls
self.assertEqual(detect_format(in_stream), 'xls')
def test_xls_date_import(self):
xls_source = Path(__file__).parent / 'files' / 'dates.xls'
wit... | XLSTests |
python | pytorch__pytorch | torch/_inductor/compile_fx.py | {
"start": 42617,
"end": 86323
} | class ____(FxCompile):
@override
def codegen_and_compile(
self,
gm: GraphModule,
example_inputs: Sequence[InputType],
inputs_to_check: Sequence[int],
graph_kwargs: _CompileFxKwargs,
) -> OutputCode:
"""
Generates the OutputCode from the GraphModule and... | _InProcessFxCompile |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.