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 | encode__django-rest-framework | tests/test_fields.py | {
"start": 80488,
"end": 81197
} | class ____(FieldValues):
"""
Values for nested `DictField` with CharField as child.
"""
valid_inputs = [
({0: {'a': 1, 'b': '2'}, 1: {3: 3}}, {'0': {'a': '1', 'b': '2'}, '1': {'3': '3'}}),
]
invalid_inputs = [
({0: {'a': 1, 'b': None}, 1: {'c': None}}, {'0': {'b': ['This field ma... | TestNestedDictField |
python | kamyu104__LeetCode-Solutions | Python/count-numbers-with-unique-digits-ii.py | {
"start": 2184,
"end": 2670
} | class ____(object):
def numberCount(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
def check(x):
lookup = 0
while x:
if lookup&(1<<(x%10)):
return False
lookup |= (1<<(x%10))
... | Solution3 |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 23227,
"end": 23544
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
skews = helper_functions.get_value("Skewnesses")
minimum = np.nanmin(skews) if len(skews) > 0 else 0
return minimum if np.isfinite(minimum) else 0
@metafeatures.define("SkewnessMax", dependency="Skewnesses")
| SkewnessMin |
python | pydantic__pydantic | pydantic/v1/networks.py | {
"start": 12331,
"end": 12433
} | class ____(AnyUrl):
allowed_schemes = {'file'}
host_required = False
__slots__ = ()
| FileUrl |
python | realpython__materials | queue/src/queues.py | {
"start": 1033,
"end": 1100
} | class ____:
priority: float
count: int
value: Any
| Element |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/zenrows_web/base.py | {
"start": 318,
"end": 15707
} | class ____(BasePydanticReader):
"""
ZenRows Web Reader.
Read web pages using ZenRows Universal Scraper API with advanced features like:
- JavaScript rendering for dynamic content
- Anti-bot bypass
- Premium residential proxies with geo-location
- Custom headers and session management
- ... | ZenRowsWebReader |
python | django__django | tests/admin_views/models.py | {
"start": 27786,
"end": 27926
} | class ____(models.Model):
book = models.ForeignKey(Book, models.CASCADE)
author = models.ForeignKey(Author, models.CASCADE)
| Authorship |
python | apache__airflow | providers/pagerduty/tests/unit/pagerduty/hooks/test_pagerduty_events.py | {
"start": 2698,
"end": 5090
} | class ____:
def test_get_integration_key_from_password(self, events_connections):
hook = PagerdutyEventsHook(pagerduty_events_conn_id=DEFAULT_CONN_ID)
assert hook.integration_key == "events_token", "token initialised."
def test_token_parameter_override(self, events_connections):
hook = ... | TestPagerdutyEventsHook |
python | ZoranPandovski__al-go-rithms | data_structures/b_tree/Python/same_tree.py | {
"start": 153,
"end": 1521
} | class ____():
def same_tree(self,root1,root2):
if root1 == None and root2 == None:
return True
if (root1 == None or root2 == None):
return False
if root1.val == root2.val:
if self.same_tree(root1.left,root2.left):
if self.same_tree(root... | SameTree |
python | google__pytype | pytype/datatypes.py | {
"start": 5018,
"end": 5164
} | class ____(Exception):
def __init__(self, existing_name):
super().__init__()
self.existing_name = existing_name
| AliasingDictConflictError |
python | tensorflow__tensorflow | tensorflow/lite/tools/optimize/sparsity/format_converter_wrapper_pybind11_test.py | {
"start": 910,
"end": 2708
} | class ____(absltest.TestCase):
def test_bcsr_fp32(self):
"""Same as FormatConverterTest::BlockTestD0S1 but via pybind11."""
# pyformat: disable
dense_matrix = [1.0, 0.0, 2.0, 3.0,
0.0, 4.0, 0.0, 0.0,
0.0, 0.0, 5.0, 0.0,
0.0, 0.0, 0.0, 6.0]
#... | FormatConverterTest |
python | numpy__numpy | numpy/f2py/tests/test_return_logical.py | {
"start": 61,
"end": 1385
} | class ____(util.F2PyTest):
def check_function(self, t):
assert t(True) == 1
assert t(False) == 0
assert t(0) == 0
assert t(None) == 0
assert t(0.0) == 0
assert t(0j) == 0
assert t(1j) == 1
assert t(234) == 1
assert t(234.6) == 1
assert ... | TestReturnLogical |
python | dagster-io__dagster | python_modules/dagster/dagster/components/testing/test_cases.py | {
"start": 3890,
"end": 4751
} | class ____:
"""Pytest test class for testing translation of asset attributes. You can subclass
this class and implement a test_translation function using the various fixtures in
order to comprehensively test asset translation options for your component.
"""
@pytest.fixture(params=test_cases, ids=[c... | TestTranslation |
python | scrapy__scrapy | tests/test_crawler.py | {
"start": 21804,
"end": 21926
} | class ____(scrapy.Spider):
name = "no_request"
async def start(self):
return
yield
| NoRequestsSpider |
python | openai__openai-python | src/openai/_exceptions.py | {
"start": 3750,
"end": 3891
} | class ____(APIStatusError):
status_code: Literal[422] = 422 # pyright: ignore[reportIncompatibleVariableOverride]
| UnprocessableEntityError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solverScoring4.py | {
"start": 456,
"end": 1181
} | class ____(Generic[T]):
@staticmethod
def resolve(resolve_value: S) -> "Promise[S]": ...
def __init__(self, executor_func: TA2[T]) -> None: ...
def then(self, onfullfilled: TA1[T, R]) -> "Promise[R]": ...
Promise.resolve(1).then(lambda result: reveal_type(result, expected_text="int"))
Promise.resol... | Promise |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/quantization/tensorflow/calibrator/calibration_algorithm_test.py | {
"start": 1252,
"end": 5152
} | class ____(test.TestCase, parameterized.TestCase):
def test_min_max_max(self):
calib_opts = stablehlo_quant_config_pb2.CalibrationOptions(
calibration_method=_CalibrationMethod.CALIBRATION_METHOD_MIN_MAX
)
statistics = calib_stats_pb2.CalibrationStatistics()
statistics.min_max_statistics.glob... | CalibrationAlgorithmTest |
python | PyCQA__pylint | tests/functional/n/not_callable.py | {
"start": 3503,
"end": 3917
} | class ____:
a = ADescriptor()
AggregateCls().a()
# Make sure not-callable isn't raised for descriptors
# astroid can't process descriptors correctly so
# pylint needs to ignore not-callable for them
# right now
# Test for https://github.com/pylint-dev/pylint/issues/1699
import multiprocessing
multiprocessin... | AggregateCls |
python | sphinx-doc__sphinx | sphinx/transforms/post_transforms/code.py | {
"start": 1254,
"end": 2639
} | class ____(nodes.NodeVisitor):
def __init__(self, document: nodes.document, default_language: str) -> None:
self.default_setting = HighlightSetting(default_language, False, sys.maxsize)
self.settings: list[HighlightSetting] = []
super().__init__(document)
def unknown_visit(self, node: N... | HighlightLanguageVisitor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol53.py | {
"start": 4603,
"end": 4829
} | class ____(Proto_ContraGeneric):
# This should not generate a reportIncompatibleMethodOverride error
# but does currently.
def m[T: Impl_ContraGenericExplicit3](self: T, x: T) -> None: ...
| Impl_ContraGenericExplicit3 |
python | django__django | tests/model_forms/models.py | {
"start": 3760,
"end": 3982
} | class ____(models.Model):
description = models.CharField(max_length=20)
file = models.FileField(storage=temp_storage, upload_to="tests", max_length=15)
def __str__(self):
return self.description
| TextFile |
python | python-attrs__attrs | tests/dataclass_transform_example.py | {
"start": 74,
"end": 172
} | class ____:
a: str
b: int
reveal_type(Define.__init__) # noqa: F821
@attr.define()
| Define |
python | lazyprogrammer__machine_learning_examples | rl2/mountaincar/pg_tf_random.py | {
"start": 775,
"end": 1388
} | class ____:
def __init__(self, M1, M2, f=tf.nn.tanh, use_bias=True, zeros=False):
if zeros:
W = np.zeros((M1, M2)).astype(np.float32)
self.W = tf.Variable(W)
else:
self.W = tf.Variable(tf.random_normal(shape=(M1, M2)))
self.params = [self.W]
self.use_bias = use_bias
if use_bias... | HiddenLayer |
python | getsentry__sentry | src/sentry/web/frontend/reactivate_account.py | {
"start": 370,
"end": 950
} | class ____(BaseView):
# auth check is managed by view code
auth_required = False
@method_decorator(never_cache)
def handle(self, request: HttpRequest) -> HttpResponseBase:
if not request.user.is_authenticated:
return self.handle_auth_required(request)
if request.POST.get("o... | ReactivateAccountView |
python | sqlalchemy__sqlalchemy | test/dialect/mysql/test_compiler.py | {
"start": 57831,
"end": 59023
} | class ____(fixtures.TestBase, RegexpCommon):
__dialect__ = "mariadb"
def test_regexp_match_flags_safestring(self):
self.assert_compile(
self.table.c.myid.regexp_match("pattern", flags="i'g"),
"mytable.myid REGEXP CONCAT('(?', 'i''g', ')', %s)",
checkpositional=("patt... | RegexpTestMariaDb |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 379714,
"end": 383973
} | class ____:
# all these tests use the WRITEBACKIFCOPY mechanism
def test_argmax_with_out(self):
mat = np.eye(5)
out = np.empty(5, dtype='i2')
res = np.argmax(mat, 0, out=out)
assert_equal(res, range(5))
def test_argmin_with_out(self):
mat = -np.eye(5)
out = n... | TestWritebackIfCopy |
python | pandas-dev__pandas | pandas/tests/indexes/numeric/test_indexing.py | {
"start": 20093,
"end": 20643
} | class ____:
@pytest.mark.parametrize("dtype", [np.float64, np.int64, np.uint64])
def test_contains_none(self, dtype):
# GH#35788 should return False, not raise TypeError
index = Index([0, 1, 2, 3, 4], dtype=dtype)
assert None not in index
def test_contains_float64_nans(self):
... | TestContains |
python | numpy__numpy | numpy/ma/tests/test_extras.py | {
"start": 21664,
"end": 34228
} | class ____:
def test_compress_nd(self):
# Tests compress_nd
x = np.array(list(range(3 * 4 * 5))).reshape(3, 4, 5)
m = np.zeros((3, 4, 5)).astype(bool)
m[1, 1, 1] = True
x = array(x, mask=m)
# axis=None
a = compress_nd(x)
assert_equal(a, [[[ 0, 2, 3... | TestCompressFunctions |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_relationship.py | {
"start": 82192,
"end": 85752
} | class ____(
AssertsCompiledSQL, fixtures.MappedTest
):
__dialect__ = "default"
run_create_tables = None
run_deletes = None
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column("id", Integer, primary_key=True),
Column... | MultipleAdaptUsesEntityOverTableTest |
python | PrefectHQ__prefect | tests/server/schemas/test_filters.py | {
"start": 177,
"end": 1984
} | class ____:
def test_applies_level_le_filter(self, db):
log_filter = LogFilter(level={"le_": 10})
sql_filter = log_filter.as_sql_filter()
assert sql_filter.compare(sa.and_(db.Log.level <= 10))
def test_applies_level_ge_filter(self, db):
log_filter = LogFilter(level={"ge_": 10})
... | TestLogFilters |
python | pytorch__pytorch | torch/fx/experimental/proxy_tensor.py | {
"start": 55063,
"end": 55977
} | class ____(TorchFunctionMode):
def __init__(self, tracer: _ProxyTracer) -> None:
self.tracer = tracer
def __torch_function__(
self,
func: OpOverload,
types: tuple[torch._C._TensorMeta, ...],
args: tuple[object, ...] = (),
kwargs: Optional[dict[str, object]] = Non... | TorchFunctionMetadataMode |
python | networkx__networkx | networkx/algorithms/planarity.py | {
"start": 5997,
"end": 6978
} | class ____:
"""Represents a different constraint between two intervals.
The edges in the left interval must have a different orientation than
the one in the right interval.
"""
def __init__(self, left=Interval(), right=Interval()):
self.left = left
self.right = right
def swap(... | ConflictPair |
python | celery__celery | t/smoke/tests/test_canvas.py | {
"start": 945,
"end": 2902
} | class ____:
def test_sanity(self, celery_setup: CeleryTestSetup):
queue = celery_setup.worker.worker_queue
sig = chain(
identity.si("chain_task1").set(queue=queue),
identity.si("chain_task2").set(queue=queue),
) | identity.si("test_chain").set(queue=queue)
res... | test_chain |
python | django__django | django/db/models/functions/mixins.py | {
"start": 1981,
"end": 2382
} | class ____:
def _resolve_output_field(self):
source_fields = self.get_source_fields()
if any(isinstance(s, DecimalField) for s in source_fields):
return DecimalField()
if any(isinstance(s, IntegerField) for s in source_fields):
return FloatField()
return super... | NumericOutputFieldMixin |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 37158,
"end": 44948
} | class ____(Node):
# Item in a function declaration argument list.
#
# base_type CBaseTypeNode
# declarator CDeclaratorNode
# not_none boolean Tagged with 'not None'
# or_none boolean Tagged with 'or None'
# accept_none boolean Resolve... | CArgDeclNode |
python | ray-project__ray | python/ray/tune/error.py | {
"start": 696,
"end": 816
} | class ____(_SubCategoryTuneError):
"""Error that happens when starting a tune trial."""
pass
| _TuneStartTrialError |
python | astropy__astropy | astropy/extern/configobj/configobj.py | {
"start": 3302,
"end": 4845
} | class ____(object):
def build(self, o):
if m is None:
raise UnknownType(o.__class__.__name__)
return m(o)
def build_List(self, o):
return list(map(self.build, o.getChildren()))
def build_Const(self, o):
return o.value
def build_Dict(self, o):
d = {... | Builder |
python | sanic-org__sanic | sanic/mixins/startup.py | {
"start": 2476,
"end": 52748
} | class ____(metaclass=SanicMeta):
_app_registry: ClassVar[dict[str, Sanic]]
name: str
asgi: bool
config: Config
listeners: dict[str, list[ListenerType[Any]]]
state: ApplicationState
websocket_enabled: bool
multiplexer: WorkerMultiplexer
test_mode: ClassVar[bool]
start_method: Cla... | StartupMixin |
python | ansible__ansible | test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/version_added.py | {
"start": 156,
"end": 251
} | class ____(object):
DOCUMENTATION = r"""
options: {}
version_added: 1.0.0
"""
| ModuleDocFragment |
python | scipy__scipy | scipy/linalg/tests/test_batch.py | {
"start": 843,
"end": 28552
} | class ____:
# Test batch support for most linalg functions
def batch_test(self, fun, arrays, *, core_dim=2, n_out=1, kwargs=None, dtype=None,
broadcast=True, check_kwargs=True):
# Check that all outputs of batched call `fun(A, **kwargs)` are the same
# as if we loop over the ... | TestBatch |
python | pennersr__django-allauth | allauth/socialaccount/providers/discogs/views.py | {
"start": 186,
"end": 357
} | class ____(OAuth):
url = "https://api.discogs.com/oauth/identity"
def get_user_info(self):
data = self.query(self.url).json()
return data
| DiscogsAPI |
python | huggingface__transformers | src/transformers/models/ibert/modeling_ibert.py | {
"start": 40738,
"end": 43148
} | class ____(IBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.ibert = IBertModel(config, add_pooling_layer=False)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden... | IBertForTokenClassification |
python | google__jax | jax/experimental/array_serialization/serialization.py | {
"start": 5745,
"end": 9809
} | class ____:
def __init__(self, timeout_secs=300):
self._timeout_secs = timeout_secs
self._timeout_in_ms = self._timeout_secs * 1000
self._commit_futures = None
self._thread = None
self._exception = None
if jax.process_count() > 1 and distributed.global_state.client is None:
raise Valu... | AsyncManager |
python | sanic-org__sanic | sanic/http/http3.py | {
"start": 8548,
"end": 8674
} | class ____(Receiver): # noqa
"""WebTransport receiver implementation."""
async def run(self): ...
| WebTransportReceiver |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/psycopg.py | {
"start": 21848,
"end": 23365
} | class ____(AsyncAdapt_dbapi_connection):
_connection: AsyncConnection
__slots__ = ()
_cursor_cls = AsyncAdapt_psycopg_cursor
_ss_cursor_cls = AsyncAdapt_psycopg_ss_cursor
def add_notice_handler(self, handler):
self._connection.add_notice_handler(handler)
@property
def info(self):
... | AsyncAdapt_psycopg_connection |
python | Pylons__pyramid | tests/test_viewderivers.py | {
"start": 63103,
"end": 68209
} | class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
self.config = None
testing.tearDown()
def test_add_single_deriver(self):
response = DummyResponse()
response.deriv = False
view = lambda *arg: response
... | TestAddDeriver |
python | fastai__fastai | fastai/torch_core.py | {
"start": 19471,
"end": 20265
} | class ____(TensorImageBase):
_show_args = ArrayMask._show_args
def show(self, ctx=None, **kwargs):
codes = getattr(self, 'codes', None)
if codes is not None: kwargs = merge({'vmin': 0, 'vmax': len(codes)}, kwargs)
return super().show(ctx=ctx, **kwargs)
# %% ../nbs/00_torch_core.ipynb 1... | TensorMask |
python | getsentry__sentry | tests/sentry/api/endpoints/test_system_health.py | {
"start": 82,
"end": 428
} | class ____(APITestCase):
def test_simple(self) -> None:
self.login_as(user=self.user, superuser=True)
url = reverse("sentry-api-0-system-health")
response = self.client.get(url)
assert response.status_code == 200
assert "problems" in response.data
assert "healthy" in ... | SystemHealthTest |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_assorted_poly.py | {
"start": 5342,
"end": 10293
} | class ____(fixtures.MappedTest):
"""test self-referential relationships on polymorphic mappers"""
@classmethod
def define_tables(cls, metadata):
global people, managers, data
people = Table(
"people",
metadata,
Column(
"person_id",
... | RelationshipTest2 |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_block_types.py | {
"start": 15856,
"end": 16614
} | class ____:
async def test_read_block_documents_for_block_type(
self, client, block_type_x, block_document
):
response = await client.get(
f"/block_types/slug/{block_type_x.slug}/block_documents"
)
assert response.status_code == status.HTTP_200_OK
read_block_... | TestReadBlockDocumentsForBlockType |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 132547,
"end": 134498
} | class ____(TestCase):
def test_default_pred(self):
iterable = [0, 1, 1, 0, 1, 0, 0]
for it in (iterable[:], iter(iterable)):
actual = list(mi.rlocate(it))
expected = [4, 2, 1]
self.assertEqual(actual, expected)
def test_no_matches(self):
iterable = [0... | RlocateTests |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF052_0.py | {
"start": 3159,
"end": 3815
} | class ____:
connected: list[Node]
def recurse(self, *, _seen: set[Node] | None = None):
if _seen is None:
_seen = set()
elif self in _seen:
return
_seen.add(self)
for other in self.connected:
other.recurse(_seen=_seen)
def foo():
_dummy... | Node |
python | getsentry__sentry | src/sentry/migrations/0955_org_option_json_field.py | {
"start": 244,
"end": 1763
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | sympy__sympy | sympy/core/logic.py | {
"start": 9826,
"end": 10476
} | class ____(Logic):
def __new__(cls, arg):
if isinstance(arg, str):
return Logic.__new__(cls, arg)
elif isinstance(arg, bool):
return not arg
elif isinstance(arg, Not):
return arg.args[0]
elif isinstance(arg, Logic):
# XXX this is a h... | Not |
python | getsentry__sentry | tests/sentry/uptime/subscriptions/test_tasks.py | {
"start": 18302,
"end": 22678
} | class ____(UptimeTestCase):
def test(self) -> None:
self.run_test(
mode=UptimeMonitorMode.AUTO_DETECTED_ACTIVE,
detector_state=DetectorPriorityLevel.HIGH,
update_date=timezone.now() - timedelta(days=8),
expected_status=ObjectStatus.DISABLED,
expect... | BrokenMonitorCheckerTest |
python | great-expectations__great_expectations | great_expectations/core/run_identifier.py | {
"start": 3905,
"end": 4382
} | class ____(Schema):
run_name = fields.Str()
run_time = fields.AwareDateTime(format="iso", default_timezone=datetime.timezone.utc)
@pre_dump
def prepare_dump(self, data, **kwargs):
data = deepcopy(data)
data.set_run_time_tz(tz=None) # sets to system local tz
return data
@po... | RunIdentifierSchema |
python | kamyu104__LeetCode-Solutions | Python/number-of-same-end-substrings.py | {
"start": 70,
"end": 629
} | class ____(object):
def sameEndSubstringCount(self, s, queries):
"""
:type s: str
:type queries: List[List[int]]
:rtype: List[int]
"""
prefix = [[0]*26]
for i in xrange(len(s)):
prefix.append(prefix[-1][:])
prefix[-1][ord(s[i])-ord('a')... | Solution |
python | joke2k__faker | faker/providers/bank/en_IN/__init__.py | {
"start": 42,
"end": 1194
} | class ____(BankProvider):
"""Implement bank provider for ``en_IN`` locale.
Source: https://en.wikipedia.org/wiki/List_of_banks_in_India
"""
banks = (
"Bank of Baroda",
"Bank of India",
"Bank of Maharashtra",
"Canara Bank",
"Central Bank of India",
"Indian... | Provider |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 8904,
"end": 9029
} | class ____(VyperException):
"""Attempt to perform an action between multiple objects of incompatible types."""
| TypeMismatch |
python | ray-project__ray | python/ray/tests/test_minimal_install.py | {
"start": 924,
"end": 3154
} | class ____:
model_fields = {}
def __init__(self, *args, **kwargs):
pass
def __init_subclass__(self, *args, **kwargs):
pass
def _make_mock_pydantic_modules(pydantic_version: str) -> Dict:
"""Make a mock for the `pydantic` module.
This module requires special handling to:
... | MockBaseModel |
python | PyCQA__pylint | tests/functional/s/super/super_checks.py | {
"start": 2114,
"end": 2283
} | class ____:
not_a_method = 42
def function(self, param):
return param + self.not_a_method
def __getattr__(self, attr):
return attr
| BaseClass |
python | ansible__ansible | test/lib/ansible_test/_internal/become.py | {
"start": 164,
"end": 683
} | class ____(metaclass=abc.ABCMeta):
"""Base class for become implementations."""
@classmethod
def name(cls) -> str:
"""The name of this plugin."""
return cls.__name__.lower()
@property
@abc.abstractmethod
def method(self) -> str:
"""The name of the Ansible become plugin ... | Become |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard_python3/bundled-services/mail/wsgi/main.py | {
"start": 3915,
"end": 4372
} | class ____:
def __call__(self, environ, start_response):
path = environ.get("PATH_INFO", "")
for regex, callable in routes.items():
match = re.search(regex, path)
if match is not None:
return callable(environ, start_response)
start_response("404 Not Fo... | WSGIApplication |
python | paramiko__paramiko | paramiko/agent.py | {
"start": 4003,
"end": 6000
} | class ____(threading.Thread):
"""
Class in charge of communication between two channels.
"""
def __init__(self, agent):
threading.Thread.__init__(self, target=self.run)
self._agent = agent
self._exit = False
def run(self):
try:
(r, addr) = self.get_conne... | AgentProxyThread |
python | tensorflow__tensorflow | tensorflow/python/compiler/xla/xla.py | {
"start": 20716,
"end": 22975
} | class ____(object):
"""A placeholder to capture an object."""
def __init__(self):
self._object = None
def capture(self, o):
if self._object:
raise RuntimeError(
'InternalError: _CapturedObject can capture only once. Please file '
'bug.')
self._object = o
def get(self):
... | _CapturedObject |
python | kubernetes-client__python | kubernetes/client/models/v1_eviction.py | {
"start": 383,
"end": 6690
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1Eviction |
python | pennersr__django-allauth | allauth/headless/account/inputs.py | {
"start": 6196,
"end": 7054
} | class ____(inputs.Input):
current_password = inputs.CharField(required=False)
new_password = inputs.CharField()
def __init__(self, *args, **kwargs):
self.user = kwargs.pop("user")
super().__init__(*args, **kwargs)
self.fields["current_password"].required = self.user.has_usable_passw... | ChangePasswordInput |
python | ray-project__ray | python/ray/llm/_internal/serve/config_generator/utils/models.py | {
"start": 629,
"end": 1014
} | class ____(ServeModel):
type: Literal["TextCompletion"] = TEXT_COMPLETION_MODEL_TYPE
reference_model_id: Optional[str] = Field(
None,
description="This field only exists for custom user entered models whose serving defaults we don't have.",
)
tensor_parallelism: int
lora_config: Opt... | TextCompletionModelConfig |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 260645,
"end": 260990
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("CreatedCommitContribution", graphql_name="node")
| CreatedCommitContributionEdge |
python | ansible__ansible | test/integration/targets/support-callback_plugins/callback_plugins/callback_debug.py | {
"start": 227,
"end": 731
} | class ____(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'callback_debug'
def __init__(self, *args, **kwargs):
super(CallbackModule, self).__init__(*args, **kwargs)
self._display.display('__init__')
for name in (cb for cb in dir(self) if cb.star... | CallbackModule |
python | huggingface__transformers | tests/models/persimmon/test_modeling_persimmon.py | {
"start": 1415,
"end": 2583
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = PersimmonModelTester
pipeline_model_mapping = (
{
"feature-extraction": PersimmonModel,
"text-classification": PersimmonForSequenceClassification,
"token-classification": PersimmonForTokenClassific... | PersimmonModelTest |
python | cython__cython | tests/run/test_patma.py | {
"start": 779,
"end": 1296
} | class ____(unittest.TestCase):
def test_refleaks(self):
# Hunting for leaks using -R doesn't catch leaks in the compiler itself,
# just the code under test. This test ensures that if there are leaks in
# the pattern compiler, those runs will fail:
with open(__file__) as file:
... | TestCompiler |
python | pytorch__pytorch | torch/optim/lr_scheduler.py | {
"start": 17612,
"end": 22331
} | class ____(LRScheduler):
"""Multiply the learning rate of each parameter group by the factor given in the specified function.
When last_epoch=-1, set initial lr as lr.
Args:
optimizer (Optimizer): Wrapped optimizer.
lr_lambda (function or list): A function which computes a multiplicative
... | MultiplicativeLR |
python | python-attrs__attrs | tests/dataclass_transform_example.py | {
"start": 357,
"end": 472
} | class ____:
a: str
d = Frozen("a")
d.a = "new"
reveal_type(d.a) # noqa: F821
@attr.define(frozen=True)
| Frozen |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 3751,
"end": 13231
} | class ____:
# Set of env vars to set for the repro command that is output on test failure.
# Specifically, this includes env vars that are set to non-default values and
# are not implied. Maps from env var name -> value (int)
repro_env_vars: dict = {}
# Defines a flag usable throughout the test sui... | TestEnvironment |
python | huggingface__transformers | src/transformers/models/clvp/modeling_clvp.py | {
"start": 17755,
"end": 18396
} | class ____(nn.Module):
"""
This MLP is used in CLVP speech or text encoder models.
"""
def __init__(self, config):
super().__init__()
self.config = config
self.fc1 = ClvpGatedLinearUnit(config)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
s... | ClvpEncoderMLP |
python | scipy__scipy | scipy/io/matlab/_mio4.py | {
"start": 19563,
"end": 20993
} | class ____:
''' Class for writing matlab 4 format files '''
def __init__(self, file_stream, oned_as=None):
self.file_stream = file_stream
if oned_as is None:
oned_as = 'row'
self.oned_as = oned_as
self._matrix_writer = None
def put_variables(self, mdict, write_he... | MatFile4Writer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py | {
"start": 11769,
"end": 12800
} | class ____(ProjectComponents, GeneratorMixin):
"""
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-project-components/#api-rest-api-3-component-post
"""
def path(self, **kwargs) -> str:
return "component"
def generate(self):
projects_stream = Projects(authenti... | ProjectComponentsGenerator |
python | scipy__scipy | scipy/stats/tests/test_continuous.py | {
"start": 46273,
"end": 61674
} | class ____:
@pytest.mark.parametrize('i, distdata', enumerate(distcont + distdiscrete))
def test_rv_generic(self, i, distdata):
distname = distdata[0]
slow = {'argus', 'exponpow', 'exponweib', 'genexpon', 'gompertz', 'halfgennorm',
'johnsonsb', 'kappa4', 'ksone', 'kstwo', 'kstwo... | TestMakeDistribution |
python | ansible__ansible | test/units/_internal/templating/fixtures/valid_collection/ansible_collections/valid/also_valid/plugins/lookup/runtime_error.py | {
"start": 84,
"end": 212
} | class ____(LookupBase):
def run(self, terms, variables=None, **kwargs) -> list:
raise NotImplementedError()
| LookupModule |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py | {
"start": 1176,
"end": 1307
} | class ____(CloudflareAIGatewayError):
"""Raised when AI Gateway does not exist."""
pass
| CloudflareAIGatewayDoesNotExistError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol19.py | {
"start": 558,
"end": 625
} | class ____(NamedTuple):
x: int
@dataclass(frozen=True)
| ConcreteC1 |
python | scikit-image__scikit-image | tests/skimage/color/test_colorconv.py | {
"start": 1361,
"end": 37344
} | class ____:
img_rgb = data.colorwheel()
img_grayscale = data.camera()
img_rgba = np.array([[[0, 0.5, 1, 0], [0, 0.5, 1, 1], [0, 0.5, 1, 0.5]]]).astype(
float
)
img_stains = img_as_float(img_rgb) * 0.3
colbars = np.array(
[[1, 1, 0, 0, 1, 1, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0], [1, 0... | TestColorconv |
python | getsentry__sentry | src/sentry/core/endpoints/scim/teams.py | {
"start": 4750,
"end": 9835
} | class ____(SCIMEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
permission_classes = (OrganizationSCIMTeamPermission,)
@extend_schema(
operation_id="List an Organization's Paginated Teams",
parameters=[GlobalParams.ORG_ID_O... | OrganizationSCIMTeamIndex |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/retrieval.py | {
"start": 154,
"end": 451
} | class ____(BaseEvent):
"""
RetrievalStartEvent.
Args:
str_or_query_bundle (QueryType): Query bundle.
"""
str_or_query_bundle: QueryType
@classmethod
def class_name(cls) -> str:
"""Class name."""
return "RetrievalStartEvent"
| RetrievalStartEvent |
python | getsentry__sentry | src/sentry/identity/oauth2.py | {
"start": 9149,
"end": 15032
} | class ____:
access_token_url: str | None = None
client_id: str | None = None
client_secret: str | None = None
def __init__(self, access_token_url=None, client_id=None, client_secret=None, *args, **kwargs):
super().__init__(*args, **kwargs)
if access_token_url is not None:
se... | OAuth2CallbackView |
python | pytorch__pytorch | torchgen/gen_vmap_plumbing.py | {
"start": 8861,
"end": 9391
} | class ____:
@method_with_native_function
def __call__(self, f: NativeFunction) -> str | None:
result = gen_vmap_plumbing(f)
return result
def gen_all_vmap_plumbing(native_functions: Sequence[NativeFunction]) -> str:
body = "\n".join(list(mapMaybe(ComputeBatchRulePlumbing(), native_function... | ComputeBatchRulePlumbing |
python | nedbat__coveragepy | tests/test_api.py | {
"start": 24344,
"end": 28502
} | class ____(CoverageTest):
"""Tests of the .switch_context() method."""
def make_test_files(self) -> None:
"""Create a simple file representing a method with two tests."""
self.make_file(
"testsuite.py",
"""\
def timestwo(x):
return x*2
... | SwitchContextTest |
python | PrefectHQ__prefect | tests/utilities/test_timeout.py | {
"start": 106,
"end": 868
} | class ____(TimeoutError): ...
def test_timeout_raises_custom_error_type_sync():
with pytest.raises(CustomTimeoutError):
with timeout(seconds=0.1, timeout_exc_type=CustomTimeoutError):
time.sleep(1)
async def test_timeout_raises_custom_error_type_async():
with pytest.raises(CustomTimeoutE... | CustomTimeoutError |
python | pytorch__pytorch | torch/distributed/checkpoint/metadata.py | {
"start": 3271,
"end": 3406
} | class ____:
properties: TensorProperties
size: torch.Size
chunks: list[ChunkStorageMetadata]
@dataclass
| TensorStorageMetadata |
python | ApeWorX__ape | tests/functional/test_explorer.py | {
"start": 210,
"end": 772
} | class ____(ExplorerAPI):
def get_transaction_url(self, transaction_hash: str) -> str:
return ""
def get_address_url(self, address: "AddressType") -> str:
return ""
def get_contract_type(self, address: "AddressType") -> Optional["ContractType"]:
return None
def publish_contract... | MyExplorer |
python | huggingface__transformers | src/transformers/models/mllama/processing_mllama.py | {
"start": 6647,
"end": 16870
} | class ____(ProcessorMixin):
r"""
Constructs a Mllama processor which wraps [`MllamaImageProcessor`] and
[`PretrainedTokenizerFast`] into a single processor that inherits both the image processor and
tokenizer functionalities. See the [`~MllamaProcessor.__call__`] and [`~OwlViTProcessor.decode`] for more... | MllamaProcessor |
python | ansible__ansible | test/integration/targets/template/role_filter/filter_plugins/myplugin.py | {
"start": 60,
"end": 201
} | class ____(object):
def filters(self):
return {'parse_ip': self.parse_ip}
def parse_ip(self, ip):
return ip
| FilterModule |
python | run-llama__llama_index | llama-index-core/llama_index/core/voice_agents/websocket.py | {
"start": 164,
"end": 1671
} | class ____(ABC):
"""
Abstract base class for a voice agent websocket.
Attributes:
uri (str): URL of the websocket.
ws (Optional[ClientConnection]): Private attribute, initialized as None, represents the websocket client.
"""
def __init__(
self,
uri: str,
):
... | BaseVoiceAgentWebsocket |
python | ray-project__ray | python/ray/dag/tests/experimental/test_torch_tensor_transport.py | {
"start": 9055,
"end": 11872
} | class ____:
"""Tests driver to worker tensor transport with default device."""
def create_and_execute_dag(self, actor, device, tensor_input, is_dict=False):
"""Create a DAG with tensor transport and execute it."""
with InputNode() as inp:
method = actor.echo_dict_device if is_dict e... | TestDriverToWorkerDeviceDefault |
python | huggingface__transformers | src/transformers/models/superpoint/image_processing_superpoint.py | {
"start": 3760,
"end": 16471
} | class ____(BaseImageProcessor):
r"""
Constructs a SuperPoint image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden
by `do_resize` in the `preproc... | SuperPointImageProcessor |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 57453,
"end": 59116
} | class ____(_CreateBase):
# create an EIP1167 "minimal proxy" to the target contract
_id = "create_minimal_proxy_to"
_inputs = [("target", AddressT())]
def _add_gas_estimate(self, args, should_use_create2):
a, b, c = eip1167_bytecode()
bytecode_len = 20 + len(b) + len(c)
return ... | CreateMinimalProxyTo |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 90075,
"end": 94843
} | class ____(VariableTracker):
_nonvar_fields = {
"fn",
"wrapped_fn",
"traceable_fn",
*VariableTracker._nonvar_fields,
}
@classmethod
@functools.cache
def _get_polyfill_handlers(cls) -> dict[Callable[..., Any], types.FunctionType]:
return {}
@classmethod
... | PolyfilledFunctionVariable |
python | falconry__falcon | tests/test_http_method_routing.py | {
"start": 2347,
"end": 2697
} | class ____:
pass
def capture(func):
@wraps(func)
def with_capture(*args, **kwargs):
self = args[0]
self.called = True
self.req, self.resp = args[1:]
func(*args, **kwargs)
return with_capture
def selfless_decorator(func):
def faulty(req, resp, foo, bar):
p... | Stonewall |
python | huggingface__transformers | src/transformers/models/xlm/modeling_xlm.py | {
"start": 17511,
"end": 22539
} | class ____(nn.Module):
r"""
Compute a single vector summary of a sequence hidden states.
Args:
config ([`XLMConfig`]):
The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
config class of your model for the default values... | XLMSequenceSummary |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.