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 | readthedocs__readthedocs.org | readthedocs/projects/tasks/builds.py | {
"start": 3384,
"end": 4895
} | class ____:
"""
Object to store all data related to a Celery task execution.
We use this object from inside the task to store data while we are running
the task. This is to avoid using `self.` inside the task due to its
limitations: it's instantiated once and that instance is re-used for all
th... | TaskData |
python | huggingface__transformers | src/transformers/generation/continuous_batching/cache_manager.py | {
"start": 1814,
"end": 9954
} | class ____:
"""A class to manage the number of free blocks and block re-use. If prefix sharing is off, the block manager is a
simple FIFO structure where blocks are either free or in use. If prefix sharing is on, blocks can have 3 states:
- in use: one or more requests references this block, thus it canno... | BlockManager |
python | ray-project__ray | python/ray/serve/tests/test_replica_request_context.py | {
"start": 348,
"end": 2480
} | class ____:
def test_basic_route_prefix(self):
@serve.deployment
class A:
def __call__(self) -> str:
return _get_request_context_route()
# No route prefix, should return "/" regardless of full route.
serve.run(A.bind())
r = httpx.get(f"{get_applic... | TestHTTPRoute |
python | django__django | tests/admin_views/models.py | {
"start": 4713,
"end": 4983
} | class ____(models.Model):
expected = models.BooleanField(default=False)
leader = models.ForeignKey(Actor, models.CASCADE)
country = models.CharField(max_length=20)
def __str__(self):
return "by %s from %s" % (self.leader, self.country)
| Inquisition |
python | pytorch__pytorch | torch/_dynamo/variables/ctx_manager.py | {
"start": 41271,
"end": 43838
} | class ____(ContextWrappingVariable):
_guards_singleton = Guard(GlobalStateSource(), GuardBuilder.FSDP_TRAINING_STATE) # type: ignore[arg-type]
@staticmethod
def create(
tx: "InstructionTranslator",
param_group_var: Any,
target_value: Any,
**kwargs: Any,
) -> "FSDPParamG... | FSDPParamGroupUseTrainingStateVariable |
python | networkx__networkx | networkx/algorithms/bipartite/tests/test_matching.py | {
"start": 7698,
"end": 11973
} | class ____:
@classmethod
def setup_class(cls):
pytest.importorskip("scipy")
def test_minimum_weight_full_matching_incomplete_graph(self):
B = nx.Graph()
B.add_nodes_from([1, 2], bipartite=0)
B.add_nodes_from([3, 4], bipartite=1)
B.add_edge(1, 4, weight=100)
B... | TestMinimumWeightFullMatching |
python | ray-project__ray | python/ray/serve/batching.py | {
"start": 19610,
"end": 19759
} | class ____(Protocol, Generic[SelfType, T, R]):
def __call__(self, self_: SelfType, __batch: List[T], /) -> List[R]:
...
| _SyncBatchingMethod |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_quote_name04.py | {
"start": 315,
"end": 1261
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("quote_name04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | getsentry__sentry | tests/sentry/tasks/test_post_process.py | {
"start": 26294,
"end": 30533
} | class ____(BasePostProgressGroupMixin):
@patch("sentry.sentry_apps.tasks.sentry_apps.process_resource_change_bound.delay")
def test_processes_resource_change_task_on_new_group(self, delay: MagicMock) -> None:
event = self.create_event(data={}, project_id=self.project.id)
group = event.group
... | ResourceChangeBoundsTestMixin |
python | gevent__gevent | src/gevent/_imap.py | {
"start": 892,
"end": 6186
} | class ____(Greenlet): # pylint:disable=undefined-variable
"""
At iterator of map results.
"""
def __init__(self, func, iterable, spawn, maxsize=None, _zipped=False):
"""
An iterator that.
:param callable spawn: The function we use to create new greenlets.
:keyword int m... | IMapUnordered |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 8372,
"end": 8971
} | class ____(_VectorizerConfigCreate):
vectorizer: Union[Vectorizers, _EnumLikeStr] = Field(
default=Vectorizers.TEXT2VEC_OPENAI, frozen=True, exclude=True
)
baseURL: Optional[AnyHttpUrl]
resourceName: str
deploymentId: str
vectorizeClassName: bool
dimensions: Optional[int]
model: ... | _Text2VecAzureOpenAIConfig |
python | langchain-ai__langchain | libs/core/langchain_core/output_parsers/openai_tools.py | {
"start": 6915,
"end": 9969
} | class ____(JsonOutputToolsParser):
"""Parse tools from OpenAI response."""
key_name: str
"""The type of tools to return."""
def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
"""Parse the result of an LLM call to a list of tool calls.
Args:
... | JsonOutputKeyToolsParser |
python | PrefectHQ__prefect | src/prefect/artifacts.py | {
"start": 10280,
"end": 11057
} | class ____(Artifact):
progress: float
type: Optional[str] = "progress"
def _format(self) -> float:
# Ensure progress is between 0 and 100
min_progress = 0.0
max_progress = 100.0
if self.progress < min_progress or self.progress > max_progress:
logger.warning(
... | ProgressArtifact |
python | sqlalchemy__sqlalchemy | examples/association/dict_of_sets_with_default.py | {
"start": 1879,
"end": 2388
} | class ____(Base):
__tablename__ = "b"
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
elements: Mapped[set[C]] = relationship("C", collection_class=set)
key: Mapped[str]
values: AssociationProxy[set[int]] = association_proxy("elements", "value")
"""Bridge the association from 'elements' o... | B |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_pgf.py | {
"start": 34774,
"end": 34840
} | class ____(_Backend):
FigureCanvas = FigureCanvasPgf
| _BackendPgf |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_request_mcp_server_tool_configuration_param.py | {
"start": 289,
"end": 441
} | class ____(TypedDict, total=False):
allowed_tools: Optional[SequenceNotStr[str]]
enabled: Optional[bool]
| BetaRequestMCPServerToolConfigurationParam |
python | pandas-dev__pandas | asv_bench/benchmarks/period.py | {
"start": 1219,
"end": 1652
} | class ____:
def setup(self):
self.rng = period_range(start="1/1/1990", freq="s", periods=20000)
self.df = DataFrame(index=range(len(self.rng)))
def time_setitem_period_column(self):
self.df["col"] = self.rng
def time_set_index(self):
# GH#21582 limited by comparisons of Per... | DataFramePeriodColumn |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/rds.py | {
"start": 1814,
"end": 2479
} | class ____(AwsBaseOperator[RdsHook]):
"""Base operator that implements common functions for all operators."""
aws_hook_class = RdsHook
ui_color = "#eeaa88"
ui_fgcolor = "#ffffff"
def __init__(
self,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
... | RdsBaseOperator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py | {
"start": 13160,
"end": 13465
} | class ____(AggregateDataMixin, IncrementalAppsflyerStream):
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None
) -> str:
return f"agg-data/export/app/{self.app_id}/geo_by_date_report/v5"
| GeoReport |
python | cython__cython | tests/run/test_tstring.py | {
"start": 1309,
"end": 4037
} | class ____:
def assertInterpolationEqual(self, i, exp):
"""Test Interpolation equality.
The *i* argument must be an Interpolation instance.
The *exp* argument must be a tuple of the form
(value, expression, conversion, format_spec) where the final three
items may be omitted... | TStringBaseCase |
python | kamyu104__LeetCode-Solutions | Python/find-pattern-in-infinite-stream-i.py | {
"start": 33,
"end": 96
} | class ____:
def next(self):
pass
# kmp
| InfiniteStream |
python | rapidsai__cudf | python/cudf/cudf/core/buffer/spillable_buffer.py | {
"start": 1665,
"end": 2399
} | class ____:
# A wrapper that exposes the __cuda_array_interface__ of a SpillableBuffer without
# actually accessing __cuda_array_interface__, which triggers spilling.
_buf: SpillableBuffer
def __init__(self, buf: SpillableBuffer) -> None:
self._buf = buf
self._spill_lock = SpillLock()
... | SpillableBufferCAIWrapper |
python | pallets__werkzeug | src/werkzeug/datastructures/mixins.py | {
"start": 475,
"end": 1932
} | class ____:
"""Makes a :class:`list` immutable.
.. versionadded:: 0.5
:private:
"""
_hash_cache: int | None = None
def __hash__(self) -> int:
if self._hash_cache is not None:
return self._hash_cache
rv = self._hash_cache = hash(tuple(self)) # type: ignore[arg-typ... | ImmutableListMixin |
python | tqdm__tqdm | tqdm/contrib/discord.py | {
"start": 638,
"end": 3077
} | class ____(MonoWorker):
"""Non-blocking file-like IO using a Discord Bot."""
API = "https://discord.com/api/v10"
UA = f"tqdm (https://tqdm.github.io, {__version__}) {default_user_agent()}"
def __init__(self, token, channel_id):
"""Creates a new message in the given `channel_id`."""
supe... | DiscordIO |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1461031,
"end": 1469700
} | class ____(TopLevelSpec):
"""
TopLevelHConcatSpec schema wrapper.
Parameters
----------
hconcat : Sequence[dict, :class:`FacetSpec`, :class:`LayerSpec`, :class:`RepeatSpec`, :class:`FacetedUnitSpec`, :class:`LayerRepeatSpec`, :class:`NonNormalizedSpec`, :class:`NonLayerRepeatSpec`, :class:`ConcatSp... | TopLevelHConcatSpec |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 50335,
"end": 51153
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self, name: str, tickers: str, interval: Optional[str] = None, range: Optional[str] = None
):
"""Airbyte Source for Yahoo Finance Price.
Args:
name (str): The name of the destination.
tickers (str): Co... | YahooFinancePriceSource |
python | bokeh__bokeh | src/bokeh/models/formatters.py | {
"start": 3296,
"end": 4237
} | class ____(TickFormatter):
''' Display tick values from continuous ranges as "basic numbers",
using scientific notation when appropriate by default.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
... | BasicTickFormatter |
python | django__django | django/contrib/auth/backends.py | {
"start": 218,
"end": 1700
} | class ____:
def authenticate(self, request, **kwargs):
return None
async def aauthenticate(self, request, **kwargs):
return await sync_to_async(self.authenticate)(request, **kwargs)
def get_user(self, user_id):
return None
async def aget_user(self, user_id):
return awa... | BaseBackend |
python | paramiko__paramiko | tests/test_client.py | {
"start": 1716,
"end": 3774
} | class ____(paramiko.ServerInterface):
def __init__(self, *args, **kwargs):
# Allow tests to enable/disable specific key types
self.__allowed_keys = kwargs.pop("allowed_keys", [])
# And allow them to set a (single...meh) expected public blob (cert)
self.__expected_public_blob = kwargs... | NullServer |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 20135,
"end": 20516
} | class ____(Element):
proto: MetricProto
label: str
delta: str
color: str
help: str
def __init__(self, proto: MetricProto, root: ElementTree) -> None:
self.proto = proto
self.key = None
self.root = root
self.type = "metric"
@property
def value(self) -> st... | Metric |
python | pytorch__pytorch | test/quantization/core/test_utils.py | {
"start": 366,
"end": 8542
} | class ____(TestCase):
def _test_get_fqn_to_example_inputs(self, M, example_inputs, expected_fqn_to_dim):
m = M().eval()
fqn_to_example_inputs = get_fqn_to_example_inputs(m, example_inputs)
for fqn, expected_dims in expected_fqn_to_dim.items():
assert fqn in expected_fqn_to_dim
... | TestUtils |
python | pexpect__pexpect | tests/test_repr.py | {
"start": 78,
"end": 999
} | class ____(PexpectTestCase.PexpectTestCase):
def test_str_spawnu(self):
""" Exercise spawnu.__str__() """
# given,
p = pexpect.spawnu('cat')
# exercise,
value = str(p)
# verify
assert isinstance(value, str)
def test_str_spawn(self):
""" Exercise ... | TestCaseMisc |
python | numpy__numpy | benchmarks/benchmarks/bench_polynomial.py | {
"start": 52,
"end": 803
} | class ____(Benchmark):
def setup(self):
self.polynomial_degree2 = np.polynomial.Polynomial(np.array([1, 2]))
self.array3 = np.linspace(0, 1, 3)
self.array1000 = np.linspace(0, 1, 10_000)
self.float64 = np.float64(1.0)
def time_polynomial_evaluation_scalar(self):
self.po... | Polynomial |
python | huggingface__transformers | src/transformers/models/poolformer/modeling_poolformer.py | {
"start": 3777,
"end": 4579
} | class ____(nn.Module):
def __init__(self, config, dropout_prob, hidden_size, intermediate_size):
super().__init__()
self.conv1 = nn.Conv2d(hidden_size, intermediate_size, 1)
self.conv2 = nn.Conv2d(intermediate_size, hidden_size, 1)
self.drop = PoolFormerDropPath(dropout_prob)
... | PoolFormerOutput |
python | GoogleCloudPlatform__python-docs-samples | compute/client_library/snippets/instances/custom_machine_types/create_shared_with_helper.py | {
"start": 1200,
"end": 20072
} | class ____:
"""
Allows to create custom machine types to be used with the VM instances.
"""
@unique
class CPUSeries(Enum):
N1 = "custom"
N2 = "n2-custom"
N2D = "n2d-custom"
E2 = "e2-custom"
E2_MICRO = "e2-custom-micro"
E2_SMALL = "e2-custom-small"
... | CustomMachineType |
python | django__django | tests/forms_tests/tests/test_validators.py | {
"start": 2364,
"end": 6829
} | class ____(TestCase):
def test_value_placeholder_with_char_field(self):
cases = [
(validators.validate_integer, "-42.5", "invalid"),
(validators.validate_email, "a", "invalid"),
(validators.validate_email, "a@b\n.com", "invalid"),
(validators.validate_email, "... | ValidatorCustomMessageTests |
python | ipython__ipython | IPython/core/historyapp.py | {
"start": 901,
"end": 4518
} | class ____(BaseIPythonApplication):
description = trim_hist_help
backup = Bool(False, help="Keep the old history file as history.sqlite.<N>").tag(
config=True
)
keep = Int(1000, help="Number of recent lines to keep in the database.").tag(
config=True
)
flags = Dict( # type: i... | HistoryTrim |
python | has2k1__plotnine | plotnine/stats/stat_sina.py | {
"start": 466,
"end": 9571
} | class ____(stat):
"""
Compute Sina plot values
{usage}
Parameters
----------
{common_parameters}
binwidth : float, default=None
The width of the bins. The default is to use bins that
cover the range of the data. You should always override this
value, exploring multi... | stat_sina |
python | Textualize__textual | docs/examples/themes/todo_app.py | {
"start": 234,
"end": 2176
} | class ____(App[None]):
CSS = """
Screen {
align: center middle;
hatch: right $foreground 10%;
}
#content {
height: auto;
width: 40;
padding: 1 2;
}
#header {
height: 1;
width: auto;
margin-bottom: 1;
}
.title {
text-style: bold;
padding: 0 1;
width: 1fr;
}
#overdue {
... | TodoList |
python | simonw__datasette | datasette/utils/baseconv.py | {
"start": 290,
"end": 1553
} | class ____(object):
decimal_digits = "0123456789"
def __init__(self, digits):
self.digits = digits
def encode(self, i):
return self.convert(i, self.decimal_digits, self.digits)
def decode(self, s):
return int(self.convert(s, self.digits, self.decimal_digits))
def convert(... | BaseConverter |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE794.py | {
"start": 764,
"end": 862
} | class ____:
name: str = "Foo"
name: str = name + " Bar"
name: str = "Bar" # PIE794
| Person |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 37614,
"end": 38386
} | class ____(BaseModel):
"""Deployment-level autoscaler observability."""
scaling_status: AutoscalingStatus = Field(
..., description="Current scaling direction or stability."
)
decisions: List[ScalingDecision] = Field(
default_factory=list, description="Recent scaling decisions."
)
... | DeploymentAutoscalingDetail |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 90646,
"end": 93922
} | class ____(Request):
"""
Update queue information
:param queue: Queue id
:type queue: str
:param name: Queue name Unique within the company.
:type name: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: System tags list. This field is reserved for... | UpdateRequest |
python | sympy__sympy | sympy/physics/quantum/cartesian.py | {
"start": 2237,
"end": 2785
} | class ____(HermitianOperator):
""" Z cartesian coordinate operator (for 3D systems) """
@classmethod
def default_args(self):
return ("Z",)
@classmethod
def _eval_hilbert_space(self, args):
return L2(Interval(S.NegativeInfinity, S.Infinity))
def _apply_operator_PositionKet3D(se... | ZOp |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_index_returned.py | {
"start": 986,
"end": 1159
} | class ____:
""" __index__ returns node which does not have 'value' in AST """
def __index__(self): # [invalid-index-returned]
return lambda: 3
| FourthBadIndex |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 3418,
"end": 3939
} | class ____:
"""
Table 3.30 Entries in a resource dictionary.
Table 34 in the 2.0 reference.
"""
EXT_G_STATE = "/ExtGState" # dictionary, optional
COLOR_SPACE = "/ColorSpace" # dictionary, optional
PATTERN = "/Pattern" # dictionary, optional
SHADING = "/Shading" # dictionary, optiona... | Resources |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/convolutional.py | {
"start": 988,
"end": 9906
} | class ____(keras_layers.Conv1D, base.Layer):
"""1D convolution layer (e.g. temporal convolution).
This layer creates a convolution kernel that is convolved
(actually cross-correlated) with the layer input to produce a tensor of
outputs. If `use_bias` is True (and a `bias_initializer` is provided),
a bias vec... | Conv1D |
python | PrefectHQ__prefect | src/prefect/server/schemas/responses.py | {
"start": 19645,
"end": 20845
} | class ____(schemas.core.Worker):
status: schemas.statuses.WorkerStatus = Field(
schemas.statuses.WorkerStatus.OFFLINE,
description="Current status of the worker.",
)
@classmethod
def model_validate(
cls: Type[Self],
obj: Any,
*,
strict: Optional[bool] = N... | WorkerResponse |
python | django__django | django/db/migrations/exceptions.py | {
"start": 252,
"end": 370
} | class ____(Exception):
"""There's an impossible-to-resolve circular dependency."""
pass
| CircularDependencyError |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external.py | {
"start": 25268,
"end": 25477
} | class ____:
job_selector: JobSubsetSelector
run_config: Optional[Mapping[str, Any]]
@cached_method
def __hash__(self) -> int:
return hash(make_hashable(self))
| RemoteExecutionPlanSelector |
python | Netflix__metaflow | test/test_config/helloconfig.py | {
"start": 818,
"end": 1085
} | class ____(FlowMutator):
def mutate(self, mutable_flow):
s = mutable_flow.start
s.add_decorator(environment, vars={"hello": mutable_flow.config.env_to_start})
@TitusOrNot
@AddEnvToStart
@project(name=config_expr("config").project_name)
| AddEnvToStart |
python | getsentry__sentry | tests/sentry/web/frontend/test_auth_organization_login.py | {
"start": 1281,
"end": 44561
} | class ____(AuthProviderTestCase):
@cached_property
def organization(self) -> Organization:
return self.create_organization(name="foo", owner=self.user)
@cached_property
def path(self) -> str:
return reverse("sentry-auth-organization", args=[self.organization.slug])
def test_renders... | OrganizationAuthLoginTest |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/__init__.py | {
"start": 8821,
"end": 9015
} | class ____(PythonTargetParser):
"""Composite argument parser for a sanity Python target."""
def __init__(self) -> None:
super().__init__(allow_venv=False)
| SanityPythonTargetParser |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 11993,
"end": 12133
} | class ____(Stmt):
"""Node for filter sections."""
fields = ("body", "filter")
body: t.List[Node]
filter: "Filter"
| FilterBlock |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 987464,
"end": 987629
} | class ____(sgqlc.types.Type, GitSignature):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ()
| SmimeSignature |
python | kamyu104__LeetCode-Solutions | Python/reaching-points.py | {
"start": 42,
"end": 503
} | class ____(object):
def reachingPoints(self, sx, sy, tx, ty):
"""
:type sx: int
:type sy: int
:type tx: int
:type ty: int
:rtype: bool
"""
while tx >= sx and ty >= sy:
if tx < ty:
sx, sy = sy, sx
tx, ty = ty,... | Solution |
python | realpython__materials | python-maze-solver/source_code_final/src/maze_solver/view/primitives.py | {
"start": 232,
"end": 451
} | class ____(NamedTuple):
x: int
y: int
def draw(self, **attributes) -> str:
return f"{self.x},{self.y}"
def translate(self, x=0, y=0) -> "Point":
return Point(self.x + x, self.y + y)
| Point |
python | Textualize__textual | tests/css/test_nested_css.py | {
"start": 1267,
"end": 2008
} | class ____(App[None]):
CSS = """
Label {
&.foo, &.bar {
background: red;
}
}
"""
def compose(self) -> ComposeResult:
yield Label("one", classes="foo")
yield Label("two", classes="bar")
yield Label("three", classes="heh")
async def test_lists_of_... | ListOfNestedSelectorsApp |
python | pytorch__pytorch | torch/_inductor/template_heuristics/decompose_k.py | {
"start": 608,
"end": 1265
} | class ____(TemplateConfigHeuristics):
"""empty heuristics to skip decompose k on anything not cuda"""
# on CUDA, we don't support hip for decompose_k yet
@register_template_heuristic(
decompose_k_subgraph_template.uid,
"cuda",
register=torch.version.hip is None,
op_name="mm",
)
# TODO(coconutruben... | EmptyDecomposeKConfigHeuristics |
python | mlflow__mlflow | mlflow/gateway/base_models.py | {
"start": 57,
"end": 340
} | class ____(
BaseModel,
# Allow extra fields for pydantic request models, e.g. to support
# vendor-specific embeddings parameters
extra="allow",
):
"""
A pydantic model representing Gateway request data, such as a chat or completions request
"""
| RequestModel |
python | plotly__plotly.py | plotly/graph_objs/isosurface/colorbar/_title.py | {
"start": 233,
"end": 3992
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface.colorbar"
_path_str = "isosurface.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of Font
t... | Title |
python | fluentpython__example-code-2e | 24-class-metaprog/hours/hours.py | {
"start": 1278,
"end": 2559
} | class ____:
h: int
_m: int
_s: float
def __class_getitem__(cls, parts: Union[slice, float]) -> 'Hours':
if isinstance(parts, slice):
h = parts.start or 0
m = valid_base_60(parts.stop or 0, 'minutes')
s = valid_base_60(parts.step or 0, 'seconds')
else:... | Hours |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/unnecessaryIsInstance1.py | {
"start": 182,
"end": 873
} | class ____(CustomClass1):
pass
def func1(p1: int, p2: int | str):
a = isinstance(p2, str)
b = isinstance(p2, (int, float))
# This should generate an error because this is always true.
c = isinstance(p2, (float, dict, int, str))
d = isinstance(p1, float)
e = isinstance(p2, (float, dict,... | CustomClass2 |
python | pytorch__pytorch | test/mobile/model_test/nn_ops.py | {
"start": 9096,
"end": 9565
} | class ____(torch.nn.Module):
def forward(self):
input = torch.tensor([[1, 2, 4, 5], [4, 3, 2, 9]])
input2 = torch.tensor([1, 2, 4, 5, 4, 3, 2, 9])
embedding_matrix = torch.rand(10, 3)
offsets = torch.tensor([0, 4])
return len(
F.embedding(input, embedding_matrix),... | NNSparseModule |
python | lxml__lxml | src/lxml/html/__init__.py | {
"start": 40005,
"end": 40747
} | class ____(MutableMapping):
def __init__(self, inputs):
self.inputs = inputs
def __getitem__(self, item):
return self.inputs[item].value
def __setitem__(self, item, value):
self.inputs[item].value = value
def __delitem__(self, item):
raise KeyError(
"You cann... | FieldsDict |
python | kennethreitz__tablib | src/tablib/formats/__init__.py | {
"start": 1962,
"end": 2288
} | class ____(FormatDescriptorBase):
def __get__(self, obj, cls, **kwargs):
self.ensure_format_loaded()
return self._format.export_set(obj, **kwargs)
def __set__(self, obj, val):
self.ensure_format_loaded()
return self._format.import_set(obj, normalize_input(val))
| ImportExportSetDescriptor |
python | ray-project__ray | python/ray/util/multiprocessing/pool.py | {
"start": 5169,
"end": 5276
} | class ____(Exception):
def __init__(self, underlying):
self.underlying = underlying
| PoolTaskError |
python | huggingface__transformers | src/transformers/models/olmo3/convert_olmo3_weights_to_hf.py | {
"start": 3492,
"end": 18401
} | class ____(dist_cp.StorageReader):
"""
A :class:`~torch.distributed.checkpoint.StorageReader` based on :class:`~torch.distributed.checkpoint.FileSystemReader`
that can read data directly from cloud storage as well as a local directory.
"""
def __init__(
self,
path: Path | str,
... | RemoteFileSystemReader |
python | huggingface__transformers | tests/models/siglip2/test_modeling_siglip2.py | {
"start": 23979,
"end": 25078
} | class ____(Siglip2ModelTester):
def __init__(self, parent):
super().__init__(parent)
self.batch_size = self.vision_model_tester.batch_size
self.num_hidden_layers = self.vision_model_tester.num_hidden_layers
self.hidden_size = self.vision_model_tester.hidden_size
self.seq_leng... | Siglip2ForImageClassificationModelTester |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/utils/dataproc.py | {
"start": 845,
"end": 960
} | class ____(Enum):
"""Contains types of long running operations."""
DIAGNOSE = "DIAGNOSE"
| DataprocOperationType |
python | pypa__warehouse | tests/unit/admin/views/test_users.py | {
"start": 48168,
"end": 57353
} | class ____:
def test_user_recover_account_complete(self, db_request, monkeypatch):
user = UserFactory.create(
totp_secret=b"aaaaabbbbbcccccddddd",
webauthn=[
WebAuthn(
label="fake", credential_id="fake", public_key="extremely fake"
... | TestUserRecoverAccountComplete |
python | django__django | tests/admin_views/test_nav_sidebar.py | {
"start": 814,
"end": 4268
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super",
password="secret",
email="super@example.com",
)
def setUp(self):
self.client.force_login(self.superuser)
def test_side... | AdminSidebarTests |
python | fastapi__sqlmodel | docs_src/tutorial/code_structure/tutorial001/models.py | {
"start": 88,
"end": 306
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
headquarters: str
heroes: List["Hero"] = Relationship(back_populates="team")
| Team |
python | pandas-dev__pandas | pandas/tests/tslibs/test_array_to_datetime.py | {
"start": 10294,
"end": 10750
} | class ____(datetime):
pass
@pytest.mark.parametrize("klass", [SubDatetime, datetime, Timestamp])
def test_datetime_subclass(klass):
# GH 25851
# ensure that subclassed datetime works with
# array_to_datetime
arr = np.array([klass(2000, 1, 1)], dtype=object)
result, _ = tslib.array_to_datetime... | SubDatetime |
python | numba__numba | numba/tests/test_compiler_flags.py | {
"start": 308,
"end": 602
} | class ____(TestCase):
def test_setting_invalid_attribute(self):
flags = Flags()
msg = "'Flags' object has no attribute 'this_really_does_not_exist'"
with self.assertRaisesRegex(AttributeError, msg):
flags.this_really_does_not_exist = True
| TestCompilerFlags |
python | streamlit__streamlit | lib/tests/streamlit/elements/metric_test.py | {
"start": 1159,
"end": 20076
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall metric protos and invalid input."""
def test_no_value(self):
st.metric("label_test", None)
c = self.get_delta_from_queue().new_element.metric
assert c.label == "label_test"
# This is an em dash. Not a regular "-"
... | MetricTest |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 157312,
"end": 165831
} | class ____(GeneratedAirbyteSource):
class Disable:
@public
def __init__(
self,
):
self.mode = "disable"
class Allow:
@public
def __init__(
self,
):
self.mode = "allow"
class Prefer:
@public
def ... | PostgresSource |
python | ipython__ipython | IPython/core/magic.py | {
"start": 1996,
"end": 10898
} | class ____:
pass
def on_off(tag):
"""Return an ON/OFF string for a 1/0 input. Simple utility function."""
return ["OFF", "ON"][tag]
def compress_dhist(dh):
"""Compress a directory history into a new one with at most 20 entries.
Return a new list made from the first and last 10 elements of dhist... | Bunch |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 9242,
"end": 9487
} | class ____(Message):
message = "'...' %% ... has unsupported format character %r"
def __init__(self, filename, loc, c):
Message.__init__(self, filename, loc)
self.message_args = (c,)
| PercentFormatUnsupportedFormatCharacter |
python | realpython__materials | python-unittest/test_age.py | {
"start": 53,
"end": 1605
} | class ____(unittest.TestCase):
def test_child(self):
"""Test for 'Child'"""
self.assertEqual(categorize_by_age(5), "Child")
def test_adolescent(self):
"""Test for 'Adolescent'"""
self.assertEqual(categorize_by_age(15), "Adolescent")
def test_adult(self):
"""Test for... | TestCategorizeByAge |
python | google__python-fire | fire/console/console_attr.py | {
"start": 3238,
"end": 3623
} | class ____(BoxLineCharacters):
"""unicode Box/line drawing characters (cp437 compatible unicode)."""
dl = 'β'
dr = 'β'
h = 'β'
hd = 'β¬'
hu = 'β΄'
ul = 'β'
ur = 'β'
v = 'β'
vh = 'βΌ'
vl = 'β€'
vr = 'β'
d_dl = 'β'
d_dr = 'β'
d_h = 'β'
d_hd = 'β¦'
d_hu = 'β©'
d_ul = 'β'
d_ur = 'β'
d_v = ... | BoxLineCharactersUnicode |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_addition_test.py | {
"start": 1442,
"end": 6853
} | class ____(test.TestCase):
"""Tests correctness of addition with combinations of a few Adders.
Tests here are done with the _DEFAULT_ADDITION_TIERS, which means
add_operators should reduce all operators resulting in one single operator.
This shows that we are able to correctly combine adders using the tiered
... | LinearOperatorAdditionCorrectnessTest |
python | numba__numba | numba/cuda/cudadrv/driver.py | {
"start": 81144,
"end": 81662
} | class ____(Module):
def get_function(self, name):
handle = driver.cuModuleGetFunction(self.handle, name.encode('utf8'))
return CudaPythonFunction(weakref.proxy(self), handle, name)
def get_global_symbol(self, name):
ptr, size = driver.cuModuleGetGlobal(self.handle, name.encode('utf8'))... | CudaPythonModule |
python | walkccc__LeetCode | solutions/841. Keys and Rooms/841.py | {
"start": 0,
"end": 281
} | class ____:
def canVisitAllRooms(self, rooms: list[list[int]]) -> bool:
seen = [False] * len(rooms)
def dfs(node: int) -> None:
seen[node] = True
for child in rooms[node]:
if not seen[child]:
dfs(child)
dfs(0)
return all(seen)
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-orb/components.py | {
"start": 2394,
"end": 5235
} | class ____(StreamSlicer):
plans_stream: Stream
subscriptions_stream: Stream
config: Config
def stream_slices(self) -> Iterable[StreamSlice]:
"""
This stream is sliced per `subscription_id` and day, as well as `billable_metric_id`
if a grouping key is provided. This is because th... | SubscriptionUsagePartitionRouter |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_athena.py | {
"start": 2561,
"end": 17537
} | class ____:
@pytest.fixture(autouse=True)
def _setup_test_cases(self):
args = {
"owner": "airflow",
"start_date": DEFAULT_DATE,
}
self.dag = DAG(TEST_DAG_ID, default_args=args, schedule="@once")
self.default_op_kwargs = dict(
task_id="test_at... | TestAthenaOperator |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 103810,
"end": 104543
} | class ____(Operation):
def call(self, x):
return backend.numpy.expm1(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(x.dtype)
if "int" in dtype or dtype == "bool":
dtype = backend.floatx()
sparse = getattr(x, "sparse", False)
return Ker... | Expm1 |
python | apache__airflow | providers/standard/src/airflow/providers/standard/operators/latest_only.py | {
"start": 1386,
"end": 5017
} | class ____(BaseBranchOperator):
"""
Skip tasks that are not running during the most recent schedule interval.
If the task is run outside the latest schedule interval (i.e. run_type == DagRunType.MANUAL),
all directly downstream tasks will be skipped.
Note that downstream tasks are never skipped if... | LatestOnlyOperator |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/debug_service_pb2_grpc.py | {
"start": 1267,
"end": 2466
} | class ____(object):
"""EventListener: Receives Event protos, e.g., from debugged TensorFlow
runtime(s).
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.SendEvents = channel.stream_stream(
'/tensorflow.EventListener/SendEvents',
req... | EventListenerStub |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 289945,
"end": 290434
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("enterprise_resource_path", "enterprise_slug", "enterprise_url")
enterprise_resource_path = sgqlc.types.Field(
URI, graphql_name="enterpriseResourcePath"
)
en... | EnterpriseAuditEntryData |
python | pypa__pip | src/pip/_vendor/pkg_resources/__init__.py | {
"start": 66274,
"end": 66968
} | class ____(ZipManifests):
"""
Memoized zipfile manifests.
"""
class manifest_mod(NamedTuple):
manifest: dict[str, zipfile.ZipInfo]
mtime: float
def load(self, path: str) -> dict[str, zipfile.ZipInfo]: # type: ignore[override] # ZipManifests.load is a classmethod
"""
... | MemoizedZipManifests |
python | django__django | tests/template_tests/filter_tests/test_linenumbers.py | {
"start": 169,
"end": 1243
} | class ____(SimpleTestCase):
"""
The contents of "linenumbers" is escaped according to the current
autoescape setting.
"""
@setup({"linenumbers01": "{{ a|linenumbers }} {{ b|linenumbers }}"})
def test_linenumbers01(self):
output = self.engine.render_to_string(
"linenumbers01"... | LinenumbersTests |
python | scipy__scipy | scipy/odr/_odrpack.py | {
"start": 2243,
"end": 5422
} | class ____(Exception):
"""
Exception stopping fitting.
You can raise this exception in your objective function to tell
`~scipy.odr.odr` to stop fitting.
"""
pass
# Backwards compatibility
odr_error = OdrError
odr_stop = OdrStop
__odrpack._set_exceptions(OdrError, OdrStop)
def _conv(obj, dt... | OdrStop |
python | openai__openai-python | src/openai/resources/evals/runs/output_items.py | {
"start": 920,
"end": 5978
} | class ____(SyncAPIResource):
@cached_property
def with_raw_response(self) -> OutputItemsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.gith... | OutputItems |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_length.py | {
"start": 1006,
"end": 1112
} | class ____:
def __len__(self):
print("raise some error")
raise NotImplementedError
| Length6 |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 123247,
"end": 125053
} | class ____(TestCase):
def setUp(self):
super().setUp()
inps = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)
tgts = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)
self.dataset = TensorDataset(inps, tgts)
@unittest.skipIf(not TEST_CUDA, "CUDA unavailable")
def t... | TestCustomPinFn |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-sambanovasystems/llama_index/llms/sambanovasystems/base.py | {
"start": 23309,
"end": 61986
} | class ____(LLM):
"""
SambaStudio model.
Setup:
To use, you should have the environment variables:
``SAMBASTUDIO_URL`` set with your SambaStudio deployed endpoint URL.
``SAMBASTUDIO_API_KEY`` set with your SambaStudio deployed endpoint Key.
https://docs.sambanova.ai/sambastud... | SambaStudio |
python | doocs__leetcode | lcp/LCP 01. ηζ°ε/Solution.py | {
"start": 0,
"end": 138
} | class ____:
def game(self, guess: List[int], answer: List[int]) -> int:
return sum(a == b for a, b in zip(guess, answer))
| Solution |
python | sanic-org__sanic | guide/webapp/display/page/renderer.py | {
"start": 265,
"end": 2007
} | class ____(BaseRenderer):
def render(self, request: Request, language: str, path: str) -> Builder:
self._setup_request(request, language, path)
builder = self.get_builder(
full=request.headers.get("HX-Request") is None,
language=language,
)
self._body(request,... | PageRenderer |
python | apache__airflow | providers/dingding/src/airflow/providers/dingding/operators/dingding.py | {
"start": 1103,
"end": 2844
} | class ____(BaseOperator):
"""
This operator allows to send DingTalk message using Custom Robot API.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DingdingOperator`
:param dingding_conn_id: Dingding connection id that has a... | DingdingOperator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.