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 | fastapi__sqlmodel | docs_src/tutorial/many_to_many/tutorial003_py310.py | {
"start": 456,
"end": 681
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
headquarters: str
hero_links: list[HeroTeamLink] = Relationship(back_populates="team")
| Team |
python | coleifer__peewee | tests/regressions.py | {
"start": 45207,
"end": 45319
} | class ____(TestModel):
name = TextField()
fkma = ForeignKeyField(FKMA, backref='fkmb_set', null=True)
| FKMB |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/schedules/schedules.py | {
"start": 1220,
"end": 9911
} | class ____(graphene.ObjectType):
id = graphene.NonNull(graphene.ID)
name = graphene.NonNull(graphene.String)
cron_schedule = graphene.NonNull(graphene.String)
pipeline_name = graphene.NonNull(graphene.String)
solid_selection = graphene.List(graphene.String)
mode = graphene.NonNull(graphene.Strin... | GrapheneSchedule |
python | scipy__scipy | benchmarks/benchmarks/spatial.py | {
"start": 14281,
"end": 15527
} | class ____(Benchmark):
params = (
[10, 20, 100],
['euclidean', 'minkowski', 'cityblock', 'sqeuclidean', 'cosine',
'correlation', 'hamming', 'jaccard', 'chebyshev', 'canberra',
'braycurtis', 'yule', 'dice', 'rogerstanimoto',
'russellrao', 'sokalsneath', 'minkowski-P3'])
... | XdistWeighted |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 751764,
"end": 753373
} | class ____(VegaLiteSchema):
"""
NumberLocale schema wrapper.
Locale definition for formatting numbers.
Parameters
----------
currency : Sequence[str], :class:`Vector2string`
The currency prefix and suffix (e.g., ["$", ""]).
decimal : str
The decimal point (e.g., ".").
g... | NumberLocale |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_reindex.py | {
"start": 3671,
"end": 47321
} | class ____:
# These are specific reindex-based tests; other indexing tests should go in
# test_indexing
@pytest.mark.xfail(
not IS64 or (is_platform_windows() and not np_version_gt2),
reason="Passes int32 values to DatetimeArray in make_na_array on "
"windows, 32bit linux builds",
... | TestDataFrameSelectReindex |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_extend.py | {
"start": 291,
"end": 524
} | class ____(FooBase):
def bar(self):
return 2
@classmethod
def baz(cls):
return 2
EXTEND_PATH = __name__ + ".Foo"
EXTEND_BASE_PATH = __name__ + ".FooBase"
EXTEND_OVERRIDE_PATH = __name__ + ".NewFoo"
| NewFoo |
python | weaviate__weaviate-python-client | weaviate/embedded.py | {
"start": 834,
"end": 1386
} | class ____:
persistence_data_path: str = os.environ.get("XDG_DATA_HOME", DEFAULT_PERSISTENCE_DATA_PATH)
binary_path: str = os.environ.get("XDG_CACHE_HOME", DEFAULT_BINARY_PATH)
version: str = WEAVIATE_VERSION
port: int = DEFAULT_PORT
hostname: str = "127.0.0.1"
additional_env_vars: Optional[Dict... | EmbeddedOptions |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_map_metrics/column_values_non_null.py | {
"start": 874,
"end": 1446
} | class ____(ColumnMapMetricProvider):
condition_metric_name = "column_values.nonnull"
filter_column_isnull = False
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return ~column.isnull()
@column_condition_partial(engine=SqlAlchemyExecutionEngine)
... | ColumnValuesNonNull |
python | apache__airflow | airflow-core/tests/unit/cluster_policies/__init__.py | {
"start": 3202,
"end": 3733
} | class ____(BaseOperator, ABC):
timeout: timedelta
def task_policy(task: TimedOperator):
if task.task_type == "HivePartitionSensor":
task.queue = "sensor_queue"
if task.timeout > timedelta(hours=48):
task.timeout = timedelta(hours=48)
# [END example_task_cluster_policy]
# [START example... | TimedOperator |
python | huggingface__transformers | tests/quantization/hqq/test_hqq.py | {
"start": 7694,
"end": 10218
} | class ____(unittest.TestCase):
def tearDown(self):
cleanup()
def test_model_serialization(self):
"""
Simple HQQ LLM save/load test
"""
quant_config = HqqConfig(nbits=4, group_size=64)
hqq_runner = HQQLLMRunner(
model_id=MODEL_ID, quant_config=quant_c... | HQQSerializationTest |
python | getsentry__sentry | src/sentry/mail/actions.py | {
"start": 624,
"end": 3111
} | class ____(EventAction):
id = "sentry.mail.actions.NotifyEmailAction"
label = "Send a notification to {targetType} and if none can be found then send a notification to {fallthroughType}"
prompt = "Send a notification"
metrics_slug = "EmailAction"
def __init__(self, *args: Any, **kwargs: Any) -> Non... | NotifyEmailAction |
python | kamyu104__LeetCode-Solutions | Python/max-value-of-equation.py | {
"start": 50,
"end": 650
} | class ____(object):
def findMaxValueOfEquation(self, points, k):
"""
:type points: List[List[int]]
:type k: int
:rtype: int
"""
result = float("-inf")
dq = collections.deque()
for i, (x, y) in enumerate(points):
while dq and points[dq[0]][0... | Solution |
python | huggingface__transformers | src/transformers/models/speech_to_text/modeling_speech_to_text.py | {
"start": 21229,
"end": 22890
} | class ____(PreTrainedModel):
config: Speech2TextConfig
base_model_prefix = "model"
main_input_name = "input_features"
supports_gradient_checkpointing = True
# TODO: tests would need a rewrite to check for correct implementation
# Current tests always assume certain inputs to be passed
_suppo... | Speech2TextPreTrainedModel |
python | psf__requests | src/requests/structures.py | {
"start": 170,
"end": 2470
} | class ____(MutableMapping):
"""A case-insensitive ``dict``-like object.
Implements all methods and operations of
``MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The structure remembers the
case of the last key to be set, and ``... | CaseInsensitiveDict |
python | walkccc__LeetCode | solutions/788. Rotated Digits/788.py | {
"start": 0,
"end": 411
} | class ____:
def rotatedDigits(self, n: int) -> int:
def isGoodNumber(i: int) -> bool:
isRotated = False
for c in str(i):
if c == '0' or c == '1' or c == '8':
continue
if c == '2' or c == '5' or c == '6' or c == '9':
isRotated = True
else:
return F... | Solution |
python | chroma-core__chroma | chromadb/api/types.py | {
"start": 59795,
"end": 59896
} | class ____:
float_inverted_index: Optional[FloatInvertedIndexType] = None
@dataclass
| FloatValueType |
python | Netflix__metaflow | metaflow/_vendor/click/exceptions.py | {
"start": 1076,
"end": 2200
} | class ____(ClickException):
"""An internal exception that signals a usage error. This typically
aborts any further handling.
:param message: the error message to display.
:param ctx: optionally the context that caused this error. Click will
fill in the context automatically in some si... | UsageError |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 73544,
"end": 73813
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
permission_level: Optional[PermissionLevel] = None
user_name: Optional[UserName] = None
| AccessControlRequestForUser |
python | tox-dev__tox | src/tox/config/sets.py | {
"start": 9647,
"end": 11426
} | class ____(ConfigSet):
"""Configuration set for a tox environment."""
def __init__(self, conf: Config, section: Section, env_name: str) -> None:
super().__init__(conf, section, env_name)
self.default_set_env_loader: Callable[[], Mapping[str, str]] = dict
def register_config(self) -> None:
... | EnvConfigSet |
python | apache__airflow | airflow-core/tests/integration/otel/test_otel.py | {
"start": 19502,
"end": 49472
} | class ____:
"""
This test is using a ConsoleSpanExporter so that it can capture
the spans from the stdout and run assertions on them.
It can also be used with otel and jaeger for manual testing.
To export the spans to otel and visualize them with jaeger,
- start breeze with '--integration otel'... | TestOtelIntegration |
python | PyCQA__pylint | tests/functional/u/unsupported/unsupported_binary_operation.py | {
"start": 818,
"end": 879
} | class ____:
pass
A() + B() # [unsupported-binary-operation]
| B |
python | has2k1__plotnine | plotnine/coords/coord_cartesian.py | {
"start": 455,
"end": 3038
} | class ____(coord):
"""
Cartesian coordinate system
Parameters
----------
xlim :
Limits (in data type of the x-aesthetic) for x axis.
If None, then they are automatically computed.
ylim :
Limits (in data type of the x-aesthetic) for y axis.
If None, then they are ... | coord_cartesian |
python | django__django | tests/postgres_tests/models.py | {
"start": 3296,
"end": 3648
} | class ____(PostgreSQLModel):
scene = models.ForeignKey("Scene", models.CASCADE)
character = models.ForeignKey("Character", models.CASCADE)
dialogue = models.TextField(blank=True, null=True)
dialogue_search_vector = SearchVectorField(blank=True, null=True)
dialogue_config = models.CharField(max_lengt... | Line |
python | django__django | tests/forms_tests/tests/test_media.py | {
"start": 270,
"end": 555
} | class ____(MediaAsset):
element_template = '<link href="{path}"{attributes}>'
def __init__(self, href, **attributes):
super().__init__(href, **attributes)
self.attributes["rel"] = "stylesheet"
@override_settings(STATIC_URL="http://media.example.com/static/")
| CSS |
python | pydantic__pydantic | pydantic/_internal/_decorators_v1.py | {
"start": 360,
"end": 527
} | class ____(Protocol):
"""A simple validator, supported for V1 validators and V2 validators."""
def __call__(self, __value: Any) -> Any: ...
| V1OnlyValueValidator |
python | django__django | tests/backends/test_ddl_references.py | {
"start": 448,
"end": 1382
} | class ____(SimpleTestCase):
def setUp(self):
self.reference = Table("table", lambda table: table.upper())
def test_references_table(self):
self.assertIs(self.reference.references_table("table"), True)
self.assertIs(self.reference.references_table("other"), False)
def test_rename_ta... | TableTests |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 49337,
"end": 54055
} | class ____:
a = np.array([0, 0, 1, 0, 2, 3, 4, 0])
b = a.astype(float)
c = a.astype(complex)
d = a.astype(object)
def construct_input_output(self, rng, shape, axis, trim):
"""Construct an input/output test pair for trim_zeros"""
# Standardize axis to a tuple.
if axis is Non... | TestTrimZeros |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/cwise_ops_test.py | {
"start": 28829,
"end": 32754
} | class ____(test.TestCase):
def _compare(self, x, y, use_gpu):
np_min, np_max = np.minimum(x, y), np.maximum(x, y)
with test_util.device(use_gpu=use_gpu):
inx = ops.convert_to_tensor(x)
iny = ops.convert_to_tensor(y)
omin, omax = math_ops.minimum(inx, iny), math_ops.maximum(inx, iny)
t... | MinMaxOpTest |
python | spack__spack | lib/spack/spack/test/web.py | {
"start": 8089,
"end": 8180
} | class ____:
def paginate(self, *args, **kwargs):
return MockPages()
| MockPaginator |
python | apache__airflow | providers/databricks/tests/unit/databricks/plugins/test_databricks_workflow.py | {
"start": 11081,
"end": 15157
} | class ____:
"""Test Databricks Workflow Plugin functionality specific to Airflow 3.x."""
def test_plugin_operator_extra_links_limited_functionality(self):
"""Test that operator_extra_links are limited in Airflow 3.x (only job run link)."""
plugin = DatabricksWorkflowPlugin()
# In Airfl... | TestDatabricksWorkflowPluginAirflow3 |
python | ray-project__ray | python/ray/data/preprocessors/encoder.py | {
"start": 26681,
"end": 36495
} | class ____(SerializablePreprocessorBase):
r"""Convert columns to ``pd.CategoricalDtype``.
Use this preprocessor with frameworks that have built-in support for
``pd.CategoricalDtype`` like LightGBM.
.. warning::
If you don't specify ``dtypes``, fit this preprocessor before splitting
yo... | Categorizer |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 161238,
"end": 163036
} | class ____:
def _test_setdiag_sorted(self, D):
A = self.spcreator(D)
# Force sorted indices
A.has_sorted_indices = False
A.sort_indices()
assert A.has_sorted_indices
# Set the diagonal (only 1 new entry / 1002, so _insert_many is used)
with check_remains_sorte... | _CompressedMixin |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_xs.py | {
"start": 543,
"end": 2760
} | class ____:
def test_xs_level_series(self, multiindex_dataframe_random_data):
df = multiindex_dataframe_random_data
ser = df["A"]
expected = ser[:, "two"]
result = df.xs("two", level=1)["A"]
tm.assert_series_equal(result, expected)
def test_series_getitem_multiindex_xs_b... | TestXSWithMultiIndex |
python | joke2k__faker | tests/providers/test_bank.py | {
"start": 6301,
"end": 6767
} | class ____:
"""Test en_IE bank provider"""
def test_bban(self, faker, num_samples):
for _ in range(num_samples):
assert re.fullmatch(r"\d{23}", faker.bban())
def test_iban(self, faker, num_samples):
for _ in range(num_samples):
iban = faker.iban()
assert... | TestEnIe |
python | pytest-dev__pytest-django | tests/test_fixtures.py | {
"start": 24855,
"end": 26907
} | class ____(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
('app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='MyCustomUser',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_crea... | Migration |
python | pypa__installer | src/installer/exceptions.py | {
"start": 134,
"end": 248
} | class ____(InstallerError):
"""When a wheel source violates a contract, or is not supported."""
| InvalidWheelSource |
python | RaRe-Technologies__gensim | gensim/matutils.py | {
"start": 11716,
"end": 17100
} | class ____:
"""Convert a sequence of dense/sparse vectors into a streamed Gensim corpus object.
See Also
--------
:func:`~gensim.matutils.corpus2csc`
Convert corpus in Gensim format to `scipy.sparse.csc` matrix.
"""
def __init__(self, vecs):
"""
Parameters
----... | Scipy2Corpus |
python | PyCQA__pylint | tests/functional/a/access/access_member_before_definition.py | {
"start": 758,
"end": 1104
} | class ____:
def test_mixin(self):
"""Don't emit access-member-before-definition for mixin classes."""
if self.already_defined:
# pylint: disable=attribute-defined-outside-init
self.already_defined = None
# Test for regression in bitbucket issue 164
# https://bitbucket.org/l... | Mixin |
python | google__pytype | pytype/rewrite/flow/frame_base.py | {
"start": 808,
"end": 928
} | class ____(Exception):
"""Raised when step() is called on a frame with no more opcodes to execute."""
| FrameConsumedError |
python | huggingface__transformers | src/transformers/models/convnext/modeling_convnext.py | {
"start": 2037,
"end": 2514
} | class ____(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: Optional[float] = None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:... | ConvNextDropPath |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 3144,
"end": 5851
} | class ____(JupyterApp, DebugLogFileMixin):
version = VERSION
flags = flags
aliases = aliases
name = "lab"
# Not configurable!
core_config = Instance(CoreConfig, allow_none=True)
app_dir = Unicode("", config=True, help="The app directory to target")
should_build = Bool(True, config=Tru... | BaseExtensionApp |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataform.py | {
"start": 15049,
"end": 18552
} | class ____(GoogleCloudBaseOperator):
"""
Returns WorkflowInvocationActions in a given WorkflowInvocation.
:param project_id: Required. The ID of the Google Cloud project that the task belongs to.
:param region: Required. The ID of the Google Cloud region that the task belongs to.
:param repository_... | DataformQueryWorkflowInvocationActionsOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 341621,
"end": 342482
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of
UpdateEnterpriseMembersCanMakePurchasesSetting
"""
__schema__ = github_schema
__field_names__ = ("enterprise_id", "setting_value", "client_mutation_id")
enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="enterp... | UpdateEnterpriseMembersCanMakePurchasesSettingInput |
python | ray-project__ray | rllib/env/external_multi_agent_env.py | {
"start": 265,
"end": 5487
} | class ____(ExternalEnv):
"""This is the multi-agent version of ExternalEnv."""
def __init__(
self,
action_space: gym.Space,
observation_space: gym.Space,
):
"""Initializes an ExternalMultiAgentEnv instance.
Args:
action_space: Action space of the env.
... | ExternalMultiAgentEnv |
python | spack__spack | lib/spack/spack/database.py | {
"start": 73617,
"end": 73730
} | class ____(SpackError):
"""Raised to request an explicit DB upgrade to the user"""
| ExplicitDatabaseUpgradeError |
python | pytorch__pytorch | test/mobile/lightweight_dispatch/tests_setup.py | {
"start": 3141,
"end": 3425
} | class ____(torch.nn.Module):
def forward(self, b):
a = torch.tensor(3, dtype=torch.int64)
out = torch.empty(size=[1], dtype=torch.float)
torch.div(b, a, out=out)
return [torch.div(b, a, rounding_mode="trunc"), out]
@save_model
| ModelWithStringOptional |
python | ray-project__ray | python/ray/data/_internal/logical/operators/from_operators.py | {
"start": 2744,
"end": 2834
} | class ____(AbstractFrom):
"""Logical operator for `from_blocks`."""
pass
| FromBlocks |
python | readthedocs__readthedocs.org | readthedocs/subscriptions/notifications.py | {
"start": 1373,
"end": 1732
} | class ____(SubscriptionNotificationMixin, EmailNotification):
"""
Subscription has ended.
Notify the customer that the Organization will be disabled *soon* if the
subscription is not renewed for the organization.
"""
name = "subscription_ended"
subject = "Your subscription to Read the Docs... | SubscriptionEndedNotification |
python | pytorch__pytorch | torch/__init__.py | {
"start": 70755,
"end": 70979
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.float
| FloatStorage |
python | coleifer__peewee | peewee.py | {
"start": 155924,
"end": 160013
} | class ____(ColumnBase):
_field_counter = 0
_order = 0
accessor_class = FieldAccessor
auto_increment = False
default_index_type = None
field_type = 'DEFAULT'
unpack = True
def __init__(self, null=False, index=False, unique=False, column_name=None,
default=None, primary_k... | Field |
python | ApeWorX__ape | src/ape_pm/project.py | {
"start": 4224,
"end": 13055
} | class ____(ProjectAPI):
"""
Helps Ape read configurations from foundry projects
and lessens the need of specifying ``config_override:``
for foundry-based dependencies.
"""
_github_client: _GithubClient = github_client
@property
def foundry_config_file(self) -> Path:
return self... | FoundryProject |
python | PrefectHQ__prefect | src/prefect/server/database/dependencies.py | {
"start": 6329,
"end": 7493
} | class ____(Generic[P, R]):
"""Mixin class to delegate all attribute access to a wrapped function
This helps compatibility and echos what the Python method wrapper object
does, and makes subclasses transarent to many introspection techniques.
"""
__slots__ = "_func"
def __init__(self, func: C... | _FuncWrapper |
python | davidhalter__parso | parso/python/tree.py | {
"start": 36712,
"end": 37226
} | class ____(Mapping):
"""
This class exists for the sole purpose of creating an immutable dict.
"""
def __init__(self, dct):
self._dict = dct
def __getitem__(self, key):
return self._dict[key]
def __len__(self):
return len(self._dict)
def __iter__(self):
ret... | UsedNamesMapping |
python | pyca__cryptography | tests/hazmat/primitives/test_xofhash.py | {
"start": 3695,
"end": 4620
} | class ____:
def test_shake256_variable(self, backend, subtests):
vectors = _load_all_params(
os.path.join("hashes", "SHAKE"),
["SHAKE256VariableOut.rsp"],
load_nist_vectors,
)
for vector in vectors:
with subtests.test():
output_... | TestXOFSHAKE256 |
python | keras-team__keras | keras/src/saving/serialization_lib.py | {
"start": 1139,
"end": 1305
} | class ____:
def __init__(self, **config):
self.config = config
def serialize(self):
return serialize_keras_object(self.config)
| SerializableDict |
python | plotly__plotly.py | plotly/graph_objs/scatter/marker/colorbar/title/_font.py | {
"start": 233,
"end": 9949
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter.marker.colorbar.title"
_path_str = "scatter.marker.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | coleifer__peewee | tests/fields.py | {
"start": 13479,
"end": 13744
} | class ____(TestModel):
name = CharField(primary_key=True)
m1 = ForeignKeyField(M1, deferrable='INITIALLY DEFERRED',
on_delete='CASCADE')
@skip_if(IS_MYSQL)
@skip_if(IS_CRDB, 'crdb does not support deferred foreign-key constraints')
| M2 |
python | sanic-org__sanic | sanic/cli/console.py | {
"start": 3022,
"end": 8606
} | class ____(InteractiveConsole):
def __init__(self, app: Sanic, start: Optional[Default] = None):
global repl_app
repl_app = app
locals_available = {
"app": app,
"sanic": sanic,
"do": do,
}
user_locals = {
user_local.name: user_... | SanicREPL |
python | ansible__ansible | test/integration/targets/old_style_vars_plugins/vars_plugins/auto_enabled.py | {
"start": 86,
"end": 247
} | class ____(BaseVarsPlugin):
REQUIRES_ENABLED = False
def get_vars(self, loader, path, entities):
return {'explicitly_auto_enabled': True}
| VarsModule |
python | apache__airflow | providers/telegram/src/airflow/providers/telegram/operators/telegram.py | {
"start": 3078,
"end": 4953
} | class ____(BaseOperator):
"""
This operator allows you to send file to Telegram using Telegram Bot API.
Takes both Telegram Bot API token directly or connection that has Telegram token in password field.
If both supplied, token parameter will be given precedence.
.. seealso::
For more info... | TelegramFileOperator |
python | numba__numba | numba/cuda/cudadecl.py | {
"start": 7232,
"end": 8616
} | class ____(AbstractTemplate):
key = cuda.selp
def generic(self, args, kws):
assert not kws
test, a, b = args
# per docs
# http://docs.nvidia.com/cuda/parallel-thread-execution/index.html#comparison-and-selection-instructions-selp
supported_types = (types.float64, types.... | Cuda_selp |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 16839,
"end": 16932
} | class ____(IterableExportEventsStreamAdjustableRange):
data_field = "pushBounce"
| PushBounce |
python | huggingface__transformers | src/transformers/models/glm/modeling_glm.py | {
"start": 2078,
"end": 2727
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
self.ac... | GlmMLP |
python | coleifer__peewee | tests/sql.py | {
"start": 52069,
"end": 54580
} | class ____(BaseTestCase):
def test_delete_query(self):
query = (User
.delete()
.where(User.c.username != 'charlie')
.limit(3))
self.assertSQL(query, (
'DELETE FROM "users" WHERE ("users"."username" != ?) LIMIT ?'),
['charlie'... | TestDeleteQuery |
python | pytorch__pytorch | test/test_testing.py | {
"start": 33664,
"end": 39929
} | class ____(TestCase):
def test_identifier_tensor_likes(self):
actual = torch.tensor([1, 2, 3, 4])
expected = torch.tensor([1, 2, 5, 6])
for fn in assert_close_with_inputs(actual, expected):
with self.assertRaisesRegex(AssertionError, re.escape("Tensor-likes")):
f... | TestAssertCloseErrorMessage |
python | getsentry__sentry | tests/sentry/models/test_projectownership.py | {
"start": 30429,
"end": 33457
} | class ____(TestCase):
def test_no_actors(self) -> None:
assert resolve_actors([], self.project.id) == {}
def test_basic(self) -> None:
owners = [Owner("user", self.user.email), Owner("team", self.team.slug)]
assert resolve_actors(owners, self.project.id) == {
owners[0]: Acto... | ResolveActorsTestCase |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 48012,
"end": 48526
} | class ____(DeferredLineBase):
"""A line that can be 'unwritten' by adding name to V.graph.removed_buffers"""
def __init__(self, name: str, line: str):
super().__init__(line)
self.name = name
assert not isinstance(line, DeferredLineBase)
def __call__(self) -> Optional[str]:
... | DeferredLine |
python | realpython__materials | python-all-attribute/shapes/circle.py | {
"start": 64,
"end": 206
} | class ____:
def __init__(self, radius):
self.radius = validate(radius)
def area(self):
return _pi * self.radius**2
| Circle |
python | apache__airflow | providers/common/sql/tests/unit/common/sql/operators/test_sql.py | {
"start": 39196,
"end": 43718
} | class ____:
def _construct_operator(self, sql, min_threshold, max_threshold):
dag = DAG("test_dag", schedule=None, start_date=datetime.datetime(2017, 1, 1))
return SQLThresholdCheckOperator(
task_id="test_task",
sql=sql,
min_threshold=min_threshold,
m... | TestThresholdCheckOperator |
python | dask__distributed | distributed/actor.py | {
"start": 7027,
"end": 7443
} | class ____:
"""
An rpc-like object that uses the scheduler's rpc to connect to a worker
"""
def __init__(self, rpc, address):
self.rpc = rpc
self._address = address
def __getattr__(self, key):
async def func(**msg):
msg["op"] = key
result = await sel... | ProxyRPC |
python | kamyu104__LeetCode-Solutions | Python/online-majority-element-in-subarray.py | {
"start": 134,
"end": 1170
} | class ____(object):
def __init__(self, arr):
"""
:type arr: List[int]
"""
Q, ERROR_RATE = 10000, 0.001
self.__K = int(Q/ERROR_RATE).bit_length() # floor(log2(Q/ERROR_RATE))+1 = 24
self.__arr = arr
self.__inv_idx = collections.defaultdict(list)
for i,... | MajorityChecker |
python | pytest-dev__pytest | testing/example_scripts/unittest/test_unittest_plain_async.py | {
"start": 81,
"end": 163
} | class ____(unittest.TestCase):
async def test_foo(self):
assert False
| Test |
python | facebook__pyre-check | tools/incremental_test/specification.py | {
"start": 621,
"end": 2590
} | class ____(ABC):
@abstractmethod
def activate_sandbox(self, environment: Environment) -> ContextManager[Path]:
raise NotImplementedError()
@abstractmethod
def to_json(self) -> Dict[str, Any]:
raise NotImplementedError()
@staticmethod
def from_json(input_json: Dict[str, Any]) ->... | RepositoryState |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_group_index_stats.py | {
"start": 256,
"end": 11051
} | class ____(APITestCase, SnubaTestCase, OccurrenceTestMixin):
endpoint = "sentry-api-0-organization-group-index-stats"
def setUp(self) -> None:
super().setUp()
self.min_ago = before_now(minutes=1)
def get_response(self, *args, **kwargs):
return super().get_response(self.project.orga... | GroupListTest |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 35154,
"end": 35673
} | class ____(RedirectSerializerBase):
"""Override RedirectSerializerBase to sanitize the empty fields."""
from_url = serializers.SerializerMethodField()
to_url = serializers.SerializerMethodField()
def get_from_url(self, obj):
# Overridden only to return ``None`` when the description is ``''``
... | RedirectDetailSerializer |
python | sqlalchemy__sqlalchemy | test/orm/test_query.py | {
"start": 66059,
"end": 79808
} | class ____(QueryTest, AssertsCompiledSQL):
__dialect__ = "default"
def test_function_element_column_labels(self):
users = self.tables.users
sess = fixture_session()
class max_(expression.FunctionElement):
name = "max"
inherit_cache = True
@compiles(max_... | ExpressionTest |
python | redis__redis-py | tests/test_sentinel.py | {
"start": 1159,
"end": 11470
} | class ____:
def __init__(self, servisentinel_ce_name="mymaster", ip="127.0.0.1", port=6379):
self.clients = {}
self.master = {
"ip": ip,
"port": port,
"is_master": True,
"is_sdown": False,
"is_odown": False,
"num-other-sentinels... | SentinelTestCluster |
python | huggingface__transformers | tests/models/flava/test_image_processing_flava.py | {
"start": 1522,
"end": 6927
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_center_crop=True,
crop_size=None,
resample=None,
do_rescale=True,
rescale... | FlavaImageProcessingTester |
python | ApeWorX__ape | src/ape_ethereum/multicall/handlers.py | {
"start": 911,
"end": 4590
} | class ____(ManagerAccessMixin):
def __init__(
self,
address: "AddressType" = MULTICALL3_ADDRESS,
supported_chains: Optional[list[int]] = None,
) -> None:
"""
Initialize a new Multicall session object. By default, there are no calls to make.
"""
self.addres... | BaseMulticall |
python | pytorch__pytorch | torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py | {
"start": 4720,
"end": 4844
} | class ____(NamedTuple):
all_reduce_input: torch.Tensor
event: Optional[torch.Event] # all-reduce event
| AllReduceState |
python | getsentry__sentry | src/sentry/search/events/builder/discover.py | {
"start": 9270,
"end": 18678
} | class ____(TimeseriesQueryBuilder):
"""Create one of two top events queries, which is used for the Top Period &
Top Daily displays
This builder requires a Snuba response dictionary that already contains
the top events for the parameters being queried. eg.
`[{transaction: foo, count: 100}, {transact... | TopEventsQueryBuilder |
python | plotly__plotly.py | plotly/graph_objs/table/_legendgrouptitle.py | {
"start": 233,
"end": 2925
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "table"
_path_str = "table.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be specified a... | Legendgrouptitle |
python | kamyu104__LeetCode-Solutions | Python/distant-barcodes.py | {
"start": 849,
"end": 1369
} | class ____(object):
def rearrangeBarcodes(self, barcodes):
"""
:type barcodes: List[int]
:rtype: List[int]
"""
cnts = collections.Counter(barcodes)
sorted_cnts = [[v, k] for k, v in cnts.iteritems()]
sorted_cnts.sort(reverse=True)
i = 0
for v,... | Solution2 |
python | PrefectHQ__prefect | src/prefect/futures.py | {
"start": 19736,
"end": 25670
} | class ____(NamedTuple, Generic[R]):
"""A named 2-tuple of sets.
multiple inheritance supported in 3.11+, use typing_extensions.NamedTuple
"""
done: set[PrefectFuture[R]]
not_done: set[PrefectFuture[R]]
def wait(
futures: list[PrefectFuture[R]], timeout: float | None = None
) -> DoneAndNotDon... | DoneAndNotDoneFutures |
python | kubernetes-client__python | kubernetes/client/models/v1_projected_volume_source.py | {
"start": 383,
"end": 5411
} | 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... | V1ProjectedVolumeSource |
python | networkx__networkx | networkx/algorithms/tests/test_voronoi.py | {
"start": 60,
"end": 3477
} | class ____:
"""Unit tests for the Voronoi cells function."""
def test_isolates(self):
"""Tests that a graph with isolated nodes has all isolates in
one block of the partition.
"""
G = nx.empty_graph(5)
cells = nx.voronoi_cells(G, {0, 2, 4})
expected = {0: {0}, 2... | TestVoronoiCells |
python | tiangolo__fastapi | scripts/people.py | {
"start": 2015,
"end": 2093
} | class ____(BaseModel):
cursor: str
node: DiscussionsNode
| DiscussionsEdge |
python | huggingface__transformers | src/transformers/models/qwen2_vl/image_processing_qwen2_vl.py | {
"start": 1714,
"end": 3675
} | class ____(ImagesKwargs, total=False):
r"""
min_pixels (`int`, *optional*, defaults to `56 * 56`):
The min pixels of the image to resize the image.
max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
The max pixels of the image to resize the image.
patch_size (`int`, *optional*... | Qwen2VLImageProcessorKwargs |
python | django__django | django/contrib/auth/forms.py | {
"start": 13417,
"end": 17084
} | class ____(forms.Form):
email = forms.EmailField(
label=_("Email"),
max_length=254,
widget=forms.EmailInput(attrs={"autocomplete": "email"}),
)
def send_mail(
self,
subject_template_name,
email_template_name,
context,
from_email,
to_em... | PasswordResetForm |
python | ray-project__ray | doc/source/serve/doc_code/monitoring/logging_config.py | {
"start": 1415,
"end": 1751
} | class ____:
def __call__(self):
logger = logging.getLogger("ray.serve")
logger.info("hello world")
serve.run(Model.bind())
resp = requests.get("http://localhost:8000/")
# __enable_access_log_end__
# __application_and_deployment_start__
import requests
import logging
from ray import serve
@se... | Model |
python | aimacode__aima-python | gui/grid_mdp.py | {
"start": 19454,
"end": 21926
} | class ____(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self.frame = tk.Frame(self)
self.frame.pack()
self.controller = controller
def create_button... | BuildMDP |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_group_current_release.py | {
"start": 468,
"end": 4551
} | class ____(APITestCase):
def _set_up_current_release(
self, group_seen_on_latest_release: bool
) -> tuple[Group, dict[str, GroupRelease]]:
clock = MockClock()
# Create several of everything, to exercise all filtering clauses.
def set_up_organization() -> tuple[Group, dict[str, ... | GroupCurrentReleaseTest |
python | catalyst-team__catalyst | catalyst/runners/runner.py | {
"start": 1200,
"end": 18835
} | class ____(IRunner):
"""Single-stage deep learning Runner with user-friendly API.
Runner supports the logic for deep learning pipeline configuration
with pure python code.
Please check the examples for intuition.
Args:
*args: `IRunner` args (model, engine)
**kwargs: `IRunner` kwarg... | Runner |
python | keras-team__keras | keras/src/ops/core.py | {
"start": 32260,
"end": 34914
} | class ____(Operation):
def __init__(self, dtype=None, sparse=None, ragged=None, *, name=None):
super().__init__(name=name)
self.dtype = None if dtype is None else backend.standardize_dtype(dtype)
self.sparse = sparse
self.ragged = ragged
def call(self, x):
return backend... | ConvertToTensor |
python | coleifer__peewee | playhouse/dataset.py | {
"start": 12097,
"end": 12306
} | class ____(CSVExporter):
def export(self, file_obj, header=True, **kwargs):
kwargs.setdefault('delimiter', '\t')
return super(TSVExporter, self).export(file_obj, header, **kwargs)
| TSVExporter |
python | coleifer__peewee | tests/models.py | {
"start": 166555,
"end": 168532
} | class ____(BaseTestCase):
def test_model_reprs(self):
class User(Model):
username = TextField(primary_key=True)
class Tweet(Model):
user = ForeignKeyField(User, backref='tweets')
content = TextField()
timestamp = TimestampField()
class EAV(Mode... | TestModelFieldReprs |
python | conda__conda | conda/core/path_actions.py | {
"start": 5558,
"end": 5701
} | class ____(Action, metaclass=ABCMeta):
@abstractproperty
def target_full_paths(self):
raise NotImplementedError()
| MultiPathAction |
python | numba__numba | numba/tests/test_python_int.py | {
"start": 187,
"end": 1690
} | class ____(unittest.TestCase):
# Issue #474: ints should be returned rather than longs under Python 2,
# as much as possible.
def test_int_return_type(self, flags=force_pyobj_flags,
int_type=types.int64, operands=(3, 4)):
pyfunc = return_int
cfunc = jit((int_ty... | TestPythonInt |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 32793,
"end": 35087
} | class ____(nn.Module):
def __init__(self, config: GroupViTVisionConfig) -> None:
super().__init__()
self.config = config
self.stages = nn.ModuleList(
[
GroupViTStage(
config=config,
depth=config.depths[i],
... | GroupViTVisionEncoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.