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 | ray-project__ray | rllib/examples/learners/classes/intrinsic_curiosity_learners.py | {
"start": 3664,
"end": 6613
} | class ____(ConnectorV2):
"""Learner ConnectorV2 piece to compute intrinsic rewards based on an ICM.
For more details, see here:
[1] Curiosity-driven Exploration by Self-supervised Prediction
Pathak, Agrawal, Efros, and Darrell - UC Berkeley - ICML 2017.
https://arxiv.org/pdf/1705.05363.pdf
This connector piece:
- requires two RLModules to be present in the MultiRLModule:
DEFAULT_MODULE_ID (the policy model to be trained) and ICM_MODULE_ID (the instrinsic
curiosity architecture).
- must be located toward the end of to your Learner pipeline (after the
`NumpyToTensor` piece) in order to perform a forward pass on the ICM model with the
readily compiled batch and a following forward-loss computation to get the intrinsi
rewards.
- these intrinsic rewards will then be added to the (extrinsic) rewards in the main
model's train batch.
"""
def __init__(
self,
input_observation_space: Optional[gym.Space] = None,
input_action_space: Optional[gym.Space] = None,
*,
intrinsic_reward_coeff: float,
**kwargs,
):
"""Initializes a CountBasedCuriosity instance.
Args:
intrinsic_reward_coeff: The weight with which to multiply the intrinsic
reward before adding it to the extrinsic rewards of the main model.
"""
super().__init__(input_observation_space, input_action_space)
self.intrinsic_reward_coeff = intrinsic_reward_coeff
def __call__(
self,
*,
rl_module: RLModule,
batch: Any,
episodes: List[EpisodeType],
explore: Optional[bool] = None,
shared_data: Optional[dict] = None,
**kwargs,
) -> Any:
# Assert that the batch is ready.
assert DEFAULT_MODULE_ID in batch and ICM_MODULE_ID not in batch
assert (
Columns.OBS in batch[DEFAULT_MODULE_ID]
and Columns.NEXT_OBS in batch[DEFAULT_MODULE_ID]
)
# TODO (sven): We are performing two forward passes per update right now.
# Once here in the connector (w/o grad) to just get the intrinsic rewards
# and once in the learner to actually compute the ICM loss and update the ICM.
# Maybe we can save one of these, but this would currently harm the DDP-setup
# for multi-GPU training.
with torch.no_grad():
# Perform ICM forward pass.
fwd_out = rl_module[ICM_MODULE_ID].forward_train(batch[DEFAULT_MODULE_ID])
# Add the intrinsic rewards to the main module's extrinsic rewards.
batch[DEFAULT_MODULE_ID][Columns.REWARDS] += (
self.intrinsic_reward_coeff * fwd_out[Columns.INTRINSIC_REWARDS]
)
# Duplicate the batch such that the ICM also has data to learn on.
batch[ICM_MODULE_ID] = batch[DEFAULT_MODULE_ID]
return batch
| IntrinsicCuriosityModelConnector |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/executor/child_process_executor.py | {
"start": 995,
"end": 1185
} | class ____(
NamedTuple(
"ChildProcessSystemErrorEvent", [("pid", int), ("error_info", SerializableErrorInfo)]
),
ChildProcessEvent,
):
pass
| ChildProcessSystemErrorEvent |
python | getsentry__sentry | src/sentry/silo/base.py | {
"start": 1488,
"end": 3124
} | class ____(threading.local):
"""
Used by silo endpoint decorators and other contexts that help 'suggest' to
acceptance testing and local single process silo testing which 'silo context' the
process should be running in.
All calls to this class's methods are no-ops in a production environment,
but are monkey-patched in a test environment. See the function
sentry.testutils.silo.monkey_patch_single_process_silo_mode_state
for the test environment's method bodies.
"""
@staticmethod
@contextlib.contextmanager
def enter(mode: SiloMode, region: Region | None = None) -> Generator[None]:
"""
Prevents re-entrant cases unless the exit_single_process_silo_context is
explicitly embedded, ensuring that this single process silo mode simulates
the boundaries explicitly between what would be separate processes in
deployment.
"""
yield
@staticmethod
@contextlib.contextmanager
def exit() -> Generator[None]:
"""
Used by silo endpoint decorators and other contexts to signal that a
potential inter process interaction is being simulated locally for acceptance
tests that validate the behavior of multiple endpoints with process
boundaries in play. Call this inside of any RPC interaction to ensure that
such acceptance tests can 'swap' the silo context on the fly.
"""
yield
@staticmethod
def get_mode() -> SiloMode | None:
return None
@staticmethod
def get_region() -> Region | None:
return None
| SingleProcessSiloModeState |
python | bokeh__bokeh | src/bokeh/colors/util.py | {
"start": 3013,
"end": 5419
} | class ____(RGB):
''' Represent a CSS named color, provided as RGB values.
Instances of this class also record the name of the created color, which
is used to populate the Bokeh enum for named colors.
'''
__all__: ClassVar[list[str]] = []
colors: ClassVar[list[NamedColor]] = []
def __init__(self, name: str, r: int, g: int, b: int) -> None:
'''
Args:
name (str) :
The name to associate with the color, e.g. "firebrick"
r (int) :
The value for the red channel in [0, 255]
g (int) :
The value for the green channel in [0, 255]
b (int) :
The value for the blue channel in [0, 255]
'''
if name not in self.__all__:
self.__all__.append(name)
self.colors.append(self)
self.name = name
super().__init__(r, g, b)
@classmethod
def find(cls, name: str) -> NamedColor | None:
''' Find and return a named color.
Args:
name (str) : Name of color to find.
Returns:
:class:`~bokeh.colors.NamedColor` or None if the name is not
recognised.
'''
try:
index = cls.__all__.index(name)
except ValueError:
return None
return cls.colors[index]
@classmethod
def from_string(cls, color: str) -> RGB:
''' Create an RGB color from a string.
Args:
color (str) :
String containing color. This may be a named color such as
"blue" or a hex RGB(A) string of one of the following formats:
'#rrggbb', '#rrggbbaa', '#rgb' or '#rgba'.
Returns:
:class:`~bokeh.colors.RGB`
'''
try:
# Is it a hex string?
return RGB.from_hex_string(color)
except ValueError:
# Is it a named color?
rgb = cls.find(color)
if rgb is None:
raise ValueError(f"Color '{color}' must be either a named color or an RGB(A) hex string")
return rgb
def to_css(self) -> str:
'''
'''
return self.name
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| NamedColor |
python | kamyu104__LeetCode-Solutions | Python/sum-of-elements-with-frequency-divisible-by-k.py | {
"start": 417,
"end": 720
} | class ____(object):
def sumDivisibleByK(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
cnt = collections.defaultdict(int)
for x in nums:
cnt[x] += 1
return sum(x for x in nums if cnt[x]%k == 0)
| Solution2 |
python | pydata__xarray | xarray/tests/test_backends_api.py | {
"start": 5811,
"end": 11911
} | class ____:
"""Test behaviors related to the backend's preferred chunks."""
var_name = "data"
def create_dataset(self, shape, pref_chunks):
"""Return a dataset with a variable with the given shape and preferred chunks."""
dims = tuple(f"dim_{idx}" for idx in range(len(shape)))
return xr.Dataset(
{
self.var_name: xr.Variable(
dims,
np.empty(shape, dtype=np.dtype("V1")),
encoding={
"preferred_chunks": dict(zip(dims, pref_chunks, strict=True))
},
)
}
)
def check_dataset(self, initial, final, expected_chunks):
assert_identical(initial, final)
assert final[self.var_name].chunks == expected_chunks
@pytest.mark.parametrize(
"shape,pref_chunks",
[
# Represent preferred chunking with int.
((5,), (2,)),
# Represent preferred chunking with tuple.
((5,), ((2, 2, 1),)),
# Represent preferred chunking with int in two dims.
((5, 6), (4, 2)),
# Represent preferred chunking with tuple in second dim.
((5, 6), (4, (2, 2, 2))),
],
)
@pytest.mark.parametrize("request_with_empty_map", [False, True])
def test_honor_chunks(self, shape, pref_chunks, request_with_empty_map):
"""Honor the backend's preferred chunks when opening a dataset."""
initial = self.create_dataset(shape, pref_chunks)
# To keep the backend's preferred chunks, the `chunks` argument must be an
# empty mapping or map dimensions to `None`.
chunks = (
{}
if request_with_empty_map
else dict.fromkeys(initial[self.var_name].dims, None)
)
final = xr.open_dataset(
initial, engine=PassThroughBackendEntrypoint, chunks=chunks
)
self.check_dataset(initial, final, explicit_chunks(pref_chunks, shape))
@pytest.mark.parametrize(
"shape,pref_chunks,req_chunks",
[
# Preferred chunking is int; requested chunking is int.
((5,), (2,), (3,)),
# Preferred chunking is int; requested chunking is tuple.
((5,), (2,), ((2, 1, 1, 1),)),
# Preferred chunking is tuple; requested chunking is int.
((5,), ((2, 2, 1),), (3,)),
# Preferred chunking is tuple; requested chunking is tuple.
((5,), ((2, 2, 1),), ((2, 1, 1, 1),)),
# Split chunks along a dimension other than the first.
((1, 5), (1, 2), (1, 3)),
],
)
def test_split_chunks(self, shape, pref_chunks, req_chunks):
"""Warn when the requested chunks separate the backend's preferred chunks."""
initial = self.create_dataset(shape, pref_chunks)
with pytest.warns(UserWarning):
final = xr.open_dataset(
initial,
engine=PassThroughBackendEntrypoint,
chunks=dict(zip(initial[self.var_name].dims, req_chunks, strict=True)),
)
self.check_dataset(initial, final, explicit_chunks(req_chunks, shape))
@pytest.mark.parametrize(
"shape,pref_chunks,req_chunks",
[
# Keep preferred chunks using int representation.
((5,), (2,), (2,)),
# Keep preferred chunks using tuple representation.
((5,), (2,), ((2, 2, 1),)),
# Join chunks, leaving a final short chunk.
((5,), (2,), (4,)),
# Join all chunks with an int larger than the dimension size.
((5,), (2,), (6,)),
# Join one chunk using tuple representation.
((5,), (1,), ((1, 1, 2, 1),)),
# Join one chunk using int representation.
((5,), ((1, 1, 2, 1),), (2,)),
# Join multiple chunks using tuple representation.
((5,), ((1, 1, 2, 1),), ((2, 3),)),
# Join chunks in multiple dimensions.
((5, 5), (2, (1, 1, 2, 1)), (4, (2, 3))),
],
)
def test_join_chunks(self, shape, pref_chunks, req_chunks):
"""Don't warn when the requested chunks join or keep the preferred chunks."""
initial = self.create_dataset(shape, pref_chunks)
with assert_no_warnings():
final = xr.open_dataset(
initial,
engine=PassThroughBackendEntrypoint,
chunks=dict(zip(initial[self.var_name].dims, req_chunks, strict=True)),
)
self.check_dataset(initial, final, explicit_chunks(req_chunks, shape))
@pytest.mark.parametrize("create_default_indexes", [True, False])
def test_default_indexes(self, create_default_indexes):
"""Create default indexes if the backend does not create them."""
coords = xr.Coordinates({"x": ("x", [0, 1]), "y": list("abc")}, indexes={})
initial = xr.Dataset({"a": ("x", [1, 2])}, coords=coords)
with assert_no_warnings():
final = xr.open_dataset(
initial,
engine=PassThroughBackendEntrypoint,
create_default_indexes=create_default_indexes,
)
if create_default_indexes:
assert all(name in final.xindexes for name in ["x", "y"])
else:
assert len(final.xindexes) == 0
@pytest.mark.parametrize("create_default_indexes", [True, False])
def test_default_indexes_passthrough(self, create_default_indexes):
"""Allow creating indexes in the backend."""
initial = xr.Dataset(
{"a": (["x", "y"], [[1, 2, 3], [4, 5, 6]])},
coords={"x": ("x", [0, 1]), "y": ("y", list("abc"))},
).stack(z=["x", "y"])
with assert_no_warnings():
final = xr.open_dataset(
initial,
engine=PassThroughBackendEntrypoint,
create_default_indexes=create_default_indexes,
)
assert initial.coords.equals(final.coords)
| TestPreferredChunks |
python | kamyu104__LeetCode-Solutions | Python/count-number-of-ways-to-place-houses.py | {
"start": 75,
"end": 889
} | class ____(object):
def countHousePlacements(self, n):
"""
:type n: int
:rtype: int
"""
MOD = 10**9+7
def matrix_mult(A, B):
ZB = zip(*B)
return [[sum(a*b % MOD for a, b in itertools.izip(row, col)) % MOD for col in ZB] for row in A]
def matrix_expo(A, K):
result = [[int(i == j) for j in xrange(len(A))] for i in xrange(len(A))]
while K:
if K % 2:
result = matrix_mult(result, A)
A = matrix_mult(A, A)
K /= 2
return result
T = [[1, 1],
[1, 0]]
return pow(matrix_mult([[2, 1]], matrix_expo(T, n-1))[0][0], 2, MOD) # [a1, a0] * T^(n-1) = [an, a(n-1)]
# Time: O(n)
# Space: O(1)
# dp
| Solution |
python | davidhalter__jedi | test/completion/classes.py | {
"start": 2939,
"end": 3029
} | class ____(SuperClass):
def method_mixin(self):
return int
#? 20 SuperClass
| Mixin |
python | readthedocs__readthedocs.org | readthedocs/integrations/migrations/0003_add_missing_model_change_migrations.py | {
"start": 150,
"end": 1887
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("integrations", "0002_add-webhook"),
]
operations = [
migrations.CreateModel(
name="BitbucketWebhook",
fields=[],
options={
"proxy": True,
"indexes": [],
},
bases=("integrations.integration",),
),
migrations.CreateModel(
name="GenericAPIWebhook",
fields=[],
options={
"proxy": True,
"indexes": [],
},
bases=("integrations.integration",),
),
migrations.CreateModel(
name="GitHubWebhook",
fields=[],
options={
"proxy": True,
"indexes": [],
},
bases=("integrations.integration",),
),
migrations.CreateModel(
name="GitLabWebhook",
fields=[],
options={
"proxy": True,
"indexes": [],
},
bases=("integrations.integration",),
),
migrations.AlterField(
model_name="integration",
name="integration_type",
field=models.CharField(
choices=[
("github_webhook", "GitHub incoming webhook"),
("bitbucket_webhook", "Bitbucket incoming webhook"),
("gitlab_webhook", "GitLab incoming webhook"),
("api_webhook", "Generic API incoming webhook"),
],
max_length=32,
verbose_name="Integration type",
),
),
]
| Migration |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 6323,
"end": 6832
} | class ____:
a: int
b: str = attr.ib(on_setattr=attr.setters.NO_OP)
c: bool = attr.ib(on_setattr=attr.setters.frozen)
d: int = attr.ib(on_setattr=[attr.setters.convert, attr.setters.validate])
e: bool = attr.ib(
on_setattr=attr.setters.pipe(
attr.setters.convert, attr.setters.validate
)
)
# field_transformer
def ft_hook(cls: type, attribs: list[attr.Attribute]) -> list[attr.Attribute]:
return attribs
@attr.s(field_transformer=ft_hook)
| ValidatedSetter |
python | pypa__pip | src/pip/_internal/commands/download.py | {
"start": 529,
"end": 5148
} | class ____(RequirementCommand):
"""
Download packages from:
- PyPI (and other indexes) using requirement specifiers.
- VCS project urls.
- Local project directories.
- Local or remote source archives.
pip also supports downloading from "requirements files", which provide
an easy way to specify a whole environment to be downloaded.
"""
usage = """
%prog [options] <requirement specifier> [package-index-options] ...
%prog [options] -r <requirements file> [package-index-options] ...
%prog [options] <vcs project url> ...
%prog [options] <local project path> ...
%prog [options] <archive url/path> ..."""
def add_options(self) -> None:
self.cmd_opts.add_option(cmdoptions.constraints())
self.cmd_opts.add_option(cmdoptions.build_constraints())
self.cmd_opts.add_option(cmdoptions.requirements())
self.cmd_opts.add_option(cmdoptions.requirements_from_scripts())
self.cmd_opts.add_option(cmdoptions.no_deps())
self.cmd_opts.add_option(cmdoptions.no_binary())
self.cmd_opts.add_option(cmdoptions.only_binary())
self.cmd_opts.add_option(cmdoptions.prefer_binary())
self.cmd_opts.add_option(cmdoptions.src())
self.cmd_opts.add_option(cmdoptions.pre())
self.cmd_opts.add_option(cmdoptions.require_hashes())
self.cmd_opts.add_option(cmdoptions.progress_bar())
self.cmd_opts.add_option(cmdoptions.no_build_isolation())
self.cmd_opts.add_option(cmdoptions.use_pep517())
self.cmd_opts.add_option(cmdoptions.check_build_deps())
self.cmd_opts.add_option(cmdoptions.ignore_requires_python())
self.cmd_opts.add_option(
"-d",
"--dest",
"--destination-dir",
"--destination-directory",
dest="download_dir",
metavar="dir",
default=os.curdir,
help="Download packages into <dir>.",
)
cmdoptions.add_target_python_options(self.cmd_opts)
index_opts = cmdoptions.make_option_group(
cmdoptions.index_group,
self.parser,
)
self.parser.insert_option_group(0, index_opts)
self.parser.insert_option_group(0, self.cmd_opts)
@with_cleanup
def run(self, options: Values, args: list[str]) -> int:
options.ignore_installed = True
# editable doesn't really make sense for `pip download`, but the bowels
# of the RequirementSet code require that property.
options.editables = []
cmdoptions.check_dist_restriction(options)
cmdoptions.check_build_constraints(options)
options.download_dir = normalize_path(options.download_dir)
ensure_dir(options.download_dir)
session = self.get_default_session(options)
target_python = make_target_python(options)
finder = self._build_package_finder(
options=options,
session=session,
target_python=target_python,
ignore_requires_python=options.ignore_requires_python,
)
build_tracker = self.enter_context(get_build_tracker())
directory = TempDirectory(
delete=not options.no_clean,
kind="download",
globally_managed=True,
)
reqs = self.get_requirements(args, options, finder, session)
preparer = self.make_requirement_preparer(
temp_build_dir=directory,
options=options,
build_tracker=build_tracker,
session=session,
finder=finder,
download_dir=options.download_dir,
use_user_site=False,
verbosity=self.verbosity,
)
resolver = self.make_resolver(
preparer=preparer,
finder=finder,
options=options,
ignore_requires_python=options.ignore_requires_python,
py_version_info=options.python_version,
)
self.trace_basic_info(finder)
requirement_set = resolver.resolve(reqs, check_supported_wheels=True)
preparer.prepare_linked_requirements_more(requirement_set.requirements.values())
downloaded: list[str] = []
for req in requirement_set.requirements.values():
if req.satisfied_by is None:
assert req.name is not None
preparer.save_linked_requirement(req)
downloaded.append(req.name)
if downloaded:
write_output("Successfully downloaded %s", " ".join(downloaded))
return SUCCESS
| DownloadCommand |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol1.py | {
"start": 2474,
"end": 2634
} | class ____:
def __call__(self: Callable[[int], int], v: int) -> int:
return v
def func8(f: Callable[[int], int]): ...
func8(TestClass8())
| TestClass8 |
python | huggingface__transformers | src/transformers/models/kosmos2/modeling_kosmos2.py | {
"start": 15400,
"end": 16089
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = self.fc2(hidden_states)
return hidden_states
# Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoderLayer with AltCLIP->Kosmos2Vision
| Kosmos2VisionMLP |
python | huggingface__transformers | src/transformers/models/pixtral/modeling_pixtral.py | {
"start": 8336,
"end": 11357
} | class ____(nn.Module):
"""
Multi-headed attention compatible with ALL_ATTENTION_FUNCTIONS.
"""
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim // self.num_heads
self.is_causal = False
self.scaling = self.head_dim**-0.5
self.is_causal = False
self.dropout = config.attention_dropout
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
self.o_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
output_attentions: Optional[bool] = False,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
"""Input shape: Batch x Time x Channel"""
batch_size, patches, _ = hidden_states.size()
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states = query_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
key_states = key_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
value_states = value_states.view(batch_size, patches, self.num_heads, self.head_dim).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, unsqueeze_dim=0)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
# Since we use packing, if flash_attention_2 is selected we rely on position_ids
if self.config._attn_implementation == "flash_attention_2":
kwargs["position_ids"] = kwargs["position_ids"].to(hidden_states.device, non_blocking=True)
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(batch_size, patches, -1).contiguous()
attn_output = self.o_proj(attn_output)
if not output_attentions:
attn_weights = None
return attn_output, attn_weights
# Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Pixtral
| PixtralAttention |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/pg8000.py | {
"start": 10625,
"end": 18778
} | class ____(PGDialect):
driver = "pg8000"
supports_statement_cache = True
supports_unicode_statements = True
supports_unicode_binds = True
default_paramstyle = "format"
supports_sane_multi_rowcount = True
execution_ctx_cls = PGExecutionContext_pg8000
statement_compiler = PGCompiler_pg8000
preparer = PGIdentifierPreparer_pg8000
supports_server_side_cursors = True
render_bind_cast = True
# reversed as of pg8000 1.16.6. 1.16.5 and lower
# are no longer compatible
description_encoding = None
# description_encoding = "use_encoding"
colspecs = util.update_copy(
PGDialect.colspecs,
{
sqltypes.String: _PGString,
sqltypes.Numeric: _PGNumericNoBind,
sqltypes.Float: _PGFloat,
sqltypes.JSON: _PGJSON,
sqltypes.Boolean: _PGBoolean,
sqltypes.NullType: _PGNullType,
JSONB: _PGJSONB,
CITEXT: CITEXT,
sqltypes.JSON.JSONPathType: _PGJSONPathType,
sqltypes.JSON.JSONIndexType: _PGJSONIndexType,
sqltypes.JSON.JSONIntIndexType: _PGJSONIntIndexType,
sqltypes.JSON.JSONStrIndexType: _PGJSONStrIndexType,
sqltypes.Interval: _PGInterval,
INTERVAL: _PGInterval,
sqltypes.DateTime: _PGTimeStamp,
sqltypes.DateTime: _PGTimeStamp,
sqltypes.Date: _PGDate,
sqltypes.Time: _PGTime,
sqltypes.Integer: _PGInteger,
sqltypes.SmallInteger: _PGSmallInteger,
sqltypes.BigInteger: _PGBigInteger,
sqltypes.Enum: _PGEnum,
sqltypes.ARRAY: _PGARRAY,
OIDVECTOR: _PGOIDVECTOR,
ranges.INT4RANGE: _Pg8000Range,
ranges.INT8RANGE: _Pg8000Range,
ranges.NUMRANGE: _Pg8000Range,
ranges.DATERANGE: _Pg8000Range,
ranges.TSRANGE: _Pg8000Range,
ranges.TSTZRANGE: _Pg8000Range,
ranges.INT4MULTIRANGE: _Pg8000MultiRange,
ranges.INT8MULTIRANGE: _Pg8000MultiRange,
ranges.NUMMULTIRANGE: _Pg8000MultiRange,
ranges.DATEMULTIRANGE: _Pg8000MultiRange,
ranges.TSMULTIRANGE: _Pg8000MultiRange,
ranges.TSTZMULTIRANGE: _Pg8000MultiRange,
},
)
def __init__(self, client_encoding=None, **kwargs):
PGDialect.__init__(self, **kwargs)
self.client_encoding = client_encoding
if self._dbapi_version < (1, 16, 6):
raise NotImplementedError("pg8000 1.16.6 or greater is required")
if self._native_inet_types:
raise NotImplementedError(
"The pg8000 dialect does not fully implement "
"ipaddress type handling; INET is supported by default, "
"CIDR is not"
)
@util.memoized_property
def _dbapi_version(self):
if self.dbapi and hasattr(self.dbapi, "__version__"):
return tuple(
[
int(x)
for x in re.findall(
r"(\d+)(?:[-\.]?|$)", self.dbapi.__version__
)
]
)
else:
return (99, 99, 99)
@classmethod
def import_dbapi(cls):
return __import__("pg8000")
def create_connect_args(self, url):
opts = url.translate_connect_args(username="user")
if "port" in opts:
opts["port"] = int(opts["port"])
opts.update(url.query)
return ([], opts)
def is_disconnect(self, e, connection, cursor):
if isinstance(e, self.dbapi.InterfaceError) and "network error" in str(
e
):
# new as of pg8000 1.19.0 for broken connections
return True
# connection was closed normally
return "connection is closed" in str(e)
def get_isolation_level_values(self, dbapi_connection):
return (
"AUTOCOMMIT",
"READ COMMITTED",
"READ UNCOMMITTED",
"REPEATABLE READ",
"SERIALIZABLE",
)
def set_isolation_level(self, dbapi_connection, level):
level = level.replace("_", " ")
if level == "AUTOCOMMIT":
dbapi_connection.autocommit = True
else:
dbapi_connection.autocommit = False
cursor = dbapi_connection.cursor()
cursor.execute(
"SET SESSION CHARACTERISTICS AS TRANSACTION "
f"ISOLATION LEVEL {level}"
)
cursor.execute("COMMIT")
cursor.close()
def detect_autocommit_setting(self, dbapi_conn) -> bool:
return bool(dbapi_conn.autocommit)
def set_readonly(self, connection, value):
cursor = connection.cursor()
try:
cursor.execute(
"SET SESSION CHARACTERISTICS AS TRANSACTION %s"
% ("READ ONLY" if value else "READ WRITE")
)
cursor.execute("COMMIT")
finally:
cursor.close()
def get_readonly(self, connection):
cursor = connection.cursor()
try:
cursor.execute("show transaction_read_only")
val = cursor.fetchone()[0]
finally:
cursor.close()
return val == "on"
def set_deferrable(self, connection, value):
cursor = connection.cursor()
try:
cursor.execute(
"SET SESSION CHARACTERISTICS AS TRANSACTION %s"
% ("DEFERRABLE" if value else "NOT DEFERRABLE")
)
cursor.execute("COMMIT")
finally:
cursor.close()
def get_deferrable(self, connection):
cursor = connection.cursor()
try:
cursor.execute("show transaction_deferrable")
val = cursor.fetchone()[0]
finally:
cursor.close()
return val == "on"
def _set_client_encoding(self, dbapi_connection, client_encoding):
cursor = dbapi_connection.cursor()
cursor.execute(
f"""SET CLIENT_ENCODING TO '{
client_encoding.replace("'", "''")
}'"""
)
cursor.execute("COMMIT")
cursor.close()
def do_begin_twophase(self, connection, xid):
connection.connection.tpc_begin((0, xid, ""))
def do_prepare_twophase(self, connection, xid):
connection.connection.tpc_prepare()
def do_rollback_twophase(
self, connection, xid, is_prepared=True, recover=False
):
connection.connection.tpc_rollback((0, xid, ""))
def do_commit_twophase(
self, connection, xid, is_prepared=True, recover=False
):
connection.connection.tpc_commit((0, xid, ""))
def do_recover_twophase(self, connection):
return [row[1] for row in connection.connection.tpc_recover()]
def on_connect(self):
fns = []
def on_connect(conn):
conn.py_types[quoted_name] = conn.py_types[str]
fns.append(on_connect)
if self.client_encoding is not None:
def on_connect(conn):
self._set_client_encoding(conn, self.client_encoding)
fns.append(on_connect)
if self._native_inet_types is False:
def on_connect(conn):
# inet
conn.register_in_adapter(869, lambda s: s)
# cidr
conn.register_in_adapter(650, lambda s: s)
fns.append(on_connect)
if self._json_deserializer:
def on_connect(conn):
# json
conn.register_in_adapter(114, self._json_deserializer)
# jsonb
conn.register_in_adapter(3802, self._json_deserializer)
fns.append(on_connect)
if len(fns) > 0:
def on_connect(conn):
for fn in fns:
fn(conn)
return on_connect
else:
return None
@util.memoized_property
def _dialect_specific_select_one(self):
return ";"
dialect = PGDialect_pg8000
| PGDialect_pg8000 |
python | pandas-dev__pandas | doc/sphinxext/contributors.py | {
"start": 591,
"end": 1723
} | class ____(Directive):
required_arguments = 1
name = "contributors"
def run(self):
range_ = self.arguments[0]
if range_.endswith("x..HEAD"):
return [nodes.paragraph(), nodes.bullet_list()]
try:
components = build_components(range_)
except git.GitCommandError as exc:
return [
self.state.document.reporter.warning(
f"Cannot find contributors for range {repr(range_)}: {exc}",
line=self.lineno,
)
]
else:
message = nodes.paragraph()
message += nodes.Text(components["author_message"])
listnode = nodes.bullet_list()
for author in components["authors"]:
para = nodes.paragraph()
para += nodes.Text(author)
listnode += nodes.list_item("", para)
return [message, listnode]
def setup(app):
app.add_directive("contributors", ContributorsDirective)
return {"version": "0.1", "parallel_read_safe": True, "parallel_write_safe": True}
| ContributorsDirective |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 864,
"end": 993
} | class ____(DD, EE):
z: float = attr.ib()
HH(x=[1], y=[], z=1.1)
# same class
c == cc
# Exceptions
@attr.s(auto_exc=True)
| HH |
python | Lightning-AI__lightning | src/lightning/fabric/plugins/io/checkpoint_io.py | {
"start": 704,
"end": 3207
} | class ____(ABC):
"""Interface to save/load checkpoints as they are saved through the ``Strategy``.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
Typically most plugins either use the Torch based IO Plugin; ``TorchCheckpointIO`` but may
require particular handling depending on the plugin.
In addition, you can pass a custom ``CheckpointIO`` by extending this class and passing it
to the Trainer, i.e ``Trainer(plugins=[MyCustomCheckpointIO()])``.
.. note::
For some plugins, it is not possible to use a custom checkpoint plugin as checkpointing logic is not
modifiable.
"""
@abstractmethod
def save_checkpoint(self, checkpoint: dict[str, Any], path: _PATH, storage_options: Optional[Any] = None) -> None:
"""Save model/training states as a checkpoint file through state-dump and file-write.
Args:
checkpoint: dict containing model and trainer state
path: write-target path
storage_options: Optional parameters when saving the model/training states.
"""
@abstractmethod
def load_checkpoint(
self, path: _PATH, map_location: Optional[Any] = None, weights_only: Optional[bool] = None
) -> dict[str, Any]:
"""Load checkpoint from a path when resuming or loading ckpt for test/validate/predict stages.
Args:
path: Path to checkpoint
map_location: a function, :class:`torch.device`, string or a dict specifying how to remap storage
locations.
weights_only: Defaults to ``None``. If ``True``, restricts loading to ``state_dicts`` of plain
``torch.Tensor`` and other primitive types. If loading a checkpoint from a trusted source that contains
an ``nn.Module``, use ``weights_only=False``. If loading checkpoint from an untrusted source, we
recommend using ``weights_only=True``. For more information, please refer to the
`PyTorch Developer Notes on Serialization Semantics <https://docs.pytorch.org/docs/main/notes/serialization.html#id3>`_.
Returns: The loaded checkpoint.
"""
@abstractmethod
def remove_checkpoint(self, path: _PATH) -> None:
"""Remove checkpoint file from the filesystem.
Args:
path: Path to checkpoint
"""
def teardown(self) -> None:
"""This method is called to teardown the process."""
| CheckpointIO |
python | getsentry__sentry | src/sentry/auth/providers/fly/views.py | {
"start": 671,
"end": 855
} | class ____(OAuth2Login):
authorize_url = AUTHORIZE_URL
scope = SCOPE
def __init__(self, client_id: str) -> None:
super().__init__(client_id=client_id)
| FlyOAuth2Login |
python | milvus-io__pymilvus | pymilvus/client/types.py | {
"start": 28134,
"end": 36569
} | class ____(list):
"""
A list that holds partially eager and partially lazy row data.
- Primitive fields are extracted at initialization.
- Variable-length fields (array/string/json) are extracted lazily on access.
Attributes:
extra (dict): Extra metadata associated with the result set.
"""
def __init__(
self,
lazy_field_data: List[Any], # lazy extract fields
*args,
extra: Optional[Dict] = None,
dynamic_fields: Optional[List] = None,
strict_float32: bool = False,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self._lazy_field_data = lazy_field_data
self._dynamic_fields = dynamic_fields
self.extra = OmitZeroDict(extra or {})
self._float_vector_np_array = {}
self._has_materialized_float_vector = False
self._strict_float32 = strict_float32
self._materialized_bitmap = [False] * len(self)
def _extract_lazy_fields(self, index: int, field_data: Any, row_data: Dict) -> Any:
if field_data.type == DataType.JSON:
if len(field_data.valid_data) > 0 and field_data.valid_data[index] is False:
row_data[field_data.field_name] = None
return
try:
json_dict = orjson.loads(field_data.scalars.json_data.data[index])
except Exception as e:
logger.error(
f"HybridExtraList::_extract_lazy_fields::Failed to load JSON data: {e}, original data: {field_data.scalars.json_data.data[index]}"
)
raise
if not field_data.is_dynamic:
row_data[field_data.field_name] = json_dict
return
if not self._dynamic_fields:
# Only update keys that don't exist in row_data
row_data.update({k: v for k, v in json_dict.items() if k not in row_data})
return
# Only update keys that don't exist in row_data and are in dynamic_fields
row_data.update(
{
k: v
for k, v in json_dict.items()
if k in self._dynamic_fields and k not in row_data
}
)
elif field_data.type == DataType.FLOAT_VECTOR:
dim = field_data.vectors.dim
start_pos = index * dim
end_pos = start_pos + dim
if len(field_data.vectors.float_vector.data) >= start_pos:
# Here we use numpy.array to convert the float64 values to numpy.float32 values,
# and return a list of numpy.float32 to users
# By using numpy.array, performance improved by 60% for topk=16384 dim=1536 case.
if self._strict_float32:
row_data[field_data.field_name] = self._float_vector_np_array[
field_data.field_name
][start_pos:end_pos]
else:
row_data[field_data.field_name] = field_data.vectors.float_vector.data[
start_pos:end_pos
]
elif field_data.type == DataType.BINARY_VECTOR:
dim = field_data.vectors.dim
bytes_per_vector = dim // 8
start_pos = index * bytes_per_vector
end_pos = start_pos + bytes_per_vector
if len(field_data.vectors.binary_vector) >= start_pos:
row_data[field_data.field_name] = [
field_data.vectors.binary_vector[start_pos:end_pos]
]
elif field_data.type == DataType.BFLOAT16_VECTOR:
dim = field_data.vectors.dim
bytes_per_vector = dim * 2
start_pos = index * bytes_per_vector
end_pos = start_pos + bytes_per_vector
if len(field_data.vectors.bfloat16_vector) >= start_pos:
row_data[field_data.field_name] = [
field_data.vectors.bfloat16_vector[start_pos:end_pos]
]
elif field_data.type == DataType.FLOAT16_VECTOR:
dim = field_data.vectors.dim
bytes_per_vector = dim * 2
start_pos = index * bytes_per_vector
end_pos = start_pos + bytes_per_vector
if len(field_data.vectors.float16_vector) >= start_pos:
row_data[field_data.field_name] = [
field_data.vectors.float16_vector[start_pos:end_pos]
]
elif field_data.type == DataType.SPARSE_FLOAT_VECTOR:
row_data[field_data.field_name] = utils.sparse_parse_single_row(
field_data.vectors.sparse_float_vector.contents[index]
)
elif field_data.type == DataType.INT8_VECTOR:
dim = field_data.vectors.dim
start_pos = index * dim
end_pos = start_pos + dim
if len(field_data.vectors.int8_vector) >= start_pos:
row_data[field_data.field_name] = [
field_data.vectors.int8_vector[start_pos:end_pos]
]
elif field_data.type == DataType._ARRAY_OF_VECTOR:
# Handle array of vectors
if hasattr(field_data, "vectors") and hasattr(field_data.vectors, "vector_array"):
if index < len(field_data.vectors.vector_array.data):
vector_data = field_data.vectors.vector_array.data[index]
dim = vector_data.dim
float_data = vector_data.float_vector.data
num_vectors = len(float_data) // dim
row_vectors = []
for vec_idx in range(num_vectors):
vec_start = vec_idx * dim
vec_end = vec_start + dim
row_vectors.append(list(float_data[vec_start:vec_end]))
row_data[field_data.field_name] = row_vectors
else:
row_data[field_data.field_name] = []
else:
row_data[field_data.field_name] = []
elif field_data.type == DataType._ARRAY_OF_STRUCT:
# Handle struct arrays - convert column format back to array of structs
if hasattr(field_data, "struct_arrays") and field_data.struct_arrays:
# Import here to avoid circular imports
from .entity_helper import extract_struct_array_from_column_data # noqa: PLC0415
row_data[field_data.field_name] = extract_struct_array_from_column_data(
field_data.struct_arrays, index
)
else:
row_data[field_data.field_name] = None
def __getitem__(self, index: Union[int, slice]):
if isinstance(index, slice):
results = []
for i in range(*index.indices(len(self))):
row = self[i]
results.append(row)
return results
if self._materialized_bitmap[index]:
return super().__getitem__(index)
self._pre_materialize_float_vector()
row = super().__getitem__(index)
for field_data in self._lazy_field_data:
self._extract_lazy_fields(index, field_data, row)
self._materialized_bitmap[index] = True
return row
def __iter__(self):
for i in range(len(self)):
yield self[i]
def __str__(self) -> str:
preview = [str(self[i]) for i in range(min(10, len(self)))]
return f"data: {preview}{' ...' if len(self) > 10 else ''}, extra_info: {self.extra}"
def _pre_materialize_float_vector(self):
if not self._strict_float32 or self._has_materialized_float_vector:
return
for field_data in self._lazy_field_data:
if field_data.type == DataType.FLOAT_VECTOR:
self._float_vector_np_array[field_data.field_name] = np.array(
field_data.vectors.float_vector.data, dtype=np.float32
)
self._has_materialized_float_vector = True
def materialize(self):
"""Materializes all lazy-loaded fields for all rows."""
for i in range(len(self)):
# By simply accessing the item, __getitem__ will trigger
# the one-time materialization logic if it hasn't been done yet.
_ = self[i]
return self
__repr__ = __str__
| HybridExtraList |
python | tornadoweb__tornado | tornado/iostream.py | {
"start": 61792,
"end": 63873
} | class ____(BaseIOStream):
"""Pipe-based `IOStream` implementation.
The constructor takes an integer file descriptor (such as one returned
by `os.pipe`) rather than an open file object. Pipes are generally
one-way, so a `PipeIOStream` can be used for reading or writing but not
both.
``PipeIOStream`` is only available on Unix-based platforms.
"""
def __init__(self, fd: int, *args: Any, **kwargs: Any) -> None:
self.fd = fd
self._fio = io.FileIO(self.fd, "r+")
if sys.platform == "win32":
# The form and placement of this assertion is important to mypy.
# A plain assert statement isn't recognized here. If the assertion
# were earlier it would worry that the attributes of self aren't
# set on windows. If it were missing it would complain about
# the absence of the set_blocking function.
raise AssertionError("PipeIOStream is not supported on Windows")
os.set_blocking(fd, False)
super().__init__(*args, **kwargs)
def fileno(self) -> int:
return self.fd
def close_fd(self) -> None:
self._fio.close()
def write_to_fd(self, data: memoryview) -> int:
try:
return os.write(self.fd, data) # type: ignore
finally:
# Avoid keeping to data, which can be a memoryview.
# See https://github.com/tornadoweb/tornado/pull/2008
del data
def read_from_fd(self, buf: Union[bytearray, memoryview]) -> Optional[int]:
try:
return self._fio.readinto(buf) # type: ignore
except OSError as e:
if errno_from_exception(e) == errno.EBADF:
# If the writing half of a pipe is closed, select will
# report it as readable but reads will fail with EBADF.
self.close(exc_info=e)
return None
else:
raise
finally:
del buf
def doctests() -> Any:
import doctest
return doctest.DocTestSuite()
| PipeIOStream |
python | getsentry__sentry | src/sentry/incidents/logic.py | {
"start": 5151,
"end": 10690
} | class ____(Exception):
pass
def create_incident(
organization: Organization,
incident_type: IncidentType,
title: str,
date_started: datetime,
date_detected: datetime | None = None,
detection_uuid: UUID | None = None, # TODO: Probably remove detection_uuid?
projects: Collection[Project] = (),
user: RpcUser | None = None,
alert_rule: AlertRule | None = None,
subscription: QuerySubscription | None = None,
) -> Incident:
if date_detected is None:
date_detected = date_started
with transaction.atomic(router.db_for_write(Incident)):
incident = Incident.objects.create(
organization=organization,
detection_uuid=detection_uuid,
status=IncidentStatus.OPEN.value,
type=incident_type.value,
title=title,
date_started=date_started,
date_detected=date_detected,
alert_rule=alert_rule,
subscription=subscription,
)
if projects:
incident_projects = [
IncidentProject(incident=incident, project=project) for project in projects
]
IncidentProject.objects.bulk_create(incident_projects)
# `bulk_create` doesn't send `post_save` signals, so we manually fire them here.
for incident_project in incident_projects:
post_save.send_robust(
sender=type(incident_project),
instance=incident_project,
created=True,
)
create_incident_activity(
incident, IncidentActivityType.DETECTED, user=user, date_added=date_started
)
create_incident_activity(incident, IncidentActivityType.CREATED, user=user)
try:
analytics.record(
IncidentCreatedEvent(
incident_id=incident.id,
organization_id=incident.organization_id,
incident_type=incident_type.value,
)
)
except Exception as e:
sentry_sdk.capture_exception(e)
return incident
def update_incident_status(
incident: Incident,
status: IncidentStatus,
status_method: IncidentStatusMethod = IncidentStatusMethod.RULE_TRIGGERED,
date_closed: datetime | None = None,
) -> Incident:
"""
Updates the status of an Incident and write an IncidentActivity row to log
the change. When the status is CLOSED we also set the date closed to the
current time and take a snapshot of the current incident state.
"""
if incident.status == status.value:
# If the status isn't actually changing just no-op.
return incident
with transaction.atomic(router.db_for_write(Incident)):
create_incident_activity(
incident,
IncidentActivityType.STATUS_CHANGE,
value=status.value,
previous_value=incident.status,
)
prev_status = incident.status
kwargs: dict[str, Any] = {
"status": status.value,
"status_method": status_method.value,
}
if status == IncidentStatus.CLOSED:
kwargs["date_closed"] = date_closed if date_closed else django_timezone.now()
elif status == IncidentStatus.OPEN:
# If we're moving back out of closed status then unset the closed
# date
kwargs["date_closed"] = None
incident.update(**kwargs)
try:
analytics.record(
IncidentStatusUpdatedEvent(
incident_id=incident.id,
organization_id=incident.organization_id,
incident_type=incident.type,
prev_status=prev_status,
status=incident.status,
)
)
except Exception as e:
sentry_sdk.capture_exception(e)
if status == IncidentStatus.CLOSED and (
status_method == IncidentStatusMethod.MANUAL
or status_method == IncidentStatusMethod.RULE_UPDATED
):
_trigger_incident_triggers(incident)
return incident
@transaction.atomic(router.db_for_write(Incident))
def create_incident_activity(
incident: Incident,
activity_type: IncidentActivityType,
user: RpcUser | User | None = None,
value: str | int | None = None,
previous_value: str | int | None = None,
date_added: datetime | None = None,
) -> IncidentActivity:
value = str(value) if value is not None else None
previous_value = str(previous_value) if previous_value is not None else None
kwargs = {}
if date_added:
kwargs["date_added"] = date_added
activity = IncidentActivity.objects.create(
incident=incident,
type=activity_type.value,
user_id=user.id if user else None,
value=value,
previous_value=previous_value,
notification_uuid=uuid4(),
**kwargs,
)
return activity
def _unpack_snuba_query(alert_rule: AlertRule) -> SnubaQuery:
snuba_query = alert_rule.snuba_query
if snuba_query is None:
raise ValueError("The alert rule must have a non-null snuba_query")
return snuba_query
def _unpack_organization(alert_rule: AlertRule) -> Organization:
organization = alert_rule.organization
if organization is None:
raise ValueError("The alert rule must have a non-null organization")
return organization
@dataclass
| ChannelLookupTimeoutError |
python | keon__algorithms | tests/test_histogram.py | {
"start": 79,
"end": 460
} | class ____(unittest.TestCase):
def test_histogram(self):
list_1 = [3, 3, 2, 1]
list_2 = [2, 3, 5, 5, 5, 6, 4, 3, 7]
self.assertEqual(get_histogram(list_1), {1: 1, 2: 1, 3: 2})
self.assertEqual(get_histogram(list_2),
{2: 1, 3: 2, 4: 1, 5: 3, 6: 1, 7: 1})
if __name__ == '__main__':
unittest.main()
| TestListsInHistogram |
python | google__pytype | pytype/tests/test_typeguard.py | {
"start": 2417,
"end": 4820
} | class ____(test_base.BaseTest):
"""Tests for TypeGuard in pyi files."""
@test_utils.skipBeforePy((3, 10), "New in 3.10")
def test_infer(self):
ty = self.Infer("""
from typing import TypeGuard
def f(x: object) -> TypeGuard[int]:
return isinstance(x, int)
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import TypeGuard
def f(x: object) -> TypeGuard[int]: ...
""",
)
def test_infer_extension(self):
ty = self.Infer("""
from typing_extensions import TypeGuard
def f(x: object) -> TypeGuard[int]:
return isinstance(x, int)
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import TypeGuard
def f(x: object) -> TypeGuard[int]: ...
""",
)
def test_import(self):
with self.DepTree([(
"foo.pyi",
"""
from typing import TypeGuard
def f(x: object) -> TypeGuard[int]: ...
""",
)]):
self.Check("""
import foo
def f(x: object):
if foo.f(x):
assert_type(x, int)
""")
def test_import_extension(self):
with self.DepTree([(
"foo.pyi",
"""
from typing_extensions import TypeGuard
def f(x: object) -> TypeGuard[int]: ...
""",
)]):
self.Check("""
import foo
def f(x: object):
if foo.f(x):
assert_type(x, int)
""")
def test_generic(self):
with self.DepTree([(
"foo.pyi",
"""
from typing import Optional, TypeGuard, TypeVar
T = TypeVar('T')
def f(x: Optional[int]) -> TypeGuard[int]: ...
""",
)]):
self.Check("""
import foo
from typing import Optional
def f(x: Optional[int]):
if foo.f(x):
assert_type(x, int)
""")
def test_non_variable(self):
with self.DepTree([(
"foo.pyi",
"""
from typing import TypeGuard
def f(x) -> TypeGuard[int]: ...
""",
)]):
errors = self.CheckWithErrors("""
import foo
from typing import Dict
def f(x: Dict[str, object]):
print(foo.f(x['k'])) # not-supported-yet[e]
""")
self.assertErrorSequences(
errors,
{"e": ["TypeGuard function 'foo.f' with an arbitrary expression"]},
)
@test_utils.skipBeforePy((3, 10), "New in 3.10")
| PyiTest |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0127_default_to_semver.py | {
"start": 149,
"end": 3424
} | class ____(migrations.Migration):
safe = Safe.always()
dependencies = [
("projects", "0126_alter_remote_repository_description"),
]
operations = [
migrations.AlterField(
model_name="addonsconfig",
name="flyout_sorting",
field=models.CharField(
choices=[
("alphabetically", "Alphabetically"),
("semver-readthedocs-compatible", "SemVer (Read the Docs)"),
("python-packaging", "Python Packaging (PEP 440 and PEP 425)"),
("calver", "CalVer (YYYY.0M.0M)"),
("custom-pattern", "Define your own pattern"),
],
default="semver-readthedocs-compatible",
max_length=64,
verbose_name="Sorting of versions",
),
),
migrations.AlterField(
model_name="addonsconfig",
name="flyout_sorting_custom_pattern",
field=models.CharField(
blank=True,
default=None,
help_text='Sorting pattern supported by BumpVer (<a href="https://github.com/mbarkhau/bumpver#pattern-examples">See examples</a>)',
max_length=32,
null=True,
verbose_name="Custom version sorting pattern",
),
),
migrations.AlterField(
model_name="addonsconfig",
name="flyout_sorting_latest_stable_at_beginning",
field=models.BooleanField(
default=True,
verbose_name="Show <code>latest</code> and <code>stable</code> at the beginning",
),
),
migrations.AlterField(
model_name="historicaladdonsconfig",
name="flyout_sorting",
field=models.CharField(
choices=[
("alphabetically", "Alphabetically"),
("semver-readthedocs-compatible", "SemVer (Read the Docs)"),
("python-packaging", "Python Packaging (PEP 440 and PEP 425)"),
("calver", "CalVer (YYYY.0M.0M)"),
("custom-pattern", "Define your own pattern"),
],
default="semver-readthedocs-compatible",
max_length=64,
verbose_name="Sorting of versions",
),
),
migrations.AlterField(
model_name="historicaladdonsconfig",
name="flyout_sorting_custom_pattern",
field=models.CharField(
blank=True,
default=None,
help_text='Sorting pattern supported by BumpVer (<a href="https://github.com/mbarkhau/bumpver#pattern-examples">See examples</a>)',
max_length=32,
null=True,
verbose_name="Custom version sorting pattern",
),
),
migrations.AlterField(
model_name="historicaladdonsconfig",
name="flyout_sorting_latest_stable_at_beginning",
field=models.BooleanField(
default=True,
verbose_name="Show <code>latest</code> and <code>stable</code> at the beginning",
),
),
]
| Migration |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 22671,
"end": 22851
} | class ____:
partition_data: Sequence[PartitionExecutionParamSnap]
@whitelist_for_serdes(storage_name="ExternalPartitionExecutionErrorData")
@record
| PartitionSetExecutionParamSnap |
python | pytorch__pytorch | torch/_inductor/mkldnn_ir.py | {
"start": 29689,
"end": 31379
} | class ____(ExternKernelAlloc):
kernel = "torch.ops.mkldnn._linear_pointwise.binary"
def __init__(
self,
layout,
inputs,
constant_args=(),
) -> None:
self.device_type = get_device_type(inputs[0])
super().__init__(
layout,
inputs,
constant_args,
None,
op_overload=torch.ops.mkldnn._linear_pointwise.binary,
cpp_kernel_name=f"aoti_torch_{self.device_type}__linear_pointwise_binary",
)
def codegen(self, wrapper):
wrapper.include_extra_header(
f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h"
)
super().codegen(wrapper)
@classmethod
def create(cls, x, y, w, B, attr):
x = cls.require_contiguous(cls.realize_input(x))
y = cls.require_contiguous(cls.realize_input(y))
w = cls.require_contiguous(cls.realize_input(w))
*m, _ic = x.get_size()
oc, _ic = w.get_size()
output_size = list(m) + [oc]
inputs = [x, y, w]
constant_args = [attr]
if B is not None:
B = cls.require_contiguous(cls.realize_input(B))
inputs.append(B)
else:
constant_args.insert(0, B)
device = x.get_device()
assert device is not None
packed = LinearBinary(
layout=FixedLayout(
device=device,
dtype=x.get_dtype(),
size=output_size,
),
inputs=inputs,
constant_args=constant_args,
)
return _create_output_node(packed)
def apply_constraint(self):
pass
| LinearBinary |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/providers.py | {
"start": 880,
"end": 1023
} | class ____(BaseModel):
"""Provider serializer for responses."""
package_name: str
description: str
version: str
| ProviderResponse |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 8326,
"end": 8486
} | class ____(DagsterError):
"""Thrown when an expected execution plan snapshot could not be found on a PipelineRun."""
| DagsterExecutionPlanSnapshotNotFoundError |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 22015,
"end": 23529
} | class ____(IDict): # docs-only interface
"""
An ordered dictionary that can have multiple values for each key. A
multidict adds the methods ``getall``, ``getone``, ``mixed``, ``extend``,
``add``, and ``dict_of_lists`` to the normal dictionary interface. A
multidict data structure is used as ``request.POST``, ``request.GET``,
and ``request.params`` within an :app:`Pyramid` application.
"""
def add(key, value):
"""Add the key and value, not overwriting any previous value."""
def dict_of_lists():
"""
Returns a dictionary where each key is associated with a list of
values.
"""
def extend(other=None, **kwargs):
"""Add a set of keys and values, not overwriting any previous
values. The ``other`` structure may be a list of two-tuples or a
dictionary. If ``**kwargs`` is passed, its value *will* overwrite
existing values."""
def getall(key):
"""Return a list of all values matching the key (may be an empty
list)"""
def getone(key):
"""Get one value matching the key, raising a KeyError if multiple
values were found."""
def mixed():
"""Returns a dictionary where the values are either single values,
or a list of values when a key/value appears more than once in this
dictionary. This is similar to the kind of dictionary often used to
represent the variables in a web request."""
# internal interfaces
| IMultiDict |
python | PrefectHQ__prefect | tests/runtime/test_task_run.py | {
"start": 5169,
"end": 5566
} | class ____:
async def test_task_name_is_attribute(self):
assert "task_name" in dir(task_run)
async def test_task_name_is_none_when_not_set(self):
assert task_run.task_name is None
async def test_task_name_from_context(self):
with TaskRunContext.model_construct(task=Task(fn=lambda: None, name="foo")):
assert task_run.task_name == "foo"
| TestTaskName |
python | nedbat__coveragepy | tests/test_plugins.py | {
"start": 10875,
"end": 11682
} | class ____(CoverageTest):
"""Test that we get a controlled exception when plugins aren't supported."""
def test_exception_if_plugins_on_pytracer(self) -> None:
self.make_file("simple.py", "a = 1")
cov = coverage.Coverage()
cov.set_option("run:plugins", ["tests.plugin1"])
if testenv.PY_TRACER:
core = "PyTracer"
else:
assert testenv.SYS_MON
core = "SysMonitor"
expected_warnings = [
rf"Plugin file tracers \(tests.plugin1.Plugin\) aren't supported with {core}",
]
with self.assert_warnings(cov, expected_warnings):
self.start_import_stop(cov, "simple")
@pytest.mark.skipif(not testenv.PLUGINS, reason="Plugins are not supported with this core.")
| PluginWarningOnPyTracerTest |
python | pandas-dev__pandas | pandas/tests/indexes/string/test_indexing.py | {
"start": 437,
"end": 1672
} | class ____:
def test_get_loc(self, any_string_dtype):
index = Index(["a", "b", "c"], dtype=any_string_dtype)
assert index.get_loc("b") == 1
def test_get_loc_raises(self, any_string_dtype):
index = Index(["a", "b", "c"], dtype=any_string_dtype)
with pytest.raises(KeyError, match="d"):
index.get_loc("d")
def test_get_loc_invalid_value(self, any_string_dtype):
index = Index(["a", "b", "c"], dtype=any_string_dtype)
with pytest.raises(KeyError, match="1"):
index.get_loc(1)
def test_get_loc_non_unique(self, any_string_dtype):
index = Index(["a", "b", "a"], dtype=any_string_dtype)
result = index.get_loc("a")
expected = np.array([True, False, True])
tm.assert_numpy_array_equal(result, expected)
def test_get_loc_non_missing(self, any_string_dtype, nulls_fixture):
index = Index(["a", "b", "c"], dtype=any_string_dtype)
with pytest.raises(KeyError):
index.get_loc(nulls_fixture)
def test_get_loc_missing(self, any_string_dtype, nulls_fixture):
index = Index(["a", "b", nulls_fixture], dtype=any_string_dtype)
assert index.get_loc(nulls_fixture) == 2
| TestGetLoc |
python | pypa__setuptools | setuptools/tests/test_editable_install.py | {
"start": 36418,
"end": 37806
} | class ____:
"""
Issue #3501 indicates that some plugins/customizations might rely on:
1. ``build_py`` not running
2. ``build_py`` always copying files to ``build_lib``
During the transition period setuptools should prevent potential errors from
happening due to those assumptions.
"""
# TODO: Remove tests after _run_build_steps is removed.
FILES = {
**TestOverallBehaviour.EXAMPLES["flat-layout"],
"setup.py": dedent(
"""\
import pathlib
from setuptools import setup
from setuptools.command.build_py import build_py as orig
class my_build_py(orig):
def run(self):
super().run()
raise ValueError("TEST_RAISE")
setup(cmdclass={"build_py": my_build_py})
"""
),
}
def test_safeguarded_from_errors(self, tmp_path, venv):
"""Ensure that errors in custom build_py are reported as warnings"""
# Warnings should show up
_, out = install_project("mypkg", venv, tmp_path, self.FILES)
assert "SetuptoolsDeprecationWarning" in out
assert "ValueError: TEST_RAISE" in out
# but installation should be successful
out = venv.run(["python", "-c", "import mypkg.mod1; print(mypkg.mod1.var)"])
assert "42" in out
| TestCustomBuildPy |
python | jina-ai__jina | jina/importer.py | {
"start": 5543,
"end": 6425
} | class ____:
"""The class to import modules from paths."""
@staticmethod
def add_modules(*paths):
"""
Import modules from paths.
:param paths: Paths of the modules.
"""
# assume paths are Python module names
not_python_module_paths = []
for path in paths:
if not os.path.isfile(path):
try:
importlib.import_module(path)
except ModuleNotFoundError:
not_python_module_paths.append(path)
except:
raise
else:
not_python_module_paths.append(path)
# try again, but assume they are file paths instead of module names
from jina.jaml.helper import complete_path
for m in not_python_module_paths:
_path_import(complete_path(m))
| PathImporter |
python | huggingface__transformers | src/transformers/models/roc_bert/modeling_roc_bert.py | {
"start": 18069,
"end": 18723
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->RoCBert
| RoCBertIntermediate |
python | pennersr__django-allauth | allauth/socialaccount/providers/oauth/provider.py | {
"start": 487,
"end": 3324
} | class ____(Provider):
supports_redirect = True
def get_login_url(self, request, **kwargs):
url = reverse(self.id + "_login")
if kwargs:
url = url + "?" + urlencode(kwargs)
return url
def get_auth_params(self):
settings = self.get_settings()
ret = dict(settings.get("AUTH_PARAMS", {}))
return ret
def get_auth_params_from_request(self, request, action):
ret = self.get_auth_params()
dynamic_auth_params = request.GET.get("auth_params", None)
if dynamic_auth_params:
ret.update(dict(parse_qsl(dynamic_auth_params)))
return ret
def get_auth_url(self, request, action):
# TODO: This is ugly. Move authorization_url away from the
# adapter into the provider. Hmpf, the line between
# adapter/provider is a bit too thin here.
return None
def get_scope_from_request(self, request):
return self.get_scope()
def get_scope(self):
settings = self.get_settings()
scope = settings.get("SCOPE")
if scope is None:
scope = self.get_default_scope()
return scope
def get_default_scope(self):
return []
def get_oauth_adapter(self, request):
if not hasattr(self, "oauth_adapter_class"):
raise ImproperlyConfigured(f"No oauth_adapter_class set for {self!r}")
return self.oauth_adapter_class(request)
def get_redirect_from_request_kwargs(self, request):
kwargs = super().get_redirect_from_request_kwargs(request)
kwargs["scope"] = self.get_scope_from_request(request)
action = request.GET.get("action", AuthAction.AUTHENTICATE)
kwargs["action"] = action
kwargs["auth_params"] = self.get_auth_params_from_request(request, action)
return kwargs
def redirect(self, request, process, next_url=None, data=None, **kwargs):
callback_url = reverse(self.id + "_callback")
oauth_adapter = self.get_oauth_adapter(request)
action = kwargs.pop("action", AuthAction.AUTHENTICATE)
auth_url = self.get_auth_url(request, action) or oauth_adapter.authorize_url
auth_params = kwargs.pop("auth_params", None)
if auth_params is None:
auth_params = self.get_auth_params()
scope = kwargs.pop("scope", None)
if scope is None:
scope = self.get_scope()
self.stash_redirect_state(request, process, next_url, data, **kwargs)
client = oauth_adapter._get_client(request, callback_url, scope=scope)
try:
return client.get_redirect(auth_url, auth_params)
except OAuthError as e:
logger.error("OAuth authentication error", exc_info=True)
return render_authentication_error(request, self, exception=e)
| OAuthProvider |
python | redis__redis-py | redis/exceptions.py | {
"start": 4820,
"end": 5168
} | class ____(RedisClusterException):
"""
This error only happens in the case where the connection pool will try to
fetch what node that is covered by a given slot.
If this error is raised the client should drop the current node layout and
attempt to reconnect and refresh the node layout again
"""
pass
| SlotNotCoveredError |
python | scrapy__scrapy | tests/test_utils_signal.py | {
"start": 3903,
"end": 4378
} | class ____:
def test_error_logged_if_deferred_not_supported(self):
def test_handler():
return defer.Deferred()
test_signal = object()
dispatcher.connect(test_handler, test_signal)
with LogCapture() as log:
send_catch_log(test_signal)
assert len(log.records) == 1
assert "Cannot return deferreds from signal handler" in str(log)
dispatcher.disconnect(test_handler, test_signal)
| TestSendCatchLog2 |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 50413,
"end": 74052
} | class ____(Request):
"""
Create a new dataview
:param name: Dataview name
:type name: str
:param description: Dataview description
:type description: str
:param project: Project ID of the project to which this task is assigned
:type project: str
:param filters: List of FilterRule ('OR' connection)
:type filters: Sequence[FilterRule]
:param output_rois: 'all_in_frame' - all rois for a frame are returned
'only_filtered' - only rois which led this frame to be selected 'frame_per_roi'
- single roi per frame. Frame can be returned multiple times with a different
roi each time. Note: this should be used for Training tasks only Note:
frame_per_roi implies that only filtered rois will be returned
:type output_rois: OutputRoisEnum
:param versions: List of dataview entries. All tasks must have at least one
dataview.
:type versions: Sequence[DataviewEntry]
:param iteration: Iteration parameters. Not applicable for register (import)
tasks.
:type iteration: Iteration
:param augmentation: Augmentation parameters. Only for training and testing
tasks.
:type augmentation: Augmentation
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: System tags list. This field is reserved for system use,
please don't use it.
:type system_tags: Sequence[str]
:param mapping: Mapping parameters
:type mapping: Mapping
:param labels_enumeration: Labels enumerations, specifies numbers to be
assigned to ROI labels when getting frames
:type labels_enumeration: dict
:param status: Dataview status
:type status: str
"""
_service = "dataviews"
_action = "create"
_version = "2.23"
_schema = {
"definitions": {
"augmentation": {
"properties": {
"crop_around_rois": {
"description": "Crop image data around all frame ROIs",
"type": ["boolean", "null"],
},
"sets": {
"description": "List of augmentation sets",
"items": {"$ref": "#/definitions/augmentation_set"},
"type": ["array", "null"],
},
},
"type": "object",
},
"augmentation_set": {
"properties": {
"arguments": {
"additionalProperties": {
"additionalProperties": True,
"type": "object",
},
"description": "Arguments dictionary per custom augmentation type.",
"type": ["object", "null"],
},
"cls": {
"description": "Augmentation class",
"type": ["string", "null"],
},
"strength": {
"description": "Augmentation strength. Range [0,).",
"minimum": 0,
"type": ["number", "null"],
},
"types": {
"description": "Augmentation type",
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"type": "object",
},
"dataview_entry": {
"properties": {
"dataset": {
"description": "Existing Dataset id",
"type": "string",
},
"merge_with": {
"description": "Version ID to merge with",
"type": "string",
},
"version": {
"description": "Version id of a version belonging to the dataset",
"type": "string",
},
},
"required": ["dataset", "version"],
"type": "object",
},
"filter_by_roi_enum": {
"default": "label_rules",
"enum": ["disabled", "no_rois", "label_rules"],
"type": "string",
},
"filter_label_rule": {
"properties": {
"conf_range": {
"description": (
"Range of ROI confidence level in the frame (min, max). -1 for not applicable\n "
" Both min and max can be either -1 or positive.\n 2nd number (max) must be"
" either -1 or larger than or equal to the 1st number (min)"
),
"items": {"type": "number"},
"maxItems": 2,
"minItems": 1,
"type": "array",
},
"count_range": {
"description": (
"Range of times ROI appears in the frame (min, max). -1 for not applicable.\n "
" Both integers must be larger than or equal to -1.\n 2nd integer (max) must be"
" either -1 or larger than or equal to the 1st integer (min)"
),
"items": {"type": "integer"},
"maxItems": 2,
"minItems": 1,
"type": "array",
},
"label": {
"description": (
"Lucene format query (see lucene query syntax).\nDefault search field is label.keyword and"
" default operator is AND, so searching for:\n\n'Bus Stop' Blue\n\nis equivalent"
" to:\n\nLabel.keyword:'Bus Stop' AND label.keyword:'Blue'"
),
"type": "string",
},
"must_not": {
"default": False,
"description": (
"If set then the label must not exist or lucene query must not be true.\n The"
" default value is false"
),
"type": "boolean",
},
},
"required": ["label"],
"type": "object",
},
"filter_rule": {
"properties": {
"dataset": {
"description": (
"Dataset ID. Must be a dataset which is in the task's view. If set to '*' all datasets in"
" View are used."
),
"type": "string",
},
"filter_by_roi": {
"description": "Type of filter. Optional, the default value is 'label_rules'",
"oneOf": [
{"$ref": "#/definitions/filter_by_roi_enum"},
{"type": "null"},
],
},
"frame_query": {
"description": "Frame filter, in Lucene query syntax",
"type": ["string", "null"],
},
"label_rules": {
"description": (
"List of FilterLabelRule ('AND' connection)\n\ndisabled - No filtering by ROIs. Select all"
" frames, even if they don't have ROIs (all frames)\n\nno_rois - Select only frames without"
" ROIs (empty frames)\n\nlabel_rules - Select frames according to label rules"
),
"items": {"$ref": "#/definitions/filter_label_rule"},
"type": ["array", "null"],
},
"sources_query": {
"description": "Sources filter, in Lucene query syntax. Filters sources in each frame.",
"type": ["string", "null"],
},
"version": {
"description": (
"Dataset version to apply rule to. Must belong to the dataset and be in the task's view. If"
" set to '*' all version of the datasets in View are used."
),
"type": "string",
},
"weight": {
"description": "Rule weight. Default is 1",
"type": "number",
},
},
"required": ["dataset"],
"type": "object",
},
"iteration": {
"description": "Sequential Iteration API configuration",
"properties": {
"infinite": {
"description": "Infinite iteration",
"type": ["boolean", "null"],
},
"jump": {
"description": "Jump entry",
"oneOf": [{"$ref": "#/definitions/jump"}, {"type": "null"}],
},
"limit": {
"description": (
"Maximum frames per task. If not passed, frames will end when no more matching frames are"
" found, unless infinite is True."
),
"type": ["integer", "null"],
},
"min_sequence": {
"description": (
"Length (in ms) of video clips to return. This is used in random order, and in sequential"
" order only if jumping is provided and only for video frames"
),
"type": ["integer", "null"],
},
"order": {
"description": (
"\n Input frames order. Values: 'sequential', 'random'\n In"
" Sequential mode frames will be returned according to the order in which the frames were"
" added to the dataset."
),
"oneOf": [
{"$ref": "#/definitions/iteration_order_enum"},
{"type": "null"},
],
},
"random_seed": {
"description": "Random seed used when iterating over the dataview",
"type": ["integer", "null"],
},
},
"type": "object",
},
"iteration_order_enum": {
"enum": ["sequential", "random"],
"type": "string",
},
"jump": {
"properties": {
"time": {
"description": "Max time in milliseconds between frames",
"type": ["integer", "null"],
}
},
"type": "object",
},
"label_source": {
"properties": {
"dataset": {
"description": "Source dataset id. '*' for all datasets in view",
"type": ["string", "null"],
},
"labels": {
"description": (
"List of source labels (AND connection). '*' indicates any label. Labels must exist in at"
" least one of the dataset versions in the task's view"
),
"items": {"type": "string"},
"type": ["array", "null"],
},
"version": {
"description": (
"Source dataset version id. Default is '*' (for all versions in dataset in the view)"
" Version must belong to the selected dataset, and must be in the task's view[i]"
),
"type": ["string", "null"],
},
},
"type": "object",
},
"mapping": {
"properties": {
"rules": {
"description": "Rules list",
"items": {"$ref": "#/definitions/mapping_rule"},
"type": ["array", "null"],
}
},
"type": "object",
},
"mapping_rule": {
"properties": {
"source": {
"description": "Source label info",
"oneOf": [
{"$ref": "#/definitions/label_source"},
{"type": "null"},
],
},
"target": {
"description": "Target label name",
"type": ["string", "null"],
},
},
"type": "object",
},
"output_rois_enum": {
"enum": ["all_in_frame", "only_filtered", "frame_per_roi"],
"type": "string",
},
},
"properties": {
"augmentation": {
"$ref": "#/definitions/augmentation",
"description": "Augmentation parameters. Only for training and testing tasks.",
},
"description": {"description": "Dataview description", "type": "string"},
"filters": {
"description": "List of FilterRule ('OR' connection)",
"items": {"$ref": "#/definitions/filter_rule"},
"type": "array",
},
"iteration": {
"$ref": "#/definitions/iteration",
"description": "Iteration parameters. Not applicable for register (import) tasks.",
},
"labels_enumeration": {
"additionalProperties": {"type": "integer"},
"description": (
"Labels enumerations, specifies numbers to be assigned to ROI labels when getting frames"
),
"type": "object",
},
"mapping": {
"$ref": "#/definitions/mapping",
"description": "Mapping parameters",
},
"name": {"description": "Dataview name", "type": "string"},
"output_rois": {
"$ref": "#/definitions/output_rois_enum",
"default": "all_in_frame",
"description": (
"'all_in_frame' - all rois for a frame are returned\n 'only_filtered' - only"
" rois which led this frame to be selected\n 'frame_per_roi' - single roi per"
" frame. Frame can be returned multiple times with a different roi each time.\n "
" Note: this should be used for Training tasks only\n Note: frame_per_roi"
" implies that only filtered rois will be returned\n "
),
},
"project": {
"description": "Project ID of the project to which this task is assigned",
"type": "string",
},
"status": {
"description": "Dataview status",
"enum": ["draft", "published"],
"type": "string",
},
"system_tags": {
"description": "System tags list. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": "array",
},
"tags": {
"description": "User-defined tags list",
"items": {"type": "string"},
"type": "array",
},
"versions": {
"description": "List of dataview entries. All tasks must have at least one dataview.",
"items": {"$ref": "#/definitions/dataview_entry"},
"type": "array",
},
},
"required": ["name"],
"type": "object",
}
def __init__(
self,
name,
description=None,
project=None,
filters=None,
output_rois="all_in_frame",
versions=None,
iteration=None,
augmentation=None,
tags=None,
system_tags=None,
mapping=None,
labels_enumeration=None,
status=None,
**kwargs
):
super(CreateRequest, self).__init__(**kwargs)
self.name = name
self.description = description
self.project = project
self.filters = filters
self.output_rois = output_rois
self.versions = versions
self.iteration = iteration
self.augmentation = augmentation
self.tags = tags
self.system_tags = system_tags
self.mapping = mapping
self.labels_enumeration = labels_enumeration
self.status = status
@schema_property("name")
def name(self):
return self._property_name
@name.setter
def name(self, value):
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("description")
def description(self):
return self._property_description
@description.setter
def description(self, value):
if value is None:
self._property_description = None
return
self.assert_isinstance(value, "description", six.string_types)
self._property_description = value
@schema_property("project")
def project(self):
return self._property_project
@project.setter
def project(self, value):
if value is None:
self._property_project = None
return
self.assert_isinstance(value, "project", six.string_types)
self._property_project = value
@schema_property("filters")
def filters(self):
return self._property_filters
@filters.setter
def filters(self, value):
if value is None:
self._property_filters = None
return
self.assert_isinstance(value, "filters", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [
FilterRule.from_dict(v) if isinstance(v, dict) else v for v in value
]
else:
self.assert_isinstance(value, "filters", FilterRule, is_array=True)
self._property_filters = value
@schema_property("output_rois")
def output_rois(self):
return self._property_output_rois
@output_rois.setter
def output_rois(self, value):
if value is None:
self._property_output_rois = None
return
if isinstance(value, six.string_types):
try:
value = OutputRoisEnum(value)
except ValueError:
pass
else:
self.assert_isinstance(value, "output_rois", enum.Enum)
self._property_output_rois = value
@schema_property("versions")
def versions(self):
return self._property_versions
@versions.setter
def versions(self, value):
if value is None:
self._property_versions = None
return
self.assert_isinstance(value, "versions", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [
DataviewEntry.from_dict(v) if isinstance(v, dict) else v for v in value
]
else:
self.assert_isinstance(value, "versions", DataviewEntry, is_array=True)
self._property_versions = value
@schema_property("iteration")
def iteration(self):
return self._property_iteration
@iteration.setter
def iteration(self, value):
if value is None:
self._property_iteration = None
return
if isinstance(value, dict):
value = Iteration.from_dict(value)
else:
self.assert_isinstance(value, "iteration", Iteration)
self._property_iteration = value
@schema_property("augmentation")
def augmentation(self):
return self._property_augmentation
@augmentation.setter
def augmentation(self, value):
if value is None:
self._property_augmentation = None
return
if isinstance(value, dict):
value = Augmentation.from_dict(value)
else:
self.assert_isinstance(value, "augmentation", Augmentation)
self._property_augmentation = value
@schema_property("tags")
def tags(self):
return self._property_tags
@tags.setter
def tags(self, value):
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self):
return self._property_system_tags
@system_tags.setter
def system_tags(self, value):
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("mapping")
def mapping(self):
return self._property_mapping
@mapping.setter
def mapping(self, value):
if value is None:
self._property_mapping = None
return
if isinstance(value, dict):
value = Mapping.from_dict(value)
else:
self.assert_isinstance(value, "mapping", Mapping)
self._property_mapping = value
@schema_property("labels_enumeration")
def labels_enumeration(self):
return self._property_labels_enumeration
@labels_enumeration.setter
def labels_enumeration(self, value):
if value is None:
self._property_labels_enumeration = None
return
self.assert_isinstance(value, "labels_enumeration", (dict,))
self._property_labels_enumeration = value
@schema_property("status")
def status(self):
return self._property_status
@status.setter
def status(self, value):
if value is None:
self._property_status = None
return
self.assert_isinstance(value, "status", six.string_types)
self._property_status = value
| CreateRequest |
python | pallets__click | tests/test_utils.py | {
"start": 21225,
"end": 23735
} | class ____:
__slots__ = "__package__"
def __init__(self, package_name):
self.__package__ = package_name
@pytest.mark.parametrize(
("path", "main", "expected"),
[
("example.py", None, "example.py"),
(str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),
("example", None, "example"),
(str(pathlib.Path("example/__main__.py")), "example", "python -m example"),
(str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),
(str(pathlib.Path("./example")), "", "example"),
],
)
def test_detect_program_name(path, main, expected):
assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected
def test_expand_args(monkeypatch):
user = os.path.expanduser("~")
assert user in click.utils._expand_args(["~"])
monkeypatch.setenv("CLICK_TEST", "hello")
assert "hello" in click.utils._expand_args(["$CLICK_TEST"])
assert "pyproject.toml" in click.utils._expand_args(["*.toml"])
assert os.path.join("tests", "conftest.py") in click.utils._expand_args(
["**/conftest.py"]
)
assert "*.not-found" in click.utils._expand_args(["*.not-found"])
# a bad glob pattern, such as a pytest identifier, should return itself
assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"
@pytest.mark.parametrize(
("value", "max_length", "expect"),
[
pytest.param("", 10, "", id="empty"),
pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),
pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),
pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),
pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),
pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),
pytest.param(
"token in ~/.netrc ciao ciao",
20,
"token in ~/.netrc...",
id="ignore dot in word",
),
],
)
@pytest.mark.parametrize(
"alter",
[
pytest.param(None, id=""),
pytest.param(
lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"
),
],
)
def test_make_default_short_help(value, max_length, alter, expect):
assert len(expect) <= max_length
if alter:
value = alter(value)
out = click.utils.make_default_short_help(value, max_length)
assert out == expect
| MockMain |
python | scipy__scipy | scipy/sparse/_lil.py | {
"start": 16732,
"end": 18801
} | class ____(_lil_base, sparray):
"""
Row-based LIst of Lists sparse array.
This is a structure for constructing sparse arrays incrementally.
Note that inserting a single item can take linear time in the worst case;
to construct the array efficiently, make sure the items are pre-sorted by
index, per row.
This can be instantiated in several ways:
lil_array(D)
where D is a 2-D ndarray
lil_array(S)
with another sparse array or matrix S (equivalent to S.tolil())
lil_array((M, N), [dtype])
to construct an empty array with shape (M, N)
dtype is optional, defaulting to dtype='d'.
Attributes
----------
dtype : dtype
Data type of the array
shape : 2-tuple
Shape of the array
ndim : int
Number of dimensions (this is always 2)
nnz
size
data
LIL format data array of the array
rows
LIL format row index array of the array
T
Notes
-----
Sparse arrays can be used in arithmetic operations: they support
addition, subtraction, multiplication, division, and matrix power.
Advantages of the LIL format
- supports flexible slicing
- changes to the array sparsity structure are efficient
Disadvantages of the LIL format
- arithmetic operations LIL + LIL are slow (consider CSR or CSC)
- slow column slicing (consider CSC)
- slow matrix vector products (consider CSR or CSC)
Intended Usage
- LIL is a convenient format for constructing sparse arrays
- once an array has been constructed, convert to CSR or
CSC format for fast arithmetic and matrix vector operations
- consider using the COO format when constructing large arrays
Data Structure
- An array (``self.rows``) of rows, each of which is a sorted
list of column indices of non-zero elements.
- The corresponding nonzero values are stored in similar
fashion in ``self.data``.
"""
| lil_array |
python | PrefectHQ__prefect | src/prefect/cli/flow_runs_watching.py | {
"start": 2300,
"end": 6797
} | class ____:
"""Handles formatting of logs and events for CLI display"""
def __init__(self):
self._last_timestamp_parts = ["", "", "", ""]
self._last_datetime: datetime | None = None
def format_timestamp(self, dt: datetime) -> str:
"""Format timestamp with incremental display"""
ms = dt.strftime("%f")[:3]
current_parts = [dt.strftime("%H"), dt.strftime("%M"), dt.strftime("%S"), ms]
if self._last_datetime and dt < self._last_datetime:
self._last_timestamp_parts = current_parts[:]
self._last_datetime = dt
return f"{current_parts[0]}:{current_parts[1]}:{current_parts[2]}.{current_parts[3]}"
display_parts = []
for i, (last, current) in enumerate(
zip(self._last_timestamp_parts, current_parts)
):
if current != last:
display_parts = current_parts[i:]
break
else:
display_parts = [current_parts[3]]
self._last_timestamp_parts = current_parts[:]
self._last_datetime = dt
if len(display_parts) == 4:
timestamp_str = f"{display_parts[0]}:{display_parts[1]}:{display_parts[2]}.{display_parts[3]}"
elif len(display_parts) == 3:
timestamp_str = f":{display_parts[0]}:{display_parts[1]}.{display_parts[2]}"
elif len(display_parts) == 2:
timestamp_str = f":{display_parts[0]}.{display_parts[1]}"
else:
timestamp_str = f".{display_parts[0]}"
return f"{timestamp_str:>12}"
def format_run_id(self, run_id_short: str) -> str:
"""Format run ID"""
return f"{run_id_short:>12}"
def format(self, item: Log | Event) -> str:
"""Format a log or event for display"""
if isinstance(item, Log):
return self.format_log(item)
else:
return self.format_event(item)
def format_log(self, log: Log) -> str:
"""Format a log entry"""
timestamp = self.format_timestamp(log.timestamp)
run_id = log.task_run_id or log.flow_run_id
run_id_short = str(run_id)[-12:] if run_id else "............"
run_id_display = self.format_run_id(run_id_short)
icon = "▪"
prefix_plain = f"{icon} {timestamp.strip()} {run_id_display.strip()} "
lines = log.message.split("\n")
if len(lines) == 1:
return f"[dim]▪[/dim] {timestamp} [dim]{run_id_display}[/dim] {log.message}"
first_line = f"[dim]▪[/dim] {timestamp} [dim]{run_id_display}[/dim] {lines[0]}"
indent = " " * len(prefix_plain)
continuation_lines = [f"{indent}{line}" for line in lines[1:]]
return first_line + "\n" + "\n".join(continuation_lines)
def format_event(self, event: Event) -> str:
"""Format an event"""
timestamp = self.format_timestamp(event.occurred)
run_id = None
if event.resource.id.startswith("prefect.task-run."):
run_id = event.resource.id.split(".", 2)[2]
elif event.resource.id.startswith("prefect.flow-run."):
run_id = event.resource.id.split(".", 2)[2]
if not run_id:
for related in event.related:
if related.id.startswith("prefect.task-run."):
run_id = related.id.split(".", 2)[2]
break
elif related.id.startswith("prefect.flow-run."):
run_id = related.id.split(".", 2)[2]
break
run_id_short = run_id[-12:] if run_id else "............"
run_id_display = self.format_run_id(run_id_short)
# Get state type from event resource or payload
state_type_str = event.resource.get("prefect.state-type")
if not state_type_str and "validated_state" in event.payload:
state_type_str = event.payload["validated_state"].get("type")
# Map state type to color
color = "bright_magenta" # default for unknown states
if state_type_str:
try:
state_type = StateType(state_type_str)
color = STATE_TYPE_COLORS.get(state_type, "bright_magenta")
except ValueError:
pass
name = event.resource.get("prefect.resource.name") or event.resource.id
return (
f"[{color}]●[/{color}] {timestamp} [dim]{run_id_display}[/dim] "
f"{event.event} * [bold cyan]{name}[/bold cyan]"
)
| FlowRunFormatter |
python | kamyu104__LeetCode-Solutions | Python/minimum-time-to-type-word-using-special-typewriter.py | {
"start": 29,
"end": 382
} | class ____(object):
def minTimeToType(self, word):
"""
:type word: str
:rtype: int
"""
return (min((ord(word[0])-ord('a'))%26, (ord('a')-ord(word[0]))%26)+1) + \
sum(min((ord(word[i])-ord(word[i-1]))%26, (ord(word[i-1])-ord(word[i]))%26)+1
for i in xrange(1, len(word)))
| Solution |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 23426,
"end": 23486
} | class ____(TopLevel):
__slots__ = ("name", "body")
| FlagDef |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constrainedTypeVar5.py | {
"start": 167,
"end": 961
} | class ____(Generic[T]):
def __init__(self, val: T):
self.val = val
Op = Callable[[MyData[T]], T]
def f_generic1(val: T, op: Op[T]) -> T:
obj = MyData[T](val)
return op(obj)
def f_generic2(val: T, op: Op[T]) -> T:
obj = MyData(val)
return op(obj)
def f_bool(val: bool) -> bool:
op: Op[bool] = lambda od: od.val
r = f_generic1(val, op)
return r
def f_generic3(val: T) -> T:
return val
def f_union(val: bool | str) -> None:
# This should generate an error because a
# union cannot be assigned to a constrained
# type variable.
f_generic3(val)
if isinstance(val, bool):
f_generic3(val)
else:
f_generic3(val)
def func1(v: T, t: type[T]):
print(t)
def func2(v: T, t: type[T]):
func1(v, t)
| MyData |
python | imageio__imageio | imageio/core/format.py | {
"start": 2396,
"end": 21366
} | class ____(object):
"""Represents an implementation to read/write a particular file format
A format instance is responsible for 1) providing information about
a format; 2) determining whether a certain file can be read/written
with this format; 3) providing a reader/writer class.
Generally, imageio will select the right format and use that to
read/write an image. A format can also be explicitly chosen in all
read/write functions. Use ``print(format)``, or ``help(format_name)``
to see its documentation.
To implement a specific format, one should create a subclass of
Format and the Format.Reader and Format.Writer classes. See
:class:`imageio.plugins` for details.
Parameters
----------
name : str
A short name of this format. Users can select a format using its name.
description : str
A one-line description of the format.
extensions : str | list | None
List of filename extensions that this format supports. If a
string is passed it should be space or comma separated. The
extensions are used in the documentation and to allow users to
select a format by file extension. It is not used to determine
what format to use for reading/saving a file.
modes : str
A string containing the modes that this format can handle ('iIvV'),
“i” for an image, “I” for multiple images, “v” for a volume,
“V” for multiple volumes.
This attribute is used in the documentation and to select the
formats when reading/saving a file.
"""
def __init__(self, name, description, extensions=None, modes=None):
"""Initialize the Plugin.
Parameters
----------
name : str
A short name of this format. Users can select a format using its name.
description : str
A one-line description of the format.
extensions : str | list | None
List of filename extensions that this format supports. If a
string is passed it should be space or comma separated. The
extensions are used in the documentation and to allow users to
select a format by file extension. It is not used to determine
what format to use for reading/saving a file.
modes : str
A string containing the modes that this format can handle ('iIvV'),
“i” for an image, “I” for multiple images, “v” for a volume,
“V” for multiple volumes.
This attribute is used in the documentation and to select the
formats when reading/saving a file.
"""
# Store name and description
self._name = name.upper()
self._description = description
# Store extensions, do some effort to normalize them.
# They are stored as a list of lowercase strings without leading dots.
if extensions is None:
extensions = []
elif isinstance(extensions, str):
extensions = extensions.replace(",", " ").split(" ")
#
if isinstance(extensions, (tuple, list)):
self._extensions = tuple(
["." + e.strip(".").lower() for e in extensions if e]
)
else:
raise ValueError("Invalid value for extensions given.")
# Store mode
self._modes = modes or ""
if not isinstance(self._modes, str):
raise ValueError("Invalid value for modes given.")
for m in self._modes:
if m not in "iIvV?":
raise ValueError("Invalid value for mode given.")
def __repr__(self):
# Short description
return "<Format %s - %s>" % (self.name, self.description)
def __str__(self):
return self.doc
@property
def doc(self):
"""The documentation for this format (name + description + docstring)."""
# Our docsring is assumed to be indented by four spaces. The
# first line needs special attention.
return "%s - %s\n\n %s\n" % (
self.name,
self.description,
self.__doc__.strip(),
)
@property
def name(self):
"""The name of this format."""
return self._name
@property
def description(self):
"""A short description of this format."""
return self._description
@property
def extensions(self):
"""A list of file extensions supported by this plugin.
These are all lowercase with a leading dot.
"""
return self._extensions
@property
def modes(self):
"""A string specifying the modes that this format can handle."""
return self._modes
def get_reader(self, request):
"""get_reader(request)
Return a reader object that can be used to read data and info
from the given file. Users are encouraged to use
imageio.get_reader() instead.
"""
select_mode = request.mode[1] if request.mode[1] in "iIvV" else ""
if select_mode not in self.modes:
raise RuntimeError(
f"Format {self.name} cannot read in {request.mode.image_mode} mode"
)
return self.Reader(self, request)
def get_writer(self, request):
"""get_writer(request)
Return a writer object that can be used to write data and info
to the given file. Users are encouraged to use
imageio.get_writer() instead.
"""
select_mode = request.mode[1] if request.mode[1] in "iIvV" else ""
if select_mode not in self.modes:
raise RuntimeError(
f"Format {self.name} cannot write in {request.mode.image_mode} mode"
)
return self.Writer(self, request)
def can_read(self, request):
"""can_read(request)
Get whether this format can read data from the specified uri.
"""
return self._can_read(request)
def can_write(self, request):
"""can_write(request)
Get whether this format can write data to the speciefed uri.
"""
return self._can_write(request)
def _can_read(self, request): # pragma: no cover
"""Check if Plugin can read from ImageResource.
This method is called when the format manager is searching for a format
to read a certain image. Return True if this format can do it.
The format manager is aware of the extensions and the modes that each
format can handle. It will first ask all formats that *seem* to be able
to read it whether they can. If none can, it will ask the remaining
formats if they can: the extension might be missing, and this allows
formats to provide functionality for certain extensions, while giving
preference to other plugins.
If a format says it can, it should live up to it. The format would
ideally check the request.firstbytes and look for a header of some kind.
Parameters
----------
request : Request
A request that can be used to access the ImageResource and obtain
metadata about it.
Returns
-------
can_read : bool
True if the plugin can read from the ImageResource, False otherwise.
"""
return None # Plugins must implement this
def _can_write(self, request): # pragma: no cover
"""Check if Plugin can write to ImageResource.
Parameters
----------
request : Request
A request that can be used to access the ImageResource and obtain
metadata about it.
Returns
-------
can_read : bool
True if the plugin can write to the ImageResource, False otherwise.
"""
return None # Plugins must implement this
# -----
class _BaseReaderWriter(object):
"""Base class for the Reader and Writer class to implement common
functionality. It implements a similar approach for opening/closing
and context management as Python's file objects.
"""
def __init__(self, format, request):
self.__closed = False
self._BaseReaderWriter_last_index = -1
self._format = format
self._request = request
# Open the reader/writer
self._open(**self.request.kwargs.copy())
@property
def format(self):
"""The :class:`.Format` object corresponding to the current
read/write operation.
"""
return self._format
@property
def request(self):
"""The :class:`.Request` object corresponding to the
current read/write operation.
"""
return self._request
def __enter__(self):
self._checkClosed()
return self
def __exit__(self, type, value, traceback):
if value is None:
# Otherwise error in close hide the real error.
self.close()
def __del__(self):
try:
self.close()
except Exception: # pragma: no cover
pass # Suppress noise when called during interpreter shutdown
def close(self):
"""Flush and close the reader/writer.
This method has no effect if it is already closed.
"""
if self.__closed:
return
self.__closed = True
self._close()
# Process results and clean request object
self.request.finish()
@property
def closed(self):
"""Whether the reader/writer is closed."""
return self.__closed
def _checkClosed(self, msg=None):
"""Internal: raise an ValueError if reader/writer is closed"""
if self.closed:
what = self.__class__.__name__
msg = msg or ("I/O operation on closed %s." % what)
raise RuntimeError(msg)
# To implement
def _open(self, **kwargs):
"""_open(**kwargs)
Plugins should probably implement this.
It is called when reader/writer is created. Here the
plugin can do its initialization. The given keyword arguments
are those that were given by the user at imageio.read() or
imageio.write().
"""
raise NotImplementedError()
def _close(self):
"""_close()
Plugins should probably implement this.
It is called when the reader/writer is closed. Here the plugin
can do a cleanup, flush, etc.
"""
raise NotImplementedError()
# -----
class Reader(_BaseReaderWriter):
"""
The purpose of a reader object is to read data from an image
resource, and should be obtained by calling :func:`.get_reader`.
A reader can be used as an iterator to read multiple images,
and (if the format permits) only reads data from the file when
new data is requested (i.e. streaming). A reader can also be
used as a context manager so that it is automatically closed.
Plugins implement Reader's for different formats. Though rare,
plugins may provide additional functionality (beyond what is
provided by the base reader class).
"""
def get_length(self):
"""get_length()
Get the number of images in the file. (Note: you can also
use ``len(reader_object)``.)
The result can be:
* 0 for files that only have meta data
* 1 for singleton images (e.g. in PNG, JPEG, etc.)
* N for image series
* inf for streams (series of unknown length)
"""
return self._get_length()
def get_data(self, index, **kwargs):
"""get_data(index, **kwargs)
Read image data from the file, using the image index. The
returned image has a 'meta' attribute with the meta data.
Raises IndexError if the index is out of range.
Some formats may support additional keyword arguments. These are
listed in the documentation of those formats.
"""
self._checkClosed()
self._BaseReaderWriter_last_index = index
try:
im, meta = self._get_data(index, **kwargs)
except StopIteration:
raise IndexError(index)
return Array(im, meta) # Array tests im and meta
def get_next_data(self, **kwargs):
"""get_next_data(**kwargs)
Read the next image from the series.
Some formats may support additional keyword arguments. These are
listed in the documentation of those formats.
"""
return self.get_data(self._BaseReaderWriter_last_index + 1, **kwargs)
def set_image_index(self, index, **kwargs):
"""set_image_index(index)
Set the internal pointer such that the next call to
get_next_data() returns the image specified by the index
"""
self._checkClosed()
n = self.get_length()
self._BaseReaderWriter_last_index = min(max(index - 1, -1), n)
def get_meta_data(self, index=None):
"""get_meta_data(index=None)
Read meta data from the file. using the image index. If the
index is omitted or None, return the file's (global) meta data.
Note that ``get_data`` also provides the meta data for the returned
image as an attribute of that image.
The meta data is a dict, which shape depends on the format.
E.g. for JPEG, the dict maps group names to subdicts and each
group is a dict with name-value pairs. The groups represent
the different metadata formats (EXIF, XMP, etc.).
"""
self._checkClosed()
meta = self._get_meta_data(index)
if not isinstance(meta, dict):
raise ValueError(
"Meta data must be a dict, not %r" % meta.__class__.__name__
)
return meta
def iter_data(self):
"""iter_data()
Iterate over all images in the series. (Note: you can also
iterate over the reader object.)
"""
self._checkClosed()
n = self.get_length()
i = 0
while i < n:
try:
im, meta = self._get_data(i)
except StopIteration:
return
except IndexError:
if n == float("inf"):
return
raise
yield Array(im, meta)
i += 1
# Compatibility
def __iter__(self):
return self.iter_data()
def __len__(self):
n = self.get_length()
if n == float("inf"):
n = sys.maxsize
return n
# To implement
def _get_length(self):
"""_get_length()
Plugins must implement this.
The returned scalar specifies the number of images in the series.
See Reader.get_length for more information.
"""
raise NotImplementedError()
def _get_data(self, index):
"""_get_data()
Plugins must implement this, but may raise an IndexError in
case the plugin does not support random access.
It should return the image and meta data: (ndarray, dict).
"""
raise NotImplementedError()
def _get_meta_data(self, index):
"""_get_meta_data(index)
Plugins must implement this.
It should return the meta data as a dict, corresponding to the
given index, or to the file's (global) meta data if index is
None.
"""
raise NotImplementedError()
# -----
class Writer(_BaseReaderWriter):
"""
The purpose of a writer object is to write data to an image
resource, and should be obtained by calling :func:`.get_writer`.
A writer will (if the format permits) write data to the file
as soon as new data is provided (i.e. streaming). A writer can
also be used as a context manager so that it is automatically
closed.
Plugins implement Writer's for different formats. Though rare,
plugins may provide additional functionality (beyond what is
provided by the base writer class).
"""
def append_data(self, im, meta=None):
"""append_data(im, meta={})
Append an image (and meta data) to the file. The final meta
data that is used consists of the meta data on the given
image (if applicable), updated with the given meta data.
"""
self._checkClosed()
# Check image data
if not isinstance(im, np.ndarray):
raise ValueError("append_data requires ndarray as first arg")
# Get total meta dict
total_meta = {}
if hasattr(im, "meta") and isinstance(im.meta, dict):
total_meta.update(im.meta)
if meta is None:
pass
elif not isinstance(meta, dict):
raise ValueError("Meta must be a dict.")
else:
total_meta.update(meta)
# Decouple meta info
im = asarray(im)
# Call
return self._append_data(im, total_meta)
def set_meta_data(self, meta):
"""set_meta_data(meta)
Sets the file's (global) meta data. The meta data is a dict which
shape depends on the format. E.g. for JPEG the dict maps
group names to subdicts, and each group is a dict with
name-value pairs. The groups represents the different
metadata formats (EXIF, XMP, etc.).
Note that some meta formats may not be supported for
writing, and individual fields may be ignored without
warning if they are invalid.
"""
self._checkClosed()
if not isinstance(meta, dict):
raise ValueError("Meta must be a dict.")
else:
return self._set_meta_data(meta)
# To implement
def _append_data(self, im, meta):
# Plugins must implement this
raise NotImplementedError()
def _set_meta_data(self, meta):
# Plugins must implement this
raise NotImplementedError()
| Format |
python | pypa__pip | src/pip/_vendor/rich/json.py | {
"start": 189,
"end": 5031
} | class ____:
"""A renderable which pretty prints JSON.
Args:
json (str): JSON encoded data.
indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
highlight (bool, optional): Enable highlighting. Defaults to True.
skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
check_circular (bool, optional): Check for circular references. Defaults to True.
allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
default (Callable, optional): A callable that converts values that can not be encoded
in to something that can be JSON encoded. Defaults to None.
sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
"""
def __init__(
self,
json: str,
indent: Union[None, int, str] = 2,
highlight: bool = True,
skip_keys: bool = False,
ensure_ascii: bool = False,
check_circular: bool = True,
allow_nan: bool = True,
default: Optional[Callable[[Any], Any]] = None,
sort_keys: bool = False,
) -> None:
data = loads(json)
json = dumps(
data,
indent=indent,
skipkeys=skip_keys,
ensure_ascii=ensure_ascii,
check_circular=check_circular,
allow_nan=allow_nan,
default=default,
sort_keys=sort_keys,
)
highlighter = JSONHighlighter() if highlight else NullHighlighter()
self.text = highlighter(json)
self.text.no_wrap = True
self.text.overflow = None
@classmethod
def from_data(
cls,
data: Any,
indent: Union[None, int, str] = 2,
highlight: bool = True,
skip_keys: bool = False,
ensure_ascii: bool = False,
check_circular: bool = True,
allow_nan: bool = True,
default: Optional[Callable[[Any], Any]] = None,
sort_keys: bool = False,
) -> "JSON":
"""Encodes a JSON object from arbitrary data.
Args:
data (Any): An object that may be encoded in to JSON
indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
highlight (bool, optional): Enable highlighting. Defaults to True.
default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None.
skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
check_circular (bool, optional): Check for circular references. Defaults to True.
allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
default (Callable, optional): A callable that converts values that can not be encoded
in to something that can be JSON encoded. Defaults to None.
sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
Returns:
JSON: New JSON object from the given data.
"""
json_instance: "JSON" = cls.__new__(cls)
json = dumps(
data,
indent=indent,
skipkeys=skip_keys,
ensure_ascii=ensure_ascii,
check_circular=check_circular,
allow_nan=allow_nan,
default=default,
sort_keys=sort_keys,
)
highlighter = JSONHighlighter() if highlight else NullHighlighter()
json_instance.text = highlighter(json)
json_instance.text.no_wrap = True
json_instance.text.overflow = None
return json_instance
def __rich__(self) -> Text:
return self.text
if __name__ == "__main__":
import argparse
import sys
parser = argparse.ArgumentParser(description="Pretty print json")
parser.add_argument(
"path",
metavar="PATH",
help="path to file, or - for stdin",
)
parser.add_argument(
"-i",
"--indent",
metavar="SPACES",
type=int,
help="Number of spaces in an indent",
default=2,
)
args = parser.parse_args()
from pip._vendor.rich.console import Console
console = Console()
error_console = Console(stderr=True)
try:
if args.path == "-":
json_data = sys.stdin.read()
else:
json_data = Path(args.path).read_text()
except Exception as error:
error_console.print(f"Unable to read {args.path!r}; {error}")
sys.exit(-1)
console.print(JSON(json_data, indent=args.indent), soft_wrap=True)
| JSON |
python | mwaskom__seaborn | seaborn/_statistics.py | {
"start": 14259,
"end": 15937
} | class ____:
"""Univariate empirical cumulative distribution estimator."""
def __init__(self, stat="proportion", complementary=False):
"""Initialize the class with its parameters
Parameters
----------
stat : {{"proportion", "percent", "count"}}
Distribution statistic to compute.
complementary : bool
If True, use the complementary CDF (1 - CDF)
"""
_check_argument("stat", ["count", "percent", "proportion"], stat)
self.stat = stat
self.complementary = complementary
def _eval_bivariate(self, x1, x2, weights):
"""Inner function for ECDF of two variables."""
raise NotImplementedError("Bivariate ECDF is not implemented")
def _eval_univariate(self, x, weights):
"""Inner function for ECDF of one variable."""
sorter = x.argsort()
x = x[sorter]
weights = weights[sorter]
y = weights.cumsum()
if self.stat in ["percent", "proportion"]:
y = y / y.max()
if self.stat == "percent":
y = y * 100
x = np.r_[-np.inf, x]
y = np.r_[0, y]
if self.complementary:
y = y.max() - y
return y, x
def __call__(self, x1, x2=None, weights=None):
"""Return proportion or count of observations below each sorted datapoint."""
x1 = np.asarray(x1)
if weights is None:
weights = np.ones_like(x1)
else:
weights = np.asarray(weights)
if x2 is None:
return self._eval_univariate(x1, weights)
else:
return self._eval_bivariate(x1, x2, weights)
| ECDF |
python | wireservice__csvkit | csvkit/utilities/csvcut.py | {
"start": 313,
"end": 2251
} | class ____(CSVKitUtility):
description = 'Filter and truncate CSV files. Like the Unix "cut" command, but for tabular data.'
override_flags = ['L', 'I']
def add_arguments(self):
self.argparser.add_argument(
'-n', '--names', dest='names_only', action='store_true',
help='Display column names and indices from the input CSV and exit.')
self.argparser.add_argument(
'-c', '--columns', dest='columns',
help='A comma-separated list of column indices, names or ranges to be extracted, e.g. "1,id,3-5". '
'Defaults to all columns.')
self.argparser.add_argument(
'-C', '--not-columns', dest='not_columns',
help='A comma-separated list of column indices, names or ranges to be excluded, e.g. "1,id,3-5". '
'Defaults to no columns.')
self.argparser.add_argument(
'-x', '--delete-empty-rows', dest='delete_empty', action='store_true',
help='After cutting, delete rows which are completely empty.')
def main(self):
if self.args.names_only:
self.print_column_names()
return
if self.additional_input_expected():
sys.stderr.write('No input file or piped data provided. Waiting for standard input:\n')
rows, column_names, column_ids = self.get_rows_and_column_names_and_column_ids(**self.reader_kwargs)
output = agate.csv.writer(self.output_file, **self.writer_kwargs)
output.writerow([column_names[column_id] for column_id in column_ids])
for row in rows:
out_row = [row[column_id] if column_id < len(row) else None for column_id in column_ids]
if not self.args.delete_empty or any(out_row):
output.writerow(out_row)
def launch_new_instance():
utility = CSVCut()
utility.run()
if __name__ == '__main__':
launch_new_instance()
| CSVCut |
python | coleifer__peewee | tests/regressions.py | {
"start": 52372,
"end": 52748
} | class ____(ModelTestCase):
requires = [FKN_A, FKN_B]
def test_set_fk_null(self):
a1 = FKN_A.create()
a2 = FKN_A()
b1 = FKN_B(a=a1)
b2 = FKN_B(a=a2)
self.assertTrue(b1.a is a1)
self.assertTrue(b2.a is a2)
b1.a = b2.a = None
self.assertTrue(b1.a is None)
self.assertTrue(b2.a is None)
| TestSetFKNull |
python | weaviate__weaviate-python-client | weaviate/users/sync.py | {
"start": 212,
"end": 296
} | class ____(_UsersDBExecutor[ConnectionSync]):
pass
@executor.wrap("sync")
| _UsersDB |
python | walkccc__LeetCode | solutions/2845. Count of Interesting Subarrays/2845.py | {
"start": 0,
"end": 448
} | class ____:
def countInterestingSubarrays(
self,
nums: list[int],
modulo: int,
k: int,
) -> int:
ans = 0
prefix = 0 # (number of nums[i] % modulo == k so far) % modulo
prefixCount = collections.Counter({0: 1})
for num in nums:
if num % modulo == k:
prefix = (prefix + 1) % modulo
ans += prefixCount[(prefix - k + modulo) % modulo]
prefixCount[prefix] += 1
return ans
| Solution |
python | PyCQA__pylint | tests/functional/s/slots_checks.py | {
"start": 1069,
"end": 1137
} | class ____:
__slots__ = ('a', 2) # [invalid-slots-object]
| ThirdBad |
python | pandas-dev__pandas | pandas/core/computation/ops.py | {
"start": 4267,
"end": 4603
} | class ____(Term):
def _resolve_name(self):
return self._name
@property
def name(self):
return self.value
def __repr__(self) -> str:
# in python 2 str() of float
# can truncate shorter than repr()
return repr(self.name)
_bool_op_map = {"not": "~", "and": "&", "or": "|"}
| Constant |
python | pytorch__pytorch | benchmarks/transformer/sdpa.py | {
"start": 1809,
"end": 8442
} | class ____:
config: ExperimentConfig
results: ExperimentResults
def asdict(self):
dict1 = self.config.asdict()
dict2 = self.results.asdict()
return {**dict1, **dict2}
def calculate_tflops(
config: ExperimentConfig,
time_us: float,
is_backward: bool = False,
sparsity: float = 0.0,
) -> float:
"""
Calculate TFLOPS for scaled dot product attention.
Parameters:
- config: The experiment configuration
- time_us: The execution time in microseconds
- is_backward: Whether to calculate for backward pass (includes gradient computation)
- sparsity: Sparsity factor between 0.0 and 1.0, where 0.0 means no sparsity and 1.0 means fully sparse
Returns:
- TFLOPS value
"""
B = config.batch_size
H = config.num_heads
M = config.q_seq_len
N = config.kv_seq_len
D = config.head_dim
# Calculate density factor (1.0 - sparsity)
density = 1.0 - sparsity
# Forward pass FLOPs
qk_flops = (
M * N * D * 2
) # Q*K^T matmul: (M,D) @ (D,N) with 2 FLOPs per multiply-add
softmax_flops = M * N * 2 # Softmax operations (exp and div)
av_flops = (
M * N * D * 2
) # Attention @ V: (M,N) @ (N,D) with 2 FLOPs per multiply-add
total_flops = B * H * (qk_flops + softmax_flops + av_flops)
# Apply density factor to account for sparsity
total_flops *= density
# For backward pass flash uses 2.5x more flops will use this
if is_backward:
total_flops *= 2.5
# Convert to TFLOPS: flops / (time_us * 1e-6) / 1e12
tflops = total_flops / (time_us * 1e-6) / 1e12
return tflops
def get_input(
config: ExperimentConfig,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
q = torch.randn(
(config.batch_size, config.num_heads, config.q_seq_len, config.head_dim),
dtype=config.dtype,
device=config.device,
requires_grad=True,
)
k = torch.randn(
(config.batch_size, config.num_heads, config.kv_seq_len, config.head_dim),
dtype=config.dtype,
device=config.device,
requires_grad=True,
)
v = torch.randn(
(config.batch_size, config.num_heads, config.kv_seq_len, config.head_dim),
dtype=config.dtype,
device=config.device,
requires_grad=True,
)
return q, k, v
def run_single_experiment(config: ExperimentConfig) -> ExperimentResults:
q, k, v = get_input(config)
is_causal = config.is_causal
context = (
sdpa_kernel(config.backend) if config.backend is not None else nullcontext()
)
with context:
forward_time = benchmark_cuda_function_in_microseconds(
scaled_dot_product_attention,
q,
k,
v,
is_causal=is_causal,
attn_mask=None,
)
out_torch = scaled_dot_product_attention(
q, k, v, is_causal=is_causal, attn_mask=None
)
d_out = torch.randn_like(out_torch)
backward_time = benchmark_cuda_function_in_microseconds(
out_torch.backward, d_out, retain_graph=True
)
# Calculate TFLOPS for forward and backward passes
sparsity = 0.5 if is_causal else 0.0
forward_tflops = calculate_tflops(config, forward_time, sparsity=sparsity)
backward_tflops = calculate_tflops(
config, backward_time, is_backward=True, sparsity=sparsity
)
return ExperimentResults(
forward_time=forward_time,
backward_time=backward_time,
forward_tflops=forward_tflops,
backward_tflops=backward_tflops,
)
def print_results(experiments: list[Experiment]):
table_data = defaultdict(list)
for experiment in experiments:
for key, value in experiment.asdict().items():
table_data[key].append(value)
del table_data["device"]
if table_data["backend"][0] is None:
del table_data["backend"]
print(tabulate(table_data, headers="keys", tablefmt="pretty", floatfmt=".3f"))
def write_results_to_csv(
experiments: list[Experiment], output_dir: str = "benchmark_results"
):
"""
Write experiment results to a CSV file in the specified directory.
The filename includes a timestamp for uniqueness.
"""
import csv
import os
from datetime import datetime
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Generate filename with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join(output_dir, f"benchmark_results_{timestamp}.csv")
# Get all fields from the first experiment
if not experiments:
return
fieldnames = list(experiments[0].asdict().keys())
if "device" in fieldnames:
fieldnames.remove("device") # Remove device field as it's always cuda
# Write results to CSV
with open(filename, "w", newline="") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for experiment in experiments:
row = experiment.asdict()
if "device" in row:
del row["device"] # Remove device field
writer.writerow(row)
print(f"Results written to: {filename}")
def generate_experiment_configs() -> list[ExperimentConfig]:
batch_sizes = [1, 8, 16]
num_heads = [16]
q_kv_seq_lens = [(128, 128), (256, 256), (512, 512), (1024, 1024), (8192, 8192)]
embed_dims = [2048]
backends = [None] # If set to None, all backends are enabled
dtypes = [
torch.bfloat16,
]
is_causal = [True, False]
all_configs = []
for (
bsz,
heads,
(q_seq_len, kv_seq_len),
embed_dim,
causal,
dtype,
backend,
) in itertools.product(
batch_sizes, num_heads, q_kv_seq_lens, embed_dims, is_causal, dtypes, backends
):
all_configs.append(
ExperimentConfig(
batch_size=bsz,
num_heads=heads,
q_seq_len=q_seq_len,
kv_seq_len=kv_seq_len,
embed_dim=embed_dim,
is_causal=causal,
dtype=dtype,
backend=backend,
)
)
return all_configs
def main():
seed = 123
torch.manual_seed(seed)
results = []
for config in tqdm(generate_experiment_configs()):
results.append(Experiment(config, run_single_experiment(config)))
print_results(results)
write_results_to_csv(results, "../benchmark_results")
if __name__ == "__main__":
main()
| Experiment |
python | Pylons__pyramid | tests/test_predicates.py | {
"start": 16326,
"end": 16979
} | class ____(unittest.TestCase):
def _makeOne(self, predicate):
from pyramid.predicates import Notted
return Notted(predicate)
def test_it_with_phash_val(self):
pred = DummyPredicate('val')
inst = self._makeOne(pred)
self.assertEqual(inst.text(), '!val')
self.assertEqual(inst.phash(), '!val')
self.assertEqual(inst(None, None), False)
def test_it_without_phash_val(self):
pred = DummyPredicate('')
inst = self._makeOne(pred)
self.assertEqual(inst.text(), '')
self.assertEqual(inst.phash(), '')
self.assertEqual(inst(None, None), True)
| TestNotted |
python | kubernetes-client__python | kubernetes/client/models/v1_persistent_volume_list.py | {
"start": 383,
"end": 7197
} | 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.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'items': 'list[V1PersistentVolume]',
'kind': 'str',
'metadata': 'V1ListMeta'
}
attribute_map = {
'api_version': 'apiVersion',
'items': 'items',
'kind': 'kind',
'metadata': 'metadata'
}
def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501
"""V1PersistentVolumeList - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._items = None
self._kind = None
self._metadata = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
self.items = items
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
@property
def api_version(self):
"""Gets the api_version of this V1PersistentVolumeList. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1PersistentVolumeList. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1PersistentVolumeList.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1PersistentVolumeList. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def items(self):
"""Gets the items of this V1PersistentVolumeList. # noqa: E501
items is a list of persistent volumes. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes # noqa: E501
:return: The items of this V1PersistentVolumeList. # noqa: E501
:rtype: list[V1PersistentVolume]
"""
return self._items
@items.setter
def items(self, items):
"""Sets the items of this V1PersistentVolumeList.
items is a list of persistent volumes. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes # noqa: E501
:param items: The items of this V1PersistentVolumeList. # noqa: E501
:type: list[V1PersistentVolume]
"""
if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501
raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501
self._items = items
@property
def kind(self):
"""Gets the kind of this V1PersistentVolumeList. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1PersistentVolumeList. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1PersistentVolumeList.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1PersistentVolumeList. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1PersistentVolumeList. # noqa: E501
:return: The metadata of this V1PersistentVolumeList. # noqa: E501
:rtype: V1ListMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1PersistentVolumeList.
:param metadata: The metadata of this V1PersistentVolumeList. # noqa: E501
:type: V1ListMeta
"""
self._metadata = metadata
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1PersistentVolumeList):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1PersistentVolumeList):
return True
return self.to_dict() != other.to_dict()
| V1PersistentVolumeList |
python | spack__spack | lib/spack/spack/vendor/attr/validators.py | {
"start": 15068,
"end": 15953
} | class ____:
max_length = attrib()
def __call__(self, inst, attr, value):
"""
We use a callable class to be able to change the ``__repr__``.
"""
if len(value) > self.max_length:
raise ValueError(
"Length of '{name}' must be <= {max}: {len}".format(
name=attr.name, max=self.max_length, len=len(value)
)
)
def __repr__(self):
return "<max_len validator for {max}>".format(max=self.max_length)
def max_len(length):
"""
A validator that raises `ValueError` if the initializer is called
with a string or iterable that is longer than *length*.
:param int length: Maximum length of the string or iterable
.. versionadded:: 21.3.0
"""
return _MaxLengthValidator(length)
@attrs(repr=False, frozen=True, slots=True)
| _MaxLengthValidator |
python | pandas-dev__pandas | pandas/core/computation/pytables.py | {
"start": 11164,
"end": 12571
} | class ____(BinOp):
def __repr__(self) -> str:
return pprint_thing(f"[Condition : [{self.condition}]]")
def invert(self):
"""invert the condition"""
# if self.condition is not None:
# self.condition = "~(%s)" % self.condition
# return self
raise NotImplementedError(
"cannot use an invert condition when passing to numexpr"
)
def format(self):
"""return the actual ne format"""
return self.condition
# error: Signature of "evaluate" incompatible with supertype "BinOp"
def evaluate(self) -> Self | None: # type: ignore[override]
if not self.is_valid:
raise ValueError(f"query term is not valid [{self}]")
# convert values if we are in the table
if not self.is_in_table:
return None
rhs = self.conform(self.rhs)
values = [self.convert_value(v) for v in rhs]
# equality conditions
if self.op in ["==", "!="]:
# too many values to create the expression?
if len(values) <= self._max_selectors:
vs = [self.generate(v) for v in values]
self.condition = f"({' | '.join(vs)})"
# use a filter after reading
else:
return None
else:
self.condition = self.generate(values[0])
return self
| ConditionBinOp |
python | dask__dask | dask/dataframe/dask_expr/io/io.py | {
"start": 1059,
"end": 1906
} | class ____(IO):
"""A DataFrame created from an opaque Dask task graph
This is used in persist, for example, and would also be used in any
conversion from legacy dataframes.
"""
_parameters = ["layer", "_meta", "divisions", "keys", "name_prefix"]
@property
def _meta(self):
return self.operand("_meta")
def _divisions(self):
return self.operand("divisions")
@functools.cached_property
def _name(self):
return self.operand("name_prefix") + "-" + self.deterministic_token
def _layer(self):
dsk = dict(self.operand("layer"))
# The name may not actually match the layers name therefore rewrite this
# using an alias
for new, old in zip(self.__dask_keys__(), self.operand("keys")):
dsk[new] = Alias(new, old)
return dsk
| FromGraph |
python | doocs__leetcode | solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/Solution.py | {
"start": 0,
"end": 230
} | class ____:
def numberOfSteps(self, num: int) -> int:
ans = 0
while num:
if num & 1:
num -= 1
else:
num >>= 1
ans += 1
return ans
| Solution |
python | django__django | django/db/backends/mysql/features.py | {
"start": 137,
"end": 8163
} | class ____(BaseDatabaseFeatures):
empty_fetchmany_value = ()
related_fields_match_type = True
# MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME.
allow_sliced_subqueries_with_in = False
has_select_for_update = True
has_select_for_update_nowait = True
has_select_for_update_skip_locked = True
supports_forward_references = False
supports_regex_backreferencing = False
supports_date_lookup_using_string = False
supports_timezones = False
requires_explicit_null_ordering_when_grouping = True
atomic_transactions = False
can_clone_databases = True
supports_aggregate_order_by_clause = True
supports_comments = True
supports_comments_inline = True
supports_temporal_subtraction = True
supports_slicing_ordering_in_compound = True
supports_index_on_text_field = False
supports_over_clause = True
supports_frame_range_fixed_distance = True
supports_update_conflicts = True
can_rename_index = True
delete_can_self_reference_subquery = False
create_test_procedure_without_params_sql = """
CREATE PROCEDURE test_procedure ()
BEGIN
DECLARE V_I INTEGER;
SET V_I = 1;
END;
"""
create_test_procedure_with_int_param_sql = """
CREATE PROCEDURE test_procedure (P_I INTEGER)
BEGIN
DECLARE V_I INTEGER;
SET V_I = P_I;
END;
"""
supports_on_delete_db_default = False
# Neither MySQL nor MariaDB support partial indexes.
supports_partial_indexes = False
# COLLATE must be wrapped in parentheses because MySQL treats COLLATE as an
# indexed expression.
collate_as_index_expression = True
insert_test_table_with_defaults = "INSERT INTO {} () VALUES ()"
supports_order_by_nulls_modifier = False
order_by_nulls_first = True
supports_logical_xor = True
supports_stored_generated_columns = True
supports_virtual_generated_columns = True
supports_json_negative_indexing = False
@cached_property
def minimum_database_version(self):
if self.connection.mysql_is_mariadb:
return (10, 6)
else:
return (8, 4)
@cached_property
def test_collations(self):
return {
"ci": "utf8mb4_general_ci",
"non_default": "utf8mb4_esperanto_ci",
"swedish_ci": "utf8mb4_swedish_ci",
"virtual": "utf8mb4_esperanto_ci",
}
test_now_utc_template = "UTC_TIMESTAMP(6)"
@cached_property
def django_test_skips(self):
skips = {
"This doesn't work on MySQL.": {
"db_functions.comparison.test_greatest.GreatestTests."
"test_coalesce_workaround",
"db_functions.comparison.test_least.LeastTests."
"test_coalesce_workaround",
},
"MySQL doesn't support functional indexes on a function that "
"returns JSON": {
"schema.tests.SchemaTests.test_func_index_json_key_transform",
},
"MySQL supports multiplying and dividing DurationFields by a "
"scalar value but it's not implemented (#25287).": {
"expressions.tests.FTimeDeltaTests.test_durationfield_multiply_divide",
},
"UPDATE ... ORDER BY syntax on MySQL/MariaDB does not support ordering by"
"related fields.": {
"update.tests.AdvancedTests."
"test_update_ordered_by_inline_m2m_annotation",
"update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation",
"update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation_desc",
},
}
if not self.connection.mysql_is_mariadb:
skips.update(
{
"MySQL doesn't allow renaming columns referenced by generated "
"columns": {
"migrations.test_operations.OperationTests."
"test_invalid_generated_field_changes_on_rename_stored",
"migrations.test_operations.OperationTests."
"test_invalid_generated_field_changes_on_rename_virtual",
},
}
)
return skips
@cached_property
def _mysql_storage_engine(self):
"""
Internal method used in Django tests. Don't rely on this from your code
"""
return self.connection.mysql_server_data["default_storage_engine"]
@cached_property
def allows_auto_pk_0(self):
"""
Autoincrement primary key can be set to 0 if it doesn't generate new
autoincrement values.
"""
return "NO_AUTO_VALUE_ON_ZERO" in self.connection.sql_mode
@cached_property
def update_can_self_select(self):
return self.connection.mysql_is_mariadb
@cached_property
def can_introspect_foreign_keys(self):
"Confirm support for introspected foreign keys"
return self._mysql_storage_engine != "MyISAM"
@cached_property
def introspected_field_types(self):
return {
**super().introspected_field_types,
"BinaryField": "TextField",
"BooleanField": "IntegerField",
"DurationField": "BigIntegerField",
"GenericIPAddressField": "CharField",
}
@cached_property
def can_return_columns_from_insert(self):
return self.connection.mysql_is_mariadb
can_return_rows_from_bulk_insert = property(
operator.attrgetter("can_return_columns_from_insert")
)
@cached_property
def has_zoneinfo_database(self):
return self.connection.mysql_server_data["has_zoneinfo_database"]
@cached_property
def is_sql_auto_is_null_enabled(self):
return self.connection.mysql_server_data["sql_auto_is_null"]
@cached_property
def has_select_for_update_of(self):
return not self.connection.mysql_is_mariadb
@cached_property
def supported_explain_formats(self):
# Alias MySQL's TRADITIONAL to TEXT for consistency with other
# backends.
formats = {"JSON", "TEXT", "TRADITIONAL"}
if not self.connection.mysql_is_mariadb:
formats.add("TREE")
return formats
@cached_property
def supports_transactions(self):
"""
All storage engines except MyISAM support transactions.
"""
return self._mysql_storage_engine != "MyISAM"
@cached_property
def ignores_table_name_case(self):
return self.connection.mysql_server_data["lower_case_table_names"]
@cached_property
def supports_default_in_lead_lag(self):
# To be added in https://jira.mariadb.org/browse/MDEV-12981.
return not self.connection.mysql_is_mariadb
@cached_property
def can_introspect_json_field(self):
if self.connection.mysql_is_mariadb:
return self.can_introspect_check_constraints
return True
@cached_property
def supports_index_column_ordering(self):
if self._mysql_storage_engine != "InnoDB":
return False
if self.connection.mysql_is_mariadb:
return self.connection.mysql_version >= (10, 8)
return True
@cached_property
def supports_expression_indexes(self):
return (
not self.connection.mysql_is_mariadb
and self._mysql_storage_engine != "MyISAM"
)
@cached_property
def has_native_uuid_field(self):
is_mariadb = self.connection.mysql_is_mariadb
return is_mariadb and self.connection.mysql_version >= (10, 7)
@cached_property
def allows_group_by_selected_pks(self):
if self.connection.mysql_is_mariadb:
return "ONLY_FULL_GROUP_BY" not in self.connection.sql_mode
return True
@cached_property
def supports_any_value(self):
return not self.connection.mysql_is_mariadb
| DatabaseFeatures |
python | walkccc__LeetCode | solutions/1253. Reconstruct a 2-Row Binary Matrix/1253.py | {
"start": 0,
"end": 617
} | class ____:
def reconstructMatrix(self, upper: int, lower: int, colsum: list[int]) -> list[list[int]]:
if upper + lower != sum(colsum):
return []
if min(upper, lower) < colsum.count(2):
return []
ans = [[0] * len(colsum) for _ in range(2)]
for j, c in enumerate(colsum):
if c == 2:
ans[0][j] = 1
ans[1][j] = 1
upper -= 1
lower -= 1
for j, c in enumerate(colsum):
if c == 1 and upper > 0:
ans[0][j] = 1
c -= 1
upper -= 1
if c == 1 and lower > 0:
ans[1][j] = 1
lower -= 1
return ans
| Solution |
python | fluentpython__example-code-2e | 14-inheritance/uppermixin.py | {
"start": 2395,
"end": 2806
} | class ____: # <2>
def __setitem__(self, key, item):
super().__setitem__(_upper(key), item)
def __getitem__(self, key):
return super().__getitem__(_upper(key))
def get(self, key, default=None):
return super().get(_upper(key), default)
def __contains__(self, key):
return super().__contains__(_upper(key))
# end::UPPERCASE_MIXIN[]
# tag::UPPERDICT[]
| UpperCaseMixin |
python | huggingface__transformers | src/transformers/models/metaclip_2/modular_metaclip_2.py | {
"start": 13604,
"end": 15377
} | class ____(CLIPTextTransformer):
@auto_docstring
def forward(
self,
input_ids,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> BaseModelOutputWithPooling:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
attention_mask = create_causal_mask(
config=self.config,
input_embeds=hidden_states,
attention_mask=attention_mask,
cache_position=torch.arange(hidden_states.shape[1], device=hidden_states.device),
past_key_values=None,
)
kwargs.pop("is_causal", None)
encoder_outputs: BaseModelOutput = self.encoder(
inputs_embeds=hidden_states,
attention_mask=attention_mask,
is_causal=True,
**kwargs,
)
last_hidden_state = encoder_outputs.last_hidden_state
last_hidden_state = self.final_layer_norm(last_hidden_state)
# Use robust pooling like CLIP - finds the first EOS token position per sequence
pooled_output = last_hidden_state[
torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
(input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id).int().argmax(dim=-1),
]
return BaseModelOutputWithPooling(
last_hidden_state=last_hidden_state,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
| MetaClip2TextTransformer |
python | hyperopt__hyperopt | hyperopt/pyll/base.py | {
"start": 497,
"end": 588
} | class ____(ImportError):
"""A pyll symbol was not defined in the scope"""
| PyllImportError |
python | PyCQA__pycodestyle | testing/data/python313.py | {
"start": 75,
"end": 116
} | class ____[T: (int, str) = str]:
pass
| C |
python | pytorch__pytorch | test/dynamo/test_dicts.py | {
"start": 38816,
"end": 51202
} | class ____(torch._dynamo.test_case.TestCase):
thetype = dict
# Methods:
# + clear
# + copy
# + fromkeys
# + get
# + items
# + keys
# + pop
# + popitem
# + setdefault
# + update
# + values
# BinOps:
# ==, !=, |
def setUp(self):
self._prev_trace_unittest = torch._dynamo.config.enable_trace_unittest
torch._dynamo.config.enable_trace_unittest = True
super().setUp()
def tearDown(self):
torch._dynamo.config.enable_trace_unittest = self._prev_trace_unittest
return super().tearDown()
def assertEqual(self, x, y):
self.assertTrue(x == y, f"Expected {x} to be equal to {y}")
def assertNotEqual(self, x, y):
self.assertFalse(x == y, f"Expected {x} to not be equal to {y}")
@make_dynamo_test
def test_cmp_eq(self):
d1 = self.thetype({"a": 1, "b": 2})
d2 = self.thetype({"a": 1, "b": 2})
d3 = self.thetype({"a": 1, "b": 3})
self.assertEqual(d1, d2)
self.assertNotEqual(d1, d3)
# Test the == operator
self.assertEqual(d1 == d2, True)
self.assertEqual(d1 == d3, False)
# Test the __eq__ method
self.assertEqual(d1.__eq__(d2), True)
self.assertEqual(d1.__eq__(d3), False)
# Test Dict.__eq__
self.assertEqual(dict.__eq__(d1, d2), True)
self.assertEqual(self.thetype.__eq__(d1, d3), False)
@make_dynamo_test
def test_cmp_ne(self):
d1 = self.thetype({"a": 1, "b": 2})
d2 = self.thetype({"a": 1, "b": 2})
d3 = self.thetype({"a": 1, "b": 3})
self.assertNotEqual(d1, d3)
self.assertEqual(d1, d2)
# Test the != operator
self.assertEqual(d1 != d3, True)
self.assertEqual(d1 != d2, False)
# Test the __ne__ method
self.assertEqual(d1.__ne__(d3), True)
self.assertEqual(d1.__ne__(d2), False)
# Test Dict.__ne__
self.assertEqual(dict.__ne__(d1, d3), True)
self.assertEqual(self.thetype.__ne__(d1, d2), False)
@make_dynamo_test
def test_binop_or(self):
d1 = self.thetype({"a": 1, "b": 2})
d2 = self.thetype({"b": 3, "c": 4})
# Test the | operator
self.assertEqual(d1 | d2, {"a": 1, "b": 3, "c": 4})
self.assertEqual(d2 | d1, {"a": 1, "b": 2, "c": 4})
# Test the __or__ method
self.assertEqual(d1.__or__(d2), {"a": 1, "b": 3, "c": 4})
self.assertEqual(d2.__or__(d1), {"a": 1, "b": 2, "c": 4})
# Test Dict.__or__
self.assertEqual(dict.__or__(d1, d2), {"a": 1, "b": 3, "c": 4})
self.assertEqual(self.thetype.__or__(d2, d1), {"a": 1, "b": 2, "c": 4})
# Test with non-dict types
self.assertRaises(TypeError, lambda: d1 | 1)
@make_dynamo_test
def test_binop_ior(self):
d1 = self.thetype({"a": 1, "b": 2})
d2 = self.thetype({"b": 3, "c": 4})
# Test the |= operator
d3, d4 = d1.copy(), d2.copy()
d3 |= d2
d4 |= d1
self.assertEqual(d3, {"a": 1, "b": 3, "c": 4})
self.assertEqual(d4, {"a": 1, "b": 2, "c": 4})
# Test with an iterable
d3, d4 = d1.copy(), d2.copy()
# Test the __ior__ method
d3, d4 = d1.copy(), d2.copy()
d3.__ior__(d2)
d4.__ior__(d1)
self.assertEqual(d3, {"a": 1, "b": 3, "c": 4})
self.assertEqual(d4, {"a": 1, "b": 2, "c": 4})
# Test Dict.__or__
d3, d4 = d1.copy(), d2.copy()
self.assertEqual(dict.__ior__(d3, d2), {"a": 1, "b": 3, "c": 4})
self.assertEqual(self.thetype.__ior__(d4, d1), {"a": 1, "b": 2, "c": 4})
# Test return value
d3, d4 = d1.copy(), d2.copy()
self.assertEqual(d3.__ior__(d2), {"a": 1, "b": 3, "c": 4})
self.assertEqual(dict.__ior__(d4, d1), {"a": 1, "b": 2, "c": 4})
# Test with non-dict types
self.assertRaises(TypeError, lambda: dict.__ior__(d1, 1))
@make_dynamo_test
def test_binop_ior_iterable(self):
d1 = self.thetype({"a": 1, "b": 2})
d2 = self.thetype({"b": 3, "c": 4})
d3, d4 = d1.copy(), d2.copy()
def fn(d):
yield from d.items()
self.assertEqual(d3.__ior__(d2.items()), {"a": 1, "b": 3, "c": 4})
self.assertEqual(d4.__ior__(fn(d1)), {"a": 1, "b": 2, "c": 4})
@make_dynamo_test
def test_clear(self):
d = self.thetype({"a": 1, "b": 2})
d.clear()
self.assertEqual(d, {})
# Test that clear returns None
d = self.thetype({"a": 1, "b": 2})
self.assertIsNone(d.clear())
# Test Dict.clear
d = self.thetype({"a": 1, "b": 2})
dict.clear(d)
self.assertEqual(d, {})
d = self.thetype({"a": 1, "b": 2})
self.thetype.clear(d)
self.assertEqual(d, {})
# Test invalid usage
self.assertRaises(TypeError, d.clear, 1)
@make_dynamo_test
def test_copy(self):
d = self.thetype({"a": 1, "b": 2})
d2 = d.copy()
self.assertEqual(d, d2)
# Test that copy returns a new instance
self.assertIsNot(d, d2)
# Test Dict.copy
self.assertEqual(dict.copy(d), d2)
self.assertEqual(self.thetype.copy(d), d2)
# Test invalid usage
self.assertRaises(TypeError, d.copy, 1)
@unittest.expectedFailure
@make_dynamo_test
def test_fromkeys(self):
d = self.thetype.fromkeys(["a", "b"], 1)
self.assertEqual(d, {"a": 1, "b": 1})
p = self.thetype.fromkeys(["a", "b"], None)
self.assertEqual(p, {"a": None, "b": None})
# Test Dict.fromkeys
d2 = self.thetype.fromkeys(["c", "d"], 2)
self.assertEqual(d2, {"c": 2, "d": 2})
# Test invalid usage
self.assertRaises(TypeError, self.thetype.fromkeys)
self.assertRaises(TypeError, self.thetype.fromkeys, 1, 2)
@make_dynamo_test
def test_get(self):
d = self.thetype({"a": 1, "b": 2})
self.assertEqual(d.get("a"), 1)
self.assertEqual(d.get("c", 3), 3)
self.assertIsNone(d.get("c"))
# Test Dict.get
self.assertEqual(dict.get(d, "b"), 2)
self.assertEqual(self.thetype.get(d, "b"), 2)
# Test invalid usage
self.assertRaises(TypeError, d.get)
@make_dynamo_test
def test_items(self):
d = self.thetype({"a": 1, "b": 2})
items = d.items()
self.assertEqual(set(items), {("a", 1), ("b", 2)})
# Test Dict.items
self.assertEqual(set(dict.items(d)), {("a", 1), ("b", 2)})
self.assertEqual(set(self.thetype.items(d)), {("a", 1), ("b", 2)})
# Test invalid usage
self.assertRaises(TypeError, d.items, 1)
@make_dynamo_test
def test_keys(self):
d = self.thetype({"a": 1, "b": 2})
keys = d.keys()
self.assertEqual(set(keys), {"a", "b"})
# Test Dict.keys
self.assertEqual(set(dict.keys(d)), {"a", "b"})
self.assertEqual(set(self.thetype.keys(d)), {"a", "b"})
# Test invalid usage
self.assertRaises(TypeError, d.keys, 1)
@make_dynamo_test
def test_pop(self):
d = self.thetype({"a": 1, "b": 2})
self.assertEqual(d.pop("a"), 1)
self.assertEqual(d, {"b": 2})
self.assertIsNone(d.pop("c", None))
# Test Dict.pop
d = self.thetype({"a": 1, "b": 2})
self.assertEqual(dict.pop(d, "b"), 2)
self.assertEqual(self.thetype.pop(d, "a"), 1)
# Test invalid usage
self.assertRaises(KeyError, d.pop, "c")
self.assertRaises(TypeError, d.pop)
@make_dynamo_test
def test_popitem(self):
d = self.thetype({"a": 1})
key, value = d.popitem()
self.assertEqual(key, "a")
self.assertEqual(value, 1)
self.assertEqual(len(d), 0)
# check LIFO
d = self.thetype()
d["a"] = 1
d["b"] = 2
self.assertEqual(d.popitem(), ("b", 2))
# Test Dict.popitem
d = self.thetype({"a": 1})
key, value = dict.popitem(d)
self.assertEqual(key, "a")
self.assertEqual(value, 1)
d = self.thetype({"a": 1})
key, value = self.thetype.popitem(d)
self.assertEqual(key, "a")
self.assertEqual(value, 1)
# Test invalid usage
if self.thetype is not OrderedDict:
# OrderedDict accepts a keyword arg
self.assertRaises(TypeError, d.popitem, 1)
@make_dynamo_test
def test_setdefault(self):
d = self.thetype({"a": 1, "b": 2})
self.assertEqual(d.setdefault("a", 3), 1)
self.assertEqual(d.setdefault("c", 3), 3)
self.assertIsNone(d.setdefault("d"), None)
self.assertEqual(d, {"a": 1, "b": 2, "c": 3, "d": None})
# Test Dict.setdefault
self.assertEqual(dict.setdefault(d, "f", 5), 5)
self.assertEqual(self.thetype.setdefault(d, "e", 5), 5)
# Test invalid usage
self.assertRaises(TypeError, d.setdefault)
self.assertRaises(TypeError, d.setdefault, [[]])
@make_dynamo_test
def test_update(self):
d = self.thetype({"a": 1, "b": 2})
d.update({"b": 3, "c": 4})
self.assertEqual(d, {"a": 1, "b": 3, "c": 4})
# Test with another dict
d2 = self.thetype({"d": 5})
d.update(d2)
self.assertEqual(d, {"a": 1, "b": 3, "c": 4, "d": 5})
# Test Dict.update
d3 = self.thetype({"e": 6})
dict.update(d, d3)
self.assertEqual(d, {"a": 1, "b": 3, "c": 4, "d": 5, "e": 6})
d4 = self.thetype({"f": 7})
self.thetype.update(d, d4)
self.assertEqual(d, {"a": 1, "b": 3, "c": 4, "d": 5, "e": 6, "f": 7})
# Test with keyword arguments
d.update(f=7, g=8)
self.assertEqual(d, {"a": 1, "b": 3, "c": 4, "d": 5, "e": 6, "f": 7, "g": 8})
# Test Dict.update with keyword arguments
self.thetype.update(d, h=9, i=10)
self.assertEqual(
d, {"a": 1, "b": 3, "c": 4, "d": 5, "e": 6, "f": 7, "g": 8, "h": 9, "i": 10}
)
# Test invalid usage
self.assertRaises(TypeError, d.update, 1)
@make_dynamo_test
def test_values(self):
d = self.thetype({"a": 1, "b": 2})
values = d.values()
self.assertEqual(set(values), {1, 2})
# Test Dict.values
self.assertEqual(set(dict.values(d)), {1, 2})
self.assertEqual(set(self.thetype.values(d)), {1, 2})
# Test invalid usage
self.assertRaises(TypeError, d.values, 1)
@make_dynamo_test
def test_type(self):
d = self.thetype({"a": 1, "b": 2})
self.assertIsInstance(d, self.thetype)
self.assertIs(type(d), self.thetype)
@make_dynamo_test
def test_dict_type_comparison(self):
types = (dict, OrderedDict, defaultdict)
self.assertEqual(self.thetype, self.thetype)
self.assertTrue(self.thetype is self.thetype)
for other in types:
if self.thetype == other:
continue
self.assertNotEqual(self.thetype, other)
self.assertTrue(self.thetype is not other, f"{self.thetype=}, {other=}")
@make_dynamo_test
def test_dict___iter__(self):
d = self.thetype({1: 2})
it = d.__iter__()
self.assertEqual(next(it), 1)
def test_functools_partial_key(self):
def gn(x, y):
return x + y
def fn(x):
new_dict = {}
new_gn1 = partial(gn, x=1)
new_dict[new_gn1] = 5
return x * new_dict[new_gn1]
x = torch.randn(4)
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
ref = fn(x)
res = opt_fn(x)
self.assertTrue(same(ref, res))
def test_namedtuple_functools(self):
class Container(NamedTuple):
partial_fn: Callable
const: int
def gn(x, y):
return x + y
def fn(x):
new_dict = {}
new_gn = partial(gn, x=1)
key = Container(new_gn, 4)
new_dict[key] = 5
return x * new_dict[key]
x = torch.randn(4)
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
ref = fn(x)
res = opt_fn(x)
self.assertTrue(same(ref, res))
| DictMethodsTests |
python | ray-project__ray | python/ray/train/horovod/config.py | {
"start": 2455,
"end": 5757
} | class ____(Backend):
share_cuda_visible_devices: bool = True
def on_start(self, worker_group: WorkerGroup, backend_config: HorovodConfig):
# NOTE: Horovod backend uses V1 WorkerGroup directly instead of BaseWorkerGroup
# because it requires direct access to worker metadata (node_id, hostname) that is
# specific to the V1 implementation. Horovod does not support V2 WorkerGroup.
# TODO(matt): Implement placement group strategies in BackendExecutor.
# Initialize workers with Horovod environment variables
setup_futures = []
for rank in range(len(worker_group)):
worker_node_id = worker_group.workers[rank].metadata.node_id
setup_futures.append(
worker_group.execute_single_async(
rank,
_init_env_vars,
rank,
len(worker_group),
worker_node_id,
)
)
ray.get(setup_futures)
# Use Horovod Ray Coordinator
# backend_config as settings
self.coordinator = Coordinator(backend_config)
# Get all the hostnames of all workers
node_ids = [w.metadata.node_id for w in worker_group.workers]
hostnames = [w.metadata.hostname for w in worker_group.workers]
# Register each hostname to the coordinator. assumes the hostname
# ordering is the same.
for rank, (hostname, node_id) in enumerate(zip(hostnames, node_ids)):
self.coordinator.register(hostname, node_id, rank)
all_info = self.coordinator.finalize_registration()
setup_futures = []
for rank, local_cross_env_var in all_info.items():
setup_futures.append(
worker_group.execute_single_async(
rank, update_env_vars, local_cross_env_var
)
)
ray.get(setup_futures)
coordinator_envs = self.coordinator.establish_rendezvous()
# Get one worker from each host/node.
node_worker_indexes = [node_ids.index(node_id) for node_id in set(node_ids)]
node_workers = [
_HorovodWorkerWrapper(worker_group.workers[worker_index])
for worker_index in node_worker_indexes
]
assert len(node_workers) == len(self.coordinator.hostnames)
nics = detect_nics(
backend_config,
all_host_names=list(self.coordinator.hostnames),
node_workers=node_workers,
)
coordinator_envs.update(nics_to_env_var(nics))
worker_group.execute(update_env_vars, coordinator_envs)
def _init_env_vars(world_rank: int, world_size: int, node_id: str):
"""Initialize Horovod environment variables."""
os.environ["HOROVOD_HOSTNAME"] = node_id
os.environ["HOROVOD_RANK"] = str(world_rank)
os.environ["HOROVOD_SIZE"] = str(world_size)
# TODO(tgaddair): temporary workaround for Horovod's worker discovery logic,
# which requires passing in an extra parameter as part of the RayExecutor
# API. This will be removed in the future as we migrate more of the
# RayExecutor utils into Ray Train.
# See: https://github.com/horovod/horovod/blob/v0.23.0/horovod/ray/driver_service.py#L9 # noqa: E501
@dataclass
| _HorovodBackend |
python | oauthlib__oauthlib | oauthlib/openid/connect/core/grant_types/dispatchers.py | {
"start": 2489,
"end": 3960
} | class ____(Dispatcher):
"""
This is an adapter class that will route simple Token requests, those that authorization_code have a scope
including 'openid' to either the default_grant or the oidc_grant based on the scopes requested.
"""
def __init__(self, request_validator, default_grant=None, oidc_grant=None):
self.default_grant = default_grant
self.oidc_grant = oidc_grant
self.request_validator = request_validator
def _handler_for_request(self, request):
handler = self.default_grant
scopes = ()
parameters = dict(request.decoded_body)
client_id = parameters.get('client_id')
code = parameters.get('code')
redirect_uri = parameters.get('redirect_uri')
# If code is not present fallback to `default_grant` which will
# raise an error for the missing `code` in `create_token_response` step.
if code:
scopes = self.request_validator.get_authorization_code_scopes(client_id, code, redirect_uri, request)
if 'openid' in scopes:
handler = self.oidc_grant
log.debug('Selecting handler for request %r.', handler)
return handler
def create_token_response(self, request, token_handler):
"""Read scope and route to the designated handler."""
handler = self._handler_for_request(request)
return handler.create_token_response(request, token_handler)
| AuthorizationTokenGrantDispatcher |
python | sqlalchemy__sqlalchemy | test/orm/test_cycles.py | {
"start": 20026,
"end": 36503
} | class ____(fixtures.MappedTest):
"""
Tests two mappers, one has a one-to-many on the other mapper, the other
has a separate many-to-one relationship to the first. two tests will have
a row for each item that is dependent on the other. without the
"post_update" flag, such relationships raise an exception when
dependencies are sorted.
"""
run_define_tables = "each"
@classmethod
def define_tables(cls, metadata):
Table(
"ball",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column(
"person_id",
Integer,
ForeignKey("person.id", name="fk_person_id"),
),
Column("data", String(30)),
)
Table(
"person",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("favorite_ball_id", Integer, ForeignKey("ball.id")),
Column("data", String(30)),
)
@classmethod
def setup_classes(cls):
class Person(cls.Basic):
pass
class Ball(cls.Basic):
pass
def test_cycle(self):
"""
This test has a peculiar aspect in that it doesn't create as many
dependent relationships as the other tests, and revealed a small
glitch in the circular dependency sorting.
"""
person, ball, Ball, Person = (
self.tables.person,
self.tables.ball,
self.classes.Ball,
self.classes.Person,
)
self.mapper_registry.map_imperatively(Ball, ball)
self.mapper_registry.map_imperatively(
Person,
person,
properties=dict(
balls=relationship(
Ball,
primaryjoin=ball.c.person_id == person.c.id,
remote_side=ball.c.person_id,
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
),
favorite=relationship(
Ball,
primaryjoin=person.c.favorite_ball_id == ball.c.id,
remote_side=ball.c.id,
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
),
),
)
b = Ball()
p = Person()
p.balls.append(b)
sess = fixture_session()
sess.add(p)
sess.flush()
def test_post_update_m2o_no_cascade(self):
person, ball, Ball, Person = (
self.tables.person,
self.tables.ball,
self.classes.Ball,
self.classes.Person,
)
self.mapper_registry.map_imperatively(Ball, ball)
self.mapper_registry.map_imperatively(
Person,
person,
properties=dict(
favorite=relationship(
Ball,
primaryjoin=person.c.favorite_ball_id == ball.c.id,
post_update=True,
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
)
),
)
b = Ball(data="some data")
p = Person(data="some data")
p.favorite = b
sess = fixture_session()
sess.add(b)
sess.add(p)
sess.flush()
sess.delete(p)
self.assert_sql_execution(
testing.db,
sess.flush,
CompiledSQL(
"UPDATE person SET favorite_ball_id=:favorite_ball_id "
"WHERE person.id = :person_id",
lambda ctx: {"favorite_ball_id": None, "person_id": p.id},
),
CompiledSQL(
"DELETE FROM person WHERE person.id = :id",
lambda ctx: {"id": p.id},
),
)
def test_post_update_m2o(self):
"""A cycle between two rows, with a post_update on the many-to-one"""
person, ball, Ball, Person = (
self.tables.person,
self.tables.ball,
self.classes.Ball,
self.classes.Person,
)
self.mapper_registry.map_imperatively(Ball, ball)
self.mapper_registry.map_imperatively(
Person,
person,
properties=dict(
balls=relationship(
Ball,
primaryjoin=ball.c.person_id == person.c.id,
remote_side=ball.c.person_id,
post_update=False,
cascade="all, delete-orphan",
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
),
favorite=relationship(
Ball,
primaryjoin=person.c.favorite_ball_id == ball.c.id,
post_update=True,
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
),
),
)
b = Ball(data="some data")
p = Person(data="some data")
p.balls.append(b)
p.balls.append(Ball(data="some data"))
p.balls.append(Ball(data="some data"))
p.balls.append(Ball(data="some data"))
p.favorite = b
sess = fixture_session()
sess.add(b)
sess.add(p)
self.assert_sql_execution(
testing.db,
sess.flush,
RegexSQL("^INSERT INTO person", {"data": "some data"}),
Conditional(
testing.db.dialect.insert_executemany_returning,
[
RegexSQL(
"^INSERT INTO ball",
lambda c: [
{"person_id": p.id, "data": "some data"},
{"person_id": p.id, "data": "some data"},
{"person_id": p.id, "data": "some data"},
{"person_id": p.id, "data": "some data"},
],
)
],
[
RegexSQL(
"^INSERT INTO ball",
lambda c: {"person_id": p.id, "data": "some data"},
),
RegexSQL(
"^INSERT INTO ball",
lambda c: {"person_id": p.id, "data": "some data"},
),
RegexSQL(
"^INSERT INTO ball",
lambda c: {"person_id": p.id, "data": "some data"},
),
RegexSQL(
"^INSERT INTO ball",
lambda c: {"person_id": p.id, "data": "some data"},
),
],
),
CompiledSQL(
"UPDATE person SET favorite_ball_id=:favorite_ball_id "
"WHERE person.id = :person_id",
lambda ctx: {
"favorite_ball_id": p.favorite.id,
"person_id": p.id,
},
),
)
sess.delete(p)
self.assert_sql_execution(
testing.db,
sess.flush,
CompiledSQL(
"UPDATE person SET favorite_ball_id=:favorite_ball_id "
"WHERE person.id = :person_id",
lambda ctx: {"person_id": p.id, "favorite_ball_id": None},
),
# lambda ctx:[{'id': 1L}, {'id': 4L}, {'id': 3L}, {'id': 2L}])
CompiledSQL("DELETE FROM ball WHERE ball.id = :id", None),
CompiledSQL(
"DELETE FROM person WHERE person.id = :id",
lambda ctx: [{"id": p.id}],
),
)
def test_post_update_backref(self):
"""test bidirectional post_update."""
person, ball, Ball, Person = (
self.tables.person,
self.tables.ball,
self.classes.Ball,
self.classes.Person,
)
self.mapper_registry.map_imperatively(Ball, ball)
self.mapper_registry.map_imperatively(
Person,
person,
properties=dict(
balls=relationship(
Ball,
primaryjoin=ball.c.person_id == person.c.id,
remote_side=ball.c.person_id,
post_update=True,
backref=backref(
"person",
post_update=True,
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
),
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
),
favorite=relationship(
Ball,
primaryjoin=person.c.favorite_ball_id == ball.c.id,
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
),
),
)
sess = fixture_session()
p1 = Person(data="p1")
p2 = Person(data="p2")
p3 = Person(data="p3")
b1 = Ball(data="b1")
b1.person = p1
sess.add_all([p1, p2, p3])
sess.commit()
# switch here. the post_update
# on ball.person can't get tripped up
# by the fact that there's a "reverse" prop.
b1.person = p2
sess.commit()
eq_(p2, b1.person)
# do it the other way
p3.balls.append(b1)
sess.commit()
eq_(p3, b1.person)
def test_post_update_o2m(self):
"""A cycle between two rows, with a post_update on the one-to-many"""
person, ball, Ball, Person = (
self.tables.person,
self.tables.ball,
self.classes.Ball,
self.classes.Person,
)
self.mapper_registry.map_imperatively(Ball, ball)
self.mapper_registry.map_imperatively(
Person,
person,
properties=dict(
balls=relationship(
Ball,
primaryjoin=ball.c.person_id == person.c.id,
remote_side=ball.c.person_id,
cascade="all, delete-orphan",
post_update=True,
backref="person",
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
),
favorite=relationship(
Ball,
primaryjoin=person.c.favorite_ball_id == ball.c.id,
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
),
),
)
b = Ball(data="some data")
p = Person(data="some data")
p.balls.append(b)
b2 = Ball(data="some data")
p.balls.append(b2)
b3 = Ball(data="some data")
p.balls.append(b3)
b4 = Ball(data="some data")
p.balls.append(b4)
p.favorite = b
sess = fixture_session()
sess.add_all((b, p, b2, b3, b4))
self.assert_sql_execution(
testing.db,
sess.flush,
Conditional(
testing.db.dialect.insert_executemany_returning,
[
CompiledSQL(
"INSERT INTO ball (person_id, data) "
"VALUES (:person_id, :data) RETURNING ball.id",
[
{"person_id": None, "data": "some data"},
{"person_id": None, "data": "some data"},
{"person_id": None, "data": "some data"},
{"person_id": None, "data": "some data"},
],
),
],
[
CompiledSQL(
"INSERT INTO ball (person_id, data) "
"VALUES (:person_id, :data)",
{"person_id": None, "data": "some data"},
),
CompiledSQL(
"INSERT INTO ball (person_id, data) "
"VALUES (:person_id, :data)",
{"person_id": None, "data": "some data"},
),
CompiledSQL(
"INSERT INTO ball (person_id, data) "
"VALUES (:person_id, :data)",
{"person_id": None, "data": "some data"},
),
CompiledSQL(
"INSERT INTO ball (person_id, data) "
"VALUES (:person_id, :data)",
{"person_id": None, "data": "some data"},
),
],
),
CompiledSQL(
"INSERT INTO person (favorite_ball_id, data) "
"VALUES (:favorite_ball_id, :data)",
lambda ctx: {"favorite_ball_id": b.id, "data": "some data"},
),
CompiledSQL(
"UPDATE ball SET person_id=:person_id "
"WHERE ball.id = :ball_id",
lambda ctx: [
{"person_id": p.id, "ball_id": b.id},
{"person_id": p.id, "ball_id": b2.id},
{"person_id": p.id, "ball_id": b3.id},
{"person_id": p.id, "ball_id": b4.id},
],
),
)
sess.delete(p)
self.assert_sql_execution(
testing.db,
sess.flush,
CompiledSQL(
"UPDATE ball SET person_id=:person_id "
"WHERE ball.id = :ball_id",
lambda ctx: [
{"person_id": None, "ball_id": b.id},
{"person_id": None, "ball_id": b2.id},
{"person_id": None, "ball_id": b3.id},
{"person_id": None, "ball_id": b4.id},
],
),
CompiledSQL(
"DELETE FROM person WHERE person.id = :id",
lambda ctx: [{"id": p.id}],
),
CompiledSQL(
"DELETE FROM ball WHERE ball.id = :id",
lambda ctx: [
{"id": b.id},
{"id": b2.id},
{"id": b3.id},
{"id": b4.id},
],
),
)
def test_post_update_m2o_detect_none(self):
person, ball, Ball, Person = (
self.tables.person,
self.tables.ball,
self.classes.Ball,
self.classes.Person,
)
self.mapper_registry.map_imperatively(
Ball,
ball,
properties={
"person": relationship(
Person,
post_update=True,
primaryjoin=person.c.id == ball.c.person_id,
_legacy_inactive_history_style=(
self._legacy_inactive_history_style
),
)
},
)
self.mapper_registry.map_imperatively(Person, person)
sess = fixture_session(expire_on_commit=True)
p1 = Person()
sess.add(Ball(person=p1))
sess.commit()
b1 = sess.query(Ball).first()
# needs to be unloaded
assert "person" not in b1.__dict__
b1.person = None
self.assert_sql_execution(
testing.db,
sess.flush,
CompiledSQL(
"UPDATE ball SET person_id=:person_id "
"WHERE ball.id = :ball_id",
lambda ctx: {"person_id": None, "ball_id": b1.id},
),
)
is_(b1.person, None)
| OneToManyManyToOneTest |
python | PyCQA__pylint | tests/functional/s/signature_differs.py | {
"start": 61,
"end": 236
} | class ____:
def __init__(self):
self.aarg = False
def abcd(self, aaa=1, bbbb=None):
return aaa, bbbb
def args(self):
self.aarg = True
| Abcd |
python | astropy__astropy | astropy/visualization/tests/test_norm.py | {
"start": 7586,
"end": 13114
} | class ____:
def test_linear(self):
"""Test linear scaling."""
norm = simple_norm(DATA2, stretch="linear")
assert_allclose(norm(DATA2), DATA2SCL, atol=0, rtol=1.0e-5)
def test_sqrt(self):
"""Test sqrt scaling."""
norm1 = simple_norm(DATA2, stretch="sqrt")
assert_allclose(norm1(DATA2), np.sqrt(DATA2SCL), atol=0, rtol=1.0e-5)
@pytest.mark.parametrize("invalid", INVALID)
def test_sqrt_invalid_kw(self, invalid):
stretch = SqrtStretch()
norm1 = simple_norm(
DATA3, stretch="sqrt", vmin=-1, vmax=1, clip=False, invalid=invalid
)
norm2 = ImageNormalize(
stretch=stretch, vmin=-1, vmax=1, clip=False, invalid=invalid
)
assert_equal(norm1(DATA3), norm2(DATA3))
def test_power(self):
"""Test power scaling."""
power = 3.0
norm = simple_norm(DATA2, stretch="power", power=power)
assert_allclose(norm(DATA2), DATA2SCL**power, atol=0, rtol=1.0e-5)
def test_log(self):
"""Test log10 scaling."""
norm = simple_norm(DATA2, stretch="log")
ref = np.log10(1000 * DATA2SCL + 1.0) / np.log10(1001.0)
assert_allclose(norm(DATA2), ref, atol=0, rtol=1.0e-5)
def test_log_with_log_a(self):
"""Test log10 scaling with a custom log_a."""
log_a = 100
norm = simple_norm(DATA2, stretch="log", log_a=log_a)
ref = np.log10(log_a * DATA2SCL + 1.0) / np.log10(log_a + 1)
assert_allclose(norm(DATA2), ref, atol=0, rtol=1.0e-5)
def test_asinh(self):
"""Test asinh scaling."""
norm = simple_norm(DATA2, stretch="asinh")
ref = np.arcsinh(10 * DATA2SCL) / np.arcsinh(10)
assert_allclose(norm(DATA2), ref, atol=0, rtol=1.0e-5)
def test_asinh_with_asinh_a(self):
"""Test asinh scaling with a custom asinh_a."""
asinh_a = 0.5
norm = simple_norm(DATA2, stretch="asinh", asinh_a=asinh_a)
ref = np.arcsinh(DATA2SCL / asinh_a) / np.arcsinh(1.0 / asinh_a)
assert_allclose(norm(DATA2), ref, atol=0, rtol=1.0e-5)
def test_sinh(self):
"""Test sinh scaling."""
sinh_a = 0.5
norm = simple_norm(DATA2, stretch="sinh", sinh_a=sinh_a)
ref = np.sinh(DATA2SCL / sinh_a) / np.sinh(1 / sinh_a)
assert_allclose(norm(DATA2), ref, atol=0, rtol=1.0e-5)
def test_min(self):
"""Test linear scaling."""
norm = simple_norm(DATA2, stretch="linear", vmin=1.0, clip=True)
assert_allclose(norm(DATA2), [0.0, 0.0, 1.0], atol=0, rtol=1.0e-5)
def test_percent(self):
"""Test percent keywords."""
norm = simple_norm(DATA2, stretch="linear", percent=99.0, clip=True)
assert_allclose(norm(DATA2), DATA2SCL, atol=0, rtol=1.0e-5)
norm2 = simple_norm(
DATA2, stretch="linear", min_percent=0.5, max_percent=99.5, clip=True
)
assert_allclose(norm(DATA2), norm2(DATA2), atol=0, rtol=1.0e-5)
def test_invalid_stretch(self):
"""Test invalid stretch keyword."""
with pytest.raises(ValueError):
simple_norm(DATA2, stretch="invalid")
@pytest.mark.skipif(not HAS_PLT, reason="requires matplotlib")
@pytest.mark.parametrize("stretch", ["linear", "sqrt", "power", "log", "asinh", "sinh"])
def test_simplenorm(stretch):
data = np.arange(25).reshape((5, 5))
snorm = SimpleNorm(stretch, percent=99)
norm = snorm(data)
assert isinstance(norm, ImageNormalize)
assert_allclose(norm(data), simple_norm(data, stretch, percent=99)(data))
@pytest.mark.skipif(not HAS_PLT, reason="requires matplotlib")
def test_simplenorm_imshow():
from matplotlib.figure import Figure
from matplotlib.image import AxesImage
data = np.arange(25).reshape((5, 5))
fig = Figure()
ax = fig.add_subplot()
snorm = SimpleNorm("sqrt", percent=99)
axim = snorm.imshow(data, ax=ax)
assert isinstance(axim, AxesImage)
keys = ("vmin", "vmax", "stretch", "clip", "invalid")
for key in keys:
assert getattr(axim.norm, key) == getattr(snorm(data), key)
fig.clear()
axim = snorm.imshow(data, ax=None)
with pytest.raises(ValueError):
snorm.imshow(data, ax=ax, norm=ImageNormalize())
@pytest.mark.skipif(not HAS_PLT, reason="requires matplotlib")
def test_imshow_norm():
from matplotlib.figure import Figure
image = np.random.randn(10, 10)
fig = Figure()
ax = fig.add_subplot(label="test_imshow_norm")
imshow_norm(image, ax=ax)
with pytest.raises(ValueError):
# illegal to manually pass in normalization since that defeats the point
imshow_norm(image, ax=ax, norm=ImageNormalize())
fig.clear()
imshow_norm(image, ax=ax, vmin=0, vmax=1)
# make sure the matplotlib version works
fig.clear()
imres, norm = imshow_norm(image, ax=None)
assert isinstance(norm, ImageNormalize)
@pytest.mark.skipif(not HAS_PLT, reason="requires matplotlib")
def test_norm_without_data():
from matplotlib.figure import Figure
image = np.arange(10).reshape((1, 10))
interval = ManualInterval(2, 5)
norm_without_data = ImageNormalize(interval=interval)
assert norm_without_data.vmin is None
assert norm_without_data.vmax is None
fig = Figure()
ax = fig.add_subplot()
ax.imshow(image, norm=norm_without_data) # calls norm_without_data.autoscale_None()
assert norm_without_data.vmin == interval.vmin
assert norm_without_data.vmax == interval.vmax
| TestImageScaling |
python | python__mypy | mypyc/irbuild/for_helpers.py | {
"start": 39055,
"end": 40286
} | class ____(ForDictionaryCommon):
"""Generate optimized IR for a for loop over dictionary items."""
dict_next_op = dict_next_item_op
dict_iter_op = dict_item_iter_op
def begin_body(self) -> None:
builder = self.builder
line = self.line
key = builder.add(TupleGet(self.next_tuple, 2, line))
value = builder.add(TupleGet(self.next_tuple, 3, line))
# Coerce just in case e.g. key is itself a tuple to be unpacked.
assert isinstance(self.target_type, RTuple), self.target_type
key = builder.coerce(key, self.target_type.types[0], line)
value = builder.coerce(value, self.target_type.types[1], line)
target = builder.get_assignment_target(self.index)
if isinstance(target, AssignmentTargetTuple):
# Simpler code for common case: for k, v in d.items().
if len(target.items) != 2:
builder.error("Expected a pair for dict item iteration", line)
builder.assign(target.items[0], key, line)
builder.assign(target.items[1], value, line)
else:
rvalue = builder.add(TupleSet([key, value], line))
builder.assign(target, rvalue, line)
| ForDictionaryItems |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 25356,
"end": 25845
} | class ____(Sky2PixProjection, PseudoCylindrical):
r"""
Molleweide's projection - sky to pixel.
Corresponds to the ``MOL`` projection in FITS WCS.
.. math::
x &= \frac{2 \sqrt{2}}{\pi} \phi \cos \gamma \\
y &= \sqrt{2} \frac{180^\circ}{\pi} \sin \gamma
where :math:`\gamma` is defined as the solution of the
transcendental equation:
.. math::
\sin \theta = \frac{\gamma}{90^\circ} + \frac{\sin 2 \gamma}{\pi}
"""
| Sky2Pix_Molleweide |
python | skorch-dev__skorch | skorch/tests/test_hf.py | {
"start": 1259,
"end": 7016
} | class ____:
"""Base class for testing huggingface tokenizer transformers
Should implement a (parametrized) ``tokenizer`` fixture.
Tests should not call ``fit`` since that can be expensive for pretrained
tokenizers. Instead, implement these tests on the subclass if necessary.
"""
@pytest.fixture(scope='module')
def data(self):
return [
"The Zen of Python, by Tim Peters",
"Beautiful is better than ugly.",
"Explicit is better than implicit.",
"Simple is better than complex.",
"Complex is better than complicated.",
"Flat is better than nested.",
"Sparse is better than dense.",
"Readability counts.",
"Special cases aren't special enough to break the rules.",
"Although practicality beats purity.",
"Errors should never pass silently.",
"Unless explicitly silenced.",
"In the face of ambiguity, refuse the temptation to guess.",
"There should be one-- and preferably only one --obvious way to do it.",
"Although that way may not be obvious at first unless you're Dutch.",
"Now is better than never.",
"Although never is often better than *right* now.",
"If the implementation is hard to explain, it's a bad idea.",
"If the implementation is easy to explain, it may be a good idea.",
"Namespaces are one honking great idea -- let's do more of those!",
]
def test_transform(self, tokenizer, data):
Xt = tokenizer.transform(data)
assert 'input_ids' in Xt
assert 'attention_mask' in Xt
for val in Xt.values():
assert val.shape[0] == len(data)
assert val.shape[1] == tokenizer.max_length
assert isinstance(val, torch.Tensor)
def test_with_numpy_array(self, tokenizer, data):
# does not raise
tokenizer.transform(np.array(data))
def test_inverse_transform(self, tokenizer, data):
# Inverse transform does not necessarily result in the exact same
# output; therefore, we test text similarity.
Xt = tokenizer.transform(data)
Xt_inv = tokenizer.inverse_transform(Xt)
cutoff = 0.9
for x_orig, x_dec, x_other in zip(data, Xt_inv, data[1:]):
# check that original and inverse transform are similar
assert text_similarity(x_orig, x_dec) > cutoff
assert text_similarity(x_orig, x_other) < cutoff
def test_tokenize(self, tokenizer, data):
tokens = tokenizer.tokenize(data)
assert tokens.shape == (len(data), tokenizer.max_length)
assert isinstance(tokens[0][0], str)
def test_tokenize_skip_special_tokens(self, tokenizer, data):
# Check that the tokens don't contain pad tokens. Only works if we
# actually know the pad token.
if not hasattr(tokenizer, 'pad_token'):
return
tokens = tokenizer.tokenize(data, skip_special_tokens=True)
last_col = tokens[:, -1]
assert not (last_col == tokenizer.pad_token).any()
def test_vocabulary(self, tokenizer):
assert isinstance(tokenizer.vocabulary_, dict)
# vocabulary size is not always exactly as indicated
vocab_size = pytest.approx(len(tokenizer.vocabulary_), abs=10)
assert vocab_size == tokenizer.fast_tokenizer_.vocab_size
def test_get_feature_names_out(self, tokenizer):
feature_names = tokenizer.get_feature_names_out()
assert isinstance(feature_names, np.ndarray)
assert isinstance(feature_names[0], str)
def test_keys_in_output(self, tokenizer, data):
Xt = tokenizer.transform(data)
assert len(Xt) == 2
assert 'input_ids' in Xt
assert 'attention_mask' in Xt
def test_return_token_type_ids(self, tokenizer, data):
with temporary_set_param(tokenizer, 'return_token_type_ids', True):
Xt = tokenizer.transform(data)
assert 'token_type_ids' in Xt
def test_return_length(self, tokenizer, data):
with temporary_set_param(tokenizer, 'return_length', True):
Xt = tokenizer.transform(data)
assert 'length' in Xt
def test_return_attention_mask(self, tokenizer, data):
with temporary_set_param(tokenizer, 'return_attention_mask', False):
Xt = tokenizer.transform(data)
assert 'attention_mask' not in Xt
def test_return_lists(self, tokenizer, data):
with temporary_set_param(tokenizer, 'return_tensors', None):
Xt = tokenizer.transform(data)
assert set(Xt) == {'input_ids', 'attention_mask'}
for val in Xt.values():
assert isinstance(val, list)
assert isinstance(val[0], list)
# input type ids can have different lengths because they're not padded
# or truncated
assert len(set(len(row) for row in Xt['input_ids'])) != 1
def test_numpy_arrays(self, tokenizer, data):
with temporary_set_param(tokenizer, 'return_tensors', 'np'):
Xt = tokenizer.transform(data)
assert 'input_ids' in Xt
assert 'attention_mask' in Xt
for val in Xt.values():
assert val.shape[0] == len(data)
assert val.shape[1] == tokenizer.max_length
assert isinstance(val, np.ndarray)
def test_pickle(self, tokenizer):
# does not raise
pickled = pickle.dumps(tokenizer)
pickle.loads(pickled)
def test_deepcopy(self, tokenizer):
deepcopy(tokenizer) # does not raise
def test_clone(self, tokenizer):
clone(tokenizer) # does not raise
| _HuggingfaceTokenizersBaseTest |
python | ray-project__ray | python/ray/autoscaler/_private/kuberay/node_provider.py | {
"start": 9661,
"end": 12425
} | class ____(IKubernetesHttpApiClient):
def __init__(self, namespace: str, kuberay_crd_version: str = KUBERAY_CRD_VER):
self._kuberay_crd_version = kuberay_crd_version
self._namespace = namespace
self._token_expires_at = datetime.datetime.now() + TOKEN_REFRESH_PERIOD
self._headers, self._verify = None, None
def _get_refreshed_headers_and_verify(self):
if (datetime.datetime.now() >= self._token_expires_at) or (
self._headers is None or self._verify is None
):
logger.info("Refreshing K8s API client token and certs.")
self._headers, self._verify = load_k8s_secrets()
self._token_expires_at = datetime.datetime.now() + TOKEN_REFRESH_PERIOD
return self._headers, self._verify
else:
return self._headers, self._verify
def get(self, path: str) -> Dict[str, Any]:
"""Wrapper for REST GET of resource with proper headers.
Args:
path: The part of the resource path that starts with the resource type.
Returns:
The JSON response of the GET request.
Raises:
HTTPError: If the GET request fails.
"""
url = url_from_resource(
namespace=self._namespace,
path=path,
kuberay_crd_version=self._kuberay_crd_version,
)
headers, verify = self._get_refreshed_headers_and_verify()
result = requests.get(
url,
headers=headers,
timeout=KUBERAY_REQUEST_TIMEOUT_S,
verify=verify,
)
if not result.status_code == 200:
result.raise_for_status()
return result.json()
def patch(self, path: str, payload: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Wrapper for REST PATCH of resource with proper headers
Args:
path: The part of the resource path that starts with the resource type.
payload: The JSON patch payload.
Returns:
The JSON response of the PATCH request.
Raises:
HTTPError: If the PATCH request fails.
"""
url = url_from_resource(
namespace=self._namespace,
path=path,
kuberay_crd_version=self._kuberay_crd_version,
)
headers, verify = self._get_refreshed_headers_and_verify()
result = requests.patch(
url,
json.dumps(payload),
headers={**headers, "Content-type": "application/json-patch+json"},
timeout=KUBERAY_REQUEST_TIMEOUT_S,
verify=verify,
)
if not result.status_code == 200:
result.raise_for_status()
return result.json()
| KubernetesHttpApiClient |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 22412,
"end": 23551
} | class ____(Response):
"""
Response of queues.add_task endpoint.
:param added: Number of tasks added (0 or 1)
:type added: int
"""
_service = "queues"
_action = "add_task"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"added": {
"description": "Number of tasks added (0 or 1)",
"enum": [0, 1],
"type": ["integer", "null"],
}
},
"type": "object",
}
def __init__(self, added: Optional[int] = None, **kwargs: Any) -> None:
super(AddTaskResponse, self).__init__(**kwargs)
self.added = added
@schema_property("added")
def added(self) -> Optional[int]:
return self._property_added
@added.setter
def added(self, value: Optional[int]) -> None:
if value is None:
self._property_added = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "added", six.integer_types)
self._property_added = value
| AddTaskResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/unit_tests/integration/api/bulk.py | {
"start": 4030,
"end": 5069
} | class ____:
def __init__(self, job_created_at: str = "2024-05-05T02:00:00Z") -> None:
self._template = {
"data": {
"bulkOperationRunQuery": {
"bulkOperation": {"id": "gid://shopify/BulkOperation/0", "status": "CREATED", "createdAt": f"{job_created_at}"},
"userErrors": [],
}
},
"extensions": {
"cost": {
"requestedQueryCost": 10,
"actualQueryCost": 10,
"throttleStatus": {"maximumAvailable": 2000.0, "currentlyAvailable": 1990, "restoreRate": 100.0},
}
},
}
def with_bulk_operation_id(self, bulk_operation_id: str) -> "JobCreationResponseBuilder":
self._template["data"]["bulkOperationRunQuery"]["bulkOperation"]["id"] = bulk_operation_id
return self
def build(self) -> HttpResponse:
return HttpResponse(json.dumps(self._template), status_code=200)
| JobCreationResponseBuilder |
python | jd__tenacity | tenacity/wait.py | {
"start": 8361,
"end": 9408
} | class ____(wait_base):
"""Wait strategy that applies exponential backoff and jitter.
It allows for a customized initial wait, maximum wait and jitter.
This implements the strategy described here:
https://cloud.google.com/storage/docs/retry-strategy
The wait time is min(initial * 2**n + random.uniform(0, jitter), maximum)
where n is the retry count.
"""
def __init__(
self,
initial: float = 1,
max: float = _utils.MAX_WAIT, # noqa
exp_base: float = 2,
jitter: float = 1,
) -> None:
self.initial = initial
self.max = max
self.exp_base = exp_base
self.jitter = jitter
def __call__(self, retry_state: "RetryCallState") -> float:
jitter = random.uniform(0, self.jitter)
try:
exp = self.exp_base ** (retry_state.attempt_number - 1)
result = self.initial * exp + jitter
except OverflowError:
result = self.max
return max(0, min(result, self.max))
| wait_exponential_jitter |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-deepset/destination_deepset/writer.py | {
"start": 452,
"end": 2409
} | class ____:
def __init__(self, api_client: DeepsetCloudApi) -> None:
self.client = api_client
@classmethod
def factory(cls, config: Mapping[str, Any]) -> DeepsetCloudFileWriter:
"""Create an instance of this writer using a mapping of config values.
Args:
config (Mapping[str, Any]): the configuration values as defined in `spec.json`.
Returns:
DeepsetCloudFileWriter: An instance of this class.
"""
try:
parsed_config = DeepsetCloudConfig.model_validate(config)
except ValueError as ex:
msg = "Failed to parse configuration into deepset cloud configuration."
raise WriterError(msg) from ex
else:
return cls(api_client=DeepsetCloudApi(config=parsed_config))
def write(
self,
file: DeepsetCloudFile,
destination_sync_mode: DestinationSyncMode = DestinationSyncMode.append_dedup,
) -> AirbyteMessage:
"""Write a record to deepset cloud workspace.
Args:
message (AirbyteMessage): The Airbyte message to write
destination_sync_mode (DestinationSyncMode, Optional): The destination sync mode. Defaults to
`append_dedup`.
Returns:
AirbyteMessage: Returns an Airbyte message with a suitable status.
"""
write_mode = util.get_file_write_mode(destination_sync_mode)
try:
file_id = self.client.upload(file, write_mode=write_mode)
except APIError as ex:
return util.get_trace_message(
f"Failed to upload a record to deepset cloud workspace, workspace = {self.client.config.workspace}.",
exception=ex,
)
else:
return util.get_log_message(
f"File uploaded, file_name = {file.name}, {file_id = }, workspace = {self.client.config.workspace}."
)
| DeepsetCloudFileWriter |
python | openai__openai-python | src/openai/types/responses/response_output_item_added_event.py | {
"start": 258,
"end": 644
} | class ____(BaseModel):
item: ResponseOutputItem
"""The output item that was added."""
output_index: int
"""The index of the output item that was added."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["response.output_item.added"]
"""The type of the event. Always `response.output_item.added`."""
| ResponseOutputItemAddedEvent |
python | huggingface__transformers | src/transformers/models/lfm2/modular_lfm2.py | {
"start": 17199,
"end": 20152
} | class ____(LlamaModel):
def __init__(self, config: Lfm2Config):
super().__init__(config)
self.embedding_norm = Lfm2RMSNorm(config.hidden_size, eps=config.norm_eps)
del self.norm
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Lfm2HybridConvCache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if use_cache and past_key_values is None:
batch_size = inputs_embeds.shape[0]
past_key_values = Lfm2HybridConvCache(
config=self.config, max_batch_size=batch_size, dtype=self.dtype, device=self.device
)
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
causal_mask = create_causal_mask(
config=self.config,
input_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
past_key_values=past_key_values,
position_ids=position_ids,
)
# Skip masking for decoding stage. We check shape here to be compile-friendly
linear_attention = attention_mask if inputs_embeds.shape[1] != 1 else None
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
# decoder layers
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
layer_mask = causal_mask if decoder_layer.is_attention_layer else linear_attention
hidden_states = decoder_layer(
hidden_states,
attention_mask=layer_mask,
position_embeddings=position_embeddings,
position_ids=position_ids,
past_key_values=past_key_values,
cache_position=cache_position,
**kwargs,
)
hidden_states = self.embedding_norm(hidden_states)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
| Lfm2Model |
python | doocs__leetcode | solution/1500-1599/1598.Crawler Log Folder/Solution.py | {
"start": 0,
"end": 247
} | class ____:
def minOperations(self, logs: List[str]) -> int:
ans = 0
for v in logs:
if v == "../":
ans = max(0, ans - 1)
elif v[0] != ".":
ans += 1
return ans
| Solution |
python | django-haystack__django-haystack | test_haystack/mocks.py | {
"start": 1175,
"end": 2989
} | class ____(BaseSearchBackend):
model_name = "mockmodel"
def update(self, index, iterable, commit=True):
global MOCK_INDEX_DATA
for obj in iterable:
doc = index.full_prepare(obj)
MOCK_INDEX_DATA[doc["id"]] = doc
def remove(self, obj, commit=True):
global MOCK_INDEX_DATA
if commit:
del MOCK_INDEX_DATA[get_identifier(obj)]
def clear(self, models=None, commit=True):
global MOCK_INDEX_DATA
MOCK_INDEX_DATA = {}
@log_query
def search(self, query_string, **kwargs):
from haystack import connections
global MOCK_INDEX_DATA
results = []
hits = len(MOCK_INDEX_DATA)
indexed_models = connections["default"].get_unified_index().get_indexed_models()
def junk_sort(key):
app, model, pk = key.split(".")
if pk.isdigit():
return int(pk)
else:
return ord(pk[0])
sliced = sorted(MOCK_INDEX_DATA, key=junk_sort)
for i, result in enumerate(sliced):
app_label, model_name, pk = result.split(".")
model = apps.get_model(app_label, model_name)
if model:
if model in indexed_models:
results.append(
MockSearchResult(app_label, model_name, pk, 1 - (i / 100.0))
)
else:
hits -= 1
else:
hits -= 1
return {
"results": results[kwargs.get("start_offset") : kwargs.get("end_offset")],
"hits": hits,
}
def more_like_this(
self, model_instance, additional_query_string=None, result_class=None
):
return self.search(query_string="*")
| MockSearchBackend |
python | paramiko__paramiko | paramiko/file.py | {
"start": 1015,
"end": 19063
} | class ____(ClosingContextManager):
"""
Reusable base class to implement Python-style file buffering around a
simpler stream.
"""
_DEFAULT_BUFSIZE = 8192
SEEK_SET = 0
SEEK_CUR = 1
SEEK_END = 2
FLAG_READ = 0x1
FLAG_WRITE = 0x2
FLAG_APPEND = 0x4
FLAG_BINARY = 0x10
FLAG_BUFFERED = 0x20
FLAG_LINE_BUFFERED = 0x40
FLAG_UNIVERSAL_NEWLINE = 0x80
def __init__(self):
self.newlines = None
self._flags = 0
self._bufsize = self._DEFAULT_BUFSIZE
self._wbuffer = BytesIO()
self._rbuffer = bytes()
self._at_trailing_cr = False
self._closed = False
# pos - position within the file, according to the user
# realpos - position according the OS
# (these may be different because we buffer for line reading)
self._pos = self._realpos = 0
# size only matters for seekable files
self._size = 0
def __del__(self):
self.close()
def __iter__(self):
"""
Returns an iterator that can be used to iterate over the lines in this
file. This iterator happens to return the file itself, since a file is
its own iterator.
:raises: ``ValueError`` -- if the file is closed.
"""
if self._closed:
raise ValueError("I/O operation on closed file")
return self
def close(self):
"""
Close the file. Future read and write operations will fail.
"""
self.flush()
self._closed = True
def flush(self):
"""
Write out any data in the write buffer. This may do nothing if write
buffering is not turned on.
"""
self._write_all(self._wbuffer.getvalue())
self._wbuffer = BytesIO()
return
def __next__(self):
"""
Returns the next line from the input, or raises ``StopIteration``
when EOF is hit. Unlike python file objects, it's okay to mix
calls to `.next` and `.readline`.
:raises: ``StopIteration`` -- when the end of the file is reached.
:returns:
a line (`str`, or `bytes` if the file was opened in binary mode)
read from the file.
"""
line = self.readline()
if not line:
raise StopIteration
return line
def readable(self):
"""
Check if the file can be read from.
:returns:
`True` if the file can be read from. If `False`, `read` will raise
an exception.
"""
return (self._flags & self.FLAG_READ) == self.FLAG_READ
def writable(self):
"""
Check if the file can be written to.
:returns:
`True` if the file can be written to. If `False`, `write` will
raise an exception.
"""
return (self._flags & self.FLAG_WRITE) == self.FLAG_WRITE
def seekable(self):
"""
Check if the file supports random access.
:returns:
`True` if the file supports random access. If `False`, `seek` will
raise an exception.
"""
return False
def readinto(self, buff):
"""
Read up to ``len(buff)`` bytes into ``bytearray`` *buff* and return the
number of bytes read.
:returns:
The number of bytes read.
"""
data = self.read(len(buff))
buff[: len(data)] = data
return len(data)
def read(self, size=None):
"""
Read at most ``size`` bytes from the file (less if we hit the end of
the file first). If the ``size`` argument is negative or omitted,
read all the remaining data in the file.
.. note::
``'b'`` mode flag is ignored (``self.FLAG_BINARY`` in
``self._flags``), because SSH treats all files as binary, since we
have no idea what encoding the file is in, or even if the file is
text data.
:param int size: maximum number of bytes to read
:returns:
data read from the file (as bytes), or an empty string if EOF was
encountered immediately
"""
if self._closed:
raise IOError("File is closed")
if not (self._flags & self.FLAG_READ):
raise IOError("File is not open for reading")
if (size is None) or (size < 0):
# go for broke
result = bytearray(self._rbuffer)
self._rbuffer = bytes()
self._pos += len(result)
while True:
try:
new_data = self._read(self._DEFAULT_BUFSIZE)
except EOFError:
new_data = None
if (new_data is None) or (len(new_data) == 0):
break
result.extend(new_data)
self._realpos += len(new_data)
self._pos += len(new_data)
return bytes(result)
if size <= len(self._rbuffer):
result = self._rbuffer[:size]
self._rbuffer = self._rbuffer[size:]
self._pos += len(result)
return result
while len(self._rbuffer) < size:
read_size = size - len(self._rbuffer)
if self._flags & self.FLAG_BUFFERED:
read_size = max(self._bufsize, read_size)
try:
new_data = self._read(read_size)
except EOFError:
new_data = None
if (new_data is None) or (len(new_data) == 0):
break
self._rbuffer += new_data
self._realpos += len(new_data)
result = self._rbuffer[:size]
self._rbuffer = self._rbuffer[size:]
self._pos += len(result)
return result
def readline(self, size=None):
"""
Read one entire line from the file. A trailing newline character is
kept in the string (but may be absent when a file ends with an
incomplete line). If the size argument is present and non-negative, it
is a maximum byte count (including the trailing newline) and an
incomplete line may be returned. An empty string is returned only when
EOF is encountered immediately.
.. note::
Unlike stdio's ``fgets``, the returned string contains null
characters (``'\\0'``) if they occurred in the input.
:param int size: maximum length of returned string.
:returns:
next line of the file, or an empty string if the end of the
file has been reached.
If the file was opened in binary (``'b'``) mode: bytes are returned
Else: the encoding of the file is assumed to be UTF-8 and character
strings (`str`) are returned
"""
# it's almost silly how complex this function is.
if self._closed:
raise IOError("File is closed")
if not (self._flags & self.FLAG_READ):
raise IOError("File not open for reading")
line = self._rbuffer
truncated = False
while True:
if (
self._at_trailing_cr
and self._flags & self.FLAG_UNIVERSAL_NEWLINE
and len(line) > 0
):
# edge case: the newline may be '\r\n' and we may have read
# only the first '\r' last time.
if line[0] == linefeed_byte_value:
line = line[1:]
self._record_newline(crlf)
else:
self._record_newline(cr_byte)
self._at_trailing_cr = False
# check size before looking for a linefeed, in case we already have
# enough.
if (size is not None) and (size >= 0):
if len(line) >= size:
# truncate line
self._rbuffer = line[size:]
line = line[:size]
truncated = True
break
n = size - len(line)
else:
n = self._bufsize
if linefeed_byte in line or (
self._flags & self.FLAG_UNIVERSAL_NEWLINE and cr_byte in line
):
break
try:
new_data = self._read(n)
except EOFError:
new_data = None
if (new_data is None) or (len(new_data) == 0):
self._rbuffer = bytes()
self._pos += len(line)
return line if self._flags & self.FLAG_BINARY else u(line)
line += new_data
self._realpos += len(new_data)
# find the newline
pos = line.find(linefeed_byte)
if self._flags & self.FLAG_UNIVERSAL_NEWLINE:
rpos = line.find(cr_byte)
if (rpos >= 0) and (rpos < pos or pos < 0):
pos = rpos
if pos == -1:
# we couldn't find a newline in the truncated string, return it
self._pos += len(line)
return line if self._flags & self.FLAG_BINARY else u(line)
xpos = pos + 1
if (
line[pos] == cr_byte_value
and xpos < len(line)
and line[xpos] == linefeed_byte_value
):
xpos += 1
# if the string was truncated, _rbuffer needs to have the string after
# the newline character plus the truncated part of the line we stored
# earlier in _rbuffer
if truncated:
self._rbuffer = line[xpos:] + self._rbuffer
else:
self._rbuffer = line[xpos:]
lf = line[pos:xpos]
line = line[:pos] + linefeed_byte
if (len(self._rbuffer) == 0) and (lf == cr_byte):
# we could read the line up to a '\r' and there could still be a
# '\n' following that we read next time. note that and eat it.
self._at_trailing_cr = True
else:
self._record_newline(lf)
self._pos += len(line)
return line if self._flags & self.FLAG_BINARY else u(line)
def readlines(self, sizehint=None):
"""
Read all remaining lines using `readline` and return them as a list.
If the optional ``sizehint`` argument is present, instead of reading up
to EOF, whole lines totalling approximately sizehint bytes (possibly
after rounding up to an internal buffer size) are read.
:param int sizehint: desired maximum number of bytes to read.
:returns: list of lines read from the file.
"""
lines = []
byte_count = 0
while True:
line = self.readline()
if len(line) == 0:
break
lines.append(line)
byte_count += len(line)
if (sizehint is not None) and (byte_count >= sizehint):
break
return lines
def seek(self, offset, whence=0):
"""
Set the file's current position, like stdio's ``fseek``. Not all file
objects support seeking.
.. note::
If a file is opened in append mode (``'a'`` or ``'a+'``), any seek
operations will be undone at the next write (as the file position
will move back to the end of the file).
:param int offset:
position to move to within the file, relative to ``whence``.
:param int whence:
type of movement: 0 = absolute; 1 = relative to the current
position; 2 = relative to the end of the file.
:raises: ``IOError`` -- if the file doesn't support random access.
"""
raise IOError("File does not support seeking.")
def tell(self):
"""
Return the file's current position. This may not be accurate or
useful if the underlying file doesn't support random access, or was
opened in append mode.
:returns: file position (`number <int>` of bytes).
"""
return self._pos
def write(self, data):
"""
Write data to the file. If write buffering is on (``bufsize`` was
specified and non-zero), some or all of the data may not actually be
written yet. (Use `flush` or `close` to force buffered data to be
written out.)
:param data: ``str``/``bytes`` data to write
"""
if isinstance(data, str):
# Accept text and encode as utf-8 for compatibility only.
data = data.encode("utf-8")
if self._closed:
raise IOError("File is closed")
if not (self._flags & self.FLAG_WRITE):
raise IOError("File not open for writing")
if not (self._flags & self.FLAG_BUFFERED):
self._write_all(data)
return
self._wbuffer.write(data)
if self._flags & self.FLAG_LINE_BUFFERED:
# only scan the new data for linefeed, to avoid wasting time.
last_newline_pos = data.rfind(linefeed_byte)
if last_newline_pos >= 0:
wbuf = self._wbuffer.getvalue()
last_newline_pos += len(wbuf) - len(data)
self._write_all(wbuf[: last_newline_pos + 1])
self._wbuffer = BytesIO()
self._wbuffer.write(wbuf[last_newline_pos + 1 :])
return
# even if we're line buffering, if the buffer has grown past the
# buffer size, force a flush.
if self._wbuffer.tell() >= self._bufsize:
self.flush()
return
def writelines(self, sequence):
"""
Write a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings. (The
name is intended to match `readlines`; `writelines` does not add line
separators.)
:param sequence: an iterable sequence of strings.
"""
for line in sequence:
self.write(line)
return
def xreadlines(self):
"""
Identical to ``iter(f)``. This is a deprecated file interface that
predates Python iterator support.
"""
return self
@property
def closed(self):
return self._closed
# ...overrides...
def _read(self, size):
"""
(subclass override)
Read data from the stream. Return ``None`` or raise ``EOFError`` to
indicate EOF.
"""
raise EOFError()
def _write(self, data):
"""
(subclass override)
Write data into the stream.
"""
raise IOError("write not implemented")
def _get_size(self):
"""
(subclass override)
Return the size of the file. This is called from within `_set_mode`
if the file is opened in append mode, so the file position can be
tracked and `seek` and `tell` will work correctly. If the file is
a stream that can't be randomly accessed, you don't need to override
this method,
"""
return 0
# ...internals...
def _set_mode(self, mode="r", bufsize=-1):
"""
Subclasses call this method to initialize the BufferedFile.
"""
# set bufsize in any event, because it's used for readline().
self._bufsize = self._DEFAULT_BUFSIZE
if bufsize < 0:
# do no buffering by default, because otherwise writes will get
# buffered in a way that will probably confuse people.
bufsize = 0
if bufsize == 1:
# apparently, line buffering only affects writes. reads are only
# buffered if you call readline (directly or indirectly: iterating
# over a file will indirectly call readline).
self._flags |= self.FLAG_BUFFERED | self.FLAG_LINE_BUFFERED
elif bufsize > 1:
self._bufsize = bufsize
self._flags |= self.FLAG_BUFFERED
self._flags &= ~self.FLAG_LINE_BUFFERED
elif bufsize == 0:
# unbuffered
self._flags &= ~(self.FLAG_BUFFERED | self.FLAG_LINE_BUFFERED)
if ("r" in mode) or ("+" in mode):
self._flags |= self.FLAG_READ
if ("w" in mode) or ("+" in mode):
self._flags |= self.FLAG_WRITE
if "a" in mode:
self._flags |= self.FLAG_WRITE | self.FLAG_APPEND
self._size = self._get_size()
self._pos = self._realpos = self._size
if "b" in mode:
self._flags |= self.FLAG_BINARY
if "U" in mode:
self._flags |= self.FLAG_UNIVERSAL_NEWLINE
# built-in file objects have this attribute to store which kinds of
# line terminations they've seen:
# <http://www.python.org/doc/current/lib/built-in-funcs.html>
self.newlines = None
def _write_all(self, raw_data):
# the underlying stream may be something that does partial writes (like
# a socket).
data = memoryview(raw_data)
while len(data) > 0:
count = self._write(data)
data = data[count:]
if self._flags & self.FLAG_APPEND:
self._size += count
self._pos = self._realpos = self._size
else:
self._pos += count
self._realpos += count
return None
def _record_newline(self, newline):
# silliness about tracking what kinds of newlines we've seen.
# i don't understand why it can be None, a string, or a tuple, instead
# of just always being a tuple, but we'll emulate that behavior anyway.
if not (self._flags & self.FLAG_UNIVERSAL_NEWLINE):
return
if self.newlines is None:
self.newlines = newline
elif self.newlines != newline and isinstance(self.newlines, bytes):
self.newlines = (self.newlines, newline)
elif newline not in self.newlines:
self.newlines += (newline,)
| BufferedFile |
python | kamyu104__LeetCode-Solutions | Python/escape-the-spreading-fire.py | {
"start": 2136,
"end": 3857
} | class ____(object):
def maximumMinutes(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]
FIRE, WALL, PERSON = range(1, 4)
INF = 10**9
def bfs(grid):
time = {FIRE:[[INF]*len(grid[0]) for _ in xrange(len(grid))],
PERSON:[[INF]*len(grid[0]) for _ in xrange(len(grid))]}
d = 0
q = [(r, c, FIRE) for r in xrange(len(grid)) for c in xrange(len(grid[0])) if grid[r][c] == FIRE]
q.append((0, 0, PERSON))
for r, c, t in q:
time[t][r][c] = d
while q:
new_q = []
for r, c, t in q:
for dr, dc in DIRECTIONS:
nr, nc = r+dr, c+dc
if not (0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and
grid[nr][nc] != WALL and time[t][nr][nc] == INF and
(t == FIRE or
d+1 < time[FIRE][nr][nc] or (d+1 == time[FIRE][nr][nc] and (nr, nc) == (len(grid)-1, len(grid[0])-1)))):
continue
time[t][nr][nc] = d+1
new_q.append((nr, nc, t))
q = new_q
d += 1
return time
time = bfs(grid)
if time[PERSON][-1][-1] == INF:
return -1
if time[FIRE][-1][-1] == INF:
return INF
diff = time[FIRE][-1][-1]-time[PERSON][-1][-1]
return diff if diff+2 in (time[FIRE][-1][-2]-time[PERSON][-1][-2], time[FIRE][-2][-1]-time[PERSON][-2][-1]) else diff-1
| Solution2 |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax_error.py | {
"start": 3594,
"end": 3651
} | class ____(type):
__or__ = lambda x: x
| HorribleMetaclass |
python | ansible__ansible | lib/ansible/plugins/become/su.py | {
"start": 3254,
"end": 5303
} | class ____(BecomeBase):
name = 'su'
pipelining = False
# messages for detecting prompted password issues
fail = ('Authentication failure',)
SU_PROMPT_LOCALIZATIONS = [
'Password',
'암호',
'パスワード',
'Adgangskode',
'Contraseña',
'Contrasenya',
'Hasło',
'Heslo',
'Jelszó',
'Lösenord',
'Mật khẩu',
'Mot de passe',
'Parola',
'Parool',
'Pasahitza',
'Passord',
'Passwort',
'Salasana',
'Sandi',
'Senha',
'Wachtwoord',
'ססמה',
'Лозинка',
'Парола',
'Пароль',
'गुप्तशब्द',
'शब्दकूट',
'సంకేతపదము',
'හස්පදය',
'密码',
'密碼',
'口令',
]
def check_password_prompt(self, b_output: bytes) -> bool:
""" checks if the expected password prompt exists in b_output """
prompts = self.get_option('prompt_l10n') or self.SU_PROMPT_LOCALIZATIONS
password_prompt_strings = "|".join(re.escape(p) for p in prompts)
# Colon or unicode fullwidth colon
prompt_pattern = rf"(?:{password_prompt_strings})\s*[::]"
match = re.search(prompt_pattern, to_text(b_output), flags=re.IGNORECASE)
if match:
self.prompt = match.group(0) # preserve the actual matched string so we can scrub the output
return bool(match)
def build_become_command(self, cmd, shell):
super(BecomeModule, self).build_become_command(cmd, shell)
# Prompt handling for ``su`` is more complicated, this
# is used to satisfy the connection plugin
self.prompt = True
if not cmd:
return cmd
exe = self.get_option('become_exe') or self.name
flags = self.get_option('become_flags') or ''
user = self.get_option('become_user') or ''
success_cmd = self._build_success_command(cmd, shell)
return "%s %s %s -c %s" % (exe, flags, user, shlex.quote(success_cmd))
| BecomeModule |
python | django__django | tests/defer/tests.py | {
"start": 340,
"end": 719
} | class ____:
def assert_delayed(self, obj, num):
"""
Instances with deferred fields look the same as normal instances when
we examine attribute values. Therefore, this method returns the number
of deferred fields on returned instances.
"""
count = len(obj.get_deferred_fields())
self.assertEqual(count, num)
| AssertionMixin |
python | dagster-io__dagster | python_modules/dagster/dagster/components/scaffold/scaffold.py | {
"start": 3317,
"end": 4339
} | class ____(Generic[TModel]):
"""Handles scaffolding its associated scaffold target based on user-supplied parameters.
Invoked by a user using the `dg scaffold` CLI command.
To associate a scaffolder with its target class, use the :py:func:`scaffold_with` decorator.
"""
@classmethod
def get_scaffold_params(cls) -> type[TModel]:
"""Returns the model class that contains the parameters for scaffolding. By default,
this is :py:class:`NoParams`, indicating that no additional parameters can be supplied
to the scaffolder.
"""
return NoParams # type: ignore
@abstractmethod
def scaffold(self, request: ScaffoldRequest[TModel]) -> None:
"""Scaffold the target with the given request.
Args:
request: The scaffold request containing type name, target path, format, project root and params.
The params are validated against the model returned by :py:meth:`get_scaffold_params`.
"""
...
| Scaffolder |
python | django__django | tests/admin_changelist/tests.py | {
"start": 79306,
"end": 81565
} | class ____(TestCase):
def test_custom_user_pk_not_named_id(self):
"""
{% get_admin_log %} works if the user model's primary key isn't named
'id'.
"""
context = Context(
{
"user": CustomIdUser(),
"log_entries": LogEntry.objects.all(),
}
)
template = Template(
"{% load log %}{% get_admin_log 10 as admin_log for_user user %}"
)
# This template tag just logs.
self.assertEqual(template.render(context), "")
def test_no_user(self):
"""{% get_admin_log %} works without specifying a user."""
user = User(username="jondoe", password="secret", email="super@example.com")
user.save()
LogEntry.objects.log_actions(user.pk, [user], 1)
context = Context({"log_entries": LogEntry.objects.all()})
t = Template(
"{% load log %}"
"{% get_admin_log 100 as admin_log %}"
"{% for entry in admin_log %}"
"{{ entry|safe }}"
"{% endfor %}"
)
self.assertEqual(t.render(context), "Added “jondoe”.")
def test_missing_args(self):
msg = "'get_admin_log' statements require two arguments"
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template("{% load log %}{% get_admin_log 10 as %}")
def test_non_integer_limit(self):
msg = "First argument to 'get_admin_log' must be an integer"
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template(
'{% load log %}{% get_admin_log "10" as admin_log for_user user %}'
)
def test_without_as(self):
msg = "Second argument to 'get_admin_log' must be 'as'"
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template("{% load log %}{% get_admin_log 10 ad admin_log for_user user %}")
def test_without_for_user(self):
msg = "Fourth argument to 'get_admin_log' must be 'for_user'"
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template("{% load log %}{% get_admin_log 10 as admin_log foruser user %}")
@override_settings(ROOT_URLCONF="admin_changelist.urls")
| GetAdminLogTests |
python | huggingface__transformers | src/transformers/models/t5gemma/modeling_t5gemma.py | {
"start": 2372,
"end": 3050
} | class ____(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float())
# Llama does x.to(float16) * w whilst T5Gemma is (x * w).to(float16)
# See https://github.com/huggingface/transformers/pull/29402
output = output * (1.0 + self.weight.float())
return output.type_as(x)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.eps}"
| T5GemmaRMSNorm |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/assertsql.py | {
"start": 14614,
"end": 14793
} | class ____(
collections.namedtuple(
"SQLCursorExecuteObserved",
["statement", "parameters", "context", "executemany"],
)
):
pass
| SQLCursorExecuteObserved |
python | rq__rq | rq/registry.py | {
"start": 18510,
"end": 20289
} | class ____(BaseRegistry):
"""
Registry of deferred jobs (waiting for another job to finish).
"""
key_template = 'rq:deferred:{0}'
def cleanup(self, timestamp: Optional[float] = None, exception_handlers: Optional[list] = None):
"""Remove expired jobs from registry and add them to FailedJobRegistry.
Removes jobs with an expiry time earlier than timestamp, specified as
seconds since the Unix epoch. timestamp defaults to call time if
unspecified. Removed jobs are added to the failed job registry.
"""
score = timestamp if timestamp is not None else current_timestamp()
job_ids = self.get_expired_job_ids(score)
if job_ids:
with self.connection.pipeline() as pipeline:
for job_id in job_ids:
try:
job = self.job_class.fetch(job_id, connection=self.connection, serializer=self.serializer)
except NoSuchJobError:
continue
job.set_status(JobStatus.FAILED, pipeline=pipeline)
exc_info = f'Expired in DeferredJobRegistry, moved to FailedJobRegistry at {now}'
job._handle_failure(exc_string=exc_info, pipeline=pipeline, worker_name='')
pipeline.zremrangebyscore(self.key, 0, score)
pipeline.execute()
def add(self, job: Job, ttl: Optional[int] = None, pipeline: Optional['Pipeline'] = None, xx: bool = False) -> int:
"""
Adds a job to a registry with expiry time of now + ttl.
Defaults to -1 (never expire).
"""
if ttl is None:
ttl = -1
return super(DeferredJobRegistry, self).add(job, ttl, pipeline, xx)
| DeferredJobRegistry |
python | PrefectHQ__prefect | tests/server/utilities/test_schemas.py | {
"start": 2399,
"end": 3315
} | class ____:
@pytest.fixture()
def nested(self) -> pydantic.BaseModel:
class Child(pydantic.BaseModel):
z: int
class Parent(PrefectBaseModel):
x: int
y: Child
return Parent(x=1, y=Child(z=2))
def test_full_dict(self, nested: PrefectBaseModel):
assert nested.model_dump() == {"x": 1, "y": {"z": 2}}
assert isinstance(nested.model_dump()["y"], dict)
def test_simple_dict(self, nested: PrefectBaseModel):
assert dict(nested) == {"x": 1, "y": nested.y}
assert isinstance(dict(nested)["y"], pydantic.BaseModel)
def test_custom_dump_methods_respected(self, nested: PrefectBaseModel):
deep = nested.model_dump(include={"y"})
shallow = nested.model_dump_for_orm(include={"y"})
assert isinstance(deep["y"], dict)
assert isinstance(shallow["y"], pydantic.BaseModel)
| TestNestedDict |
python | plotly__plotly.py | plotly/graph_objs/_scatter.py | {
"start": 215,
"end": 104747
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "scatter"
_valid_props = {
"alignmentgroup",
"cliponaxis",
"connectgaps",
"customdata",
"customdatasrc",
"dx",
"dy",
"error_x",
"error_y",
"fill",
"fillcolor",
"fillgradient",
"fillpattern",
"groupnorm",
"hoverinfo",
"hoverinfosrc",
"hoverlabel",
"hoveron",
"hovertemplate",
"hovertemplatefallback",
"hovertemplatesrc",
"hovertext",
"hovertextsrc",
"ids",
"idssrc",
"legend",
"legendgroup",
"legendgrouptitle",
"legendrank",
"legendwidth",
"line",
"marker",
"meta",
"metasrc",
"mode",
"name",
"offsetgroup",
"opacity",
"orientation",
"selected",
"selectedpoints",
"showlegend",
"stackgaps",
"stackgroup",
"stream",
"text",
"textfont",
"textposition",
"textpositionsrc",
"textsrc",
"texttemplate",
"texttemplatefallback",
"texttemplatesrc",
"type",
"uid",
"uirevision",
"unselected",
"visible",
"x",
"x0",
"xaxis",
"xcalendar",
"xhoverformat",
"xperiod",
"xperiod0",
"xperiodalignment",
"xsrc",
"y",
"y0",
"yaxis",
"ycalendar",
"yhoverformat",
"yperiod",
"yperiod0",
"yperiodalignment",
"ysrc",
"zorder",
}
@property
def alignmentgroup(self):
"""
Set several traces linked to the same position axis or matching
axes to the same alignmentgroup. This controls whether bars
compute their positional range dependently or independently.
The 'alignmentgroup' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["alignmentgroup"]
@alignmentgroup.setter
def alignmentgroup(self, val):
self["alignmentgroup"] = val
@property
def cliponaxis(self):
"""
Determines whether or not markers and text nodes are clipped
about the subplot axes. To show markers and text nodes above
axis lines and tick labels, make sure to set `xaxis.layer` and
`yaxis.layer` to *below traces*.
The 'cliponaxis' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["cliponaxis"]
@cliponaxis.setter
def cliponaxis(self, val):
self["cliponaxis"] = val
@property
def connectgaps(self):
"""
Determines whether or not gaps (i.e. {nan} or missing values)
in the provided data arrays are connected.
The 'connectgaps' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["connectgaps"]
@connectgaps.setter
def connectgaps(self, val):
self["connectgaps"] = val
@property
def customdata(self):
"""
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note that,
"scatter" traces also appends customdata items in the markers
DOM elements
The 'customdata' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["customdata"]
@customdata.setter
def customdata(self, val):
self["customdata"] = val
@property
def customdatasrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`customdata`.
The 'customdatasrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["customdatasrc"]
@customdatasrc.setter
def customdatasrc(self, val):
self["customdatasrc"] = val
@property
def dx(self):
"""
Sets the x coordinate step. See `x0` for more info.
The 'dx' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["dx"]
@dx.setter
def dx(self, val):
self["dx"] = val
@property
def dy(self):
"""
Sets the y coordinate step. See `y0` for more info.
The 'dy' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["dy"]
@dy.setter
def dy(self, val):
self["dy"] = val
@property
def error_x(self):
"""
The 'error_x' property is an instance of ErrorX
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.ErrorX`
- A dict of string/value properties that will be passed
to the ErrorX constructor
Returns
-------
plotly.graph_objs.scatter.ErrorX
"""
return self["error_x"]
@error_x.setter
def error_x(self, val):
self["error_x"] = val
@property
def error_y(self):
"""
The 'error_y' property is an instance of ErrorY
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.ErrorY`
- A dict of string/value properties that will be passed
to the ErrorY constructor
Returns
-------
plotly.graph_objs.scatter.ErrorY
"""
return self["error_y"]
@error_y.setter
def error_y(self, val):
self["error_y"] = val
@property
def fill(self):
"""
Sets the area to fill with a solid color. Defaults to "none"
unless this trace is stacked, then it gets "tonexty"
("tonextx") if `orientation` is "v" ("h") Use with `fillcolor`
if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0
respectively. "tonextx" and "tonexty" fill between the
endpoints of this trace and the endpoints of the trace before
it, connecting those endpoints with straight lines (to make a
stacked area graph); if there is no trace before it, they
behave like "tozerox" and "tozeroy". "toself" connects the
endpoints of the trace (or each segment of the trace if it has
gaps) into a closed shape. "tonext" fills the space between two
traces if one completely encloses the other (eg consecutive
contour lines), and behaves like "toself" if there is no trace
before it. "tonext" should not be used if one trace does not
enclose the other. Traces in a `stackgroup` will only fill to
(or be filled to) other traces in the same group. With multiple
`stackgroup`s or some traces stacked and some not, if fill-
linked traces are not already consecutive, the later ones will
be pushed down in the drawing order.
The 'fill' property is an enumeration that may be specified as:
- One of the following enumeration values:
['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx',
'toself', 'tonext']
Returns
-------
Any
"""
return self["fill"]
@fill.setter
def fill(self, val):
self["fill"] = val
@property
def fillcolor(self):
"""
Sets the fill color. Defaults to a half-transparent variant of
the line color, marker color, or marker line color, whichever
is available. If fillgradient is specified, fillcolor is
ignored except for setting the background color of the hover
label, if any.
The 'fillcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["fillcolor"]
@fillcolor.setter
def fillcolor(self, val):
self["fillcolor"] = val
@property
def fillgradient(self):
"""
Sets a fill gradient. If not specified, the fillcolor is used
instead.
The 'fillgradient' property is an instance of Fillgradient
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Fillgradient`
- A dict of string/value properties that will be passed
to the Fillgradient constructor
Returns
-------
plotly.graph_objs.scatter.Fillgradient
"""
return self["fillgradient"]
@fillgradient.setter
def fillgradient(self, val):
self["fillgradient"] = val
@property
def fillpattern(self):
"""
Sets the pattern within the marker.
The 'fillpattern' property is an instance of Fillpattern
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Fillpattern`
- A dict of string/value properties that will be passed
to the Fillpattern constructor
Returns
-------
plotly.graph_objs.scatter.Fillpattern
"""
return self["fillpattern"]
@fillpattern.setter
def fillpattern(self, val):
self["fillpattern"] = val
@property
def groupnorm(self):
"""
Only relevant when `stackgroup` is used, and only the first
`groupnorm` found in the `stackgroup` will be used - including
if `visible` is "legendonly" but not if it is `false`. Sets the
normalization for the sum of this `stackgroup`. With
"fraction", the value of each trace at each location is divided
by the sum of all trace values at that location. "percent" is
the same but multiplied by 100 to show percentages. If there
are multiple subplots, or multiple `stackgroup`s on one
subplot, each will be normalized within its own set.
The 'groupnorm' property is an enumeration that may be specified as:
- One of the following enumeration values:
['', 'fraction', 'percent']
Returns
-------
Any
"""
return self["groupnorm"]
@groupnorm.setter
def groupnorm(self, val):
self["groupnorm"] = val
@property
def hoverinfo(self):
"""
Determines which trace information appear on hover. If `none`
or `skip` are set, no information is displayed upon hovering.
But, if `none` is set, click and hover events are still fired.
The 'hoverinfo' property is a flaglist and may be specified
as a string containing:
- Any combination of ['x', 'y', 'z', 'text', 'name'] joined with '+' characters
(e.g. 'x+y')
OR exactly one of ['all', 'none', 'skip'] (e.g. 'skip')
- A list or array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["hoverinfo"]
@hoverinfo.setter
def hoverinfo(self, val):
self["hoverinfo"] = val
@property
def hoverinfosrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
The 'hoverinfosrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["hoverinfosrc"]
@hoverinfosrc.setter
def hoverinfosrc(self, val):
self["hoverinfosrc"] = val
@property
def hoverlabel(self):
"""
The 'hoverlabel' property is an instance of Hoverlabel
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Hoverlabel`
- A dict of string/value properties that will be passed
to the Hoverlabel constructor
Returns
-------
plotly.graph_objs.scatter.Hoverlabel
"""
return self["hoverlabel"]
@hoverlabel.setter
def hoverlabel(self, val):
self["hoverlabel"] = val
@property
def hoveron(self):
"""
Do the hover effects highlight individual points (markers or
line points) or do they highlight filled regions? If the fill
is "toself" or "tonext" and there are no markers or text, then
the default is "fills", otherwise it is "points".
The 'hoveron' property is a flaglist and may be specified
as a string containing:
- Any combination of ['points', 'fills'] joined with '+' characters
(e.g. 'points+fills')
Returns
-------
Any
"""
return self["hoveron"]
@hoveron.setter
def hoveron(self, val):
self["hoveron"] = val
@property
def hovertemplate(self):
"""
Template string used for rendering the information that appear
on hover box. Note that this will override `hoverinfo`.
Variables are inserted using %{variable}, for example "y: %{y}"
as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When
showing info for several points, "xother" will be added to
those with different x positions from the first point. An
underscore before or after "(x|y)other" will add a space on
that side, only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format for
details on the formatting syntax. Dates are formatted using
d3-time-format's syntax %{variable|d3-time-format}, for example
"Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the date
formatting syntax. Variables that can't be found will be
replaced with the specifier. For example, a template of "data:
%{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1
and y is missing. Variables with an undefined value will be
replaced with the fallback value. The variables available in
`hovertemplate` are the ones emitted as event data described at
this link https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, all attributes that can be specified per-
point (the ones that are `arrayOk: true`) are available.
Anything contained in tag `<extra>` is displayed in the
secondary box, for example `<extra>%{fullData.name}</extra>`.
To hide the secondary box completely, use an empty tag
`<extra></extra>`.
The 'hovertemplate' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["hovertemplate"]
@hovertemplate.setter
def hovertemplate(self, val):
self["hovertemplate"] = val
@property
def hovertemplatefallback(self):
"""
Fallback string that's displayed when a variable referenced in
a template is missing. If the boolean value 'false' is passed
in, the specifier with the missing variable will be displayed.
The 'hovertemplatefallback' property accepts values of any type
Returns
-------
Any
"""
return self["hovertemplatefallback"]
@hovertemplatefallback.setter
def hovertemplatefallback(self, val):
self["hovertemplatefallback"] = val
@property
def hovertemplatesrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
The 'hovertemplatesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["hovertemplatesrc"]
@hovertemplatesrc.setter
def hovertemplatesrc(self, val):
self["hovertemplatesrc"] = val
@property
def hovertext(self):
"""
Sets hover text elements associated with each (x,y) pair. If a
single string, the same string appears over all the data
points. If an array of string, the items are mapped in order to
the this trace's (x,y) coordinates. To be seen, trace
`hoverinfo` must contain a "text" flag.
The 'hovertext' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["hovertext"]
@hovertext.setter
def hovertext(self, val):
self["hovertext"] = val
@property
def hovertextsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`hovertext`.
The 'hovertextsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["hovertextsrc"]
@hovertextsrc.setter
def hovertextsrc(self, val):
self["hovertextsrc"] = val
@property
def ids(self):
"""
Assigns id labels to each datum. These ids for object constancy
of data points during animation. Should be an array of strings,
not numbers or any other type.
The 'ids' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["ids"]
@ids.setter
def ids(self, val):
self["ids"] = val
@property
def idssrc(self):
"""
Sets the source reference on Chart Studio Cloud for `ids`.
The 'idssrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["idssrc"]
@idssrc.setter
def idssrc(self, val):
self["idssrc"] = val
@property
def legend(self):
"""
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2", "legend3",
etc. Settings for these legends are set in the layout, under
`layout.legend`, `layout.legend2`, etc.
The 'legend' property is an identifier of a particular
subplot, of type 'legend', that may be specified as the string 'legend'
optionally followed by an integer >= 1
(e.g. 'legend', 'legend1', 'legend2', 'legend3', etc.)
Returns
-------
str
"""
return self["legend"]
@legend.setter
def legend(self, val):
self["legend"] = val
@property
def legendgroup(self):
"""
Sets the legend group for this trace. Traces and shapes part of
the same legend group hide/show at the same time when toggling
legend items.
The 'legendgroup' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["legendgroup"]
@legendgroup.setter
def legendgroup(self, val):
self["legendgroup"] = val
@property
def legendgrouptitle(self):
"""
The 'legendgrouptitle' property is an instance of Legendgrouptitle
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Legendgrouptitle`
- A dict of string/value properties that will be passed
to the Legendgrouptitle constructor
Returns
-------
plotly.graph_objs.scatter.Legendgrouptitle
"""
return self["legendgrouptitle"]
@legendgrouptitle.setter
def legendgrouptitle(self, val):
self["legendgrouptitle"] = val
@property
def legendrank(self):
"""
Sets the legend rank for this trace. Items and groups with
smaller ranks are presented on top/left side while with
"reversed" `legend.traceorder` they are on bottom/right side.
The default legendrank is 1000, so that you can use ranks less
than 1000 to place certain items before all unranked items, and
ranks greater than 1000 to go after all unranked items. When
having unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and layout.
The 'legendrank' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["legendrank"]
@legendrank.setter
def legendrank(self, val):
self["legendrank"] = val
@property
def legendwidth(self):
"""
Sets the width (in px or fraction) of the legend for this
trace.
The 'legendwidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["legendwidth"]
@legendwidth.setter
def legendwidth(self, val):
self["legendwidth"] = val
@property
def line(self):
"""
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Line`
- A dict of string/value properties that will be passed
to the Line constructor
Returns
-------
plotly.graph_objs.scatter.Line
"""
return self["line"]
@line.setter
def line(self, val):
self["line"] = val
@property
def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Returns
-------
plotly.graph_objs.scatter.Marker
"""
return self["marker"]
@marker.setter
def marker(self, val):
self["marker"] = val
@property
def meta(self):
"""
Assigns extra meta information associated with this trace that
can be used in various text attributes. Attributes such as
trace `name`, graph, axis and colorbar `title.text`, annotation
`text` `rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta` values in
an attribute in the same trace, simply use `%{meta[i]}` where
`i` is the index or key of the `meta` item in question. To
access trace `meta` in layout attributes, use
`%{data[n[.meta[i]}` where `i` is the index or key of the
`meta` and `n` is the trace index.
The 'meta' property accepts values of any type
Returns
-------
Any|numpy.ndarray
"""
return self["meta"]
@meta.setter
def meta(self, val):
self["meta"] = val
@property
def metasrc(self):
"""
Sets the source reference on Chart Studio Cloud for `meta`.
The 'metasrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["metasrc"]
@metasrc.setter
def metasrc(self, val):
self["metasrc"] = val
@property
def mode(self):
"""
Determines the drawing mode for this scatter trace. If the
provided `mode` includes "text" then the `text` elements appear
at the coordinates. Otherwise, the `text` elements appear on
hover. If there are less than 20 points and the trace is not
stacked then the default is "lines+markers". Otherwise,
"lines".
The 'mode' property is a flaglist and may be specified
as a string containing:
- Any combination of ['lines', 'markers', 'text'] joined with '+' characters
(e.g. 'lines+markers')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["mode"]
@mode.setter
def mode(self, val):
self["mode"] = val
@property
def name(self):
"""
Sets the trace name. The trace name appears as the legend item
and on hover.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["name"]
@name.setter
def name(self, val):
self["name"] = val
@property
def offsetgroup(self):
"""
Set several traces linked to the same position axis or matching
axes to the same offsetgroup where bars of the same position
coordinate will line up.
The 'offsetgroup' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["offsetgroup"]
@offsetgroup.setter
def offsetgroup(self, val):
self["offsetgroup"] = val
@property
def opacity(self):
"""
Sets the opacity of the trace.
The 'opacity' property is a number and may be specified as:
- An int or float in the interval [0, 1]
Returns
-------
int|float
"""
return self["opacity"]
@opacity.setter
def opacity(self, val):
self["opacity"] = val
@property
def orientation(self):
"""
Only relevant in the following cases: 1. when `scattermode` is
set to "group". 2. when `stackgroup` is used, and only the
first `orientation` found in the `stackgroup` will be used -
including if `visible` is "legendonly" but not if it is
`false`. Sets the stacking direction. With "v" ("h"), the y (x)
values of subsequent traces are added. Also affects the default
value of `fill`.
The 'orientation' property is an enumeration that may be specified as:
- One of the following enumeration values:
['v', 'h']
Returns
-------
Any
"""
return self["orientation"]
@orientation.setter
def orientation(self, val):
self["orientation"] = val
@property
def selected(self):
"""
The 'selected' property is an instance of Selected
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Selected`
- A dict of string/value properties that will be passed
to the Selected constructor
Returns
-------
plotly.graph_objs.scatter.Selected
"""
return self["selected"]
@selected.setter
def selected(self, val):
self["selected"] = val
@property
def selectedpoints(self):
"""
Array containing integer indices of selected points. Has an
effect only for traces that support selections. Note that an
empty array means an empty selection where the `unselected` are
turned on for all points, whereas, any other non-array values
means no selection all where the `selected` and `unselected`
styles have no effect.
The 'selectedpoints' property accepts values of any type
Returns
-------
Any
"""
return self["selectedpoints"]
@selectedpoints.setter
def selectedpoints(self, val):
self["selectedpoints"] = val
@property
def showlegend(self):
"""
Determines whether or not an item corresponding to this trace
is shown in the legend.
The 'showlegend' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showlegend"]
@showlegend.setter
def showlegend(self, val):
self["showlegend"] = val
@property
def stackgaps(self):
"""
Only relevant when `stackgroup` is used, and only the first
`stackgaps` found in the `stackgroup` will be used - including
if `visible` is "legendonly" but not if it is `false`.
Determines how we handle locations at which other traces in
this group have data but this one does not. With *infer zero*
we insert a zero at these locations. With "interpolate" we
linearly interpolate between existing values, and extrapolate a
constant beyond the existing values.
The 'stackgaps' property is an enumeration that may be specified as:
- One of the following enumeration values:
['infer zero', 'interpolate']
Returns
-------
Any
"""
return self["stackgaps"]
@stackgaps.setter
def stackgaps(self, val):
self["stackgaps"] = val
@property
def stackgroup(self):
"""
Set several scatter traces (on the same subplot) to the same
stackgroup in order to add their y values (or their x values if
`orientation` is "h"). If blank or omitted this trace will not
be stacked. Stacking also turns `fill` on by default, using
"tonexty" ("tonextx") if `orientation` is "h" ("v") and sets
the default `mode` to "lines" irrespective of point count. You
can only stack on a numeric (linear or log) axis. Traces in a
`stackgroup` will only fill to (or be filled to) other traces
in the same group. With multiple `stackgroup`s or some traces
stacked and some not, if fill-linked traces are not already
consecutive, the later ones will be pushed down in the drawing
order.
The 'stackgroup' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["stackgroup"]
@stackgroup.setter
def stackgroup(self, val):
self["stackgroup"] = val
@property
def stream(self):
"""
The 'stream' property is an instance of Stream
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Stream`
- A dict of string/value properties that will be passed
to the Stream constructor
Returns
-------
plotly.graph_objs.scatter.Stream
"""
return self["stream"]
@stream.setter
def stream(self, val):
self["stream"] = val
@property
def text(self):
"""
Sets text elements associated with each (x,y) pair. If a single
string, the same string appears over all the data points. If an
array of string, the items are mapped in order to the this
trace's (x,y) coordinates. If trace `hoverinfo` contains a
"text" flag and "hovertext" is not set, these elements will be
seen in the hover labels.
The 'text' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["text"]
@text.setter
def text(self, val):
self["text"] = val
@property
def textfont(self):
"""
Sets the text font.
The 'textfont' property is an instance of Textfont
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Textfont`
- A dict of string/value properties that will be passed
to the Textfont constructor
Returns
-------
plotly.graph_objs.scatter.Textfont
"""
return self["textfont"]
@textfont.setter
def textfont(self, val):
self["textfont"] = val
@property
def textposition(self):
"""
Sets the positions of the `text` elements with respects to the
(x,y) coordinates.
The 'textposition' property is an enumeration that may be specified as:
- One of the following enumeration values:
['top left', 'top center', 'top right', 'middle left',
'middle center', 'middle right', 'bottom left', 'bottom
center', 'bottom right']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["textposition"]
@textposition.setter
def textposition(self, val):
self["textposition"] = val
@property
def textpositionsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`textposition`.
The 'textpositionsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["textpositionsrc"]
@textpositionsrc.setter
def textpositionsrc(self, val):
self["textpositionsrc"] = val
@property
def textsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `text`.
The 'textsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["textsrc"]
@textsrc.setter
def textsrc(self, val):
self["textsrc"] = val
@property
def texttemplate(self):
"""
Template string used for rendering the information text that
appears on points. Note that this will override `textinfo`.
Variables are inserted using %{variable}, for example "y:
%{y}". Numbers are formatted using d3-format's syntax
%{variable:d3-format}, for example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format for
details on the formatting syntax. Dates are formatted using
d3-time-format's syntax %{variable|d3-time-format}, for example
"Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the date
formatting syntax. Variables that can't be found will be
replaced with the specifier. For example, a template of "data:
%{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1
and y is missing. Variables with an undefined value will be
replaced with the fallback value. All attributes that can be
specified per-point (the ones that are `arrayOk: true`) are
available.
The 'texttemplate' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["texttemplate"]
@texttemplate.setter
def texttemplate(self, val):
self["texttemplate"] = val
@property
def texttemplatefallback(self):
"""
Fallback string that's displayed when a variable referenced in
a template is missing. If the boolean value 'false' is passed
in, the specifier with the missing variable will be displayed.
The 'texttemplatefallback' property accepts values of any type
Returns
-------
Any
"""
return self["texttemplatefallback"]
@texttemplatefallback.setter
def texttemplatefallback(self, val):
self["texttemplatefallback"] = val
@property
def texttemplatesrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
The 'texttemplatesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["texttemplatesrc"]
@texttemplatesrc.setter
def texttemplatesrc(self, val):
self["texttemplatesrc"] = val
@property
def uid(self):
"""
Assign an id to this trace, Use this to provide object
constancy between traces during animations and transitions.
The 'uid' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["uid"]
@uid.setter
def uid(self, val):
self["uid"] = val
@property
def uirevision(self):
"""
Controls persistence of some user-driven changes to the trace:
`constraintrange` in `parcoords` traces, as well as some
`editable: true` modifications such as `name` and
`colorbar.title`. Defaults to `layout.uirevision`. Note that
other user-driven trace attribute changes are controlled by
`layout` attributes: `trace.visible` is controlled by
`layout.legend.uirevision`, `selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)` (accessible
with `config: {editable: true}`) is controlled by
`layout.editrevision`. Trace changes are tracked by `uid`,
which only falls back on trace index if no `uid` is provided.
So if your app can add/remove traces before the end of the
`data` array, such that the same trace has a different index,
you can still preserve user-driven changes if you give each
trace a `uid` that stays with it as it moves.
The 'uirevision' property accepts values of any type
Returns
-------
Any
"""
return self["uirevision"]
@uirevision.setter
def uirevision(self, val):
self["uirevision"] = val
@property
def unselected(self):
"""
The 'unselected' property is an instance of Unselected
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Unselected`
- A dict of string/value properties that will be passed
to the Unselected constructor
Returns
-------
plotly.graph_objs.scatter.Unselected
"""
return self["unselected"]
@unselected.setter
def unselected(self, val):
self["unselected"] = val
@property
def visible(self):
"""
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as a
legend item (provided that the legend itself is visible).
The 'visible' property is an enumeration that may be specified as:
- One of the following enumeration values:
[True, False, 'legendonly']
Returns
-------
Any
"""
return self["visible"]
@visible.setter
def visible(self, val):
self["visible"] = val
@property
def x(self):
"""
Sets the x coordinates.
The 'x' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["x"]
@x.setter
def x(self, val):
self["x"] = val
@property
def x0(self):
"""
Alternate to `x`. Builds a linear space of x coordinates. Use
with `dx` where `x0` is the starting coordinate and `dx` the
step.
The 'x0' property accepts values of any type
Returns
-------
Any
"""
return self["x0"]
@x0.setter
def x0(self, val):
self["x0"] = val
@property
def xaxis(self):
"""
Sets a reference between this trace's x coordinates and a 2D
cartesian x axis. If "x" (the default value), the x coordinates
refer to `layout.xaxis`. If "x2", the x coordinates refer to
`layout.xaxis2`, and so on.
The 'xaxis' property is an identifier of a particular
subplot, of type 'x', that may be specified as the string 'x'
optionally followed by an integer >= 1
(e.g. 'x', 'x1', 'x2', 'x3', etc.)
Returns
-------
str
"""
return self["xaxis"]
@xaxis.setter
def xaxis(self, val):
self["xaxis"] = val
@property
def xcalendar(self):
"""
Sets the calendar system to use with `x` date data.
The 'xcalendar' property is an enumeration that may be specified as:
- One of the following enumeration values:
['chinese', 'coptic', 'discworld', 'ethiopian',
'gregorian', 'hebrew', 'islamic', 'jalali', 'julian',
'mayan', 'nanakshahi', 'nepali', 'persian', 'taiwan',
'thai', 'ummalqura']
Returns
-------
Any
"""
return self["xcalendar"]
@xcalendar.setter
def xcalendar(self, val):
self["xcalendar"] = val
@property
def xhoverformat(self):
"""
Sets the hover text formatting rulefor `x` using d3 formatting
mini-languages which are very similar to those in Python. For
numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for
dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to d3's date
formatter: "%h" for half of the year as a decimal number as
well as "%{n}f" for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with tickformat
"%H~%M~%S.%2f" would display *09~15~23.46*By default the values
are formatted using `xaxis.hoverformat`.
The 'xhoverformat' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["xhoverformat"]
@xhoverformat.setter
def xhoverformat(self, val):
self["xhoverformat"] = val
@property
def xperiod(self):
"""
Only relevant when the axis `type` is "date". Sets the period
positioning in milliseconds or "M<n>" on the x axis. Special
values in the form of "M<n>" could be used to declare the
number of months. In this case `n` must be a positive integer.
The 'xperiod' property accepts values of any type
Returns
-------
Any
"""
return self["xperiod"]
@xperiod.setter
def xperiod(self, val):
self["xperiod"] = val
@property
def xperiod0(self):
"""
Only relevant when the axis `type` is "date". Sets the base for
period positioning in milliseconds or date string on the x0
axis. When `x0period` is round number of weeks, the `x0period0`
by default would be on a Sunday i.e. 2000-01-02, otherwise it
would be at 2000-01-01.
The 'xperiod0' property accepts values of any type
Returns
-------
Any
"""
return self["xperiod0"]
@xperiod0.setter
def xperiod0(self, val):
self["xperiod0"] = val
@property
def xperiodalignment(self):
"""
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the x axis.
The 'xperiodalignment' property is an enumeration that may be specified as:
- One of the following enumeration values:
['start', 'middle', 'end']
Returns
-------
Any
"""
return self["xperiodalignment"]
@xperiodalignment.setter
def xperiodalignment(self, val):
self["xperiodalignment"] = val
@property
def xsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `x`.
The 'xsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["xsrc"]
@xsrc.setter
def xsrc(self, val):
self["xsrc"] = val
@property
def y(self):
"""
Sets the y coordinates.
The 'y' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["y"]
@y.setter
def y(self, val):
self["y"] = val
@property
def y0(self):
"""
Alternate to `y`. Builds a linear space of y coordinates. Use
with `dy` where `y0` is the starting coordinate and `dy` the
step.
The 'y0' property accepts values of any type
Returns
-------
Any
"""
return self["y0"]
@y0.setter
def y0(self, val):
self["y0"] = val
@property
def yaxis(self):
"""
Sets a reference between this trace's y coordinates and a 2D
cartesian y axis. If "y" (the default value), the y coordinates
refer to `layout.yaxis`. If "y2", the y coordinates refer to
`layout.yaxis2`, and so on.
The 'yaxis' property is an identifier of a particular
subplot, of type 'y', that may be specified as the string 'y'
optionally followed by an integer >= 1
(e.g. 'y', 'y1', 'y2', 'y3', etc.)
Returns
-------
str
"""
return self["yaxis"]
@yaxis.setter
def yaxis(self, val):
self["yaxis"] = val
@property
def ycalendar(self):
"""
Sets the calendar system to use with `y` date data.
The 'ycalendar' property is an enumeration that may be specified as:
- One of the following enumeration values:
['chinese', 'coptic', 'discworld', 'ethiopian',
'gregorian', 'hebrew', 'islamic', 'jalali', 'julian',
'mayan', 'nanakshahi', 'nepali', 'persian', 'taiwan',
'thai', 'ummalqura']
Returns
-------
Any
"""
return self["ycalendar"]
@ycalendar.setter
def ycalendar(self, val):
self["ycalendar"] = val
@property
def yhoverformat(self):
"""
Sets the hover text formatting rulefor `y` using d3 formatting
mini-languages which are very similar to those in Python. For
numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for
dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to d3's date
formatter: "%h" for half of the year as a decimal number as
well as "%{n}f" for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with tickformat
"%H~%M~%S.%2f" would display *09~15~23.46*By default the values
are formatted using `yaxis.hoverformat`.
The 'yhoverformat' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["yhoverformat"]
@yhoverformat.setter
def yhoverformat(self, val):
self["yhoverformat"] = val
@property
def yperiod(self):
"""
Only relevant when the axis `type` is "date". Sets the period
positioning in milliseconds or "M<n>" on the y axis. Special
values in the form of "M<n>" could be used to declare the
number of months. In this case `n` must be a positive integer.
The 'yperiod' property accepts values of any type
Returns
-------
Any
"""
return self["yperiod"]
@yperiod.setter
def yperiod(self, val):
self["yperiod"] = val
@property
def yperiod0(self):
"""
Only relevant when the axis `type` is "date". Sets the base for
period positioning in milliseconds or date string on the y0
axis. When `y0period` is round number of weeks, the `y0period0`
by default would be on a Sunday i.e. 2000-01-02, otherwise it
would be at 2000-01-01.
The 'yperiod0' property accepts values of any type
Returns
-------
Any
"""
return self["yperiod0"]
@yperiod0.setter
def yperiod0(self, val):
self["yperiod0"] = val
@property
def yperiodalignment(self):
"""
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the y axis.
The 'yperiodalignment' property is an enumeration that may be specified as:
- One of the following enumeration values:
['start', 'middle', 'end']
Returns
-------
Any
"""
return self["yperiodalignment"]
@yperiodalignment.setter
def yperiodalignment(self, val):
self["yperiodalignment"] = val
@property
def ysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `y`.
The 'ysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["ysrc"]
@ysrc.setter
def ysrc(self, val):
self["ysrc"] = val
@property
def zorder(self):
"""
Sets the layer on which this trace is displayed, relative to
other SVG traces on the same subplot. SVG traces with higher
`zorder` appear in front of those with lower `zorder`.
The 'zorder' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
Returns
-------
int
"""
return self["zorder"]
@zorder.setter
def zorder(self, val):
self["zorder"] = val
@property
def type(self):
return self._props["type"]
@property
def _prop_descriptions(self):
return """\
alignmentgroup
Set several traces linked to the same position axis or
matching axes to the same alignmentgroup. This controls
whether bars compute their positional range dependently
or independently.
cliponaxis
Determines whether or not markers and text nodes are
clipped about the subplot axes. To show markers and
text nodes above axis lines and tick labels, make sure
to set `xaxis.layer` and `yaxis.layer` to *below
traces*.
connectgaps
Determines whether or not gaps (i.e. {nan} or missing
values) in the provided data arrays are connected.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
dx
Sets the x coordinate step. See `x0` for more info.
dy
Sets the y coordinate step. See `y0` for more info.
error_x
:class:`plotly.graph_objects.scatter.ErrorX` instance
or dict with compatible properties
error_y
:class:`plotly.graph_objects.scatter.ErrorY` instance
or dict with compatible properties
fill
Sets the area to fill with a solid color. Defaults to
"none" unless this trace is stacked, then it gets
"tonexty" ("tonextx") if `orientation` is "v" ("h") Use
with `fillcolor` if not "none". "tozerox" and "tozeroy"
fill to x=0 and y=0 respectively. "tonextx" and
"tonexty" fill between the endpoints of this trace and
the endpoints of the trace before it, connecting those
endpoints with straight lines (to make a stacked area
graph); if there is no trace before it, they behave
like "tozerox" and "tozeroy". "toself" connects the
endpoints of the trace (or each segment of the trace if
it has gaps) into a closed shape. "tonext" fills the
space between two traces if one completely encloses the
other (eg consecutive contour lines), and behaves like
"toself" if there is no trace before it. "tonext"
should not be used if one trace does not enclose the
other. Traces in a `stackgroup` will only fill to (or
be filled to) other traces in the same group. With
multiple `stackgroup`s or some traces stacked and some
not, if fill-linked traces are not already consecutive,
the later ones will be pushed down in the drawing
order.
fillcolor
Sets the fill color. Defaults to a half-transparent
variant of the line color, marker color, or marker line
color, whichever is available. If fillgradient is
specified, fillcolor is ignored except for setting the
background color of the hover label, if any.
fillgradient
Sets a fill gradient. If not specified, the fillcolor
is used instead.
fillpattern
Sets the pattern within the marker.
groupnorm
Only relevant when `stackgroup` is used, and only the
first `groupnorm` found in the `stackgroup` will be
used - including if `visible` is "legendonly" but not
if it is `false`. Sets the normalization for the sum of
this `stackgroup`. With "fraction", the value of each
trace at each location is divided by the sum of all
trace values at that location. "percent" is the same
but multiplied by 100 to show percentages. If there are
multiple subplots, or multiple `stackgroup`s on one
subplot, each will be normalized within its own set.
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.scatter.Hoverlabel`
instance or dict with compatible properties
hoveron
Do the hover effects highlight individual points
(markers or line points) or do they highlight filled
regions? If the fill is "toself" or "tonext" and there
are no markers or text, then the default is "fills",
otherwise it is "points".
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Variables that can't be found
will be replaced with the specifier. For example, a
template of "data: %{x}, %{y}" will result in a value
of "data: 1, %{y}" if x is 1 and y is missing.
Variables with an undefined value will be replaced with
the fallback value. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, all attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
`<extra>%{fullData.name}</extra>`. To hide the
secondary box completely, use an empty tag
`<extra></extra>`.
hovertemplatefallback
Fallback string that's displayed when a variable
referenced in a template is missing. If the boolean
value 'false' is passed in, the specifier with the
missing variable will be displayed.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each (x,y)
pair. If a single string, the same string appears over
all the data points. If an array of string, the items
are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace `hoverinfo` must contain
a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.scatter.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
line
:class:`plotly.graph_objects.scatter.Line` instance or
dict with compatible properties
marker
:class:`plotly.graph_objects.scatter.Marker` instance
or dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
mode
Determines the drawing mode for this scatter trace. If
the provided `mode` includes "text" then the `text`
elements appear at the coordinates. Otherwise, the
`text` elements appear on hover. If there are less than
20 points and the trace is not stacked then the default
is "lines+markers". Otherwise, "lines".
name
Sets the trace name. The trace name appears as the
legend item and on hover.
offsetgroup
Set several traces linked to the same position axis or
matching axes to the same offsetgroup where bars of the
same position coordinate will line up.
opacity
Sets the opacity of the trace.
orientation
Only relevant in the following cases: 1. when
`scattermode` is set to "group". 2. when `stackgroup`
is used, and only the first `orientation` found in the
`stackgroup` will be used - including if `visible` is
"legendonly" but not if it is `false`. Sets the
stacking direction. With "v" ("h"), the y (x) values of
subsequent traces are added. Also affects the default
value of `fill`.
selected
:class:`plotly.graph_objects.scatter.Selected` instance
or dict with compatible properties
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
stackgaps
Only relevant when `stackgroup` is used, and only the
first `stackgaps` found in the `stackgroup` will be
used - including if `visible` is "legendonly" but not
if it is `false`. Determines how we handle locations at
which other traces in this group have data but this one
does not. With *infer zero* we insert a zero at these
locations. With "interpolate" we linearly interpolate
between existing values, and extrapolate a constant
beyond the existing values.
stackgroup
Set several scatter traces (on the same subplot) to the
same stackgroup in order to add their y values (or
their x values if `orientation` is "h"). If blank or
omitted this trace will not be stacked. Stacking also
turns `fill` on by default, using "tonexty" ("tonextx")
if `orientation` is "h" ("v") and sets the default
`mode` to "lines" irrespective of point count. You can
only stack on a numeric (linear or log) axis. Traces in
a `stackgroup` will only fill to (or be filled to)
other traces in the same group. With multiple
`stackgroup`s or some traces stacked and some not, if
fill-linked traces are not already consecutive, the
later ones will be pushed down in the drawing order.
stream
:class:`plotly.graph_objects.scatter.Stream` instance
or dict with compatible properties
text
Sets text elements associated with each (x,y) pair. If
a single string, the same string appears over all the
data points. If an array of string, the items are
mapped in order to the this trace's (x,y) coordinates.
If trace `hoverinfo` contains a "text" flag and
"hovertext" is not set, these elements will be seen in
the hover labels.
textfont
Sets the text font.
textposition
Sets the positions of the `text` elements with respects
to the (x,y) coordinates.
textpositionsrc
Sets the source reference on Chart Studio Cloud for
`textposition`.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appears on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Variables that can't be found
will be replaced with the specifier. For example, a
template of "data: %{x}, %{y}" will result in a value
of "data: 1, %{y}" if x is 1 and y is missing.
Variables with an undefined value will be replaced with
the fallback value. All attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available.
texttemplatefallback
Fallback string that's displayed when a variable
referenced in a template is missing. If the boolean
value 'false' is passed in, the specifier with the
missing variable will be displayed.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
unselected
:class:`plotly.graph_objects.scatter.Unselected`
instance or dict with compatible properties
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
x
Sets the x coordinates.
x0
Alternate to `x`. Builds a linear space of x
coordinates. Use with `dx` where `x0` is the starting
coordinate and `dx` the step.
xaxis
Sets a reference between this trace's x coordinates and
a 2D cartesian x axis. If "x" (the default value), the
x coordinates refer to `layout.xaxis`. If "x2", the x
coordinates refer to `layout.xaxis2`, and so on.
xcalendar
Sets the calendar system to use with `x` date data.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
xperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the x
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
xperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the x0 axis. When `x0period` is round number
of weeks, the `x0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
xperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the x axis.
xsrc
Sets the source reference on Chart Studio Cloud for
`x`.
y
Sets the y coordinates.
y0
Alternate to `y`. Builds a linear space of y
coordinates. Use with `dy` where `y0` is the starting
coordinate and `dy` the step.
yaxis
Sets a reference between this trace's y coordinates and
a 2D cartesian y axis. If "y" (the default value), the
y coordinates refer to `layout.yaxis`. If "y2", the y
coordinates refer to `layout.yaxis2`, and so on.
ycalendar
Sets the calendar system to use with `y` date data.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
yperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the y
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
yperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the y0 axis. When `y0period` is round number
of weeks, the `y0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
yperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the y axis.
ysrc
Sets the source reference on Chart Studio Cloud for
`y`.
zorder
Sets the layer on which this trace is displayed,
relative to other SVG traces on the same subplot. SVG
traces with higher `zorder` appear in front of those
with lower `zorder`.
"""
def __init__(
self,
arg=None,
alignmentgroup=None,
cliponaxis=None,
connectgaps=None,
customdata=None,
customdatasrc=None,
dx=None,
dy=None,
error_x=None,
error_y=None,
fill=None,
fillcolor=None,
fillgradient=None,
fillpattern=None,
groupnorm=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hoveron=None,
hovertemplate=None,
hovertemplatefallback=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
line=None,
marker=None,
meta=None,
metasrc=None,
mode=None,
name=None,
offsetgroup=None,
opacity=None,
orientation=None,
selected=None,
selectedpoints=None,
showlegend=None,
stackgaps=None,
stackgroup=None,
stream=None,
text=None,
textfont=None,
textposition=None,
textpositionsrc=None,
textsrc=None,
texttemplate=None,
texttemplatefallback=None,
texttemplatesrc=None,
uid=None,
uirevision=None,
unselected=None,
visible=None,
x=None,
x0=None,
xaxis=None,
xcalendar=None,
xhoverformat=None,
xperiod=None,
xperiod0=None,
xperiodalignment=None,
xsrc=None,
y=None,
y0=None,
yaxis=None,
ycalendar=None,
yhoverformat=None,
yperiod=None,
yperiod0=None,
yperiodalignment=None,
ysrc=None,
zorder=None,
**kwargs,
):
"""
Construct a new Scatter object
The scatter trace type encompasses line charts, scatter charts,
text charts, and bubble charts. The data visualized as scatter
point or lines is set in `x` and `y`. Text (appearing either on
the chart or on hover only) is via `text`. Bubble charts are
achieved by setting `marker.size` and/or `marker.color` to
numerical arrays.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Scatter`
alignmentgroup
Set several traces linked to the same position axis or
matching axes to the same alignmentgroup. This controls
whether bars compute their positional range dependently
or independently.
cliponaxis
Determines whether or not markers and text nodes are
clipped about the subplot axes. To show markers and
text nodes above axis lines and tick labels, make sure
to set `xaxis.layer` and `yaxis.layer` to *below
traces*.
connectgaps
Determines whether or not gaps (i.e. {nan} or missing
values) in the provided data arrays are connected.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
dx
Sets the x coordinate step. See `x0` for more info.
dy
Sets the y coordinate step. See `y0` for more info.
error_x
:class:`plotly.graph_objects.scatter.ErrorX` instance
or dict with compatible properties
error_y
:class:`plotly.graph_objects.scatter.ErrorY` instance
or dict with compatible properties
fill
Sets the area to fill with a solid color. Defaults to
"none" unless this trace is stacked, then it gets
"tonexty" ("tonextx") if `orientation` is "v" ("h") Use
with `fillcolor` if not "none". "tozerox" and "tozeroy"
fill to x=0 and y=0 respectively. "tonextx" and
"tonexty" fill between the endpoints of this trace and
the endpoints of the trace before it, connecting those
endpoints with straight lines (to make a stacked area
graph); if there is no trace before it, they behave
like "tozerox" and "tozeroy". "toself" connects the
endpoints of the trace (or each segment of the trace if
it has gaps) into a closed shape. "tonext" fills the
space between two traces if one completely encloses the
other (eg consecutive contour lines), and behaves like
"toself" if there is no trace before it. "tonext"
should not be used if one trace does not enclose the
other. Traces in a `stackgroup` will only fill to (or
be filled to) other traces in the same group. With
multiple `stackgroup`s or some traces stacked and some
not, if fill-linked traces are not already consecutive,
the later ones will be pushed down in the drawing
order.
fillcolor
Sets the fill color. Defaults to a half-transparent
variant of the line color, marker color, or marker line
color, whichever is available. If fillgradient is
specified, fillcolor is ignored except for setting the
background color of the hover label, if any.
fillgradient
Sets a fill gradient. If not specified, the fillcolor
is used instead.
fillpattern
Sets the pattern within the marker.
groupnorm
Only relevant when `stackgroup` is used, and only the
first `groupnorm` found in the `stackgroup` will be
used - including if `visible` is "legendonly" but not
if it is `false`. Sets the normalization for the sum of
this `stackgroup`. With "fraction", the value of each
trace at each location is divided by the sum of all
trace values at that location. "percent" is the same
but multiplied by 100 to show percentages. If there are
multiple subplots, or multiple `stackgroup`s on one
subplot, each will be normalized within its own set.
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.scatter.Hoverlabel`
instance or dict with compatible properties
hoveron
Do the hover effects highlight individual points
(markers or line points) or do they highlight filled
regions? If the fill is "toself" or "tonext" and there
are no markers or text, then the default is "fills",
otherwise it is "points".
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Variables that can't be found
will be replaced with the specifier. For example, a
template of "data: %{x}, %{y}" will result in a value
of "data: 1, %{y}" if x is 1 and y is missing.
Variables with an undefined value will be replaced with
the fallback value. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, all attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
`<extra>%{fullData.name}</extra>`. To hide the
secondary box completely, use an empty tag
`<extra></extra>`.
hovertemplatefallback
Fallback string that's displayed when a variable
referenced in a template is missing. If the boolean
value 'false' is passed in, the specifier with the
missing variable will be displayed.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each (x,y)
pair. If a single string, the same string appears over
all the data points. If an array of string, the items
are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace `hoverinfo` must contain
a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.scatter.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
line
:class:`plotly.graph_objects.scatter.Line` instance or
dict with compatible properties
marker
:class:`plotly.graph_objects.scatter.Marker` instance
or dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
mode
Determines the drawing mode for this scatter trace. If
the provided `mode` includes "text" then the `text`
elements appear at the coordinates. Otherwise, the
`text` elements appear on hover. If there are less than
20 points and the trace is not stacked then the default
is "lines+markers". Otherwise, "lines".
name
Sets the trace name. The trace name appears as the
legend item and on hover.
offsetgroup
Set several traces linked to the same position axis or
matching axes to the same offsetgroup where bars of the
same position coordinate will line up.
opacity
Sets the opacity of the trace.
orientation
Only relevant in the following cases: 1. when
`scattermode` is set to "group". 2. when `stackgroup`
is used, and only the first `orientation` found in the
`stackgroup` will be used - including if `visible` is
"legendonly" but not if it is `false`. Sets the
stacking direction. With "v" ("h"), the y (x) values of
subsequent traces are added. Also affects the default
value of `fill`.
selected
:class:`plotly.graph_objects.scatter.Selected` instance
or dict with compatible properties
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
stackgaps
Only relevant when `stackgroup` is used, and only the
first `stackgaps` found in the `stackgroup` will be
used - including if `visible` is "legendonly" but not
if it is `false`. Determines how we handle locations at
which other traces in this group have data but this one
does not. With *infer zero* we insert a zero at these
locations. With "interpolate" we linearly interpolate
between existing values, and extrapolate a constant
beyond the existing values.
stackgroup
Set several scatter traces (on the same subplot) to the
same stackgroup in order to add their y values (or
their x values if `orientation` is "h"). If blank or
omitted this trace will not be stacked. Stacking also
turns `fill` on by default, using "tonexty" ("tonextx")
if `orientation` is "h" ("v") and sets the default
`mode` to "lines" irrespective of point count. You can
only stack on a numeric (linear or log) axis. Traces in
a `stackgroup` will only fill to (or be filled to)
other traces in the same group. With multiple
`stackgroup`s or some traces stacked and some not, if
fill-linked traces are not already consecutive, the
later ones will be pushed down in the drawing order.
stream
:class:`plotly.graph_objects.scatter.Stream` instance
or dict with compatible properties
text
Sets text elements associated with each (x,y) pair. If
a single string, the same string appears over all the
data points. If an array of string, the items are
mapped in order to the this trace's (x,y) coordinates.
If trace `hoverinfo` contains a "text" flag and
"hovertext" is not set, these elements will be seen in
the hover labels.
textfont
Sets the text font.
textposition
Sets the positions of the `text` elements with respects
to the (x,y) coordinates.
textpositionsrc
Sets the source reference on Chart Studio Cloud for
`textposition`.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appears on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Variables that can't be found
will be replaced with the specifier. For example, a
template of "data: %{x}, %{y}" will result in a value
of "data: 1, %{y}" if x is 1 and y is missing.
Variables with an undefined value will be replaced with
the fallback value. All attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available.
texttemplatefallback
Fallback string that's displayed when a variable
referenced in a template is missing. If the boolean
value 'false' is passed in, the specifier with the
missing variable will be displayed.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
unselected
:class:`plotly.graph_objects.scatter.Unselected`
instance or dict with compatible properties
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
x
Sets the x coordinates.
x0
Alternate to `x`. Builds a linear space of x
coordinates. Use with `dx` where `x0` is the starting
coordinate and `dx` the step.
xaxis
Sets a reference between this trace's x coordinates and
a 2D cartesian x axis. If "x" (the default value), the
x coordinates refer to `layout.xaxis`. If "x2", the x
coordinates refer to `layout.xaxis2`, and so on.
xcalendar
Sets the calendar system to use with `x` date data.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
xperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the x
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
xperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the x0 axis. When `x0period` is round number
of weeks, the `x0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
xperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the x axis.
xsrc
Sets the source reference on Chart Studio Cloud for
`x`.
y
Sets the y coordinates.
y0
Alternate to `y`. Builds a linear space of y
coordinates. Use with `dy` where `y0` is the starting
coordinate and `dy` the step.
yaxis
Sets a reference between this trace's y coordinates and
a 2D cartesian y axis. If "y" (the default value), the
y coordinates refer to `layout.yaxis`. If "y2", the y
coordinates refer to `layout.yaxis2`, and so on.
ycalendar
Sets the calendar system to use with `y` date data.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
yperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the y
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
yperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the y0 axis. When `y0period` is round number
of weeks, the `y0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
yperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the y axis.
ysrc
Sets the source reference on Chart Studio Cloud for
`y`.
zorder
Sets the layer on which this trace is displayed,
relative to other SVG traces on the same subplot. SVG
traces with higher `zorder` appear in front of those
with lower `zorder`.
Returns
-------
Scatter
"""
super().__init__("scatter")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.Scatter
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Scatter`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("alignmentgroup", arg, alignmentgroup)
self._set_property("cliponaxis", arg, cliponaxis)
self._set_property("connectgaps", arg, connectgaps)
self._set_property("customdata", arg, customdata)
self._set_property("customdatasrc", arg, customdatasrc)
self._set_property("dx", arg, dx)
self._set_property("dy", arg, dy)
self._set_property("error_x", arg, error_x)
self._set_property("error_y", arg, error_y)
self._set_property("fill", arg, fill)
self._set_property("fillcolor", arg, fillcolor)
self._set_property("fillgradient", arg, fillgradient)
self._set_property("fillpattern", arg, fillpattern)
self._set_property("groupnorm", arg, groupnorm)
self._set_property("hoverinfo", arg, hoverinfo)
self._set_property("hoverinfosrc", arg, hoverinfosrc)
self._set_property("hoverlabel", arg, hoverlabel)
self._set_property("hoveron", arg, hoveron)
self._set_property("hovertemplate", arg, hovertemplate)
self._set_property("hovertemplatefallback", arg, hovertemplatefallback)
self._set_property("hovertemplatesrc", arg, hovertemplatesrc)
self._set_property("hovertext", arg, hovertext)
self._set_property("hovertextsrc", arg, hovertextsrc)
self._set_property("ids", arg, ids)
self._set_property("idssrc", arg, idssrc)
self._set_property("legend", arg, legend)
self._set_property("legendgroup", arg, legendgroup)
self._set_property("legendgrouptitle", arg, legendgrouptitle)
self._set_property("legendrank", arg, legendrank)
self._set_property("legendwidth", arg, legendwidth)
self._set_property("line", arg, line)
self._set_property("marker", arg, marker)
self._set_property("meta", arg, meta)
self._set_property("metasrc", arg, metasrc)
self._set_property("mode", arg, mode)
self._set_property("name", arg, name)
self._set_property("offsetgroup", arg, offsetgroup)
self._set_property("opacity", arg, opacity)
self._set_property("orientation", arg, orientation)
self._set_property("selected", arg, selected)
self._set_property("selectedpoints", arg, selectedpoints)
self._set_property("showlegend", arg, showlegend)
self._set_property("stackgaps", arg, stackgaps)
self._set_property("stackgroup", arg, stackgroup)
self._set_property("stream", arg, stream)
self._set_property("text", arg, text)
self._set_property("textfont", arg, textfont)
self._set_property("textposition", arg, textposition)
self._set_property("textpositionsrc", arg, textpositionsrc)
self._set_property("textsrc", arg, textsrc)
self._set_property("texttemplate", arg, texttemplate)
self._set_property("texttemplatefallback", arg, texttemplatefallback)
self._set_property("texttemplatesrc", arg, texttemplatesrc)
self._set_property("uid", arg, uid)
self._set_property("uirevision", arg, uirevision)
self._set_property("unselected", arg, unselected)
self._set_property("visible", arg, visible)
self._set_property("x", arg, x)
self._set_property("x0", arg, x0)
self._set_property("xaxis", arg, xaxis)
self._set_property("xcalendar", arg, xcalendar)
self._set_property("xhoverformat", arg, xhoverformat)
self._set_property("xperiod", arg, xperiod)
self._set_property("xperiod0", arg, xperiod0)
self._set_property("xperiodalignment", arg, xperiodalignment)
self._set_property("xsrc", arg, xsrc)
self._set_property("y", arg, y)
self._set_property("y0", arg, y0)
self._set_property("yaxis", arg, yaxis)
self._set_property("ycalendar", arg, ycalendar)
self._set_property("yhoverformat", arg, yhoverformat)
self._set_property("yperiod", arg, yperiod)
self._set_property("yperiod0", arg, yperiod0)
self._set_property("yperiodalignment", arg, yperiodalignment)
self._set_property("ysrc", arg, ysrc)
self._set_property("zorder", arg, zorder)
self._props["type"] = "scatter"
arg.pop("type", None)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Scatter |
python | ansible__ansible | lib/ansible/module_utils/_internal/_messages.py | {
"start": 791,
"end": 1416
} | class ____(_datatag.AnsibleSerializableEnum):
"""Enum of Ansible plugin types."""
ACTION = _enum.auto()
BECOME = _enum.auto()
CACHE = _enum.auto()
CALLBACK = _enum.auto()
CLICONF = _enum.auto()
CONNECTION = _enum.auto()
DOC_FRAGMENTS = _enum.auto()
FILTER = _enum.auto()
HTTPAPI = _enum.auto()
INVENTORY = _enum.auto()
LOOKUP = _enum.auto()
MODULE = _enum.auto()
NETCONF = _enum.auto()
SHELL = _enum.auto()
STRATEGY = _enum.auto()
TERMINAL = _enum.auto()
TEST = _enum.auto()
VARS = _enum.auto()
@_dataclasses.dataclass(**_dataclass_kwargs)
| PluginType |
python | mitmproxy__pdoc | test/testdata/misc.py | {
"start": 7764,
"end": 7905
} | class ____:
def __new__(cls, *args, **kwargs):
"""This is a class with a docstring inferred from `__new__`."""
| DocstringFromNew |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.