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 | davidhalter__jedi | jedi/inference/names.py | {
"start": 849,
"end": 2742
} | class ____:
start_pos: Optional[Tuple[int, int]] = None
string_name: str
parent_context = None
tree_name = None
is_value_name = True
"""
Used for the Jedi API to know if it's a keyword or an actual name.
"""
@abstractmethod
def infer(self):
raise NotImplementedError
... | AbstractNameDefinition |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias18.py | {
"start": 716,
"end": 740
} | class ____(A[T2]): ...
| A_3 |
python | sqlalchemy__sqlalchemy | test/orm/test_versioning.py | {
"start": 17653,
"end": 22813
} | class ____(fixtures.MappedTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"node",
metadata,
Column("id", Integer, primary_key=True),
Column("version_id", Integer),
Column("parent_id", ForeignKe... | VersionOnPostUpdateTest |
python | crytic__slither | slither/detectors/statements/msg_value_in_loop.py | {
"start": 2546,
"end": 4259
} | class ____(AbstractDetector):
"""
Detect the use of msg.value inside a loop
"""
ARGUMENT = "msg-value-loop"
HELP = "msg.value inside a loop"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documenta... | MsgValueInLoop |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_training.py | {
"start": 10913,
"end": 27677
} | class ____(FSDPTest):
@property
def world_size(self) -> int:
return min(8, torch.get_device_module(device_type).device_count())
@skip_if_lt_x_gpu(2)
def test_train_parity_single_group_shard_dim0(self):
"""
Tests train parity with DDP for a single FSDP group when sharding
... | TestFullyShard1DTrainingCore |
python | plotly__plotly.py | plotly/graph_objs/_choropleth.py | {
"start": 231,
"end": 65984
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "choropleth"
_valid_props = {
"autocolorscale",
"coloraxis",
"colorbar",
"colorscale",
"customdata",
"customdatasrc",
"featureidkey",
"geo",
"geojson",
"hoverinfo",
... | Choropleth |
python | dask__dask | dask/dataframe/dask_expr/_str_accessor.py | {
"start": 3379,
"end": 3717
} | class ____(Blockwise):
_parameters = ["frame", "sep", "na_rep"]
_keyword_only = ["sep", "na_rep"]
@property
def _args(self) -> list:
return [self.frame] + self.operands[len(self._parameters) :]
@staticmethod
def operation(ser, *args, **kwargs):
return ser.str.cat(list(args), **... | CatBlockwise |
python | numba__numba | numba/core/bytecode.py | {
"start": 8571,
"end": 9253
} | class ____(object):
def __init__(self, code):
self.code = code
self.iter = iter(_patched_opargs(_unpack_opargs(self.code.co_code)))
def __iter__(self):
return self
def _fetch_opcode(self):
return next(self.iter)
def next(self):
offset, opcode, arg, nextoffset =... | ByteCodeIter |
python | has2k1__plotnine | plotnine/scales/scale_linetype.py | {
"start": 310,
"end": 782
} | class ____(scale_discrete):
"""
Scale for line patterns
Notes
-----
The available linetypes are
`'solid', 'dashed', 'dashdot', 'dotted'`
If you need more custom linetypes, use
[](`~plotnine.scales.scale_linetype_manual`)
"""
_aesthetics = ["linetype"]
def __post_init__(sel... | scale_linetype |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/extra/django/_impl.py | {
"start": 988,
"end": 1433
} | class ____:
def setup_example(self):
self._pre_setup()
def teardown_example(self, example):
self._post_teardown()
def __call__(self, result=None):
testMethod = getattr(self, self._testMethodName)
if getattr(testMethod, "is_hypothesis_test", False):
return unitte... | HypothesisTestCase |
python | ray-project__ray | doc/source/ray-core/doc_code/cgraph_quickstart.py | {
"start": 3074,
"end": 3943
} | class ____:
def echo(self, msg):
return msg
actors = [EchoActor.remote() for _ in range(4)]
with InputNode() as inp:
outputs = [actor.echo.bind(inp) for actor in actors]
dag = MultiOutputNode(outputs)
compiled_dag = dag.experimental_compile()
# Kill one of the actors to simulate unexpected actor ... | EchoActor |
python | mlflow__mlflow | mlflow/store/artifact/databricks_artifact_repo_resources.py | {
"start": 763,
"end": 832
} | class ____(Enum):
READ = 1
WRITE = 2
@dataclass
| _CredentialType |
python | PyCQA__pylint | tests/functional/r/regression/regression_issue_4633.py | {
"start": 341,
"end": 466
} | class ____:
def whatever(self):
test_var = Ham()
while not test_var.queue.empty():
pass
| SecondHam |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 14992,
"end": 15060
} | class ____:
def __init__(*, tastes_bitter=None):
...
| Fruit |
python | huggingface__transformers | src/transformers/models/smollm3/modular_smollm3.py | {
"start": 1449,
"end": 10530
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SmolLM3Model`]. It is used to instantiate a
SmolLM3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar confi... | SmolLM3Config |
python | squidfunk__mkdocs-material | material/extensions/preview.py | {
"start": 1691,
"end": 5611
} | class ____(Treeprocessor):
"""
A Markdown treeprocessor to enable instant previews on links.
Note that this treeprocessor is dependent on the `relpath` treeprocessor
registered programmatically by MkDocs before rendering a page.
"""
def __init__(self, md: Markdown, config: dict):
"""
... | PreviewProcessor |
python | charliermarsh__ruff | scripts/ty_benchmark/src/benchmark/__init__.py | {
"start": 237,
"end": 476
} | class ____(NamedTuple):
name: str
"""The name of the command to benchmark."""
command: list[str]
"""The command to benchmark."""
prepare: str | None = None
"""The command to run before each benchmark run."""
| Command |
python | pytorch__pytorch | torch/_export/passes/lift_constants_pass.py | {
"start": 646,
"end": 17478
} | class ____(collections.abc.MutableMapping):
"""A mapping class that understands how to use module constants (tensors,
ScriptObjects, FakeScriptObjects) as keys. We store tensors and FakeScriptObjects normally,
but ScriptObjects are stored by hash, because different torch.ScriptObjects can point to
the s... | ConstantAttrMap |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 56331,
"end": 56923
} | class ____:
# sfx is sf(x). The values were computed with mpmath:
#
# from mpmath import mp
# mp.dps = 100
# def gibrat_sf(x):
# return 1 - mp.ncdf(mp.log(x))
#
# E.g.
#
# >>> float(gibrat_sf(1.5))
# 0.3425678305148459
#
@pytest.mark.parametrize('x, ... | TestGibrat |
python | huggingface__transformers | src/transformers/models/albert/modeling_albert.py | {
"start": 8424,
"end": 9924
} | class ____(nn.Module):
def __init__(self, config: AlbertConfig):
super().__init__()
self.config = config
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.full_layer_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps... | AlbertLayer |
python | huggingface__transformers | tests/models/cvt/test_modeling_cvt.py | {
"start": 1342,
"end": 1614
} | class ____(ConfigTester):
def create_and_test_config_common_properties(self):
config = self.config_class(**self.inputs_dict)
self.parent.assertTrue(hasattr(config, "embed_dim"))
self.parent.assertTrue(hasattr(config, "num_heads"))
| CvtConfigTester |
python | pytorch__pytorch | test/inductor/extension_backends/triton/device_interface.py | {
"start": 144,
"end": 369
} | class ____:
def __init__(self) -> None:
self.major = 8 # TODO: bypass check for H100 in triton_heuristics.py
self.max_threads_per_multi_processor = 1
self.multi_processor_count = 80
| DeviceProperties |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 10606,
"end": 11496
} | class ____(ChainedSource):
member: str
def __post_init__(self) -> None:
assert self.base, "Can't construct an AttrSource without a valid base source"
if "." in self.member:
member_parts = self.member.split(".")
object.__setattr__(
self, "base", AttrSource... | GenericAttrSource |
python | pytorch__pytorch | torch/distributed/checkpoint/_pg_transport.py | {
"start": 771,
"end": 1167
} | class ____:
"""
This is the metadata for a tensor that is used to transfer checkpoints.
It contains the shape, the dtype, the storage offset and the stride of the
tensor.
This must be pickleable so that it can be sent over the wire.
"""
shape: torch.Size
dtype: torch.dtype
storage_... | _TensorMeta |
python | pytorch__pytorch | test/dynamo/test_base_output.py | {
"start": 369,
"end": 2363
} | class ____(torch._dynamo.test_case.TestCase):
@maybe_skip
def test_create(self):
def fn(a):
tmp = unet_2d.UNet2DOutput(a + 1)
return tmp
torch._dynamo.testing.standard_test(self, fn=fn, nargs=1, expected_ops=1)
@maybe_skip
def test_assign(self):
def fn(a... | TestBaseOutput |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-cut-a-stick.py | {
"start": 33,
"end": 579
} | class ____(object):
def minCost(self, n, cuts):
"""
:type n: int
:type cuts: List[int]
:rtype: int
"""
sorted_cuts = sorted(cuts + [0, n])
dp = [[0]*len(sorted_cuts) for _ in xrange(len(sorted_cuts))]
for l in xrange(2, len(sorted_cuts)):
f... | Solution |
python | pytorch__pytorch | tools/experimental/torchfuzz/checks.py | {
"start": 832,
"end": 2187
} | class ____(Check):
"""Check that runs eager and compiled, compares forward numerics."""
def codegen(self, args_tuple: str) -> list[str]:
return [
f"args = {args_tuple}",
"out_eager = fuzzed_program(*args)",
"out_eager.sum().backward()",
"print('Eager Succ... | EagerVsFullGraphDynamicCompileWithNumericsCheck |
python | pydata__xarray | xarray/backends/h5netcdf_.py | {
"start": 3072,
"end": 14857
} | class ____(WritableCFDataStore):
"""Store for reading and writing data via h5netcdf"""
__slots__ = (
"_filename",
"_group",
"_manager",
"_mode",
"autoclose",
"format",
"is_remote",
"lock",
)
def __init__(
self,
manager: Fi... | H5NetCDFStore |
python | numba__numba | numba/tests/test_parfors.py | {
"start": 165587,
"end": 166200
} | class ____(TestCase):
@TestCase.run_test_in_subprocess()
def test_diagnostics_env_var1(self):
os.environ['NUMBA_PARALLEL_DIAGNOSTICS']='4'
with captured_stdout() as stdout:
@njit(parallel=True)
def impl():
n = 100
b = np.zeros((n), dtype=np... | TestDiagnosticEnvVar |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 35066,
"end": 36056
} | class ____(
_MutableDictTestBase, fixtures.MappedTest
):
@classmethod
def define_tables(cls, metadata):
import json
class JSONEncodedDict(TypeDecorator):
impl = VARCHAR(50)
cache_ok = True
def process_bind_param(self, value, dialect):
if ... | MutableAssociationScalarJSONTest |
python | tornadoweb__tornado | tornado/web.py | {
"start": 93476,
"end": 97324
} | class ____(httputil.HTTPMessageDelegate):
def __init__(
self,
application: Application,
request: httputil.HTTPServerRequest,
handler_class: Type[RequestHandler],
handler_kwargs: Optional[Dict[str, Any]],
path_args: Optional[List[bytes]],
path_kwargs: Optional[... | _HandlerDelegate |
python | networkx__networkx | networkx/readwrite/tests/test_graph6.py | {
"start": 4613,
"end": 6559
} | class ____:
def test_null_graph(self):
G = nx.null_graph()
assert g6.to_graph6_bytes(G) == b">>graph6<<?\n"
def test_trivial_graph(self):
G = nx.trivial_graph()
assert g6.to_graph6_bytes(G) == b">>graph6<<@\n"
def test_complete_graph(self):
assert g6.to_graph6_bytes... | TestToGraph6Bytes |
python | ansible__ansible | packaging/release.py | {
"start": 9169,
"end": 9392
} | class ____:
"""Details required to create a GitHub release."""
user: str
repo: str
tag: str
target: str
title: str
body: str
pre_release: bool
@dataclasses.dataclass(frozen=True)
| GitHubRelease |
python | getsentry__sentry | src/sentry_plugins/pushover/client.py | {
"start": 46,
"end": 809
} | class ____(ApiClient):
base_url = "https://api.pushover.net/1"
allow_redirects = False
plugin_name = "pushover"
def __init__(self, userkey=None, apikey=None):
self.userkey = userkey
self.apikey = apikey
super().__init__()
def request(self, method, path, data):
# see... | PushoverClient |
python | python-poetry__poetry | tests/types.py | {
"start": 3707,
"end": 3884
} | class ____(Protocol):
def __call__(
self,
distribution_locations: list[Path],
metadata_locations: list[Path],
) -> None: ...
| PythonHostedFileMocker |
python | kennethreitz__tablib | tests/test_tablib.py | {
"start": 44238,
"end": 44863
} | class ____(BaseTestCase):
def test_cli_export_github(self):
self.assertEqual(
'|---|---|---|\n| a | b | c |',
tablib.Dataset(['a', 'b', 'c']).export('cli', tablefmt='github')
)
def test_cli_export_simple(self):
self.assertEqual(
'- - -\na b c\n- ... | CliTests |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 66546,
"end": 66717
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('size', c_ulonglong),
]
VgpuRuntimeState_v1 = 0x1000010
| nvmlVgpuRuntimeState_v1_t |
python | pytorch__pytorch | torch/_inductor/choices.py | {
"start": 1655,
"end": 25785
} | class ____:
"""
This class contains a collection of default heuristics that effect performance of our generated
code. We try to not put correctness requirements in this file.
You can override the choices made here by doing:
class MyHeuristics(InductorChoices):
...
... | InductorChoices |
python | joke2k__faker | faker/providers/color/de/__init__.py | {
"start": 140,
"end": 5877
} | class ____(ColorProvider):
"""
Color provider for ``de`` locale. Source: https://www.sttmedia.com/colornames
"""
all_colors: OrderedDictType[str, str] = OrderedDict(
(
("Eisfarben", "#F0F8FF"),
("Antikweiß", "#FAEBD7"),
("Wasser", "#00FFFF"),
("Aq... | Provider |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor24.py | {
"start": 1801,
"end": 1848
} | class ____: ...
T_A = TypeVar("T_A", bound=A)
| A |
python | doocs__leetcode | lcof/面试题14- I. 剪绳子/Solution2.py | {
"start": 0,
"end": 257
} | class ____:
def cuttingRope(self, n: int) -> int:
if n < 4:
return n - 1
if n % 3 == 0:
return pow(3, n // 3)
if n % 3 == 1:
return pow(3, n // 3 - 1) * 4
return pow(3, n // 3) * 2
| Solution |
python | huggingface__transformers | src/transformers/models/vit_msn/modeling_vit_msn.py | {
"start": 19406,
"end": 21788
} | class ____(ViTMSNPreTrainedModel):
def __init__(self, config: ViTMSNConfig) -> None:
super().__init__(config)
self.num_labels = config.num_labels
self.vit = ViTMSNModel(config)
# Classifier head
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.nu... | ViTMSNForImageClassification |
python | getsentry__sentry-python | sentry_sdk/session.py | {
"start": 598,
"end": 5589
} | class ____:
def __init__(
self,
sid=None, # type: Optional[Union[str, uuid.UUID]]
did=None, # type: Optional[str]
timestamp=None, # type: Optional[datetime]
started=None, # type: Optional[datetime]
duration=None, # type: Optional[float]
status=None, # ty... | Session |
python | pypa__setuptools | setuptools/_vendor/jaraco/collections/__init__.py | {
"start": 12564,
"end": 13066
} | class ____:
"""
Provide a getitem interface for attributes of an object.
Let's say you want to get at the string.lowercase property in a formatted
string. It's easy with DictAdapter.
>>> import string
>>> print("lowercase is %(ascii_lowercase)s" % DictAdapter(string))
lowercase is abcdefgh... | DictAdapter |
python | google__pytype | pytype/pytd/booleq.py | {
"start": 3124,
"end": 5705
} | class ____(BooleanTerm):
"""An equality constraint.
This declares an equality between a variable and a value, or a variable
and a variable. External code should use Eq rather than creating an _Eq
instance directly.
Attributes:
left: A string; left side of the equality. This is expected to be the string
... | _Eq |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/output.py | {
"start": 7825,
"end": 9376
} | class ____(OutputDefinition):
"""Variant of :py:class:`OutputDefinition <dagster.OutputDefinition>` for an
output that will dynamically alter the graph at runtime.
When using in a composition function such as :py:func:`@job <dagster.job>`,
dynamic outputs must be used with either:
* ``map`` - clon... | DynamicOutputDefinition |
python | pandas-dev__pandas | pandas/core/nanops.py | {
"start": 2346,
"end": 52884
} | class ____:
def __init__(self, name=None, **kwargs) -> None:
self.name = name
self.kwargs = kwargs
def __call__(self, alt: F) -> F:
bn_name = self.name or alt.__name__
try:
bn_func = getattr(bn, bn_name)
except (AttributeError, NameError): # pragma: no cove... | bottleneck_switch |
python | kamyu104__LeetCode-Solutions | Python/minimize-malware-spread.py | {
"start": 510,
"end": 1297
} | class ____(object):
def minMalwareSpread(self, graph, initial):
"""
:type graph: List[List[int]]
:type initial: List[int]
:rtype: int
"""
union_find = UnionFind(len(graph))
for i in xrange(len(graph)):
for j in xrange(i+1, len(graph)):
... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-aws/infra/worker/events_stack.py | {
"start": 404,
"end": 4243
} | class ____(Stack):
"""EventBridge and SQS infrastructure for ECS task state monitoring."""
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# Parameters
self.work_pool_name = CfnParameter(
self,
... | EcsEventsStack |
python | huggingface__transformers | src/transformers/models/dots1/configuration_dots1.py | {
"start": 878,
"end": 10435
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Dots1Model`]. It is used to instantiate a
`dots.llm1` model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar con... | Dots1Config |
python | streamlit__streamlit | lib/tests/streamlit/elements/plotly_chart_test.py | {
"start": 10908,
"end": 19355
} | class ____(DeltaGeneratorTestCase):
"""Test plotly_chart width parameter functionality."""
@parameterized.expand(
[
# width, expected_width_spec, expected_width_value
("stretch", "use_stretch", True),
("content", "pixel_width", 700), # Content width resolves to 700p... | PlotlyChartWidthTest |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/branch/models.py | {
"start": 1029,
"end": 1226
} | class ____:
"""Individual diagnostics log entry."""
correlation_id: str
timestamp: str
level: str
category: str
message: str
data: dict[str, Any]
@record
| DiagnosticsEntry |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/asset/__init__.py | {
"start": 17052,
"end": 17174
} | class ____(AssetRef):
"""URI reference to an asset."""
uri: str
_dependency_type = "asset-uri-ref"
| AssetUriRef |
python | pandas-dev__pandas | pandas/core/arrays/string_arrow.py | {
"start": 1971,
"end": 19291
} | class ____(ObjectStringArrayMixin, ArrowExtensionArray, BaseStringArray):
"""
Extension array for string data in a ``pyarrow.ChunkedArray``.
.. warning::
ArrowStringArray is considered experimental. The implementation and
parts of the API may change without warning.
Parameters
-----... | ArrowStringArray |
python | sympy__sympy | sympy/categories/baseclasses.py | {
"start": 803,
"end": 1101
} | class ____(Symbol):
"""
The base class for any kind of object in an abstract category.
Explanation
===========
While technically any instance of :class:`~.Basic` will do, this
class is the recommended way to create abstract objects in
abstract categories.
"""
| Object |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 32941,
"end": 34090
} | class ____(PrefectFilterBaseModel):
"""Filter by `TaskRun.start_time`."""
before_: Optional[DateTime] = Field(
default=None,
description="Only include task runs starting at or before this time",
)
after_: Optional[DateTime] = Field(
default=None,
description="Only includ... | TaskRunFilterStartTime |
python | ray-project__ray | python/ray/data/_internal/arrow_block.py | {
"start": 2272,
"end": 4374
} | class ____(Mapping):
"""
Row of a tabular Dataset backed by a Arrow Table block.
"""
def __init__(self, row: Any):
self._row = row
def __getitem__(self, key: Union[str, List[str]]) -> Any:
from ray.data.extensions import get_arrow_extension_tensor_types
tensor_arrow_extens... | ArrowRow |
python | ray-project__ray | python/ray/tests/test_gcs_fault_tolerance.py | {
"start": 981,
"end": 36152
} | class ____:
def method(self, x):
return x + 2
@ray.remote
def increase(x):
return x + 1
def cluster_kill_gcs_wait(cluster):
head_node = cluster.head_node
gcs_server_process = head_node.all_processes["gcs_server"][0].process
gcs_server_pid = gcs_server_process.pid
# Kill gcs server.
... | Increase |
python | ipython__ipython | tests/test_zzz_autoreload.py | {
"start": 1493,
"end": 2985
} | class ____:
def __init__(self):
self.ns = {}
self.user_ns = self.ns
self.user_ns["In"] = []
self.user_ns_hidden = {}
self.events = EventManager(self, {"pre_run_cell", pre_run_cell})
self.auto_magics = AutoreloadMagics(shell=self)
self.events.register("pre_run_... | FakeShell |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/sentry_app_publish_request.py | {
"start": 1021,
"end": 1232
} | class ____(serializers.Serializer):
question = serializers.CharField(required=True, allow_null=False)
answer = serializers.CharField(required=True, allow_null=False)
| SentryAppPublishQuestionnaireSerializer |
python | mlflow__mlflow | mlflow/types/llm.py | {
"start": 23016,
"end": 24035
} | class ____(_BaseDataclass):
"""
A single chat response generated by the model.
ref: https://platform.openai.com/docs/api-reference/chat/object
Args:
message (:py:class:`ChatMessage`): The message that was generated.
index (int): The index of the response in the list of responses.
... | ChatChoice |
python | doocs__leetcode | solution/1400-1499/1426.Counting Elements/Solution.py | {
"start": 0,
"end": 155
} | class ____:
def countElements(self, arr: List[int]) -> int:
cnt = Counter(arr)
return sum(v for x, v in cnt.items() if cnt[x + 1])
| Solution |
python | pytest-dev__pytest | src/_pytest/python.py | {
"start": 9201,
"end": 12128
} | class ____(nodes.Node):
"""this mix-in inherits from Node to carry over the typing information
as its intended to always mix in before a node
its position in the mro is unaffected"""
_ALLOW_MARKERS = True
@property
def module(self):
"""Python module object this node was collected from... | PyobjMixin |
python | lazyprogrammer__machine_learning_examples | supervised_class/perceptron.py | {
"start": 755,
"end": 3105
} | class ____:
def fit(self, X, Y, learning_rate=1.0, epochs=1000):
# solution
# self.w = np.array([-0.5, 0.5])
# self.b = 0.1
# initialize random weights
D = X.shape[1]
self.w = np.random.randn(D)
self.b = 0
N = len(Y)
costs = []
for ep... | Perceptron |
python | Textualize__textual | src/textual/events.py | {
"start": 24058,
"end": 24214
} | class ____(Event, bubble=False):
"""Sent to screen when it is no longer active.
- [ ] Bubbles
- [ ] Verbose
"""
@rich.repr.auto
| ScreenSuspend |
python | getsentry__sentry | src/sentry/auth/elevated_mode.py | {
"start": 584,
"end": 1938
} | class ____(ABC):
@property
@abstractmethod
def is_active(self) -> bool:
pass
@abstractmethod
def is_privileged_request(self) -> tuple[bool, InactiveReason]:
pass
@abstractmethod
def get_session_data(self, current_datetime: datetime | None = None) -> dict[str, Any] | None:
... | ElevatedMode |
python | getsentry__sentry | src/sentry/utils/kvstore/encoding.py | {
"start": 194,
"end": 1676
} | class ____(KVStorage[K, TDecoded]):
"""
This class provides a wrapper that can be used to transparently
encode/decode values in the provided key/value storage to another type on
reading and writing by using the provided codec. This allows key/value
storages that have different value types to be used... | KVStorageCodecWrapper |
python | pydata__xarray | xarray/coding/variables.py | {
"start": 21689,
"end": 22817
} | class ____(VariableCoder):
"""Code boolean values."""
def encode(self, variable: Variable, name: T_Name = None) -> Variable:
if (
(variable.dtype == bool)
and ("dtype" not in variable.encoding)
and ("dtype" not in variable.attrs)
):
dims, data, at... | BooleanCoder |
python | sphinx-doc__sphinx | sphinx/domains/_index.py | {
"start": 1035,
"end": 3259
} | class ____(ABC):
"""An Index is the description for a domain-specific index. To add an index to
a domain, subclass Index, overriding the three name attributes:
* `name` is an identifier used for generating file names.
It is also used for a hyperlink target for the index. Therefore, users can
r... | Index |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 13417,
"end": 13999
} | class ____(graphene.Mutation):
"""Resumes a set of partition backfill runs. Resuming a backfill will not retry any failed runs."""
Output = graphene.NonNull(GrapheneResumeBackfillResult)
class Arguments:
backfillId = graphene.NonNull(graphene.String)
class Meta:
name = "ResumeBackfill... | GrapheneResumeBackfillMutation |
python | kamyu104__LeetCode-Solutions | Python/maximum-sum-of-distinct-subarrays-with-length-k.py | {
"start": 44,
"end": 636
} | class ____(object):
def maximumSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result = left = total = 0
lookup = set()
for right in xrange(len(nums)):
while nums[right] in lookup or len(lookup) == k:
... | Solution |
python | plotly__plotly.py | plotly/graph_objs/isosurface/_legendgrouptitle.py | {
"start": 233,
"end": 2960
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface"
_path_str = "isosurface.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be s... | Legendgrouptitle |
python | pytorch__pytorch | test/onnx/exporter/test_api.py | {
"start": 330,
"end": 455
} | class ____(torch.nn.Module):
def forward(self, x):
y = x + 1
z = y.relu()
return (y, z)
| SampleModel |
python | cython__cython | tests/run/pep3135_class_cell.py | {
"start": 3453,
"end": 3518
} | class ____:
def method(self): return __class__
@cython.cclass
| K |
python | run-llama__llama_index | llama-index-core/llama_index/core/node_parser/text/semantic_splitter.py | {
"start": 1135,
"end": 11005
} | class ____(NodeParser):
"""
Semantic node parser.
Splits a document into Nodes, with each node being a group of semantically related sentences.
Args:
buffer_size (int): number of sentences to group together when evaluating semantic similarity
embed_model: (BaseEmbedding): embedding mod... | SemanticSplitterNodeParser |
python | ethereum__web3.py | web3/geth.py | {
"start": 3325,
"end": 3432
} | class ____(Module):
admin: GethAdmin
txpool: GethTxPool
debug: GethDebug
# --- async --- #
| Geth |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/data/query.py | {
"start": 2851,
"end": 3357
} | class ____:
"""
Represents a wrapper around the results of a list of MQLQuery(s) which exposes useful methods to run on the query
results.
"""
results: list[QueryResult]
def apply_transformer(
self, transformer: QueryResultsTransformer[QueryTransformerResult]
) -> QueryTransformerR... | MQLQueriesResult |
python | encode__httpx | httpx/_auth.py | {
"start": 3191,
"end": 3600
} | class ____(Auth):
"""
Allows the 'auth' argument to be passed as a simple callable function,
that takes the request, and returns a new, modified request.
"""
def __init__(self, func: typing.Callable[[Request], Request]) -> None:
self._func = func
def auth_flow(self, request: Request) -... | FunctionAuth |
python | anthropics__anthropic-sdk-python | src/anthropic/types/redacted_thinking_block_param.py | {
"start": 226,
"end": 358
} | class ____(TypedDict, total=False):
data: Required[str]
type: Required[Literal["redacted_thinking"]]
| RedactedThinkingBlockParam |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/mutable.py | {
"start": 33920,
"end": 37048
} | class ____(Mutable, Set[_T]):
"""A set type that implements :class:`.Mutable`.
The :class:`.MutableSet` object implements a set that will
emit change events to the underlying mapping when the contents of
the set are altered, including when values are added or removed.
Note that :class:`.MutableSet... | MutableSet |
python | kamyu104__LeetCode-Solutions | Python/k-th-largest-perfect-subtree-size-in-binary-tree.py | {
"start": 2408,
"end": 4103
} | class ____(object):
def kthLargestPerfectSubtree(self, root, k):
"""
:type root: Optional[TreeNode]
:type k: int
:rtype: int
"""
def nth_element(nums, left, n, right, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target):
... | Solution2 |
python | pytorch__pytorch | test/quantization/core/test_quantized_module.py | {
"start": 1558,
"end": 59023
} | class ____(QuantizationTestCase):
def test_relu(self):
relu_module = nn.ReLU()
relu6_module = nnq.ReLU6()
x = torch.arange(-10, 10, dtype=torch.float)
y_ref = torch.relu(x)
y6_ref = torch.nn.modules.ReLU6()(x)
qx = torch.quantize_per_tensor(x, 1.0, 0, dtype=torch.qi... | TestStaticQuantizedModule |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/teams.py | {
"start": 999,
"end": 1146
} | class ____(BaseModel):
"""Team collection serializer for responses."""
teams: list[TeamResponse]
total_entries: int
| TeamCollectionResponse |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/inprocess.py | {
"start": 1733,
"end": 1892
} | class ____(SuperQObject, InProcessHBChannel):
# This signal will never be fired, but it needs to exist
kernel_died = QtCore.Signal()
| QtInProcessHBChannel |
python | huggingface__transformers | src/transformers/models/helium/modeling_helium.py | {
"start": 13002,
"end": 14807
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = HeliumAttention(config=config, layer_idx=layer_idx)
self.mlp = HeliumMLP(config)
self... | HeliumDecoderLayer |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 97971,
"end": 100235
} | class ____(Request):
"""
Get all metric/variant pairs reported for tasks in a specific project.
If no project is specified, metrics/variant paris reported for all tasks will be returned.
If the project does not exist, an empty list will be returned.
:param project: Project ID
:t... | GetUniqueMetricVariantsRequest |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_class_parameters_reference.py | {
"start": 383,
"end": 8009
} | 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... | V1IngressClassParametersReference |
python | pytorch__pytorch | torch/autograd/_functions/tensor.py | {
"start": 194,
"end": 987
} | class ____(Function):
@staticmethod
@deprecated(
"`torch.autograd._functions.Type` is deprecated as of PyTorch 2.1, "
"please use `torch.tensor.to(dtype=dtype)` instead.",
category=FutureWarning,
)
# pyrefly: ignore [bad-override]
def forward(ctx, i, dest_type):
ctx.i... | Type |
python | joke2k__faker | faker/providers/company/th_TH/__init__.py | {
"start": 82,
"end": 3171
} | class ____(CompanyProvider):
formats = OrderedDict(
(
("{{company_limited_prefix}}{{last_name}} {{company_limited_suffix}}", 0.2),
(
"{{company_limited_prefix}}{{last_name}}{{company_suffix}} {{company_limited_suffix}}",
0.2,
),
... | Provider |
python | astropy__astropy | astropy/coordinates/tests/test_representation_methods.py | {
"start": 428,
"end": 1773
} | class ____:
"""Manipulation of Representation shapes.
Checking that attributes are manipulated correctly.
Even more exhaustive tests are done in time.tests.test_methods
"""
def setup_class(cls):
# We set up some representations with, on purpose, copy=False,
# so we can check that ... | ShapeSetup |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 55421,
"end": 56878
} | class ____(unittest.TestCase):
def test_context_manager_retry_one(self):
from tenacity import Retrying
raise_ = True
for attempt in Retrying():
with attempt:
if raise_:
raise_ = False
raise Exception("Retry it!")
def ... | TestContextManager |
python | readthedocs__readthedocs.org | readthedocs/api/v2/views/integrations.py | {
"start": 26355,
"end": 29916
} | class ____(WebhookMixin, APIView):
"""
Webhook consumer for Bitbucket.
Accepts webhook events from Bitbucket, 'repo:push' events trigger builds.
Expects the following JSON::
{
"push": {
"changes": [{
"new": {
"name": "bra... | BitbucketWebhookView |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/cli_utils.py | {
"start": 660,
"end": 1005
} | class ____(argparse.Action):
"""
Internal custom Action to help detect arguments that aren't default.
"""
non_default_args: Set[str] = set()
def __call__(self, arg_parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
DetectDefault.non_default_args.a... | DetectDefault |
python | PyCQA__isort | isort/exceptions.py | {
"start": 4241,
"end": 4716
} | class ____(ISortError):
"""Raised when an isort literal sorting comment is used, with a type that doesn't match the
supplied data structure's type.
"""
def __init__(self, kind: type, expected_kind: type):
super().__init__(
f"isort was told to sort a literal of type {expected_kind} b... | LiteralSortTypeMismatch |
python | django__django | tests/forms_tests/tests/test_input_formats.py | {
"start": 21316,
"end": 25245
} | class ____(SimpleTestCase):
def test_dateField(self):
"DateFields can parse dates in the default format"
f = forms.DateField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
f.clean("21.12.2010")
# Parse a date in a ... | SimpleDateFormatTests |
python | buildout__buildout | src/zc/buildout/easy_install.py | {
"start": 4545,
"end": 8276
} | class ____(EnvironmentMixin, pkg_resources.Environment):
"""Buildout version of Environment with canonicalized names.
* pkg_resources defines the Environment class
* setuptools defines a PackageIndex class that inherits from Environment
* Buildout needs a few fixes that should be used by both.
The... | Environment |
python | jina-ai__jina | jina/proto/serializer.py | {
"start": 2171,
"end": 2853
} | class ____:
"""Since the serializer is replacing the `jina_pb2 to know how to exactly serialize messages, this is just a placeholder that
delegates the serializing and deserializing to the internal protobuf structure with no extra optimization.
"""
@staticmethod
def SerializeToString(x):
""... | EndpointsProto |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 83503,
"end": 83842
} | class ____:
key: ClassVar[str] = "opt_ctx"
dtype: Optional[torch.dtype] = None
ops_name: str = ""
@functools.cache
def jinja2_env() -> Any:
try:
import jinja2
return jinja2.Environment(
undefined=jinja2.StrictUndefined,
)
except ImportError:
return Non... | OptimizationContext |
python | redis__redis-py | redis/multidb/database.py | {
"start": 2413,
"end": 3569
} | class ____(BaseDatabase, SyncDatabase):
def __init__(
self,
client: Union[redis.Redis, RedisCluster],
circuit: CircuitBreaker,
weight: float,
health_check_url: Optional[str] = None,
):
"""
Initialize a new Database instance.
Args:
clie... | Database |
python | django-import-export__django-import-export | tests/core/tests/admin_integration/test_import_functionality.py | {
"start": 24948,
"end": 25862
} | class ____(AdminTestMixin, TestCase):
"""
Display correct import order when 'import_order' is declared (issue 1845).
Ensure that the prompt text on the import page renders the
fields in the correct order.
"""
def setUp(self):
super().setUp()
EBookResource._meta.import_order = ("... | DeclaredImportOrderTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.