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 | getsentry__sentry | src/sentry/issues/status_change_message.py | {
"start": 216,
"end": 512
} | class ____(TypedDict):
fingerprint: Sequence[str]
project_id: int
new_status: int
new_substatus: int | None
id: str
detector_id: int | None
activity_data: dict[str, Any] | None
update_date: NotRequired[datetime | None]
@dataclass(frozen=True)
| StatusChangeMessageData |
python | ray-project__ray | python/ray/tune/tests/test_tune_restore_warm_start.py | {
"start": 5541,
"end": 6352
} | class ____(AbstractWarmStartTest, unittest.TestCase):
def set_basic_conf(self, analysis=None):
space = {"width": (0, 20), "height": (-100, 100)}
def cost(space):
tune.report(
dict(loss=(space["height"] - 14) ** 2 - abs(space["width"] - 3))
)
search_a... | BayesoptWarmStartTest |
python | redis__redis-py | tests/test_cluster.py | {
"start": 114100,
"end": 116541
} | class ____:
"""
Tests for the ClusterPubSub class
"""
def test_init_pubsub_with_host_and_port(self, r):
"""
Test creation of pubsub instance with passed host and port
"""
node = r.get_default_node()
p = r.pubsub(host=node.host, port=node.port)
assert p.ge... | TestClusterPubSubObject |
python | ray-project__ray | python/ray/dashboard/modules/job/common.py | {
"start": 22202,
"end": 22324
} | class ____:
# DEPRECATED: Use submission_id instead.
job_id: str
submission_id: str
@dataclass
| JobSubmitResponse |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 63838,
"end": 64333
} | class ____:
xlBetween = 1 # from enum XlFormatConditionOperator
xlEqual = 3 # from enum XlFormatConditionOperator
xlGreater = 5 # from enum XlFormatConditionOperator
xlGreaterEqual = 7 # from enum XlFormatConditionOperator
xlLess = 6 # from enum XlFormatConditionOperator
xlLessEqual = 8 # ... | FormatConditionOperator |
python | pytorch__pytorch | torch/ao/nn/intrinsic/modules/fused.py | {
"start": 4815,
"end": 5523
} | class ____(_FusedModule):
r"""This is a sequential container which calls the Conv 2d, Batch Norm 2d, and ReLU modules.
During quantization this will be replaced with the corresponding fused module."""
def __init__(self, conv, bn, relu):
assert (
type_before_parametrizations(conv) == Con... | ConvBnReLU2d |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_logging_sink.py | {
"start": 15107,
"end": 18415
} | class ____:
def test_template_fields(self):
operator = CloudLoggingListSinksOperator(
task_id=TASK_ID,
project_id=PROJECT_ID,
)
assert "project_id" in operator.template_fields
def test_missing_required_params(self):
with pytest.raises(AirflowException) as... | TestCloudLoggingListSinksOperator |
python | PrefectHQ__prefect | src/prefect/_versioning.py | {
"start": 465,
"end": 690
} | class ____(VersionInfo):
type: Literal["prefect:simple"] = "prefect:simple"
version: str = Field(default="")
branch: Optional[str] = Field(default=None)
url: Optional[str] = Field(default=None)
| SimpleVersionInfo |
python | PyCQA__pylint | tests/functional/r/regression/regression_property_no_member_870.py | {
"start": 123,
"end": 372
} | class ____:
def __init__(self, val=None):
self._val = val
@property
def val(self):
return self._val
@val.setter
def val(self, value):
self._val = value
if __name__ == '__main__':
print(X([]).val.append)
| X |
python | Textualize__textual | tests/css/test_nested_css.py | {
"start": 2008,
"end": 3198
} | class ____(App[None]):
CSS = """
Screen {
background: green;
Label {
background: red;
}
}
"""
def compose(self) -> ComposeResult:
yield Label("one")
async def test_rule_declaration_after_nested() -> None:
"""Regression test for https://githu... | DeclarationAfterNestedApp |
python | doocs__leetcode | solution/2200-2299/2263.Make Array Non-decreasing or Non-increasing/Solution.py | {
"start": 0,
"end": 486
} | class ____:
def convertArray(self, nums: List[int]) -> int:
def solve(nums):
n = len(nums)
f = [[0] * 1001 for _ in range(n + 1)]
for i, x in enumerate(nums, 1):
mi = inf
for j in range(1001):
if mi > f[i - 1][j]:
... | Solution |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 27599,
"end": 28195
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to create a block schema."""
fields: dict[str, Any] = Field(
default_factory=dict, description="The block schema's field schema"
)
block_type_id: UUID = Field(default=..., description="A block type ID")
capabilities: List[st... | BlockSchemaCreate |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/psycopg2.py | {
"start": 20951,
"end": 21041
} | class ____(_Psycopg2Range):
_psycopg2_range_cls = "DateTimeRange"
| _Psycopg2DateTimeRange |
python | wandb__wandb | wandb/vendor/pygments/styles/vim.py | {
"start": 407,
"end": 1976
} | class ____(Style):
"""
Styles somewhat like vim 7.0
"""
background_color = "#000000"
highlight_color = "#222222"
default_style = "#cccccc"
styles = {
Token: "#cccccc",
Whitespace: "",
Comment: "#000080",
C... | VimStyle |
python | astropy__astropy | astropy/cosmology/_src/tests/test_core.py | {
"start": 2370,
"end": 2993
} | class ____:
"""Tests for a :class:`astropy.utils.metadata.MetaData` on a Cosmology."""
def test_meta_on_class(self, cosmo_cls):
assert cosmo_cls.meta is None
def test_meta_on_instance(self, cosmo):
assert isinstance(cosmo.meta, dict) # test type
# value set at initialization
... | MetaTestMixin |
python | plotly__plotly.py | plotly/graph_objs/layout/newshape/legendgrouptitle/_font.py | {
"start": 235,
"end": 9970
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.newshape.legendgrouptitle"
_path_str = "layout.newshape.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant"... | Font |
python | euske__pdfminer | pdfminer/pdfinterp.py | {
"start": 2583,
"end": 3497
} | class ____:
def __init__(self):
self.linewidth = 0
self.linecap = None
self.linejoin = None
self.miterlimit = None
self.dash = None
self.intent = None
self.flatness = None
return
def copy(self):
obj = PDFGraphicState()
obj.linewid... | PDFGraphicState |
python | astropy__astropy | astropy/units/equivalencies.py | {
"start": 1210,
"end": 30761
} | class ____(list):
"""
A container for a units equivalency.
Attributes
----------
name: `str`
The name of the equivalency.
kwargs: `dict`
Any positional or keyword arguments used to make the equivalency.
"""
def __init__(self, equiv_list, name="", kwargs=None):
s... | Equivalency |
python | getsentry__sentry | src/sentry/db/models/manager/option.py | {
"start": 260,
"end": 925
} | class ____(BaseManager[M]):
@property
def _option_cache(self) -> dict[str, dict[str, Any]]:
if not hasattr(_local_cache, "option_cache"):
_local_cache.option_cache = {}
return _local_cache.option_cache
def clear_local_cache(self, **kwargs: Any) -> None:
self._option_cac... | OptionManager |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/losses_test.py | {
"start": 1532,
"end": 4832
} | class ____(test.TestCase):
def setUp(self):
super(AbsoluteDifferenceLossTest, self).setUp()
self._predictions = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
self._labels = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.... | AbsoluteDifferenceLossTest |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 87463,
"end": 87550
} | class ____(openblas_ilp64_lapack_info, openblas64__info):
pass
| openblas64__lapack_info |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/types.py | {
"start": 13515,
"end": 14029
} | class ____(AirbyteSource):
"""Base class used by the codegen Airbyte sources. This class is not intended to be used directly.
Converts all of its attributes into a source configuration dict which is passed down to the base
AirbyteSource class.
"""
def __init__(self, source_type: str, name: str):
... | GeneratedAirbyteSource |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/pretty.py | {
"start": 17234,
"end": 36436
} | class ____:
"""A line in repr output."""
parent: Optional["_Line"] = None
is_root: bool = False
node: Optional[Node] = None
text: str = ""
suffix: str = ""
whitespace: str = ""
expanded: bool = False
last: bool = False
@property
def expandable(self) -> bool:
"""Chec... | _Line |
python | gabrielfalcao__HTTPretty | tests/functional/base.py | {
"start": 2400,
"end": 3671
} | class ____(threading.Thread):
def __init__(self, lock, port, *args, **kw):
self.lock = lock
self.port = int(port)
self._stop = threading.Event()
super(JSONEchoServer, self).__init__(*args, **kw)
self.daemon = True
def stop(self):
self._stop.set()
def stopped... | JSONEchoServer |
python | astropy__astropy | astropy/time/formats.py | {
"start": 78945,
"end": 79580
} | class ____(TimeFormat):
"""Base class for time delta representations."""
_registry = TIME_DELTA_FORMATS
_default_precision = 3
# Somewhat arbitrary values that are effectively no limit for precision.
_min_precision = -99
_max_precision = 99
def _check_scale(self, scale):
"""
... | TimeDeltaFormat |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/operators/databricks_workflow.py | {
"start": 2468,
"end": 10285
} | class ____(BaseOperator):
"""
Creates a Databricks workflow from a DatabricksWorkflowTaskGroup specified in a DAG.
:param task_id: The task_id of the operator
:param databricks_conn_id: The connection ID to use when connecting to Databricks.
:param existing_clusters: A list of existing clusters to ... | _CreateDatabricksWorkflowOperator |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_snippets.py | {
"start": 17776,
"end": 18348
} | class ____(util.MdCase):
"""Test nested no bounds."""
extension = [
'pymdownx.snippets',
]
extension_configs = {
'pymdownx.snippets': {
'base_path': os.path.join(BASE, '_snippets', 'nested'),
'restrict_base_path': False
}
}
def test_restricted(s... | TestSnippetsNestedUnrestricted |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol40.py | {
"start": 480,
"end": 583
} | class ____(Protocol[T]):
def f0(self, right: Self, /) -> "P2Parent[T]":
return right
| P2Parent |
python | pdm-project__pdm | src/pdm/cli/utils.py | {
"start": 1186,
"end": 4655
} | class ____(argparse.RawDescriptionHelpFormatter):
def start_section(self, heading: str | None) -> None:
return super().start_section(termui.style(heading.title() if heading else "", style="warning"))
def _format_usage(
self,
usage: str | None,
actions: Iterable[Action],
... | PdmFormatter |
python | jazzband__django-pipeline | tests/tests/test_compiler.py | {
"start": 5516,
"end": 5997
} | class ____(TestCase):
def setUp(self):
default_collector.collect()
self.compiler = Compiler()
def test_compile(self):
paths = self.compiler.compile([_("pipeline/js/dummy.coffee")])
default_collector.collect()
self.assertEqual([_("pipeline/js/dummy.junk")], list(paths))
... | CompilerWithEmptyFirstArgTest |
python | scrapy__scrapy | scrapy/http/request/__init__.py | {
"start": 1045,
"end": 2259
} | class ____(TypedDict):
name: str | bytes
value: str | bytes | bool | float | int
domain: NotRequired[str | bytes]
path: NotRequired[str | bytes]
secure: NotRequired[bool]
CookiesT: TypeAlias = dict[str, str] | list[VerboseCookie]
RequestTypeVar = TypeVar("RequestTypeVar", bound="Request")
def ... | VerboseCookie |
python | numpy__numpy | numpy/lib/tests/test_io.py | {
"start": 49012,
"end": 103191
} | class ____(LoadTxtBase):
loadfunc = staticmethod(np.genfromtxt)
def test_record(self):
# Test w/ explicit dtype
data = TextIO('1 2\n3 4')
test = np.genfromtxt(data, dtype=[('x', np.int32), ('y', np.int32)])
control = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
... | TestFromTxt |
python | redis__redis-py | redis/commands/search/hybrid_query.py | {
"start": 11991,
"end": 12307
} | class ____(Filter):
def __init__(
self,
conditions: str,
) -> None:
"""
Create a new hybrid filter object.
Args:
conditions: Filter conditions.
"""
args = [conditions]
Filter.__init__(self, "FILTER", *args)
@experimental
| HybridFilter |
python | huggingface__transformers | src/transformers/models/dinat/modeling_dinat.py | {
"start": 12329,
"end": 12782
} | class ____(nn.Module):
def __init__(self, config, dim):
super().__init__()
self.dense = nn.Linear(dim, dim)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = ... | NeighborhoodAttentionOutput |
python | cython__cython | tests/run/test_grammar.py | {
"start": 4213,
"end": 10420
} | class ____(unittest.TestCase):
#from test.support import check_syntax_error
check_syntax_error = check_syntax_error
def test_backslash(self):
# Backslash means line continuation:
x = 1 \
+ 1
self.assertEqual(x, 2, 'backslash for line continuation')
# Backslash does... | TokenTests |
python | pytorch__pytorch | torch/distributions/utils.py | {
"start": 6116,
"end": 8027
} | class ____(lazy_property[T, R], property):
"""We want lazy properties to look like multiple things.
* property when Sphinx autodoc looks
* lazy_property when Distribution validate_args looks
"""
def __init__(self, wrapped: Callable[[T], R]) -> None:
property.__init__(self, wrapped)
def t... | _lazy_property_and_property |
python | viewflow__viewflow | viewflow/workflow/flow/views/list.py | {
"start": 350,
"end": 1490
} | class ____(
mixins.StoreRequestPathMixin,
mixins.ProcessViewTemplateNames,
ListModelView,
):
"""List of current user assigned tasks of a flow"""
flow_class = None
template_filename = "process_tasks_list.html"
title = _("Inbox")
columns = ("task_id", "task_title", "brief", "created")
... | FlowInboxListView |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py | {
"start": 801,
"end": 845
} | class ____(
object # )
,
):
...
| A |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_values_to_not_match_like_pattern.py | {
"start": 2071,
"end": 13578
} | class ____(ColumnMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectColumnValuesToNotMatchLikePattern is a \
Column Map Expectation.
Column Map Expectations are one of the most common types of Expectation.
They are evaluated for a single column and ask a yes/no question for every... | ExpectColumnValuesToNotMatchLikePattern |
python | doocs__leetcode | solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.py | {
"start": 0,
"end": 284
} | class ____:
def minimumRecolors(self, blocks: str, k: int) -> int:
ans = cnt = blocks[:k].count('W')
for i in range(k, len(blocks)):
cnt += blocks[i] == 'W'
cnt -= blocks[i - k] == 'W'
ans = min(ans, cnt)
return ans
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolModule2.py | {
"start": 1809,
"end": 1902
} | class ____(Protocol):
@property
def var_1(self) -> int: ...
v6: P6 = protocolModule1
| P6 |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 9847,
"end": 13497
} | class ____(OfflineTestCaseMixin, TestCase):
templates_dir = "basic"
expected_hash = "822ac7501287"
@patch.object(CompressCommand, "compress")
def test_handle_no_args(self, compress_mock):
compress_mock.return_value = {}, 1, []
CompressCommand().handle()
self.assertEqual(compress... | OfflineCompressBasicTestCase |
python | PyCQA__isort | isort/io.py | {
"start": 452,
"end": 2067
} | class ____:
stream: TextIO
path: Path
encoding: str
@staticmethod
def detect_encoding(filename: str | Path, readline: Callable[[], bytes]) -> str:
try:
return tokenize.detect_encoding(readline)[0]
except Exception:
raise UnsupportedEncoding(filename)
@st... | File |
python | doocs__leetcode | solution/1800-1899/1830.Minimum Number of Operations to Make String Sorted/Solution.py | {
"start": 151,
"end": 591
} | class ____:
def makeStringSorted(self, s: str) -> int:
cnt = Counter(s)
ans, n = 0, len(s)
for i, c in enumerate(s):
m = sum(v for a, v in cnt.items() if a < c)
t = f[n - i - 1] * m
for v in cnt.values():
t = t * g[v] % mod
ans ... | Solution |
python | huggingface__transformers | src/transformers/models/evolla/modular_evolla.py | {
"start": 5970,
"end": 6020
} | class ____(EsmEncoder):
pass
| EvollaSaProtEncoder |
python | django__django | tests/admin_scripts/tests.py | {
"start": 32344,
"end": 33657
} | class ____(AdminScriptTestCase):
"A series of tests for manage.py when there is no settings.py file."
def test_builtin_command(self):
"""
no settings: manage.py builtin commands fail with an error when no
settings provided.
"""
args = ["check", "admin_scripts"]
o... | ManageNoSettings |
python | kamyu104__LeetCode-Solutions | Python/maximize-consecutive-elements-in-an-array-after-modification.py | {
"start": 836,
"end": 1622
} | class ____(object):
def maxSelectedElements(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
dp = collections.defaultdict(int)
dp[nums[0]] = dp[nums[0]+1] = 1
for i in xrange(1, len(nums)):
if nums[i] == nums[i-1]:
... | Solution2 |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 894,
"end": 1111
} | class ____:
def func1():
pass
# comment
def func2():
pass
# This is a
# ... multi-line comment
def func3():
pass
# This is a
# ... multi-line comment
@decorator
| Class |
python | PyCQA__pylint | tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.py | {
"start": 8868,
"end": 11655
} | class ____:
def test_useless_docs_ignored_argument_names_sphinx( # [useless-type-doc, useless-param-doc]
self, arg, _, _ignored
):
"""Example of a method documenting the return type that an
implementation should return.
:param arg: An argument.
:type arg: int
:... | Foo |
python | huggingface__transformers | tests/utils/test_hf_argparser.py | {
"start": 2946,
"end": 3698
} | class ____:
foo: int
required_enum: "BasicEnum" = field()
opt: "bool | None" = None
baz: "str" = field(default="toto", metadata={"help": "help message"})
foo_str: "list[str]" = list_field(default=["Hallo", "Bonjour", "Hello"])
if is_python_no_less_than_3_10:
@dataclass
class WithDefaultBo... | StringLiteralAnnotationExample |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 6717,
"end": 6822
} | class ____(DocumentEvent):
''' Base class for connection status related events.
'''
| ConnectionEvent |
python | ansible__ansible | test/lib/ansible_test/_internal/config.py | {
"start": 809,
"end": 994
} | class ____:
"""Configuration for modules."""
python_requires: str
python_versions: tuple[str, ...]
controller_only: bool
@dataclasses.dataclass(frozen=True)
| ModulesConfig |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 97903,
"end": 101717
} | class ____:
@pytest.fixture
def _organization_update(self, pyramid_user):
self.user = UserFactory.create()
EmailFactory.create(user=self.user, verified=True)
self.organization_name = "example"
self.organization_display_name = "Example"
self.organization_link_url = "https:... | TestOrganizationUpdateEmails |
python | pytorch__pytorch | test/test_utils.py | {
"start": 20568,
"end": 22988
} | class ____(TestCase):
MAX_TIMEOUT_IN_SECOND = 300
def test_random_seed(self):
def run():
dataloader = torch.utils.data.DataLoader(
RandomDatasetMock(),
batch_size=2,
num_workers=4,
shuffle=True,
timeout=self.MAX... | TestDataLoaderUtils |
python | getsentry__sentry | src/sentry/monitors/serializers.py | {
"start": 1047,
"end": 1224
} | class ____(TypedDict):
userNotifiedTimestamp: datetime
environmentMutedTimestamp: datetime
@register(MonitorEnvBrokenDetection)
| MonitorEnvBrokenDetectionSerializerResponse |
python | django__django | tests/template_tests/test_logging.py | {
"start": 124,
"end": 2412
} | class ____(SimpleTestCase):
loglevel = logging.DEBUG
def test_log_on_variable_does_not_exist_silent(self):
class TestObject:
class SilentDoesNotExist(Exception):
silent_variable_failure = True
@property
def template_name(self):
return... | VariableResolveLoggingTests |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_test.py | {
"start": 9643,
"end": 12248
} | class ____(test_lib.TestCase):
def _l2Normalize(self, x, dim):
if isinstance(dim, list):
norm = np.linalg.norm(x, axis=tuple(dim))
for d in dim:
norm = np.expand_dims(norm, d)
return x / norm
else:
norm = np.apply_along_axis(np.linalg.norm, dim, x)
return x / np.expand_d... | L2NormalizeTest |
python | cherrypy__cherrypy | cherrypy/process/plugins.py | {
"start": 1200,
"end": 2191
} | class ____(object):
"""Plugin base class which auto-subscribes methods for known channels."""
bus = None
"""A :class:`Bus <cherrypy.process.wspbus.Bus>`, usually cherrypy.engine.
"""
def __init__(self, bus):
"""Initialize a simple plugin."""
self.bus = bus
def subscribe(self):... | SimplePlugin |
python | simplejson__simplejson | simplejson/tests/test_for_json.py | {
"start": 216,
"end": 293
} | class ____(object):
def for_json(self):
return ['list']
| ForJsonList |
python | scikit-image__scikit-image | src/skimage/measure/fit.py | {
"start": 915,
"end": 1192
} | class ____:
def __init_subclass__(self):
warn(
f'`BaseModel` deprecated since version {_PARAMS_DEP_START} and '
f'will be removed in version {_PARAMS_DEP_STOP}',
category=FutureWarning,
stacklevel=2,
)
| BaseModel |
python | MongoEngine__mongoengine | tests/fixtures.py | {
"start": 194,
"end": 425
} | class ____(Document):
number = IntField()
string = StringField(choices=(("One", "1"), ("Two", "2")))
embedded = EmbeddedDocumentField(PickleEmbedded)
lists = ListField(StringField())
photo = FileField()
| PickleTest |
python | ethereum__web3.py | web3/types.py | {
"start": 14750,
"end": 15129
} | class ____(TypedDict, total=False):
after: int
count: int
fromAddress: Sequence[Address | ChecksumAddress | ENS]
fromBlock: BlockIdentifier
toAddress: Sequence[Address | ChecksumAddress | ENS]
toBlock: BlockIdentifier
# Subscriptions
SubscriptionType = Literal[
"newHeads",
"logs",
... | TraceFilterParams |
python | huggingface__transformers | src/transformers/models/sam_hq/modular_sam_hq.py | {
"start": 7316,
"end": 8190
} | class ____(ModelOutput):
r"""
masks (`torch.FloatTensor` of shape `(batch_size, num_prompts, num_masks, height, width)`):
The predicted masks for the input image. The masks are of shape `(batch_size, num_prompts, num_masks, height, width)`.
iou_scores (`torch.FloatTensor` of shape `(batch_size, num_... | SamHQMMaskDecoderOutputs |
python | huggingface__transformers | src/transformers/models/conditional_detr/modeling_conditional_detr.py | {
"start": 43745,
"end": 44619
} | class ____(nn.Module):
"""
Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
height and width of a bounding box w.r.t. an image.
Copied from https://github.com/facebookresearch/detr/blob/master/models/detr.py
"""
def __init__(self, i... | MLP |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/events.py | {
"start": 24272,
"end": 26075
} | class ____(
NamedTuple(
"_TypeCheck",
[
("success", PublicAttr[bool]),
("description", PublicAttr[Optional[str]]),
("metadata", PublicAttr[Mapping[str, MetadataValue]]),
],
)
):
"""Event corresponding to a successful typecheck.
Events of this ... | TypeCheck |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/streaming/_types.py | {
"start": 1461,
"end": 1564
} | class ____(RawMessageStopEvent):
type: Literal["message_stop"]
message: Message
| MessageStopEvent |
python | huggingface__transformers | tests/test_video_processing_common.py | {
"start": 2979,
"end": 23868
} | class ____:
test_cast_dtype = None
fast_video_processing_class = None
video_processor_list = None
input_name = "pixel_values_videos"
def setUp(self):
video_processor_list = []
if self.fast_video_processing_class:
video_processor_list.append(self.fast_video_processing_cl... | VideoProcessingTestMixin |
python | pennersr__django-allauth | allauth/headless/mfa/inputs.py | {
"start": 1292,
"end": 1714
} | class ____(inputs.Input):
authenticators = inputs.ModelMultipleChoiceField(
queryset=Authenticator.objects.none()
)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop("user")
super().__init__(*args, **kwargs)
self.fields["authenticators"].queryset = Authenticator.ob... | DeleteWebAuthnInput |
python | getsentry__sentry | src/sentry/core/endpoints/organization_member_index.py | {
"start": 7373,
"end": 19986
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
rate_limits = RateLimitConfig(
limit_overrides={
"GET": {
RateLimitCategory.IP: RateLimit(limit=40, window=1),
RateLimi... | OrganizationMemberIndexEndpoint |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/cloud_memorystore.py | {
"start": 1877,
"end": 2096
} | class ____(BaseGoogleLink):
"""Helper class for constructing Memorystore Redis Instance Link."""
name = "Memorystore Redis Instance"
key = "redis_instance"
format_str = REDIS_LINK
| RedisInstanceDetailsLink |
python | Farama-Foundation__Gymnasium | gymnasium/envs/box2d/car_racing.py | {
"start": 3091,
"end": 29599
} | class ____(gym.Env, EzPickle):
"""
## Description
The easiest control task to learn from pixels - a top-down
racing environment. The generated track is random every episode.
Some indicators are shown at the bottom of the window along with the
state RGB buffer. From left to right: true speed, fo... | CarRacing |
python | vyperlang__vyper | vyper/venom/passes/dead_store_elimination.py | {
"start": 573,
"end": 5974
} | class ____(IRPass):
"""
This pass eliminates dead stores using Memory SSA analysis.
"""
def run_pass(self, /, addr_space: AddrSpace):
mem_ssa_type = mem_ssa_type_factory(addr_space)
if addr_space == MEMORY:
self.NON_RELATED_EFFECTS = NON_MEMORY_EFFECTS
elif addr_spac... | DeadStoreElimination |
python | sqlalchemy__sqlalchemy | test/sql/test_case_statement.py | {
"start": 598,
"end": 10900
} | class ____(fixtures.TablesTest, AssertsCompiledSQL):
__dialect__ = "default"
run_inserts = "once"
run_deletes = "never"
@classmethod
def define_tables(cls, metadata):
Table(
"info_table",
metadata,
Column("pk", Integer, primary_key=True),
Col... | CaseTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/batchtospace_op_test.py | {
"start": 4520,
"end": 4650
} | class ____(BatchToSpaceErrorHandlingTest,
CppOpImpl):
pass
| BatchToSpaceErrorHandlingCppTest |
python | great-expectations__great_expectations | docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py | {
"start": 1460,
"end": 3596
} | class ____(ColumnAggregateMetricProvider):
# </snippet>
"""MetricProvider Class for Custom Aggregate Max MetricProvider"""
# <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py metric_name">
metric_name = "column.custom_max"
# </snippet>
# <snippet name="docs... | ColumnCustomMax |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/cascade_delete_relationships/tutorial004_py310.py | {
"start": 329,
"end": 3455
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
team_id: int | None = Field(
default=None, foreign_key="team.id", ondelete="RESTRICT"
)
team: Tea... | Hero |
python | astropy__astropy | astropy/modeling/fitting.py | {
"start": 59920,
"end": 63976
} | class ____(_NonLinearLSQFitter):
"""
Wrapper class for `scipy.optimize.least_squares` method, which provides:
- Trust Region Reflective
- dogbox
- Levenberg-Marquardt
algorithms using the least squares statistic.
Parameters
----------
method : str
‘trf’ : Trust ... | _NLLSQFitter |
python | doocs__leetcode | solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution.py | {
"start": 0,
"end": 609
} | class ____:
def findNumberOfLIS(self, nums: List[int]) -> int:
n = len(nums)
f = [1] * n
cnt = [1] * n
mx = 0
for i in range(n):
for j in range(i):
if nums[j] < nums[i]:
if f[i] < f[j] + 1:
f[i] = f[j] + ... | Solution |
python | doocs__leetcode | solution/1000-1099/1047.Remove All Adjacent Duplicates In String/Solution.py | {
"start": 0,
"end": 239
} | class ____:
def removeDuplicates(self, s: str) -> str:
stk = []
for c in s:
if stk and stk[-1] == c:
stk.pop()
else:
stk.append(c)
return ''.join(stk)
| Solution |
python | getsentry__sentry | src/sentry/api/serializers/models/release.py | {
"start": 7849,
"end": 14404
} | class ____(TypedDict):
name: str | None
email: str
Author = Union[UserSerializerResponse, NonMappableUser]
def get_author_users_by_external_actors(
authors: list[CommitAuthor], organization_id: int
) -> tuple[dict[CommitAuthor, str], list[CommitAuthor]]:
found: dict[CommitAuthor, str] = {}
user... | NonMappableUser |
python | numba__numba | numba/core/errors.py | {
"start": 13976,
"end": 16144
} | class ____(object):
"""
An object "fixing" warnings of a given category caught during
certain phases. The warnings can have their filename and lineno fixed,
and they are deduplicated as well.
When used as a context manager, any warnings caught by `.catch_warnings()`
will be flushed at the exit... | WarningsFixer |
python | ansible__ansible | lib/ansible/parsing/vault/__init__.py | {
"start": 2766,
"end": 2829
} | class ____(AnsibleVaultError):
pass
| AnsibleVaultPasswordError |
python | google__jax | jax/_src/core.py | {
"start": 18308,
"end": 18566
} | class ____(Var):
def __init__(self, aval: AbstractValue):
super().__init__(aval)
def __repr__(self): return '_'
def pretty_print(self, context: JaxprPpContext, *, print_dtype: bool = True):
del context, print_dtype # unused
return '_'
| DropVar |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/common.py | {
"start": 2455,
"end": 2712
} | class ____(CatalogModel):
amount: Decimal
current_billing_cycle: Optional[Decimal]
description: str
id: str
kind: str
name: str
never_expires: bool
number_of_billing_cycles: Optional[Decimal]
quantity: Optional[Decimal]
| AddOn |
python | scrapy__scrapy | tests/test_settings/__init__.py | {
"start": 529,
"end": 777
} | class ____:
def test_get_settings_priority(self):
for prio_str, prio_num in SETTINGS_PRIORITIES.items():
assert get_settings_priority(prio_str) == prio_num
assert get_settings_priority(99) == 99
| TestSettingsGlobalFuncs |
python | pytorch__pytorch | test/distributed/test_c10d_nccl.py | {
"start": 179594,
"end": 181734
} | class ____(
test_c10d_common.ProcessGroupWithDispatchedCollectivesTests
):
@requires_nccl()
@skip_if_lt_x_gpu(1)
def test_collectives(self):
self._test_collectives(backend="nccl")
@requires_nccl()
@skip_if_lt_x_gpu(1)
def test_allreduce_coalesced(self):
self._test_allreduce_... | NcclProcessGroupWithDispatchedCollectivesTests |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_ec2.py | {
"start": 5505,
"end": 7048
} | class ____(BaseEc2TestClass):
def test_init(self):
ec2_operator = EC2StartInstanceOperator(
task_id="task_test",
instance_id="i-123abc",
aws_conn_id="aws_conn_test",
region_name="region-test",
check_interval=3,
)
assert ec2_operator... | TestEC2StartInstanceOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed3.py | {
"start": 1172,
"end": 1268
} | class ____(ParentClosed3):
b: NotRequired[int]
# This should generate an error.
| ChildClosed3_3 |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 9901,
"end": 10993
} | class ____(Widget):
"""A representation of ``st.button`` and ``st.form_submit_button``."""
_value: bool
proto: ButtonProto = field(repr=False)
label: str
help: str
form_id: str
def __init__(self, proto: ButtonProto, root: ElementTree) -> None:
super().__init__(proto, root)
... | Button |
python | ray-project__ray | rllib/examples/envs/classes/mock_env.py | {
"start": 4447,
"end": 7675
} | class ____(VectorEnv):
"""A custom vector env that uses a single(!) CartPole sub-env.
However, this env pretends to be a vectorized one to illustrate how one
could create custom VectorEnvs w/o the need for actual vectorizations of
sub-envs under the hood.
"""
def __init__(self, episode_length,... | MockVectorEnv |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_changed_validator.py | {
"start": 8390,
"end": 9868
} | class ____:
def test_validation_with_errors(self):
symbol_info = SymbolInfo(symbol_path="test.func", file_path=Path("/test.py"))
# Mock the validation function to return errors and warnings
mock_result = ValidatorResult.create("test.func")
mock_result = mock_result.with_error("Test ... | TestValidateSymbols |
python | numpy__numpy | numpy/f2py/symbolic.py | {
"start": 44820,
"end": 53310
} | class ____:
def __init__(self, language=Language.C):
self.original = None
self.quotes_map = None
self.language = language
def finalize_string(self, s):
return insert_quotes(s, self.quotes_map)
def parse(self, inp):
self.original = inp
unquoted, self.quotes_... | _FromStringWorker |
python | sqlalchemy__sqlalchemy | examples/versioned_history/test_versioning.py | {
"start": 29673,
"end": 29825
} | class ____(TestVersioning):
def make_base(self):
class Base(DeclarativeBase):
pass
self.Base = Base
| TestVersioningNewBase |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-isaacus/llama_index/embeddings/isaacus/base.py | {
"start": 569,
"end": 10178
} | class ____(BaseEmbedding):
"""
Isaacus Embeddings Integration.
This class provides an interface to Isaacus' embedding API, featuring the
Kanon 2 Embedder - the world's most accurate legal embedding model on the
Massive Legal Embedding Benchmark (MLEB).
Args:
model (str, optional): The ... | IsaacusEmbedding |
python | getsentry__sentry | src/sentry/uptime/migrations/0046_delete_project_uptime_subscription_table.py | {
"start": 239,
"end": 1510
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | sympy__sympy | sympy/tensor/tensor.py | {
"start": 55655,
"end": 58073
} | class ____(Basic):
"""
Class of tensor types. Deprecated, use tensor_heads() instead.
Parameters
==========
index_types : list of ``TensorIndexType`` of the tensor indices
symmetry : ``TensorSymmetry`` of the tensor
Attributes
==========
``index_types``
``symmetry``
``typ... | TensorType |
python | tornadoweb__tornado | tornado/test/websocket_test.py | {
"start": 21356,
"end": 21951
} | class ____(WebSocketBaseTestCase):
def get_app(self):
return Application([("/native", NativeCoroutineOnMessageHandler)])
@gen_test
def test_native_coroutine(self):
ws = yield self.ws_connect("/native")
# Send both messages immediately, coroutine must process one at a time.
y... | WebSocketNativeCoroutineTest |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 45463,
"end": 116701
} | class ____(BooleanFunction):
"""
True if only one or no argument is true.
``Exclusive(A, B, C)`` is equivalent to ``~(A & B) & ~(A & C) & ~(B & C)``.
For two arguments, this is equivalent to :py:class:`~.Xor`.
Examples
========
>>> from sympy.logic.boolalg import Exclusive
>>> Exclus... | Exclusive |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 52373,
"end": 52779
} | class ____(DelegatingLexer):
"""
Coldfusion markup/script components
.. versionadded:: 2.0
"""
name = 'Coldfusion CFC'
aliases = ['cfc']
filenames = ['*.cfc']
mimetypes = []
def __init__(self, **options):
super(ColdfusionCFCLexer, self).__init__(ColdfusionHtmlLexer, Coldfus... | ColdfusionCFCLexer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_types.py | {
"start": 4032,
"end": 6480
} | class ____(_LiteralRoundTripFixture, fixtures.TestBase):
__requires__ = ("unicode_data",)
data = (
"Alors vous imaginez ma 🐍 surprise, au lever du jour, "
"quand une drôle de petite 🐍 voix m’a réveillé. Elle "
"disait: « S’il vous plaît… dessine-moi 🐍 un mouton! »"
)
@proper... | _UnicodeFixture |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.