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 | tornadoweb__tornado | tornado/httputil.py | {
"start": 4941,
"end": 13859
} | class ____(StrMutableMapping):
"""A dictionary that maintains ``Http-Header-Case`` for all keys.
Supports multiple values per key via a pair of new methods,
`add()` and `get_list()`. The regular dictionary interface
returns a single value per key, with multiple values joined by a
comma.
>>> h... | HTTPHeaders |
python | kamyu104__LeetCode-Solutions | Python/third-maximum-number.py | {
"start": 29,
"end": 669
} | class ____(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
top = [float("-inf")] * 3
for num in nums:
if num > top[0]:
top[0], top[1], top[2] = num, top[0], top[1]
count += 1
... | Solution |
python | python-rapidjson__python-rapidjson | tests/test_dict_subclass.py | {
"start": 590,
"end": 884
} | class ____(Decoder):
def start_object(self):
return []
def test_objects_as_key_value_pairs():
kvp = ObjectsAsKeyValuePairsDecoder()
result = kvp('{"a": 1, "b": {"b1": 1, "b2": 2}}')
assert result == [('a', 1), ('b', [('b1', 1), ('b2', 2)])]
| ObjectsAsKeyValuePairsDecoder |
python | spack__spack | lib/spack/spack/bootstrap/_common.py | {
"start": 668,
"end": 9037
} | class ____(TypedDict, total=False):
spec: spack.spec.Spec
command: spack.util.executable.Executable
def _python_import(module: str) -> bool:
try:
importlib.import_module(module)
except ImportError:
return False
return True
def _try_import_from_store(
module: str, query_spec: ... | QueryInfo |
python | pydata__xarray | xarray/tests/test_datatree.py | {
"start": 86416,
"end": 88081
} | class ____:
def test_close(self, tree_and_closers):
tree, closers = tree_and_closers
assert not any(closer.closed for closer in closers.values())
tree.close()
assert all(closer.closed for closer in closers.values())
tree.close() # should not error
def test_context_manag... | TestClose |
python | getsentry__sentry | src/sentry/utils/sdk_crashes/sdk_crash_detection_config.py | {
"start": 543,
"end": 1062
} | class ____:
"""Pattern for matching function and module to ignore SDK crashes.
Use "*" as a wildcard to match any value.
Examples:
- FunctionAndModulePattern("specific.module", "invoke") - matches only "invoke" in "specific.module"
- FunctionAndModulePattern("*", "invoke") - matches "invoke" in any... | FunctionAndModulePattern |
python | astropy__astropy | astropy/utils/masked/tests/test_function_helpers.py | {
"start": 49292,
"end": 49915
} | class ____(MaskedArraySetup):
def test_meshgrid(self):
a = np.arange(1.0, 4.0)
mask_a = np.array([True, False, False])
ma = Masked(a, mask=mask_a)
b = np.array([2.5, 10.0, 3.0, 4.0])
mask_b = np.array([False, True, False, True])
mb = Masked(b, mask=mask_b)
oa,... | TestMeshGrid |
python | walkccc__LeetCode | solutions/3373. Maximize the Number of Target Nodes After Connecting Trees II/3373.py | {
"start": 0,
"end": 1291
} | class ____:
def maxTargetNodes(
self,
edges1: list[list[int]],
edges2: list[list[int]]
) -> list[int]:
n = len(edges1) + 1
m = len(edges2) + 1
graph1 = self._buildGraph(edges1)
graph2 = self._buildGraph(edges2)
parity1 = [False] * n
parity2 = [False] * m # placeholder (par... | Solution |
python | paramiko__paramiko | paramiko/client.py | {
"start": 33926,
"end": 34337
} | class ____(MissingHostKeyPolicy):
"""
Policy for logging a Python-style warning for an unknown host key, but
accepting it. This is used by `.SSHClient`.
"""
def missing_host_key(self, client, hostname, key):
warnings.warn(
"Unknown {} host key for {}: {}".format(
... | WarningPolicy |
python | pypa__hatch | tests/project/test_config.py | {
"start": 3990,
"end": 5002
} | class ____:
def test_not_table(self, isolation):
with pytest.raises(TypeError, match="Field `tool.hatch.env.collectors` must be a table"):
_ = ProjectConfig(isolation, {"env": {"collectors": 9000}}).env_collectors
def test_collector_not_table(self, isolation):
with pytest.raises(Typ... | TestEnvCollectors |
python | ray-project__ray | python/ray/dag/compiled_dag_node.py | {
"start": 29767,
"end": 143800
} | class ____:
"""Experimental class for accelerated execution.
This class should not be called directly. Instead, create
a ray.dag and call experimental_compile().
See REP https://github.com/ray-project/enhancements/pull/48 for more
information.
"""
@ray.remote(num_cpus=0)
class DAGDriv... | CompiledDAG |
python | coleifer__peewee | tests/models.py | {
"start": 158278,
"end": 158405
} | class ____(TestModel):
seq_id = IntegerField(sequence='seq_id_sequence')
key = TextField()
@requires_pglike
| SequenceModel |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/inputs.py | {
"start": 1381,
"end": 1557
} | class ____:
"""Serializable payload of information for the result of processing a step input."""
input_name: str
type_check_data: TypeCheckData
@record
| StepInputData |
python | jazzband__django-pipeline | pipeline/templatetags/pipeline.py | {
"start": 4362,
"end": 5677
} | class ____(PipelineMixin, template.Node):
def __init__(self, name):
self.name = name
def render(self, context):
super().render(context)
package_name = template.Variable(self.name).resolve(context)
try:
package = self.package_for(package_name, "css")
except P... | StylesheetNode |
python | pypa__warehouse | tests/unit/manage/views/test_organizations.py | {
"start": 124682,
"end": 143862
} | class ____:
def test_manage_organization_publishing_get(self, db_request):
"""Test GET request returns all forms and pending publishers"""
organization = OrganizationFactory.create()
user = UserFactory.create()
db_request.POST = MultiDict()
db_request.user = user
db_r... | TestManageOrganizationPublishingViews |
python | kamyu104__LeetCode-Solutions | Python/find-longest-self-contained-substring.py | {
"start": 1141,
"end": 2164
} | class ____(object):
def maxSubstringLength(self, s):
"""
:type s: str
:rtype: int
"""
def check(left, right):
for x in idxs:
if not x:
continue
l = bisect.bisect_left(x, left)
r = bisect.bisect_ri... | Solution2 |
python | langchain-ai__langchain | libs/core/langchain_core/callbacks/base.py | {
"start": 5443,
"end": 6472
} | class ____:
"""Mixin for tool callbacks."""
def on_tool_end(
self,
output: Any,
*,
run_id: UUID,
parent_run_id: UUID | None = None,
**kwargs: Any,
) -> Any:
"""Run when the tool ends running.
Args:
output: The output of the tool.
... | ToolManagerMixin |
python | jazzband__django-polymorphic | example/orders/admin.py | {
"start": 464,
"end": 822
} | class ____(StackedPolymorphicInline):
"""
An inline for a polymorphic model.
The actual form appearance of each row is determined by
the child inline that corresponds with the actual model type.
"""
model = Payment
child_inlines = (CreditCardPaymentInline, BankPaymentInline, SepaPaymentInli... | PaymentInline |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 7447,
"end": 8538
} | class ____(XYGlyph, LineGlyph, FillGlyph, HatchGlyph):
''' Render annuli.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
__example__ = "examples/reference/models/Annulus.py"
_args = ('x', 'y'... | Annulus |
python | pandas-dev__pandas | pandas/tests/arrays/integer/test_comparison.py | {
"start": 151,
"end": 1212
} | class ____(NumericOps, ComparisonOps):
@pytest.mark.parametrize("other", [True, False, pd.NA, -1, 0, 1])
def test_scalar(self, other, comparison_op, dtype):
ComparisonOps.test_scalar(self, other, comparison_op, dtype)
def test_compare_to_int(self, dtype, comparison_op):
# GH 28930
o... | TestComparisonOps |
python | apache__airflow | providers/standard/tests/unit/standard/decorators/test_branch_python.py | {
"start": 1221,
"end": 3546
} | class ____:
# when run in "Parallel" test run environment, sometimes this test runs for a long time
# because creating virtualenv and starting new Python interpreter creates a lot of IO/contention
# possibilities. So we are increasing the timeout for this test to 3x of the default timeout
@pytest.mark.e... | TestBranchPythonDecoratedOperator |
python | wandb__wandb | wandb/_pydantic/pagination.py | {
"start": 559,
"end": 616
} | class ____(GQLResult, Generic[NodeT]):
node: NodeT
| Edge |
python | langchain-ai__langchain | libs/core/tests/unit_tests/tracers/test_async_base_tracer.py | {
"start": 582,
"end": 21915
} | class ____(AsyncBaseTracer):
"""Fake tracer to test async based tracers."""
def __init__(self) -> None:
"""Initialize the tracer."""
super().__init__()
self.runs: list[Run] = []
async def _persist_run(self, run: Run) -> None:
self.runs.append(run)
def _compare_run_with_er... | FakeAsyncTracer |
python | pytorch__pytorch | torch/distributions/multivariate_normal.py | {
"start": 3469,
"end": 11256
} | class ____(Distribution):
r"""
Creates a multivariate normal (also called Gaussian) distribution
parameterized by a mean vector and a covariance matrix.
The multivariate normal distribution can be parameterized either
in terms of a positive definite covariance matrix :math:`\mathbf{\Sigma}`
or ... | MultivariateNormal |
python | ray-project__ray | python/ray/train/v2/_internal/state/schema.py | {
"start": 285,
"end": 1236
} | class ____(str, Enum):
"""Enumeration of the possible statuses for a Train run."""
# ====== Active States ======
# The Train run is currently in the process of initializing.
INITIALIZING = "INITIALIZING"
# The Train run is waiting to be scheduled.
SCHEDULING = "SCHEDULING"
# The Train run i... | RunStatus |
python | pappasam__jedi-language-server | tests/lsp_test_client/session.py | {
"start": 621,
"end": 13099
} | class ____(MethodDispatcher):
"""Send and Receive messages over LSP as a test LS Client."""
def __init__(self, cwd=None):
self.cwd = cwd if cwd else os.getcwd()
self._thread_pool = ThreadPoolExecutor()
self._sub = None
self._writer = None
self._reader = None
self... | LspSession |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/utils/eks_test_constants.py | {
"start": 7433,
"end": 7809
} | class ____:
"""The names of methods, used when a test is expected to throw an exception."""
CREATE_CLUSTER: str = "CreateCluster"
CREATE_NODEGROUP: str = "CreateNodegroup"
DELETE_CLUSTER: str = "DeleteCluster"
DELETE_NODEGROUP: str = "DeleteNodegroup"
DESCRIBE_CLUSTER: str = "DescribeCluster"
... | MethodNames |
python | coleifer__peewee | tests/base_models.py | {
"start": 795,
"end": 911
} | class ____(TestModel):
email = CharField()
user = ForeignKeyField(User, backref='accounts', null=True)
| Account |
python | ray-project__ray | python/ray/experimental/channel/common.py | {
"start": 21147,
"end": 22468
} | class ____(WriterInterface):
def start(self):
for channel in self._output_channels:
channel.ensure_registered_as_writer()
def write(self, val: Any, timeout: Optional[float] = None) -> None:
# If it is an exception, there's only 1 return value.
# We have to send the same data... | SynchronousWriter |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 68302,
"end": 69055
} | class ____(FieldValues):
"""
Valid and invalid values for a `Choice` field that uses a grouped list for the
choices, rather than a list of pairs of (`value`, `description`).
"""
valid_inputs = {
'poor': 'poor',
'medium': 'medium',
'good': 'good',
}
invalid_inputs = {
... | TestChoiceFieldWithGroupedChoices |
python | facebook__pyre-check | client/tests/backend_arguments_test.py | {
"start": 701,
"end": 28285
} | class ____(testslide.TestCase):
def test_create_remote_logging(self) -> None:
self.assertIsNone(
RemoteLogging.create(),
)
self.assertIsNone(
RemoteLogging.create(identifier="foo"),
)
self.assertEqual(
RemoteLogging.create(logger="logger"),... | ArgumentsTest |
python | getsentry__sentry | src/sentry/grouping/api.py | {
"start": 5088,
"end": 5330
} | class ____(ProjectGroupingConfigLoader):
"""Secondary config to find old groups after config change"""
option_name = "sentry:secondary_grouping_config"
cache_prefix = "secondary-grouping-enhancements:"
| SecondaryGroupingConfigLoader |
python | sqlalchemy__sqlalchemy | examples/dogpile_caching/model.py | {
"start": 2132,
"end": 3034
} | class ____(Base):
__tablename__ = "person"
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
addresses = relationship(Address, collection_class=set)
def __init__(self, name, *addresses):
self.name = name
self.addresses = set(addresses)
def __str... | Person |
python | keras-team__keras | keras/src/legacy/preprocessing/image.py | {
"start": 15036,
"end": 18813
} | class ____(BatchFromFilesMixin, Iterator):
"""Iterator capable of reading images from a directory on disk.
DEPRECATED.
"""
allowed_class_modes = {"categorical", "binary", "sparse", "input", None}
def __init__(
self,
directory,
image_data_generator,
target_size=(256... | DirectoryIterator |
python | PyCQA__pylint | tests/functional/ext/docparams/return/missing_return_doc_Numpy.py | {
"start": 2766,
"end": 3229
} | class ____:
"""test_useless_docs_ignored_argument_names_numpy
Example of a method documenting the return type that an
implementation should return.
"""
def foo(self, arg, _, _ignored): # [useless-type-doc, useless-param-doc]
"""docstring ...
Parameters
----------
a... | Foo |
python | doocs__leetcode | solution/1600-1699/1696.Jump Game VI/Solution.py | {
"start": 0,
"end": 370
} | class ____:
def maxResult(self, nums: List[int], k: int) -> int:
n = len(nums)
f = [0] * n
q = deque([0])
for i in range(n):
if i - q[0] > k:
q.popleft()
f[i] = nums[i] + f[q[0]]
while q and f[q[-1]] <= f[i]:
q.pop()... | Solution |
python | fastai__fastai | fastai/callback/tracker.py | {
"start": 503,
"end": 836
} | class ____(Callback):
"A `Callback` that terminates training if loss is NaN."
order=-9
def after_batch(self):
"Test if `last_loss` is NaN and interrupts training."
if torch.isinf(self.loss) or torch.isnan(self.loss): raise CancelFitException
# %% ../../nbs/17_callback.tracker.ipynb 10
| TerminateOnNaNCallback |
python | django-extensions__django-extensions | django_extensions/db/models.py | {
"start": 789,
"end": 1129
} | class ____(models.Model):
"""
TitleDescriptionModel
An abstract base class model that provides title and description fields.
"""
title = models.CharField(_("title"), max_length=255)
description = models.TextField(_("description"), blank=True, null=True)
class Meta:
abstract = True... | TitleDescriptionModel |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/strategies.py | {
"start": 377,
"end": 439
} | class ____:
MockConnection = MockConnection
| MockEngineStrategy |
python | walkccc__LeetCode | solutions/2374. Node With Highest Edge Score/2374.py | {
"start": 0,
"end": 192
} | class ____:
def edgeScore(self, edges: list[int]) -> int:
scores = [0] * len(edges)
for i, edge in enumerate(edges):
scores[edge] += i
return scores.index(max(scores))
| Solution |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 33007,
"end": 34479
} | class ____(TypedDict, total=False):
type: Required[Literal['bytes']]
max_length: int
min_length: int
strict: bool
ref: str
metadata: dict[str, Any]
serialization: SerSchema
def bytes_schema(
*,
max_length: int | None = None,
min_length: int | None = None,
strict: bool | Non... | BytesSchema |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_hexadecimal.py | {
"start": 121,
"end": 4063
} | class ____(RegexBasedColumnMapExpectation):
"""Expect column values to be valid hexadecimals."""
regex_camel_name = "HexadecimalNumber"
regex = r"^[0-9a-fA-F]+$"
semantic_type_name_plural = "hexadecimals"
map_metric = RegexBasedColumnMapExpectation.register_metric(
regex_camel_name=regex_c... | ExpectColumnValuesToBeHexadecimal |
python | zarr-developers__zarr-python | tests/test_codecs/test_codecs.py | {
"start": 1112,
"end": 11483
} | class ____:
array: AnyAsyncArray
selection: BasicSelection
async def get(self) -> NDArrayLikeOrScalar:
return await self.array.getitem(self.selection)
async def set(self, value: np.ndarray[Any, Any]) -> None:
return await self.array.setitem(self.selection, value)
def order_from_dim(o... | _AsyncArraySelectionProxy |
python | pytorch__pytorch | torch/fx/passes/splitter_base.py | {
"start": 13893,
"end": 14034
} | class ____:
is_acc: bool
nodes: NodeList
device_ordinal: Optional[int] = None
@compatibility(is_backward_compatible=False)
| Subgraph |
python | streamlit__streamlit | lib/tests/streamlit/data_mocks/snowpandas_mocks.py | {
"start": 731,
"end": 1715
} | class ____:
"""This is dummy DataFrame class, which imitates
snowflake.snowpark.modin.pandas.dataframe.DataFrame class for testing purposes.
We use this to make sure that our code does a special handling
if it detects a Snowpark Pandas Dataframe.
This allows testing of the functionality without hav... | DataFrame |
python | pytorch__pytorch | torch/testing/_internal/common_jit.py | {
"start": 5767,
"end": 15860
} | class ____(TestCase):
def createFunctionFromGraph(self, trace):
graph = trace if isinstance(trace, torch._C.Graph) else trace.graph()
return torch._C._create_function_from_graph("forward", graph)
def assertExportImport(self, trace, inputs):
m = self.createFunctionFromGraph(trace)
... | JitCommonTestCase |
python | huggingface__transformers | src/transformers/models/beit/modeling_beit.py | {
"start": 33611,
"end": 37707
} | class ____(BeitPreTrainedModel):
def __init__(self, config: BeitConfig) -> None:
super().__init__(config)
self.num_labels = config.num_labels
self.beit = BeitModel(config, add_pooling_layer=False)
# Classifier head
self.layernorm = nn.LayerNorm(config.hidden_size, eps=confi... | BeitForMaskedImageModeling |
python | google__pytype | pytype/tools/analyze_project/parse_args_test.py | {
"start": 297,
"end": 712
} | class ____(unittest.TestCase):
"""Test parse_args.convert_string."""
def test_int(self):
self.assertEqual(parse_args.convert_string('3'), 3)
def test_bool(self):
self.assertIs(parse_args.convert_string('True'), True)
self.assertIs(parse_args.convert_string('False'), False)
def test_whitespace(sel... | TestConvertString |
python | walkccc__LeetCode | solutions/95. Unique Binary Search Trees II/95.py | {
"start": 0,
"end": 500
} | class ____:
def generateTrees(self, n: int) -> list[TreeNode]:
if n == 0:
return []
def generateTrees(mn: int, mx: int) -> list[int | None]:
if mn > mx:
return [None]
ans = []
for i in range(mn, mx + 1):
for left in generateTrees(mn, i - 1):
for right in ge... | Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_20/workers.py | {
"start": 58089,
"end": 59551
} | class ____(Request):
"""
Returns worker statistics metric keys grouped by categories.
:param worker_ids: List of worker ids to collect metrics for. If not provided
or empty then all the company workers metrics are analyzed.
:type worker_ids: Sequence[str]
"""
_service = "workers"
_... | GetMetricKeysRequest |
python | gevent__gevent | src/greentest/3.9/test_socket.py | {
"start": 207994,
"end": 208785
} | class ____(SocketUDPLITETest):
def testUDPLITETimeout(self):
def raise_timeout(*args, **kwargs):
self.serv.settimeout(1.0)
self.serv.recv(1024)
self.assertRaises(socket.timeout, raise_timeout,
"Error generating a timeout exception (UDPLITE)")
... | UDPLITETimeoutTest |
python | getsentry__sentry | src/sentry/core/endpoints/scim/teams.py | {
"start": 3050,
"end": 4585
} | class ____(serializers.Serializer):
# we don't actually use "schemas" for anything atm but its part of the spec
schemas = serializers.ListField(child=serializers.CharField(), required=True)
Operations = serializers.ListField(
child=SCIMTeamPatchOperationSerializer(),
required=True,
s... | SCIMTeamPatchRequestSerializer |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_reflection.py | {
"start": 18054,
"end": 19674
} | class ____(fixtures.TestBase):
__only_on__ = "oracle"
__sparse_driver_backend__ = True
def setup_test(self):
with testing.db.begin() as conn:
conn.exec_driver_sql("create table my_table (id integer)")
conn.exec_driver_sql(
"create global temporary table my_te... | SystemTableTablenamesTest |
python | huggingface__transformers | src/transformers/models/layoutlmv3/modeling_layoutlmv3.py | {
"start": 23429,
"end": 35958
} | class ____(LayoutLMv3PreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
if config.text_embed:
self.embeddings = LayoutLMv3TextEmbeddings(config)
if config.visual_embed:
# use the default pre-training parameters for fi... | LayoutLMv3Model |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 78494,
"end": 79370
} | class ____(Request):
"""
:param project: Project id
:type project: str
"""
_service = "projects"
_action = "get_by_id"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {"project": {"description": "Project id", "type": "string"}},
"required": ["proje... | GetByIdRequest |
python | encode__django-rest-framework | tests/test_utils.py | {
"start": 898,
"end": 993
} | class ____(APIView):
def get_view_name(self):
return "Foo"
| CustomNameResourceInstance |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/connectors/asyncio.py | {
"start": 12565,
"end": 14151
} | class ____:
"""Mixin for a AsyncAdapt_dbapi_connection to add terminate support."""
__slots__ = ()
def terminate(self) -> None:
if in_greenlet():
# in a greenlet; this is the connection was invalidated case.
try:
# try to gracefully close; see #10717
... | AsyncAdapt_terminate |
python | mlflow__mlflow | mlflow/server/graphql/autogenerated_graphql_schema.py | {
"start": 319,
"end": 521
} | class ____(graphene.Enum):
DEPLOYMENT_JOB_CONNECTION_STATE_UNSPECIFIED = 1
NOT_SET_UP = 2
CONNECTED = 3
NOT_FOUND = 4
REQUIRED_PARAMETERS_CHANGED = 5
| MlflowDeploymentJobConnectionState |
python | kamyu104__LeetCode-Solutions | Python/minimum-score-after-removals-on-a-tree.py | {
"start": 48,
"end": 1883
} | class ____(object):
def minimumScore(self, nums, edges):
"""
:type nums: List[int]
:type edges: List[List[int]]
:rtype: int
"""
def is_ancestor(a, b):
return left[a] <= left[b] and right[b] <= right[a]
def iter_dfs():
cnt = 0
... | Solution |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_pickle.py | {
"start": 66,
"end": 302
} | class ____:
def test_pickle_after_set_freq(self):
tdi = timedelta_range("1 day", periods=4, freq="s")
tdi = tdi._with_freq(None)
res = tm.round_trip_pickle(tdi)
tm.assert_index_equal(res, tdi)
| TestPickle |
python | getsentry__sentry | src/sentry/notifications/platform/types.py | {
"start": 2423,
"end": 2788
} | class ____:
"""
A rendered action for an integration.
"""
label: str
"""
The text content of the action (usually appears as a button).
This string should not contain any formatting, and will be displayed as is.
"""
link: str
"""
The underlying link of the action.
"""
@... | NotificationRenderedAction |
python | pytorch__pytorch | test/torch_np/test_ndarray_methods.py | {
"start": 4444,
"end": 6205
} | class ____(TestCase):
def test_nonzero_trivial(self):
assert_equal(np.nonzero(np.array([])), ([],))
assert_equal(np.array([]).nonzero(), ([],))
assert_equal(np.nonzero(np.array([0])), ([],))
assert_equal(np.array([0]).nonzero(), ([],))
assert_equal(np.nonzero(np.array([1]))... | TestNonzero |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_search_views.py | {
"start": 17833,
"end": 23749
} | class ____(APITestCase):
def create_base_data_with_page_filters(self) -> None:
self.team_1 = self.create_team(organization=self.organization, slug="team-1")
self.team_2 = self.create_team(organization=self.organization, slug="team-2")
# User 1 is on team 1 only
user_1 = self.user
... | OrganizationGroupSearchViewsGetPageFiltersTest |
python | django__django | django/template/response.py | {
"start": 143,
"end": 5098
} | class ____(HttpResponse):
rendering_attrs = ["template_name", "context_data", "_post_render_callbacks"]
def __init__(
self,
template,
context=None,
content_type=None,
status=None,
charset=None,
using=None,
headers=None,
):
# It would s... | SimpleTemplateResponse |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 29981,
"end": 32310
} | class ____(Widget, Generic[T]):
"""A representation of ``st.selectbox``."""
_value: T | None | InitialValue
proto: SelectboxProto = field(repr=False)
label: str
options: list[str]
help: str
form_id: str
def __init__(self, proto: SelectboxProto, root: ElementTree) -> None:
supe... | Selectbox |
python | wandb__wandb | wandb/vendor/pygments/lexers/business.py | {
"start": 11958,
"end": 22098
} | class ____(RegexLexer):
"""
Lexer for ABAP, SAP's integrated language.
.. versionadded:: 1.1
"""
name = 'ABAP'
aliases = ['abap']
filenames = ['*.abap', '*.ABAP']
mimetypes = ['text/x-abap']
flags = re.IGNORECASE | re.MULTILINE
tokens = {
'common': [
(r'\s+... | ABAPLexer |
python | numba__numba | numba/core/dispatcher.py | {
"start": 38726,
"end": 41539
} | class ____(serialize.ReduceMixin, _MemoMixin, _DispatcherBase):
"""
Implementation of the hidden dispatcher objects used for lifted code
(a lifted loop is really compiled as a separate function).
"""
_fold_args = False
can_cache = False
def __init__(self, func_ir, typingctx, targetctx, flag... | LiftedCode |
python | ipython__ipython | IPython/core/interactiveshell.py | {
"start": 159736,
"end": 159889
} | class ____(metaclass=abc.ABCMeta):
"""An abstract base class for InteractiveShell."""
InteractiveShellABC.register(InteractiveShell)
| InteractiveShellABC |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 123463,
"end": 124317
} | class ____(BaseModel):
shard_id: int = Field(..., description="")
to_shard_id: Optional[int] = Field(
default=None,
description="Target shard ID if different than source shard ID Used exclusively with `ReshardStreamRecords` transfer method.",
)
from_: int = Field(..., description="Sourc... | ShardTransferInfo |
python | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 56696,
"end": 58186
} | class ____(PreTrainedModel):
config: ClapConfig
base_model_prefix = "clap"
input_modalities = ("audio", "text")
supports_gradient_checkpointing = False
@torch.no_grad()
def _init_weights(self, module: nn.Module):
"""Initialize the weights"""
factor = self.config.initializer_fact... | ClapPreTrainedModel |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_marker.py | {
"start": 1377,
"end": 11488
} | class ____(markers.MarkerStyle):
"""
A MarkerStyle where the snap threshold is force-disabled.
This is used to compare to polygon/star/asterisk markers which do not have
any snap threshold set.
"""
def _recache(self):
super()._recache()
self._snap_threshold = None
@check_figur... | UnsnappedMarkerStyle |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Data.py | {
"start": 5361,
"end": 5724
} | class ____(QtWidgets.QTextEdit):
def __init__(self, on_update):
super().__init__()
self.on_update = on_update
self.lastText = None
def focusOutEvent(self, ev):
text = self.toPlainText()
if text != self.lastText:
self.lastText = text
self.on_update... | TextEdit |
python | sympy__sympy | sympy/physics/mechanics/actuator.py | {
"start": 22231,
"end": 33203
} | class ____(ActuatorBase):
"""Torque-producing actuator.
Explanation
===========
A ``TorqueActuator`` is an actuator that produces a pair of equal and
opposite torques on a pair of bodies.
Examples
========
To construct a torque actuator, an expression (or symbol) must be supplied
... | TorqueActuator |
python | viewflow__viewflow | tests/json/test_json__basics.py | {
"start": 3234,
"end": 3341
} | class ____(forms.ModelForm):
class Meta:
model = VIPClient
exclude = ["data"]
| VIPClientForm |
python | getsentry__sentry | src/sentry/issue_detection/detectors/consecutive_db_detector.py | {
"start": 1290,
"end": 11094
} | class ____(PerformanceDetector):
"""
Let X and Y be the consecutive db span count threshold and the span duration threshold respectively,
each defined in the threshold settings.
The detector first looks for X number of consecutive db query spans,
Once these set of spans are found, the detector will... | ConsecutiveDBSpanDetector |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_object_position01.py | {
"start": 315,
"end": 875
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("object_position01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook =... | TestCompareXLSXFiles |
python | RaRe-Technologies__gensim | gensim/test/test_glove2word2vec.py | {
"start": 428,
"end": 1604
} | class ____(unittest.TestCase):
def setUp(self):
self.datapath = datapath('test_glove.txt')
self.output_file = get_tmpfile('glove2word2vec.test')
def test_conversion(self):
check_output(args=[
sys.executable, '-m', 'gensim.scripts.glove2word2vec',
'--input', self.... | TestGlove2Word2Vec |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 240099,
"end": 251106
} | class ____:
def test_invalid_init(self):
with pytest.raises(TypeError):
x509.Admission(
42, # type:ignore[arg-type]
None,
[],
)
with pytest.raises(TypeError):
x509.Admission(
None,
42... | TestAdmission |
python | sqlalchemy__sqlalchemy | test/dialect/mysql/test_compiler.py | {
"start": 27992,
"end": 47046
} | class ____(fixtures.TestBase, AssertsCompiledSQL, CacheKeyFixture):
"""Tests MySQL-dialect specific compilation."""
__dialect__ = mysql.dialect()
def test_precolumns(self):
dialect = self.__dialect__
def gen(distinct=None, prefixes=None):
stmt = select(column("q"))
... | SQLTest |
python | simplejson__simplejson | simplejson/tests/test_namedtuple.py | {
"start": 997,
"end": 1041
} | class ____(object):
_asdict = None
| DeadDuck |
python | davidhalter__jedi | test/completion/pep0484_typing.py | {
"start": 3861,
"end": 4822
} | class ____(typing.Dict[str, int]):
def setdud(self):
pass
def testdict(x: TestDict):
#? ["setdud", "setdefault"]
x.setd
for key in x.keys():
#? str()
key
for value in x.values():
#? int()
value
x = TestDict()
#? ["setdud", "setdefault"]
x.setd
for key in x.k... | TestDict |
python | huggingface__transformers | src/transformers/models/bridgetower/modeling_bridgetower.py | {
"start": 19271,
"end": 22512
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a mu... | BridgeTowerSelfAttention |
python | Lightning-AI__lightning | tests/tests_fabric/utilities/test_device_dtype_mixin.py | {
"start": 432,
"end": 4017
} | class ____(_DeviceDtypeModuleMixin):
def __init__(self) -> None:
super().__init__()
self.module = SubModule()
@pytest.mark.parametrize(
("dst_device_str", "dst_type"),
[
("cpu", torch.half),
("cpu", torch.float),
("cpu", torch.double),
pytest.param("cuda:0",... | TopModule |
python | getsentry__sentry | tests/sentry/sentry_apps/api/endpoints/test_sentry_apps.py | {
"start": 19321,
"end": 34909
} | class ____(SentryAppsTest):
method = "post"
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
def assert_sentry_app_status_code(self, sentry_app: SentryApp, status_code: int) -> None:
token = ApiToken.objects.create(
application=sentry_app.application,
... | PostSentryAppsTest |
python | scipy__scipy | scipy/sparse/linalg/_dsolve/linsolve.py | {
"start": 782,
"end": 31179
} | class ____(UserWarning):
"""Warning for exactly singular matrices."""
pass
def use_solver(**kwargs):
"""
Select default sparse direct solver to be used.
Parameters
----------
useUmfpack : bool, optional
Use UMFPACK [1]_, [2]_, [3]_, [4]_. over SuperLU. Has effect only
if `... | MatrixRankWarning |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_changed_validator.py | {
"start": 3256,
"end": 3381
} | class ____:
"""Test class docstring."""
pass
def test_function():
"""Test function docstring."""
pass
| TestClass |
python | python-visualization__folium | folium/plugins/timestamped_wmstilelayer.py | {
"start": 207,
"end": 4810
} | class ____(JSCSSMixin, MacroElement):
"""
Creates a TimestampedWmsTileLayer that takes a WmsTileLayer and adds time
control with the Leaflet.TimeDimension plugin.
Parameters
----------
data: WmsTileLayer.
The WmsTileLayer that you want to add time support to.
Must be created li... | TimestampedWmsTileLayers |
python | pytorch__pytorch | test/onnx/test_symbolic_helper.py | {
"start": 254,
"end": 2323
} | class ____(common_utils.TestCase):
def setUp(self):
super().setUp()
self._initial_training_mode = GLOBALS.training_mode
def tearDown(self):
GLOBALS.training_mode = self._initial_training_mode
@common_utils.parametrize(
"op_train_mode,export_mode",
[
comm... | TestHelperFunctions |
python | huggingface__transformers | tests/utils/test_core_model_loading.py | {
"start": 7494,
"end": 21071
} | class ____(unittest.TestCase):
def test_moe_and_qkv_conversion(self):
model = DummyRoot()
model.config = PretrainedConfig()
raw_tensors = {
"model.layers.0.experts.0.w1.weight": torch.tensor([[0.0, 1.0], [2.0, 3.0]]),
"model.layers.0.experts.1.w1.weight": torch.tenso... | TestConvertAndLoadStateDict |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/quantization/tensorflow/python/representative_dataset_test.py | {
"start": 10214,
"end": 11860
} | class ____(test.TestCase):
"""Test cases for TfRecordRepresentativeDatasetLoader."""
def test_tf_record_saver_with_generator_dataset(self):
tf_record_path = self.create_tempfile().full_path
path_map = {'serving_default': tf_record_path}
num_samples = 2
def data_gen():
for _ in range(num_samp... | TfRecordRepresentativeDatasetTest |
python | mlflow__mlflow | mlflow/store/artifact/http_artifact_repo.py | {
"start": 1113,
"end": 9088
} | class ____(ArtifactRepository, MultipartUploadMixin):
"""Stores artifacts in a remote artifact storage using HTTP requests"""
@property
def _host_creds(self):
return get_default_host_creds(self.artifact_uri)
def log_artifact(self, local_file, artifact_path=None):
verify_artifact_path(a... | HttpArtifactRepository |
python | tensorflow__tensorflow | tensorflow/python/data/ops/from_tensors_op.py | {
"start": 1017,
"end": 1721
} | class ____(dataset_ops.DatasetSource):
"""A `Dataset` with a single element."""
def __init__(self, element, name=None):
"""See `tf.data.Dataset.from_tensors` for details."""
element = structure.normalize_element(element)
self._structure = structure.type_spec_from_value(element)
self._tensors = stru... | _TensorDataset |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 6062,
"end": 6105
} | class ____(Foo, RootModel[int]):
pass
| Bar |
python | apache__airflow | providers/common/sql/tests/unit/common/sql/operators/test_sql.py | {
"start": 4592,
"end": 8811
} | class ____:
def setup_method(self):
self.task_id = "test_task"
self.conn_id = "sql_default"
self._operator = SQLExecuteQueryOperator(task_id=self.task_id, conn_id=self.conn_id, sql="sql")
def _construct_operator(self, sql, **kwargs):
dag = DAG("test_dag", schedule=None, start_da... | TestSQLExecuteQueryOperator |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/models/resource_details.py | {
"start": 2064,
"end": 2366
} | class ____(Enum):
"""Enum of specific views the user tries to access."""
CLUSTER_ACTIVITY = "CLUSTER_ACTIVITY"
DOCS = "DOCS"
IMPORT_ERRORS = "IMPORT_ERRORS"
JOBS = "JOBS"
PLUGINS = "PLUGINS"
PROVIDERS = "PROVIDERS"
TRIGGERS = "TRIGGERS"
WEBSITE = "WEBSITE"
| AccessView |
python | google__pytype | pytype/inspect/graph.py | {
"start": 281,
"end": 2805
} | class ____:
"""Networkx graph builder."""
def __init__(self, program, ignored, only_cfg=False):
self.graph = nx.MultiDiGraph()
self._add_cfg(program, ignored)
if not only_cfg:
self._add_variables(program, ignored)
def add_node(self, obj, **kwargs):
self.graph.add_node(obj_key(obj), **kwarg... | TypeGraph |
python | mlflow__mlflow | mlflow/tracing/otel/translation/traceloop.py | {
"start": 281,
"end": 3512
} | class ____(OtelSchemaTranslator):
"""
Translator for Traceloop/OpenLLMetry semantic conventions.
Only defines the attribute keys and mappings. All translation logic
is inherited from the base class.
"""
# Traceloop span kind attribute key
# Reference: https://github.com/traceloop/openllmet... | TraceloopTranslator |
python | openai__gym | gym/vector/async_vector_env.py | {
"start": 828,
"end": 27608
} | class ____(VectorEnv):
"""Vectorized environment that runs multiple environments in parallel.
It uses ``multiprocessing`` processes, and pipes for communication.
Example::
>>> import gym
>>> env = gym.vector.AsyncVectorEnv([
... lambda: gym.make("Pendulum-v0", g=9.81),
... | AsyncVectorEnv |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 95780,
"end": 97445
} | class ____(TestCase):
databases = {"default", "other"}
def setUp(self):
self.user = get_user_model().objects.create(
username="username", email="username@test.com", password="top_secret"
)
def test_history_user_with_fk_in_different_db_raises_value_error(self):
instance ... | MultiDBExplicitHistoryUserIDTest |
python | scipy__scipy | scipy/stats/tests/test_mstats_basic.py | {
"start": 26116,
"end": 33292
} | class ____:
# Comparison numbers are found using R v.1.5.1
# note that length(testcase) = 4
# testmathworks comes from documentation for the
# Statistics Toolbox for Matlab and can be found at both
# https://www.mathworks.com/help/stats/kurtosis.html
# https://www.mathworks.com/help/stats/skewne... | TestMoments |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.