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 | apache__airflow | airflow-core/src/airflow/models/backfill.py | {
"start": 2030,
"end": 2186
} | class ____(AirflowException):
"""
Raised when attempting to create backfill and one already active.
:meta private:
"""
| AlreadyRunningBackfill |
python | matplotlib__matplotlib | galleries/examples/event_handling/image_slices_viewer.py | {
"start": 517,
"end": 1511
} | class ____:
def __init__(self, ax, X):
self.index = 0
self.X = X
self.ax = ax
self.im = ax.imshow(self.X[:, :, self.index])
self.update()
def on_scroll(self, event):
print(event.button, event.step)
increment = 1 if event.button == 'up' else -1
max... | IndexTracker |
python | huggingface__transformers | tests/models/longformer/test_modeling_longformer.py | {
"start": 1435,
"end": 12855
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
use_labels=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=2,
num_attention_head... | LongformerModelTester |
python | doocs__leetcode | solution/2900-2999/2925.Maximum Score After Applying Operations on a Tree/Solution.py | {
"start": 0,
"end": 670
} | class ____:
def maximumScoreAfterOperations(
self, edges: List[List[int]], values: List[int]
) -> int:
def dfs(i: int, fa: int = -1) -> (int, int):
a = b = 0
leaf = True
for j in g[i]:
if j != fa:
leaf = False
... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1120706,
"end": 1121047
} | class ____(sgqlc.types.Type, Contribution):
"""Represents the contribution a user made on GitHub by opening an
issue.
"""
__schema__ = github_schema
__field_names__ = ("issue",)
issue = sgqlc.types.Field(sgqlc.types.non_null("Issue"), graphql_name="issue")
"""The issue that was opened."""
... | CreatedIssueContribution |
python | getsentry__sentry | tests/sentry/utils/test_projectflags.py | {
"start": 295,
"end": 1642
} | class ____(TestCase):
@patch.object(test_signal, "send_robust")
def test_basic(self, mock_send_robust: Mock) -> None:
assert not self.project.flags.has_transactions
assert set_project_flag_and_signal(self.project, "has_transactions", test_signal) == 1
mock_send_robust.assert_called_once_... | SetProjectFlagsAndSignalTest |
python | bokeh__bokeh | tests/unit/bokeh/server/test_contexts.py | {
"start": 1310,
"end": 1785
} | class ____:
def test_init(self) -> None:
ac = bsc.ApplicationContext("app", io_loop="ioloop")
c = bsc.BokehServerContext(ac)
assert c.application_context == ac
assert len(gc.get_referrers(ac)) == 0
def test_sessions(self) -> None:
ac = bsc.ApplicationContext("app", io_lo... | TestBokehServerContext |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/processors.py | {
"start": 4890,
"end": 5159
} | class ____(Processor):
"""
A `Processor` that doesn't do anything.
"""
def apply_transformation(
self, transformation_input: TransformationInput
) -> Transformation:
return Transformation(transformation_input.fragments)
| DummyProcessor |
python | joke2k__faker | faker/providers/ssn/nl_BE/__init__.py | {
"start": 172,
"end": 2868
} | class ____(SsnProvider):
def ssn(self) -> str:
"""
Returns a 11 digits Belgian SSN called "rijksregisternummer" as a string
The first 6 digits represent the birthdate with (in order) year, month and day.
The second group of 3 digits is represents a sequence number (order of birth).
... | Provider |
python | gevent__gevent | src/gevent/tests/test__server.py | {
"start": 563,
"end": 1965
} | class ____(StreamServer):
def handle(self, client_socket, _address): # pylint:disable=method-hidden
fd = client_socket.makefile()
try:
request_line = fd.readline()
if not request_line:
return
try:
_method, path, _rest = request_lin... | SimpleStreamServer |
python | pennersr__django-allauth | allauth/app_settings.py | {
"start": 31,
"end": 1324
} | class ____:
def __init__(self, prefix):
self.prefix = prefix
def _setting(self, name, dflt):
from allauth.utils import get_setting
return get_setting(self.prefix + name, dflt)
@property
def SITES_ENABLED(self):
return apps.is_installed("django.contrib.sites")
@pro... | AppSettings |
python | tensorflow__tensorflow | tensorflow/python/ops/functional_ops_test.py | {
"start": 1119,
"end": 2776
} | class ____(test.TestCase):
def testIfWithDefun(self):
# Defun should only be used in graph mode
with ops.Graph().as_default():
@function.Defun(dtypes.float32)
def Then(x):
return x + 1
@function.Defun(dtypes.float32)
def Else(x):
return x - 1
inputs = [10.]
... | FunctionalOpsTest |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/dynamic_rendezvous.py | {
"start": 32610,
"end": 32956
} | class ____:
"""Represent a rendezvous close operation."""
def __call__(self, ctx: _RendezvousContext, deadline: float) -> _Action:
if ctx.state.closed:
return _Action.FINISH
if time.monotonic() > deadline:
return _Action.ERROR_TIMEOUT
return _Action.MARK_RENDEZVO... | _RendezvousCloseOp |
python | ApeWorX__ape | tests/functional/test_deploymentscache.py | {
"start": 93,
"end": 2464
} | class ____:
CONTRACT_NAME = "DeploymentTestContractName"
@pytest.fixture(scope="class")
def contract_name(self):
return self.CONTRACT_NAME
@pytest.fixture
def cache(self):
return DeploymentDiskCache()
def test_cache_deployment(self, zero_address, cache, contract_name):
... | TestDeploymentDiskCache |
python | python-markdown__markdown | markdown/core.py | {
"start": 1511,
"end": 21328
} | class ____:
"""
A parser which converts Markdown to HTML.
Attributes:
Markdown.tab_length (int): The number of spaces which correspond to a single tab. Default: `4`.
Markdown.ESCAPED_CHARS (list[str]): List of characters which get the backslash escape treatment.
Markdown.block_level... | Markdown |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadOverlap1.py | {
"start": 1864,
"end": 2321
} | class ____(Generic[_T1, _T2]):
@overload
def method1(self, a: _T1, b: tuple[_T2, ...]) -> int: ...
@overload
def method1(self, a: _T1, b: tuple[Any, ...]) -> int: ...
def method1(self, *args: Any, **kwargs: Any) -> Any: ...
@overload
def method2(self, a: _T2, b: int) -> int: ...
@ove... | GenericClass |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_self/SLF001_1.py | {
"start": 280,
"end": 393
} | class ____:
def __new__(cls):
instance = super().__new__(cls)
instance._value = 1 # fine
| Ipsum |
python | scrapy__scrapy | scrapy/http/cookies.py | {
"start": 4370,
"end": 4479
} | class ____:
def acquire(self) -> None:
pass
def release(self) -> None:
pass
| _DummyLock |
python | conda__conda | conda/common/_logic.py | {
"start": 3615,
"end": 5143
} | class ____:
"""Simple wrapper to call a SAT solver given a _ClauseList/_ClauseArray instance."""
def __init__(self, **run_kwargs):
self._run_kwargs = run_kwargs or {}
self._clauses = _ClauseList()
# Bind some methods of _clauses to reduce lookups and call overhead.
self.add_clau... | _SatSolver |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_nevada_zip.py | {
"start": 737,
"end": 1735
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_nevada_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas... | ColumnValuesToBeValidNevadaZip |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_rename_field_app/migrations/0002_rename_field.py | {
"start": 145,
"end": 432
} | class ____(CheckedMigration):
dependencies = [
("bad_flow_rename_field_app", "0001_initial"),
]
operations = [
migrations.RenameField(
model_name="TestTable",
old_name="field",
new_name="new_field",
),
]
| Migration |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 43238,
"end": 44743
} | class ____(Operator):
""" Decrement a lower b index. """
# XXX this is "essentially" the same as MeijerUnShiftA. This "essentially"
# can be made rigorous using the functional equation G(1/z) = G'(z),
# where G' denotes a G function of slightly altered parameters.
# However, sorting out ... | MeijerUnShiftC |
python | django__django | django/contrib/gis/geos/prototypes/io.py | {
"start": 4088,
"end": 4610
} | class ____(GEOSBase):
"Base class for GEOS I/O objects."
def __init__(self):
# Getting the pointer with the constructor.
self.ptr = self._constructor()
# Loading the real destructor function at this point as doing it in
# __del__ is too late (import error).
self.destruct... | IOBase |
python | spyder-ide__spyder | spyder/utils/workers.py | {
"start": 6732,
"end": 11730
} | class ____(QObject):
"""Manager for generic workers."""
def __init__(self, parent=None, max_threads=10):
super().__init__(parent=parent)
self.parent = parent
self._queue = deque()
self._queue_workers = deque()
self._threads = []
self._workers = []
self._... | WorkerManager |
python | scikit-image__scikit-image | tests/skimage/feature/test_canny.py | {
"start": 230,
"end": 6388
} | class ____(unittest.TestCase):
def test_00_00_zeros(self):
'''Test that the Canny filter finds no points for a blank field'''
result = feature.canny(np.zeros((20, 20)), 4, 0, 0, np.ones((20, 20), bool))
self.assertFalse(np.any(result))
def test_00_01_zeros_mask(self):
'''Test th... | TestCanny |
python | qdrant__qdrant-client | qdrant_client/embed/embed_inspector.py | {
"start": 362,
"end": 6751
} | class ____:
"""Inspector which collects paths to objects requiring inference in the received models
Attributes:
parser: ModelSchemaParser instance
"""
def __init__(self, parser: Optional[ModelSchemaParser] = None) -> None:
self.parser = ModelSchemaParser() if parser is None else parser... | InspectorEmbed |
python | kamyu104__LeetCode-Solutions | Python/string-transformation.py | {
"start": 1311,
"end": 3071
} | class ____(object):
def numberOfWays(self, s, t, k):
"""
:type s: str
:type t: str
:type k: int
:rtype: int
"""
MOD = 10**9+7
def matrix_mult(A, B):
ZB = zip(*B)
return [[sum(a*b % MOD for a, b in itertools.izip(row, col)) % MOD... | Solution2 |
python | mozilla__bleach | bleach/_vendor/parse.py | {
"start": 5051,
"end": 5322
} | class ____(object):
"""Standard approach to decoding parsed results from bytes to str"""
__slots__ = ()
def decode(self, encoding='ascii', errors='strict'):
return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self))
| _ResultMixinBytes |
python | huggingface__transformers | src/transformers/models/dab_detr/modeling_dab_detr.py | {
"start": 1976,
"end": 3796
} | class ____(BaseModelOutputWithCrossAttentions):
r"""
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(bat... | DabDetrDecoderOutput |
python | numba__numba | numba/core/typing/arraydecl.py | {
"start": 20779,
"end": 21270
} | class ____(AttributeTemplate):
key = types.DType
def resolve_type(self, ary):
# Wrap the numeric type in NumberClass
return types.NumberClass(ary.dtype)
def resolve_kind(self, ary):
if isinstance(ary.key, types.scalars.Float):
val = 'f'
elif isinstance(ary.key, ... | DTypeAttr |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 84579,
"end": 85728
} | class ____:
xlPatternAutomatic = -4105 # from enum XlPattern
xlPatternChecker = 9 # from enum XlPattern
xlPatternCrissCross = 16 # from enum XlPattern
xlPatternDown = -4121 # from enum XlPattern
xlPatternGray16 = 17 # from enum XlPattern
xlPatternGray25 = -4124 # from enum XlPattern
xl... | Pattern |
python | catalyst-team__catalyst | catalyst/metrics/_accuracy.py | {
"start": 4948,
"end": 10302
} | class ____(AdditiveMetric, ICallbackBatchMetric):
"""
This metric computes accuracy for multilabel classification case.
It computes mean value of accuracy and it's approximate std value
(note that it's not a real accuracy std but std of accuracy over batch mean values).
Args:
compute_on_cal... | MultilabelAccuracyMetric |
python | sympy__sympy | sympy/utilities/codegen.py | {
"start": 54844,
"end": 64114
} | class ____(CodeGen):
"""Generator for Octave code.
The .write() method inherited from CodeGen will output a code file
<prefix>.m.
Octave .m files usually contain one function. That function name should
match the filename (``prefix``). If you pass multiple ``name_expr`` pairs,
the latter ones... | OctaveCodeGen |
python | pytest-dev__pytest | src/_pytest/capture.py | {
"start": 9017,
"end": 9807
} | class ____(abc.ABC, Generic[AnyStr]):
EMPTY_BUFFER: AnyStr
@abc.abstractmethod
def __init__(self, fd: int) -> None:
raise NotImplementedError()
@abc.abstractmethod
def start(self) -> None:
raise NotImplementedError()
@abc.abstractmethod
def done(self) -> None:
rais... | CaptureBase |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_macro02.py | {
"start": 315,
"end": 953
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("macro02.xlsm")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filen... | TestCompareXLSXFiles |
python | pypa__pip | src/pip/_vendor/rich/containers.py | {
"start": 461,
"end": 1678
} | class ____:
"""A list subclass which renders its contents to the console."""
def __init__(
self, renderables: Optional[Iterable["RenderableType"]] = None
) -> None:
self._renderables: List["RenderableType"] = (
list(renderables) if renderables is not None else []
)
... | Renderables |
python | scipy__scipy | scipy/linalg/tests/test_basic.py | {
"start": 59966,
"end": 74529
} | class ____:
lapack_drivers = ('gelsd', 'gelss', 'gelsy', None)
def test_simple_exact(self):
for dtype in REAL_DTYPES:
a = np.array([[1, 20], [-30, 4]], dtype=dtype)
for lapack_driver in TestLstsq.lapack_drivers:
for overwrite in (True, False):
... | TestLstsq |
python | huggingface__transformers | tests/models/longt5/test_modeling_longt5.py | {
"start": 49581,
"end": 66717
} | class ____(unittest.TestCase):
@cached_property
def model(self):
return LongT5ForConditionalGeneration.from_pretrained("Stancld/longt5-tglobal-large-16384-pubmed-3k_steps").to(
torch_device
)
@cached_property
def tokenizer(self):
return AutoTokenizer.from_pretrained(... | LongT5ModelIntegrationTests |
python | tensorflow__tensorflow | tensorflow/python/distribute/test_util.py | {
"start": 1622,
"end": 10622
} | class ____:
cluster: dict
max_num_worker: int
max_num_ps: int
def get_cluster_def(cluster_params, num_workers, num_ps):
if (num_workers > cluster_params.max_num_worker or
num_ps > cluster_params.max_num_ps):
raise ValueError("Requesting more servers than the maximum, adjust"
"cl... | TestClusterParams |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/repo.py | {
"start": 46184,
"end": 60832
} | class ____(AutomationCondition):
@property
def name(self) -> str:
return "some_custom_name"
def evaluate(self): ... # pyright: ignore[reportIncompatibleMethodOverride]
@asset(automation_condition=MyAutomationCondition().since_last_handled())
def asset_with_custom_automation_condition() -> None: ... | MyAutomationCondition |
python | walkccc__LeetCode | solutions/831. Masking Personal Information/831.py | {
"start": 0,
"end": 337
} | class ____:
def maskPII(self, s: str) -> str:
atIndex = s.find('@')
if atIndex != -1:
s = s.lower()
return s[0] + '*' * 5 + s[atIndex - 1:]
ans = ''.join(c for c in s if c.isdigit())
if len(ans) == 10:
return '***-***-' + ans[-4:]
return '+' + '*' * (len(ans) - 10) + '-***-***-... | Solution |
python | numba__numba | numba/tests/test_struct_ref.py | {
"start": 10426,
"end": 11316
} | class ____(structref.StructRefProxy):
def __new__(cls, value, parent):
return structref.StructRefProxy.__new__(cls, value, parent)
@property
def value(self):
return PolygonStruct_get_value(self)
@property
def parent(self):
return PolygonStruct_get_parent(self)
@njit
def P... | PolygonStruct |
python | huggingface__transformers | src/transformers/models/perception_lm/processing_perception_lm.py | {
"start": 1379,
"end": 11052
} | class ____(ProcessorMixin):
r"""
Constructs a PerceptionLM processor which wraps a PerceptionLM image processor, a PerceptionLM video processor, and a tokenizer into a single processor.
[`PerceptionLMProcessor`] offers all the functionalities of [`PerceptionLMImageProcessorFast`], [`PerceptionLMVideoProces... | PerceptionLMProcessor |
python | mlflow__mlflow | mlflow/pyfunc/__init__.py | {
"start": 46676,
"end": 164117
} | class ____(PyFuncModel):
def __init__(self, model_meta: Model, client: Any, server_pid: int, env_manager="local"):
super().__init__(model_meta=model_meta, model_impl=client, predict_fn="invoke")
self._client = client
self._server_pid = server_pid
# We need to set `env_manager` attrib... | _ServedPyFuncModel |
python | realpython__materials | python-built-in-functions/stack.py | {
"start": 0,
"end": 279
} | class ____:
def __init__(self, items=None):
self.items = list(items) if items is not None else []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def __bool__(self):
return bool(self.items)
| Stack |
python | pytorch__pytorch | torch/distributed/flight_recorder/components/types.py | {
"start": 12011,
"end": 21817
} | class ____:
"""Parses relevant info about operation out of 'event' dict
examples of supported `profiling_name`s:
nccl:broadcast
nccl:send 1->2
nccl:recv 3<-0
"""
def __init__(
self, event: dict[Any, Any], memberships: dict[str, set[Any]], pg_name: str
):
sel... | Op |
python | astropy__astropy | astropy/logger.py | {
"start": 19615,
"end": 19825
} | class ____:
"""A filter for the record origin."""
def __init__(self, origin):
self.origin = origin
def filter(self, record):
return record.origin.startswith(self.origin)
| FilterOrigin |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 7413,
"end": 8482
} | class ____(BaseExtensionApp):
description = "(developer) Develop labextension"
flags = develop_flags
user = Bool(False, config=True, help="Whether to do a user install")
sys_prefix = Bool(True, config=True, help="Use the sys.prefix as the prefix")
overwrite = Bool(False, config=True, help="Whether ... | DevelopLabExtensionApp |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/debug_events_monitors.py | {
"start": 3081,
"end": 4400
} | class ____(object):
"""Alert for Infinity and NaN values."""
def __init__(self,
wall_time,
op_type,
output_slot,
size=None,
num_neg_inf=None,
num_pos_inf=None,
num_nan=None,
execution_index=None,... | InfNanAlert |
python | getsentry__sentry | src/sentry/seer/anomaly_detection/types.py | {
"start": 2501,
"end": 2601
} | class ____(IntEnum):
ABOVE = 0
BELOW = 1
ABOVE_AND_BELOW = 2
| AnomalyDetectionThresholdType |
python | realpython__materials | python-dict-attribute/person.py | {
"start": 0,
"end": 695
} | class ____:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def __str__(self):
return "{first_name} {last_name} is {age} years old".format(
**self.__dict__
)
def __repr__(self):
... | Person |
python | fluentpython__example-code-2e | 18-with-match/lispy/py3.9/lis.py | {
"start": 1666,
"end": 5490
} | class ____(ChainMap[Symbol, Any]):
"A ChainMap that allows changing an item in-place."
def change(self, key: Symbol, value: Any) -> None:
"Find where key is defined and change the value there."
for map in self.maps:
if key in map:
map[key] = value # type: ignore[ind... | Environment |
python | wandb__wandb | wandb/vendor/pygments/styles/perldoc.py | {
"start": 462,
"end": 2175
} | class ____(Style):
"""
Style similar to the style used in the perldoc code blocks.
"""
background_color = '#eeeedd'
default_style = ''
styles = {
Whitespace: '#bbbbbb',
Comment: '#228B22',
Comment.Preproc: '#1e889b',
Comment.Spe... | PerldocStyle |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mailchimp/components.py | {
"start": 798,
"end": 3981
} | class ____(ConfigTransformation):
def transform(self, config: MutableMapping[str, Any]) -> None:
"""
Extract the data center from auth credentials and add it to the config.
For API key auth, extract from the API key itself.
For OAuth, make an HTTP request to get the data center.
... | ExtractAndSetDataCenterConfigValue |
python | optuna__optuna | optuna/cli.py | {
"start": 16257,
"end": 17843
} | class ____(_BaseCommand):
"""Show a list of trials."""
def add_arguments(self, parser: ArgumentParser) -> None:
parser.add_argument(
"--study-name",
type=str,
required=True,
help="The name of the study which includes trials.",
)
parser.add... | _Trials |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 691,
"end": 936
} | class ____:
def foo():
os.system("This is a regression test. xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxxx.".format("xxxxxxxxxx", "xxxxxx", "xxxxxxxxxx"))
| A |
python | doocs__leetcode | solution/0500-0599/0552.Student Attendance Record II/Solution2.py | {
"start": 0,
"end": 909
} | class ____:
def checkRecord(self, n: int) -> int:
mod = int(1e9 + 7)
dp = [[[0, 0, 0], [0, 0, 0]] for _ in range(n)]
# base case
dp[0][0][0] = dp[0][0][1] = dp[0][1][0] = 1
for i in range(1, n):
# A
dp[i][1][0] = (dp[i - 1][0][0] + dp[i - 1][0][1] + ... | Solution |
python | kamyu104__LeetCode-Solutions | Python/single-number-ii.py | {
"start": 1106,
"end": 1453
} | class ____(object):
# @param A, a list of integer
# @return an integer
# [1, 1, 1, 1, 2, 2, 2, 2, 3, 3]
def singleNumber(self, A):
one, two, three = 0, 0, 0
for x in A:
one, two, three = (~x & one) | (x & ~one & ~two & ~three), (~x & two) | (x & one), (~x & three) | (x & two)... | SolutionEX |
python | walkccc__LeetCode | solutions/283. Move Zeroes/283.py | {
"start": 0,
"end": 205
} | class ____:
def moveZeroes(self, nums: list[int]) -> None:
j = 0
for num in nums:
if num != 0:
nums[j] = num
j += 1
for i in range(j, len(nums)):
nums[i] = 0
| Solution |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 2286,
"end": 3201
} | class ____(RequestHandler):
# stub out enough methods to make the signed_cookie functions work
def __init__(self, cookie_secret="0123456789", key_version=None):
# don't call super.__init__
self._cookies = {} # type: typing.Dict[str, bytes]
if key_version is None:
self.applic... | CookieTestRequestHandler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solver9.py | {
"start": 660,
"end": 1039
} | class ____(ClassA):
pass
def func3(value: _T1) -> type[ClassA[_T1]]:
v1 = ClassA(value)
v2 = type(v1)
reveal_type(v2, expected_text="type[ClassA[_T1@func3]]")
return v2
d = ClassB.get()
reveal_type(d, expected_text="type[ClassB]")
reveal_type(ClassB.get(), expected_text="type[ClassB]")
def fun... | ClassB |
python | wandb__wandb | wandb/sdk/integration_utils/auto_logging.py | {
"start": 5426,
"end": 8205
} | class ____:
def __init__(
self,
name: str,
symbols: Sequence[str],
resolver: ArgumentResponseResolver,
telemetry_feature: Optional[str] = None,
) -> None:
"""Autolog API calls to W&B."""
self._telemetry_feature = telemetry_feature
self._patch_api =... | AutologAPI |
python | huggingface__transformers | src/transformers/models/mistral3/modeling_mistral3.py | {
"start": 7939,
"end": 8511
} | class ____(PreTrainedModel):
config: Mistral3Config
base_model_prefix = "model"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_sdpa = True
_can_compile_fullgraph = True
... | Mistral3PreTrainedModel |
python | apache__airflow | providers/openlineage/tests/unit/openlineage/utils/test_utils.py | {
"start": 72548,
"end": 100955
} | class ____:
def test_dag_info(self):
with DAG(
dag_id="dag_id",
schedule="@once",
start_date=datetime.datetime(2024, 6, 1),
tags={"test"},
description="test desc",
owner_links={"some_owner": "https://airflow.apache.org"},
) as d... | TestDagInfoAirflow3 |
python | davidhalter__jedi | test/completion/descriptors.py | {
"start": 3130,
"end": 3421
} | class ____():
def __init__(self, x):
self.x = x
@Memoize
def some_func(self):
return self.x
#? int()
MemoizeTest(10).some_func()
# Now also call the same function over the class (see if clause above).
#? float()
MemoizeTest.some_func(MemoizeTest(10.0))
| MemoizeTest |
python | huggingface__transformers | src/transformers/models/swinv2/modeling_swinv2.py | {
"start": 26278,
"end": 26923
} | class ____(nn.Module):
def __init__(self, config, dim):
super().__init__()
self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = con... | Swinv2Intermediate |
python | skorch-dev__skorch | skorch/tests/callbacks/test_training.py | {
"start": 35220,
"end": 39935
} | class ____:
@pytest.fixture(params=['torch', 'safetensors'])
def use_safetensors(self, request):
return request.param == 'safetensors'
@pytest.fixture
def checkpoint_cls(self):
from skorch.callbacks import Checkpoint
return Checkpoint
@pytest.fixture
def loadinitstate_c... | TestLoadInitState |
python | dask__distributed | distributed/protocol/tests/test_serialize.py | {
"start": 9900,
"end": 19239
} | class ____:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def my_dumps(obj, context=None):
if type(obj).__name__ == "MyObject":
header = {"serializer": "my-ser"}
frames = [
msgpack.dumps(obj.__dict__, use_bin_type=True),
msgpack.dumps(context, use_b... | MyObject |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 535583,
"end": 536805
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("contributions", "repository")
contributions = sgqlc.types.Field(
sgqlc.types.non_null(CreatedPullRequestContributionConnection),
graphql_name="contributions",
... | PullRequestContributionsByRepository |
python | huggingface__transformers | src/transformers/models/detr/image_processing_detr_fast.py | {
"start": 9456,
"end": 40321
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
format = AnnotationFormat.COCO_DETECTION
do_resize = True
do_rescale = True
do_normalize = True
do_pad = True
size = {"shortest_edge": 800, "... | DetrImageProcessorFast |
python | oauthlib__oauthlib | oauthlib/openid/connect/core/exceptions.py | {
"start": 408,
"end": 824
} | class ____(OpenIDClientError):
"""
The Authorization Server requires End-User interaction to proceed.
This error MAY be returned when the prompt parameter value in the
Authentication Request is none, but the Authentication Request cannot be
completed without displaying a user interface for End-User... | InteractionRequired |
python | streamlit__streamlit | lib/streamlit/elements/widgets/audio_input.py | {
"start": 3298,
"end": 12411
} | class ____:
@gather_metrics("audio_input")
def audio_input(
self,
label: str,
*,
sample_rate: int | None = 16000,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
args: WidgetArgs | None = None,
kwar... | AudioInputMixin |
python | google__pytype | pytype/rewrite/function_call_helper_test.py | {
"start": 2187,
"end": 2799
} | class ____(TestBase):
def test_build(self):
code = test_utils.parse('def C(): pass').consts[0]
builder = abstract.InterpreterFunction(
ctx=self.ctx,
name='C',
code=code,
enclosing_scope=(),
parent_frame=self.helper._frame,
)
args = abstract.Args(
posarg... | BuildClassTest |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 7793,
"end": 8002
} | class ____(BaseModel):
"""
Connection Test serializer for responses.
"""
status: Annotated[bool, Field(title="Status")]
message: Annotated[str, Field(title="Message")]
| ConnectionTestResponse |
python | dask__dask | dask/dataframe/dask_expr/_concat.py | {
"start": 11807,
"end": 12484
} | class ____(Blockwise):
_parameters = ["ignore_order", "_kwargs", "axis", "join"]
_defaults = {"ignore_order": False, "_kwargs": {}, "axis": 1, "join": "outer"}
_keyword_only = ["ignore_order", "_kwargs", "axis", "join"]
@functools.cached_property
def _meta(self):
return methods.concat(
... | ConcatUnindexed |
python | ray-project__ray | python/ray/tune/utils/object_cache.py | {
"start": 195,
"end": 5512
} | class ____:
"""Cache up to some maximum count given a grouping key.
This object cache can e.g. be used to cache Ray Tune trainable actors
given their resource requirements (reuse_actors=True).
If the max number of cached objects for a grouping key is reached,
no more objects for this group will be... | _ObjectCache |
python | numpy__numpy | numpy/polynomial/tests/test_hermite.py | {
"start": 12852,
"end": 16023
} | class ____:
def test_hermfit(self):
def f(x):
return x * (x - 1) * (x - 2)
def f2(x):
return x**4 + x**2 + 1
# Test exceptions
assert_raises(ValueError, herm.hermfit, [1], [1], -1)
assert_raises(TypeError, herm.hermfit, [[1]], [1], 0)
assert... | TestFitting |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 53370,
"end": 53872
} | class ____(RegexLexer):
"""
Base for the `TeaTemplateLexer`. Yields `Token.Other` for area outside of
code blocks.
.. versionadded:: 1.5
"""
tokens = {
'root': [
(r'<%\S?', Keyword, 'sec'),
(r'[^<]+', Other),
(r'<', Other),
],
'sec': ... | TeaTemplateRootLexer |
python | django__django | django/db/backends/oracle/base.py | {
"start": 18280,
"end": 25945
} | class ____:
"""
Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var"
style. This fixes it -- but note that if you want to use a literal "%s" in
a query, you'll need to use "%%s".
"""
charset = "utf-8"
def __init__(self, connection, database):
self.cursor = co... | FormatStylePlaceholderCursor |
python | scikit-learn__scikit-learn | sklearn/cluster/_agglomerative.py | {
"start": 28169,
"end": 41155
} | class ____(ClusterMixin, BaseEstimator):
"""
Agglomerative Clustering.
Recursively merges pair of clusters of sample data; uses linkage distance.
Read more in the :ref:`User Guide <hierarchical_clustering>`.
Parameters
----------
n_clusters : int or None, default=2
The number of c... | AgglomerativeClustering |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass11.py | {
"start": 585,
"end": 666
} | class ____(type):
def __setattr__(cls, key: str, value: Any) -> None: ...
| MetaB |
python | walkccc__LeetCode | solutions/2438. Range Product Queries of Powers/2438.py | {
"start": 0,
"end": 373
} | class ____:
def productQueries(self, n: int, queries: list[list[int]]) -> list[int]:
MOD = 1_000_000_007
MAX_BIT = 30
ans = []
pows = [1 << i for i in range(MAX_BIT) if n >> i & 1]
for left, right in queries:
prod = 1
for i in range(left, right + 1):
prod *= pows[i]
pr... | Solution |
python | google__python-fire | fire/test_components.py | {
"start": 8542,
"end": 8601
} | class ____(enum.Enum):
RED = 1
GREEN = 2
BLUE = 3
| Color |
python | sqlalchemy__sqlalchemy | test/orm/test_subquery_relations.py | {
"start": 88095,
"end": 91829
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"foo",
metadata,
Column("id", Integer, primary_key=True),
Column("type", String(50)),
Column("related_id", Integer, ForeignKey("related.id")),
)
... | InheritanceToRelatedTest |
python | pydantic__pydantic | tests/mypy/modules/plugin_success_baseConfig.py | {
"start": 686,
"end": 950
} | class ____(BaseModel, from_attributes=True):
x: float
y: str
class NotConfig:
frozen = True
kwargs_model = KwargsModel(x=1, y='y')
KwargsModel(x=1, y='y', z='z')
kwargs_model.x = 2
kwargs_model.model_validate(kwargs_model.__dict__)
| KwargsModel |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/event_log/polling_event_watcher.py | {
"start": 812,
"end": 3877
} | class ____:
"""Event Log Watcher that uses a multithreaded polling approach to retrieving new events for run_ids
This class' job is to manage a collection of threads that each poll the event log for a given run_id
Uses one thread (SqlPollingRunIdEventWatcherThread) per watched run_id.
LOCKING INFO:
... | SqlPollingEventWatcher |
python | sqlalchemy__sqlalchemy | examples/versioned_history/history_meta.py | {
"start": 7623,
"end": 11477
} | class ____:
use_mapper_versioning = False
"""if True, also assign the version column to be tracked by the mapper"""
__table_args__ = {"sqlite_autoincrement": True}
"""Use sqlite_autoincrement, to ensure unique integer values
are used for new rows even for rows that have been deleted."""
def __... | Versioned |
python | walkccc__LeetCode | solutions/2741. Special Permutations/2741.py | {
"start": 0,
"end": 710
} | class ____:
def specialPerm(self, nums: list[int]) -> int:
MOD = 1_000_000_007
maxMask = 1 << len(nums)
@functools.lru_cache(None)
def dp(prev: int, mask: int) -> int:
"""
Returns the number of special permutations, where the previous number is
nums[i] and `mask` is the bitmask of t... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 18840,
"end": 18957
} | class ____(IterableExportEventsStreamAdjustableRange):
data_field = "hostedUnsubscribeClick"
| HostedUnsubscribeClick |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 6548,
"end": 6894
} | class ____(ConcreteTemplate):
cases = [signature(types.float64, op1, op2)
for op1, op2 in itertools.product(machine_ints, machine_ints)]
cases += [signature(op, op, op) for op in sorted(types.real_domain)]
cases += [signature(op, op, op) for op in sorted(types.complex_domain)]
@infer_global(o... | BinOpTrueDiv |
python | ray-project__ray | python/ray/data/tests/test_namespace_expressions.py | {
"start": 9106,
"end": 9872
} | class ____:
"""Tests for string searching operations."""
def test_string_search(
self,
dataset_format,
method_name,
method_args,
method_kwargs,
input_values,
expected_results,
):
"""Test string searching methods."""
data = [{"val": v}... | TestStringSearch |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_types06.py | {
"start": 315,
"end": 981
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("types06.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels... | TestCompareXLSXFiles |
python | python-openxml__python-docx | src/docx/oxml/xmlchemy.py | {
"start": 18911,
"end": 19445
} | class ____(_BaseChildElement):
"""Defines an optional repeating child element for MetaOxmlElement."""
def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
"""Add the appropriate methods to `element_cls`."""
super(ZeroOrMore, self).populate_class_members(elemen... | ZeroOrMore |
python | encode__django-rest-framework | tests/test_serializer_lists.py | {
"start": 9794,
"end": 11402
} | class ____:
"""Tests the behavior of allow_empty=False when a ListSerializer is used as a field."""
@pytest.mark.parametrize('partial', (False, True))
def test_allow_empty_true(self, partial):
"""
If allow_empty is True, empty lists should be allowed regardless of the value
of parti... | TestNestedListSerializerAllowEmpty |
python | Lightning-AI__lightning | tests/tests_pytorch/models/test_hparams.py | {
"start": 31138,
"end": 31942
} | class ____(BoringModel):
def __init__(self, config):
super().__init__()
self.save_hyperparameters(config)
def test_empty_hparams_container(tmp_path):
"""Test that save_hyperparameters() is a no-op when saving an empty hparams container."""
model = HparamsKwargsContainerModel()
assert n... | HparamsNamespaceContainerModel |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/bedrock/_beta.py | {
"start": 2805,
"end": 3055
} | class ____:
def __init__(self, beta: Beta) -> None:
self._beta = beta
@cached_property
def messages(self) -> MessagesWithStreamingResponse:
return MessagesWithStreamingResponse(self._beta.messages)
| BetaWithStreamingResponse |
python | django-guardian__django-guardian | guardian/testapp/tests/test_core.py | {
"start": 1244,
"end": 2077
} | class ____(TestCase):
def setUp(self):
self.group, created = Group.objects.get_or_create(name="jackGroup")
self.user, created = User.objects.get_or_create(username="jack")
self.user.groups.add(self.group)
self.ctype = ContentType.objects.create(model="bar", app_label="fake-for-guardi... | ObjectPermissionTestCase |
python | giampaolo__psutil | tests/test_contracts.py | {
"start": 5395,
"end": 7186
} | class ____(PsutilTestCase):
def test_environ(self):
assert hasattr(psutil.Process, "environ") == (
LINUX
or MACOS
or WINDOWS
or AIX
or SUNOS
or FREEBSD
or OPENBSD
or NETBSD
)
def test_uids(self):
... | TestAvailProcessAPIs |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mixpanel/source_mixpanel/components.py | {
"start": 8100,
"end": 10688
} | class ____(SubstreamPartitionRouter):
def stream_slices(self) -> Iterable[StreamSlice]:
"""
Add 'funnel_name' to the slice, the rest code is exactly the same as in super().stream_slices(...)
Remove empty 'parent_slice' attribute to be compatible with LegacyToPerPartitionStateMigration
... | FunnelsSubstreamPartitionRouter |
python | pypa__pip | src/pip/_vendor/distlib/util.py | {
"start": 57646,
"end": 59574
} | class ____(object):
"""
Mixin for running subprocesses and capturing their output
"""
def __init__(self, verbose=False, progress=None):
self.verbose = verbose
self.progress = progress
def reader(self, stream, context):
"""
Read lines from a subprocess' output stream... | SubprocessMixin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.