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 | huggingface__transformers | src/transformers/models/megatron_bert/modeling_megatron_bert.py | {
"start": 11155,
"end": 11837
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_f... | MegatronBertIntermediate |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/big_button.py | {
"start": 80,
"end": 338
} | class ____(App):
CSS = """
Button {
height: 9;
}
"""
def compose(self) -> ComposeResult:
yield Button("Hello")
yield Button("Hello\nWorld !!")
if __name__ == "__main__":
app = ButtonApp()
app.run()
| ButtonApp |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 93787,
"end": 97072
} | class ____(rv_continuous):
r"""A generalized Pareto continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `genpareto` is:
.. math::
f(x, c) = (1 + c x)^{-1 - 1/c}
defined for :math:`x \ge 0` if :math:`c \ge 0`, and for
:math:`0 \le x \... | genpareto_gen |
python | encode__django-rest-framework | tests/test_permissions.py | {
"start": 19642,
"end": 19736
} | class ____(PermissionInstanceView):
permission_classes = (BasicObjectPerm,)
| DeniedObjectView |
python | pypa__warehouse | tests/unit/utils/test_paginate.py | {
"start": 1872,
"end": 2238
} | class ____(FakeQuery):
def __init__(self, fake, options=None, suggestion=None):
super().__init__(fake)
self.options = options
self.suggestion = suggestion
def execute(self):
data = self.fake[self.range]
total = len(self.fake)
return FakeSuggestResult(data, total,... | FakeSuggestQuery |
python | pytorch__pytorch | torch/_dynamo/functional_export.py | {
"start": 18562,
"end": 33526
} | class ____:
graph_module: torch.fx.GraphModule
in_spec: TreeSpec
in_shuffle_graph: torch.fx.GraphModule
num_flat_args: int
out_spec: TreeSpec
out_shuffle_graph: torch.fx.GraphModule
root: Optional[torch.nn.Module] = None
def pytreeify(
out: CaptureOutput, mod: Any, args: tuple[Any, ...... | PyTreeifyOutput |
python | tensorflow__tensorflow | tensorflow/python/ops/control_flow_ops.py | {
"start": 17900,
"end": 24660
} | class ____(metaclass=abc.ABCMeta):
"""The base class for control flow context.
The usage pattern is a sequence of (Enter, Exit) followed by a final
ExitResult.
We maintain the following state for control flow contexts during graph
construction:
1. graph has _control_flow_context: the current context used... | ControlFlowContext |
python | huggingface__transformers | src/transformers/models/depth_pro/modeling_depth_pro.py | {
"start": 15658,
"end": 17542
} | class ____(nn.Module):
def __init__(self, config: DepthProConfig):
super().__init__()
self.config = config
self.intermediate_hook_ids = config.intermediate_hook_ids
self.intermediate_feature_dims = config.intermediate_feature_dims
self.scaled_images_ratios = config.scaled_ima... | DepthProEncoder |
python | django-extensions__django-extensions | tests/testapp_with_appconfig/apps.py | {
"start": 36,
"end": 123
} | class ____(AppConfig):
name = "tests.testapp_with_appconfig"
| TestappWithAppConfigConfig |
python | arrow-py__arrow | arrow/locales.py | {
"start": 10715,
"end": 12190
} | class ____(Locale):
names = ["it", "it-it"]
past = "{0} fa"
future = "tra {0}"
and_word = "e"
timeframes = {
"now": "adesso",
"second": "un secondo",
"seconds": "{0} qualche secondo",
"minute": "un minuto",
"minutes": "{0} minuti",
"hour": "un'ora",
... | ItalianLocale |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/baked.py | {
"start": 1256,
"end": 10083
} | class ____:
"""A builder object for :class:`.query.Query` objects."""
__slots__ = "steps", "_bakery", "_cache_key", "_spoiled"
def __init__(self, bakery, initial_fn, args=()):
self._cache_key = ()
self._update_cache_key(initial_fn, args)
self.steps = [initial_fn]
self._spoi... | BakedQuery |
python | huggingface__transformers | src/transformers/models/gpt_oss/modeling_gpt_oss.py | {
"start": 32729,
"end": 32992
} | class ____(GenericForTokenClassification, GptOssPreTrainedModel):
pass
__all__ = [
"GptOssForCausalLM",
"GptOssForSequenceClassification",
"GptOssForTokenClassification",
"GptOssModel",
"GptOssPreTrainedModel",
]
| GptOssForTokenClassification |
python | django__django | django/db/models/expressions.py | {
"start": 43588,
"end": 43727
} | class ____(Expression):
def __repr__(self):
return "'*'"
def as_sql(self, compiler, connection):
return "*", []
| Star |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/declarative_automation_tests/scenario_utils/scenario_state.py | {
"start": 3608,
"end": 9642
} | class ____:
"""A construct for declaring and modifying a desired Definitions object."""
asset_specs: Sequence[Union[dg.AssetSpec, MultiAssetSpec]]
check_specs: Sequence[dg.AssetCheckSpec] = field(default_factory=list)
current_time: datetime.datetime = field(default_factory=lambda: get_current_datetime(... | ScenarioSpec |
python | pypa__warehouse | tests/unit/manage/test_views.py | {
"start": 75986,
"end": 99699
} | class ____:
def test_default_response(self, monkeypatch):
create_macaroon_obj = pretend.stub()
create_macaroon_cls = pretend.call_recorder(
lambda *a, **kw: create_macaroon_obj
)
monkeypatch.setattr(views, "CreateMacaroonForm", create_macaroon_cls)
delete_macaroo... | TestProvisionMacaroonViews |
python | gevent__gevent | src/gevent/pool.py | {
"start": 25020,
"end": 25634
} | class ____(object):
__slots__ = ['callback']
def __init__(self, callback):
self.callback = callback
def __call__(self, source):
if source.successful():
self.callback(source.value)
def __hash__(self):
return hash(self.callback)
def __eq__(self, other):
... | pass_value |
python | great-expectations__great_expectations | tests/integration/fluent/test_snowflake_datasource.py | {
"start": 319,
"end": 2380
} | class ____:
@parameterize_batch_for_data_sources(
data_source_configs=[
SnowflakeDatasourceTestConfig(table_name=TEST_TABLE_NAME.lower()),
],
data=pd.DataFrame({"test_column": [1, 2, 3]}),
)
def test_lower(self, batch_for_datasource):
"""Test Snowflake with lower ... | TestSnowflakeTableIdentifiers |
python | huggingface__transformers | src/transformers/models/nanochat/configuration_nanochat.py | {
"start": 731,
"end": 7625
} | class ____(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`NanoChatModel`]. It is used to instantiate a
NanoChat model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar con... | NanoChatConfig |
python | apache__airflow | dev/breeze/src/airflow_breeze/prepare_providers/provider_documentation.py | {
"start": 5736,
"end": 53566
} | class ____(Exception):
"""Raised when user decided to quit."""
TYPE_OF_CHANGE_DESCRIPTION = {
TypeOfChange.DOCUMENTATION: "Documentation only changes - no version change needed, "
"only documentation needs to be updated",
TypeOfChange.BUGFIX: "Bugfix changes only - bump in PATCHLEVEL version needed",
... | PrepareReleaseDocsUserQuitException |
python | openai__openai-python | src/openai/resources/chat/completions/completions.py | {
"start": 160117,
"end": 161026
} | class ____:
def __init__(self, completions: Completions) -> None:
self._completions = completions
self.parse = _legacy_response.to_raw_response_wrapper(
completions.parse,
)
self.create = _legacy_response.to_raw_response_wrapper(
completions.create,
)... | CompletionsWithRawResponse |
python | python__mypy | mypy/erasetype.py | {
"start": 8581,
"end": 10768
} | class ____(TypeTranslator):
"""Removes the Literal[...] type that may be associated with any
Instance types."""
def visit_instance(self, t: Instance) -> Type:
if not t.last_known_value and not t.args:
return t
return t.copy_modified(args=[a.accept(self) for a in t.args], last_kn... | LastKnownValueEraser |
python | pypa__pipenv | pipenv/patched/pip/_internal/network/auth.py | {
"start": 7453,
"end": 20899
} | class ____(AuthBase):
def __init__(
self,
prompting: bool = True,
index_urls: Optional[List[str]] = None,
keyring_provider: str = "auto",
) -> None:
self.prompting = prompting
self.index_urls = index_urls
self.keyring_provider = keyring_provider # type: i... | MultiDomainBasicAuth |
python | numba__numba | numba/tests/cache_usecases.py | {
"start": 2445,
"end": 3566
} | class ____(TestCase):
"""
Tests for functionality of this module's functions.
Note this does not define any "test_*" method, instead check_module()
should be called by hand.
"""
def check_module(self, mod):
self.assertPreciseEqual(mod.add_usecase(2, 3), 6)
self.assertPreciseEqua... | _TestModule |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 40787,
"end": 42622
} | class ____(base_classes.Font):
def __init__(self, parent, xl):
# xl can be font or font_object
self.parent = parent
self.xl = xl
@property
def api(self):
return self.xl
@property
def bold(self):
return self.xl.bold.get()
@bold.setter
def bold(self, ... | Font |
python | django__django | tests/middleware_exceptions/tests.py | {
"start": 13186,
"end": 15707
} | class ____(SimpleTestCase):
@override_settings(
MIDDLEWARE=[
"middleware_exceptions.middleware.AsyncTemplateResponseMiddleware",
]
)
async def test_process_template_response(self):
response = await self.async_client.get(
"/middleware_exceptions/template_respon... | AsyncMiddlewareTests |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_base_classes_3.py | {
"start": 313,
"end": 367
} | class ____(BaseModel[int]):
x: collections.Awaitable
| E |
python | django__django | tests/serializers/models/natural.py | {
"start": 1117,
"end": 1498
} | class ____(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100, unique=True)
class Manager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
objects = Manager()
def natu... | NaturalPKWithDefault |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 25806,
"end": 26997
} | class ____(MeanMetricWrapper):
"""Calculates how often predictions equal labels.
This metric creates two local variables, `total` and `count` that are used to
compute the frequency with which `y_pred` matches `y_true`. This frequency is
ultimately returned as `binary accuracy`: an idempotent operation that sim... | Accuracy |
python | weaviate__weaviate-python-client | weaviate/collections/grpc/shared.py | {
"start": 28504,
"end": 29548
} | class ____:
@staticmethod
def parse_single_or_multi_vec(vector: PrimitiveVectorType) -> _Packing:
if _is_2d_vector(vector):
return _Packing(
bytes_=_Pack.multi(vector),
type_=base_pb2.Vectors.VECTOR_TYPE_MULTI_FP32,
)
elif _is_1d_vector(vec... | _Pack |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 6361,
"end": 6835
} | class ____(Token):
""" Represents an array constructor.
Examples
========
>>> from sympy import fcode
>>> from sympy.codegen.fnodes import ArrayConstructor
>>> ac = ArrayConstructor([1, 2, 3])
>>> fcode(ac, standard=95, source_format='free')
'(/1, 2, 3/)'
>>> fcode(ac, standard=200... | ArrayConstructor |
python | pytorch__pytorch | test/test_autocast.py | {
"start": 13594,
"end": 14757
} | class ____(TestCase):
def test_autocast_fast_dtype(self):
gpu_fast_dtype = torch.get_autocast_dtype(device_type="cuda")
cpu_fast_dtype = torch.get_autocast_dtype(device_type="cpu")
self.assertEqual(gpu_fast_dtype, torch.half)
self.assertEqual(cpu_fast_dtype, torch.bfloat16)
def ... | TestTorchAutocast |
python | dagster-io__dagster | python_modules/libraries/dagster-gcp/dagster_gcp/gcs/io_manager.py | {
"start": 796,
"end": 2907
} | class ____(UPathIOManager):
def __init__(self, bucket: str, client: Optional[Any] = None, prefix: str = "dagster"):
self.bucket = check.str_param(bucket, "bucket")
self.client = client or storage.Client()
self.bucket_obj = self.client.bucket(bucket)
check.invariant(self.bucket_obj.ex... | PickledObjectGCSIOManager |
python | jmcnamara__XlsxWriter | xlsxwriter/test/color/test_color01.py | {
"start": 282,
"end": 2147
} | class ____(unittest.TestCase):
"""
Test cases for the Color class.
"""
def test_color_rgb_from_string(self):
"""Test creating a Color instance from a hex string."""
color = Color("#FF5733")
self.assertEqual(color._rgb_value, 0xFF5733)
self.assertEqual(color._type, ColorT... | TestColor |
python | huggingface__transformers | src/transformers/trainer_callback.py | {
"start": 8580,
"end": 10340
} | class ____:
"""
A class for objects that include the ability to have its state
be saved during `Trainer._save_checkpoint` and loaded back in during
`Trainer._load_from_checkpoint`.
These must implement a `state` function that gets called during the respective
Trainer function call. It should on... | ExportableState |
python | kamyu104__LeetCode-Solutions | Python/find-the-occurrence-of-first-almost-equal-substring.py | {
"start": 50,
"end": 910
} | class ____(object):
def minStartingIndex(self, s, pattern):
"""
:type s: str
:type pattern: str
:rtype: int
"""
K = 1
# Template: https://cp-algorithms.com/string/z-function.html
def z_function(s): # Time: O(n), Space: O(n)
z = [0]*len(s)
... | Solution |
python | numpy__numpy | numpy/polynomial/tests/test_symbol.py | {
"start": 3735,
"end": 5372
} | class ____:
"""
Test other methods for manipulating/creating polynomial objects.
"""
p = poly.Polynomial([1, 2, 3, 0], symbol='z')
def test_copy(self):
other = self.p.copy()
assert_equal(other.symbol, 'z')
def test_trim(self):
other = self.p.trim()
assert_equal(... | TestExtraMethods |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/api_fastapi/services/test_roles.py | {
"start": 2183,
"end": 14147
} | class ____:
def setup_method(self):
self.body_ok = types.SimpleNamespace(
name="roleA",
permissions=[
types.SimpleNamespace(
action=types.SimpleNamespace(name="can_read"),
resource=types.SimpleNamespace(name="DAG"),
... | TestRolesService |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 118124,
"end": 119190
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
existing_cluster_id: Optional[str] = Field(
None,
description=(
"If existing_cluster_id, the ID of an existing cluster that is used for all"... | ClusterSpec |
python | tox-dev__tox | src/tox/tox_env/register.py | {
"start": 293,
"end": 2640
} | class ____:
"""tox environment registry."""
def __init__(self) -> None:
self._run_envs: dict[str, type[RunToxEnv]] = {}
self._package_envs: dict[str, type[PackageToxEnv]] = {}
self._default_run_env: str = ""
def _register_tox_env_types(self, manager: Plugin) -> None:
manage... | ToxEnvRegister |
python | jina-ai__jina | jina/logging/logger.py | {
"start": 2449,
"end": 3031
} | class ____(logging.handlers.SysLogHandler):
"""
Override the priority_map :class:`SysLogHandler`.
.. warning::
This messages at DEBUG and INFO are therefore not stored by ASL, (ASL = Apple System Log)
which in turn means they can't be printed by syslog after the fact. You can confirm it via... | SysLogHandlerWrapper |
python | PrefectHQ__prefect | src/prefect/server/concurrency/lease_storage/memory.py | {
"start": 405,
"end": 4046
} | class ____(_ConcurrencyLeaseStorage):
"""
A singleton concurrency lease storage implementation that stores leases in memory.
"""
_instance: "ConcurrencyLeaseStorage | None" = None
_initialized: bool = False
def __new__(cls) -> "ConcurrencyLeaseStorage":
if cls._instance is None:
... | ConcurrencyLeaseStorage |
python | walkccc__LeetCode | solutions/273. Integer to English Words/273.py | {
"start": 0,
"end": 1129
} | class ____:
def numberToWords(self, num: int) -> str:
if num == 0:
return 'Zero'
belowTwenty = ['', 'One', 'Two', 'Three',
'Four', 'Five', 'Six', 'Seven',
'Eight', 'Nine', 'Ten', 'Eleven',
'Twelve', 'Th... | Solution |
python | huggingface__transformers | src/transformers/models/dinov3_vit/modular_dinov3_vit.py | {
"start": 11770,
"end": 11822
} | class ____(Dinov2DropPath):
pass
| DINOv3ViTDropPath |
python | tensorflow__tensorflow | tensorflow/python/lib/io/tf_record_test.py | {
"start": 12875,
"end": 20293
} | class ____(TFCompressionTestCase):
"""TFRecordIterator test"""
def setUp(self):
super(TFRecordIteratorTest, self).setUp()
self._num_records = 7
def testIterator(self):
"""test Iterator"""
records = [self._Record(0, i) for i in range(self._num_records)]
options = tf_record.TFRecordOptions(TFR... | TFRecordIteratorTest |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 102012,
"end": 102128
} | class ____:
xlA1 = 1 # from enum XlReferenceStyle
xlR1C1 = -4150 # from enum XlReferenceStyle
| ReferenceStyle |
python | scikit-learn__scikit-learn | sklearn/preprocessing/_data.py | {
"start": 40277,
"end": 51643
} | class ____(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Scale each feature by its maximum absolute value.
This estimator scales and translates each feature individually such
that the maximal absolute value of each feature in the
training set will be 1.0. It does not shift/center the data,... | MaxAbsScaler |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_merge_range05.py | {
"start": 315,
"end": 892
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("merge_range05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | ansible__ansible | test/lib/ansible_test/_util/controller/sanity/validate-modules/validate_modules/utils.py | {
"start": 5971,
"end": 7023
} | class ____(AnsibleModule):
"""AnsibleModule that does not actually load params. This is used to get access to the
methods within AnsibleModule without having to fake a bunch of data
"""
def _load_params(self):
self.params = {'_ansible_selinux_special_fs': [], '_ansible_remote_tmp': '/tmp', '_an... | NoArgsAnsibleModule |
python | PrefectHQ__prefect | tests/server/schemas/test_schedules.py | {
"start": 31898,
"end": 50687
} | class ____:
@pytest.mark.parametrize(
"start_date",
[
datetime(2018, 1, 1, tzinfo=ZoneInfo("UTC")),
datetime(2021, 2, 2, tzinfo=ZoneInfo("UTC")),
datetime(2025, 3, 3, tzinfo=ZoneInfo("UTC")),
],
)
async def test_daily_with_start_date(self, start_da... | TestRRuleSchedule |
python | ansible__ansible | lib/ansible/_internal/_templating/_lazy_containers.py | {
"start": 2844,
"end": 3575
} | class ____(Sentinel):
"""Sentinel used to indicate a requested key was not found."""
# There are several operations performed by lazy containers, with some variation between types.
#
# Columns: D=dict, L=list, T=tuple
# Cells: l=lazy (upon access), n=non-lazy (__init__/__new__)
#
# D L T Feature Descrip... | _NoKeySentinel |
python | django__django | tests/model_regress/tests.py | {
"start": 9472,
"end": 10103
} | class ____(TestCase):
def test_fields_cache_reset_on_copy(self):
department1 = Department.objects.create(id=1, name="department1")
department2 = Department.objects.create(id=2, name="department2")
worker1 = Worker.objects.create(name="worker", department=department1)
worker2 = copy.c... | ModelFieldsCacheTest |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 15961,
"end": 16321
} | class ____(GroupType):
type_id = 1013
slug = "performance_db_main_thread"
description = "DB on Main Thread"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.MOBILE.value
noise_config = NoiseConfig()
default_priority = PriorityLevel.LOW
released = True
@dataclass(f... | PerformanceDBMainThreadGroupType |
python | huggingface__transformers | src/transformers/models/gemma3/configuration_gemma3.py | {
"start": 1442,
"end": 12314
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Gemma3TextModel`]. It is used to instantiate an Gemma3Text
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a simila... | Gemma3TextConfig |
python | PyCQA__pylint | doc/data/messages/a/abstract-class-instantiated/good.py | {
"start": 13,
"end": 101
} | class ____(abc.ABC):
@abc.abstractmethod
def make_sound(self):
pass
| Animal |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/data_structures/lookup_ops_test.py | {
"start": 164118,
"end": 165947
} | class ____(test.Benchmark):
def _create_table(self):
return lookup_ops.MutableHashTable(dtypes.int64, dtypes.float32, 0.0)
def benchmark_single_repeated_scalar_insert_scalar(self):
table = self._create_table()
value = variables.Variable(1.0)
insert = table.insert(0, value)
size = table.size()
... | MutableHashTableBenchmark |
python | lazyprogrammer__machine_learning_examples | rl2/atari/dqn_theano.py | {
"start": 7138,
"end": 14414
} | class ____:
def __init__(self, K, conv_layer_sizes, hidden_layer_sizes):
self.K = K
# inputs and targets
X = T.ftensor4('X')
G = T.fvector('G')
actions = T.ivector('actions')
# create the graph
self.conv_layers = []
num_input_filters = 4 # number of filters / color channels
curre... | DQN |
python | getsentry__sentry | src/sentry/api/serializers/models/rule.py | {
"start": 1853,
"end": 2173
} | class ____(TypedDict, total=False):
owner: str | None
createdBy: RuleCreatedBy | None
environment: str | None
lastTriggered: str | None
snoozeCreatedBy: str | None
snoozeForEveryone: bool | None
disableReason: str
disableDate: str
errors: list[_ErrorDict]
| RuleSerializerResponseOptional |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_s3.py | {
"start": 16946,
"end": 17729
} | class ____:
def test_execute(self):
operator = S3ListPrefixesOperator(
task_id="test-s3-list-prefixes-operator", bucket=BUCKET_NAME, prefix="test/", delimiter="/"
)
operator.hook = mock.MagicMock()
operator.hook.list_prefixes.return_value = ["test/"]
subfolders =... | TestS3ListPrefixesOperator |
python | django__django | tests/queries/test_query.py | {
"start": 8847,
"end": 9069
} | class ____(SimpleTestCase):
def test_repr(self):
self.assertEqual(
repr(JoinPromoter(AND, 3, True)),
"JoinPromoter(connector='AND', num_children=3, negated=True)",
)
| JoinPromoterTest |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 83686,
"end": 83975
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
AutoModelForSeq2SeqLM = auto_class_update(
AutoModelForSeq2SeqLM,
head_doc="sequence-to-sequence language modeling",
checkpoint_for_example="google-t5/t5-base",
)
| AutoModelForSeq2SeqLM |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_dialect.py | {
"start": 30103,
"end": 33962
} | class ____:
__only_on__ = "postgresql+psycopg2"
__backend__ = True
run_create_tables = "each"
run_deletes = None
options = None
@config.fixture()
def connection(self):
opts = dict(self.options)
opts["use_reaper"] = False
eng = engines.testing_engine(options=opts)
... | ExecuteManyMode |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/graph/asset_graph_differ.py | {
"start": 424,
"end": 859
} | class ____(Enum):
"""What change an asset has undergone between two deployments. Used
in distinguishing asset definition changes in branch deployment and
in subsequent other deployments.
"""
NEW = "NEW"
CODE_VERSION = "CODE_VERSION"
DEPENDENCIES = "DEPENDENCIES"
PARTITIONS_DEFINITION = ... | AssetDefinitionChangeType |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 6289,
"end": 6641
} | class ____(LocalizableStreamlitException):
"""Exception raised when an invalid key is specified."""
def __init__(self, key: str) -> None:
super().__init__(
'We only accept the keys: `"Get help"`, `"Report a bug"`, and `"About"` (`"{key}"` is not a valid key.)',
key=key,
... | StreamlitInvalidMenuItemKeyError |
python | tornadoweb__tornado | tornado/websocket.py | {
"start": 23028,
"end": 26055
} | class ____(abc.ABC):
"""Base class for WebSocket protocol versions."""
def __init__(self, handler: "_WebSocketDelegate") -> None:
self.handler = handler
self.stream = None # type: Optional[IOStream]
self.client_terminated = False
self.server_terminated = False
def _run_cal... | WebSocketProtocol |
python | psf__black | tests/data/cases/dummy_implementations.py | {
"start": 3322,
"end": 3384
} | class ____:
def f(self):
# Comment
...
| ClassH |
python | scikit-learn__scikit-learn | sklearn/decomposition/_dict_learning.py | {
"start": 34537,
"end": 38398
} | class ____(ClassNamePrefixFeaturesOutMixin, TransformerMixin):
"""Base class from SparseCoder and DictionaryLearning algorithms."""
def __init__(
self,
transform_algorithm,
transform_n_nonzero_coefs,
transform_alpha,
split_sign,
n_jobs,
positive_code,
... | _BaseSparseCoding |
python | spack__spack | lib/spack/spack/repo.py | {
"start": 80742,
"end": 81165
} | class ____(RepoError):
"""Raised when a package's class constructor fails."""
def __init__(self, name, exc_type, exc_obj, exc_tb):
super().__init__(
"Class constructor failed for package '%s'." % name,
"\nCaused by:\n"
+ ("%s: %s\n" % (exc_type.__name__, exc_obj))
... | FailedConstructorError |
python | Netflix__metaflow | test/core/tests/large_mflog.py | {
"start": 67,
"end": 4857
} | class ____(MetaflowTest):
"""
Test that we can capture a large amount of log messages with
accurate timings
"""
PRIORITY = 2
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_... | LargeMflogTest |
python | sqlalchemy__sqlalchemy | test/sql/test_sequences.py | {
"start": 13558,
"end": 19666
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
__requires__ = ("sequences",)
__sparse_driver_backend__ = True
@testing.combinations(
(Sequence("foo_seq"),),
(Sequence("foo_seq", start=8),),
(Sequence("foo_seq", increment=5),),
)
def test_start_increment(self, seq... | SequenceTest |
python | great-expectations__great_expectations | great_expectations/expectations/sql_tokens_and_types.py | {
"start": 1998,
"end": 2651
} | class ____(str, Enum):
ARRAYTYPE = "ARRAY"
BINARYTYPE = "BINARY"
BOOLEAN = "BOOLEAN"
BYTE = "BYTE"
TINYINT = "TINYINT"
DATE = "DATE"
DECIMAL = "DECIMAL"
DEC = "DEC"
NUMERIC = "NUMERIC"
INTERVAL = "INTERVAL"
DAY = "DAY"
YEAR = "YEAR"
MONTH = "MONTH"
HOUR = "HOUR"
... | ValidSparkSqlTypes |
python | kubernetes-client__python | kubernetes/client/models/v1_self_subject_rules_review_spec.py | {
"start": 383,
"end": 3626
} | 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... | V1SelfSubjectRulesReviewSpec |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/via_type_of.py | {
"start": 1036,
"end": 1798
} | class ____:
x: Dict[str, int] = {}
y: List[str] = []
z: Annotated[float, "test2"] = 0.0
def test2_alarm1():
# always-via-type:Dict[str, int]
c = Test2_C(**_test_source())
_test_sink(c.x)
def test2_alarm2():
# always-via-type:List[str]
c = Test2_C(**_test_source())
_test_sink(c.y)... | Test2_C |
python | getsentry__sentry | src/sentry/notifications/validators.py | {
"start": 1716,
"end": 2503
} | class ____(
UserNotificationSettingsOptionsDetailsSerializer
):
providers = serializers.ListField(child=serializers.CharField())
def validate_providers(self, value):
for provider in value:
if provider not in PERSONAL_NOTIFICATION_PROVIDERS:
raise serializers.ValidationEr... | UserNotificationSettingsProvidersDetailsSerializer |
python | getsentry__sentry | tests/sentry/integrations/msteams/notifications/test_regression.py | {
"start": 602,
"end": 2154
} | class ____(MSTeamsActivityNotificationTest):
def test_regression(self, mock_send_card: MagicMock) -> None:
"""
Test that the card for MS Teams notification is generated correctly when an issue regresses.
"""
notification = RegressionActivityNotification(
Activity(
... | MSTeamsRegressionNotificationTest |
python | numba__numba | numba/core/ir.py | {
"start": 26753,
"end": 27067
} | class ____(Terminator):
"""
Unconditional branch.
"""
def __init__(self, target, loc):
assert isinstance(loc, Loc)
self.target = target
self.loc = loc
def __str__(self):
return 'jump %s' % self.target
def get_targets(self):
return [self.target]
| Jump |
python | openai__openai-python | src/openai/types/realtime/realtime_mcp_tool_call.py | {
"start": 666,
"end": 1325
} | class ____(BaseModel):
id: str
"""The unique ID of the tool call."""
arguments: str
"""A JSON string of the arguments passed to the tool."""
name: str
"""The name of the tool that was run."""
server_label: str
"""The label of the MCP server running the tool."""
type: Literal["mcp... | RealtimeMcpToolCall |
python | django__django | django/views/generic/dates.py | {
"start": 2094,
"end": 3768
} | class ____:
"""Mixin for views manipulating month-based data."""
month_format = "%b"
month = None
def get_month_format(self):
"""
Get a month format string in strptime syntax to be used to parse the
month from url variables.
"""
return self.month_format
def... | MonthMixin |
python | pyqtgraph__pyqtgraph | pyqtgraph/configfile.py | {
"start": 657,
"end": 5978
} | class ____(Exception):
def __init__(self, message, lineNum, line, fileName=None):
self.lineNum = lineNum
self.line = line
self.message = message
self.fileName = fileName
Exception.__init__(self, message)
def __str__(self):
if self.fileName is None:
ms... | ParseError |
python | ray-project__ray | python/ray/serve/tests/test_autoscaling_policy.py | {
"start": 57024,
"end": 70825
} | class ____:
@pytest.fixture
def serve_instance_with_two_signal(self, serve_instance):
client = serve_instance
signal_a = SignalActor.options(name="signal_A").remote()
signal_b = SignalActor.options(name="signal_B").remote()
yield client, signal_a, signal_b
# Delete sig... | TestAppLevelAutoscalingPolicy |
python | pyca__cryptography | tests/hazmat/primitives/test_rsa.py | {
"start": 54350,
"end": 57805
} | class ____:
test_rsa_pkcs1v15_verify_sha1 = pytest.mark.supported(
only_if=lambda backend: (
backend.signature_hash_supported(hashes.SHA1())
and backend.rsa_padding_supported(padding.PKCS1v15())
),
skip_message="Does not support SHA1 and PKCS1v1.5.",
)(
ge... | TestRSAPKCS1Verification |
python | numba__numba | numba/cuda/tests/cudapy/test_datetime.py | {
"start": 192,
"end": 3508
} | class ____(CUDATestCase):
def test_basic_datetime_kernel(self):
@cuda.jit
def foo(start, end, delta):
for i in range(cuda.grid(1), delta.size, cuda.gridsize(1)):
delta[i] = end[i] - start[i]
arr1 = np.arange('2005-02', '2006-02', dtype='datetime64[D]')
ar... | TestCudaDateTime |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurecosmosmongo/tests/test_azurecosmosmongo.py | {
"start": 2219,
"end": 4432
} | class ____:
@classmethod
def setup_class(cls) -> None:
# insure the test collection is empty
assert collection.count_documents({}) == 0 # type: ignore[index]
@classmethod
def teardown_class(cls) -> None:
# delete all the documents in the collection
collection.delete_man... | TestAzureMongovCoreVectorSearch |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/TargetItem.py | {
"start": 351,
"end": 11973
} | class ____(UIGraphicsItem):
"""Draws a draggable target symbol (circle plus crosshair).
The size of TargetItem will remain fixed on screen even as the view is zoomed.
Includes an optional text label.
"""
sigPositionChanged = QtCore.Signal(object)
sigPositionChangeFinished = QtCore.Signal(objec... | TargetItem |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_ex_returned.py | {
"start": 1627,
"end": 1843
} | class ____:
""" __getnewargs_ex__ returns tuple with wrong type for first arg """
def __getnewargs_ex__(self): # [invalid-getnewargs-ex-returned]
return (dict(x="y"), dict(x="y"))
| ThirdBadGetNewArgsEx |
python | oauthlib__oauthlib | tests/oauth2/rfc8628/endpoints/test_error_responses.py | {
"start": 297,
"end": 3701
} | class ____(TestCase):
def set_client(self, request):
request.client = mock.MagicMock()
request.client.client_id = "mocked"
return True
def build_request(self, uri="https://example.com/device_authorize", client_id="foo"):
body = ""
if client_id:
body = f"clien... | ErrorResponseTest |
python | bokeh__bokeh | src/bokeh/models/widgets/pickers.py | {
"start": 8484,
"end": 8838
} | class ____(BaseDatePicker):
""" Calendar-based picker of date ranges. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
value = Nullable(Tuple(Date, Date), default=None, help="""
The initial or picked... | DateRangePicker |
python | walkccc__LeetCode | solutions/2147. Number of Ways to Divide a Long Corridor/2147.py | {
"start": 0,
"end": 386
} | class ____:
def numberOfWays(self, corridor: str) -> int:
MOD = 1_000_000_007
ans = 1
prevSeat = -1
numSeats = 0
for i, c in enumerate(corridor):
if c == 'S':
numSeats += 1
if numSeats > 2 and numSeats % 2 == 1:
ans = ans * (i - prevSeat) % MOD
prevSeat = i... | Solution |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 28786,
"end": 29881
} | class ____(Token):
""" Subclass of Token, carrying the attribute 'attrs' (Tuple)
Examples
========
>>> from sympy.codegen.ast import Node, value_const, pointer_const
>>> n1 = Node([value_const])
>>> n1.attr_params('value_const') # get the parameters of attribute (by name)
()
>>> from ... | Node |
python | django-haystack__django-haystack | haystack/exceptions.py | {
"start": 795,
"end": 916
} | class ____(HaystackError):
"""Raised when incorrect arguments have been provided for spatial."""
pass
| SpatialError |
python | gevent__gevent | src/gevent/_fileobjectcommon.py | {
"start": 20276,
"end": 24359
} | class ____(FileObjectBase):
"""
FileObjectThread()
A file-like object wrapping another file-like object, performing all blocking
operations on that object in a background thread.
.. caution::
Attempting to change the threadpool or lock of an existing FileObjectThread
has undefined ... | FileObjectThread |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_base_aws.py | {
"start": 15534,
"end": 46372
} | class ____:
@mock_aws
def test_get_client_type_set_in_class_attribute(self):
client = boto3.client("emr", region_name="us-east-1")
if client.list_clusters()["Clusters"]:
raise ValueError("AWS not properly mocked")
hook = AwsBaseHook(aws_conn_id="aws_default", client_type="emr... | TestAwsBaseHook |
python | dask__dask | dask/dataframe/dask_expr/_str_accessor.py | {
"start": 3717,
"end": 4405
} | class ____(Reduction):
_parameters = ["frame", "sep", "na_rep"]
@property
def chunk_kwargs(self):
return {"sep": self.sep, "na_rep": self.na_rep}
@property
def combine_kwargs(self):
return self.chunk_kwargs
@property
def aggregate_kwargs(self):
return self.chunk_kw... | Cat |
python | tensorflow__tensorflow | tensorflow/lite/python/util_test.py | {
"start": 17732,
"end": 21046
} | class ____(
test_util.TensorFlowTestCase, parameterized.TestCase
):
def _generate_int8_f32io_concat_residual_tflite(self, number_of_inputs=3):
dtype = float
class ConcatNResidual(tf.keras.layers.Layer):
"""A simple concat and residual Keras Model."""
def __init__(self, number_of_inputs=3, *... | UtilModifyIntegerQuantizedConcatResidualModelIOTypeTest |
python | falconry__falcon | tests/asgi/test_middleware_asgi.py | {
"start": 134,
"end": 256
} | class ____:
async def process_resource(self, req, resp, resource, params):
pass
| MiddlewareIncompatibleWithWSGI_B |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 596543,
"end": 596878
} | 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("RepositoryInvitation", graphql_name="node")
| RepositoryInvitationEdge |
python | vyperlang__vyper | vyper/venom/memory_location.py | {
"start": 3388,
"end": 4754
} | class ____(MemoryLocation):
op: IRAbstractMemLoc
segment: MemoryLocationSegment
def is_empty(self):
return self.segment.is_empty()
@property
def is_offset_fixed(self) -> bool:
return True
@property
def is_size_fixed(self) -> bool:
return True
@property
def... | MemoryLocationAbstract |
python | huggingface__transformers | examples/modular-transformers/modeling_dummy_bert.py | {
"start": 16359,
"end": 19127
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx=None):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = DummyBertAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
... | DummyBertLayer |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/config.py | {
"start": 8901,
"end": 9383
} | class ____(namedtuple("_EvaluationError", "stack reason message error_data")):
def __new__(cls, stack, reason, message, error_data):
return super().__new__(
cls,
check.inst_param(stack, "stack", GrapheneEvaluationStack),
check.inst_param(reason, "reason", GrapheneEvaluati... | EvaluationError |
python | huggingface__transformers | src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py | {
"start": 104422,
"end": 106134
} | class ____(nn.Module):
def __init__(self, embed_dim, hidden_dim, kernel_size, var_pred_dropout):
super().__init__()
self.conv1 = nn.Conv1d(
embed_dim,
hidden_dim,
kernel_size=kernel_size,
padding="same",
)
self.activation_function = nn... | SeamlessM4Tv2VariancePredictor |
python | kamyu104__LeetCode-Solutions | Python/find-missing-observations.py | {
"start": 29,
"end": 516
} | class ____(object):
def missingRolls(self, rolls, mean, n):
"""
:type rolls: List[int]
:type mean: int
:type n: int
:rtype: List[int]
"""
MAX_V = 6
MIN_V = 1
total = sum(rolls)
missing = mean*(n+len(rolls))-total
if missing < MI... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.