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 | pytorch__pytorch | test/quantization/fx/test_numeric_suite_fx.py | {
"start": 84002,
"end": 109615
} | class ____(FXNumericSuiteQuantizationTestCase):
"""
Tests the "n shadows" workflow.
"""
def _test_impl(self, m, example_input, qconfig_mappings):
backend_config = get_native_backend_config()
# test that input is valid
_ = m(*example_input)
msp = prepare_n_shadows_model... | TestFXNumericSuiteNShadows |
python | django__django | tests/migrations/test_migrations/0002_second.py | {
"start": 43,
"end": 663
} | class ____(migrations.Migration):
dependencies = [
("migrations", "0001_initial"),
]
operations = [
migrations.DeleteModel("Tribble"),
migrations.RemoveField("Author", "silly_field"),
migrations.AddField("Author", "rating", models.IntegerField(default=0)),
migrations... | Migration |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_lib.py | {
"start": 32506,
"end": 35084
} | class ____(object):
"""A class wrapping information needed by an input function.
This is a context class that is passed to the user's input function and
contains information about the compute replicas and input pipelines. The
number of compute replicas (in sync training) helps compute the local batch
size fr... | InputContext |
python | openai__openai-python | src/openai/resources/files.py | {
"start": 27879,
"end": 28759
} | class ____:
def __init__(self, files: AsyncFiles) -> None:
self._files = files
self.create = _legacy_response.async_to_raw_response_wrapper(
files.create,
)
self.retrieve = _legacy_response.async_to_raw_response_wrapper(
files.retrieve,
)
self... | AsyncFilesWithRawResponse |
python | spack__spack | var/spack/test_repos/spack_repo/builder_test/packages/builder_and_mixins/package.py | {
"start": 601,
"end": 814
} | class ____(metaclass=spack.phase_callbacks.PhaseCallbacksMeta):
@run_before("install")
def before_install(self):
pass
@run_after("install")
def after_install(self):
pass
| BuilderMixin |
python | bokeh__bokeh | src/bokeh/util/compiler.py | {
"start": 5815,
"end": 18931
} | class ____:
''' Represent a custom (user-defined) Bokeh model.
'''
def __init__(self, cls: type[HasProps]) -> None:
self.cls = cls
@property
def name(self) -> str:
return self.cls.__name__
@property
def full_name(self) -> str:
name = self.cls.__module__ + "." + sel... | CustomModel |
python | pytoolz__toolz | toolz/tests/test_dicttoolz.py | {
"start": 439,
"end": 6046
} | class ____:
"""Test typical usage: dict inputs, no factory keyword.
Class attributes:
D: callable that inputs a dict and creates or returns a MutableMapping
kw: kwargs dict to specify "factory" keyword (if applicable)
"""
D = dict
kw = {}
def test_merge(self):
D, kw = s... | TestDict |
python | doocs__leetcode | solution/0300-0399/0310.Minimum Height Trees/Solution.py | {
"start": 0,
"end": 705
} | class ____:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1:
return [0]
g = [[] for _ in range(n)]
degree = [0] * n
for a, b in edges:
g[a].append(b)
g[b].append(a)
degree[a] += 1
degree[... | Solution |
python | falconry__falcon | examples/recipes/pretty_json_main.py | {
"start": 29,
"end": 847
} | class ____(falcon.media.BaseHandler):
MAX_INDENT_LEVEL = 8
def deserialize(self, stream, content_type, content_length):
data = stream.read()
return json.loads(data.decode())
def serialize(self, media, content_type):
_, params = falcon.parse_header(content_type)
indent = par... | CustomJSONHandler |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/cut_mix.py | {
"start": 273,
"end": 7877
} | class ____(BaseImagePreprocessingLayer):
"""CutMix data augmentation technique.
CutMix is a data augmentation method where patches are cut and pasted
between two images in the dataset, while the labels are also mixed
proportionally to the area of the patches.
**Note:** This layer is safe to use in... | CutMix |
python | facebook__pyre-check | client/commands/infer.py | {
"start": 6080,
"end": 7240
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
qualifier: str
global_annotations: List[RawGlobalAnnotation] = dataclasses.field(
metadata=dataclasses_json.config(field_name="globals"), default_factory=list
)
attribute_annotations: List[RawAttributeAnnotation] = dataclasses.field(
m... | RawInferOutputForPath |
python | Pylons__pyramid | tests/test_scripting.py | {
"start": 1459,
"end": 6705
} | class ____(unittest.TestCase):
def _callFUT(self, request=None, registry=None):
from pyramid.scripting import prepare
return prepare(request, registry)
def _makeRegistry(self, L=None):
if L is None:
L = [None, DummyFactory]
return DummyRegistry(L)
def setUp(sel... | Test_prepare |
python | kamyu104__LeetCode-Solutions | Python/print-zero-even-odd.py | {
"start": 48,
"end": 1359
} | class ____(object):
def __init__(self, n):
self.__n = n
self.__curr = 0
self.__cv = threading.Condition()
# printNumber(x) outputs "x", where x is an integer.
def zero(self, printNumber):
"""
:type printNumber: method
:rtype: void
"""
for... | ZeroEvenOdd |
python | keras-team__keras | keras/src/backend/common/masking_test.py | {
"start": 208,
"end": 1311
} | class ____(testing.TestCase):
def test_mask_on_eager_tensor(self):
x = ops.zeros((2, 3))
self.assertIsNone(get_keras_mask(x))
set_keras_mask(x, None)
self.assertIsNone(get_keras_mask(x))
mask = ops.ones((2, 3))
set_keras_mask(x, mask)
self.assertIs(get_keras... | MaskingTest |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/constructors.py | {
"start": 3390,
"end": 3805
} | class ____(ConstructorTitoModelQuery):
def __init__(self, a, b):
super().__init__(a, b)
def test_constructor_with_tito_model_query():
_test_sink(DerivedConstructorTitoModelQuery("", "").a) # No issue.
_test_sink(DerivedConstructorTitoModelQuery(_test_source(), "").a) # Issue.
_test_sink(Deri... | DerivedConstructorTitoModelQuery |
python | PrefectHQ__prefect | src/prefect/server/utilities/messaging/__init__.py | {
"start": 3071,
"end": 3230
} | class ____(Exception):
"""
Exception to raise to stop a consumer.
"""
def __init__(self, ack: bool = False):
self.ack = ack
| StopConsumer |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 394025,
"end": 395873
} | class ____(Response):
"""
Response of tasks.stop endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "tasks"
_action = "stop"
_version = "2.20"
_schema = {
"de... | StopResponse |
python | weaviate__weaviate-python-client | weaviate/aliases/executor.py | {
"start": 321,
"end": 5498
} | class ____(Generic[ConnectionType]):
def __init__(self, connection: Connection):
self._connection = connection
def list_all(
self, *, collection: Optional[str] = None
) -> executor.Result[Dict[str, AliasReturn]]:
"""Get the alias for a given alias name."""
self._connection._... | _AliasExecutor |
python | sympy__sympy | sympy/polys/fields.py | {
"start": 10866,
"end": 22375
} | class ____(DomainElement, DefaultPrinting, CantSympify, Generic[Er]):
"""Element of multivariate distributed rational function field. """
def __init__(self,
field: FracField[Er],
numer: PolyElement[Er],
denom: PolyElement[Er] | None = None) -> None:
if... | FracElement |
python | pytorch__pytorch | torch/testing/_internal/opinfo/core.py | {
"start": 114296,
"end": 116811
} | class ____(OpInfo):
"""Early version of a specialized OpInfo for Shape manipulating operations like tile and roll"""
def __init__(
self,
name, # the string name of the function
*,
ref, # a reference function
dtypes=floating_types(),
dtypesIfCUDA=None,
d... | ShapeFuncInfo |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_1.py | {
"start": 360,
"end": 636
} | class ____[_T, _U: str, _V: (int, float), *_W, **_X]:
@staticmethod
def transform(t: _T, u: _U, v: _V) -> tuple[*_W] | Callable[_X, _T] | None:
return None
# this should not be fixed because the new name is a keyword, but we still
# offer a diagnostic
| Everything |
python | Pylons__pyramid | tests/test_exceptions.py | {
"start": 485,
"end": 827
} | class ____(unittest.TestCase):
def test_response_equivalence(self):
from pyramid.exceptions import BadCSRFOrigin
from pyramid.httpexceptions import HTTPBadRequest
self.assertTrue(isinstance(BadCSRFOrigin(), HTTPBadRequest))
self.assertEqual(BadCSRFOrigin().status, HTTPBadRequest().s... | TestBadCSRFOrigin |
python | pytorch__pytorch | test/test_overrides.py | {
"start": 7358,
"end": 8061
} | class ____(torch.Tensor):
pass
@implements_sub(torch.mean)
def sub_mean(mat):
return 0
@implements_sub(torch.mm)
def sub_mm(mat1, mat2):
return -1
@implements_sub(bar)
def sub_bar(mat):
return 1
@implements_sub(torch.div)
def sub_div(input, other, out=None):
return NotImplemented
# The dispatch... | SubTensor3 |
python | plotly__plotly.py | plotly/graph_objs/volume/_lightposition.py | {
"start": 233,
"end": 3489
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume"
_path_str = "volume.lightposition"
_valid_props = {"x", "y", "z"}
@property
def x(self):
"""
Numeric vector, representing the X coordinate for each vertex.
The 'x' property is a number and may be specified as:... | Lightposition |
python | pytorch__pytorch | torch/distributed/fsdp/fully_sharded_data_parallel.py | {
"start": 2999,
"end": 101286
} | class ____(nn.Module, _FSDPState):
"""A wrapper for sharding module parameters across data parallel workers.
This is inspired by `Xu et al. <https://arxiv.org/abs/2004.13336>`_ as
well as the ZeRO Stage 3 from `DeepSpeed <https://www.deepspeed.ai/>`_.
FullyShardedDataParallel is commonly shortened to F... | FullyShardedDataParallel |
python | PrefectHQ__prefect | tests/server/orchestration/test_core_policy.py | {
"start": 113770,
"end": 115631
} | class ____:
@pytest.mark.parametrize(
"proposed_state_type",
sorted(
list(set(ALL_ORCHESTRATION_STATES) - {states.StateType.CANCELLED, None})
),
)
async def test_rejects_cancelling_to_anything_but_cancelled(
self,
session,
initialize_orchestration,... | TestHandleCancellingStateTransitions |
python | run-llama__llama_index | llama-index-integrations/program/llama-index-program-evaporate/llama_index/program/evaporate/base.py | {
"start": 4127,
"end": 6210
} | class ____(BaseEvaporateProgram[DataFrameRowsOnly]):
"""
Evaporate DF program.
Given a set of fields, extracts a dataframe from a set of nodes.
Each node corresponds to a row in the dataframe - each value in the row
corresponds to a field value.
"""
def fit(
self,
nodes: L... | DFEvaporateProgram |
python | viewflow__viewflow | viewflow/urls/model.py | {
"start": 3304,
"end": 3577
} | class ____(metaclass=ViewsetMeta):
list_bulk_actions = DEFAULT
def get_list_bulk_actions(self, request, *actions):
if self.list_bulk_actions is not DEFAULT:
actions = (*self.list_bulk_actions, *actions)
return actions
| ListBulkActionsMixin |
python | google__jax | tests/pallas/tpu_pallas_test.py | {
"start": 109463,
"end": 109557
} | class ____(PallasCallTPUBooleanTest):
INTERPRET: bool = True
| PallasCallTPUBooleanInterpretTest |
python | pypa__pip | src/pip/_vendor/pygments/filters/__init__.py | {
"start": 1804,
"end": 2862
} | class ____(Filter):
"""Highlight special code tags in comments and docstrings.
Options accepted:
`codetags` : list of strings
A list of strings that are flagged as code tags. The default is to
highlight ``XXX``, ``TODO``, ``FIXME``, ``BUG`` and ``NOTE``.
.. versionchanged:: 2.13
... | CodeTagFilter |
python | google__pytype | pytype/block_environment.py | {
"start": 247,
"end": 1822
} | class ____:
"""A store of local variables per blockgraph node."""
def __init__(self):
self.block_locals: BlockLocals = {}
# Blocks whose outgoing edges cannot be traversed. This can happen if, for
# example, a block unconditionally raises an exception.
self._dead_ends: set[blocks.Block] = set()
... | Environment |
python | google__jax | tests/pallas/mosaic_gpu_test.py | {
"start": 113797,
"end": 113915
} | class ____(
PallasCallSm90ATest, lowering_semantics=plgpu.LoweringSemantics.Warpgroup
):
...
| PallasCallSm90AWGTest |
python | tensorflow__tensorflow | tensorflow/python/util/function_parameter_canonicalizer_test.py | {
"start": 884,
"end": 3638
} | class ____(test.TestCase):
def setUp(self):
super(FunctionParameterCanonicalizerTest, self).setUp()
self._matmul_func = (
_function_parameter_canonicalizer_binding_for_test
.FunctionParameterCanonicalizer([
'a', 'b', 'transpose_a', 'transpose_b', 'adjoint_a', 'adjoint_b',
... | FunctionParameterCanonicalizerTest |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/exception.py | {
"start": 366,
"end": 504
} | class ____(UnityException):
"""
Raised when communicator has stopped gracefully.
"""
pass
| UnityCommunicatorStoppedException |
python | django__django | tests/forms_tests/widget_tests/test_splithiddendatetimewidget.py | {
"start": 177,
"end": 4047
} | class ____(WidgetTest):
widget = SplitHiddenDateTimeWidget()
def test_render_empty(self):
self.check_html(
self.widget,
"date",
"",
html=(
'<input type="hidden" name="date_0"><input type="hidden" name="date_1">'
),
)
... | SplitHiddenDateTimeWidgetTest |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/rpc_test.py | {
"start": 17464,
"end": 18353
} | class ____(nn.Module):
def __init__(self, device):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(1, 16, 3, 1),
nn.ReLU(),
nn.Conv2d(16, 32, 3, 1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Flatten(1),
nn.Linear(4608, 1... | MyConvNetForMNIST |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 522619,
"end": 523286
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("ProjectV2ItemFieldValueEdge"), graphql_name="edges"
)
nod... | ProjectV2ItemFieldValueConnection |
python | jmcnamara__XlsxWriter | xlsxwriter/exceptions.py | {
"start": 1028,
"end": 1115
} | class ____(XlsxFileError):
"""No size data found in image file."""
| UndefinedImageSize |
python | SmileyChris__easy-thumbnails | easy_thumbnails/tests/test_files.py | {
"start": 374,
"end": 17517
} | class ____(test.BaseTest):
def setUp(self):
super().setUp()
self.storage = test.TemporaryStorage()
self.remote_storage = test.FakeRemoteStorage()
# Save a test image in both storages.
filename = self.create_image(self.storage, 'test.jpg')
self.thumbnailer = files.ge... | FilesTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_bigtable.py | {
"start": 21339,
"end": 25957
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook")
def test_delete_execute(self, mock_hook):
op = BigtableDeleteInstanceOperator(
project_id=PROJECT_ID,
instance_id=INSTANCE_ID,
task_id="id",
gcp_conn_id=GCP_CONN_ID,
... | TestBigtableInstanceDelete |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/parent_foo/package.py | {
"start": 217,
"end": 634
} | class ____(Package):
"""This package has a variant "foo", which is True by default, and depends on another
package which has the same variant defaulting to False.
"""
homepage = "http://www.example.com"
url = "http://www.example.com/c-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789a... | ParentFoo |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar01.py | {
"start": 315,
"end": 1445
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/compiler/tests/concat_ops_test.py | {
"start": 13744,
"end": 14996
} | class ____(xla_test.XLATestCase):
def testBasic(self):
with self.session():
with self.test_scope():
s0 = constant_op.constant([2, 3, 5], dtypes.int32)
s1 = constant_op.constant([2, 7, 5], dtypes.int32)
s2 = constant_op.constant([2, 20, 5], dtypes.int32)
packed = array_ops_st... | PackTest |
python | getsentry__sentry | tests/sentry/api/endpoints/release_thresholds/utils/test_get_errors_counts_timeseries.py | {
"start": 310,
"end": 1738
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.org = self.create_organization()
self.project = self.create_project(name="foo", organization=self.org)
@mock.patch("sentry.api.endpoints.release_thresholds.utils.snuba.raw_snql_query")
def test_errors_timeseries_snu... | GetErrorCountTimeseriesTest |
python | pytorch__pytorch | test/distributed/checkpoint/test_hsdp_checkpoint.py | {
"start": 1532,
"end": 2069
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.net1 = nn.Linear(5, 10)
self.relu = nn.ReLU()
self.net2 = nn.Linear(10, 15)
self.net3 = nn.Linear(15, 30)
self.net4 = nn.Linear(30, 5)
def forward(self, x):
x = F.relu(self.n... | SimpleModelUneven |
python | ray-project__ray | python/ray/tune/schedulers/trial_scheduler.py | {
"start": 4321,
"end": 5484
} | class ____(TrialScheduler):
"""Simple scheduler that just runs trials in submission order."""
def __init__(self):
super().__init__()
def on_trial_add(self, tune_controller: "TuneController", trial: Trial):
pass
def on_trial_error(self, tune_controller: "TuneController", trial: Trial):... | FIFOScheduler |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 641086,
"end": 641429
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("StatusCheckRollupContext", graphql_name="node")
| StatusCheckRollupContextEdge |
python | ionelmc__pytest-benchmark | src/pytest_benchmark/cli.py | {
"start": 5954,
"end": 6690
} | class ____:
def __init__(self):
self._tw = TerminalWriter()
def ensure_newline(self):
pass
def write(self, content, **markup):
self._tw.write(content, **markup)
def write_line(self, line, **markup):
if not isinstance(line, str):
line = line.decode(errors='r... | TerminalReporter |
python | TheAlgorithms__Python | graphs/deep_clone_graph.py | {
"start": 318,
"end": 1741
} | class ____:
value: int = 0
neighbors: list["Node"] | None = None
def __post_init__(self) -> None:
"""
>>> Node(3).neighbors
[]
"""
self.neighbors = self.neighbors or []
def __hash__(self) -> int:
"""
>>> hash(Node(3)) != 0
True
""... | Node |
python | celery__celery | t/unit/utils/test_platforms.py | {
"start": 2161,
"end": 2551
} | class ____:
def test_raises_EBADF(self):
with ignore_errno('EBADF'):
exc = OSError()
exc.errno = errno.EBADF
raise exc
def test_otherwise(self):
with pytest.raises(OSError):
with ignore_errno('EBADF'):
exc = OSError()
... | test_ignore_errno |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 20842,
"end": 21406
} | class ____(LocalizableStreamlitException):
"""Exception raised when an invalid height value is provided."""
def __init__(self, height: Any, allow_content: bool = False) -> None:
valid_values = "an integer (pixels) or 'stretch'"
if allow_content:
valid_values = "an integer (pixels), ... | StreamlitInvalidHeightError |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/parallel.py | {
"start": 3958,
"end": 4203
} | class ____(AbstractProgressInfoMatcher):
def get_best_matching_lines(self, output: Output) -> list[str] | None:
last_lines, _ = get_last_lines_of_file(output.file_name, num_lines=1)
return last_lines
| ShowLastLineProgressMatcher |
python | pytorch__pytorch | torch/_inductor/dependencies.py | {
"start": 28837,
"end": 31333
} | class ____(DefaultHandler):
symbols: OrderedSet[sympy.Symbol]
def __init__(self, unbacked_only: bool = True) -> None:
self.symbols = OrderedSet()
self.get_symbols = free_unbacked_symbols if unbacked_only else free_symbols
def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[st... | FreeSymbolsOpsHandler |
python | joerick__pyinstrument | test/low_level/test_threaded.py | {
"start": 247,
"end": 1226
} | class ____:
def __init__(self, thread) -> None:
self.thread = thread
self.count = 0
def __call__(self, *args: Any, **kwds: Any) -> Any:
assert self.thread is threading.current_thread()
self.count += 1
def test_threaded():
# assert that each thread gets its own callbacks, a... | CallCounter |
python | dagster-io__dagster | python_modules/dagster/dagster/_utils/log.py | {
"start": 2082,
"end": 2928
} | class ____(
NamedTuple(
"_StructuredLoggerMessage",
[
("name", str),
("message", str),
("level", int),
("meta", Mapping[str, object]),
("record", logging.LogRecord),
],
)
):
def __new__(
cls,
name: str,
... | StructuredLoggerMessage |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/constant_fields.py | {
"start": 238,
"end": 1106
} | class ____(Enum):
TRACKED_FIELD = "A"
UNTRACKED_field = "B"
untracked_field = "C"
def tracked_index():
d = {}
d[CustomEnum.TRACKED_FIELD] = _test_source()
return d[CustomEnum.TRACKED_FIELD]
def untracked_index_a():
d = {}
d[CustomEnum.untracked_field] = _test_source()
return d[Cu... | CustomEnum |
python | prabhupant__python-ds | data_structures/binary_trees/right_view.py | {
"start": 244,
"end": 924
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def right_view_util(root, max_level, level):
if not root:
return
if max_level[0] < level:
print(root.val)
max_level[0] = level
right_view_util(root.right, max_l... | Node |
python | dask__distributed | distributed/diagnostics/progress.py | {
"start": 4360,
"end": 9063
} | class ____(Progress):
"""Progress variant that keeps track of different groups of keys
See Progress for most details.
Parameters
----------
func : Callable (deprecated)
Function that splits keys. This defaults to ``key_split`` which
aligns with naming conventions chosen in the das... | MultiProgress |
python | pytorch__pytorch | torch/_inductor/mkldnn_ir.py | {
"start": 22775,
"end": 26776
} | class ____(ExternKernelAlloc):
def __init__(
self,
layout,
inputs,
constant_args=(),
) -> None:
"""
Needs input/weight/output qparams
if bias is not None
- inputs = [x, x_scale, x_zp, w, w_scale, w_zp, accum, b]
- const_args = [str... | QConvPointWiseBinaryPT2E |
python | google__pytype | pytype/types/classes.py | {
"start": 1047,
"end": 1621
} | class ____:
"""Represents a class member variable.
Members:
name: field name
typ: field python type
init: Whether the field should be included in the generated __init__
kw_only: Whether the field is kw_only in the generated __init__
default: Default value
kind: Kind of attribute
Used in ... | Attribute |
python | getsentry__sentry | src/sentry/rules/conditions/base.py | {
"start": 464,
"end": 797
} | class ____(RuleBase, abc.ABC):
rule_type = "condition/event"
@abc.abstractmethod
def passes(self, event: GroupEvent, state: EventState) -> bool:
pass
def get_activity(
self, start: datetime, end: datetime, limit: int
) -> Sequence[ConditionActivity]:
raise NotImplementedErr... | EventCondition |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 153743,
"end": 154905
} | class ____(PositionToken):
"""Matches if the current position is at the end of a :class:`Word`,
and is not followed by any character in a given set of ``word_chars``
(default= ``printables``). To emulate the ``\b`` behavior of
regular expressions, use ``WordEnd(alphanums)``. ``WordEnd``
will also ma... | WordEnd |
python | apache__airflow | providers/github/tests/unit/github/hooks/test_github.py | {
"start": 1174,
"end": 5899
} | class ____:
# TODO: Potential performance issue, converted setup_class to a setup_connections function level fixture
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="github_default"... | TestGithubHook |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 37372,
"end": 37489
} | class ____(Enum):
string = "string"
number = "number"
integer = "integer"
boolean = "boolean"
| ValueType |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 2504,
"end": 2644
} | class ____(TypedDict):
userId: str
roles: List[str]
groups: List[str]
active: bool
dbUserType: str
| WeaviateDBUserRoleNames |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/evaluator_evaluation.py | {
"start": 11015,
"end": 12255
} | class ____(BaseLlamaPredictionDataset):
"""Pairwise evaluation predictions dataset class."""
_prediction_type = PairwiseEvaluatorExamplePrediction
def to_pandas(self) -> Any:
"""Create pandas dataframe."""
try:
import pandas as pd
except ImportError:
raise I... | PairwiseEvaluatorPredictionDataset |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/transfers/sql_to_s3.py | {
"start": 1410,
"end": 1835
} | class ____(enum.Enum):
"""Possible file formats."""
CSV = enum.auto()
JSON = enum.auto()
PARQUET = enum.auto()
FileOptions = namedtuple("FileOptions", ["mode", "suffix", "function"])
FILE_OPTIONS_MAP = {
FILE_FORMAT.CSV: FileOptions("r+", ".csv", "to_csv"),
FILE_FORMAT.JSON: FileOptions("r+"... | FILE_FORMAT |
python | getsentry__sentry | src/sentry/seer/models.py | {
"start": 2703,
"end": 2890
} | class ____(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return f"Seer permission error: {self.message}"
| SeerPermissionError |
python | gevent__gevent | src/gevent/events.py | {
"start": 11178,
"end": 11286
} | class ____(GeventPatchEvent):
"""
Implementation of `IGeventDidPatchEvent`.
"""
| GeventDidPatchEvent |
python | pytorch__pytorch | torch/distributed/_composable/replicate_with_fsdp.py | {
"start": 1366,
"end": 2587
} | class ____:
"""This has state shared across Replicate states."""
def __init__(self) -> None:
# All Replicate states in the root state's module tree
self.all_states: list[_ReplicateState] = []
# Iteration's forward root runs the once-per-forward logic; this root
# may not be the ... | _ReplicateStateContext |
python | jazzband__django-model-utils | tests/test_choices.py | {
"start": 6010,
"end": 9580
} | class ____(TestCase, ChoicesTestsMixin[int]):
def setUp(self) -> None:
self.STATUS = Choices(
(0, 'DRAFT', 'is draft'),
(1, 'PUBLISHED', 'is published'),
(2, 'DELETED', 'is deleted'))
def test_iteration(self) -> None:
self.assertEqual(tuple(self.STATUS), (
... | IdentifierChoicesTests |
python | Pylons__pyramid | docs/tutorials/wiki2/src/authorization/tutorial/routes.py | {
"start": 1044,
"end": 1545
} | class ____:
def __init__(self, pagename):
self.pagename = pagename
def __acl__(self):
return [
(Allow, 'role:editor', 'create'),
(Allow, 'role:basic', 'create'),
]
def page_factory(request):
pagename = request.matchdict['pagename']
page = request.dbsessi... | NewPage |
python | tensorflow__tensorflow | tensorflow/python/framework/python_api_dispatcher_test.py | {
"start": 1410,
"end": 10421
} | class ____(test_util.TensorFlowTestCase):
def testInstanceChecker(self):
t = constant_op.constant([1, 2, 3])
rt = ragged_factory_ops.constant([[1, 2], [3, 4, 5]])
with self.subTest('int checker'):
int_checker = dispatch.MakeInstanceChecker(int)
self.assertEqual(int_checker.Check(3), MATCH)
... | PythonTypeCheckerTest |
python | django__django | django/db/models/fields/__init__.py | {
"start": 48002,
"end": 48710
} | class ____(CharField):
default_validators = [validators.validate_comma_separated_integer_list]
description = _("Comma-separated integers")
system_check_removed_details = {
"msg": (
"CommaSeparatedIntegerField is removed except for support in "
"historical migrations."
... | CommaSeparatedIntegerField |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 58223,
"end": 63575
} | class ____(Request):
"""
Get the debug image events for the requested amount of iterations per each task
:param metrics: List of metrics and variants
:type metrics: Sequence[TaskMetricVariants]
:param iters: Max number of latest iterations for which to return debug images
:type iters: int
:... | DebugImagesRequest |
python | pydata__xarray | xarray/core/indexing.py | {
"start": 23456,
"end": 27678
} | class ____(ExplicitlyIndexedNDArrayMixin):
"""Wrap an array to make basic and outer indexing lazy."""
__slots__ = ("_shape", "array", "key")
def __init__(self, array: Any, key: ExplicitIndexer | None = None):
"""
Parameters
----------
array : array_like
Array li... | LazilyIndexedArray |
python | getsentry__sentry | src/sentry/tagstore/base.py | {
"start": 947,
"end": 9965
} | class ____(Service):
__read_methods__ = frozenset(
[
"get_tag_key",
"get_tag_keys",
"get_tag_values",
"get_group_tag_key",
"get_group_tag_keys",
"get_group_list_tag_value",
"get_generic_group_list_tag_value",
"ge... | TagStorage |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/resources.py | {
"start": 32896,
"end": 40715
} | class ____(BaseAirbyteWorkspace):
"""This resource allows users to programatically interface with the Airbyte Cloud REST API to launch
syncs and monitor their progress for a given Airbyte Cloud workspace.
**Examples:**
.. code-block:: python
from dagster_airbyte import AirbyteCloudWorkspace, ... | AirbyteCloudWorkspace |
python | jpadilla__pyjwt | jwt/exceptions.py | {
"start": 1034,
"end": 1184
} | class ____(InvalidTokenError):
"""Raised when a token's ``nbf`` or ``iat`` claims represent a time in the future"""
pass
| ImmatureSignatureError |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/operators/campaign_manager.py | {
"start": 4806,
"end": 9629
} | class ____(BaseOperator):
"""
Retrieves a report and uploads it to GCS bucket.
.. seealso::
Check official API docs:
`https://developers.google.com/doubleclick-advertisers/rest/v4/reports/get`
.. seealso::
For more information on how to use this operator, take a look at the gui... | GoogleCampaignManagerDownloadReportOperator |
python | joke2k__faker | faker/providers/color/hy_AM/__init__.py | {
"start": 80,
"end": 6419
} | class ____(ColorProvider):
"""Implement color provider for ``hy_AM`` locale."""
all_colors = OrderedDict(
(
("Ալիսի կապույտ", "#F0F8FF"),
("Անանուխի կրեմ", "#F5FFFA"),
("Անտառային կանաչ", "#228B22"),
("Արծաթագույն", "#C0C0C0"),
("Արքայական կապ... | Provider |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_expand_dims_op_test.py | {
"start": 1040,
"end": 4725
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
# An example 4-d ragged tensor with shape [3, (D2), (D3), 2], and the
# expected result calling for expand_dims on each axis. c.f. the table of
# expected result shapes in the ragged_array_ops.expand_dims docstring.
... | RaggedExpandDimsOpTest |
python | kamyu104__LeetCode-Solutions | Python/pancake-sorting.py | {
"start": 3389,
"end": 3906
} | class ____(object):
def pancakeSort(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
def reverse(l, begin, end):
for i in xrange((end-begin) // 2):
l[begin+i], l[end-1-i] = l[end-1-i], l[begin+i]
result = []
for n in reversed... | Solution3 |
python | automl__auto-sklearn | autosklearn/pipeline/components/base.py | {
"start": 2733,
"end": 5466
} | class ____(BaseEstimator):
@staticmethod
def get_properties(dataset_properties=None):
"""Get the properties of the underlying algorithm.
Find more information at :ref:`get_properties`
Parameters
----------
dataset_properties : dict, optional (default=None)
Ret... | AutoSklearnComponent |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braze/components.py | {
"start": 1460,
"end": 4282
} | class ____(DatetimeBasedCursor):
"""
Extends DatetimeBasedCursor for Braze's API requirements where instead of using explicit
start_time/end_time parameters, the API expects:
- An end_time (ending_at)
- A length parameter indicating how many days before end_time to fetch
The length parameter re... | DatetimeIncrementalSyncComponent |
python | neetcode-gh__leetcode | python/0448-find-all-numbers-disappeared-in-an-array.py | {
"start": 0,
"end": 304
} | class ____:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
for n in nums:
i = abs(n) - 1
nums[i] = -1 * abs(nums[i])
res = []
for i, n in enumerate(nums):
if n > 0:
res.append(i + 1)
return res
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py | {
"start": 19125,
"end": 19630
} | class ____(MetadataValue[str]):
"""Container class for URL metadata entry data.
Args:
url (Optional[str]): The URL as a string.
"""
url: PublicAttr[Optional[str]] = "" # type: ignore
@public
@property
def value(self) -> str:
"""Optional[str]: The wrapped URL."""
r... | UrlMetadataValue |
python | kamyu104__LeetCode-Solutions | Python/shortest-palindrome.py | {
"start": 694,
"end": 1441
} | class ____(object):
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def getPrefix(pattern):
prefix = [-1] * len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j > -1 and pattern[j+1] != pattern[i]:... | Solution2 |
python | getsentry__sentry | src/sentry/similarity/backends/dummy.py | {
"start": 71,
"end": 885
} | class ____(AbstractIndexBackend):
def classify(self, scope, items, limit=None, timestamp=None):
return []
def compare(self, scope, key, items, limit=None, timestamp=None):
return []
def record(self, scope, key, items, timestamp=None):
return {}
def merge(self, scope, destinati... | DummyIndexBackend |
python | numba__numba | numba/tests/test_extending.py | {
"start": 35961,
"end": 43157
} | class ____(TestCase):
def test_void_return(self):
"""
Verify that returning a None from codegen function is handled
automatically for void functions, otherwise raise exception.
"""
@intrinsic
def void_func(typingctx, a):
sig = types.void(types.int32)
... | TestIntrinsic |
python | kubernetes-client__python | kubernetes/client/models/v1alpha1_cluster_trust_bundle_spec.py | {
"start": 383,
"end": 7397
} | 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... | V1alpha1ClusterTrustBundleSpec |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 24428,
"end": 24631
} | class ____(PrefectBaseModel):
"""Filter by `BlockDocument.id`."""
any_: Optional[List[UUID]] = Field(
default=None, description="A list of block ids to include"
)
| BlockDocumentFilterId |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/dataset.py | {
"start": 4966,
"end": 8199
} | class ____(GoogleCloudBaseOperator):
"""
Get a Dataset.
:param project_id: Required. The ID of the Google Cloud project the cluster belongs to.
:param region: Required. The Cloud Dataproc region in which to handle the request.
:param dataset_id: Required. The ID of the Dataset to get.
:param re... | GetDatasetOperator |
python | spyder-ide__spyder | spyder/plugins/shortcuts/plugin.py | {
"start": 1468,
"end": 9089
} | class ____(SpyderPluginV2, SpyderShortcutsMixin):
"""
Shortcuts Plugin.
"""
NAME = 'shortcuts'
# TODO: Fix requires to reflect the desired order in the preferences
REQUIRES = [Plugins.Preferences]
OPTIONAL = [Plugins.MainMenu]
CONF_WIDGET_CLASS = ShortcutsConfigPage
CONF_SECTION = N... | Shortcuts |
python | google__pytype | pytype/overlays/typing_overlay.py | {
"start": 19750,
"end": 21075
} | class ____(overlay_utils.TypingContainer):
"""Implementation of typing.Literal."""
def _build_value(self, node, inner, ellipses):
values = []
errors = []
for i, param in enumerate(inner):
# TODO(b/173742489): Once the enum overlay is enabled, we should
# stop allowing unsolvable and handle ... | Literal |
python | google__jax | tests/extend_test.py | {
"start": 982,
"end": 2643
} | class ____(jtu.JaxTestCase):
def test_symbols(self):
# Assume these are tested in random_test.py, only check equivalence
self.assertIs(jex.random.seed_with_impl, prng.seed_with_impl)
self.assertIs(jex.random.threefry2x32_p, prng.threefry2x32_p)
self.assertIs(jex.random.threefry_2x32, prng.threefry_2x... | ExtendTest |
python | graphql-python__graphene | graphene/relay/tests/test_node_custom.py | {
"start": 181,
"end": 555
} | class ____(Node):
class Meta:
name = "Node"
@staticmethod
def to_global_id(type_, id):
return id
@staticmethod
def get_node_from_global_id(info, id, only_type=None):
assert info.schema is graphql_schema
if id in user_data:
return user_data.get(id)
... | CustomNode |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/angle_helper.py | {
"start": 5166,
"end": 5349
} | class ____(LocatorBase):
def __call__(self, v1, v2):
return select_step360(v1, v2, self.nbins, self._include_last,
threshold_factor=1)
| LocatorD |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_util__embed.py | {
"start": 23195,
"end": 24060
} | class ____:
def test_no_docs(self) -> None:
p1 = SomeModel()
p2 = SomeModel()
beu._dispose_temp_doc([p1, p2])
assert p1.document is None
assert p2.document is None
def test_with_docs(self) -> None:
d1 = Document()
d2 = Document()
p1 = SomeModel()
... | Test__dispose_temp_doc |
python | huggingface__transformers | src/transformers/models/big_bird/tokenization_big_bird.py | {
"start": 1103,
"end": 8733
} | class ____(TokenizersBackend):
"""
Construct a "fast" BigBird tokenizer (backed by HuggingFace's *tokenizers* library). Based on
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
tokenizer inherits from [`PreTrainedTokenizerFast`] which contai... | BigBirdTokenizer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.