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 | crytic__slither | slither/tools/mutator/mutators/RR.py | {
"start": 214,
"end": 1748
} | class ____(AbstractMutator): # pylint: disable=too-few-public-methods
NAME = "RR"
HELP = "Revert Replacement"
def _mutate(self) -> Dict:
result: Dict = {}
for function in self.contract.functions_and_modifiers_declared:
for node in function.nodes:
if not self.sh... | RR |
python | joke2k__faker | tests/providers/test_lorem.py | {
"start": 30588,
"end": 33409
} | class ____:
"""Test vi_VN lorem provider"""
word_list = [word.lower() for word in ViVNLoremProvider.word_list]
def test_paragraph(self, faker, num_samples):
num_sentences = 10
for _ in range(num_samples):
paragraph = faker.paragraph(nb_sentences=num_sentences)
asser... | TestViVn |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc_metastore.py | {
"start": 23039,
"end": 26074
} | class ____(GoogleCloudBaseOperator):
"""
Delete a single service.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param service_id: Required. The ID of the metastor... | DataprocMetastoreDeleteServiceOperator |
python | huggingface__transformers | src/transformers/models/edgetam/modular_edgetam.py | {
"start": 6115,
"end": 6165
} | class ____(Sam2LayerNorm):
pass
| EdgeTamLayerNorm |
python | jazzband__django-model-utils | tests/test_fields/test_field_tracker.py | {
"start": 34087,
"end": 35168
} | class ____(FieldTrackedModelMultiTests):
tracked_class = ModelTrackedMultiple
def test_pre_save_has_changed(self) -> None:
self.tracker = self.instance.name_tracker
self.assertHasChanged(name=True, number=True)
self.instance.name = 'new age'
self.assertHasChanged(name=True, num... | ModelTrackedModelMultiTests |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_projects_tasks.py | {
"start": 1938,
"end": 3735
} | class ____(TestCase):
@patch("readthedocs.projects.tasks.utils.app")
def test_finish_unhealthy_builds_task(self, mocked_app):
project = get(Project)
feature = get(Feature, feature_id=Feature.BUILD_HEALTHCHECK)
feature.projects.add(project)
# Build just started with the default ... | TestFinishInactiveBuildsTask |
python | django__django | django/views/generic/dates.py | {
"start": 22209,
"end": 26913
} | class ____(SingleObjectTemplateResponseMixin, BaseDateDetailView):
"""
Detail view of a single object on a single date; this differs from the
standard DetailView by accepting a year/month/day in the URL.
"""
template_name_suffix = "_detail"
def _date_from_string(
year, year_format, month="", ... | DateDetailView |
python | apache__airflow | providers/standard/tests/unit/standard/sensors/test_time_delta.py | {
"start": 1964,
"end": 5274
} | class ____:
def setup_method(self):
self.dagbag = DagBag(dag_folder=DEV_NULL, include_examples=False)
self.dag = DAG(TEST_DAG_ID, schedule=timedelta(days=1), start_date=DEFAULT_DATE)
def test_timedelta_sensor(self, mocker):
op = TimeDeltaSensor(task_id="timedelta_sensor_check", delta=ti... | TestTimedeltaSensor |
python | google__jax | jax/_src/internal_test_util/export_back_compat_test_util.py | {
"start": 6222,
"end": 16339
} | class ____(jtu.JaxTestCase):
"""Base class with helper functions for backward compatibility tests."""
def default_jax_backend(self) -> str:
# Canonicalize to turn into "cuda" or "rocm"
return xb.canonicalize_platform(xb.default_backend())
def starter_data(self, inputs: Sequence[np.ndarray]) -> CompatTest... | CompatTestBase |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_float.py | {
"start": 32760,
"end": 36911
} | class ____(__TestCase):
def test_format(self):
# these should be rewritten to use both format(x, spec) and
# x.__format__(spec)
self.assertEqual(format(0.0, 'f'), '0.000000')
# the default is 'g', except for empty format spec
self.assertEqual(format(0.0, ''), '0.0')
... | FormatTestCase |
python | paramiko__paramiko | paramiko/ssh_exception.py | {
"start": 7323,
"end": 7494
} | class ____(SSHException):
"""
Out-of-order protocol messages were received, violating "strict kex" mode.
.. versionadded:: 3.4
"""
pass
| MessageOrderError |
python | getsentry__sentry | src/sentry/uptime/types.py | {
"start": 3405,
"end": 3674
} | class ____(enum.IntEnum):
# Manually created by a user
MANUAL = 1
# Auto-detected by our system and in the onboarding stage
AUTO_DETECTED_ONBOARDING = 2
# Auto-detected by our system and actively monitoring
AUTO_DETECTED_ACTIVE = 3
| UptimeMonitorMode |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/scrutineer.py | {
"start": 1696,
"end": 8729
} | class ____:
"""A super-simple branch coverage tracer."""
__slots__ = (
"_previous_location",
"_should_trace",
"_tried_and_failed_to_trace",
"branches",
)
def __init__(self, *, should_trace: bool) -> None:
self.branches: Trace = set()
self._previous_locat... | Tracer |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1101294,
"end": 1108494
} | class ____(OffsetDef):
"""
ScaleDatumDef schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
and at the ... | ScaleDatumDef |
python | Textualize__textual | src/textual/containers.py | {
"start": 4317,
"end": 4582
} | class ____(Widget):
"""A non-expanding container with vertical layout and no scrollbars."""
DEFAULT_CSS = """
VerticalGroup {
width: 1fr;
height: auto;
layout: vertical;
overflow: hidden hidden;
}
"""
| VerticalGroup |
python | fluentpython__example-code | 19-dyn-attr-prop/oscon/schedule2.py | {
"start": 1125,
"end": 1238
} | class ____(RuntimeError):
"""Raised when a database is required but was not set.""" # <1>
| MissingDatabaseError |
python | jazzband__django-oauth-toolkit | tests/custom_hasher.py | {
"start": 63,
"end": 251
} | class ____(PBKDF2PasswordHasher):
"""
A subclass of PBKDF2PasswordHasher that uses less iterations.
"""
algorithm = "fast_pbkdf2"
iterations = 10000
| MyPBKDF2PasswordHasher |
python | Netflix__metaflow | metaflow/plugins/aws/batch/batch_client.py | {
"start": 25468,
"end": 25554
} | class ____(Exception):
def __init__(self, ex):
self.ex = ex
| TriableException |
python | certifi__python-certifi | certifi/tests/test_certify.py | {
"start": 44,
"end": 467
} | class ____(unittest.TestCase):
def test_cabundle_exists(self) -> None:
assert os.path.exists(certifi.where())
def test_read_contents(self) -> None:
content = certifi.contents()
assert "-----BEGIN CERTIFICATE-----" in content
def test_py_typed_exists(self) -> None:
assert os... | TestCertifi |
python | numpy__numpy | tools/swig/test/testVector.py | {
"start": 11956,
"end": 12219
} | class ____(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "uint"
self.typeCode = "I"
######################################################################
| uintTestCase |
python | openai__openai-python | tests/api_resources/chat/test_completions.py | {
"start": 495,
"end": 15982
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@parametrize
def test_method_create_overload_1(self, client: OpenAI) -> None:
completion = client.chat.completions.create(
messages=[
{
... | TestCompletions |
python | pallets__jinja | src/jinja2/runtime.py | {
"start": 12539,
"end": 18638
} | class ____:
"""A wrapper iterable for dynamic ``for`` loops, with information
about the loop and iteration.
"""
#: Current iteration of the loop, starting at 0.
index0 = -1
_length: int | None = None
_after: t.Any = missing
_current: t.Any = missing
_before: t.Any = missing
_la... | LoopContext |
python | un33k__django-uuslug | uuslug/tests/tests.py | {
"start": 9129,
"end": 10029
} | class ____(TestCase):
"""Tests for Slug - Max length less than field length"""
def test_manager(self):
name = "john" * 51
with self.assertNumQueries(2):
obj = CoolSlug.objects.create(name=name)
self.assertEqual(obj.slug, name[:200])
with self.assertNumQueries(3):
... | SlugMaxLengthTestCase |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 48567,
"end": 50291
} | class ____(RegexLexer):
"""
Coldfusion statements
"""
name = 'cfstatement'
aliases = ['cfs']
filenames = []
mimetypes = []
flags = re.IGNORECASE
tokens = {
'root': [
(r'//.*?\n', Comment.Single),
(r'/\*(?:.|\n)*?\*/', Comment.Multiline),
(... | ColdfusionLexer |
python | coleifer__peewee | peewee.py | {
"start": 33476,
"end": 37943
} | class ____(Node):
_converter = None
@Node.copy
def converter(self, converter=None):
self._converter = converter
def alias(self, alias):
if alias:
return Alias(self, alias)
return self
def unalias(self):
return self
def bind_to(self, dest):
... | ColumnBase |
python | python-openxml__python-docx | tests/oxml/test__init__.py | {
"start": 1830,
"end": 3214
} | class ____:
def it_accepts_bytes_and_assumes_utf8_encoding(self, xml_bytes):
parse_xml(xml_bytes)
def it_accepts_unicode_providing_there_is_no_encoding_declaration(self):
non_enc_decl = '<?xml version="1.0" standalone="yes"?>'
enc_decl = '<?xml version="1.0" encoding="UTF-8" standalone=... | DescribeParseXml |
python | google__jax | tests/array_extensibility_test.py | {
"start": 18332,
"end": 21033
} | class ____(jtu.JaxTestCase):
@parameterized.named_parameters(
{'testcase_name': api.name(), 'api': api} for api in NUMPY_APIS)
def test_numpy_api_supports_jax_array(self, api):
if api.skip_on_devices and jtu.test_device_matches(api.skip_on_devices):
self.skipTest(f'{api.name()} not supported on {api... | JaxArrayTests |
python | viewflow__viewflow | tests/test_middleware.py | {
"start": 374,
"end": 852
} | class ____(AppMenuMixin, Viewset):
index_path = path(
"", TemplateView.as_view(template_name="viewflow/base.html"), name="index"
)
nested_path = route("nested/", NestedViewset())
site = Site(
title="Test site",
viewsets=[
Application(
app_name="test",
viewse... | CityViewset |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 32120,
"end": 32893
} | class ____(BaseModel):
type: Literal["PageIncrement"]
page_size: Optional[Union[int, str]] = Field(
None,
description="The number of records to include in each pages.",
examples=[100, "100", "{{ config['page_size'] }}"],
title="Page Size",
)
start_from_page: Optional[int]... | PageIncrement |
python | pytorch__pytorch | torch/optim/nadam.py | {
"start": 586,
"end": 26761
} | class ____(Optimizer): # noqa: D101
def __init__(
self,
params: ParamsT,
lr: Union[float, Tensor] = 2e-3,
betas: tuple[float, float] = (0.9, 0.999),
eps: float = 1e-8,
weight_decay: float = 0,
momentum_decay: float = 4e-3,
decoupled_weight_decay: bool... | NAdam |
python | huggingface__transformers | src/transformers/models/afmoe/modeling_afmoe.py | {
"start": 2118,
"end": 5155
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: AfmoeConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.c... | AfmoeRotaryEmbedding |
python | getsentry__sentry | src/sentry/tagstore/types.py | {
"start": 3605,
"end": 3783
} | class ____(TypedDict, total=False):
uniqueValues: int | None
totalValues: int | None
topValues: list[TagValueSerializerResponse] | None
| TagKeySerializerResponseOptional |
python | streamlit__streamlit | lib/streamlit/runtime/caching/cached_message_replay.py | {
"start": 3860,
"end": 10691
} | class ____(threading.local):
"""A utility for storing messages generated by `st` commands called inside
a cached function.
Data is stored in a thread-local object, so it's safe to use an instance
of this class across multiple threads.
"""
def __init__(self, cache_type: CacheType) -> None:
... | CachedMessageReplayContext |
python | numba__numba | numba/cuda/cudadrv/nvvm.py | {
"start": 14569,
"end": 24107
} | class ____(object):
_cache_ = None
def __init__(self):
if self._cache_ is None:
if get_libdevice() is None:
raise RuntimeError(MISSING_LIBDEVICE_FILE_MSG)
self._cache_ = open_libdevice()
self.bc = self._cache_
def get(self):
return self.bc
... | LibDevice |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor2.py | {
"start": 381,
"end": 473
} | class ____(Animal[_T3, int]):
def __init__(self, p1: _T3 | None = None):
pass
| Bear |
python | astropy__astropy | astropy/coordinates/builtin_frames/ecliptic.py | {
"start": 4012,
"end": 5195
} | class ____(BaseEclipticFrame):
"""
Geocentric true ecliptic coordinates. These origin of the coordinates are the
geocenter (Earth), with the x axis pointing to the *true* (not mean) equinox
at the time specified by the ``equinox`` attribute, and the xy-plane in the
plane of the ecliptic for that da... | GeocentricTrueEcliptic |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 1488,
"end": 2097
} | class ____:
x: int | None = attr.ib(converter=attr.converters.optional(int))
ConvCOptional(1)
ConvCOptional(None)
# XXX: Fails with E: Unsupported converter, only named functions, types and lambdas are currently supported [misc]
# See https://github.com/python/mypy/issues/15736
#
# @attr.s
# class ConvCPipe:
#... | ConvCOptional |
python | apache__airflow | airflow-core/src/airflow/jobs/triggerer_job_runner.py | {
"start": 10397,
"end": 28056
} | class ____(WatchedSubprocess):
"""
TriggerRunnerSupervisor is responsible for monitoring the subprocess and marshalling DB access.
This class (which runs in the main/sync process) is responsible for querying the DB, sending RunTrigger
workload messages to the subprocess, and collecting results and upda... | TriggerRunnerSupervisor |
python | sqlalchemy__sqlalchemy | examples/association/basic_association.py | {
"start": 1342,
"end": 1764
} | class ____(Base):
__tablename__ = "item"
item_id: Mapped[int] = mapped_column(primary_key=True)
description: Mapped[str] = mapped_column(String(30))
price: Mapped[float]
def __init__(self, description: str, price: float) -> None:
self.description = description
self.price = price
... | Item |
python | PrefectHQ__prefect | src/integrations/prefect-redis/prefect_redis/messaging.py | {
"start": 6391,
"end": 9559
} | class ____(_Publisher):
def __init__(
self,
topic: str,
cache: _Cache,
deduplicate_by: Optional[str] = None,
batch_size: Optional[int] = None,
publish_every: Optional[timedelta] = None,
):
settings = RedisMessagingPublisherSettings()
self.stream =... | Publisher |
python | apache__airflow | providers/common/sql/tests/unit/common/sql/hooks/test_sql.py | {
"start": 8101,
"end": 12375
} | class ____:
def setup_method(self, **kwargs):
logging.root.disabled = True
@pytest.mark.db_test
@pytest.mark.parametrize(
"empty_statement",
[
pytest.param([], id="Empty list"),
pytest.param("", id="Empty string"),
pytest.param("\n", id="Only EOL"... | TestDbApiHook |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/editorstack/helpers.py | {
"start": 4291,
"end": 7319
} | class ____(QObject):
"""File properties."""
todo_results_changed = Signal()
sig_save_bookmarks = Signal(str, str)
text_changed_at = Signal(str, tuple)
edit_goto = Signal(str, int, str)
sig_send_to_help = Signal(str, str, bool)
sig_filename_changed = Signal(str)
sig_show_object_info = Sig... | FileInfo |
python | cython__cython | docs/examples/userguide/extension_types/wrapper_class.py | {
"start": 174,
"end": 2160
} | class ____:
"""A wrapper class for a C/C++ data structure"""
_ptr: cython.pointer[my_c_struct]
ptr_owner: cython.bint
def __cinit__(self):
self.ptr_owner = False
def __dealloc__(self):
# De-allocate if not null and flag is set
if self._ptr is not cython.NULL and self.ptr_ow... | WrapperClass |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/components/reward_providers/base_reward_provider.py | {
"start": 278,
"end": 2891
} | class ____(ABC):
def __init__(self, specs: BehaviorSpec, settings: RewardSignalSettings) -> None:
self._policy_specs = specs
self._gamma = settings.gamma
self._strength = settings.strength
self._ignore_done = False
@property
def gamma(self) -> float:
"""
The ... | BaseRewardProvider |
python | scrapy__scrapy | tests/test_engine_stop_download_bytes.py | {
"start": 427,
"end": 618
} | class ____(CrawlerRun):
def bytes_received(self, data, request, spider):
super().bytes_received(data, request, spider)
raise StopDownload(fail=False)
| BytesReceivedCrawlerRun |
python | ray-project__ray | python/ray/serve/_private/logging_utils.py | {
"start": 1409,
"end": 2623
} | class ____(logging.Filter):
"""Serve component filter.
The filter will add the component name, id, and type to the log record.
"""
def __init__(
self,
component_name: str,
component_id: str,
component_type: Optional[ServeComponentType] = None,
):
self.compon... | ServeComponentFilter |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 44180,
"end": 44497
} | class ____(StructModel):
"""Model for a mutable struct.
A reference to the payload
"""
def __init__(self, dmm, fe_typ):
dtype = fe_typ.get_data_type()
members = [
("meminfo", types.MemInfoPointer(dtype)),
]
super().__init__(dmm, fe_typ, members)
| StructRefModel |
python | miyuchina__mistletoe | mistletoe/contrib/md2jira.py | {
"start": 2339,
"end": 3547
} | class ____:
def __init__(self):
self.version = "1.0.2"
self.options = {}
self.options['output'] = '-'
def run(self, optlist, args):
for o, i in optlist:
if o in ('-h', '--help'):
sys.stderr.write(usageString + '\n')
sys.stderr.write(h... | MarkdownToJira |
python | google__jax | tests/pallas/pallas_test.py | {
"start": 92751,
"end": 92873
} | class ____(PallasCallNamedGridTest):
INTERPRET = True
@dataclasses.dataclass(frozen=True)
| PallasCallNamedGridInterpretTest |
python | graphql-python__graphene | graphene/types/interface.py | {
"start": 259,
"end": 397
} | class ____(BaseOptions):
fields = None # type: Dict[str, Field]
interfaces = () # type: Iterable[Type[Interface]]
| InterfaceOptions |
python | huggingface__transformers | src/transformers/models/vjepa2/modeling_vjepa2.py | {
"start": 42102,
"end": 45099
} | class ____(VJEPA2PreTrainedModel):
def __init__(self, config: VJEPA2Config):
super().__init__(config)
self.num_labels = config.num_labels
self.vjepa2 = VJEPA2Model(config)
# Classifier head
self.pooler = VJEPA2AttentivePooler(config)
self.classifier = nn.Linear(conf... | VJEPA2ForVideoClassification |
python | sanic-org__sanic | sanic/cli/arguments.py | {
"start": 4467,
"end": 5121
} | class ____(Group):
name = "Socket binding"
def attach(self):
self.container.add_argument(
"-H",
"--host",
dest="host",
type=str,
help="Host address [default 127.0.0.1]",
)
self.container.add_argument(
"-p",
... | SocketGroup |
python | ray-project__ray | python/ray/tune/tests/test_trial_scheduler_resource_changing.py | {
"start": 6613,
"end": 10771
} | class ____(TestUniformResourceAllocation):
def testAllocateFreeResources(self):
scheduler = ResourceChangingScheduler(
resources_allocation_function=DistributeResources(add_bundles=True)
)
base_pgf = PlacementGroupFactory([{"CPU": 1, "GPU": 0}])
trial1, trial2, trial3, t... | TestUniformResourceAllocationAddBundles |
python | pytorch__pytorch | torch/utils/benchmark/utils/_stubs.py | {
"start": 120,
"end": 497
} | class ____(Protocol):
"""This is the portion of the `timeit.Timer` API used by benchmark utils."""
def __init__(
self,
stmt: str,
setup: str,
timer: Callable[[], float],
globals: dict[str, Any],
**kwargs: Any,
) -> None:
...
def timeit(self, numbe... | TimerClass |
python | django-extensions__django-extensions | django_extensions/mongodb/fields/json.py | {
"start": 1197,
"end": 2130
} | class ____(StringField):
"""
JSONField is a generic textfield that neatly serializes/unserializes
JSON objects seamlessly. Main object must be a dict object.
"""
def __init__(self, *args, **kwargs):
if "default" not in kwargs:
kwargs["default"] = "{}"
StringField.__init_... | JSONField |
python | optuna__optuna | optuna/cli.py | {
"start": 12274,
"end": 12775
} | class ____(_BaseCommand):
"""Delete a specified study."""
def add_arguments(self, parser: ArgumentParser) -> None:
parser.add_argument("--study-name", default=None, help="The name of the study to delete.")
def take_action(self, parsed_args: Namespace) -> int:
storage = _get_storage(parsed_... | _DeleteStudy |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 16279,
"end": 20906
} | class ____(test.TestCase):
def testEmpty(self):
inp = np.random.rand(4, 4).astype("f")
for k in xrange(4):
with self.cached_session(use_gpu=True):
a = constant_op.constant(inp, shape=[4, 4], dtype=dtypes.float32)
slice_t = a[2, k:k]
slice_val = self.evaluate(slice_t)
self.... | SliceTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-drive/source_google_drive/exceptions.py | {
"start": 139,
"end": 205
} | class ____(BaseFileBasedSourceError):
pass
| ErrorFetchingMetadata |
python | Textualize__rich | examples/fullscreen.py | {
"start": 1932,
"end": 5492
} | class ____:
"""Display header with clock."""
def __rich__(self) -> Panel:
grid = Table.grid(expand=True)
grid.add_column(justify="center", ratio=1)
grid.add_column(justify="right")
grid.add_row(
"[b]Rich[/b] Layout application",
datetime.now().ctime().rep... | Header |
python | huggingface__transformers | src/transformers/models/flex_olmo/modeling_flex_olmo.py | {
"start": 15333,
"end": 16423
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.top_k = config.num_experts_per_tok
self.num_experts = config.num_experts
self.norm_topk_prob = config.norm_topk_prob
self.hidden_dim = config.hidden_size
self.weight = nn.Parameter(torch.zeros(... | FlexOlmoTopKRouter |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 87336,
"end": 89295
} | class ____(AwsBaseOperator[SageMakerHook]):
"""
Delete a notebook instance.
.. seealso:
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerDeleteNotebookOperator`
:param instance_name: The name of the notebook instance to delete.
... | SageMakerDeleteNotebookOperator |
python | getsentry__sentry | src/sentry/tasks/symbolication.py | {
"start": 2620,
"end": 13164
} | class ____(Exception):
pass
def _do_symbolicate_event(
task_kind: SymbolicatorTaskKind,
cache_key: str,
start_time: float | None,
event_id: str | None,
data: Event | None = None,
queue_switches: int = 0,
has_attachments: bool = False,
symbolicate_platforms: list[SymbolicatorPlatfor... | SymbolicationTimeout |
python | sympy__sympy | sympy/physics/quantum/tests/test_represent.py | {
"start": 1856,
"end": 5177
} | class ____(Operator):
def _represent_default_basis(self, **options):
return self._represent_AOp(None, **options)
def _represent_AOp(self, basis, **options):
return Bmat
k = AKet('a')
b = ABra('a')
A = AOp('A')
B = BOp('B')
_tests = [
# Bra
(b, Dagger(Avec)),
(Dagger(b), Avec),
... | BOp |
python | ray-project__ray | doc/source/serve/doc_code/monitoring/monitoring.py | {
"start": 193,
"end": 486
} | class ____:
async def __call__(self, request: Request) -> str:
logger.info("Hello world!")
return "hi"
say_hello = SayHello.bind()
# __end__
# serve.run(say_hello)
# import requests
# response = requests.get("http://localhost:8000/")
# assert response.text == "hi"
| SayHello |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_group_search_view_starred_order.py | {
"start": 680,
"end": 1085
} | class ____(serializers.Serializer):
view_ids = serializers.ListField(child=serializers.IntegerField(), required=True, min_length=0)
def validate_view_ids(self, view_ids):
if len(view_ids) != len(set(view_ids)):
raise serializers.ValidationError("Single view cannot take up multiple positions... | GroupSearchViewStarredOrderSerializer |
python | Textualize__textual | src/textual/cache.py | {
"start": 437,
"end": 6526
} | class ____(Generic[CacheKey, CacheValue]):
"""
A dictionary-like container with a maximum size.
If an additional item is added when the LRUCache is full, the least
recently used key is discarded to make room for the new item.
The implementation is similar to functools.lru_cache, which uses a (doub... | LRUCache |
python | kevin1024__vcrpy | tests/unit/test_vcr.py | {
"start": 11250,
"end": 12419
} | class ____(VCR().test_case()):
def no_decoration(self):
assert httplib.HTTPConnection == _HTTPConnection
self.test_dynamically_added()
assert httplib.HTTPConnection == _HTTPConnection
def test_one(self):
with force_reset():
self.no_decoration()
with force_res... | TestVCRClass |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_assorted_poly.py | {
"start": 49455,
"end": 52060
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global base_item_table, item_table
global base_item_collection_table, collection_table
base_item_table = Table(
"base_item",
metadata,
Column(
"id", Integer... | ManyToManyPolyTest |
python | imageio__imageio | imageio/plugins/spe.py | {
"start": 13810,
"end": 32159
} | class ____(PluginV3):
def __init__(
self,
request: Request,
check_filesize: bool = True,
char_encoding: Optional[str] = None,
sdt_meta: Optional[bool] = None,
) -> None:
"""Instantiate a new SPE file plugin object
Parameters
----------
req... | SpePlugin |
python | mkdocs__mkdocs | mkdocs/config/config_options.py | {
"start": 5886,
"end": 8051
} | class ____(Generic[T], BaseConfigOption[List[T]]):
"""
Validates a homogeneous list of items.
E.g. for `config_options.ListOfItems(config_options.Type(int))` a valid item is `[1, 2, 3]`.
"""
required: bool | None = None # Only for subclasses to set.
def __init__(self, option_type: BaseConfig... | ListOfItems |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py | {
"start": 328,
"end": 1097
} | class ____(ParentA[_T1]): ...
def func1(a: ParentA[int], b: ParentA[str] | ParentA[complex]) -> None:
if isinstance(a, ChildA1):
reveal_type(a, expected_text="ChildA1[int]")
if isinstance(b, ChildA1):
reveal_type(b, expected_text="ChildA1[str] | ChildA1[complex]")
def func2(
a: type[Par... | ChildA1 |
python | getsentry__sentry | src/sentry/migrations/0968_delete_dashboardwidgetsnapshot_db_constraint.py | {
"start": 222,
"end": 1712
} | 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 | getsentry__sentry | src/sentry/identity/vsts/provider.py | {
"start": 2076,
"end": 5327
} | class ____(OAuth2Provider):
key = IntegrationProviderSlug.AZURE_DEVOPS.value
name = "Azure DevOps"
oauth_access_token_url = "https://app.vssps.visualstudio.com/oauth2/token"
oauth_authorize_url = "https://app.vssps.visualstudio.com/oauth2/authorize"
def get_oauth_client_id(self):
return op... | VSTSIdentityProvider |
python | google__python-fire | fire/parser_fuzz_test.py | {
"start": 821,
"end": 3041
} | class ____(testutils.BaseTestCase):
@settings(max_examples=10000)
@given(st.text(min_size=1))
@example('True')
@example(r'"test\t\t\a\\a"')
@example(r' "test\t\t\a\\a" ')
@example('"(1, 2)"')
@example('(1, 2)')
@example('(1, 2)')
@example('(1, 2) ')
@example('a,b,c,d')
@... | ParserFuzzTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/dispute.py | {
"start": 465,
"end": 1106
} | class ____(CatalogModel):
amount_disputed: Decimal
amount_won: Decimal
case_number: str
chargeback_protection_level: Optional[str]
created_at: datetime
currency_iso_code: str
evidence: Union[Evidence, List[Evidence]]
graphql_id: str
id: str
kind: str
merchant_account_id: str
... | Dispute |
python | kamyu104__LeetCode-Solutions | Python/number-of-people-aware-of-a-secret.py | {
"start": 34,
"end": 451
} | class ____(object):
def peopleAwareOfSecret(self, n, delay, forget):
"""
:type n: int
:type delay: int
:type forget: int
:rtype: int
"""
MOD = 10**9+7
dp = [0]*forget
dp[0] = 1
for i in xrange(1, n):
dp[i%forget] = ((dp[(i-1... | Solution |
python | spack__spack | lib/spack/spack/vendor/jinja2/bccache.py | {
"start": 6155,
"end": 9802
} | class ____(BytecodeCache):
"""A bytecode cache that stores bytecode on the filesystem. It accepts
two arguments: The directory where the cache items are stored and a
pattern string that is used to build the filename.
If no directory is specified a default cache directory is selected. On
Windows t... | FileSystemBytecodeCache |
python | getsentry__sentry | src/sentry/api/serializers/models/group_stream.py | {
"start": 6907,
"end": 7007
} | class ____(TypedDict, total=False):
stats: dict[str, dict[int, list[tuple[int, int]]]]
| _MaybeStats |
python | getsentry__sentry-python | tests/integrations/mcp/test_mcp.py | {
"start": 2310,
"end": 2834
} | class ____:
"""Mock HTTP request for SSE/StreamableHTTP transport"""
def __init__(self, session_id=None, transport="http"):
self.headers = {}
self.query_params = {}
if transport == "sse":
# SSE transport uses query parameter
if session_id:
self.q... | MockHTTPRequest |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 3503,
"end": 4330
} | class ____(ANTLRException):
def __init__(self, *args):
ANTLRException.__init__(self, *args)
self.fileName = None
self.line = -1
self.column = -1
if len(args) >= 2:
self.fileName = args[1]
if len(args) >= 3:
self.line = args[2]
if len(a... | RecognitionException |
python | qdrant__qdrant-client | qdrant_client/http/api/service_api.py | {
"start": 1311,
"end": 4085
} | class ____:
def __init__(self, api_client: "Union[ApiClient, AsyncApiClient]"):
self.api_client = api_client
def _build_for_healthz(
self,
):
"""
An endpoint for health checking used in Kubernetes.
"""
headers = {}
return self.api_client.request(
... | _ServiceApi |
python | django__django | django/db/models/functions/math.py | {
"start": 3623,
"end": 3724
} | class ____(FixDecimalInputMixin, NumericOutputFieldMixin, Func):
function = "MOD"
arity = 2
| Mod |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 411230,
"end": 412319
} | class ____(ExprNode):
# Represents a single item in a DictNode
#
# key ExprNode
# value ExprNode
subexprs = ['key', 'value']
nogil_check = None # Parent DictNode takes care of it
def calculate_constant_result(self):
self.constant_result = (
self.key.con... | DictItemNode |
python | django__django | tests/db_functions/text/test_substr.py | {
"start": 174,
"end": 1918
} | class ____(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.annotate(name_part=Substr("name", 5, 3))
self.assertQuerySetEqual(
authors.order_by("name"), [" Sm", "da"], l... | SubstrTests |
python | tensorflow__tensorflow | tensorflow/python/autograph/core/function_wrappers.py | {
"start": 1209,
"end": 4355
} | class ____(object):
"""Context manager that wraps the body of a converted function.
This context manager handles various operations related to the scope of a
function:
* optional TF name scopes - these name scopes match the name of the
function, for easy visualization in tensorBoard;
* optional a... | FunctionScope |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/template_vars_tests/test_basic_template_vars.py | {
"start": 237,
"end": 2002
} | class ____(dg.Component, dg.Resolvable, dg.Model):
value: str
@staticmethod
@dg.template_var
def foo() -> str:
return "value_for_foo"
@staticmethod
@dg.template_var
def a_udf() -> Callable:
return lambda: "a_udf_value"
@staticmethod
@dg.template_var
def a_udf_w... | ComponentWithAdditionalScope |
python | huggingface__transformers | tests/models/siglip/test_modeling_siglip.py | {
"start": 6125,
"end": 9442
} | class ____(SiglipModelTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as SIGLIP does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (SiglipVisionModel,) if is_torch_available() else ()
test_resi... | SiglipVisionModelTest |
python | vyperlang__vyper | vyper/semantics/namespace.py | {
"start": 249,
"end": 3703
} | class ____(dict):
"""
Dictionary subclass that represents the namespace of a contract.
Attributes
----------
_scopes : List[Set]
List of sets containing the key names for each scope
"""
def __new__(cls, *args, **kwargs):
self = super().__new__(cls, *args, **kwargs)
... | Namespace |
python | Netflix__metaflow | metaflow/exception.py | {
"start": 4137,
"end": 4215
} | class ____(MetaflowException):
headline = "Data missing"
| MetaflowDataMissing |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 50329,
"end": 52239
} | class ____(ExtensionType):
oid = ExtensionOID.ISSUER_ALTERNATIVE_NAME
def __init__(self, general_names: Iterable[GeneralName]) -> None:
self._general_names = GeneralNames(general_names)
__len__, __iter__, __getitem__ = _make_sequence_methods("_general_names")
@typing.overload
def get_valu... | IssuerAlternativeName |
python | walkccc__LeetCode | solutions/213. House Robber II/213.py | {
"start": 0,
"end": 401
} | class ____:
def rob(self, nums: list[int]) -> int:
if not nums:
return 0
if len(nums) < 2:
return nums[0]
def rob(l: int, r: int) -> int:
dp1 = 0
dp2 = 0
for i in range(l, r + 1):
temp = dp1
dp1 = max(dp1, dp2 + nums[i])
dp2 = temp
return dp1
... | Solution |
python | pyinstaller__pyinstaller | PyInstaller/loader/pyimod02_importers.py | {
"start": 4764,
"end": 17392
} | class ____:
"""
PyInstaller's frozen path entry finder for specific search path.
Per-path instances allow us to properly translate the given module name ("fullname") into full PYZ entry name.
For example, with search path being `sys._MEIPASS`, the module "mypackage.mod" would translate to "mypackage.mo... | PyiFrozenFinder |
python | ray-project__ray | doc/source/serve/doc_code/image_classifier_example.py | {
"start": 407,
"end": 1055
} | class ____:
def __init__(self, downloader: DeploymentHandle):
self.downloader = downloader
self.model = pipeline(
"image-classification", model="google/vit-base-patch16-224"
)
async def classify(self, image_url: str) -> str:
image = await self.downloader.remote(image... | ImageClassifier |
python | tensorflow__tensorflow | tensorflow/python/framework/combinations.py | {
"start": 1122,
"end": 1844
} | class ____(test_combinations.TestCombination):
"""Run the test in Graph or Eager mode.
The optional `mode` parameter controls the test's execution mode. Its
accepted values are "graph" or "eager" literals.
"""
def context_managers(self, kwargs):
mode = kwargs.pop("mode", None)
if mode is None:
... | EagerGraphCombination |
python | Netflix__metaflow | metaflow/exception.py | {
"start": 2436,
"end": 2614
} | class ____(MetaflowException):
headline = "External command failed"
def __init__(self, msg):
super(ExternalCommandFailed, self).__init__(msg)
| ExternalCommandFailed |
python | pypa__hatch | tests/project/test_utils.py | {
"start": 78,
"end": 1303
} | class ____:
def test_no_metadata(self):
assert parse_inline_script_metadata("") is None
def test_too_many_blocks(self, helpers):
script = helpers.dedent(
"""
# /// script
# dependencies = ["foo"]
# ///
# /// script
# depen... | TestParseInlineScriptMetadata |
python | PrefectHQ__prefect | tests/assets/test_materializing_tasks.py | {
"start": 48,
"end": 1370
} | class ____:
def test_with_options_assets_parameter_keeps_existing(self):
@materialize("storage://original/asset.csv", persist_result=True)
def initial_task():
pass
task_with_options = initial_task.with_options(persist_result=False)
assert task_with_options.assets == [As... | TestMaterializingTask |
python | walkccc__LeetCode | solutions/2273. Find Resultant Array After Removing Anagrams/2273.py | {
"start": 0,
"end": 456
} | class ____:
def removeAnagrams(self, words: list[str]) -> list[str]:
ans = []
def isAnagram(a: str, b: str) -> bool:
count = collections.Counter(a)
count.subtract(collections.Counter(b))
return all(value == 0 for value in count.values())
i = 0
while i < len(words):
j = i + 1
... | Solution |
python | django__django | tests/model_forms/models.py | {
"start": 392,
"end": 711
} | class ____(models.Model):
name = models.CharField(max_length=20)
slug = models.SlugField(max_length=20)
url = models.CharField("The URL", max_length=40)
class Meta:
ordering = ("pk",)
def __str__(self):
return self.name
def __repr__(self):
return self.__str__()
| Category |
python | scikit-image__scikit-image | src/skimage/segmentation/morphsnakes.py | {
"start": 297,
"end": 14878
} | class ____:
def __init__(self, iterable):
"""Call functions from the iterable each time it is called."""
self.funcs = cycle(iterable)
def __call__(self, *args, **kwargs):
f = next(self.funcs)
return f(*args, **kwargs)
# SI and IS operators for 2D and 3D.
_P2 = [
np.eye(3),... | _fcycle |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.