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 | catalyst-team__catalyst | catalyst/core/callback.py | {
"start": 2756,
"end": 4054
} | class ____(ICallback):
"""
An abstraction that lets you customize your experiment run logic.
Args:
order: flag from ``CallbackOrder``
To give users maximum flexibility and extensibility Catalyst supports
callback execution anywhere in the training loop:
.. code:: bash
-- expe... | Callback |
python | plotly__plotly.py | codegen/utils.py | {
"start": 32793,
"end": 34485
} | class ____(PlotlyNode):
def __init__(self, array_node, plotly_schema):
"""
Create node that represents element defaults properties
(e.g. layout.annotationdefaults). Construct as a wrapper around the
corresponding array property node (e.g. layout.annotations)
Parameters
... | ElementDefaultsNode |
python | huggingface__transformers | src/transformers/models/qwen3_vl/modeling_qwen3_vl.py | {
"start": 11723,
"end": 15962
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Qwen3VLTextConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
... | Qwen3VLTextRotaryEmbedding |
python | mlflow__mlflow | tests/paddle/test_paddle_model_export.py | {
"start": 1271,
"end": 11465
} | class ____(NamedTuple):
model: Any
inference_dataframe: Any
def get_dataset():
X, y = load_diabetes(return_X_y=True)
min_max_scaler = preprocessing.MinMaxScaler()
X_min_max = min_max_scaler.fit_transform(X)
X_normalized = preprocessing.scale(X_min_max, with_std=False)
X_train, X_test, y_... | ModelWithData |
python | hyperopt__hyperopt | hyperopt/tests/unit/test_pchoice.py | {
"start": 2533,
"end": 5341
} | class ____(unittest.TestCase):
# test that that a space with a pchoice in it is
# (a) accepted for each algo (random, tpe, anneal)
# and
# (b) handled correctly.
#
def setUp(self):
self.space = hp.pchoice("a", [(0.1, 0), (0.2, 1), (0.3, 2), (0.4, 3)])
self.trials = Trials()
... | TestSimpleFMin |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/sensors/bigquery.py | {
"start": 1484,
"end": 6151
} | class ____(BaseSensorOperator):
"""
Checks for the existence of a table in Google Bigquery.
:param project_id: The Google cloud project in which to look for the table.
The connection supplied to the hook must provide
access to the specified project.
:param dataset_id: The name of the da... | BigQueryTableExistenceSensor |
python | tensorflow__tensorflow | tensorflow/python/keras/constraints.py | {
"start": 4229,
"end": 4491
} | class ____(Constraint):
"""Constrains the weights to be non-negative.
Also available via the shortcut function `tf.keras.constraints.non_neg`.
"""
def __call__(self, w):
return w * math_ops.cast(math_ops.greater_equal(w, 0.), backend.floatx())
| NonNeg |
python | getlogbook__logbook | src/logbook/utils.py | {
"start": 2741,
"end": 5604
} | class ____:
def __init__(self, func, message, obj=None, objtype=None):
super().__init__()
self._func = func
self._message = message
self._obj = obj
self._objtype = objtype
def _get_underlying_func(self):
returned = self._func
if isinstance(returned, class... | _DeprecatedFunction |
python | numba__numba | numba/tests/npyufunc/test_vectorize_decor.py | {
"start": 2220,
"end": 2309
} | class ____(unittest.TestCase, BaseVectorizeDecor):
target = 'cpu'
| TestCPUVectorizeDecor |
python | mwaskom__seaborn | seaborn/_core/scales.py | {
"start": 7338,
"end": 12915
} | class ____(Scale):
"""
A categorical scale without relative importance / magnitude.
"""
# Categorical (convert to strings), un-sortable
values: tuple | str | list | dict | None = None
order: list | None = None
_priority: ClassVar[int] = 4
def _setup(
self, data: Series, prop: ... | Nominal |
python | pyinstaller__pyinstaller | PyInstaller/loader/pyimod02_importers.py | {
"start": 26184,
"end": 29280
} | class ____:
"""
Resource reader for importlib.resources / importlib_resources support.
Supports only on-disk resources, which should cover the typical use cases, i.e., the access to data files;
PyInstaller collects data files onto filesystem, and as of v6.0.0, the embedded PYZ archive is guaranteed
... | PyiFrozenResourceReader |
python | django-mptt__django-mptt | mptt/templatetags/mptt_tags.py | {
"start": 480,
"end": 973
} | class ____(template.Node):
def __init__(self, model, context_var):
self.model = model
self.context_var = context_var
def render(self, context):
cls = apps.get_model(*self.model.split("."))
if cls is None:
raise template.TemplateSyntaxError(
_("full_tr... | FullTreeForModelNode |
python | django__django | django/test/testcases.py | {
"start": 56291,
"end": 60323
} | class ____:
"""Descriptor class for deferred condition checking."""
def __init__(self, *conditions):
self.conditions = conditions
def add_condition(self, condition, reason):
return self.__class__(*self.conditions, (condition, reason))
def __get__(self, instance, cls=None):
# T... | CheckCondition |
python | django__django | tests/gis_tests/inspectapp/models.py | {
"start": 43,
"end": 397
} | class ____(models.Model):
f_decimal = models.FloatField()
f_float = models.FloatField()
f_int = models.IntegerField()
f_char = models.CharField(max_length=10)
f_date = models.DateField()
f_datetime = models.DateTimeField()
f_time = models.TimeField()
geom = models.PolygonField()
poin... | AllOGRFields |
python | django__django | tests/admin_inlines/models.py | {
"start": 4240,
"end": 4457
} | class ____(models.Model):
person = models.OneToOneField(Person, models.CASCADE, primary_key=True)
weaknesses = models.ManyToManyField(
OutfitItem, through="ShoppingWeakness", blank=True
)
| Fashionista |
python | huggingface__transformers | src/transformers/models/vivit/modeling_vivit.py | {
"start": 13755,
"end": 14278
} | class ____(nn.Module):
def __init__(self, config: VivitConfig):
super().__init__()
self.config = config
self.layer = nn.ModuleList([VivitLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(self, hidden_states: torch.Tensor) ->... | VivitEncoder |
python | plotly__plotly.py | plotly/graph_objs/isosurface/_colorbar.py | {
"start": 233,
"end": 61532
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface"
_path_str = "isosurface.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"minexponent",
... | ColorBar |
python | mlflow__mlflow | mlflow/spark/autologging.py | {
"start": 9287,
"end": 10449
} | class ____(RunContextProvider):
"""
Context provider used when there's no active run. Accumulates datasource read information,
then logs that information to the next-created run. Note that this doesn't clear the accumulated
info when logging them to the next run, so it will be logged to any successive r... | SparkAutologgingContext |
python | dask__distributed | distributed/gc.py | {
"start": 5357,
"end": 9207
} | class ____:
"""
An object that hooks itself into the gc callbacks to collect
timing and memory statistics, and log interesting info.
Don't instantiate this directly except for tests.
Instead, use the global instance.
"""
N_SAMPLES = 30
def __init__(self, info_over_frac=0.1, info_over_... | GCDiagnosis |
python | scipy__scipy | scipy/optimize/tests/test_minpack.py | {
"start": 15653,
"end": 42688
} | class ____:
def setup_method(self):
self.y = array([1.0, 3.2, 9.5, 13.7])
self.x = array([1.0, 2.0, 3.0, 4.0])
def test_one_argument(self):
def func(x,a):
return x**a
popt, pcov = curve_fit(func, self.x, self.y)
assert_(len(popt) == 1)
assert_(pcov.sh... | TestCurveFit |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-faker/source_faker/streams.py | {
"start": 4310,
"end": 6705
} | class ____(Stream, IncrementalMixin):
primary_key = "id"
cursor_field = "updated_at"
def __init__(self, count: int, seed: int, parallelism: int, records_per_slice: int, always_updated: bool, **kwargs):
super().__init__(**kwargs)
self.count = count
self.seed = seed
self.recor... | Purchases |
python | walkccc__LeetCode | solutions/856. Score of Parentheses/856.py | {
"start": 0,
"end": 232
} | class ____:
def scoreOfParentheses(self, s: str) -> int:
ans = 0
layer = 0
for a, b in itertools.pairwise(s):
if a + b == '()':
ans += 1 << layer
layer += 1 if a == '(' else -1
return ans
| Solution |
python | pappasam__jedi-language-server | jedi_language_server/notebook_utils.py | {
"start": 8188,
"end": 8541
} | class ____(LanguageServer):
def __init__(self, server: LanguageServer):
self._wrapped = server
self._workspace = WorkspaceWrapper(server.workspace)
@property
def workspace(self) -> Workspace:
return self._workspace
def __getattr__(self, name: str) -> Any:
return getattr... | ServerWrapper |
python | getsentry__sentry | tests/sentry/issues/test_occurrence_consumer.py | {
"start": 14787,
"end": 27735
} | class ____(IssueOccurrenceTestBase):
def run_test(self, message: dict[str, Any]) -> None:
_get_kwargs(message)
def run_invalid_schema_test(
self, message: dict[str, Any], expected_error: type[Exception]
) -> None:
with pytest.raises(expected_error):
self.run_test(message... | ParseEventPayloadTest |
python | donnemartin__interactive-coding-challenges | graphs_trees/bst_successor/test_bst_successor.py | {
"start": 18,
"end": 1192
} | class ____(unittest.TestCase):
def test_bst_successor_empty(self):
bst_successor = BstSuccessor()
bst_successor.get_next(None)
def test_bst_successor(self):
nodes = {}
node = Node(5)
nodes[5] = node
bst = Bst(nodes[5])
nodes[3] = bst.insert(3)
no... | TestBstSuccessor |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-make-median-of-array-equal-to-k.py | {
"start": 68,
"end": 1594
} | class ____(object):
def minOperationsToMakeMedianK(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def nth_element(nums, n, left=0, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
m... | Solution |
python | django__django | django/db/models/fields/mixins.py | {
"start": 110,
"end": 972
} | class ____:
"""
An API for working with the model's fields value cache.
Subclasses must set self.cache_name to a unique entry for the cache -
typically the field’s name.
"""
@cached_property
def cache_name(self):
raise NotImplementedError
def get_cached_value(self, instance, d... | FieldCacheMixin |
python | allegroai__clearml | clearml/backend_api/services/v2_23/frames.py | {
"start": 86495,
"end": 104983
} | class ____(NonStrictDataModel):
"""
:param id: Frame id
:type id: str
:param augmentation: List of augmentations
:type augmentation: Sequence[Augmentation]
:param timestamp: Frame's offset in milliseconds, used primarily for video
content. Used for the default frames sorting as the secon... | Snippet |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 58730,
"end": 59075
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional["QueryResponse"] = Field(default=None, descript... | InlineResponse20021 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 4216,
"end": 4841
} | class ____(sgqlc.types.Enum):
"""The possible states for a check suite or run status.
Enumeration Choices:
* `COMPLETED`: The check suite or run has been completed.
* `IN_PROGRESS`: The check suite or run is in progress.
* `PENDING`: The check suite or run is in pending state.
* `QUEUED`: The ... | CheckStatusState |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/contrib/regular_languages/regex_parser.py | {
"start": 2414,
"end": 2974
} | class ____(Node):
"""
Mark a variable in the regular grammar. This will be translated into a
named group. Each variable can have his own completer, validator, etc..
:param childnode: The grammar which is wrapped inside this variable.
:param varname: String.
"""
def __init__(self, childnode... | Variable |
python | django__django | tests/auth_tests/models/with_integer_username.py | {
"start": 427,
"end": 681
} | class ____(AbstractBaseUser):
username = models.IntegerField()
password = models.CharField(max_length=255)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ["username", "password"]
objects = IntegerUsernameUserManager()
| IntegerUsernameUser |
python | jazzband__django-waffle | test_app/views.py | {
"start": 3198,
"end": 3277
} | class ____(WaffleFlagMixin, BaseWaffleView):
waffle_flag = '!foo'
| FlagOffView |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataproc.py | {
"start": 20213,
"end": 30503
} | class ____:
def test_image_version(self):
with pytest.raises(ValueError, match="custom_image and image_version"):
ClusterGenerator(
custom_image="custom_image",
image_version="image_version",
project_id=GCP_PROJECT,
cluster_name=CLU... | TestsClusterGenerator |
python | coleifer__peewee | peewee.py | {
"start": 160302,
"end": 160371
} | class ____(IntegerField):
field_type = 'SMALLINT'
| SmallIntegerField |
python | pdm-project__pdm | src/pdm/builders/editable.py | {
"start": 102,
"end": 1060
} | class ____(EnvBuilder):
"""Build egg-info in isolated env with managed Python."""
@wrap_error
def prepare_metadata(self, out_dir: str) -> str:
if self.isolated:
self.install(self._requires, shared=True)
requires = self._hook.get_requires_for_build_editable(self.config_settin... | EditableBuilder |
python | Textualize__textual | src/textual/css/tokenize.py | {
"start": 6965,
"end": 9283
} | class ____:
"""State machine for the tokenizer.
Attributes:
EXPECT: The initial expectation of the tokenizer. Since we start tokenizing
at the root scope, we might expect to see either a variable or selector, for example.
STATE_MAP: Maps token names to Expects, defines the sets of v... | TCSSTokenizerState |
python | sphinx-doc__sphinx | tests/roots/test-ext-autosummary/autosummary_dummy_module.py | {
"start": 669,
"end": 961
} | class ____(Exception):
pass
#: a module-level attribute
qux = 2
#: a module-level attribute that has been excluded from __all__
quuz = 2
considered_as_imported = Class()
non_imported_member = Class()
""" This attribute has a docstring, so it is recognized as a not-imported member """
| _Exc |
python | walkccc__LeetCode | solutions/37. Sudoku Solver/37.py | {
"start": 0,
"end": 703
} | class ____:
def solveSudoku(self, board: list[list[str]]) -> None:
def isValid(row: int, col: int, c: str) -> bool:
for i in range(9):
if (board[i][col] == c or
board[row][i] == c or
board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == c):
return False
... | Solution |
python | doocs__leetcode | lcof/面试题33. 二叉搜索树的后序遍历序列/Solution.py | {
"start": 0,
"end": 441
} | class ____:
def verifyPostorder(self, postorder: List[int]) -> bool:
def dfs(l, r):
if l >= r:
return True
v = postorder[r]
i = l
while i < r and postorder[i] < v:
i += 1
if any(x < v for x in postorder[i:r]):
... | Solution |
python | justquick__django-activity-stream | actstream/admin.py | {
"start": 559,
"end": 883
} | class ____(ModelAdmin):
list_display = ('__str__', 'user', 'follow_object', 'actor_only', 'started')
list_editable = ('user',)
list_filter = ('user', 'started',)
raw_id_fields = ('user', 'content_type')
admin.site.register(models.Action, ActionAdmin)
admin.site.register(models.Follow, FollowAdmin)
| FollowAdmin |
python | jupyterlab__jupyterlab | jupyterlab/handlers/announcements.py | {
"start": 3818,
"end": 4545
} | class ____(CheckForUpdateABC):
"""Check update version that does nothing.
This is provided for administrators that want to
turn off requesting external resources.
Args:
version: Current JupyterLab version
Attributes:
version - str: Current JupyterLab version
logger - loggi... | NeverCheckForUpdate |
python | redis__redis-py | redis/exceptions.py | {
"start": 4103,
"end": 4376
} | class ____(ResponseError):
"""
Error indicated CROSSSLOT error received from cluster.
A CROSSSLOT error is generated when keys in a request don't hash to the
same slot.
"""
message = "Keys in request don't hash to the same slot"
| ClusterCrossSlotError |
python | astropy__astropy | astropy/extern/ply/yacc.py | {
"start": 116966,
"end": 137736
} | class ____(object):
def __init__(self, pdict, log=None):
self.pdict = pdict
self.start = None
self.error_func = None
self.tokens = None
self.modules = set()
self.grammar = []
self.error = False
if log is None:
self... | ParserReflect |
python | bokeh__bokeh | tests/unit/bokeh/core/test_has_props.py | {
"start": 2570,
"end": 2632
} | class ____(Parent):
int1 = Override(default=20)
| OverrideChild |
python | networkx__networkx | networkx/algorithms/assortativity/tests/test_pairs.py | {
"start": 1675,
"end": 3008
} | class ____(BaseTestDegreeMixing):
def test_node_degree_xy_undirected(self):
xy = sorted(nx.node_degree_xy(self.P4))
xy_result = sorted([(1, 2), (2, 1), (2, 2), (2, 2), (1, 2), (2, 1)])
assert xy == xy_result
def test_node_degree_xy_undirected_nodes(self):
xy = sorted(nx.node_deg... | TestDegreeMixingXY |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 35181,
"end": 35346
} | class ____(FontConstantsBase):
script_space = 0.1
sup1 = 0.8
sub2 = 0.6
delta = 0.05
delta_slanted = 0.3
delta_integral = 0.3
| STIXFontConstants |
python | nedbat__coveragepy | tests/test_debug.py | {
"start": 13289,
"end": 15473
} | class ____(CoverageTest):
"""Tests of coverage.debug.short_stack."""
run_in_temp_dir = False
def test_short_stack(self) -> None:
stack = f_one().splitlines()
assert 4 == len(stack)
assert "test_short_stack" in stack[0]
assert "f_one" in stack[1]
assert "f_two" in st... | ShortStackTest |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_repositories.py | {
"start": 360,
"end": 9718
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.org = self.create_organization(owner=self.user, name="baz")
self.url = reverse("sentry-api-0-organization-repositories", args=[self.org.slug])
self.login_as(user=self.user)
def test_simple(self) -> None:
... | OrganizationRepositoriesListTest |
python | doocs__leetcode | solution/0900-0999/0935.Knight Dialer/Solution.py | {
"start": 0,
"end": 483
} | class ____:
def knightDialer(self, n: int) -> int:
f = [1] * 10
for _ in range(n - 1):
g = [0] * 10
g[0] = f[4] + f[6]
g[1] = f[6] + f[8]
g[2] = f[7] + f[9]
g[3] = f[4] + f[8]
g[4] = f[0] + f[3] + f[9]
g[6] = f[0] + ... | Solution |
python | walkccc__LeetCode | solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.py | {
"start": 0,
"end": 795
} | class ____:
def sumOfPower(self, nums: list[int], k: int) -> int:
MOD = 1_000_000_007
n = len(nums)
# dp[i][j] := the number of subsequences in nums[0..i) that sums to k
dp = [[0] * (k + 1) for _ in range(n + 1)]
dp[0][0] = 1
for i in range(1, n + 1):
num = nums[i - 1]
for j in ra... | Solution |
python | streamlit__streamlit | lib/streamlit/runtime/caching/storage/local_disk_cache_storage.py | {
"start": 4531,
"end": 8932
} | class ____(CacheStorage):
"""Cache storage that persists data to disk
This is the default cache persistence layer for `@st.cache_data`.
"""
def __init__(self, context: CacheStorageContext) -> None:
self.function_key = context.function_key
self.persist = context.persist
self._ttl... | LocalDiskCacheStorage |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 29959,
"end": 30125
} | class ____(ExprNode):
__slots__ = ("keys", "values")
@property
def is_literal_value(self):
return all(v.is_literal_value for v in self.values)
| Dict |
python | pytorch__pytorch | test/distributed/checkpoint/test_file_system_checkpoint_cpu.py | {
"start": 9241,
"end": 19937
} | class ____(ShardedTensorTestBase):
@property
def world_size(self) -> int:
return 2
def get_file_path(self) -> str:
paths = [tempfile.mkdtemp()] if dist.get_rank() == 0 else [None]
dist.broadcast_object_list(paths)
return paths[0]
def load_tensor(self, tensor: ShardedTen... | TestDistributedReshardOnLoad |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/general_tests/seven_tests/test_seven.py | {
"start": 2238,
"end": 3161
} | class ____(Foo):
pass
def test_is_subclass():
assert is_subclass(Bar, Foo)
assert not is_subclass(Foo, Bar)
assert is_subclass(dg.DagsterType, dg.DagsterType)
assert is_subclass(str, str)
assert is_subclass(ListType, dg.DagsterType)
assert not is_subclass(dg.DagsterType, ListType)
ass... | Bar |
python | getsentry__sentry | tests/snuba/models/test_group.py | {
"start": 12828,
"end": 19268
} | class ____(TestCase, SnubaTestCase, PerformanceIssueTestCase):
def setUp(self) -> None:
super().setUp()
self.project = self.create_project()
group_fingerprint = f"{PerformanceNPlusOneGroupType.type_id}-group1"
event_data_a = load_data(
"transaction-n-plus-one",
... | GroupTestSnubaPerformanceIssue |
python | realpython__materials | django-migrations/bitcoin_tracker/historical_data/migrations/0002_switch_to_decimals.py | {
"start": 92,
"end": 393
} | class ____(migrations.Migration):
dependencies = [("historical_data", "0001_initial")]
operations = [
migrations.AlterField(
model_name="pricehistory",
name="volume",
field=models.DecimalField(decimal_places=3, max_digits=7),
)
]
| Migration |
python | graphql-python__graphene | graphene/types/tests/test_objecttype.py | {
"start": 293,
"end": 378
} | class ____(ObjectType):
field1 = Field(MyType)
field2 = Field(MyType)
| Container |
python | huggingface__transformers | src/transformers/models/vits/modeling_vits.py | {
"start": 31272,
"end": 35676
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
embed_dim = config.speaker_embedding_size
filter_channels = config.hidden_size
self.conv_pre = nn.Conv1d(filter_channels, filter_channels, 1)
self.conv_proj = nn.Conv1d(filter_channels, filter_channels, 1)... | VitsStochasticDurationPredictor |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/job_base.py | {
"start": 458,
"end": 1830
} | class ____(ABC):
"""IJob is a wrapper interface for JobDefinitions to be used as parameters to Dagster's
core execution APIs. This enables these execution APIs to operate on both in memory job
definitions to be executed in the current process (InMemoryJob) as well as definitions that
can be reconstruct... | IJob |
python | numba__numba | numba/cuda/cudamath.py | {
"start": 1508,
"end": 1863
} | class ____(ConcreteTemplate):
key = math.atan2
cases = [
signature(types.float64, types.int64, types.int64),
signature(types.float64, types.uint64, types.uint64),
signature(types.float32, types.float32, types.float32),
signature(types.float64, types.float64, types.float64),
]... | Math_atan2 |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_tm_future_annotations_sync.py | {
"start": 148092,
"end": 153175
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
"""try a bunch of common mappings using the new style"""
__dialect__ = "default"
def test_employee_joined_inh(self, decl_base: Type[DeclarativeBase]):
global str50, str30, opt_str50
str50 = Annotated[str, 50]
str30 = Annota... | AllYourFavoriteHitsTest |
python | bottlepy__bottle | bottle.py | {
"start": 142180,
"end": 142330
} | class ____(ServerAdapter):
""" Extend ServerAdapter for adding custom event loop """
def get_event_loop(self):
pass
| AsyncioServerAdapter |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/atrous_conv2d_test.py | {
"start": 9430,
"end": 10577
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testAtrousDepthwiseConv2DForward(self):
strides = [1, 1, 1, 1]
with self.session():
# Input: [batch, height, width, input_depth]
height = 9
for width in [9, 10]: # Test both odd and even width.
x_shape = [2, height, widt... | AtrousDepthwiseConv2DTest |
python | walkccc__LeetCode | solutions/261. Graph Valid Tree/261-2.py | {
"start": 0,
"end": 557
} | class ____:
def __init__(self, n: int):
self.count = n
self.id = list(range(n))
self.rank = [0] * n
def unionByRank(self, u: int, v: int) -> None:
i = self._find(u)
j = self._find(v)
if i == j:
return
if self.rank[i] < self.rank[j]:
self.id[i] = j
elif self.rank[i] > sel... | UnionFind |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_format12.py | {
"start": 315,
"end": 1820
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format12.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = ... | TestCompareXLSXFiles |
python | sqlalchemy__sqlalchemy | test/sql/test_compare.py | {
"start": 64048,
"end": 69139
} | class ____(CoreFixtures, fixtures.TestBase):
@classmethod
def setup_test_class(cls):
# TODO: we need to get dialects here somehow, perhaps in test_suite?
[
importlib.import_module("sqlalchemy.dialects.%s" % d)
for d in dialects.__all__
if not d.startswith("_")... | CompareAndCopyTest |
python | coleifer__peewee | peewee.py | {
"start": 161435,
"end": 161613
} | class ____(Field):
field_type = 'FLOAT'
def adapt(self, value):
try:
return float(value)
except ValueError:
return value
| FloatField |
python | pytorch__pytorch | test/torch_np/numpy_tests/fft/test_helper.py | {
"start": 5468,
"end": 5872
} | class ____(TestCase):
def test_definition(self):
x = [0, 1, 2, 3, 4, -4, -3, -2, -1]
assert_array_almost_equal(9 * fft.fftfreq(9), x)
assert_array_almost_equal(9 * pi * fft.fftfreq(9, pi), x)
x = [0, 1, 2, 3, 4, -5, -4, -3, -2, -1]
assert_array_almost_equal(10 * fft.fftfreq(1... | TestFFTFreq |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 88744,
"end": 93520
} | class ____(Operation):
def __init__(self, axis=-1, epsilon=None, rms_scaling=False, *, name=None):
super().__init__(name=name)
self.axis = axis
self.epsilon = epsilon
self.rms_scaling = rms_scaling
def compute_output_spec(self, x, gamma, beta):
return KerasTensor(shape=x... | LayerNorm |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 957297,
"end": 957753
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of RevokeMigratorRole"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "success")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mut... | RevokeMigratorRolePayload |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1255773,
"end": 1262769
} | class ____(RepeatSpec):
"""
NonLayerRepeatSpec schema wrapper.
Base interface for a repeat specification.
Parameters
----------
repeat : dict, Sequence[str], :class:`RepeatMapping`
Definition for fields to be repeated. One of: 1) An array of fields to be repeated.
If ``"repeat"... | NonLayerRepeatSpec |
python | pytorch__pytorch | test/test_functional_autograd_benchmark.py | {
"start": 378,
"end": 2659
} | class ____(TestCase):
def _test_runner(self, model, disable_gpu=False):
# Note about windows:
# The temporary file is exclusively open by this process and the child process
# is not allowed to open it again. As this is a simple smoke test, we choose for now
# not to run this on windo... | TestFunctionalAutogradBenchmark |
python | pydata__xarray | xarray/tests/test_tutorial.py | {
"start": 835,
"end": 1517
} | class ____:
def test_download_from_github(self, tmp_path) -> None:
cache_dir = tmp_path / tutorial._default_cache_dir_name
ds = tutorial.load_datatree("tiny", cache_dir=cache_dir)
tiny = DataTree.from_dict({"/": DataArray(range(5), name="tiny").to_dataset()})
assert_identical(ds, tin... | TestLoadDataTree |
python | google__pytype | pytype/tests/test_typing1.py | {
"start": 14545,
"end": 16771
} | class ____(test_base.BaseTest):
"""Tests for importing typing constructs only present in some Python versions.
We want pytype to behave as follows:
Is the construct supported by pytype?
|
-> No: Log a plain [not supported-yet] error.
|
-> Yes: Is the construct being imported from typing_extensions or ty... | NotSupportedYetTest |
python | keras-team__keras | keras/src/quantizers/gptq_core_test.py | {
"start": 831,
"end": 3186
} | class ____(layers.Layer):
"""A toy transformer block with a quantizable Dense layer."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.dense = layers.Dense(128)
def call(self, inputs):
return self.dense(inputs)
def _get_model_with_backbone(
has_transformer_laye... | TransformerBlock |
python | jazzband__django-pipeline | pipeline/storage.py | {
"start": 3146,
"end": 3602
} | class ____(NonPackagingMixin, PipelineStorage):
pass
if _CACHED_STATIC_FILES_STORAGE_AVAILABLE:
class PipelineCachedStorage(PipelineMixin, CachedStaticFilesStorage):
# Deprecated since Django 2.2
# Removed in Django 3.1
pass
class NonPackagingPipelineCachedStorage(NonPackagingMix... | NonPackagingPipelineStorage |
python | spack__spack | lib/spack/spack/test/cmd_extensions.py | {
"start": 271,
"end": 10391
} | class ____:
"""Helper class to simplify the creation of simple command extension
directory structures with a conventional format for testing.
"""
def __init__(self, name, root: pathlib.Path):
"""Create a command extension.
Args:
name (str): The name of the command extension... | Extension |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 54346,
"end": 55852
} | class ____(Request):
"""
get scalar metric data for task
:param task: task ID
:type task: str
:param metric: type of metric
:type metric: str
"""
_service = "events"
_action = "get_scalar_metric_data"
_version = "2.9"
_schema = {
"definitions": {},
"properti... | GetScalarMetricDataRequest |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_mac.py | {
"start": 1637,
"end": 3785
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid MAC addresses."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_mac": [
... | ExpectColumnValuesToBeValidMac |
python | tiangolo__fastapi | docs_src/path_operation_advanced_configuration/tutorial004.py | {
"start": 109,
"end": 717
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: Set[str] = set()
@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(item: Item):
"""
Create an item with all the information:
... | Item |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/black/cases/line_ranges_fmt_off_decorator.py | {
"start": 266,
"end": 496
} | class ____:
# fmt: off
@decorator ( )
# fmt: on
def method():
print ( "str" )
@decor(
a=1,
# fmt: off
b=(2, 3),
# fmt: on
)
def func():
pass
| MyClass |
python | jina-ai__jina | tests/integration/stateful/stateful_no_snapshot_exec/executor.py | {
"start": 198,
"end": 334
} | class ____(TextDoc):
id: str
tags: Dict[str, str] = {}
l: List[str] = []
random_num = random.randint(0, 50000)
| TextDocWithId |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 17144,
"end": 17856
} | class ____(TypedDict, total=False):
type: Required[Literal['model']]
cls: Required[type[Any]]
schema: Required[CoreSchema]
def model_ser_schema(cls: type[Any], schema: CoreSchema) -> ModelSerSchema:
"""
Returns a schema for serialization using a model.
Args:
cls: The expected class ty... | ModelSerSchema |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fetch_org_info_from_entity.py | {
"start": 320,
"end": 466
} | class ____(GQLResult):
organization: Optional[OrgInfoFragment]
user: Optional[FetchOrgInfoFromEntityEntityUser]
| FetchOrgInfoFromEntityEntity |
python | ray-project__ray | python/ray/serve/_private/request_router/common.py | {
"start": 1890,
"end": 3602
} | class ____:
def __init__(
self,
*,
staleness_timeout_s: float = RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S,
get_curr_time_s: Optional[Callable[[], float]] = None,
):
self._cache: Dict[ReplicaID, ReplicaQueueLengthCacheEntry] = {}
self._staleness_timeout_s = staleness_... | ReplicaQueueLengthCache |
python | getsentry__sentry | src/sentry/integrations/jira/models/create_issue_metadata.py | {
"start": 1279,
"end": 2663
} | class ____:
schema_type: str
"""
The Field type. Possible types include:
- string
- array (has a corresponding `items` field with its subtype)
- user
- issuetype
- issuelink
- project (and PROJECT)
- date
- team
- any
"""
custom: str | None = None
"""
The ... | JiraSchema |
python | huggingface__transformers | src/transformers/pipelines/token_classification.py | {
"start": 4778,
"end": 29932
} | class ____(ChunkPipeline):
"""
Named Entity Recognition pipeline using any `ModelForTokenClassification`. See the [named entity recognition
examples](../task_summary#named-entity-recognition) for more information.
Example:
```python
>>> from transformers import pipeline
>>> token_classifi... | TokenClassificationPipeline |
python | Textualize__textual | src/textual/widget.py | {
"start": 3458,
"end": 4795
} | class ____:
"""An *optional* awaitable returned by [mount][textual.widget.Widget.mount] and [mount_all][textual.widget.Widget.mount_all].
Example:
```python
await self.mount(Static("foo"))
```
"""
def __init__(self, parent: Widget, widgets: Sequence[Widget]) -> None:
se... | AwaitMount |
python | huggingface__transformers | tests/models/chinese_clip/test_modeling_chinese_clip.py | {
"start": 21251,
"end": 24196
} | class ____(unittest.TestCase):
@slow
def test_inference(self):
model_name = "OFA-Sys/chinese-clip-vit-base-patch16"
model = ChineseCLIPModel.from_pretrained(model_name).to(torch_device)
processor = ChineseCLIPProcessor.from_pretrained(model_name)
image = prepare_img()
in... | ChineseCLIPModelIntegrationTest |
python | Netflix__metaflow | test/core/tests/resume_foreach_split.py | {
"start": 67,
"end": 2300
} | class ____(MetaflowTest):
"""
Resuming from a foreach split should work.
Check that data changes in all downstream steps after resume.
"""
RESUME = True
PRIORITY = 3
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
... | ResumeForeachSplitTest |
python | Textualize__textual | docs/examples/guide/layout/grid_layout_auto.py | {
"start": 80,
"end": 534
} | class ____(App):
CSS_PATH = "grid_layout_auto.tcss"
def compose(self) -> ComposeResult:
yield Static("First column", classes="box")
yield Static("Two", classes="box")
yield Static("Three", classes="box")
yield Static("Four", classes="box")
yield Static("Five", classes="b... | GridLayoutExample |
python | Textualize__rich | rich/syntax.py | {
"start": 7871,
"end": 36261
} | class ____(JupyterMixin):
"""Construct a Syntax object to render syntax highlighted code.
Args:
code (str): Code to highlight.
lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)
theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/... | Syntax |
python | GoogleCloudPlatform__python-docs-samples | people-and-planet-ai/weather-forecasting/serving/weather-model/weather/model.py | {
"start": 1837,
"end": 4721
} | class ____(PreTrainedModel):
"""A custom Hugging Face model.
For more information:
https://huggingface.co/docs/transformers/main/en/custom_models#writing-a-custom-model
"""
config_class = WeatherConfig
def __init__(self, config: WeatherConfig) -> None:
super().__init__(config)
... | WeatherModel |
python | getsentry__sentry | src/sentry/audit_log/events.py | {
"start": 8276,
"end": 8577
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=38, name="PROJECT_DISABLE", api_name="project.disable")
def render(self, audit_log_entry: AuditLogEntry) -> str:
return render_project_action(audit_log_entry, "disable")
| ProjectDisableAuditLogEvent |
python | aimacode__aima-python | csp.py | {
"start": 20241,
"end": 23830
} | class ____:
"""A universal dict maps any key to the same value. We use it here
as the domains dict for CSPs in which all variables have the same domain.
>>> d = UniversalDict(42)
>>> d['life']
42
"""
def __init__(self, value): self.value = value
def __getitem__(self, key): return self.... | UniversalDict |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/mysql.py | {
"start": 658,
"end": 1450
} | class ____(DataSourceTestConfig):
@property
@override
def label(self) -> str:
return "mysql"
@property
@override
def pytest_mark(self) -> pytest.MarkDecorator:
return pytest.mark.mysql
@override
def create_batch_setup(
self,
request: pytest.FixtureReques... | MySQLDatasourceTestConfig |
python | python-jsonschema__jsonschema | jsonschema/tests/test_deprecations.py | {
"start": 292,
"end": 15754
} | class ____(TestCase):
def test_version(self):
"""
As of v4.0.0, __version__ is deprecated in favor of importlib.metadata.
"""
message = "Accessing jsonschema.__version__ is deprecated"
with self.assertWarnsRegex(DeprecationWarning, message) as w:
from jsonschema ... | TestDeprecations |
python | kubernetes-client__python | kubernetes/client/models/v1_expression_warning.py | {
"start": 383,
"end": 5228
} | 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... | V1ExpressionWarning |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/url_test/package.py | {
"start": 217,
"end": 392
} | class ____(Package):
"""Mock package that fetches from a URL."""
homepage = "http://www.url-fetch-example.com"
version("test", url="to-be-filled-in-by-test")
| UrlTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.