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 | run-llama__llama_index | llama-index-core/llama_index/core/indices/query/query_transform/base.py | {
"start": 6873,
"end": 8410
} | class ____(BaseQueryTransform):
"""
Image output query transform.
Adds instructions for formatting image output.
By default, this prompts the LLM to format image output as an HTML <img> tag,
which can be displayed nicely in jupyter notebook.
"""
def __init__(
self,
width: int = 400,
query_prompt: Optional[ImageOutputQueryTransformPrompt] = None,
) -> None:
"""
Init ImageOutputQueryTransform.
Args:
width (int): desired image display width in pixels
query_prompt (ImageOutputQueryTransformPrompt): custom prompt for
augmenting query with image output instructions.
"""
self._width = width
self._query_prompt: BasePromptTemplate = (
query_prompt or DEFAULT_IMAGE_OUTPUT_PROMPT
)
def _get_prompts(self) -> PromptDictType:
"""Get prompts."""
return {"query_prompt": self._query_prompt}
def _update_prompts(self, prompts: PromptDictType) -> None:
"""Update prompts."""
if "query_prompt" in prompts:
self._query_prompt = prompts["query_prompt"]
def _run(self, query_bundle: QueryBundle, metadata: Dict) -> QueryBundle:
"""Run query transform."""
del metadata # Unused
new_query_str = self._query_prompt.format(
query_str=query_bundle.query_str, image_width=self._width
)
return dataclasses.replace(query_bundle, query_str=new_query_str)
| ImageOutputQueryTransform |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 181897,
"end": 182714
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"project_id",
"title",
"short_description",
"readme",
"closed",
"public",
"client_mutation_id",
)
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId")
title = sgqlc.types.Field(String, graphql_name="title")
short_description = sgqlc.types.Field(String, graphql_name="shortDescription")
readme = sgqlc.types.Field(String, graphql_name="readme")
closed = sgqlc.types.Field(Boolean, graphql_name="closed")
public = sgqlc.types.Field(Boolean, graphql_name="public")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| UpdateProjectV2Input |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 8634,
"end": 8763
} | class ____:
xlAutomaticAllocation = 2 # from enum XlAllocation
xlManualAllocation = 1 # from enum XlAllocation
| Allocation |
python | pytorch__pytorch | torch/nn/modules/pooling.py | {
"start": 4963,
"end": 8504
} | class ____(_MaxPoolNd):
r"""Applies a 2D max pooling over an input signal composed of several input planes.
In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`,
output :math:`(N, C, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kH, kW)`
can be precisely described as:
.. math::
\begin{aligned}
out(N_i, C_j, h, w) ={} & \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1} \\
& \text{input}(N_i, C_j, \text{stride[0]} \times h + m,
\text{stride[1]} \times w + n)
\end{aligned}
If :attr:`padding` is non-zero, then the input is implicitly padded with negative infinity on both sides
for :attr:`padding` number of points. :attr:`dilation` controls the spacing between the kernel points.
It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
Note:
When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
or the input. Sliding windows that would start in the right padded region are ignored.
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
- a single ``int`` -- in which case the same value is used for the height and width dimension
- a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
and the second `int` for the width dimension
Args:
kernel_size: the size of the window to take a max over
stride: the stride of the window. Default value is :attr:`kernel_size`
padding: Implicit negative infinity padding to be added on both sides
dilation: a parameter that controls the stride of elements in the window
return_indices: if ``True``, will return the max indices along with the outputs.
Useful for :class:`torch.nn.MaxUnpool2d` later
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
Shape:
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
.. math::
H_{out} = \left\lfloor\frac{H_{in} + 2 * \text{padding[0]} - \text{dilation[0]}
\times (\text{kernel\_size[0]} - 1) - 1}{\text{stride[0]}} + 1\right\rfloor
.. math::
W_{out} = \left\lfloor\frac{W_{in} + 2 * \text{padding[1]} - \text{dilation[1]}
\times (\text{kernel\_size[1]} - 1) - 1}{\text{stride[1]}} + 1\right\rfloor
Examples::
>>> # pool of square window of size=3, stride=2
>>> m = nn.MaxPool2d(3, stride=2)
>>> # pool of non-square window
>>> m = nn.MaxPool2d((3, 2), stride=(2, 1))
>>> input = torch.randn(20, 16, 50, 32)
>>> output = m(input)
.. _link:
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
"""
kernel_size: _size_2_t
stride: _size_2_t
padding: _size_2_t
dilation: _size_2_t
def forward(self, input: Tensor):
"""Runs the forward pass."""
return F.max_pool2d(
input,
self.kernel_size,
self.stride,
self.padding,
self.dilation,
ceil_mode=self.ceil_mode,
return_indices=self.return_indices,
)
| MaxPool2d |
python | django__django | django/db/models/constraints.py | {
"start": 10195,
"end": 28124
} | class ____(BaseConstraint):
def __init__(
self,
*expressions,
fields=(),
name=None,
condition=None,
deferrable=None,
include=None,
opclasses=(),
nulls_distinct=None,
violation_error_code=None,
violation_error_message=None,
):
if not name:
raise ValueError("A unique constraint must be named.")
if not expressions and not fields:
raise ValueError(
"At least one field or expression is required to define a "
"unique constraint."
)
if expressions and fields:
raise ValueError(
"UniqueConstraint.fields and expressions are mutually exclusive."
)
if not isinstance(condition, (NoneType, Q)):
raise ValueError("UniqueConstraint.condition must be a Q instance.")
if condition and deferrable:
raise ValueError("UniqueConstraint with conditions cannot be deferred.")
if include and deferrable:
raise ValueError("UniqueConstraint with include fields cannot be deferred.")
if opclasses and deferrable:
raise ValueError("UniqueConstraint with opclasses cannot be deferred.")
if expressions and deferrable:
raise ValueError("UniqueConstraint with expressions cannot be deferred.")
if expressions and opclasses:
raise ValueError(
"UniqueConstraint.opclasses cannot be used with expressions. "
"Use django.contrib.postgres.indexes.OpClass() instead."
)
if not isinstance(deferrable, (NoneType, Deferrable)):
raise TypeError(
"UniqueConstraint.deferrable must be a Deferrable instance."
)
if not isinstance(include, (NoneType, list, tuple)):
raise TypeError("UniqueConstraint.include must be a list or tuple.")
if not isinstance(opclasses, (list, tuple)):
raise TypeError("UniqueConstraint.opclasses must be a list or tuple.")
if not isinstance(nulls_distinct, (NoneType, bool)):
raise TypeError("UniqueConstraint.nulls_distinct must be a bool.")
if opclasses and len(fields) != len(opclasses):
raise ValueError(
"UniqueConstraint.fields and UniqueConstraint.opclasses must "
"have the same number of elements."
)
self.fields = tuple(fields)
self.condition = condition
self.deferrable = deferrable
self.include = tuple(include) if include else ()
self.opclasses = opclasses
self.nulls_distinct = nulls_distinct
self.expressions = tuple(
F(expression) if isinstance(expression, str) else expression
for expression in expressions
)
super().__init__(
name=name,
violation_error_code=violation_error_code,
violation_error_message=violation_error_message,
)
@property
def contains_expressions(self):
return bool(self.expressions)
def check(self, model, connection):
errors = model._check_local_fields({*self.fields, *self.include}, "constraints")
required_db_features = model._meta.required_db_features
if self.condition is not None and not (
connection.features.supports_partial_indexes
or "supports_partial_indexes" in required_db_features
):
errors.append(
checks.Warning(
f"{connection.display_name} does not support unique constraints "
"with conditions.",
hint=(
"A constraint won't be created. Silence this warning if you "
"don't care about it."
),
obj=model,
id="models.W036",
)
)
if self.deferrable is not None and not (
connection.features.supports_deferrable_unique_constraints
or "supports_deferrable_unique_constraints" in required_db_features
):
errors.append(
checks.Warning(
f"{connection.display_name} does not support deferrable unique "
"constraints.",
hint=(
"A constraint won't be created. Silence this warning if you "
"don't care about it."
),
obj=model,
id="models.W038",
)
)
if self.include and not (
connection.features.supports_covering_indexes
or "supports_covering_indexes" in required_db_features
):
errors.append(
checks.Warning(
f"{connection.display_name} does not support unique constraints "
"with non-key columns.",
hint=(
"A constraint won't be created. Silence this warning if you "
"don't care about it."
),
obj=model,
id="models.W039",
)
)
if self.contains_expressions and not (
connection.features.supports_expression_indexes
or "supports_expression_indexes" in required_db_features
):
errors.append(
checks.Warning(
f"{connection.display_name} does not support unique constraints on "
"expressions.",
hint=(
"A constraint won't be created. Silence this warning if you "
"don't care about it."
),
obj=model,
id="models.W044",
)
)
if self.nulls_distinct is not None and not (
connection.features.supports_nulls_distinct_unique_constraints
or "supports_nulls_distinct_unique_constraints" in required_db_features
):
errors.append(
checks.Warning(
f"{connection.display_name} does not support unique constraints "
"with nulls distinct.",
hint=(
"A constraint won't be created. Silence this warning if you "
"don't care about it."
),
obj=model,
id="models.W047",
)
)
references = set()
if (
connection.features.supports_partial_indexes
or "supports_partial_indexes" not in required_db_features
) and isinstance(self.condition, Q):
references.update(model._get_expr_references(self.condition))
if self.contains_expressions and (
connection.features.supports_expression_indexes
or "supports_expression_indexes" not in required_db_features
):
for expression in self.expressions:
references.update(model._get_expr_references(expression))
errors.extend(self._check_references(model, references))
return errors
def _get_condition_sql(self, model, schema_editor):
if self.condition is None:
return None
query = Query(model=model, alias_cols=False)
where = query.build_where(self.condition)
compiler = query.get_compiler(connection=schema_editor.connection)
sql, params = where.as_sql(compiler, schema_editor.connection)
return sql % tuple(schema_editor.quote_value(p) for p in params)
def _get_index_expressions(self, model, schema_editor):
if not self.expressions:
return None
index_expressions = []
for expression in self.expressions:
index_expression = IndexExpression(expression)
index_expression.set_wrapper_classes(schema_editor.connection)
index_expressions.append(index_expression)
return ExpressionList(*index_expressions).resolve_expression(
Query(model, alias_cols=False),
)
def constraint_sql(self, model, schema_editor):
fields = [model._meta.get_field(field_name) for field_name in self.fields]
include = [
model._meta.get_field(field_name).column for field_name in self.include
]
condition = self._get_condition_sql(model, schema_editor)
expressions = self._get_index_expressions(model, schema_editor)
return schema_editor._unique_sql(
model,
fields,
self.name,
condition=condition,
deferrable=self.deferrable,
include=include,
opclasses=self.opclasses,
expressions=expressions,
nulls_distinct=self.nulls_distinct,
)
def create_sql(self, model, schema_editor):
fields = [model._meta.get_field(field_name) for field_name in self.fields]
include = [
model._meta.get_field(field_name).column for field_name in self.include
]
condition = self._get_condition_sql(model, schema_editor)
expressions = self._get_index_expressions(model, schema_editor)
return schema_editor._create_unique_sql(
model,
fields,
self.name,
condition=condition,
deferrable=self.deferrable,
include=include,
opclasses=self.opclasses,
expressions=expressions,
nulls_distinct=self.nulls_distinct,
)
def remove_sql(self, model, schema_editor):
condition = self._get_condition_sql(model, schema_editor)
include = [
model._meta.get_field(field_name).column for field_name in self.include
]
expressions = self._get_index_expressions(model, schema_editor)
return schema_editor._delete_unique_sql(
model,
self.name,
condition=condition,
deferrable=self.deferrable,
include=include,
opclasses=self.opclasses,
expressions=expressions,
nulls_distinct=self.nulls_distinct,
)
def __repr__(self):
return "<%s:%s%s%s%s%s%s%s%s%s%s>" % (
self.__class__.__qualname__,
"" if not self.fields else " fields=%s" % repr(self.fields),
"" if not self.expressions else " expressions=%s" % repr(self.expressions),
" name=%s" % repr(self.name),
"" if self.condition is None else " condition=%s" % self.condition,
"" if self.deferrable is None else " deferrable=%r" % self.deferrable,
"" if not self.include else " include=%s" % repr(self.include),
"" if not self.opclasses else " opclasses=%s" % repr(self.opclasses),
(
""
if self.nulls_distinct is None
else " nulls_distinct=%r" % self.nulls_distinct
),
(
""
if self.violation_error_code is None
else " violation_error_code=%r" % self.violation_error_code
),
(
""
if self.violation_error_message is None
or self.violation_error_message == self.default_violation_error_message
else " violation_error_message=%r" % self.violation_error_message
),
)
def __eq__(self, other):
if isinstance(other, UniqueConstraint):
return (
self.name == other.name
and self.fields == other.fields
and self.condition == other.condition
and self.deferrable == other.deferrable
and self.include == other.include
and self.opclasses == other.opclasses
and self.expressions == other.expressions
and self.nulls_distinct is other.nulls_distinct
and self.violation_error_code == other.violation_error_code
and self.violation_error_message == other.violation_error_message
)
return super().__eq__(other)
def deconstruct(self):
path, args, kwargs = super().deconstruct()
if self.fields:
kwargs["fields"] = self.fields
if self.condition:
kwargs["condition"] = self.condition
if self.deferrable:
kwargs["deferrable"] = self.deferrable
if self.include:
kwargs["include"] = self.include
if self.opclasses:
kwargs["opclasses"] = self.opclasses
if self.nulls_distinct is not None:
kwargs["nulls_distinct"] = self.nulls_distinct
return path, self.expressions, kwargs
def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS):
queryset = model._default_manager.using(using)
if self.fields:
lookup_kwargs = {}
generated_field_names = []
for field_name in self.fields:
if exclude and field_name in exclude:
return
field = model._meta.get_field(field_name)
if field.generated:
if exclude and self._expression_refs_exclude(
model, field.expression, exclude
):
return
generated_field_names.append(field.name)
else:
lookup_value = getattr(instance, field.attname)
if (
self.nulls_distinct is not False
and lookup_value is None
or (
lookup_value == ""
and connections[
using
].features.interprets_empty_strings_as_nulls
)
):
# A composite constraint containing NULL value cannot
# cause a violation since NULL != NULL in SQL.
return
lookup_kwargs[field.name] = lookup_value
lookup_args = []
if generated_field_names:
field_expression_map = instance._get_field_expression_map(
meta=model._meta, exclude=exclude
)
for field_name in generated_field_names:
expression = field_expression_map[field_name]
if self.nulls_distinct is False:
lhs = F(field_name)
condition = Q(Exact(lhs, expression)) | Q(
IsNull(lhs, True), IsNull(expression, True)
)
lookup_args.append(condition)
else:
lookup_kwargs[field_name] = expression
queryset = queryset.filter(*lookup_args, **lookup_kwargs)
else:
# Ignore constraints with excluded fields.
if exclude and any(
self._expression_refs_exclude(model, expression, exclude)
for expression in self.expressions
):
return
replacements = {
F(field): value
for field, value in instance._get_field_expression_map(
meta=model._meta, exclude=exclude
).items()
}
filters = []
for expr in self.expressions:
if hasattr(expr, "get_expression_for_validation"):
expr = expr.get_expression_for_validation()
rhs = expr.replace_expressions(replacements)
condition = Exact(expr, rhs)
if self.nulls_distinct is False:
condition = Q(condition) | Q(IsNull(expr, True), IsNull(rhs, True))
filters.append(condition)
queryset = queryset.filter(*filters)
model_class_pk = instance._get_pk_val(model._meta)
if not instance._state.adding and instance._is_pk_set(model._meta):
queryset = queryset.exclude(pk=model_class_pk)
if not self.condition:
if queryset.exists():
if (
self.fields
and self.violation_error_message
== self.default_violation_error_message
):
# When fields are defined, use the unique_error_message()
# as a default for backward compatibility.
validation_error_message = instance.unique_error_message(
model, self.fields
)
raise ValidationError(
validation_error_message,
code=validation_error_message.code,
)
raise ValidationError(
self.get_violation_error_message(),
code=self.violation_error_code,
)
else:
# Ignore constraints with excluded fields in condition.
if exclude and self._expression_refs_exclude(
model, self.condition, exclude
):
return
against = instance._get_field_expression_map(
meta=model._meta, exclude=exclude
)
if (self.condition & Exists(queryset.filter(self.condition))).check(
against, using=using
):
raise ValidationError(
self.get_violation_error_message(),
code=self.violation_error_code,
)
| UniqueConstraint |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 5027,
"end": 8746
} | class ____(BuiltinFunctionT):
_id = "convert"
def fetch_call_return(self, node):
_, target_typedef = self.infer_arg_types(node)
# note: more type conversion validation happens in convert.py
return target_typedef.typedef
# TODO: push this down into convert.py for more consistency
def infer_arg_types(self, node, expected_return_typ=None):
validate_call_args(node, 2)
target_type = type_from_annotation(node.args[1])
value_types = get_possible_types_from_node(node.args[0])
# For `convert` of integer literals, we need to match type inference rules in
# convert.py codegen routines.
# TODO: This can probably be removed once constant folding for `convert` is implemented
if len(value_types) > 1 and all(isinstance(v, IntegerT) for v in value_types):
# Get the smallest (and unsigned if available) type for non-integer target types
# (note this is different from the ordering returned by `get_possible_types_from_node`)
if not isinstance(target_type, IntegerT):
value_types = sorted(value_types, key=lambda v: (v.is_signed, v.bits), reverse=True)
else:
# filter out the target type from list of possible types
value_types = [i for i in value_types if not target_type.compare_type(i)]
value_type = value_types.pop()
# block conversions between same type
if target_type.compare_type(value_type):
raise InvalidType(f"Value and target type are both '{target_type}'", node)
return [value_type, TYPE_T(target_type)]
def build_IR(self, expr, context):
return convert(expr, context)
ADHOC_SLICE_NODE_MACROS = ["~calldata", "~selfcode", "~extcode"]
def _build_adhoc_slice_node(sub: IRnode, start: IRnode, length: IRnode, context: Context) -> IRnode:
assert length.is_literal, "typechecker failed"
assert isinstance(length.value, int) # mypy hint
dst_typ = BytesT(length.value)
# allocate a buffer for the return value
buf = context.new_internal_variable(dst_typ)
with scope_multi((start, length), ("start", "length")) as (b1, (start, length)):
# `msg.data` by `calldatacopy`
if sub.value == "~calldata":
node = [
"seq",
check_buffer_overflow_ir(start, length, "calldatasize"),
["mstore", buf, length],
["calldatacopy", add_ofst(buf, 32), start, length],
buf,
]
# `self.code` by `codecopy`
elif sub.value == "~selfcode":
node = [
"seq",
check_buffer_overflow_ir(start, length, "codesize"),
["mstore", buf, length],
["codecopy", add_ofst(buf, 32), start, length],
buf,
]
# `<address>.code` by `extcodecopy`
else:
assert sub.value == "~extcode" and len(sub.args) == 1
node = [
"with",
"_extcode_address",
sub.args[0],
[
"seq",
check_buffer_overflow_ir(start, length, ["extcodesize", "_extcode_address"]),
["mstore", buf, length],
["extcodecopy", "_extcode_address", add_ofst(buf, 32), start, length],
buf,
],
]
assert isinstance(length.value, int) # mypy hint
ret = IRnode.from_list(node, typ=BytesT(length.value), location=MEMORY)
return b1.resolve(ret)
# note: this and a lot of other builtins could be refactored to accept any uint type
| Convert |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/svd_op_test.py | {
"start": 10015,
"end": 12134
} | class ____(test.TestCase):
pass # Filled in below
def _NormalizingSvd(tf_a, full_matrices_):
tf_s, tf_u, tf_v = linalg_ops.svd(
tf_a, compute_uv=True, full_matrices=full_matrices_)
# Singular vectors are only unique up to an arbitrary phase. We normalize
# the vectors such that the first component of u (if m >=n) or v (if n > m)
# have phase 0.
m = tf_a.shape[-2]
n = tf_a.shape[-1]
if m >= n:
top_rows = tf_u[..., 0:1, :]
else:
top_rows = tf_v[..., 0:1, :]
if tf_u.dtype.is_complex:
angle = -math_ops.angle(top_rows)
phase = math_ops.complex(math_ops.cos(angle), math_ops.sin(angle))
else:
phase = math_ops.sign(top_rows)
tf_u *= phase[..., :m]
tf_v *= phase[..., :n]
return tf_s, tf_u, tf_v
def _GetSvdGradOpTest(dtype_, shape_, compute_uv_, full_matrices_):
@test_util.run_in_graph_and_eager_modes(use_gpu=True)
def Test(self):
def RandomInput():
np.random.seed(42)
a = np.random.uniform(low=-1.0, high=1.0, size=shape_).astype(dtype_)
if dtype_ in [np.complex64, np.complex128]:
a += 1j * np.random.uniform(
low=-1.0, high=1.0, size=shape_).astype(dtype_)
return a
# Optimal stepsize for central difference is O(epsilon^{1/3}).
# See Equation (21) in:
# http://www.karenkopecky.net/Teaching/eco613614/Notes_NumericalDifferentiation.pdf
# TODO(rmlarsen): Move step size control to gradient checker.
epsilon = np.finfo(dtype_).eps
delta = 0.25 * epsilon**(1.0 / 3.0)
if dtype_ in [np.float32, np.complex64]:
tol = 3e-2
else:
tol = 1e-6
if compute_uv_:
funcs = [
lambda a: _NormalizingSvd(a, full_matrices_)[0],
lambda a: _NormalizingSvd(a, full_matrices_)[1],
lambda a: _NormalizingSvd(a, full_matrices_)[2]
]
else:
funcs = [lambda a: linalg_ops.svd(a, compute_uv=False)]
for f in funcs:
theoretical, numerical = gradient_checker_v2.compute_gradient(
f, [RandomInput()], delta=delta)
self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)
return Test
| SvdGradOpTest |
python | jamielennox__requests-mock | requests_mock/response.py | {
"start": 3075,
"end": 4210
} | class ____(object):
"""An object that can mock the necessary parts of a socket interface."""
def send(self, request, **kwargs):
msg = 'This response was created without a connection. You are ' \
'therefore unable to make a request directly on that connection.'
raise exceptions.InvalidRequest(msg)
def close(self):
pass
def _extract_cookies(request, response, cookies):
"""Add cookies to the response.
Cookies in requests are extracted from the headers in the original_response
httplib.HTTPMessage which we don't create so we have to do this step
manually.
"""
# This will add cookies set manually via the Set-Cookie or Set-Cookie2
# header but this only allows 1 cookie to be set.
response.cookies.extract_cookies(MockResponse(response.raw.headers),
MockRequest(request))
# This allows you to pass either a CookieJar or a dictionary to request_uri
# or directly to create_response. To allow more than one cookie to be set.
if cookies:
merge_cookies(response.cookies, cookies)
| _FakeConnection |
python | Textualize__textual | tests/animations/test_switch_animation.py | {
"start": 218,
"end": 2369
} | class ____(App[None]):
def compose(self) -> ComposeResult:
yield Switch()
async def test_switch_animates_on_full() -> None:
app = SwitchApp()
app.animation_level = "full"
async with app.run_test() as pilot:
switch = app.query_one(Switch)
animator = app.animator
# Freeze time at 0 before triggering the animation.
animator._get_time = lambda *_: 0
switch.action_toggle_switch()
await pilot.pause()
# Freeze time after the animation start and before animation end.
animator._get_time = lambda *_: 0.01
# Move to the next frame.
animator()
# The animation should still be running.
assert app.animator.is_being_animated(switch, "_slider_position")
async def test_switch_animates_on_basic() -> None:
app = SwitchApp()
app.animation_level = "basic"
async with app.run_test() as pilot:
switch = app.query_one(Switch)
animator = app.animator
# Freeze time at 0 before triggering the animation.
animator._get_time = lambda *_: 0
switch.action_toggle_switch()
await pilot.pause()
# Freeze time after the animation start and before animation end.
animator._get_time = lambda *_: 0.01
# Move to the next frame.
animator()
# The animation should still be running.
assert app.animator.is_being_animated(switch, "_slider_position")
async def test_switch_does_not_animate_on_none() -> None:
app = SwitchApp()
app.animation_level = "none"
async with app.run_test() as pilot:
switch = app.query_one(Switch)
animator = app.animator
# Freeze time at 0 before triggering the animation.
animator._get_time = lambda *_: 0
switch.action_toggle_switch()
await pilot.pause()
# Freeze time after the animation start and before animation end.
animator._get_time = lambda *_: 0.01
# Move to the next frame.
animator()
# The animation should still be running.
assert not app.animator.is_being_animated(switch, "_slider_position")
| SwitchApp |
python | joke2k__faker | faker/providers/internet/sv_SE/__init__.py | {
"start": 46,
"end": 475
} | class ____(InternetProvider):
free_email_domains = (
"telia.com",
"gmail.com",
"swipnet.se",
"googlemail.com",
"live.se",
"spray.se",
"yahoo.de",
)
tlds = ("com", "com", "com", "se", "se", "se", "net", "org")
replacements = (
("å", "a"),
("Å", "A"),
("ä", "a"),
("Ä", "A"),
("ö", "o"),
("Ö", "O"),
)
| Provider |
python | scikit-learn__scikit-learn | sklearn/kernel_approximation.py | {
"start": 836,
"end": 8651
} | class ____(
ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator
):
"""Polynomial kernel approximation via Tensor Sketch.
Implements Tensor Sketch, which approximates the feature map
of the polynomial kernel::
K(X, Y) = (gamma * <X, Y> + coef0)^degree
by efficiently computing a Count Sketch of the outer product of a
vector with itself using Fast Fourier Transforms (FFT). Read more in the
:ref:`User Guide <polynomial_kernel_approx>`.
.. versionadded:: 0.24
Parameters
----------
gamma : float, default=1.0
Parameter of the polynomial kernel whose feature map
will be approximated.
degree : int, default=2
Degree of the polynomial kernel whose feature map
will be approximated.
coef0 : int, default=0
Constant term of the polynomial kernel whose feature map
will be approximated.
n_components : int, default=100
Dimensionality of the output feature space. Usually, `n_components`
should be greater than the number of features in input samples in
order to achieve good performance. The optimal score / run time
balance is typically achieved around `n_components` = 10 * `n_features`,
but this depends on the specific dataset being used.
random_state : int, RandomState instance, default=None
Determines random number generation for indexHash and bitHash
initialization. Pass an int for reproducible results across multiple
function calls. See :term:`Glossary <random_state>`.
Attributes
----------
indexHash_ : ndarray of shape (degree, n_features), dtype=int64
Array of indexes in range [0, n_components) used to represent
the 2-wise independent hash functions for Count Sketch computation.
bitHash_ : ndarray of shape (degree, n_features), dtype=float32
Array with random entries in {+1, -1}, used to represent
the 2-wise independent hash functions for Count Sketch computation.
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
AdditiveChi2Sampler : Approximate feature map for additive chi2 kernel.
Nystroem : Approximate a kernel map using a subset of the training data.
RBFSampler : Approximate a RBF kernel feature map using random Fourier
features.
SkewedChi2Sampler : Approximate feature map for "skewed chi-squared" kernel.
sklearn.metrics.pairwise.kernel_metrics : List of built-in kernels.
Examples
--------
>>> from sklearn.kernel_approximation import PolynomialCountSketch
>>> from sklearn.linear_model import SGDClassifier
>>> X = [[0, 0], [1, 1], [1, 0], [0, 1]]
>>> y = [0, 0, 1, 1]
>>> ps = PolynomialCountSketch(degree=3, random_state=1)
>>> X_features = ps.fit_transform(X)
>>> clf = SGDClassifier(max_iter=10, tol=1e-3)
>>> clf.fit(X_features, y)
SGDClassifier(max_iter=10)
>>> clf.score(X_features, y)
1.0
For a more detailed example of usage, see
:ref:`sphx_glr_auto_examples_kernel_approximation_plot_scalable_poly_kernels.py`
"""
_parameter_constraints: dict = {
"gamma": [Interval(Real, 0, None, closed="left")],
"degree": [Interval(Integral, 1, None, closed="left")],
"coef0": [Interval(Real, None, None, closed="neither")],
"n_components": [Interval(Integral, 1, None, closed="left")],
"random_state": ["random_state"],
}
def __init__(
self, *, gamma=1.0, degree=2, coef0=0, n_components=100, random_state=None
):
self.gamma = gamma
self.degree = degree
self.coef0 = coef0
self.n_components = n_components
self.random_state = random_state
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y=None):
"""Fit the model with X.
Initializes the internal variables. The method needs no information
about the distribution of data, so we only care about n_features in X.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : array-like of shape (n_samples,) or (n_samples, n_outputs), \
default=None
Target values (None for unsupervised transformations).
Returns
-------
self : object
Returns the instance itself.
"""
X = validate_data(self, X, accept_sparse="csc")
random_state = check_random_state(self.random_state)
n_features = X.shape[1]
if self.coef0 != 0:
n_features += 1
self.indexHash_ = random_state.randint(
0, high=self.n_components, size=(self.degree, n_features)
)
self.bitHash_ = random_state.choice(a=[-1, 1], size=(self.degree, n_features))
self._n_features_out = self.n_components
return self
def transform(self, X):
"""Generate the feature map approximation for X.
Parameters
----------
X : {array-like}, shape (n_samples, n_features)
New data, where `n_samples` is the number of samples
and `n_features` is the number of features.
Returns
-------
X_new : array-like, shape (n_samples, n_components)
Returns the instance itself.
"""
check_is_fitted(self)
X = validate_data(self, X, accept_sparse="csc", reset=False)
X_gamma = np.sqrt(self.gamma) * X
if sp.issparse(X_gamma) and self.coef0 != 0:
X_gamma = sp.hstack(
[X_gamma, np.sqrt(self.coef0) * np.ones((X_gamma.shape[0], 1))],
format="csc",
)
elif not sp.issparse(X_gamma) and self.coef0 != 0:
X_gamma = np.hstack(
[X_gamma, np.sqrt(self.coef0) * np.ones((X_gamma.shape[0], 1))]
)
if X_gamma.shape[1] != self.indexHash_.shape[1]:
raise ValueError(
"Number of features of test samples does not"
" match that of training samples."
)
count_sketches = np.zeros((X_gamma.shape[0], self.degree, self.n_components))
if sp.issparse(X_gamma):
for j in range(X_gamma.shape[1]):
for d in range(self.degree):
iHashIndex = self.indexHash_[d, j]
iHashBit = self.bitHash_[d, j]
count_sketches[:, d, iHashIndex] += (
(iHashBit * X_gamma[:, [j]]).toarray().ravel()
)
else:
for j in range(X_gamma.shape[1]):
for d in range(self.degree):
iHashIndex = self.indexHash_[d, j]
iHashBit = self.bitHash_[d, j]
count_sketches[:, d, iHashIndex] += iHashBit * X_gamma[:, j]
# For each same, compute a count sketch of phi(x) using the polynomial
# multiplication (via FFT) of p count sketches of x.
count_sketches_fft = fft(count_sketches, axis=2, overwrite_x=True)
count_sketches_fft_prod = np.prod(count_sketches_fft, axis=1)
data_sketch = np.real(ifft(count_sketches_fft_prod, overwrite_x=True))
return data_sketch
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.input_tags.sparse = True
return tags
| PolynomialCountSketch |
python | pypa__pipenv | pipenv/vendor/click/_termui_impl.py | {
"start": 15625,
"end": 24069
} | class ____:
def __init__(
self,
editor: t.Optional[str] = None,
env: t.Optional[t.Mapping[str, str]] = None,
require_save: bool = True,
extension: str = ".txt",
) -> None:
self.editor = editor
self.env = env
self.require_save = require_save
self.extension = extension
def get_editor(self) -> str:
if self.editor is not None:
return self.editor
for key in "VISUAL", "EDITOR":
rv = os.environ.get(key)
if rv:
return rv
if WIN:
return "notepad"
for editor in "sensible-editor", "vim", "nano":
if os.system(f"which {editor} >/dev/null 2>&1") == 0:
return editor
return "vi"
def edit_file(self, filename: str) -> None:
import subprocess
editor = self.get_editor()
environ: t.Optional[t.Dict[str, str]] = None
if self.env:
environ = os.environ.copy()
environ.update(self.env)
try:
c = subprocess.Popen(f'{editor} "{filename}"', env=environ, shell=True)
exit_code = c.wait()
if exit_code != 0:
raise ClickException(
_("{editor}: Editing failed").format(editor=editor)
)
except OSError as e:
raise ClickException(
_("{editor}: Editing failed: {e}").format(editor=editor, e=e)
) from e
def edit(self, text: t.Optional[t.AnyStr]) -> t.Optional[t.AnyStr]:
import tempfile
if not text:
data = b""
elif isinstance(text, (bytes, bytearray)):
data = text
else:
if text and not text.endswith("\n"):
text += "\n"
if WIN:
data = text.replace("\n", "\r\n").encode("utf-8-sig")
else:
data = text.encode("utf-8")
fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)
f: t.BinaryIO
try:
with os.fdopen(fd, "wb") as f:
f.write(data)
# If the filesystem resolution is 1 second, like Mac OS
# 10.12 Extended, or 2 seconds, like FAT32, and the editor
# closes very fast, require_save can fail. Set the modified
# time to be 2 seconds in the past to work around this.
os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))
# Depending on the resolution, the exact value might not be
# recorded, so get the new recorded value.
timestamp = os.path.getmtime(name)
self.edit_file(name)
if self.require_save and os.path.getmtime(name) == timestamp:
return None
with open(name, "rb") as f:
rv = f.read()
if isinstance(text, (bytes, bytearray)):
return rv
return rv.decode("utf-8-sig").replace("\r\n", "\n") # type: ignore
finally:
os.unlink(name)
def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
import subprocess
def _unquote_file(url: str) -> str:
from urllib.parse import unquote
if url.startswith("file://"):
url = unquote(url[7:])
return url
if sys.platform == "darwin":
args = ["open"]
if wait:
args.append("-W")
if locate:
args.append("-R")
args.append(_unquote_file(url))
null = open("/dev/null", "w")
try:
return subprocess.Popen(args, stderr=null).wait()
finally:
null.close()
elif WIN:
if locate:
url = _unquote_file(url.replace('"', ""))
args = f'explorer /select,"{url}"'
else:
url = url.replace('"', "")
wait_str = "/WAIT" if wait else ""
args = f'start {wait_str} "" "{url}"'
return os.system(args)
elif CYGWIN:
if locate:
url = os.path.dirname(_unquote_file(url).replace('"', ""))
args = f'cygstart "{url}"'
else:
url = url.replace('"', "")
wait_str = "-w" if wait else ""
args = f'cygstart {wait_str} "{url}"'
return os.system(args)
try:
if locate:
url = os.path.dirname(_unquote_file(url)) or "."
else:
url = _unquote_file(url)
c = subprocess.Popen(["xdg-open", url])
if wait:
return c.wait()
return 0
except OSError:
if url.startswith(("http://", "https://")) and not locate and not wait:
import webbrowser
webbrowser.open(url)
return 0
return 1
def _translate_ch_to_exc(ch: str) -> t.Optional[BaseException]:
if ch == "\x03":
raise KeyboardInterrupt()
if ch == "\x04" and not WIN: # Unix-like, Ctrl+D
raise EOFError()
if ch == "\x1a" and WIN: # Windows, Ctrl+Z
raise EOFError()
return None
if WIN:
import msvcrt
@contextlib.contextmanager
def raw_terminal() -> t.Iterator[int]:
yield -1
def getchar(echo: bool) -> str:
# The function `getch` will return a bytes object corresponding to
# the pressed character. Since Windows 10 build 1803, it will also
# return \x00 when called a second time after pressing a regular key.
#
# `getwch` does not share this probably-bugged behavior. Moreover, it
# returns a Unicode object by default, which is what we want.
#
# Either of these functions will return \x00 or \xe0 to indicate
# a special key, and you need to call the same function again to get
# the "rest" of the code. The fun part is that \u00e0 is
# "latin small letter a with grave", so if you type that on a French
# keyboard, you _also_ get a \xe0.
# E.g., consider the Up arrow. This returns \xe0 and then \x48. The
# resulting Unicode string reads as "a with grave" + "capital H".
# This is indistinguishable from when the user actually types
# "a with grave" and then "capital H".
#
# When \xe0 is returned, we assume it's part of a special-key sequence
# and call `getwch` again, but that means that when the user types
# the \u00e0 character, `getchar` doesn't return until a second
# character is typed.
# The alternative is returning immediately, but that would mess up
# cross-platform handling of arrow keys and others that start with
# \xe0. Another option is using `getch`, but then we can't reliably
# read non-ASCII characters, because return values of `getch` are
# limited to the current 8-bit codepage.
#
# Anyway, Click doesn't claim to do this Right(tm), and using `getwch`
# is doing the right thing in more situations than with `getch`.
func: t.Callable[[], str]
if echo:
func = msvcrt.getwche # type: ignore
else:
func = msvcrt.getwch # type: ignore
rv = func()
if rv in ("\x00", "\xe0"):
# \x00 and \xe0 are control characters that indicate special key,
# see above.
rv += func()
_translate_ch_to_exc(rv)
return rv
else:
import tty
import termios
@contextlib.contextmanager
def raw_terminal() -> t.Iterator[int]:
f: t.Optional[t.TextIO]
fd: int
if not isatty(sys.stdin):
f = open("/dev/tty")
fd = f.fileno()
else:
fd = sys.stdin.fileno()
f = None
try:
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
yield fd
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
sys.stdout.flush()
if f is not None:
f.close()
except termios.error:
pass
def getchar(echo: bool) -> str:
with raw_terminal() as fd:
ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")
if echo and isatty(sys.stdout):
sys.stdout.write(ch)
_translate_ch_to_exc(ch)
return ch
| Editor |
python | modin-project__modin | modin/utils.py | {
"start": 1982,
"end": 2215
} | class ____(Protocol): # noqa: PR01
"""Structural type for objects with a ``to_pandas`` method (without a leading underscore)."""
def to_pandas(self) -> Any: # noqa: GL08
pass
@runtime_checkable
| SupportsPublicToPandas |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 38960,
"end": 41520
} | class ____(rv_continuous):
r"""A Burr (Type XII) continuous random variable.
%(before_notes)s
See Also
--------
fisk : a special case of either `burr` or `burr12` with ``d=1``
burr : Burr Type III distribution
Notes
-----
The probability density function for `burr12` is:
.. math::
f(x; c, d) = c d \frac{x^{c-1}}
{(1 + x^c)^{d + 1}}
for :math:`x >= 0` and :math:`c, d > 0`.
`burr12` takes ``c`` and ``d`` as shape parameters for :math:`c`
and :math:`d`.
This is the PDF corresponding to the twelfth CDF given in Burr's list;
specifically, it is equation (20) in Burr's paper [1]_.
%(after_notes)s
The Burr type 12 distribution is also sometimes referred to as
the Singh-Maddala distribution from NIST [2]_.
References
----------
.. [1] Burr, I. W. "Cumulative frequency functions", Annals of
Mathematical Statistics, 13(2), pp 215-232 (1942).
.. [2] https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/b12pdf.htm
.. [3] "Burr distribution",
https://en.wikipedia.org/wiki/Burr_distribution
%(example)s
"""
def _shape_info(self):
ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
id = _ShapeInfo("d", False, (0, np.inf), (False, False))
return [ic, id]
def _pdf(self, x, c, d):
# burr12.pdf(x, c, d) = c * d * x**(c-1) * (1+x**(c))**(-d-1)
return np.exp(self._logpdf(x, c, d))
def _logpdf(self, x, c, d):
return np.log(c) + np.log(d) + sc.xlogy(c - 1, x) + sc.xlog1py(-d-1, x**c)
def _cdf(self, x, c, d):
return -sc.expm1(self._logsf(x, c, d))
def _logcdf(self, x, c, d):
return sc.log1p(-(1 + x**c)**(-d))
def _sf(self, x, c, d):
return np.exp(self._logsf(x, c, d))
def _logsf(self, x, c, d):
return sc.xlog1py(-d, x**c)
def _ppf(self, q, c, d):
# The following is an implementation of
# ((1 - q)**(-1.0/d) - 1)**(1.0/c)
# that does a better job handling small values of q.
return sc.expm1(-1/d * sc.log1p(-q))**(1/c)
def _isf(self, p, c, d):
return sc.expm1(-1/d * np.log(p))**(1/c)
def _munp(self, n, c, d):
def moment_if_exists(n, c, d):
nc = 1. * n / c
return d * sc.beta(1.0 + nc, d - nc)
return xpx.apply_where(c * d > n, (n, c, d), moment_if_exists,
fill_value=np.nan)
burr12 = burr12_gen(a=0.0, name='burr12')
| burr12_gen |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 12286,
"end": 13912
} | class ____(TestCase):
def test_len(self):
source = TensorDataset(torch.randn(15, 10, 2, 3, 4, 5), torch.randperm(15))
self.assertEqual(len(source), 15)
def test_getitem(self):
t = torch.randn(15, 10, 2, 3, 4, 5)
l = torch.randn(15, 10)
source = TensorDataset(t, l)
for i in range(15):
self.assertEqual(t[i], source[i][0])
self.assertEqual(l[i], source[i][1])
def test_getitem_1d(self):
t = torch.randn(15)
l = torch.randn(15)
source = TensorDataset(t, l)
for i in range(15):
self.assertEqual(t[i], source[i][0])
self.assertEqual(l[i], source[i][1])
def test_single_tensor(self):
t = torch.randn(5, 10)
source = TensorDataset(t)
self.assertEqual(len(source), 5)
for i in range(5):
self.assertEqual(t[i], source[i][0])
def test_many_tensors(self):
t0 = torch.randn(5, 10, 2, 3, 4, 5)
t1 = torch.randn(5, 10)
t2 = torch.randn(5, 10, 2, 5)
t3 = torch.randn(5, 10, 3, 7)
source = TensorDataset(t0, t1, t2, t3)
self.assertEqual(len(source), 5)
for i in range(5):
self.assertEqual(t0[i], source[i][0])
self.assertEqual(t1[i], source[i][1])
self.assertEqual(t2[i], source[i][2])
self.assertEqual(t3[i], source[i][3])
@unittest.skipIf(
TEST_WITH_TSAN,
"Fails with TSAN with the following error: starting new threads after multi-threaded "
"fork is not supported. Dying (set die_after_fork=0 to override)",
)
| TestTensorDataset |
python | streamlit__streamlit | lib/streamlit/web/server/oidc_mixin.py | {
"start": 4092,
"end": 4641
} | class ____(BaseOAuth):
oauth2_client_cls = TornadoOAuth2App
framework_integration_cls = TornadoIntegration
def __init__(
self,
config: dict[str, Any] | None = None,
cache: AuthCache | None = None,
fetch_token: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
update_token: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
):
super().__init__(
cache=cache, fetch_token=fetch_token, update_token=update_token
)
self.config = config
| TornadoOAuth |
python | apache__thrift | test/crossrunner/report.py | {
"start": 7203,
"end": 16880
} | class ____(TestReporter):
def __init__(self, basedir, testdir_relative, concurrent=True):
super(SummaryReporter, self).__init__()
self._basedir = basedir
self._testdir_rel = testdir_relative
self.logdir = os.path.join(self.testdir, LOG_DIR)
self.out_path = os.path.join(self.testdir, RESULT_JSON)
self.concurrent = concurrent
self.out = sys.stdout
self._platform = platform.system()
self._revision = self._get_revision()
self._tests = []
if not os.path.exists(self.logdir):
os.mkdir(self.logdir)
self._known_failures = load_known_failures(self.testdir)
self._unexpected_success = []
self._flaky_success = []
self._unexpected_failure = []
self._expected_failure = []
self._print_header()
def __getstate__(self):
"""Prepare object for pickling - remove unpicklable file handle (Since Python 3.14)"""
state = self.__dict__.copy()
# Remove the unpicklable file handle
state['out'] = None
return state
def __setstate__(self, state):
"""Restore object after unpickling - restore stdout"""
self.__dict__.update(state)
# Restore stdout (since that's what it was initialized to)
self.out = sys.stdout
@property
def testdir(self):
return os.path.join(self._basedir, self._testdir_rel)
def _result_string(self, test):
if test.success:
if test.retry_count == 0:
return 'success'
elif test.retry_count == 1:
return 'flaky(1 retry)'
else:
return 'flaky(%d retries)' % test.retry_count
elif test.expired:
return 'failure(timeout)'
else:
return 'failure(%d)' % test.returncode
def _get_revision(self):
p = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'],
cwd=self.testdir, stdout=subprocess.PIPE)
out, _ = p.communicate()
return out.strip()
def _format_test(self, test, with_result=True):
name = '%s-%s' % (test.server.name, test.client.name)
trans = '%s-%s' % (test.transport, test.socket)
if not with_result:
return '{:24s}{:18s}{:25s}'.format(name[:23], test.protocol[:17], trans[:24])
else:
return '{:24s}{:18s}{:25s}{:s}\n'.format(name[:23], test.protocol[:17],
trans[:24], self._result_string(test))
def _print_test_header(self):
self._print_bar()
print(
'{:24s}{:18s}{:25s}{:s}'.format('server-client:', 'protocol:', 'transport:', 'result:'),
file=self.out)
def _print_header(self):
self._start()
print('Apache Thrift - Integration Test Suite', file=self.out)
self._print_date()
self._print_test_header()
def _print_unexpected_failure(self):
if len(self._unexpected_failure) > 0:
self.out.writelines([
'*** Following %d failures were unexpected ***:\n' % len(self._unexpected_failure),
'If it is introduced by you, please fix it before submitting the code.\n',
# 'If not, please report at https://issues.apache.org/jira/browse/THRIFT\n',
])
self._print_test_header()
for i in self._unexpected_failure:
self.out.write(self._format_test(self._tests[i]))
self._print_bar()
else:
print('No unexpected failures.', file=self.out)
def _print_flaky_success(self):
if len(self._flaky_success) > 0:
print(
'Following %d tests were expected to cleanly succeed but needed retry:' % len(self._flaky_success),
file=self.out)
self._print_test_header()
for i in self._flaky_success:
self.out.write(self._format_test(self._tests[i]))
self._print_bar()
def _print_unexpected_success(self):
if len(self._unexpected_success) > 0:
print(
'Following %d tests were known to fail but succeeded (maybe flaky):' % len(self._unexpected_success),
file=self.out)
self._print_test_header()
for i in self._unexpected_success:
self.out.write(self._format_test(self._tests[i]))
self._print_bar()
def _http_server_command(self, port):
return 'python -m http.server %d' % port
def _print_footer(self):
fail_count = len(self._expected_failure) + len(self._unexpected_failure)
self._print_bar()
self._print_unexpected_success()
self._print_flaky_success()
self._print_unexpected_failure()
self._write_html_data()
self._assemble_log('unexpected failures', self._unexpected_failure)
self._assemble_log('known failures', self._expected_failure)
self.out.writelines([
'You can browse results at:\n',
'\tfile://%s/%s\n' % (self.testdir, RESULT_HTML),
'# If you use Chrome, run:\n',
'# \tcd %s\n#\t%s\n' % (self._basedir, self._http_server_command(8001)),
'# then browse:\n',
'# \thttp://localhost:%d/%s/\n' % (8001, self._testdir_rel),
'Full log for each test is here:\n',
'\ttest/log/server_client_protocol_transport_client.log\n',
'\ttest/log/server_client_protocol_transport_server.log\n',
'%d failed of %d tests in total.\n' % (fail_count, len(self._tests)),
])
self._print_exec_time()
self._print_date()
def _render_result(self, test):
return [
test.server.name,
test.client.name,
test.protocol,
test.transport,
test.socket,
test.success,
test.as_expected,
test.returncode,
{
'server': self.test_logfile(test.name, test.server.kind),
'client': self.test_logfile(test.name, test.client.kind),
},
]
def _write_html_data(self):
"""Writes JSON data to be read by result html"""
results = [self._render_result(r) for r in self._tests]
with logfile_open(self.out_path, 'w+') as fp:
fp.write(json.dumps({
'date': self._format_date(),
'revision': str(self._revision),
'platform': self._platform,
'duration': '{:.1f}'.format(self._elapsed),
'results': results,
}, indent=2))
def _assemble_log(self, title, indexes):
if len(indexes) > 0:
def add_prog_log(fp, test, prog_kind):
print('*************************** %s message ***************************' % prog_kind,
file=fp)
path = self.test_logfile(test.name, prog_kind, self.testdir)
if os.path.exists(path):
with logfile_open(path, 'r') as prog_fp:
print(prog_fp.read(), file=fp)
filename = title.replace(' ', '_') + '.log'
with logfile_open(os.path.join(self.logdir, filename), 'w+') as fp:
for test in map(self._tests.__getitem__, indexes):
fp.write('TEST: [%s]\n' % test.name)
add_prog_log(fp, test, test.server.kind)
add_prog_log(fp, test, test.client.kind)
fp.write('**********************************************************************\n\n')
print('%s are logged to %s/%s/%s' % (title.capitalize(), self._testdir_rel, LOG_DIR, filename))
def end(self):
self._print_footer()
return len(self._unexpected_failure) == 0
def add_test(self, test_dict):
test = TestEntry(self.testdir, **test_dict)
self._lock.acquire()
try:
if not self.concurrent:
self.out.write(self._format_test(test, False))
self.out.flush()
self._tests.append(test)
return len(self._tests) - 1
finally:
self._lock.release()
def add_result(self, index, returncode, expired, retry_count):
self._lock.acquire()
try:
failed = returncode is None or returncode != 0
flaky = not failed and retry_count != 0
test = self._tests[index]
known = test.name in self._known_failures
if failed:
if known:
self._log.debug('%s failed as expected' % test.name)
self._expected_failure.append(index)
else:
self._log.info('unexpected failure: %s' % test.name)
self._unexpected_failure.append(index)
elif flaky and not known:
self._log.info('unexpected flaky success: %s' % test.name)
self._flaky_success.append(index)
elif not flaky and known:
self._log.info('unexpected success: %s' % test.name)
self._unexpected_success.append(index)
test.success = not failed
test.returncode = returncode
test.retry_count = retry_count
test.expired = expired
test.as_expected = known == failed
if not self.concurrent:
self.out.write(self._result_string(test) + '\n')
else:
self.out.write(self._format_test(test))
finally:
self._lock.release()
| SummaryReporter |
python | plotly__plotly.py | plotly/graph_objs/histogram2d/_colorbar.py | {
"start": 233,
"end": 61565
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram2d"
_path_str = "histogram2d.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"minexponent",
"nticks",
"orientation",
"outlinecolor",
"outlinewidth",
"separatethousands",
"showexponent",
"showticklabels",
"showtickprefix",
"showticksuffix",
"thickness",
"thicknessmode",
"tick0",
"tickangle",
"tickcolor",
"tickfont",
"tickformat",
"tickformatstopdefaults",
"tickformatstops",
"ticklabeloverflow",
"ticklabelposition",
"ticklabelstep",
"ticklen",
"tickmode",
"tickprefix",
"ticks",
"ticksuffix",
"ticktext",
"ticktextsrc",
"tickvals",
"tickvalssrc",
"tickwidth",
"title",
"x",
"xanchor",
"xpad",
"xref",
"y",
"yanchor",
"ypad",
"yref",
}
@property
def bgcolor(self):
"""
Sets the color of padded area.
The 'bgcolor' 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["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def bordercolor(self):
"""
Sets the axis line color.
The 'bordercolor' 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["bordercolor"]
@bordercolor.setter
def bordercolor(self, val):
self["bordercolor"] = val
@property
def borderwidth(self):
"""
Sets the width (in px) or the border enclosing this color bar.
The 'borderwidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["borderwidth"]
@borderwidth.setter
def borderwidth(self, val):
self["borderwidth"] = val
@property
def dtick(self):
"""
Sets the step in-between ticks on this axis. Use with `tick0`.
Must be a positive number, or special strings available to
"log" and "date" axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick number. For
example, to set a tick mark at 1, 10, 100, 1000, ... set dtick
to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2.
To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special values;
"L<f>", where `f` is a positive number, gives ticks linearly
spaced in value (but not position). For example `tick0` = 0.1,
`dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To
show powers of 10 plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and
"D2". If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval between
ticks to one day, set `dtick` to 86400000.0. "date" also has
special values "M<n>" gives ticks spaced by a number of months.
`n` must be a positive integer. To set ticks on the 15th of
every third month, set `tick0` to "2000-01-15" and `dtick` to
"M3". To set ticks every 4 years, set `dtick` to "M48"
The 'dtick' property accepts values of any type
Returns
-------
Any
"""
return self["dtick"]
@dtick.setter
def dtick(self, val):
self["dtick"] = val
@property
def exponentformat(self):
"""
Determines a formatting rule for the tick exponents. For
example, consider the number 1,000,000,000. If "none", it
appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If "SI", 1G. If
"B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T
(10^12). *SI extended* covers instead the full SI range from
"quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI
extended* is used and the exponent is beyond the above ranges,
the formatting rule will automatically be switched to the power
notation.
The 'exponentformat' property is an enumeration that may be specified as:
- One of the following enumeration values:
['none', 'e', 'E', 'power', 'SI', 'B', 'SI extended']
Returns
-------
Any
"""
return self["exponentformat"]
@exponentformat.setter
def exponentformat(self, val):
self["exponentformat"] = val
@property
def labelalias(self):
"""
Replacement text for specific tick or hover labels. For example
using {US: 'USA', CA: 'Canada'} changes US to USA and CA to
Canada. The labels we would have shown must match the keys
exactly, after adding any tickprefix or ticksuffix. For
negative numbers the minus sign symbol used (U+2212) is wider
than the regular ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any axis type, and
both keys (if needed) and values (if desired) can include html-
like tags or MathJax.
The 'labelalias' property accepts values of any type
Returns
-------
Any
"""
return self["labelalias"]
@labelalias.setter
def labelalias(self, val):
self["labelalias"] = val
@property
def len(self):
"""
Sets the length of the color bar This measure excludes the
padding of both ends. That is, the color bar length is this
length minus the padding on both ends.
The 'len' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["len"]
@len.setter
def len(self, val):
self["len"] = val
@property
def lenmode(self):
"""
Determines whether this color bar's length (i.e. the measure in
the color variation direction) is set in units of plot
"fraction" or in *pixels. Use `len` to set the value.
The 'lenmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['fraction', 'pixels']
Returns
-------
Any
"""
return self["lenmode"]
@lenmode.setter
def lenmode(self, val):
self["lenmode"] = val
@property
def minexponent(self):
"""
Hide SI prefix for 10^n if |n| is below this number. This only
has an effect when `tickformat` is "SI" or "B".
The 'minexponent' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["minexponent"]
@minexponent.setter
def minexponent(self, val):
self["minexponent"] = val
@property
def nticks(self):
"""
Specifies the maximum number of ticks for the particular axis.
The actual number of ticks will be chosen automatically to be
less than or equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
The 'nticks' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [0, 9223372036854775807]
Returns
-------
int
"""
return self["nticks"]
@nticks.setter
def nticks(self, val):
self["nticks"] = val
@property
def orientation(self):
"""
Sets the orientation of the colorbar.
The 'orientation' property is an enumeration that may be specified as:
- One of the following enumeration values:
['h', 'v']
Returns
-------
Any
"""
return self["orientation"]
@orientation.setter
def orientation(self, val):
self["orientation"] = val
@property
def outlinecolor(self):
"""
Sets the axis line color.
The 'outlinecolor' 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["outlinecolor"]
@outlinecolor.setter
def outlinecolor(self, val):
self["outlinecolor"] = val
@property
def outlinewidth(self):
"""
Sets the width (in px) of the axis line.
The 'outlinewidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["outlinewidth"]
@outlinewidth.setter
def outlinewidth(self, val):
self["outlinewidth"] = val
@property
def separatethousands(self):
"""
If "true", even 4-digit integers are separated
The 'separatethousands' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["separatethousands"]
@separatethousands.setter
def separatethousands(self, val):
self["separatethousands"] = val
@property
def showexponent(self):
"""
If "all", all exponents are shown besides their significands.
If "first", only the exponent of the first tick is shown. If
"last", only the exponent of the last tick is shown. If "none",
no exponents appear.
The 'showexponent' property is an enumeration that may be specified as:
- One of the following enumeration values:
['all', 'first', 'last', 'none']
Returns
-------
Any
"""
return self["showexponent"]
@showexponent.setter
def showexponent(self, val):
self["showexponent"] = val
@property
def showticklabels(self):
"""
Determines whether or not the tick labels are drawn.
The 'showticklabels' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showticklabels"]
@showticklabels.setter
def showticklabels(self, val):
self["showticklabels"] = val
@property
def showtickprefix(self):
"""
If "all", all tick labels are displayed with a prefix. If
"first", only the first tick is displayed with a prefix. If
"last", only the last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
The 'showtickprefix' property is an enumeration that may be specified as:
- One of the following enumeration values:
['all', 'first', 'last', 'none']
Returns
-------
Any
"""
return self["showtickprefix"]
@showtickprefix.setter
def showtickprefix(self, val):
self["showtickprefix"] = val
@property
def showticksuffix(self):
"""
Same as `showtickprefix` but for tick suffixes.
The 'showticksuffix' property is an enumeration that may be specified as:
- One of the following enumeration values:
['all', 'first', 'last', 'none']
Returns
-------
Any
"""
return self["showticksuffix"]
@showticksuffix.setter
def showticksuffix(self, val):
self["showticksuffix"] = val
@property
def thickness(self):
"""
Sets the thickness of the color bar This measure excludes the
size of the padding, ticks and labels.
The 'thickness' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["thickness"]
@thickness.setter
def thickness(self, val):
self["thickness"] = val
@property
def thicknessmode(self):
"""
Determines whether this color bar's thickness (i.e. the measure
in the constant color direction) is set in units of plot
"fraction" or in "pixels". Use `thickness` to set the value.
The 'thicknessmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['fraction', 'pixels']
Returns
-------
Any
"""
return self["thicknessmode"]
@thicknessmode.setter
def thicknessmode(self, val):
self["thicknessmode"] = val
@property
def tick0(self):
"""
Sets the placement of the first tick on this axis. Use with
`dtick`. If the axis `type` is "log", then you must take the
log of your starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when `dtick`=*L<f>* (see
`dtick` for more info). If the axis `type` is "date", it should
be a date string, like date data. If the axis `type` is
"category", it should be a number, using the scale where each
category is assigned a serial number from zero in the order it
appears.
The 'tick0' property accepts values of any type
Returns
-------
Any
"""
return self["tick0"]
@tick0.setter
def tick0(self, val):
self["tick0"] = val
@property
def tickangle(self):
"""
Sets the angle of the tick labels with respect to the
horizontal. For example, a `tickangle` of -90 draws the tick
labels vertically.
The 'tickangle' property is a angle (in degrees) that may be
specified as a number between -180 and 180.
Numeric values outside this range are converted to the equivalent value
(e.g. 270 is converted to -90).
Returns
-------
int|float
"""
return self["tickangle"]
@tickangle.setter
def tickangle(self, val):
self["tickangle"] = val
@property
def tickcolor(self):
"""
Sets the tick color.
The 'tickcolor' 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["tickcolor"]
@tickcolor.setter
def tickcolor(self, val):
self["tickcolor"] = val
@property
def tickfont(self):
"""
Sets the color bar's tick label font
The 'tickfont' property is an instance of Tickfont
that may be specified as:
- An instance of :class:`plotly.graph_objs.histogram2d.colorbar.Tickfont`
- A dict of string/value properties that will be passed
to the Tickfont constructor
Returns
-------
plotly.graph_objs.histogram2d.colorbar.Tickfont
"""
return self["tickfont"]
@tickfont.setter
def tickfont(self, val):
self["tickfont"] = val
@property
def tickformat(self):
"""
Sets the tick label formatting rule 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"
The 'tickformat' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["tickformat"]
@tickformat.setter
def tickformat(self, val):
self["tickformat"] = val
@property
def tickformatstops(self):
"""
The 'tickformatstops' property is a tuple of instances of
Tickformatstop that may be specified as:
- A list or tuple of instances of plotly.graph_objs.histogram2d.colorbar.Tickformatstop
- A list or tuple of dicts of string/value properties that
will be passed to the Tickformatstop constructor
Returns
-------
tuple[plotly.graph_objs.histogram2d.colorbar.Tickformatstop]
"""
return self["tickformatstops"]
@tickformatstops.setter
def tickformatstops(self, val):
self["tickformatstops"] = val
@property
def tickformatstopdefaults(self):
"""
When used in a template (as layout.template.data.histogram2d.co
lorbar.tickformatstopdefaults), sets the default property
values to use for elements of
histogram2d.colorbar.tickformatstops
The 'tickformatstopdefaults' property is an instance of Tickformatstop
that may be specified as:
- An instance of :class:`plotly.graph_objs.histogram2d.colorbar.Tickformatstop`
- A dict of string/value properties that will be passed
to the Tickformatstop constructor
Returns
-------
plotly.graph_objs.histogram2d.colorbar.Tickformatstop
"""
return self["tickformatstopdefaults"]
@tickformatstopdefaults.setter
def tickformatstopdefaults(self, val):
self["tickformatstopdefaults"] = val
@property
def ticklabeloverflow(self):
"""
Determines how we handle tick labels that would overflow either
the graph div or the domain of the axis. The default value for
inside tick labels is *hide past domain*. In other cases the
default is *hide past div*.
The 'ticklabeloverflow' property is an enumeration that may be specified as:
- One of the following enumeration values:
['allow', 'hide past div', 'hide past domain']
Returns
-------
Any
"""
return self["ticklabeloverflow"]
@ticklabeloverflow.setter
def ticklabeloverflow(self, val):
self["ticklabeloverflow"] = val
@property
def ticklabelposition(self):
"""
Determines where tick labels are drawn relative to the ticks.
Left and right options are used when `orientation` is "h", top
and bottom when `orientation` is "v".
The 'ticklabelposition' property is an enumeration that may be specified as:
- One of the following enumeration values:
['outside', 'inside', 'outside top', 'inside top',
'outside left', 'inside left', 'outside right', 'inside
right', 'outside bottom', 'inside bottom']
Returns
-------
Any
"""
return self["ticklabelposition"]
@ticklabelposition.setter
def ticklabelposition(self, val):
self["ticklabelposition"] = val
@property
def ticklabelstep(self):
"""
Sets the spacing between tick labels as compared to the spacing
between ticks. A value of 1 (default) means each tick gets a
label. A value of 2 means shows every 2nd label. A larger value
n means only every nth tick is labeled. `tick0` determines
which labels are shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is "array".
The 'ticklabelstep' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 9223372036854775807]
Returns
-------
int
"""
return self["ticklabelstep"]
@ticklabelstep.setter
def ticklabelstep(self, val):
self["ticklabelstep"] = val
@property
def ticklen(self):
"""
Sets the tick length (in px).
The 'ticklen' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["ticklen"]
@ticklen.setter
def ticklen(self, val):
self["ticklen"] = val
@property
def tickmode(self):
"""
Sets the tick mode for this axis. If "auto", the number of
ticks is set via `nticks`. If "linear", the placement of the
ticks is determined by a starting position `tick0` and a tick
step `dtick` ("linear" is the default value if `tick0` and
`dtick` are provided). If "array", the placement of the ticks
is set via `tickvals` and the tick text is `ticktext`. ("array"
is the default value if `tickvals` is provided).
The 'tickmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['auto', 'linear', 'array']
Returns
-------
Any
"""
return self["tickmode"]
@tickmode.setter
def tickmode(self, val):
self["tickmode"] = val
@property
def tickprefix(self):
"""
Sets a tick label prefix.
The 'tickprefix' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["tickprefix"]
@tickprefix.setter
def tickprefix(self, val):
self["tickprefix"] = val
@property
def ticks(self):
"""
Determines whether ticks are drawn or not. If "", this axis'
ticks are not drawn. If "outside" ("inside"), this axis' are
drawn outside (inside) the axis lines.
The 'ticks' property is an enumeration that may be specified as:
- One of the following enumeration values:
['outside', 'inside', '']
Returns
-------
Any
"""
return self["ticks"]
@ticks.setter
def ticks(self, val):
self["ticks"] = val
@property
def ticksuffix(self):
"""
Sets a tick label suffix.
The 'ticksuffix' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["ticksuffix"]
@ticksuffix.setter
def ticksuffix(self, val):
self["ticksuffix"] = val
@property
def ticktext(self):
"""
Sets the text displayed at the ticks position via `tickvals`.
Only has an effect if `tickmode` is set to "array". Used with
`tickvals`.
The 'ticktext' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["ticktext"]
@ticktext.setter
def ticktext(self, val):
self["ticktext"] = val
@property
def ticktextsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `ticktext`.
The 'ticktextsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["ticktextsrc"]
@ticktextsrc.setter
def ticktextsrc(self, val):
self["ticktextsrc"] = val
@property
def tickvals(self):
"""
Sets the values at which ticks on this axis appear. Only has an
effect if `tickmode` is set to "array". Used with `ticktext`.
The 'tickvals' property is an array that may be specified as a tuple,
list, numpy array, or pandas Series
Returns
-------
numpy.ndarray
"""
return self["tickvals"]
@tickvals.setter
def tickvals(self, val):
self["tickvals"] = val
@property
def tickvalssrc(self):
"""
Sets the source reference on Chart Studio Cloud for `tickvals`.
The 'tickvalssrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["tickvalssrc"]
@tickvalssrc.setter
def tickvalssrc(self, val):
self["tickvalssrc"] = val
@property
def tickwidth(self):
"""
Sets the tick width (in px).
The 'tickwidth' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["tickwidth"]
@tickwidth.setter
def tickwidth(self, val):
self["tickwidth"] = val
@property
def title(self):
"""
The 'title' property is an instance of Title
that may be specified as:
- An instance of :class:`plotly.graph_objs.histogram2d.colorbar.Title`
- A dict of string/value properties that will be passed
to the Title constructor
Returns
-------
plotly.graph_objs.histogram2d.colorbar.Title
"""
return self["title"]
@title.setter
def title(self, val):
self["title"] = val
@property
def x(self):
"""
Sets the x position with respect to `xref` of the color bar (in
plot fraction). When `xref` is "paper", defaults to 1.02 when
`orientation` is "v" and 0.5 when `orientation` is "h". When
`xref` is "container", defaults to 1 when `orientation` is "v"
and 0.5 when `orientation` is "h". Must be between 0 and 1 if
`xref` is "container" and between "-2" and 3 if `xref` is
"paper".
The 'x' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["x"]
@x.setter
def x(self, val):
self["x"] = val
@property
def xanchor(self):
"""
Sets this color bar's horizontal position anchor. This anchor
binds the `x` position to the "left", "center" or "right" of
the color bar. Defaults to "left" when `orientation` is "v" and
"center" when `orientation` is "h".
The 'xanchor' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'center', 'right']
Returns
-------
Any
"""
return self["xanchor"]
@xanchor.setter
def xanchor(self, val):
self["xanchor"] = val
@property
def xpad(self):
"""
Sets the amount of padding (in px) along the x direction.
The 'xpad' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["xpad"]
@xpad.setter
def xpad(self, val):
self["xpad"] = val
@property
def xref(self):
"""
Sets the container `x` refers to. "container" spans the entire
`width` of the plot. "paper" refers to the width of the
plotting area only.
The 'xref' property is an enumeration that may be specified as:
- One of the following enumeration values:
['container', 'paper']
Returns
-------
Any
"""
return self["xref"]
@xref.setter
def xref(self, val):
self["xref"] = val
@property
def y(self):
"""
Sets the y position with respect to `yref` of the color bar (in
plot fraction). When `yref` is "paper", defaults to 0.5 when
`orientation` is "v" and 1.02 when `orientation` is "h". When
`yref` is "container", defaults to 0.5 when `orientation` is
"v" and 1 when `orientation` is "h". Must be between 0 and 1 if
`yref` is "container" and between "-2" and 3 if `yref` is
"paper".
The 'y' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["y"]
@y.setter
def y(self, val):
self["y"] = val
@property
def yanchor(self):
"""
Sets this color bar's vertical position anchor This anchor
binds the `y` position to the "top", "middle" or "bottom" of
the color bar. Defaults to "middle" when `orientation` is "v"
and "bottom" when `orientation` is "h".
The 'yanchor' property is an enumeration that may be specified as:
- One of the following enumeration values:
['top', 'middle', 'bottom']
Returns
-------
Any
"""
return self["yanchor"]
@yanchor.setter
def yanchor(self, val):
self["yanchor"] = val
@property
def ypad(self):
"""
Sets the amount of padding (in px) along the y direction.
The 'ypad' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["ypad"]
@ypad.setter
def ypad(self, val):
self["ypad"] = val
@property
def yref(self):
"""
Sets the container `y` refers to. "container" spans the entire
`height` of the plot. "paper" refers to the height of the
plotting area only.
The 'yref' property is an enumeration that may be specified as:
- One of the following enumeration values:
['container', 'paper']
Returns
-------
Any
"""
return self["yref"]
@yref.setter
def yref(self, val):
self["yref"] = val
@property
def _prop_descriptions(self):
return """\
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing this
color bar.
dtick
Sets the step in-between ticks on this axis. Use with
`tick0`. Must be a positive number, or special strings
available to "log" and "date" axes. If the axis `type`
is "log", then ticks are set every 10^(n*dtick) where n
is the tick number. For example, to set a tick mark at
1, 10, 100, 1000, ... set dtick to 1. To set tick marks
at 1, 100, 10000, ... set dtick to 2. To set tick marks
at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special
values; "L<f>", where `f` is a positive number, gives
ticks linearly spaced in value (but not position). For
example `tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus
small digits between, use "D1" (all digits) or "D2"
(only 2 and 5). `tick0` is ignored for "D1" and "D2".
If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to 86400000.0.
"date" also has special values "M<n>" gives ticks
spaced by a number of months. `n` must be a positive
integer. To set ticks on the 15th of every third month,
set `tick0` to "2000-01-15" and `dtick` to "M3". To set
ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick exponents.
For example, consider the number 1,000,000,000. If
"none", it appears as 1,000,000,000. If "e", 1e+9. If
"E", 1E+9. If "power", 1x10^9 (with 9 in a super
script). If "SI", 1G. If "B", 1B. "SI" uses prefixes
from "femto" f (10^-15) to "tera" T (10^12). *SI
extended* covers instead the full SI range from
"quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or
*SI extended* is used and the exponent is beyond the
above ranges, the formatting rule will automatically be
switched to the power notation.
labelalias
Replacement text for specific tick or hover labels. For
example using {US: 'USA', CA: 'Canada'} changes US to
USA and CA to Canada. The labels we would have shown
must match the keys exactly, after adding any
tickprefix or ticksuffix. For negative numbers the
minus sign symbol used (U+2212) is wider than the
regular ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any axis
type, and both keys (if needed) and values (if desired)
can include html-like tags or MathJax.
len
Sets the length of the color bar This measure excludes
the padding of both ends. That is, the color bar length
is this length minus the padding on both ends.
lenmode
Determines whether this color bar's length (i.e. the
measure in the color variation direction) is set in
units of plot "fraction" or in *pixels. Use `len` to
set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this number.
This only has an effect when `tickformat` is "SI" or
"B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks will be
chosen automatically to be less than or equal to
`nticks`. Has an effect only if `tickmode` is set to
"auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of the
first tick is shown. If "last", only the exponent of
the last tick is shown. If "none", no exponents appear.
showticklabels
Determines whether or not the tick labels are drawn.
showtickprefix
If "all", all tick labels are displayed with a prefix.
If "first", only the first tick is displayed with a
prefix. If "last", only the last tick is displayed with
a suffix. If "none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This measure
excludes the size of the padding, ticks and labels.
thicknessmode
Determines whether this color bar's thickness (i.e. the
measure in the constant color direction) is set in
units of plot "fraction" or in "pixels". Use
`thickness` to set the value.
tick0
Sets the placement of the first tick on this axis. Use
with `dtick`. If the axis `type` is "log", then you
must take the log of your starting tick (e.g. to set
the starting tick to 100, set the `tick0` to 2) except
when `dtick`=*L<f>* (see `dtick` for more info). If the
axis `type` is "date", it should be a date string, like
date data. If the axis `type` is "category", it should
be a number, using the scale where each category is
assigned a serial number from zero in the order it
appears.
tickangle
Sets the angle of the tick labels with respect to the
horizontal. For example, a `tickangle` of -90 draws the
tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule 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"
tickformatstops
A tuple of :class:`plotly.graph_objects.histogram2d.col
orbar.Tickformatstop` instances or dicts with
compatible properties
tickformatstopdefaults
When used in a template (as layout.template.data.histog
ram2d.colorbar.tickformatstopdefaults), sets the
default property values to use for elements of
histogram2d.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of the
axis. The default value for inside tick labels is *hide
past domain*. In other cases the default is *hide past
div*.
ticklabelposition
Determines where tick labels are drawn relative to the
ticks. Left and right options are used when
`orientation` is "h", top and bottom when `orientation`
is "v".
ticklabelstep
Sets the spacing between tick labels as compared to the
spacing between ticks. A value of 1 (default) means
each tick gets a label. A value of 2 means shows every
2nd label. A larger value n means only every nth tick
is labeled. `tick0` determines which labels are shown.
Not implemented for axes with `type` "log" or
"multicategory", or when `tickmode` is "array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto", the number
of ticks is set via `nticks`. If "linear", the
placement of the ticks is determined by a starting
position `tick0` and a tick step `dtick` ("linear" is
the default value if `tick0` and `dtick` are provided).
If "array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`. ("array" is
the default value if `tickvals` is provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If "", this
axis' ticks are not drawn. If "outside" ("inside"),
this axis' are drawn outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position via
`tickvals`. Only has an effect if `tickmode` is set to
"array". Used with `tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud for
`ticktext`.
tickvals
Sets the values at which ticks on this axis appear.
Only has an effect if `tickmode` is set to "array".
Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.histogram2d.colorbar.Title
` instance or dict with compatible properties
x
Sets the x position with respect to `xref` of the color
bar (in plot fraction). When `xref` is "paper",
defaults to 1.02 when `orientation` is "v" and 0.5 when
`orientation` is "h". When `xref` is "container",
defaults to 1 when `orientation` is "v" and 0.5 when
`orientation` is "h". Must be between 0 and 1 if `xref`
is "container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the color bar. Defaults to "left" when
`orientation` is "v" and "center" when `orientation` is
"h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container" spans the
entire `width` of the plot. "paper" refers to the width
of the plotting area only.
y
Sets the y position with respect to `yref` of the color
bar (in plot fraction). When `yref` is "paper",
defaults to 0.5 when `orientation` is "v" and 1.02 when
`orientation` is "h". When `yref` is "container",
defaults to 0.5 when `orientation` is "v" and 1 when
`orientation` is "h". Must be between 0 and 1 if `yref`
is "container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor This
anchor binds the `y` position to the "top", "middle" or
"bottom" of the color bar. Defaults to "middle" when
`orientation` is "v" and "bottom" when `orientation` is
"h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container" spans the
entire `height` of the plot. "paper" refers to the
height of the plotting area only.
"""
def __init__(
self,
arg=None,
bgcolor=None,
bordercolor=None,
borderwidth=None,
dtick=None,
exponentformat=None,
labelalias=None,
len=None,
lenmode=None,
minexponent=None,
nticks=None,
orientation=None,
outlinecolor=None,
outlinewidth=None,
separatethousands=None,
showexponent=None,
showticklabels=None,
showtickprefix=None,
showticksuffix=None,
thickness=None,
thicknessmode=None,
tick0=None,
tickangle=None,
tickcolor=None,
tickfont=None,
tickformat=None,
tickformatstops=None,
tickformatstopdefaults=None,
ticklabeloverflow=None,
ticklabelposition=None,
ticklabelstep=None,
ticklen=None,
tickmode=None,
tickprefix=None,
ticks=None,
ticksuffix=None,
ticktext=None,
ticktextsrc=None,
tickvals=None,
tickvalssrc=None,
tickwidth=None,
title=None,
x=None,
xanchor=None,
xpad=None,
xref=None,
y=None,
yanchor=None,
ypad=None,
yref=None,
**kwargs,
):
"""
Construct a new ColorBar object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.histogram2d.ColorBar`
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing this
color bar.
dtick
Sets the step in-between ticks on this axis. Use with
`tick0`. Must be a positive number, or special strings
available to "log" and "date" axes. If the axis `type`
is "log", then ticks are set every 10^(n*dtick) where n
is the tick number. For example, to set a tick mark at
1, 10, 100, 1000, ... set dtick to 1. To set tick marks
at 1, 100, 10000, ... set dtick to 2. To set tick marks
at 1, 5, 25, 125, 625, 3125, ... set dtick to
log_10(5), or 0.69897000433. "log" has several special
values; "L<f>", where `f` is a positive number, gives
ticks linearly spaced in value (but not position). For
example `tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus
small digits between, use "D1" (all digits) or "D2"
(only 2 and 5). `tick0` is ignored for "D1" and "D2".
If the axis `type` is "date", then you must convert the
time to milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to 86400000.0.
"date" also has special values "M<n>" gives ticks
spaced by a number of months. `n` must be a positive
integer. To set ticks on the 15th of every third month,
set `tick0` to "2000-01-15" and `dtick` to "M3". To set
ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick exponents.
For example, consider the number 1,000,000,000. If
"none", it appears as 1,000,000,000. If "e", 1e+9. If
"E", 1E+9. If "power", 1x10^9 (with 9 in a super
script). If "SI", 1G. If "B", 1B. "SI" uses prefixes
from "femto" f (10^-15) to "tera" T (10^12). *SI
extended* covers instead the full SI range from
"quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or
*SI extended* is used and the exponent is beyond the
above ranges, the formatting rule will automatically be
switched to the power notation.
labelalias
Replacement text for specific tick or hover labels. For
example using {US: 'USA', CA: 'Canada'} changes US to
USA and CA to Canada. The labels we would have shown
must match the keys exactly, after adding any
tickprefix or ticksuffix. For negative numbers the
minus sign symbol used (U+2212) is wider than the
regular ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any axis
type, and both keys (if needed) and values (if desired)
can include html-like tags or MathJax.
len
Sets the length of the color bar This measure excludes
the padding of both ends. That is, the color bar length
is this length minus the padding on both ends.
lenmode
Determines whether this color bar's length (i.e. the
measure in the color variation direction) is set in
units of plot "fraction" or in *pixels. Use `len` to
set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this number.
This only has an effect when `tickformat` is "SI" or
"B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks will be
chosen automatically to be less than or equal to
`nticks`. Has an effect only if `tickmode` is set to
"auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of the
first tick is shown. If "last", only the exponent of
the last tick is shown. If "none", no exponents appear.
showticklabels
Determines whether or not the tick labels are drawn.
showtickprefix
If "all", all tick labels are displayed with a prefix.
If "first", only the first tick is displayed with a
prefix. If "last", only the last tick is displayed with
a suffix. If "none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This measure
excludes the size of the padding, ticks and labels.
thicknessmode
Determines whether this color bar's thickness (i.e. the
measure in the constant color direction) is set in
units of plot "fraction" or in "pixels". Use
`thickness` to set the value.
tick0
Sets the placement of the first tick on this axis. Use
with `dtick`. If the axis `type` is "log", then you
must take the log of your starting tick (e.g. to set
the starting tick to 100, set the `tick0` to 2) except
when `dtick`=*L<f>* (see `dtick` for more info). If the
axis `type` is "date", it should be a date string, like
date data. If the axis `type` is "category", it should
be a number, using the scale where each category is
assigned a serial number from zero in the order it
appears.
tickangle
Sets the angle of the tick labels with respect to the
horizontal. For example, a `tickangle` of -90 draws the
tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule 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"
tickformatstops
A tuple of :class:`plotly.graph_objects.histogram2d.col
orbar.Tickformatstop` instances or dicts with
compatible properties
tickformatstopdefaults
When used in a template (as layout.template.data.histog
ram2d.colorbar.tickformatstopdefaults), sets the
default property values to use for elements of
histogram2d.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of the
axis. The default value for inside tick labels is *hide
past domain*. In other cases the default is *hide past
div*.
ticklabelposition
Determines where tick labels are drawn relative to the
ticks. Left and right options are used when
`orientation` is "h", top and bottom when `orientation`
is "v".
ticklabelstep
Sets the spacing between tick labels as compared to the
spacing between ticks. A value of 1 (default) means
each tick gets a label. A value of 2 means shows every
2nd label. A larger value n means only every nth tick
is labeled. `tick0` determines which labels are shown.
Not implemented for axes with `type` "log" or
"multicategory", or when `tickmode` is "array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto", the number
of ticks is set via `nticks`. If "linear", the
placement of the ticks is determined by a starting
position `tick0` and a tick step `dtick` ("linear" is
the default value if `tick0` and `dtick` are provided).
If "array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`. ("array" is
the default value if `tickvals` is provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If "", this
axis' ticks are not drawn. If "outside" ("inside"),
this axis' are drawn outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position via
`tickvals`. Only has an effect if `tickmode` is set to
"array". Used with `tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud for
`ticktext`.
tickvals
Sets the values at which ticks on this axis appear.
Only has an effect if `tickmode` is set to "array".
Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.histogram2d.colorbar.Title
` instance or dict with compatible properties
x
Sets the x position with respect to `xref` of the color
bar (in plot fraction). When `xref` is "paper",
defaults to 1.02 when `orientation` is "v" and 0.5 when
`orientation` is "h". When `xref` is "container",
defaults to 1 when `orientation` is "v" and 0.5 when
`orientation` is "h". Must be between 0 and 1 if `xref`
is "container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the color bar. Defaults to "left" when
`orientation` is "v" and "center" when `orientation` is
"h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container" spans the
entire `width` of the plot. "paper" refers to the width
of the plotting area only.
y
Sets the y position with respect to `yref` of the color
bar (in plot fraction). When `yref` is "paper",
defaults to 0.5 when `orientation` is "v" and 1.02 when
`orientation` is "h". When `yref` is "container",
defaults to 0.5 when `orientation` is "v" and 1 when
`orientation` is "h". Must be between 0 and 1 if `yref`
is "container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor This
anchor binds the `y` position to the "top", "middle" or
"bottom" of the color bar. Defaults to "middle" when
`orientation` is "v" and "bottom" when `orientation` is
"h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container" spans the
entire `height` of the plot. "paper" refers to the
height of the plotting area only.
Returns
-------
ColorBar
"""
super().__init__("colorbar")
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.histogram2d.ColorBar
constructor must be a dict or
an instance of :class:`plotly.graph_objs.histogram2d.ColorBar`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("bordercolor", arg, bordercolor)
self._set_property("borderwidth", arg, borderwidth)
self._set_property("dtick", arg, dtick)
self._set_property("exponentformat", arg, exponentformat)
self._set_property("labelalias", arg, labelalias)
self._set_property("len", arg, len)
self._set_property("lenmode", arg, lenmode)
self._set_property("minexponent", arg, minexponent)
self._set_property("nticks", arg, nticks)
self._set_property("orientation", arg, orientation)
self._set_property("outlinecolor", arg, outlinecolor)
self._set_property("outlinewidth", arg, outlinewidth)
self._set_property("separatethousands", arg, separatethousands)
self._set_property("showexponent", arg, showexponent)
self._set_property("showticklabels", arg, showticklabels)
self._set_property("showtickprefix", arg, showtickprefix)
self._set_property("showticksuffix", arg, showticksuffix)
self._set_property("thickness", arg, thickness)
self._set_property("thicknessmode", arg, thicknessmode)
self._set_property("tick0", arg, tick0)
self._set_property("tickangle", arg, tickangle)
self._set_property("tickcolor", arg, tickcolor)
self._set_property("tickfont", arg, tickfont)
self._set_property("tickformat", arg, tickformat)
self._set_property("tickformatstops", arg, tickformatstops)
self._set_property("tickformatstopdefaults", arg, tickformatstopdefaults)
self._set_property("ticklabeloverflow", arg, ticklabeloverflow)
self._set_property("ticklabelposition", arg, ticklabelposition)
self._set_property("ticklabelstep", arg, ticklabelstep)
self._set_property("ticklen", arg, ticklen)
self._set_property("tickmode", arg, tickmode)
self._set_property("tickprefix", arg, tickprefix)
self._set_property("ticks", arg, ticks)
self._set_property("ticksuffix", arg, ticksuffix)
self._set_property("ticktext", arg, ticktext)
self._set_property("ticktextsrc", arg, ticktextsrc)
self._set_property("tickvals", arg, tickvals)
self._set_property("tickvalssrc", arg, tickvalssrc)
self._set_property("tickwidth", arg, tickwidth)
self._set_property("title", arg, title)
self._set_property("x", arg, x)
self._set_property("xanchor", arg, xanchor)
self._set_property("xpad", arg, xpad)
self._set_property("xref", arg, xref)
self._set_property("y", arg, y)
self._set_property("yanchor", arg, yanchor)
self._set_property("ypad", arg, ypad)
self._set_property("yref", arg, yref)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| ColorBar |
python | django__django | tests/fixtures_regress/models.py | {
"start": 5516,
"end": 5721
} | class ____(models.Model):
name = models.CharField(max_length=255, unique=True)
def natural_key(self):
return (self.name,)
natural_key.dependencies = ["fixtures_regress.circle6"]
| Circle5 |
python | automl__auto-sklearn | autosklearn/experimental/selector.py | {
"start": 129,
"end": 1014
} | class ____:
def fit(
self,
X: pd.DataFrame,
y: pd.DataFrame,
minima: typing.Dict[int, typing.Dict[str, float]],
maxima: typing.Dict[int, typing.Dict[str, float]],
) -> None:
raise NotImplementedError()
def predict(
self, X: pd.DataFrame, y: typing.Optional[pd.DataFrame] = None
) -> pd.DataFrame:
prediction = self._predict(X, y)
for col, series in prediction.iteritems():
assert series.dtype == float, (col, series)
np.testing.assert_array_almost_equal(
prediction.sum(axis="columns").to_numpy(),
np.ones(X.shape[0]),
err_msg=prediction.to_csv(),
)
return prediction
def _predict(
self, X: pd.DataFrame, y: typing.Optional[pd.DataFrame]
) -> pd.DataFrame:
raise NotImplementedError()
| AbstractSelector |
python | numpy__numpy | numpy/_core/tests/test_deprecations.py | {
"start": 4909,
"end": 5026
} | class ____(_DeprecationTestCase):
warning_cls = np.exceptions.VisibleDeprecationWarning
| _VisibleDeprecationTestCase |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/relationship.py | {
"start": 1915,
"end": 2486
} | class ____(Base):
__tablename__ = "address"
id = mapped_column(Integer, primary_key=True)
user_id = mapped_column(ForeignKey("user.id"))
email: Mapped[str]
email_name: Mapped[str] = mapped_column("email_name")
user_style_one: Mapped[User] = relationship()
user_style_two: Mapped["User"] = relationship()
rel_style_one: Relationship[List["MoreMail"]] = relationship()
# everything works even if using Relationship instead of Mapped
# users should use Mapped though
rel_style_one_anno_only: Relationship[Set["MoreMail"]]
| Address |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 32220,
"end": 33778
} | class ____(WrapperLine):
"""
Given a MultiOutputLayout buffer, indexes actual buffer(s) from the result.
"""
wrapper: PythonWrapperCodegen
result_name: str
arg_name: str
indices: Sequence[Any]
def codegen(self, code: IndentedBuffer) -> None:
def codegen_list_tuple_access(basename, indices): # type: ignore[no-untyped-def]
if len(indices) > 0:
itype, i = indices[0]
if issubclass(itype, list):
return codegen_list_tuple_access(f"{basename}[{i}]", indices[1:])
elif issubclass(itype, tuple):
# cpp wrapper code needs to use std::get<> to access a tuple
tuple_access = self.wrapper.codegen_tuple_access(
basename, self.result_name, str(i)
)
return codegen_list_tuple_access(tuple_access, indices[1:])
elif issubclass(itype, dict):
return codegen_list_tuple_access(f"{basename}['{i}']", indices[1:])
else:
raise AssertionError("non supported index type: ", itype)
else:
return basename
value = codegen_list_tuple_access(self.arg_name, self.indices)
code.writeline(
f"{self.wrapper.declare}{self.result_name} = {value}{self.wrapper.ending}"
)
def codegen_fx(self, converter: FxConverter) -> FxConversionFunc:
return converter._generate_multi_output
@dataclasses.dataclass
| MultiOutputLine |
python | Netflix__metaflow | metaflow/plugins/airflow/exception.py | {
"start": 191,
"end": 287
} | class ____(MetaflowException):
headline = "Not yet supported with Airflow"
| NotSupportedException |
python | PyCQA__flake8 | src/flake8/api/legacy.py | {
"start": 1858,
"end": 6900
} | class ____:
"""Public facing object that mimic's Flake8 2.0's StyleGuide.
.. note::
There are important changes in how this object behaves compared to
the StyleGuide object provided in Flake8 2.x.
.. warning::
This object should not be instantiated directly by users.
.. versionchanged:: 3.0.0
"""
def __init__(self, application: app.Application) -> None:
"""Initialize our StyleGuide."""
self._application = application
self._file_checker_manager = application.file_checker_manager
@property
def options(self) -> argparse.Namespace:
"""Return application's options.
An instance of :class:`argparse.Namespace` containing parsed options.
"""
assert self._application.options is not None
return self._application.options
@property
def paths(self) -> list[str]:
"""Return the extra arguments passed as paths."""
assert self._application.options is not None
return self._application.options.filenames
def check_files(self, paths: list[str] | None = None) -> Report:
"""Run collected checks on the files provided.
This will check the files passed in and return a :class:`Report`
instance.
:param paths:
List of filenames (or paths) to check.
:returns:
Object that mimic's Flake8 2.0's Reporter class.
"""
assert self._application.options is not None
self._application.options.filenames = paths
self._application.run_checks()
self._application.report_errors()
return Report(self._application)
def excluded(self, filename: str, parent: str | None = None) -> bool:
"""Determine if a file is excluded.
:param filename:
Path to the file to check if it is excluded.
:param parent:
Name of the parent directory containing the file.
:returns:
True if the filename is excluded, False otherwise.
"""
def excluded(path: str) -> bool:
paths = tuple(
expand_paths(
paths=[path],
stdin_display_name=self.options.stdin_display_name,
filename_patterns=self.options.filename,
exclude=self.options.exclude,
),
)
return not paths
return excluded(filename) or (
parent is not None and excluded(os.path.join(parent, filename))
)
def init_report(
self,
reporter: type[formatter.BaseFormatter] | None = None,
) -> None:
"""Set up a formatter for this run of Flake8."""
if reporter is None:
return
if not issubclass(reporter, formatter.BaseFormatter):
raise ValueError(
"Report should be subclass of "
"flake8.formatter.BaseFormatter.",
)
self._application.formatter = reporter(self.options)
self._application.guide = None
# NOTE(sigmavirus24): This isn't the intended use of
# Application#make_guide but it works pretty well.
# Stop cringing... I know it's gross.
self._application.make_guide()
self._application.file_checker_manager = None
self._application.make_file_checker_manager([])
def input_file(
self,
filename: str,
lines: Any | None = None,
expected: Any | None = None,
line_offset: Any | None = 0,
) -> Report:
"""Run collected checks on a single file.
This will check the file passed in and return a :class:`Report`
instance.
:param filename:
The path to the file to check.
:param lines:
Ignored since Flake8 3.0.
:param expected:
Ignored since Flake8 3.0.
:param line_offset:
Ignored since Flake8 3.0.
:returns:
Object that mimic's Flake8 2.0's Reporter class.
"""
return self.check_files([filename])
def get_style_guide(**kwargs: Any) -> StyleGuide:
r"""Provision a StyleGuide for use.
:param \*\*kwargs:
Keyword arguments that provide some options for the StyleGuide.
:returns:
An initialized StyleGuide
"""
application = app.Application()
application.plugins, application.options = parse_args([])
# We basically want application.initialize to be called but with these
# options set instead before we make our formatter, notifier, internal
# style guide and file checker manager.
options = application.options
for key, value in kwargs.items():
try:
getattr(options, key)
setattr(options, key, value)
except AttributeError:
LOG.error('Could not update option "%s"', key)
application.make_formatter()
application.make_guide()
application.make_file_checker_manager([])
return StyleGuide(application)
| StyleGuide |
python | pypa__pip | src/pip/_vendor/rich/prompt.py | {
"start": 10414,
"end": 12447
} | class ____(PromptBase[bool]):
"""A yes / no confirmation prompt.
Example:
>>> if Confirm.ask("Continue"):
run_job()
"""
response_type = bool
validate_error_message = "[prompt.invalid]Please enter Y or N"
choices: List[str] = ["y", "n"]
def render_default(self, default: DefaultType) -> Text:
"""Render the default as (y) or (n) rather than True/False."""
yes, no = self.choices
return Text(f"({yes})" if default else f"({no})", style="prompt.default")
def process_response(self, value: str) -> bool:
"""Convert choices to a bool."""
value = value.strip().lower()
if value not in self.choices:
raise InvalidResponse(self.validate_error_message)
return value == self.choices[0]
if __name__ == "__main__": # pragma: no cover
from pip._vendor.rich import print
if Confirm.ask("Run [i]prompt[/i] tests?", default=True):
while True:
result = IntPrompt.ask(
":rocket: Enter a number between [b]1[/b] and [b]10[/b]", default=5
)
if result >= 1 and result <= 10:
break
print(":pile_of_poo: [prompt.invalid]Number must be between 1 and 10")
print(f"number={result}")
while True:
password = Prompt.ask(
"Please enter a password [cyan](must be at least 5 characters)",
password=True,
)
if len(password) >= 5:
break
print("[prompt.invalid]password too short")
print(f"password={password!r}")
fruit = Prompt.ask("Enter a fruit", choices=["apple", "orange", "pear"])
print(f"fruit={fruit!r}")
doggie = Prompt.ask(
"What's the best Dog? (Case INSENSITIVE)",
choices=["Border Terrier", "Collie", "Labradoodle"],
case_sensitive=False,
)
print(f"doggie={doggie!r}")
else:
print("[b]OK :loudly_crying_face:")
| Confirm |
python | tensorflow__tensorflow | tensorflow/python/training/saver.py | {
"start": 25689,
"end": 76501
} | class ____:
# pylint: disable=line-too-long
"""Saves and restores variables.
@compatibility(TF2)
`tf.compat.v1.train.Saver` is not supported for saving and restoring
checkpoints in TF2. Please switch to `tf.train.Checkpoint` or
`tf.keras.Model.save_weights`, which perform a more robust [object-based
saving](https://www.tensorflow.org/guide/checkpoint#loading_mechanics).
### How to Rewrite Checkpoints
Please rewrite your checkpoints immediately using the object-based checkpoint
APIs.
You can load a name-based checkpoint written by `tf.compat.v1.train.Saver`
using `tf.train.Checkpoint.restore` or `tf.keras.Model.load_weights`. However,
you may have to change the names of the variables in your model to match the
variable names in the name-based checkpoint, which can be viewed with
`tf.train.list_variables(path)`.
Another option is to create an `assignment_map` that maps the name of the
variables in the name-based checkpoint to the variables in your model, eg:
```
{
'sequential/dense/bias': model.variables[0],
'sequential/dense/kernel': model.variables[1]
}
```
and use `tf.compat.v1.train.init_from_checkpoint(path, assignment_map)` to
restore the name-based checkpoint.
After restoring, re-encode your checkpoint
using `tf.train.Checkpoint.save` or `tf.keras.Model.save_weights`.
See the [Checkpoint compatibility](
https://www.tensorflow.org/guide/migrate#checkpoint_compatibility)
section of the migration guide for more details.
### Checkpoint Management in TF2
Use `tf.train.CheckpointManager` to manage checkpoints in TF2.
`tf.train.CheckpointManager` offers equivalent `keep_checkpoint_every_n_hours`
and `max_to_keep` parameters.
To recover the latest checkpoint,
```
checkpoint = tf.train.Checkpoint(model)
manager = tf.train.CheckpointManager(checkpoint)
status = checkpoint.restore(manager.latest_checkpoint)
```
`tf.train.CheckpointManager` also writes a [`CheckpointState` proto]
(https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/checkpoint_state.proto)
which contains the timestamp when each checkpoint was created.
### Writing `MetaGraphDef`s in TF2
To replace, `tf.compat.v1.train.Saver.save(write_meta_graph=True)`, use
`tf.saved_model.save` to write the `MetaGraphDef` (which is contained in
`saved_model.pb`).
@end_compatibility
See [Variables](https://tensorflow.org/guide/variables)
for an overview of variables, saving and restoring.
The `Saver` class adds ops to save and restore variables to and from
*checkpoints*. It also provides convenience methods to run these ops.
Checkpoints are binary files in a proprietary format which map variable names
to tensor values. The best way to examine the contents of a checkpoint is to
load it using a `Saver`.
Savers can automatically number checkpoint filenames with a provided counter.
This lets you keep multiple checkpoints at different steps while training a
model. For example you can number the checkpoint filenames with the training
step number. To avoid filling up disks, savers manage checkpoint files
automatically. For example, they can keep only the N most recent files, or
one checkpoint for every N hours of training.
You number checkpoint filenames by passing a value to the optional
`global_step` argument to `save()`:
```python
saver.save(sess, 'my-model', global_step=0) ==> filename: 'my-model-0'
...
saver.save(sess, 'my-model', global_step=1000) ==> filename: 'my-model-1000'
```
Additionally, optional arguments to the `Saver()` constructor let you control
the proliferation of checkpoint files on disk:
* `max_to_keep` indicates the maximum number of recent checkpoint files to
keep. As new files are created, older files are deleted. If None or 0,
no checkpoints are deleted from the filesystem but only the last one is
kept in the `checkpoint` file. Defaults to 5 (that is, the 5 most recent
checkpoint files are kept.)
* `keep_checkpoint_every_n_hours`: In addition to keeping the most recent
`max_to_keep` checkpoint files, you might want to keep one checkpoint file
for every N hours of training. This can be useful if you want to later
analyze how a model progressed during a long training session. For
example, passing `keep_checkpoint_every_n_hours=2` ensures that you keep
one checkpoint file for every 2 hours of training. The default value of
10,000 hours effectively disables the feature.
Note that you still have to call the `save()` method to save the model.
Passing these arguments to the constructor will not save variables
automatically for you.
A training program that saves regularly looks like:
```python
...
# Create a saver.
saver = tf.compat.v1.train.Saver(...variables...)
# Launch the graph and train, saving the model every 1,000 steps.
sess = tf.compat.v1.Session()
for step in range(1000000):
sess.run(..training_op..)
if step % 1000 == 0:
# Append the step number to the checkpoint name:
saver.save(sess, 'my-model', global_step=step)
```
In addition to checkpoint files, savers keep a protocol buffer on disk with
the list of recent checkpoints. This is used to manage numbered checkpoint
files and by `latest_checkpoint()`, which makes it easy to discover the path
to the most recent checkpoint. That protocol buffer is stored in a file named
'checkpoint' next to the checkpoint files.
If you create several savers, you can specify a different filename for the
protocol buffer file in the call to `save()`.
"""
# pylint: enable=line-too-long
def __init__(self,
var_list=None,
reshape=False,
sharded=False,
max_to_keep=5,
keep_checkpoint_every_n_hours=10000.0,
name=None,
restore_sequentially=False,
saver_def=None,
builder=None,
defer_build=False,
allow_empty=False,
write_version=saver_pb2.SaverDef.V2,
pad_step_number=False,
save_relative_paths=False,
filename=None):
"""Creates a `Saver`.
The constructor adds ops to save and restore variables.
`var_list` specifies the variables that will be saved and restored. It can
be passed as a `dict` or a list:
* A `dict` of names to variables: The keys are the names that will be
used to save or restore the variables in the checkpoint files.
* A list of variables: The variables will be keyed with their op name in
the checkpoint files.
For example:
```python
v1 = tf.Variable(..., name='v1')
v2 = tf.Variable(..., name='v2')
# Pass the variables as a dict:
saver = tf.compat.v1.train.Saver({'v1': v1, 'v2': v2})
# Or pass them as a list.
saver = tf.compat.v1.train.Saver([v1, v2])
# Passing a list is equivalent to passing a dict with the variable op names
# as keys:
saver = tf.compat.v1.train.Saver({v.op.name: v for v in [v1, v2]})
```
Note: the newer `AutoTrackable` API is not supported by `Saver`. In this
case, the `tf.train.Checkpoint` class should be used.
The optional `reshape` argument, if `True`, allows restoring a variable from
a save file where the variable had a different shape, but the same number
of elements and type. This is useful if you have reshaped a variable and
want to reload it from an older checkpoint.
The optional `sharded` argument, if `True`, instructs the saver to shard
checkpoints per device.
Args:
var_list: A list of `Variable`/`SaveableObject`, or a dictionary mapping
names to `SaveableObject`s. If `None`, defaults to the list of all
saveable objects.
reshape: If `True`, allows restoring parameters from a checkpoint where
the variables have a different shape.
sharded: If `True`, shard the checkpoints, one per device.
max_to_keep: Maximum number of recent checkpoints to keep. Defaults to 5.
keep_checkpoint_every_n_hours: How often to keep checkpoints. Defaults to
10,000 hours.
name: String. Optional name to use as a prefix when adding operations.
restore_sequentially: A `Bool`, which if true, causes restore of different
variables to happen sequentially within each device. This can lower
memory usage when restoring very large models.
saver_def: Optional `SaverDef` proto to use instead of running the
builder. This is only useful for specialty code that wants to recreate a
`Saver` object for a previously built `Graph` that had a `Saver`. The
`saver_def` proto should be the one returned by the `as_saver_def()`
call of the `Saver` that was created for that `Graph`.
builder: Optional `SaverBuilder` to use if a `saver_def` was not provided.
Defaults to `BulkSaverBuilder()`.
defer_build: If `True`, defer adding the save and restore ops to the
`build()` call. In that case `build()` should be called before
finalizing the graph or using the saver.
allow_empty: If `False` (default) raise an error if there are no variables
in the graph. Otherwise, construct the saver anyway and make it a no-op.
write_version: controls what format to use when saving checkpoints. It
also affects certain filepath matching logic. The V2 format is the
recommended choice: it is much more optimized than V1 in terms of memory
required and latency incurred during restore. Regardless of this flag,
the Saver is able to restore from both V2 and V1 checkpoints.
pad_step_number: if True, pads the global step number in the checkpoint
filepaths to some fixed width (8 by default). This is turned off by
default.
save_relative_paths: If `True`, will write relative paths to the
checkpoint state file. This is needed if the user wants to copy the
checkpoint directory and reload from the copied directory.
filename: If known at graph construction time, filename used for variable
loading/saving.
Raises:
TypeError: If `var_list` is invalid.
ValueError: If any of the keys or values in `var_list` are not unique.
RuntimeError: If eager execution is enabled and`var_list` does not specify
a list of variables to save.
@compatibility(eager)
When eager execution is enabled, `var_list` must specify a `list` or `dict`
of variables to save. Otherwise, a `RuntimeError` will be raised.
Although Saver works in some cases when executing eagerly, it is
fragile. Please switch to `tf.train.Checkpoint` or
`tf.keras.Model.save_weights`, which perform a more robust object-based
saving. These APIs will load checkpoints written by `Saver`.
@end_compatibility
"""
global _END_TIME_OF_LAST_WRITE
with _END_TIME_OF_LAST_WRITE_LOCK:
if _END_TIME_OF_LAST_WRITE is None:
_END_TIME_OF_LAST_WRITE = time.time()
if defer_build and var_list:
raise ValueError(
"If `var_list` is provided then build cannot be deferred. "
"Either set defer_build=False or var_list=None.")
if context.executing_eagerly():
logging.warning(
"Saver is deprecated, please switch to tf.train.Checkpoint or "
"tf.keras.Model.save_weights for training checkpoints. When "
"executing eagerly variables do not necessarily have unique names, "
"and so the variable.name-based lookups Saver performs are "
"error-prone.")
if var_list is None:
raise RuntimeError(
"When eager execution is enabled, `var_list` must specify a list "
"or dict of variables to save")
self._var_list = var_list
self._reshape = reshape
self._sharded = sharded
self._max_to_keep = max_to_keep
self._keep_checkpoint_every_n_hours = keep_checkpoint_every_n_hours
self._name = name
self._restore_sequentially = restore_sequentially
self.saver_def = saver_def
self._builder = builder
self._is_built = False
self._allow_empty = allow_empty
self._is_empty = None
self._write_version = write_version
self._pad_step_number = pad_step_number
self._filename = filename
self._last_checkpoints = []
self._checkpoints_to_be_deleted = []
if context.executing_eagerly():
self._next_checkpoint_time = (
time.time() + self._keep_checkpoint_every_n_hours * 3600)
elif not defer_build:
self.build()
if self.saver_def:
self._check_saver_def()
self._write_version = self.saver_def.version
self._save_relative_paths = save_relative_paths
# For compatibility with object-based checkpoints, we may build a second
# Saver to read the renamed keys.
self._object_restore_saver = None
def build(self):
if context.executing_eagerly():
raise RuntimeError("Use save/restore instead of build in eager mode.")
self._build(self._filename, build_save=True, build_restore=True)
def _build_eager(self, checkpoint_path, build_save, build_restore):
self._build(
checkpoint_path, build_save=build_save, build_restore=build_restore)
def _build(self, checkpoint_path, build_save, build_restore):
"""Builds saver_def."""
if not context.executing_eagerly():
if self._is_built:
return
self._is_built = True
if not self.saver_def or context.executing_eagerly():
if self._builder is None:
self._builder = BulkSaverBuilder(self._write_version)
if self._var_list is None:
# pylint: disable=protected-access
self._var_list = variables._all_saveable_objects()
if not self._var_list:
if self._allow_empty:
self._is_empty = True
return
else:
raise ValueError("No variables to save")
self._is_empty = False
self.saver_def = self._builder._build_internal( # pylint: disable=protected-access
self._var_list,
reshape=self._reshape,
sharded=self._sharded,
max_to_keep=self._max_to_keep,
keep_checkpoint_every_n_hours=self._keep_checkpoint_every_n_hours,
name=self._name,
restore_sequentially=self._restore_sequentially,
filename=checkpoint_path,
build_save=build_save,
build_restore=build_restore)
elif self.saver_def and self._name:
# Since self._name is used as a name_scope by builder(), we are
# overloading the use of this field to represent the "import_scope" as
# well.
self.saver_def.filename_tensor_name = ops.prepend_name_scope(
self.saver_def.filename_tensor_name, self._name)
self.saver_def.save_tensor_name = ops.prepend_name_scope(
self.saver_def.save_tensor_name, self._name)
self.saver_def.restore_op_name = ops.prepend_name_scope(
self.saver_def.restore_op_name, self._name)
self._check_saver_def()
if not context.executing_eagerly():
# Updates next checkpoint time.
# Set in __init__ when executing eagerly.
self._next_checkpoint_time = (
time.time() + self.saver_def.keep_checkpoint_every_n_hours * 3600)
def _check_saver_def(self):
if not isinstance(self.saver_def, saver_pb2.SaverDef):
raise ValueError("saver_def must be a saver_pb2.SaverDef: %s" %
self.saver_def)
if not context.executing_eagerly():
if not self.saver_def.save_tensor_name:
raise ValueError("saver_def must specify the save_tensor_name: %s" %
str(self.saver_def))
if not self.saver_def.restore_op_name:
raise ValueError("saver_def must specify the restore_op_name: %s" %
str(self.saver_def))
def _CheckpointFilename(self, p):
"""Returns the checkpoint filename given a `(filename, time)` pair.
Args:
p: (filename, time) pair.
Returns:
Checkpoint file name.
"""
name, _ = p
return name
def _RecordLastCheckpoint(self, latest_save_path):
"""Manages the list of the latest checkpoints."""
if not self.saver_def.max_to_keep:
return
# Remove first from list if the same name was used before.
for p in self._last_checkpoints[:]:
if latest_save_path == self._CheckpointFilename(p):
self._last_checkpoints.remove(p)
# Append new path to list
self._last_checkpoints.append((latest_save_path, time.time()))
# If more than max_to_keep, remove oldest.
if len(self._last_checkpoints) > self.saver_def.max_to_keep:
self._checkpoints_to_be_deleted.append(self._last_checkpoints.pop(0))
def _MaybeDeleteOldCheckpoints(self, meta_graph_suffix="meta"):
"""Deletes old checkpoints if necessary.
`self._checkpoints_to_be_deleted` is going to contain checkpoints that are
over `max_to_keep`. They are going to be deleted. If
`keep_checkpoint_every_n_hours` was specified, keep an additional checkpoint
every `N` hours. For example, if `N` is 0.5, an additional checkpoint is
kept for every 0.5 hours of training; if `N` is 10, an additional
checkpoint is kept for every 10 hours of training.
Args:
meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'.
"""
if self._checkpoints_to_be_deleted:
p = self._checkpoints_to_be_deleted.pop(0)
# Do not delete the file if we keep_checkpoint_every_n_hours is set and we
# have reached N hours of training.
should_keep = p[1] > self._next_checkpoint_time
if should_keep:
self._next_checkpoint_time += (
self.saver_def.keep_checkpoint_every_n_hours * 3600)
return
# Otherwise delete the files.
try:
checkpoint_management.remove_checkpoint(
self._CheckpointFilename(p), self.saver_def.version,
meta_graph_suffix)
except Exception as e: # pylint: disable=broad-except
logging.warning("Ignoring: %s", str(e))
def as_saver_def(self):
"""Generates a `SaverDef` representation of this saver.
Returns:
A `SaverDef` proto.
"""
return self.saver_def
def to_proto(self, export_scope=None):
"""Converts this `Saver` to a `SaverDef` protocol buffer.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `SaverDef` protocol buffer.
"""
if export_scope is None:
return self.saver_def
if not (self.saver_def.filename_tensor_name.startswith(export_scope) and
self.saver_def.save_tensor_name.startswith(export_scope) and
self.saver_def.restore_op_name.startswith(export_scope)):
return None
saver_def = saver_pb2.SaverDef()
saver_def.CopyFrom(self.saver_def)
saver_def.filename_tensor_name = ops.strip_name_scope(
saver_def.filename_tensor_name, export_scope)
saver_def.save_tensor_name = ops.strip_name_scope(
saver_def.save_tensor_name, export_scope)
saver_def.restore_op_name = ops.strip_name_scope(saver_def.restore_op_name,
export_scope)
return saver_def
@staticmethod
def from_proto(saver_def, import_scope=None):
"""Returns a `Saver` object created from `saver_def`.
Args:
saver_def: a `SaverDef` protocol buffer.
import_scope: Optional `string`. Name scope to use.
Returns:
A `Saver` built from saver_def.
"""
return Saver(saver_def=saver_def, name=import_scope)
@property
def last_checkpoints(self):
"""List of not-yet-deleted checkpoint filenames.
You can pass any of the returned values to `restore()`.
Returns:
A list of checkpoint filenames, sorted from oldest to newest.
"""
return list(self._CheckpointFilename(p) for p in self._last_checkpoints)
def set_last_checkpoints(self, last_checkpoints):
"""DEPRECATED: Use set_last_checkpoints_with_time.
Sets the list of old checkpoint filenames.
Args:
last_checkpoints: A list of checkpoint filenames.
Raises:
AssertionError: If last_checkpoints is not a list.
"""
assert isinstance(last_checkpoints, list)
# We use a timestamp of +inf so that this checkpoint will never be
# deleted. This is both safe and backwards compatible to a previous
# version of the code which used s[1] as the "timestamp".
self._last_checkpoints = [(s, np.inf) for s in last_checkpoints]
def set_last_checkpoints_with_time(self, last_checkpoints_with_time):
"""Sets the list of old checkpoint filenames and timestamps.
Args:
last_checkpoints_with_time: A list of tuples of checkpoint filenames and
timestamps.
Raises:
AssertionError: If last_checkpoints_with_time is not a list.
"""
assert isinstance(last_checkpoints_with_time, list)
self._last_checkpoints = last_checkpoints_with_time
def recover_last_checkpoints(self, checkpoint_paths):
"""Recovers the internal saver state after a crash.
This method is useful for recovering the "self._last_checkpoints" state.
Globs for the checkpoints pointed to by `checkpoint_paths`. If the files
exist, use their mtime as the checkpoint timestamp.
Args:
checkpoint_paths: a list of checkpoint paths.
"""
checkpoints_with_mtimes = []
for checkpoint_path in checkpoint_paths:
try:
mtime = checkpoint_management.get_checkpoint_mtimes([checkpoint_path])
except errors.NotFoundError:
# It's fine if some other thread/process is deleting some older
# checkpoint concurrently.
continue
if mtime:
checkpoints_with_mtimes.append((checkpoint_path, mtime[0]))
self.set_last_checkpoints_with_time(checkpoints_with_mtimes)
def save(self,
sess,
save_path,
global_step=None,
latest_filename=None,
meta_graph_suffix="meta",
write_meta_graph=True,
write_state=True,
strip_default_attrs=False,
save_debug_info=False):
# pylint: disable=line-too-long
"""Saves variables.
This method runs the ops added by the constructor for saving variables.
It requires a session in which the graph was launched. The variables to
save must also have been initialized.
The method returns the path prefix of the newly created checkpoint files.
This string can be passed directly to a call to `restore()`.
Args:
sess: A Session to use to save the variables.
save_path: String. Prefix of filenames created for the checkpoint.
global_step: If provided the global step number is appended to `save_path`
to create the checkpoint filenames. The optional argument can be a
`Tensor`, a `Tensor` name or an integer.
latest_filename: Optional name for the protocol buffer file that will
contains the list of most recent checkpoints. That file, kept in the
same directory as the checkpoint files, is automatically managed by the
saver to keep track of recent checkpoints. Defaults to 'checkpoint'.
meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'.
write_meta_graph: `Boolean` indicating whether or not to write the meta
graph file.
write_state: `Boolean` indicating whether or not to write the
`CheckpointStateProto`.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
removed from the NodeDefs. For a detailed guide, see [Stripping
Default-Valued
Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
save_debug_info: If `True`, save the GraphDebugInfo to a separate file,
which in the same directory of save_path and with `_debug` added before
the file extension. This is only enabled when `write_meta_graph` is
`True`
Returns:
A string: path prefix used for the checkpoint files. If the saver is
sharded, this string ends with: '-?????-of-nnnnn' where 'nnnnn'
is the number of shards created.
If the saver is empty, returns None.
Raises:
TypeError: If `sess` is not a `Session`.
ValueError: If `latest_filename` contains path components, or if it
collides with `save_path`.
RuntimeError: If save and restore ops weren't built.
"""
# pylint: enable=line-too-long
start_time = time.time()
if not self._is_built and not context.executing_eagerly():
raise RuntimeError(
"`build()` should be called before save if defer_build==True")
if latest_filename is None:
latest_filename = "checkpoint"
if self._write_version != saver_pb2.SaverDef.V2:
logging.warning("*******************************************************")
logging.warning("TensorFlow's V1 checkpoint format has been deprecated.")
logging.warning("Consider switching to the more efficient V2 format:")
logging.warning(" `tf.train.Saver(write_version=tf.train.SaverDef.V2)`")
logging.warning("now on by default.")
logging.warning("*******************************************************")
if os.path.split(latest_filename)[0]:
raise ValueError("'latest_filename' must not contain path components")
save_path = compat.as_str(save_path)
if global_step is not None:
if not isinstance(global_step, compat.integral_types):
global_step = training_util.global_step(sess, global_step)
checkpoint_file = "%s-%d" % (save_path, global_step)
if self._pad_step_number:
# Zero-pads the step numbers, so that they are sorted when listed.
checkpoint_file = "%s-%s" % (save_path, "{:08d}".format(global_step))
else:
checkpoint_file = save_path
if os.path.basename(save_path) == latest_filename and not self._sharded:
# Guard against collision between data file and checkpoint state file.
raise ValueError(
"'latest_filename' collides with 'save_path': '%s' and '%s'" %
(latest_filename, save_path))
if (not context.executing_eagerly() and
not isinstance(sess, session.SessionInterface)):
raise TypeError("'sess' must be a Session; %s" % sess)
save_path_parent = os.path.dirname(save_path)
if not self._is_empty:
try:
if context.executing_eagerly():
self._build_eager(
checkpoint_file, build_save=True, build_restore=False)
model_checkpoint_path = self.saver_def.save_tensor_name
else:
model_checkpoint_path = sess.run(
self.saver_def.save_tensor_name,
{self.saver_def.filename_tensor_name: checkpoint_file})
model_checkpoint_path = compat.as_str(model_checkpoint_path)
if write_state:
self._RecordLastCheckpoint(model_checkpoint_path)
checkpoint_management.update_checkpoint_state_internal(
save_dir=save_path_parent,
model_checkpoint_path=model_checkpoint_path,
all_model_checkpoint_paths=self.last_checkpoints,
latest_filename=latest_filename,
save_relative_paths=self._save_relative_paths)
self._MaybeDeleteOldCheckpoints(meta_graph_suffix=meta_graph_suffix)
except (errors.FailedPreconditionError, errors.NotFoundError) as exc:
if not gfile.IsDirectory(save_path_parent):
exc = ValueError(
"Parent directory of {} doesn't exist, can't save.".format(
save_path))
raise exc
end_time = time.time()
metrics.AddCheckpointWriteDuration(
api_label=_SAVER_LABEL,
microseconds=_get_duration_microseconds(start_time, end_time))
global _END_TIME_OF_LAST_WRITE
with _END_TIME_OF_LAST_WRITE_LOCK:
metrics.AddTrainingTimeSaved(
api_label=_SAVER_LABEL,
microseconds=_get_duration_microseconds(_END_TIME_OF_LAST_WRITE,
end_time))
_END_TIME_OF_LAST_WRITE = end_time
if write_meta_graph:
meta_graph_filename = checkpoint_management.meta_graph_filename(
checkpoint_file, meta_graph_suffix=meta_graph_suffix)
if not context.executing_eagerly():
with sess.graph.as_default():
self.export_meta_graph(
meta_graph_filename,
strip_default_attrs=strip_default_attrs,
save_debug_info=save_debug_info)
if self._is_empty:
return None
else:
metrics.RecordCheckpointSize(
api_label=_SAVER_LABEL,
filesize=_get_checkpoint_size(model_checkpoint_path))
return model_checkpoint_path
def export_meta_graph(self,
filename=None,
collection_list=None,
as_text=False,
export_scope=None,
clear_devices=False,
clear_extraneous_savers=False,
strip_default_attrs=False,
save_debug_info=False):
# pylint: disable=line-too-long
"""Writes `MetaGraphDef` to save_path/filename.
Args:
filename: Optional meta_graph filename including the path.
collection_list: List of string keys to collect.
as_text: If `True`, writes the meta_graph as an ASCII proto.
export_scope: Optional `string`. Name scope to remove.
clear_devices: Whether or not to clear the device field for an `Operation`
or `Tensor` during export.
clear_extraneous_savers: Remove any Saver-related information from the
graph (both Save/Restore ops and SaverDefs) that are not associated with
this Saver.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
removed from the NodeDefs. For a detailed guide, see [Stripping
Default-Valued
Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
save_debug_info: If `True`, save the GraphDebugInfo to a separate file,
which in the same directory of filename and with `_debug` added before
the file extension.
Returns:
A `MetaGraphDef` proto.
"""
# pylint: enable=line-too-long
return export_meta_graph(
filename=filename,
graph_def=ops.get_default_graph().as_graph_def(
add_shapes=True, use_pybind11_proto=True
),
saver_def=self.saver_def,
collection_list=collection_list,
as_text=as_text,
export_scope=export_scope,
clear_devices=clear_devices,
clear_extraneous_savers=clear_extraneous_savers,
strip_default_attrs=strip_default_attrs,
save_debug_info=save_debug_info,
)
def restore(self, sess, save_path):
"""Restores previously saved variables.
This method runs the ops added by the constructor for restoring variables.
It requires a session in which the graph was launched. The variables to
restore do not have to have been initialized, as restoring is itself a way
to initialize variables.
The `save_path` argument is typically a value previously returned from a
`save()` call, or a call to `latest_checkpoint()`.
Args:
sess: A `Session` to use to restore the parameters. None in eager mode.
save_path: Path where parameters were previously saved.
Raises:
ValueError: If save_path is None or not a valid checkpoint.
"""
start_time = time.time()
if self._is_empty:
return
if save_path is None:
raise ValueError("Can't load save_path when it is None.")
checkpoint_prefix = compat.as_text(save_path)
if not checkpoint_management.checkpoint_exists_internal(checkpoint_prefix):
raise ValueError("The passed save_path is not a valid checkpoint: " +
checkpoint_prefix)
logging.info("Restoring parameters from %s", checkpoint_prefix)
try:
if context.executing_eagerly():
self._build_eager(save_path, build_save=False, build_restore=True)
else:
sess.run(self.saver_def.restore_op_name,
{self.saver_def.filename_tensor_name: save_path})
except errors.NotFoundError as err:
# There are three common conditions that might cause this error:
# 0. The file is missing. We ignore here, as this is checked above.
# 1. This is an object-based checkpoint trying name-based loading.
# 2. The graph has been altered and a variable or other name is missing.
# 1. The checkpoint would not be loaded successfully as is. Try to parse
# it as an object-based checkpoint.
try:
names_to_keys = object_graph_key_mapping(save_path)
except errors.NotFoundError:
# 2. This is not an object-based checkpoint, which likely means there
# is a graph mismatch. Re-raise the original error with
# a helpful message (b/110263146)
raise _wrap_restore_error_with_msg(
err, "a Variable name or other graph key that is missing")
# This is an object-based checkpoint. We'll print a warning and then do
# the restore.
logging.warning(
"Restoring an object-based checkpoint using a name-based saver. This "
"may be somewhat fragile, and will re-build the Saver. Instead, "
"consider loading object-based checkpoints using "
"tf.train.Checkpoint().")
self._object_restore_saver = saver_from_object_based_checkpoint(
checkpoint_path=save_path,
var_list=self._var_list,
builder=self._builder,
names_to_keys=names_to_keys,
cached_saver=self._object_restore_saver)
self._object_restore_saver.restore(sess=sess, save_path=save_path)
except errors.InvalidArgumentError as err:
# There is a mismatch between the graph and the checkpoint being loaded.
# We add a more reasonable error message here to help users (b/110263146)
raise _wrap_restore_error_with_msg(
err, "a mismatch between the current graph and the graph")
metrics.AddCheckpointReadDuration(
api_label=_SAVER_LABEL,
microseconds=_get_duration_microseconds(start_time, time.time()))
@staticmethod
def _add_collection_def(meta_graph_def, key, export_scope=None):
"""Adds a collection to MetaGraphDef protocol buffer.
Args:
meta_graph_def: MetaGraphDef protocol buffer.
key: One of the GraphKeys or user-defined string.
export_scope: Optional `string`. Name scope to remove.
"""
meta_graph.add_collection_def(
meta_graph_def, key, export_scope=export_scope)
@tf_export(v1=["train.import_meta_graph"])
def import_meta_graph(meta_graph_or_file,
clear_devices=False,
import_scope=None,
**kwargs):
"""Recreates a Graph saved in a `MetaGraphDef` proto.
This function takes a `MetaGraphDef` protocol buffer as input. If
the argument is a file containing a `MetaGraphDef` protocol buffer ,
it constructs a protocol buffer from the file content. The function
then adds all the nodes from the `graph_def` field to the
current graph, recreates all the collections, and returns a saver
constructed from the `saver_def` field.
In combination with `export_meta_graph()`, this function can be used to
* Serialize a graph along with other Python objects such as `QueueRunner`,
`Variable` into a `MetaGraphDef`.
* Restart training from a saved graph and checkpoints.
* Run inference from a saved graph and checkpoints.
```Python
...
# Create a saver.
saver = tf.compat.v1.train.Saver(...variables...)
# Remember the training_op we want to run by adding it to a collection.
tf.compat.v1.add_to_collection('train_op', train_op)
sess = tf.compat.v1.Session()
for step in range(1000000):
sess.run(train_op)
if step % 1000 == 0:
# Saves checkpoint, which by default also exports a meta_graph
# named 'my-model-global_step.meta'.
saver.save(sess, 'my-model', global_step=step)
```
Later we can continue training from this saved `meta_graph` without building
the model from scratch.
```Python
with tf.Session() as sess:
new_saver =
tf.train.import_meta_graph('my-save-dir/my-model-10000.meta')
new_saver.restore(sess, 'my-save-dir/my-model-10000')
# tf.get_collection() returns a list. In this example we only want
# the first one.
train_op = tf.get_collection('train_op')[0]
for step in range(1000000):
sess.run(train_op)
```
NOTE: Restarting training from saved `meta_graph` only works if the
device assignments have not changed.
Example:
Variables, placeholders, and independent operations can also be stored, as
shown in the following example.
```Python
# Saving contents and operations.
v1 = tf.placeholder(tf.float32, name="v1")
v2 = tf.placeholder(tf.float32, name="v2")
v3 = tf.math.multiply(v1, v2)
vx = tf.Variable(10.0, name="vx")
v4 = tf.add(v3, vx, name="v4")
saver = tf.train.Saver([vx])
sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(vx.assign(tf.add(vx, vx)))
result = sess.run(v4, feed_dict={v1:12.0, v2:3.3})
print(result)
saver.save(sess, "./model_ex1")
```
Later this model can be restored and contents loaded.
```Python
# Restoring variables and running operations.
saver = tf.train.import_meta_graph("./model_ex1.meta")
sess = tf.Session()
saver.restore(sess, "./model_ex1")
result = sess.run("v4:0", feed_dict={"v1:0": 12.0, "v2:0": 3.3})
print(result)
```
Args:
meta_graph_or_file: `MetaGraphDef` protocol buffer or filename (including
the path) containing a `MetaGraphDef`.
clear_devices: Whether or not to clear the device field for an `Operation`
or `Tensor` during import.
import_scope: Optional `string`. Name scope to add. Only used when
initializing from protocol buffer.
**kwargs: Optional keyed arguments.
Returns:
A saver constructed from `saver_def` in `MetaGraphDef` or None.
A None value is returned if no variables exist in the `MetaGraphDef`
(i.e., there are no variables to restore).
Raises:
RuntimeError: If called with eager execution enabled.
@compatibility(eager)
Exporting/importing meta graphs is not supported. No graph exists when eager
execution is enabled.
@end_compatibility
""" # pylint: disable=g-doc-exception
return _import_meta_graph_with_return_elements(meta_graph_or_file,
clear_devices, import_scope,
**kwargs)[0]
def _import_meta_graph_with_return_elements(meta_graph_or_file,
clear_devices=False,
import_scope=None,
return_elements=None,
**kwargs):
"""Import MetaGraph, and return both a saver and returned elements."""
if context.executing_eagerly():
raise RuntimeError("Exporting/importing meta graphs is not supported when "
"eager execution is enabled. No graph exists when eager "
"execution is enabled.")
if not isinstance(meta_graph_or_file, meta_graph_pb2.MetaGraphDef):
meta_graph_def = meta_graph.read_meta_graph_file(meta_graph_or_file)
else:
meta_graph_def = meta_graph_or_file
imported_vars, imported_return_elements = (
meta_graph.import_scoped_meta_graph_with_return_elements(
meta_graph_def,
clear_devices=clear_devices,
import_scope=import_scope,
return_elements=return_elements,
**kwargs))
saver = _create_saver_from_imported_meta_graph(meta_graph_def, import_scope,
imported_vars)
return saver, imported_return_elements
def _create_saver_from_imported_meta_graph(meta_graph_def, import_scope,
imported_vars):
"""Return a saver for restoring variable values to an imported MetaGraph."""
if meta_graph_def.HasField("saver_def"):
# Infer the scope that is prepended by `import_scoped_meta_graph`.
scope = import_scope
var_names = list(imported_vars.keys())
if var_names:
sample_key = var_names[0]
sample_var = imported_vars[sample_key]
scope = sample_var.name[:-len(sample_key)]
return Saver(saver_def=meta_graph_def.saver_def, name=scope)
else:
if variables._all_saveable_objects(scope=import_scope): # pylint: disable=protected-access
# Return the default saver instance for all graph variables.
return Saver()
else:
# If no graph variables exist, then a Saver cannot be constructed.
logging.info("Saver not created because there are no variables in the"
" graph to restore")
return None
@tf_export(v1=["train.export_meta_graph"])
def export_meta_graph(filename=None,
meta_info_def=None,
graph_def=None,
saver_def=None,
collection_list=None,
as_text=False,
graph=None,
export_scope=None,
clear_devices=False,
clear_extraneous_savers=False,
strip_default_attrs=False,
save_debug_info=False,
**kwargs):
# pylint: disable=line-too-long
"""Returns `MetaGraphDef` proto.
Optionally writes it to filename.
This function exports the graph, saver, and collection objects into
`MetaGraphDef` protocol buffer with the intention of it being imported
at a later time or location to restart training, run inference, or be
a subgraph.
Args:
filename: Optional filename including the path for writing the generated
`MetaGraphDef` protocol buffer.
meta_info_def: `MetaInfoDef` protocol buffer.
graph_def: `GraphDef` protocol buffer.
saver_def: `SaverDef` protocol buffer.
collection_list: List of string keys to collect.
as_text: If `True`, writes the `MetaGraphDef` as an ASCII proto.
graph: The `Graph` to export. If `None`, use the default graph.
export_scope: Optional `string`. Name scope under which to extract the
subgraph. The scope name will be striped from the node definitions for
easy import later into new name scopes. If `None`, the whole graph is
exported. graph_def and export_scope cannot both be specified.
clear_devices: Whether or not to clear the device field for an `Operation`
or `Tensor` during export.
clear_extraneous_savers: Remove any Saver-related information from the graph
(both Save/Restore ops and SaverDefs) that are not associated with the
provided SaverDef.
strip_default_attrs: Boolean. If `True`, default-valued attributes will be
removed from the NodeDefs. For a detailed guide, see [Stripping
Default-Valued
Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes).
save_debug_info: If `True`, save the GraphDebugInfo to a separate file,
which in the same directory of filename and with `_debug` added before the
file extend.
**kwargs: Optional keyed arguments.
Returns:
A `MetaGraphDef` proto.
Raises:
ValueError: When the `GraphDef` is larger than 2GB.
RuntimeError: If called with eager execution enabled.
@compatibility(eager)
Exporting/importing meta graphs is not supported unless both `graph_def` and
`graph` are provided. No graph exists when eager execution is enabled.
@end_compatibility
"""
# pylint: enable=line-too-long
if context.executing_eagerly() and not (graph_def is not None and
graph is not None):
raise RuntimeError("Exporting/importing meta graphs is not supported when "
"eager execution is enabled. No graph exists when eager "
"execution is enabled.")
meta_graph_def, _ = meta_graph.export_scoped_meta_graph(
filename=filename,
meta_info_def=meta_info_def,
graph_def=graph_def,
saver_def=saver_def,
collection_list=collection_list,
as_text=as_text,
graph=graph,
export_scope=export_scope,
clear_devices=clear_devices,
clear_extraneous_savers=clear_extraneous_savers,
strip_default_attrs=strip_default_attrs,
save_debug_info=save_debug_info,
**kwargs)
return meta_graph_def
def _wrap_restore_error_with_msg(err, extra_verbiage):
err_msg = ("Restoring from checkpoint failed. This is most likely "
"due to {} from the checkpoint. Please ensure that you "
"have not altered the graph expected based on the checkpoint. "
"Original error:\n\n{}").format(extra_verbiage, err.message)
return err.__class__(err.node_def, err.op, err_msg)
ops.register_proto_function(
ops.GraphKeys.SAVERS,
proto_type=saver_pb2.SaverDef,
to_proto=Saver.to_proto,
from_proto=Saver.from_proto)
def object_graph_key_mapping(checkpoint_path):
"""Return name to key mappings from the checkpoint.
Args:
checkpoint_path: string, path to object-based checkpoint
Returns:
Dictionary mapping tensor names to checkpoint keys.
"""
reader = py_checkpoint_reader.NewCheckpointReader(checkpoint_path)
object_graph_string = reader.get_tensor(trackable.OBJECT_GRAPH_PROTO_KEY)
object_graph_proto = (trackable_object_graph_pb2.TrackableObjectGraph())
object_graph_proto.ParseFromString(object_graph_string)
names_to_keys = {}
for node in object_graph_proto.nodes:
for attribute in node.attributes:
names_to_keys[attribute.full_name] = attribute.checkpoint_key
return names_to_keys
def saver_from_object_based_checkpoint(checkpoint_path,
var_list=None,
builder=None,
names_to_keys=None,
cached_saver=None):
"""Return a `Saver` which reads from an object-based checkpoint.
This function validates that all variables in the variables list are remapped
in the object-based checkpoint (or `names_to_keys` dict if provided). A
saver will be created with the list of remapped variables.
The `cached_saver` argument allows the user to pass in a previously created
saver, so multiple `saver.restore()` calls don't pollute the graph when graph
building. This assumes that keys are consistent, meaning that the
1) `checkpoint_path` checkpoint, and
2) checkpoint used to create the `cached_saver`
are the same type of object-based checkpoint. If this argument is set, this
function will simply validate that all variables have been remapped by the
checkpoint at `checkpoint_path`.
Note that in general, `tf.train.Checkpoint` should be used to restore/save an
object-based checkpoint.
Args:
checkpoint_path: string, path to object-based checkpoint
var_list: list of `Variables` that appear in the checkpoint. If `None`,
`var_list` will be set to all saveable objects.
builder: a `BaseSaverBuilder` instance. If `None`, a new `BulkSaverBuilder`
will be created.
names_to_keys: dict mapping string tensor names to checkpoint keys. If
`None`, this dict will be generated from the checkpoint file.
cached_saver: Cached `Saver` object with remapped variables.
Returns:
`Saver` with remapped variables for reading from an object-based checkpoint.
Raises:
ValueError if the checkpoint provided is not an object-based checkpoint.
NotFoundError: If one of the variables in `var_list` can not be found in the
checkpoint. This could mean the checkpoint or `names_to_keys` mapping is
missing the variable.
"""
if names_to_keys is None:
try:
names_to_keys = object_graph_key_mapping(checkpoint_path)
except errors.NotFoundError:
raise ValueError("Checkpoint in %s not an object-based checkpoint." %
checkpoint_path)
if var_list is None:
var_list = variables._all_saveable_objects() # pylint: disable=protected-access
if builder is None:
builder = BulkSaverBuilder()
if not isinstance(var_list, dict):
var_list = saveable_object_util.op_list_to_dict(var_list)
saveables = saveable_object_util.validate_and_slice_inputs(var_list)
current_names = set()
for saveable in saveables:
for spec in saveable.specs:
current_names.add(spec.name)
previous_names = set(names_to_keys.keys())
missing_names = current_names - previous_names
if missing_names:
extra_names = previous_names - current_names
intersecting_names = previous_names.intersection(current_names)
raise errors.NotFoundError(
None,
None,
message=(
"\n\nExisting variables not in the checkpoint: %s\n\n"
"Variables names when this checkpoint was written which don't "
"exist now: %s\n\n"
"(%d variable name(s) did match)\n\n"
"Could not find some variables in the checkpoint (see names "
"above). Saver was attempting to load an object-based checkpoint "
"(saved using tf.train.Checkpoint or tf.keras.Model.save_weights) "
"using variable names. If the checkpoint was written with eager "
"execution enabled, it's possible that variable names have "
"changed (for example missing a '_1' suffix). It's also "
"possible that there are new variables which did not exist "
"when the checkpoint was written. You can construct a "
"Saver(var_list=...) with only the variables which previously "
"existed, and if variable names have changed you may need to "
"make this a dictionary with the old names as keys.") %
(", ".join(sorted(missing_names)), ", ".join(
sorted(extra_names)), len(intersecting_names)))
for saveable in saveables:
for spec in saveable.specs:
spec.name = names_to_keys[spec.name]
if cached_saver is None:
return Saver(saveables)
return cached_saver
| Saver |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 62193,
"end": 62402
} | class ____(IP):
"""A IPv4 address field.
.. versionadded:: 3.8.0
"""
default_error_messages = {"invalid_ip": "Not a valid IPv4 address."}
DESERIALIZATION_CLASS = ipaddress.IPv4Address
| IPv4 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/executor_definition.py | {
"start": 9985,
"end": 21829
} | class ____:
def __init__(self, name=None, config_schema=None, requirements=None):
self.name = check.opt_str_param(name, "name")
self.config_schema = config_schema # type check in definition
self.requirements = requirements
def __call__(self, fn: ExecutorCreationFunction) -> ExecutorDefinition:
check.callable_param(fn, "fn")
if not self.name:
self.name = fn.__name__
executor_def = ExecutorDefinition(
name=self.name,
config_schema=self.config_schema,
executor_creation_fn=fn,
requirements=self.requirements,
)
# `update_wrapper` typing cannot currently handle a Union of Callables correctly
update_wrapper(executor_def, wrapped=fn) # type: ignore
return executor_def
def _core_in_process_executor_creation(config: ExecutorConfig) -> "InProcessExecutor":
from dagster._core.executor.in_process import InProcessExecutor
return InProcessExecutor(
# shouldn't need to .get() here - issue with defaults in config setup
retries=RetryMode.from_config(check.dict_elem(config, "retries")), # type: ignore # (possible none)
marker_to_close=config.get("marker_to_close"), # type: ignore # (should be str)
step_dependency_config=StepDependencyConfig.from_config(
check.opt_nullable_dict_elem(config, "step_dependency_config")
),
)
IN_PROC_CONFIG = Field(
{
"retries": get_retries_config(),
"marker_to_close": Field(
str,
is_required=False,
description="[DEPRECATED]",
),
"step_dependency_config": get_step_dependency_config_field(),
},
description="Execute all steps in a single process.",
)
@executor(
name="in_process",
config_schema=IN_PROC_CONFIG,
)
def in_process_executor(init_context):
"""The in-process executor executes all steps in a single process.
To select it, include the following top-level fragment in config:
.. code-block:: yaml
execution:
in_process:
Execution priority can be configured using the ``dagster/priority`` tag via op metadata,
where the higher the number the higher the priority. 0 is the default and both positive
and negative numbers can be used.
"""
return _core_in_process_executor_creation(init_context.executor_config)
@executor(name="execute_in_process_executor")
def execute_in_process_executor(_) -> "InProcessExecutor":
"""Executor used by execute_in_process.
Use of this executor triggers special behavior in the config system that ignores all incoming
executor config. This is because someone might set executor config on a job, and when we foist
this executor onto the job for `execute_in_process`, that config becomes nonsensical.
"""
from dagster._core.executor.in_process import InProcessExecutor
return InProcessExecutor(
retries=RetryMode.ENABLED,
marker_to_close=None,
)
def _core_multiprocess_executor_creation(config: ExecutorConfig) -> "MultiprocessExecutor":
from dagster._core.executor.multiprocess import MultiprocessExecutor
# unpack optional selector
start_method = None
start_cfg: dict[str, object] = {}
start_selector = check.opt_dict_elem(config, "start_method")
if start_selector:
start_method, start_cfg = next(iter(start_selector.items()))
return MultiprocessExecutor(
max_concurrent=check.opt_int_elem(config, "max_concurrent"),
tag_concurrency_limits=check.opt_list_elem(config, "tag_concurrency_limits"),
retries=RetryMode.from_config(check.dict_elem(config, "retries")), # type: ignore
start_method=start_method,
explicit_forkserver_preload=check.opt_list_elem(start_cfg, "preload_modules", of_type=str),
step_dependency_config=StepDependencyConfig.from_config(
check.opt_nullable_dict_elem(config, "step_dependency_config")
),
)
MULTI_PROC_CONFIG = Field(
{
"max_concurrent": Field(
Noneable(Int),
default_value=None,
description=(
"The number of processes that may run concurrently. "
"By default, this is set to be the return value of `multiprocessing.cpu_count()`."
),
),
"tag_concurrency_limits": get_tag_concurrency_limits_config(),
"start_method": Field(
Selector(
fields={
"spawn": Field(
{},
description=(
"Configure the multiprocess executor to start subprocesses "
"using `spawn`."
),
),
"forkserver": Field(
{
"preload_modules": Field(
[str],
is_required=False,
description=(
"Explicitly specify the modules to preload in the forkserver."
" Otherwise, there are two cases for default values if modules"
" are not specified. If the Dagster job was loaded from a"
" module, the same module will be preloaded. If not, the"
" `dagster` module is preloaded."
),
),
},
description=(
"Configure the multiprocess executor to start subprocesses "
"using `forkserver`."
),
),
# fork currently unsupported due to threads usage
}
),
is_required=False,
description=(
"Select how subprocesses are created. By default, `spawn` is selected. See "
"https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods."
),
),
"retries": get_retries_config(),
"step_dependency_config": get_step_dependency_config_field(),
},
description="Execute each step in an individual process.",
)
@executor(
name="multiprocess",
config_schema=MULTI_PROC_CONFIG,
requirements=multiple_process_executor_requirements(),
)
def multiprocess_executor(init_context):
"""The multiprocess executor executes each step in an individual process.
Any job that does not specify custom executors will use the multiprocess_executor by default.
To configure the multiprocess executor, include a fragment such as the following in your run
config:
.. code-block:: yaml
execution:
config:
multiprocess:
max_concurrent: 4
The ``max_concurrent`` arg is optional and tells the execution engine how many processes may run
concurrently. By default, or if you set ``max_concurrent`` to be None or 0, this is the return value of
:py:func:`python:multiprocessing.cpu_count`.
Execution priority can be configured using the ``dagster/priority`` tag via op metadata,
where the higher the number the higher the priority. 0 is the default and both positive
and negative numbers can be used.
"""
return _core_multiprocess_executor_creation(init_context.executor_config)
def check_cross_process_constraints(init_context: "InitExecutorContext") -> None:
from dagster._core.executor.init import InitExecutorContext
check.inst_param(init_context, "init_context", InitExecutorContext)
requirements_lst = init_context.executor_def.get_requirements(init_context.executor_config)
if ExecutorRequirement.RECONSTRUCTABLE_JOB in requirements_lst:
_check_intra_process_job(init_context.job)
if ExecutorRequirement.NON_EPHEMERAL_INSTANCE in requirements_lst:
_check_non_ephemeral_instance(init_context.instance)
def _check_intra_process_job(job: IJob) -> None:
if not isinstance(job, ReconstructableJob):
raise DagsterUnmetExecutorRequirementsError(
"You have attempted to use an executor that uses multiple processes with the job"
f' "{job.get_definition().name}" that is not reconstructable. Job must be loaded in a'
" way that allows dagster to reconstruct them in a new process. This means: \n *"
" using the file, module, or workspace.yaml arguments of"
" dagster-webserver/dagster-graphql/dagster\n * loading the job through the"
" reconstructable() function\n"
)
def _check_non_ephemeral_instance(instance: "DagsterInstance") -> None:
if instance.is_ephemeral:
raise DagsterUnmetExecutorRequirementsError(
"You have attempted to use an executor that uses multiple processes with an ephemeral"
" DagsterInstance. A non-ephemeral instance is needed to coordinate execution between"
" multiple processes. You can configure your default instance via $DAGSTER_HOME or"
" ensure a valid one is passed when invoking the python APIs. You can learn more about"
" setting up a persistent DagsterInstance from the DagsterInstance docs here:"
" https://docs.dagster.io/guides/deploy/dagster-instance-configuration#default-local-behavior"
)
def _get_default_executor_requirements(
executor_config: ExecutorConfig,
) -> Sequence[ExecutorRequirement]:
return multiple_process_executor_requirements() if "multiprocess" in executor_config else []
@executor(
name="multi_or_in_process_executor",
config_schema=Field(
Selector(
{"multiprocess": MULTI_PROC_CONFIG, "in_process": IN_PROC_CONFIG},
),
default_value={"multiprocess": {}},
),
requirements=_get_default_executor_requirements,
)
def multi_or_in_process_executor(init_context: "InitExecutorContext") -> "Executor":
"""The default executor for a job.
This is the executor available by default on a :py:class:`JobDefinition`
that does not provide custom executors. This executor has a multiprocessing-enabled mode, and a
single-process mode. By default, multiprocessing mode is enabled. Switching between multiprocess
mode and in-process mode can be achieved via config.
.. code-block:: yaml
execution:
config:
multiprocess:
execution:
config:
in_process:
When using the multiprocess mode, ``max_concurrent`` and ``retries`` can also be configured.
.. code-block:: yaml
execution:
config:
multiprocess:
max_concurrent: 4
retries:
enabled:
The ``max_concurrent`` arg is optional and tells the execution engine how many processes may run
concurrently. By default, or if you set ``max_concurrent`` to be 0, this is the return value of
:py:func:`python:multiprocessing.cpu_count`.
When using the in_process mode, then only retries can be configured.
Execution priority can be configured using the ``dagster/priority`` tag via op metadata,
where the higher the number the higher the priority. 0 is the default and both positive
and negative numbers can be used.
"""
if "multiprocess" in init_context.executor_config:
return _core_multiprocess_executor_creation(
check.dict_elem(init_context.executor_config, "multiprocess")
)
else:
return _core_in_process_executor_creation(
check.dict_elem(init_context.executor_config, "in_process")
)
| _ExecutorDecoratorCallable |
python | redis__redis-py | redis/multidb/command_executor.py | {
"start": 1255,
"end": 2037
} | class ____(CommandExecutor):
def __init__(
self,
auto_fallback_interval: float = DEFAULT_AUTO_FALLBACK_INTERVAL,
):
self._auto_fallback_interval = auto_fallback_interval
self._next_fallback_attempt: datetime
@property
def auto_fallback_interval(self) -> float:
return self._auto_fallback_interval
@auto_fallback_interval.setter
def auto_fallback_interval(self, auto_fallback_interval: int) -> None:
self._auto_fallback_interval = auto_fallback_interval
def _schedule_next_fallback(self) -> None:
if self._auto_fallback_interval < 0:
return
self._next_fallback_attempt = datetime.now() + timedelta(
seconds=self._auto_fallback_interval
)
| BaseCommandExecutor |
python | Lightning-AI__lightning | tests/tests_fabric/helpers/dataloaders.py | {
"start": 1208,
"end": 1650
} | class ____(CustomInfDataloader):
def __len__(self):
"""Raise NotImplementedError."""
raise NotImplementedError
def __next__(self):
if self.count >= 2:
raise StopIteration
self.count = self.count + 1
try:
return next(self.iter)
except StopIteration:
self.iter = iter(self.dataloader)
return next(self.iter)
| CustomNotImplementedErrorDataloader |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_translate.py | {
"start": 36072,
"end": 37754
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.translate.TranslateHook")
def test_minimal_green_path(self, mock_hook):
DELETION_RESULT_SAMPLE = {
"submit_time": "2024-11-17T14:05:00Z",
"end_time": "2024-11-17T17:09:03Z",
"name": f"projects/{PROJECT_ID}/locations/{LOCATION}/glossaries/{GLOSSARY_ID}",
}
sample_operation = mock.MagicMock()
sample_operation.result.return_value = translation_service.DeleteGlossaryResponse(
DELETION_RESULT_SAMPLE
)
gl_delete_method = mock_hook.return_value.delete_glossary
gl_delete_method.return_value = sample_operation
mock_hook.return_value.wait_for_operation_result.side_effect = lambda operation: operation.result()
op = TranslateDeleteGlossaryOperator(
task_id="task_id",
glossary_id=GLOSSARY_ID,
project_id=PROJECT_ID,
location=LOCATION,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
timeout=TIMEOUT_VALUE,
retry=DEFAULT,
)
context = mock.MagicMock()
result = op.execute(context=context)
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
gl_delete_method.assert_called_once_with(
glossary_id=GLOSSARY_ID,
project_id=PROJECT_ID,
location=LOCATION,
timeout=TIMEOUT_VALUE,
retry=DEFAULT,
metadata=(),
)
assert result == DELETION_RESULT_SAMPLE
| TestTranslateDeleteGlossary |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 81624,
"end": 85587
} | class ____(MoeCausalLMOutputWithPast):
r"""
Args:
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
The rope index difference between sequence length and multimodal rope.
"""
rope_deltas: Optional[torch.LongTensor] = None
def load_balancing_loss_func(
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
num_experts: Optional[int] = None,
top_k=2,
attention_mask: Optional[torch.Tensor] = None,
) -> Union[torch.Tensor, int]:
r"""
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
experts is too unbalanced.
Args:
gate_logits:
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
shape [batch_size X sequence_length, num_experts].
num_experts:
Number of experts
top_k:
The number of experts to route per-token, can be also interpreted as the `top-k` routing
parameter.
attention_mask (`torch.Tensor`, *optional*):
The attention_mask used in forward function
shape [batch_size X sequence_length] if not None.
Returns:
The auxiliary loss.
"""
if gate_logits is None or not isinstance(gate_logits, tuple):
return 0
if isinstance(gate_logits, tuple):
compute_device = gate_logits[0].device
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
if attention_mask is None:
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.mean(routing_weights, dim=0)
else:
batch_size, sequence_length = attention_mask.shape
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
expert_attention_mask = (
attention_mask[None, :, :, None, None]
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
.reshape(-1, top_k, num_experts)
.to(compute_device)
)
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
expert_attention_mask, dim=0
)
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
router_per_expert_attention_mask = (
attention_mask[None, :, :, None]
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
.reshape(-1, num_experts)
.to(compute_device)
)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
router_per_expert_attention_mask, dim=0
)
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
return overall_loss * num_experts
@auto_docstring(
custom_intro="""
The Qwen2.5OmniThinker model which consists of a audio backbone and a language model.
"""
)
| Qwen3OmniMoeThinkerCausalLMOutputWithPast |
python | django__django | django/contrib/messages/storage/cookie.py | {
"start": 2238,
"end": 8678
} | class ____(BaseStorage):
"""
Store messages in a cookie.
"""
cookie_name = "messages"
# uwsgi's default configuration enforces a maximum size of 4kb for all the
# HTTP headers. In order to leave some room for other cookies and headers,
# restrict the session cookie to 1/2 of 4kb. See #18781.
max_cookie_size = 2048
not_finished = "__messagesnotfinished__"
not_finished_json = json.dumps("__messagesnotfinished__")
key_salt = "django.contrib.messages"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.signer = signing.get_cookie_signer(salt=self.key_salt)
def _get(self, *args, **kwargs):
"""
Retrieve a list of messages from the messages cookie. If the
not_finished sentinel value is found at the end of the message list,
remove it and return a result indicating that not all messages were
retrieved by this storage.
"""
data = self.request.COOKIES.get(self.cookie_name)
messages = self._decode(data)
all_retrieved = not (messages and messages[-1] == self.not_finished)
if messages and not all_retrieved:
# remove the sentinel value
messages.pop()
return messages, all_retrieved
def _update_cookie(self, encoded_data, response):
"""
Either set the cookie with the encoded data if there is any data to
store, or delete the cookie.
"""
if encoded_data:
response.set_cookie(
self.cookie_name,
encoded_data,
domain=settings.SESSION_COOKIE_DOMAIN,
secure=settings.SESSION_COOKIE_SECURE or None,
httponly=settings.SESSION_COOKIE_HTTPONLY or None,
samesite=settings.SESSION_COOKIE_SAMESITE,
)
else:
response.delete_cookie(
self.cookie_name,
domain=settings.SESSION_COOKIE_DOMAIN,
samesite=settings.SESSION_COOKIE_SAMESITE,
)
def _store(self, messages, response, remove_oldest=True, *args, **kwargs):
"""
Store the messages to a cookie and return a list of any messages which
could not be stored.
If the encoded data is larger than ``max_cookie_size``, remove
messages until the data fits (these are the messages which are
returned), and add the not_finished sentinel value to indicate as much.
"""
unstored_messages = []
serialized_messages = MessagePartSerializer().dumps(messages)
encoded_data = self._encode_parts(serialized_messages)
if self.max_cookie_size:
# data is going to be stored eventually by SimpleCookie, which
# adds its own overhead, which we must account for.
cookie = SimpleCookie() # create outside the loop
def is_too_large_for_cookie(data):
return data and len(cookie.value_encode(data)[1]) > self.max_cookie_size
def compute_msg(some_serialized_msg):
return self._encode_parts(
[*some_serialized_msg, self.not_finished_json],
encode_empty=True,
)
if is_too_large_for_cookie(encoded_data):
if remove_oldest:
idx = bisect_keep_right(
serialized_messages,
fn=lambda m: is_too_large_for_cookie(compute_msg(m)),
)
unstored_messages = messages[:idx]
encoded_data = compute_msg(serialized_messages[idx:])
else:
idx = bisect_keep_left(
serialized_messages,
fn=lambda m: is_too_large_for_cookie(compute_msg(m)),
)
unstored_messages = messages[idx:]
encoded_data = compute_msg(serialized_messages[:idx])
self._update_cookie(encoded_data, response)
return unstored_messages
def _encode_parts(self, messages, encode_empty=False):
"""
Return an encoded version of the serialized messages list which can be
stored as plain text.
Since the data will be retrieved from the client-side, the encoded data
also contains a hash to ensure that the data was not tampered with.
"""
if messages or encode_empty:
return self.signer.sign_object(
messages, serializer=MessagePartGatherSerializer, compress=True
)
def _encode(self, messages, encode_empty=False):
"""
Return an encoded version of the messages list which can be stored as
plain text.
Proxies MessagePartSerializer.dumps and _encoded_parts.
"""
serialized_messages = MessagePartSerializer().dumps(messages)
return self._encode_parts(serialized_messages, encode_empty=encode_empty)
def _decode(self, data):
"""
Safely decode an encoded text stream back into a list of messages.
If the encoded text stream contained an invalid hash or was in an
invalid format, return None.
"""
if not data:
return None
try:
return self.signer.unsign_object(data, serializer=MessageSerializer)
except (signing.BadSignature, binascii.Error, json.JSONDecodeError):
pass
# Mark the data as used (so it gets removed) since something was wrong
# with the data.
self.used = True
return None
def bisect_keep_left(a, fn):
"""
Find the index of the first element from the start of the array that
verifies the given condition.
The function is applied from the start of the array to the pivot.
"""
lo = 0
hi = len(a)
while lo < hi:
mid = (lo + hi) // 2
if fn(a[: mid + 1]):
hi = mid
else:
lo = mid + 1
return lo
def bisect_keep_right(a, fn):
"""
Find the index of the first element from the end of the array that verifies
the given condition.
The function is applied from the pivot to the end of array.
"""
lo = 0
hi = len(a)
while lo < hi:
mid = (lo + hi) // 2
if fn(a[mid:]):
lo = mid + 1
else:
hi = mid
return lo
| CookieStorage |
python | sanic-org__sanic | sanic/http/http1.py | {
"start": 763,
"end": 21365
} | class ____(Stream, metaclass=TouchUpMeta):
""" "Internal helper for managing the HTTP/1.1 request/response cycle.
Raises:
BadRequest: If the request body is malformed.
Exception: If the request is malformed.
ExpectationFailed: If the request is malformed.
PayloadTooLarge: If the request body exceeds the size limit.
RuntimeError: If the response status is invalid.
ServerError: If the handler does not produce a response.
ServerError: If the response is bigger than the content-length.
"""
HEADER_CEILING = 16_384
HEADER_MAX_SIZE = 0
__touchup__ = (
"http1_request_header",
"http1_response_header",
"read",
)
__slots__ = [
"_send",
"_receive_more",
"dispatch",
"recv_buffer",
"protocol",
"expecting_continue",
"stage",
"keep_alive",
"head_only",
"request",
"exception",
"url",
"request_body",
"request_bytes",
"request_bytes_left",
"response",
"response_func",
"response_size",
"response_bytes_left",
"upgrade_websocket",
"perft0",
]
def __init__(self, protocol):
self._send = protocol.send
self._receive_more = protocol.receive_more
self.recv_buffer = protocol.recv_buffer
self.protocol = protocol
self.keep_alive = True
self.stage: Stage = Stage.IDLE
self.dispatch = self.protocol.app.dispatch
def init_for_request(self):
"""Init/reset all per-request variables."""
self.exception = None
self.expecting_continue: bool = False
self.head_only = None
self.request_body = None
self.request_bytes = None
self.request_bytes_left = None
self.request_max_size = self.protocol.request_max_size
self.request: Request = None
self.response: BaseHTTPResponse = None
self.upgrade_websocket = False
self.url = None
self.perft0 = None
def __bool__(self):
"""Test if request handling is in progress"""
return self.stage in (Stage.HANDLER, Stage.RESPONSE)
async def http1(self):
"""HTTP 1.1 connection handler"""
# Handle requests while the connection stays reusable
while self.keep_alive and self.stage is Stage.IDLE:
self.init_for_request()
# Wait for incoming bytes (in IDLE stage)
if not self.recv_buffer:
await self._receive_more()
self.stage = Stage.REQUEST
try:
# Receive and handle a request
self.response_func = self.http1_response_header
await self.http1_request_header()
self.stage = Stage.HANDLER
self.perft0 = perf_counter()
self.request.conn_info = self.protocol.conn_info
await self.protocol.request_handler(self.request)
# Handler finished, response should've been sent
if self.stage is Stage.HANDLER and not self.upgrade_websocket:
raise ServerError("Handler produced no response")
if self.stage is Stage.RESPONSE:
await self.response.send(end_stream=True)
except CancelledError as exc:
# Write an appropriate response before exiting
if not self.protocol.transport:
logger.info(
f"Request: {self.request.method} {self.request.url} "
"stopped. Transport is closed."
)
return
e = (
RequestCancelled()
if self.protocol.conn_info.lost
else (self.exception or exc)
)
self.exception = None
self.keep_alive = False
await self.error_response(e)
except Exception as e:
# Write an error response
await self.error_response(e)
# Try to consume any remaining request body
if self.request_body:
if self.response and 200 <= self.response.status < 300:
error_logger.error(f"{self.request} body not consumed.")
# Limit the size because the handler may have set it infinite
self.request_max_size = min(
self.request_max_size, self.protocol.request_max_size
)
try:
async for _ in self:
pass
except PayloadTooLarge:
# We won't read the body and that may cause httpx and
# tests to fail. This little delay allows clients to push
# a small request into network buffers before we close the
# socket, so that they are then able to read the response.
await sleep(0.001)
self.keep_alive = False
# Clean up to free memory and for the next request
if self.request:
self.request.stream = None
if self.response:
self.response.stream = None
async def http1_request_header(self): # no cov
"""Receive and parse request header into self.request."""
# Receive until full header is in buffer
buf = self.recv_buffer
pos = 0
while True:
pos = buf.find(b"\r\n\r\n", pos)
if pos != -1:
break
pos = max(0, len(buf) - 3)
if pos >= self.HEADER_MAX_SIZE:
break
await self._receive_more()
if pos >= self.HEADER_MAX_SIZE:
raise PayloadTooLarge("Request header exceeds the size limit")
# Parse header content
try:
head = buf[:pos]
raw_headers = head.decode(errors="surrogateescape")
reqline, *split_headers = raw_headers.split("\r\n")
method, self.url, protocol = reqline.split(" ")
await self.dispatch(
"http.lifecycle.read_head",
inline=True,
context={"head": bytes(head)},
)
if protocol == "HTTP/1.1":
self.keep_alive = True
elif protocol == "HTTP/1.0":
self.keep_alive = False
else:
raise Exception # Raise a Bad Request on try-except
self.head_only = method.upper() == "HEAD"
request_body = False
headers = []
for name, value in (h.split(":", 1) for h in split_headers):
name, value = h = name.lower(), value.lstrip()
if name in ("content-length", "transfer-encoding"):
if request_body:
raise ValueError(
"Duplicate Content-Length or Transfer-Encoding"
)
request_body = True
elif name == "connection":
self.keep_alive = value.lower() == "keep-alive"
headers.append(h)
except Exception:
raise BadRequest("Bad Request")
headers_instance = Header(headers)
self.upgrade_websocket = (
headers_instance.getone("upgrade", "").lower() == "websocket"
)
try:
url_bytes = self.url.encode("ASCII")
except UnicodeEncodeError:
raise BadRequest("URL may only contain US-ASCII characters.")
# Prepare a Request object
request = self.protocol.request_class(
url_bytes=url_bytes,
headers=headers_instance,
head=bytes(head),
version=protocol[5:],
method=method,
transport=self.protocol.transport,
app=self.protocol.app,
)
self.protocol.request_class._current.set(request)
await self.dispatch(
"http.lifecycle.request",
inline=True,
context={"request": request},
)
# Prepare for request body
self.request_bytes_left = self.request_bytes = 0
if request_body:
headers = request.headers
expect = headers.getone("expect", None)
if expect is not None:
if expect.lower() == "100-continue":
self.expecting_continue = True
else:
raise ExpectationFailed(f"Unknown Expect: {expect}")
if headers.getone("transfer-encoding", None) == "chunked":
self.request_body = "chunked"
pos -= 2 # One CRLF stays in buffer
else:
self.request_body = True
try:
self.request_bytes_left = self.request_bytes = (
self._safe_int(headers["content-length"])
)
except Exception:
raise BadRequest("Bad content-length")
# Remove header and its trailing CRLF
del buf[: pos + 4]
self.request, request.stream = request, self
self.protocol.state["requests_count"] += 1
async def http1_response_header(
self, data: bytes, end_stream: bool
) -> None: # no cov
"""Format response header and send it."""
res = self.response
# Compatibility with simple response body
if not data and getattr(res, "body", None):
data, end_stream = res.body, True # type: ignore
size = len(data)
headers = res.headers
status = res.status
self.response_size = size
if not isinstance(status, int) or status < 200:
raise RuntimeError(f"Invalid response status {status!r}")
if not has_message_body(status):
# Header-only response status
self.response_func = None
if (
data
or not end_stream
or "content-length" in headers
or "transfer-encoding" in headers
):
data, size, end_stream = b"", 0, True
headers.pop("content-length", None)
headers.pop("transfer-encoding", None)
logger.warning(
f"Message body set in response on {self.request.path}. "
f"A {status} response may only have headers, no body."
)
elif self.head_only and "content-length" in headers:
self.response_func = None
elif end_stream:
# Non-streaming response (all in one block)
headers["content-length"] = size
self.response_func = None
elif "content-length" in headers:
# Streaming response with size known in advance
self.response_bytes_left = int(headers["content-length"]) - size
self.response_func = self.http1_response_normal
else:
# Length not known, use chunked encoding
headers["transfer-encoding"] = "chunked"
data = b"%x\r\n%b\r\n" % (size, data) if size else b""
self.response_func = self.http1_response_chunked
if self.head_only:
# Head request: don't send body
data = b""
self.response_func = self.head_response_ignored
headers["connection"] = "keep-alive" if self.keep_alive else "close"
# This header may be removed or modified by the AltSvcCheck Touchup
# service. At server start, we either remove this header from ever
# being assigned, or we change the value as required.
headers["alt-svc"] = ""
ret = format_http1_response(status, res.processed_headers)
if data:
ret += data
# Send a 100-continue if expected and not Expectation Failed
if self.expecting_continue:
self.expecting_continue = False
if status != 417:
ret = HTTP_CONTINUE + ret
# Send response
if self.protocol.access_log:
self.log_response()
await self._send(ret)
self.stage = Stage.IDLE if end_stream else Stage.RESPONSE
def head_response_ignored(self, data: bytes, end_stream: bool) -> None:
"""HEAD response: body data silently ignored."""
if end_stream:
self.response_func = None
self.stage = Stage.IDLE
async def http1_response_chunked(
self, data: bytes, end_stream: bool
) -> None:
"""Format a part of response body in chunked encoding."""
# Chunked encoding
size = len(data)
if end_stream:
await self._send(
b"%x\r\n%b\r\n0\r\n\r\n" % (size, data)
if size
else b"0\r\n\r\n"
)
self.response_func = None
self.stage = Stage.IDLE
elif size:
await self._send(b"%x\r\n%b\r\n" % (size, data))
async def http1_response_normal(
self, data: bytes, end_stream: bool
) -> None:
"""Format / keep track of non-chunked response."""
bytes_left = self.response_bytes_left - len(data)
if bytes_left <= 0:
if bytes_left < 0:
raise ServerError("Response was bigger than content-length")
await self._send(data)
self.response_func = None
self.stage = Stage.IDLE
else:
if end_stream:
raise ServerError("Response was smaller than content-length")
await self._send(data)
self.response_bytes_left = bytes_left
async def error_response(self, exception: Exception) -> None:
"""Handle response when exception encountered"""
# Disconnect after an error if in any other state than handler
if self.stage is not Stage.HANDLER:
self.keep_alive = False
# Request failure? Respond but then disconnect
if self.stage is Stage.REQUEST:
self.stage = Stage.HANDLER
# From request and handler states we can respond, otherwise be silent
if self.stage is Stage.HANDLER:
app = self.protocol.app
if self.request is None:
self.create_empty_request()
request_middleware = not isinstance(
exception, (ServiceUnavailable, RequestCancelled)
)
try:
await app.handle_exception(
self.request, exception, request_middleware
)
except Exception as e:
await app.handle_exception(self.request, e, False)
def create_empty_request(self) -> None:
"""Create an empty request object for error handling use.
Current error handling code needs a request object that won't exist
if an error occurred during before a request was received. Create a
bogus response for error handling use.
"""
# Reformat any URL already received with \xHH escapes for better logs
url_bytes = (
self.url.encode(errors="surrogateescape")
.decode("ASCII", errors="backslashreplace")
.encode("ASCII")
if self.url
else b"*"
)
# FIXME: Avoid this by refactoring error handling and response code
self.request = self.protocol.request_class(
url_bytes=url_bytes,
headers=Header({}),
version="1.1",
method="NONE",
transport=self.protocol.transport,
app=self.protocol.app,
)
self.request.stream = self
def log_response(self) -> None:
"""Helper method provided to enable the logging of responses in case if the `HttpProtocol.access_log` is enabled.""" # noqa: E501
req, res = self.request, self.response
extra = {
"status": getattr(res, "status", 0),
"byte": res.headers.get("content-length", 0)
if res.headers.get("transfer-encoding") != "chunked"
else "chunked",
"host": f"{id(self.protocol.transport):X}"[-5:-1] + "unx",
"request": "nil",
"duration": (
f" {1000 * (perf_counter() - self.perft0):.1f}ms"
if self.perft0 is not None
else ""
),
}
if ip := req.client_ip:
extra["host"] = f"{ip}:{req.port}"
extra["request"] = f"{req.method} {req.url}"
access_logger.info("", extra=extra)
# Request methods
async def __aiter__(self):
"""Async iterate over request body."""
while self.request_body:
data = await self.read()
if data:
yield data
async def read(self) -> Optional[bytes]: # no cov
"""Read some bytes of request body."""
# Send a 100-continue if needed
if self.expecting_continue:
self.expecting_continue = False
await self._send(HTTP_CONTINUE)
# Receive request body chunk
buf = self.recv_buffer
if self.request_bytes_left == 0 and self.request_body == "chunked":
# Process a chunk header: \r\n<size>[;<chunk extensions>]\r\n
while True:
pos = buf.find(b"\r\n", 3)
if pos != -1:
break
if len(buf) > 64:
self.keep_alive = False
raise BadRequest("Bad chunked encoding")
await self._receive_more()
try:
raw = buf[2:pos].split(b";", 1)[0].decode()
size = self._safe_int(raw, 16)
except Exception:
self.keep_alive = False
raise BadRequest("Bad chunked encoding")
if size <= 0:
self.request_body = None
if size < 0:
self.keep_alive = False
raise BadRequest("Bad chunked encoding")
# Consume CRLF, chunk size 0 and the two CRLF that follow
pos += 4
# Might need to wait for the final CRLF
while len(buf) < pos:
await self._receive_more()
del buf[:pos]
return None
# Remove CRLF, chunk size and the CRLF that follows
del buf[: pos + 2]
self.request_bytes_left = size
self.request_bytes += size
# Request size limit
if self.request_bytes > self.request_max_size:
self.keep_alive = False
raise PayloadTooLarge("Request body exceeds the size limit")
# End of request body?
if not self.request_bytes_left:
self.request_body = None
return None
# At this point we are good to read/return up to request_bytes_left
if not buf:
await self._receive_more()
data = bytes(buf[: self.request_bytes_left])
size = len(data)
del buf[:size]
self.request_bytes_left -= size
await self.dispatch(
"http.lifecycle.read_body",
inline=True,
context={"body": data},
)
return data
# Response methods
def respond(self, response: BaseHTTPResponse) -> BaseHTTPResponse:
"""Initiate new streaming response.
Nothing is sent until the first send() call on the returned object, and
calling this function multiple times will just alter the response to be
given.
"""
if self.stage is not Stage.HANDLER:
self.stage = Stage.FAILED
raise RuntimeError("Response already started")
# Disconnect any earlier but unused response object
if self.response is not None:
self.response.stream = None
# Connect and return the response
self.response, response.stream = response, self
return response
@property
def send(self):
return self.response_func
@classmethod
def set_header_max_size(cls, *sizes: int):
cls.HEADER_MAX_SIZE = min(
*sizes,
cls.HEADER_CEILING,
)
@staticmethod
def _safe_int(value: str, base: int = 10) -> int:
if "-" in value or "+" in value or "_" in value:
raise ValueError
return int(value, base)
| Http |
python | pandas-dev__pandas | pandas/tests/indexes/numeric/test_indexing.py | {
"start": 3203,
"end": 15986
} | class ____:
def test_get_indexer(self):
index1 = Index([1, 2, 3, 4, 5])
index2 = Index([2, 4, 6])
r1 = index1.get_indexer(index2)
e1 = np.array([1, 3, -1], dtype=np.intp)
tm.assert_almost_equal(r1, e1)
@pytest.mark.parametrize("reverse", [True, False])
@pytest.mark.parametrize(
"expected,method",
[
([-1, 0, 0, 1, 1], "pad"),
([-1, 0, 0, 1, 1], "ffill"),
([0, 0, 1, 1, 2], "backfill"),
([0, 0, 1, 1, 2], "bfill"),
],
)
def test_get_indexer_methods(self, reverse, expected, method):
index1 = Index([1, 2, 3, 4, 5])
index2 = Index([2, 4, 6])
expected = np.array(expected, dtype=np.intp)
if reverse:
index1 = index1[::-1]
expected = expected[::-1]
result = index2.get_indexer(index1, method=method)
tm.assert_almost_equal(result, expected)
def test_get_indexer_invalid(self):
# GH10411
index = Index(np.arange(10))
with pytest.raises(ValueError, match="tolerance argument"):
index.get_indexer([1, 0], tolerance=1)
with pytest.raises(ValueError, match="limit argument"):
index.get_indexer([1, 0], limit=1)
@pytest.mark.parametrize(
"method, tolerance, indexer, expected",
[
("pad", None, [0, 5, 9], [0, 5, 9]),
("backfill", None, [0, 5, 9], [0, 5, 9]),
("nearest", None, [0, 5, 9], [0, 5, 9]),
("pad", 0, [0, 5, 9], [0, 5, 9]),
("backfill", 0, [0, 5, 9], [0, 5, 9]),
("nearest", 0, [0, 5, 9], [0, 5, 9]),
("pad", None, [0.2, 1.8, 8.5], [0, 1, 8]),
("backfill", None, [0.2, 1.8, 8.5], [1, 2, 9]),
("nearest", None, [0.2, 1.8, 8.5], [0, 2, 9]),
("pad", 1, [0.2, 1.8, 8.5], [0, 1, 8]),
("backfill", 1, [0.2, 1.8, 8.5], [1, 2, 9]),
("nearest", 1, [0.2, 1.8, 8.5], [0, 2, 9]),
("pad", 0.2, [0.2, 1.8, 8.5], [0, -1, -1]),
("backfill", 0.2, [0.2, 1.8, 8.5], [-1, 2, -1]),
("nearest", 0.2, [0.2, 1.8, 8.5], [0, 2, -1]),
],
)
def test_get_indexer_nearest(self, method, tolerance, indexer, expected):
index = Index(np.arange(10))
actual = index.get_indexer(indexer, method=method, tolerance=tolerance)
tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
@pytest.mark.parametrize("listtype", [list, tuple, Series, np.array])
@pytest.mark.parametrize(
"tolerance, expected",
[
[[0.3, 0.3, 0.1], [0, 2, -1]],
[[0.2, 0.1, 0.1], [0, -1, -1]],
[[0.1, 0.5, 0.5], [-1, 2, 9]],
],
)
def test_get_indexer_nearest_listlike_tolerance(
self, tolerance, expected, listtype
):
index = Index(np.arange(10))
actual = index.get_indexer(
[0.2, 1.8, 8.5], method="nearest", tolerance=listtype(tolerance)
)
tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
def test_get_indexer_nearest_error(self):
index = Index(np.arange(10))
with pytest.raises(ValueError, match="limit argument"):
index.get_indexer([1, 0], method="nearest", limit=1)
with pytest.raises(ValueError, match="tolerance size must match"):
index.get_indexer([1, 0], method="nearest", tolerance=[1, 2, 3])
@pytest.mark.parametrize(
"method,expected",
[("pad", [8, 7, 0]), ("backfill", [9, 8, 1]), ("nearest", [9, 7, 0])],
)
def test_get_indexer_nearest_decreasing(self, method, expected):
index = Index(np.arange(10))[::-1]
actual = index.get_indexer([0, 5, 9], method=method)
tm.assert_numpy_array_equal(actual, np.array([9, 4, 0], dtype=np.intp))
actual = index.get_indexer([0.2, 1.8, 8.5], method=method)
tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))
@pytest.mark.parametrize("idx_dtype", ["int64", "float64", "uint64", "range"])
@pytest.mark.parametrize("method", ["get_indexer", "get_indexer_non_unique"])
def test_get_indexer_numeric_index_boolean_target(self, method, idx_dtype):
# GH 16877
if idx_dtype == "range":
numeric_index = RangeIndex(4)
else:
numeric_index = Index(np.arange(4, dtype=idx_dtype))
other = Index([True, False, True])
result = getattr(numeric_index, method)(other)
expected = np.array([-1, -1, -1], dtype=np.intp)
if method == "get_indexer":
tm.assert_numpy_array_equal(result, expected)
else:
missing = np.arange(3, dtype=np.intp)
tm.assert_numpy_array_equal(result[0], expected)
tm.assert_numpy_array_equal(result[1], missing)
@pytest.mark.parametrize("method", ["pad", "backfill", "nearest"])
def test_get_indexer_with_method_numeric_vs_bool(self, method):
left = Index([1, 2, 3])
right = Index([True, False])
with pytest.raises(TypeError, match="Cannot compare"):
left.get_indexer(right, method=method)
with pytest.raises(TypeError, match="Cannot compare"):
right.get_indexer(left, method=method)
def test_get_indexer_numeric_vs_bool(self):
left = Index([1, 2, 3])
right = Index([True, False])
res = left.get_indexer(right)
expected = -1 * np.ones(len(right), dtype=np.intp)
tm.assert_numpy_array_equal(res, expected)
res = right.get_indexer(left)
expected = -1 * np.ones(len(left), dtype=np.intp)
tm.assert_numpy_array_equal(res, expected)
res = left.get_indexer_non_unique(right)[0]
expected = -1 * np.ones(len(right), dtype=np.intp)
tm.assert_numpy_array_equal(res, expected)
res = right.get_indexer_non_unique(left)[0]
expected = -1 * np.ones(len(left), dtype=np.intp)
tm.assert_numpy_array_equal(res, expected)
def test_get_indexer_float64(self):
idx = Index([0.0, 1.0, 2.0], dtype=np.float64)
tm.assert_numpy_array_equal(
idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)
)
target = [-0.1, 0.5, 1.1]
tm.assert_numpy_array_equal(
idx.get_indexer(target, "pad"), np.array([-1, 0, 1], dtype=np.intp)
)
tm.assert_numpy_array_equal(
idx.get_indexer(target, "backfill"), np.array([0, 1, 2], dtype=np.intp)
)
tm.assert_numpy_array_equal(
idx.get_indexer(target, "nearest"), np.array([0, 1, 1], dtype=np.intp)
)
def test_get_indexer_nan(self):
# GH#7820
result = Index([1, 2, np.nan], dtype=np.float64).get_indexer([np.nan])
expected = np.array([2], dtype=np.intp)
tm.assert_numpy_array_equal(result, expected)
def test_get_indexer_int64(self):
index = Index(range(0, 20, 2), dtype=np.int64)
target = Index(np.arange(10), dtype=np.int64)
indexer = index.get_indexer(target)
expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
target = Index(np.arange(10), dtype=np.int64)
indexer = index.get_indexer(target, method="pad")
expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
target = Index(np.arange(10), dtype=np.int64)
indexer = index.get_indexer(target, method="backfill")
expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
def test_get_indexer_uint64(self):
index_large = Index(
[2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25],
dtype=np.uint64,
)
target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
indexer = index_large.get_indexer(target)
expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
indexer = index_large.get_indexer(target, method="pad")
expected = np.array([0, 0, 1, 2, 3, 4, 4, 4, 4, 4], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
target = Index(np.arange(10).astype("uint64") * 5 + 2**63)
indexer = index_large.get_indexer(target, method="backfill")
expected = np.array([0, 1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)
tm.assert_numpy_array_equal(indexer, expected)
@pytest.mark.parametrize("val, val2", [(4, 5), (4, 4), (4, NA), (NA, NA)])
def test_get_loc_masked(self, val, val2, any_numeric_ea_and_arrow_dtype):
# GH#39133
idx = Index([1, 2, 3, val, val2], dtype=any_numeric_ea_and_arrow_dtype)
result = idx.get_loc(2)
assert result == 1
with pytest.raises(KeyError, match="9"):
idx.get_loc(9)
def test_get_loc_masked_na(self, any_numeric_ea_and_arrow_dtype):
# GH#39133
idx = Index([1, 2, NA], dtype=any_numeric_ea_and_arrow_dtype)
result = idx.get_loc(NA)
assert result == 2
idx = Index([1, 2, NA, NA], dtype=any_numeric_ea_and_arrow_dtype)
result = idx.get_loc(NA)
tm.assert_numpy_array_equal(result, np.array([False, False, True, True]))
idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype)
with pytest.raises(KeyError, match="NA"):
idx.get_loc(NA)
def test_get_loc_masked_na_and_nan(self, using_nan_is_na):
# GH#39133
mask = np.array([False, False, True, False])
if using_nan_is_na:
mask[-1] = True
idx = Index(FloatingArray(np.array([1, 2, 1, np.nan]), mask=mask))
if using_nan_is_na:
# NaN and NA are consistently treated as the same
result = idx.get_loc(NA)
expected = np.array([False, False, True, True])
tm.assert_numpy_array_equal(result, expected)
result = idx.get_loc(np.nan)
tm.assert_numpy_array_equal(result, expected)
else:
result = idx.get_loc(NA)
assert result == 2
result = idx.get_loc(np.nan)
assert result == 3
idx = Index(
FloatingArray(np.array([1, 2, 1.0]), mask=np.array([False, False, True]))
)
result = idx.get_loc(NA)
assert result == 2
if using_nan_is_na:
result = idx.get_loc(np.nan)
assert result == 2
else:
with pytest.raises(KeyError, match="nan"):
idx.get_loc(np.nan)
mask = np.array([False, False, False])
if using_nan_is_na:
mask[-1] = True
idx = Index(FloatingArray(np.array([1, 2, np.nan]), mask=mask))
result = idx.get_loc(np.nan)
assert result == 2
if using_nan_is_na:
result = idx.get_loc(NA)
assert result == 2
else:
with pytest.raises(KeyError, match="NA"):
idx.get_loc(NA)
@pytest.mark.parametrize("val", [4, 2])
def test_get_indexer_masked_na(self, any_numeric_ea_and_arrow_dtype, val):
# GH#39133
idx = Index([1, 2, NA, 3, val], dtype=any_numeric_ea_and_arrow_dtype)
result = idx.get_indexer_for([1, NA, 5])
expected = np.array([0, 2, -1])
tm.assert_numpy_array_equal(result, expected, check_dtype=False)
@pytest.mark.parametrize("dtype", ["boolean", "bool[pyarrow]"])
def test_get_indexer_masked_na_boolean(self, dtype):
# GH#39133
if dtype == "bool[pyarrow]":
pytest.importorskip("pyarrow")
idx = Index([True, False, NA], dtype=dtype)
result = idx.get_loc(False)
assert result == 1
result = idx.get_loc(NA)
assert result == 2
def test_get_indexer_arrow_dictionary_target(self):
pa = pytest.importorskip("pyarrow")
target = Index(
ArrowExtensionArray(
pa.array([1, 2], type=pa.dictionary(pa.int8(), pa.int8()))
)
)
idx = Index([1])
result = idx.get_indexer(target)
expected = np.array([0, -1], dtype=np.int64)
tm.assert_numpy_array_equal(result, expected)
result_1, result_2 = idx.get_indexer_non_unique(target)
expected_1, expected_2 = (
np.array([0, -1], dtype=np.int64),
np.array([1], dtype=np.int64),
)
tm.assert_numpy_array_equal(result_1, expected_1)
tm.assert_numpy_array_equal(result_2, expected_2)
| TestGetIndexer |
python | spack__spack | lib/spack/spack/util/gcs.py | {
"start": 7464,
"end": 7552
} | class ____(BaseHandler):
def gs_open(self, req):
return gcs_open(req)
| GCSHandler |
python | django__django | tests/model_meta/tests.py | {
"start": 8854,
"end": 9246
} | class ____(SimpleTestCase):
def test_string(self):
# Clear cached property.
Relation._meta.__dict__.pop("verbose_name_raw", None)
self.assertEqual(Relation._meta.verbose_name_raw, "relation")
def test_gettext(self):
Person._meta.__dict__.pop("verbose_name_raw", None)
self.assertEqual(Person._meta.verbose_name_raw, "Person")
| VerboseNameRawTests |
python | walkccc__LeetCode | solutions/1551. Minimum Operations to Make Array Equal/1551.py | {
"start": 0,
"end": 690
} | class ____:
def minOperations(self, n: int) -> int:
def arr(self, i: int) -> int:
"""Returns the i-th element of `arr`, where 1 <= i <= n."""
return (i - 1) * 2 + 1
# median := median of arr
# diffs[i] := median - arr[i] where i <= i <= n // 2
# ans := sum(diffs)
# e.g.
# n = 5, arr = [1, 3, 5, 7, 9], diffs = [4, 2]
# ans = (4 + 2) * 2 // 2 = 6
# n = 6, arr = [1, 3, 5, 7, 9, 11], diffs = [5, 3, 1]
# ans = (5 + 1) * 3 // 2 = 9
halfSize = n // 2
median = (arr(n) + arr(1)) // 2
firstDiff = median - arr(1)
lastDiff = median - arr(halfSize)
return (firstDiff + lastDiff) * halfSize // 2
| Solution |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 14911,
"end": 15637
} | class ____(models.Model):
char_field = models.CharField(max_length=10)
integer_field = models.IntegerField()
foreign_key_field = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
def has_self_only(self):
pass
def has_one_extra_argument(self, arg_one):
pass
def has_two_extra_arguments(self, arg_one, arg_two):
pass
def has_args_kwargs(self, *args, **kwargs):
pass
def has_defaults(self, one=1, two="Two", true=True, false=False, none=None):
pass
class Meta:
app_label = "django_extensions"
def dummy_handler(sender, instance, **kwargs):
pass
pre_save.connect(dummy_handler, sender=HasOwnerModel)
| MultipleFieldsAndMethods |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 634359,
"end": 634676
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("Sponsorship", graphql_name="node")
| SponsorshipEdge |
python | weaviate__weaviate-python-client | weaviate/cluster/replicate/async_.py | {
"start": 179,
"end": 248
} | class ____(_ReplicateExecutor[ConnectionAsync]):
pass
| _ReplicateAsync |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1523513,
"end": 1523892
} | class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, TeamAuditEntryData):
"""Audit log entry for a team.add_member event."""
__schema__ = github_schema
__field_names__ = ("is_ldap_mapped",)
is_ldap_mapped = sgqlc.types.Field(Boolean, graphql_name="isLdapMapped")
"""Whether the team was mapped to an LDAP Group."""
| TeamAddMemberAuditEntry |
python | scipy__scipy | scipy/stats/tests/test_discrete_distns.py | {
"start": 26622,
"end": 27016
} | class ____:
def test_gh19759(self):
# test zero PMF values within the support reported by gh-19759
a = -354
max_range = abs(a)
all_b_1 = [a + 2 ** 31 + i for i in range(max_range)]
res = randint.pmf(325, a, all_b_1)
assert (res > 0).all()
ref = 1 / (np.asarray(all_b_1, dtype=np.float64) - a)
assert_allclose(res, ref)
| TestRandInt |
python | has2k1__plotnine | plotnine/_utils/yippie.py | {
"start": 1566,
"end": 1944
} | class ____:
"""
Position Legends
"""
@property
def left(self):
return theme(legend_position="left")
@property
def bottom(self):
return theme(legend_position="bottom")
@property
def right(self):
return theme(legend_position="right")
@property
def top(self):
return theme(legend_position="top")
| _Legend |
python | FactoryBoy__factory_boy | factory/errors.py | {
"start": 224,
"end": 321
} | class ____(FactoryError):
"""Raised when a factory uses an unknown strategy."""
| UnknownStrategy |
python | neetcode-gh__leetcode | python/1091-shortest-path-in-binary-matrix.py | {
"start": 0,
"end": 730
} | class ____:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
N = len(grid)
q = deque([(0, 0, 1)]) # r, c, length
visit = set((0, 0))
direct = [[0, 1], [1, 0], [0, -1], [-1, 0],
[1, 1], [-1, -1], [1, -1], [-1, 1]]
while q:
r, c, length = q.popleft()
if (min(r, c) < 0 or max(r, c) >= N or
grid[r][c]):
continue
if r == N - 1 and c == N - 1:
return length
for dr, dc in direct:
if (r + dr, c + dc) not in visit:
q.append((r + dr, c + dc, length + 1))
visit.add((r + dr, c + dc))
return -1
| Solution |
python | Textualize__textual | tests/css/test_screen_css.py | {
"start": 418,
"end": 774
} | class ____(Screen):
SCOPED_CSS = False
CSS = """
#screen-css {
background: #ff0000;
}
"""
CSS_PATH = "test_screen_css.tcss"
def compose(self):
yield Label("Hello, world!", id="app-css")
yield Label("Hello, world!", id="screen-css-path")
yield Label("Hello, world!", id="screen-css")
| ScreenWithCSS |
python | huggingface__transformers | src/transformers/models/sam2_video/modeling_sam2_video.py | {
"start": 18274,
"end": 20696
} | class ____(nn.Module):
"""
SAM2_VIDEO's attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and
values.
"""
def __init__(self, config, downsample_rate=None):
super().__init__()
downsample_rate = config.attention_downsample_rate if downsample_rate is None else downsample_rate
self.config = config
self.hidden_size = config.hidden_size
self.internal_dim = config.hidden_size // downsample_rate
self.num_attention_heads = config.num_attention_heads
self.head_dim = self.internal_dim // config.num_attention_heads
self.scaling = self.head_dim**-0.5
self.is_causal = False
self.q_proj = nn.Linear(self.hidden_size, self.internal_dim)
self.k_proj = nn.Linear(self.hidden_size, self.internal_dim)
self.v_proj = nn.Linear(self.hidden_size, self.internal_dim)
self.o_proj = nn.Linear(self.internal_dim, self.hidden_size)
def forward(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_similarity: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor, torch.Tensor]:
# Input projections
batch_size, point_batch_size = query.shape[:2]
new_shape = (batch_size * point_batch_size, -1, self.num_attention_heads, self.head_dim)
query = self.q_proj(query).view(*new_shape).transpose(1, 2)
key = self.k_proj(key).view(*new_shape).transpose(1, 2)
value = self.v_proj(value).view(*new_shape).transpose(1, 2)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query,
key,
value,
attention_mask=attention_similarity,
dropout=0.0,
scaling=self.scaling,
is_causal=self.is_causal,
**kwargs,
)
attn_output = attn_output.reshape(
batch_size, point_batch_size, -1, self.num_attention_heads * self.head_dim
).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| Sam2VideoAttention |
python | getsentry__sentry | src/sentry/preprod/migrations/0011_add_preprod_artifact_app_name_and_app_id_fields.py | {
"start": 155,
"end": 1661
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = False
dependencies = [
("preprod", "0010_actual_drop_preprod_artifact_analysis_file_id_col"),
]
operations = [
migrations.AddField(
model_name="preprodartifact",
name="app_id",
field=models.CharField(max_length=255, null=True),
),
migrations.AddField(
model_name="preprodartifact",
name="app_name",
field=models.CharField(max_length=255, null=True),
),
]
| Migration |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-document360/llama_index/readers/document360/entities/article_slim.py | {
"start": 181,
"end": 600
} | class ____(BaseModel):
id: Optional[str]
title: Optional[str]
modified_at: Optional[str]
public_version: Optional[int]
latest_version: Optional[int]
language_code: Optional[str]
hidden: Optional[bool]
status: Optional[int]
order: Optional[int]
slug: Optional[str]
content_type: Optional[int]
translation_option: Optional[int]
is_shared_article: Optional[bool]
| ArticleSlim |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 87528,
"end": 88264
} | class ____(nn.Module):
"""
RepVGG architecture block introduced by the work "RepVGG: Making VGG-style ConvNets Great Again".
"""
def __init__(self, config: DFineConfig, in_channels: int, out_channels: int):
super().__init__()
activation = config.activation_function
hidden_channels = in_channels
self.conv1 = DFineConvNormLayer(config, hidden_channels, out_channels, 3, 1, padding=1)
self.conv2 = DFineConvNormLayer(config, hidden_channels, out_channels, 1, 1, padding=0)
self.activation = nn.Identity() if activation is None else ACT2CLS[activation]()
def forward(self, x):
y = self.conv1(x) + self.conv2(x)
return self.activation(y)
| DFineRepVggBlock |
python | getsentry__sentry | src/sentry/core/endpoints/organization_member_utils.py | {
"start": 2088,
"end": 2165
} | class ____(serializers.ValidationError):
pass
| MemberConflictValidationError |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/ir.py | {
"start": 98603,
"end": 99416
} | class ____(IR):
"""Filter a dataframe with a boolean mask."""
__slots__ = ("mask",)
_non_child = ("schema", "mask")
mask: expr.NamedExpr
"""Expression to produce the filter mask."""
def __init__(self, schema: Schema, mask: expr.NamedExpr, df: IR):
self.schema = schema
self.mask = mask
self._non_child_args = (mask,)
self.children = (df,)
@classmethod
@log_do_evaluate
@nvtx_annotate_cudf_polars(message="Filter")
def do_evaluate(
cls, mask_expr: expr.NamedExpr, df: DataFrame, *, context: IRExecutionContext
) -> DataFrame:
"""Evaluate and return a dataframe."""
(mask,) = broadcast(
mask_expr.evaluate(df), target_length=df.num_rows, stream=df.stream
)
return df.filter(mask)
| Filter |
python | vyperlang__vyper | vyper/evm/address_space.py | {
"start": 204,
"end": 2201
} | class ____:
"""
Object representing info about the "address space", analogous to the
LLVM concept. It includes some metadata so that codegen can be
written in a more generic way.
Attributes:
name: human-readable nickname for the address space
word_scale: a constant which helps calculate offsets in a given
address space. 1 for word-addressable locations (storage),
32 for byte-addressable locations (memory, calldata, code)
load_op: the opcode for loading a word from this address space
store_op: the opcode for storing a word to this address space
(an address space is read-only if store_op is None)
copy_op: the opcode for batch-copying from this address space
to memory
"""
name: str
word_scale: int
load_op: str
# TODO maybe make positional instead of defaulting to None
store_op: Optional[str] = None
copy_op: Optional[str] = None
@property
def word_addressable(self) -> bool:
return self.word_scale == 1
@property
def has_copy_opcode(self):
return self.copy_op is not None
# alternative:
# class Memory(AddrSpace):
# @property
# def word_scale(self):
# return 32
# # implement more properties...
#
# MEMORY = Memory()
MEMORY = AddrSpace("memory", 32, "mload", "mstore", "mcopy")
STORAGE = AddrSpace("storage", 1, "sload", "sstore")
TRANSIENT = AddrSpace("transient", 1, "tload", "tstore")
CALLDATA = AddrSpace("calldata", 32, "calldataload", None, "calldatacopy")
# immutables address space: "immutables" section of memory
# which is read-write in deploy code but then gets turned into
# the "data" section of the runtime code
IMMUTABLES = AddrSpace("immutables", 32, "iload", "istore")
# data addrspace: "data" section of runtime code, read-only.
DATA = AddrSpace("data", 32, "dload", None, "dloadbytes")
def legal_in_staticcall(location: AddrSpace):
return location not in (STORAGE, TRANSIENT)
| AddrSpace |
python | django__django | tests/mail/tests.py | {
"start": 86939,
"end": 87992
} | class ____(SimpleTestCase):
"""
Tests for #12422 -- Django smarts (#2472/#11212) with charset of utf-8 text
parts shouldn't pollute global email Python package charset registry when
django.mail.message is imported.
"""
def test_utf8(self):
txt = MIMEText("UTF-8 encoded body", "plain", "utf-8")
self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
def test_7bit(self):
txt = MIMEText("Body with only ASCII characters.", "plain", "utf-8")
self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
def test_8bit_latin(self):
txt = MIMEText("Body with latin characters: àáä.", "plain", "utf-8")
self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
def test_8bit_non_latin(self):
txt = MIMEText(
"Body with non latin characters: А Б В Г Д Е Ж Ѕ З И І К Л М Н О П.",
"plain",
"utf-8",
)
self.assertIn("Content-Transfer-Encoding: base64", txt.as_string())
| PythonGlobalState |
python | getsentry__sentry | tests/sentry/tasks/test_llm_issue_detection.py | {
"start": 740,
"end": 10693
} | class ____(TestCase):
@patch("sentry.tasks.llm_issue_detection.detection.detect_llm_issues_for_project.delay")
def test_run_detection_dispatches_sub_tasks(self, mock_delay):
"""Test run_detection spawns sub-tasks for each project."""
project = self.create_project()
with self.options(
{
"issue-detection.llm-detection.enabled": True,
"issue-detection.llm-detection.projects-allowlist": [project.id],
}
):
run_llm_issue_detection()
assert mock_delay.called
assert mock_delay.call_args[0][0] == project.id
@with_feature("organizations:gen-ai-features")
@patch("sentry.tasks.llm_issue_detection.detection.get_transactions_for_project")
def test_detect_llm_issues_no_transactions(self, mock_get_transactions):
"""Test that the task returns early when there are no transactions."""
mock_get_transactions.return_value = []
detect_llm_issues_for_project(self.project.id)
mock_get_transactions.assert_called_once_with(
self.project.id, limit=50, start_time_delta={"minutes": 30}
)
@with_feature("organizations:gen-ai-features")
@patch("sentry.tasks.llm_issue_detection.detection.get_evidence_trace_for_llm_detection")
@patch("sentry.tasks.llm_issue_detection.detection.get_transactions_for_project")
@patch("sentry.tasks.llm_issue_detection.detection.random.shuffle")
def test_detect_llm_issues_no_traces(self, mock_shuffle, mock_get_transactions, mock_get_trace):
"""Test that the task continues gracefully when traces can't be fetched."""
mock_transaction = Mock()
mock_transaction.name = "test_tx"
mock_transaction.project_id = self.project.id
mock_get_transactions.return_value = [mock_transaction]
mock_shuffle.return_value = None # shuffle modifies in place
mock_get_trace.return_value = None
detect_llm_issues_for_project(self.project.id)
mock_get_trace.assert_called_once_with(mock_transaction.name, mock_transaction.project_id)
@patch("sentry.tasks.llm_issue_detection.detection.produce_occurrence_to_kafka")
def test_create_issue_occurrence_from_detection(self, mock_produce_occurrence):
detected_issue = DetectedIssue(
title="Database Connection Pool Exhaustion",
explanation="Your application is running out of database connections",
impact="High - may cause request failures",
evidence="Connection pool at 95% capacity",
missing_telemetry="Database connection metrics",
)
mock_trace = Mock()
mock_trace.trace_id = "abc123xyz"
create_issue_occurrence_from_detection(
detected_issue=detected_issue,
trace=mock_trace,
project_id=self.project.id,
transaction_name="test_transaction",
)
assert mock_produce_occurrence.called
call_kwargs = mock_produce_occurrence.call_args.kwargs
assert call_kwargs["payload_type"].value == "occurrence"
occurrence = call_kwargs["occurrence"]
assert occurrence.type == LLMDetectedExperimentalGroupType
assert occurrence.issue_title == "Database Connection Pool Exhaustion"
assert occurrence.subtitle == "Your application is running out of database connections"
assert occurrence.project_id == self.project.id
assert occurrence.culprit == "test_transaction"
assert occurrence.level == "warning"
assert len(occurrence.fingerprint) == 1
assert (
occurrence.fingerprint[0]
== "llm-detected-database-connection-pool-exhaustion-test_transaction"
)
assert occurrence.evidence_data["trace_id"] == "abc123xyz"
assert occurrence.evidence_data["transaction"] == "test_transaction"
assert (
occurrence.evidence_data["explanation"]
== "Your application is running out of database connections"
)
assert occurrence.evidence_data["impact"] == "High - may cause request failures"
evidence_display = occurrence.evidence_display
assert len(evidence_display) == 3
assert evidence_display[0].name == "Explanation"
assert (
evidence_display[0].value == "Your application is running out of database connections"
)
assert evidence_display[1].name == "Impact"
assert evidence_display[1].value == "High - may cause request failures"
assert evidence_display[2].name == "Evidence"
assert evidence_display[2].value == "Connection pool at 95% capacity"
event_data = call_kwargs["event_data"]
assert event_data["project_id"] == self.project.id
assert event_data["platform"] == "other"
assert event_data["contexts"]["trace"]["trace_id"] == "abc123xyz"
assert "event_id" in event_data
assert "received" in event_data
assert "timestamp" in event_data
@patch("sentry.tasks.llm_issue_detection.detection.produce_occurrence_to_kafka")
def test_create_issue_occurrence_without_missing_telemetry(self, mock_produce_occurrence):
detected_issue = DetectedIssue(
title="Slow API Response",
explanation="API calls taking too long",
impact="Medium",
evidence="Response time > 2s",
)
mock_trace = Mock()
mock_trace.trace_id = "xyz789"
create_issue_occurrence_from_detection(
detected_issue=detected_issue,
trace=mock_trace,
project_id=self.project.id,
transaction_name="api_endpoint",
)
occurrence = mock_produce_occurrence.call_args.kwargs["occurrence"]
assert len(occurrence.evidence_display) == 3
evidence_names = {e.name for e in occurrence.evidence_display}
assert evidence_names == {"Explanation", "Impact", "Evidence"}
@with_feature("organizations:gen-ai-features")
@patch("sentry.tasks.llm_issue_detection.detection.produce_occurrence_to_kafka")
@patch("sentry.tasks.llm_issue_detection.detection.make_signed_seer_api_request")
@patch("sentry.tasks.llm_issue_detection.detection.get_evidence_trace_for_llm_detection")
@patch("sentry.tasks.llm_issue_detection.detection.get_transactions_for_project")
@patch("sentry.tasks.llm_issue_detection.detection.random.shuffle")
def test_detect_llm_issues_full_flow(
self,
mock_shuffle,
mock_get_transactions,
mock_get_trace,
mock_seer_request,
mock_produce_occurrence,
):
"""Test the full detect_llm_issues_for_project flow with Seer API interaction."""
mock_transaction = Mock()
mock_transaction.name = "api/users/list"
mock_transaction.project_id = self.project.id
mock_get_transactions.return_value = [mock_transaction]
mock_shuffle.return_value = None
mock_span = EvidenceSpan(
span_id="span123",
parent_span_id=None,
op="db.query",
description="SELECT * FROM users",
exclusive_time=150.5,
data={
"duration": 200.0,
"status": "ok",
},
)
mock_trace = EvidenceTraceData(
trace_id="trace-abc-123",
project_id=self.project.id,
transaction_name="api/users/list",
total_spans=100,
spans=[mock_span],
)
mock_get_trace.return_value = mock_trace
seer_response_data = {
"issues": [
{
"title": "N+1 Query Detected",
"explanation": "Multiple sequential database queries detected in loop",
"impact": "High - causes performance degradation",
"evidence": "15 queries executed sequentially",
"missing_telemetry": "Database query attribution",
},
{
"title": "Memory Leak Risk",
"explanation": "Large object allocations without cleanup",
"impact": "Medium - may cause OOM",
"evidence": "Objects not released after use",
"missing_telemetry": None,
},
]
}
mock_response = Mock()
mock_response.status = 200
mock_response.json.return_value = seer_response_data
mock_seer_request.return_value = mock_response
detect_llm_issues_for_project(self.project.id)
assert mock_seer_request.called
seer_call_kwargs = mock_seer_request.call_args.kwargs
assert seer_call_kwargs["path"] == "/v1/automation/issue-detection/analyze"
request_body = json.loads(seer_call_kwargs["body"].decode("utf-8"))
assert request_body["project_id"] == self.project.id
assert request_body["organization_id"] == self.project.organization_id
assert len(request_body["telemetry"]) == 1
assert request_body["telemetry"][0]["kind"] == "trace"
assert request_body["telemetry"][0]["trace_id"] == "trace-abc-123"
assert mock_produce_occurrence.call_count == 2
first_occurrence = mock_produce_occurrence.call_args_list[0].kwargs["occurrence"]
assert first_occurrence.type == LLMDetectedExperimentalGroupType
assert first_occurrence.issue_title == "N+1 Query Detected"
assert first_occurrence.culprit == "api/users/list"
assert first_occurrence.project_id == self.project.id
assert len(first_occurrence.evidence_display) == 3
second_occurrence = mock_produce_occurrence.call_args_list[1].kwargs["occurrence"]
assert second_occurrence.issue_title == "Memory Leak Risk"
assert len(second_occurrence.evidence_display) == 3
| LLMIssueDetectionTest |
python | conda__conda | conda/models/records.py | {
"start": 7861,
"end": 18409
} | class ____(DictSafeMixin, Entity):
"""Representation of a concrete package archive (tarball or .conda file).
It captures all the relevant information about a given package archive, including its source,
in the following attributes.
Note that there are three subclasses, :class:`SolvedRecord`, :class:`PrefixRecord` and
:class:`PackageCacheRecord`. These capture the same information, but are augmented with
additional information relevant for these sources of packages.
Further note that :class:`PackageRecord` makes use of its :attr:`_pkey`
for comparison and hash generation.
This means that for common operations, like comparisons between :class:`PackageRecord` s
and reference of :class:`PackageRecord` s in mappings, _different_ objects appear identical.
The fields taken into account are marked in the following list of attributes.
The subclasses do not add further attributes to the :attr:`_pkey`.
"""
#: str: The name of the package.
#:
#: Part of the :attr:`_pkey`.
name = StringField()
#: str: The version of the package.
#:
#: Part of the :attr:`_pkey`.
version = StringField()
#: str: The build string of the package.
#:
#: Part of the :attr:`_pkey`.
build = StringField(aliases=("build_string",))
#: int: The build number of the package.
#:
#: Part of the :attr:`_pkey`.
build_number = IntegerField()
# the canonical code abbreviation for PackageRef is `pref`
# fields required to uniquely identifying a package
#: :class:`conda.models.channel.Channel`: The channel where the package can be found.
channel = ChannelField(aliases=("schannel",))
#: str: The subdir, i.e. ``noarch`` or a platform (``linux-64`` or similar).
#:
#: Part of the :attr:`_pkey`.
subdir = SubdirField()
#: str: The filename of the package.
#:
#: Only part of the :attr:`_pkey` if :ref:`separate_format_cache <auto-config-reference>` is ``true`` (default: ``false``).
fn = FilenameField(aliases=("filename",))
#: str: The md5 checksum of the package.
md5 = StringField(
default=None, required=False, nullable=True, default_in_dump=False
)
#: str: If this is a ``.conda`` package and a corresponding ``.tar.bz2`` package exists, this may contain the md5 checksum of that package.
legacy_bz2_md5 = StringField(
default=None, required=False, nullable=True, default_in_dump=False
)
#: str: If this is a ``.conda`` package and a corresponding ``.tar.bz2`` package exists, this may contain the size of that package.
legacy_bz2_size = IntegerField(required=False, nullable=True, default_in_dump=False)
#: str: The download url of the package.
url = StringField(
default=None, required=False, nullable=True, default_in_dump=False
)
#: str: The sha256 checksum of the package.
sha256 = StringField(
default=None, required=False, nullable=True, default_in_dump=False
)
@property
def channel_name(self) -> str | None:
"""str: The canonical name of the channel of this package.
Part of the :attr:`_pkey`.
"""
return getattr(self.channel, "canonical_name", None)
@property
@deprecated("25.9", "26.3", addendum="Use .channel_name instead")
def schannel(self):
return self.channel_name
@property
def _pkey(self):
"""tuple: The components of the PackageRecord that are used for comparison and hashing.
The :attr:`_pkey` is a tuple made up of the following fields of the :class:`PackageRecord`.
Two :class:`PackageRecord` s test equal if their respective :attr:`_pkey` s are equal.
The hash of the :class:`PackageRecord` (important for dictionary access) is the hash of the :attr:`_pkey`.
The included fields are:
* :attr:`channel_name`
* :attr:`subdir`
* :attr:`name`
* :attr:`version`
* :attr:`build_number`
* :attr:`build`
* :attr:`fn` only if :ref:`separate_format_cache <auto-config-reference>` is set to true (default: false)
"""
try:
return self.__pkey
except AttributeError:
__pkey = self.__pkey = [
self.channel.canonical_name,
self.subdir,
self.name,
self.version,
self.build_number,
self.build,
]
# NOTE: fn is included to distinguish between .conda and .tar.bz2 packages
if context.separate_format_cache:
__pkey.append(self.fn)
self.__pkey = tuple(__pkey)
return self.__pkey
def __hash__(self):
try:
return self._hash
except AttributeError:
self._hash = hash(self._pkey)
return self._hash
def __eq__(self, other):
return self._pkey == other._pkey
def dist_str(self, canonical_name: bool = True) -> str:
return "{}{}::{}-{}-{}".format(
self.channel.canonical_name if canonical_name else self.channel.name,
("/" + self.subdir) if self.subdir else "",
self.name,
self.version,
self.build,
)
def dist_fields_dump(self):
return {
"base_url": self.channel.base_url,
"build_number": self.build_number,
"build_string": self.build,
"channel": self.channel.name,
"dist_name": self.dist_str().split(":")[-1],
"name": self.name,
"platform": self.subdir,
"version": self.version,
}
arch = StringField(required=False, nullable=True) # so legacy
platform = EnumField(Platform, required=False, nullable=True) # so legacy
depends = ListField(str, default=())
constrains = ListField(str, default=())
track_features = _FeaturesField(required=False, default=(), default_in_dump=False)
features = _FeaturesField(required=False, default=(), default_in_dump=False)
noarch = NoarchField(
NoarchType, required=False, nullable=True, default=None, default_in_dump=False
) # TODO: rename to package_type
preferred_env = StringField(
required=False, nullable=True, default=None, default_in_dump=False
)
python_site_packages_path = StringField(
default=None, required=False, nullable=True, default_in_dump=False
)
license = StringField(
required=False, nullable=True, default=None, default_in_dump=False
)
license_family = StringField(
required=False, nullable=True, default=None, default_in_dump=False
)
package_type = PackageTypeField()
@property
def is_unmanageable(self):
return self.package_type in PackageType.unmanageable_package_types()
timestamp = TimestampField()
@property
def combined_depends(self):
from .match_spec import MatchSpec
result = {ms.name: ms for ms in MatchSpec.merge(self.depends)}
for spec in self.constrains or ():
ms = MatchSpec(spec)
result[ms.name] = MatchSpec(ms, optional=(ms.name not in result))
return tuple(result.values())
# the canonical code abbreviation for PackageRecord is `prec`, not to be confused with
# PackageCacheRecord (`pcrec`) or PrefixRecord (`prefix_rec`)
#
# important for "choosing" a package (i.e. the solver), listing packages
# (like search), and for verifying downloads
#
# this is the highest level of the record inheritance model that MatchSpec is designed to
# work with
date = StringField(required=False)
size = IntegerField(required=False)
def __str__(self):
return f"{self.channel.canonical_name}/{self.subdir}::{self.name}=={self.version}={self.build}"
def to_match_spec(self):
return MatchSpec(
channel=self.channel,
subdir=self.subdir,
name=self.name,
version=self.version,
build=self.build,
)
def to_simple_match_spec(self):
return MatchSpec(
name=self.name,
version=self.version,
)
@property
def namekey(self):
return "global:" + self.name
@property
def spec(self):
"""Return package spec: name=version=build"""
return f"{self.name}={self.version}={self.build}"
@property
def spec_no_build(self):
"""Return package spec without build: name=version"""
return f"{self.name}={self.version}"
def record_id(self):
# WARNING: This is right now only used in link.py _change_report_str(). It is not
# the official record_id / uid until it gets namespace. Even then, we might
# make the format different. Probably something like
# channel_name/subdir:namespace:name-version-build_number-build_string
return f"{self.channel.name}/{self.subdir}::{self.name}-{self.version}-{self.build}"
metadata: set[str]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.metadata = set()
@classmethod
def feature(cls, feature_name) -> PackageRecord:
# necessary for the SAT solver to do the right thing with features
pkg_name = f"{feature_name}@"
return cls(
name=pkg_name,
version="0",
build="0",
channel="@",
subdir=context.subdir,
md5="12345678901234567890123456789012",
track_features=(feature_name,),
build_number=0,
fn=pkg_name,
)
@classmethod
def virtual_package(
cls, name: str, version: str | None = None, build_string: str | None = None
) -> PackageRecord:
"""
Create a virtual package record.
:param name: The name of the virtual package.
:param version: The version of the virtual package, defaults to "0".
:param build_string: The build string of the virtual package, defaults to "0".
:return: A PackageRecord representing the virtual package.
"""
return cls(
package_type=PackageType.VIRTUAL_SYSTEM,
name=name,
version=version or "0",
build_string=build_string or "0",
channel="@",
subdir=context.subdir,
md5="12345678901234567890123456789012",
build_number=0,
fn=name,
)
| PackageRecord |
python | django__django | tests/model_indexes/tests.py | {
"start": 339,
"end": 11649
} | class ____(SimpleTestCase):
def test_suffix(self):
self.assertEqual(models.Index.suffix, "idx")
def test_repr(self):
index = models.Index(fields=["title"])
named_index = models.Index(fields=["title"], name="title_idx")
multi_col_index = models.Index(fields=["title", "author"])
partial_index = models.Index(
fields=["title"], name="long_books_idx", condition=models.Q(pages__gt=400)
)
covering_index = models.Index(
fields=["title"],
name="include_idx",
include=["author", "pages"],
)
opclasses_index = models.Index(
fields=["headline", "body"],
name="opclasses_idx",
opclasses=["varchar_pattern_ops", "text_pattern_ops"],
)
func_index = models.Index(Lower("title"), "subtitle", name="book_func_idx")
tablespace_index = models.Index(
fields=["title"],
db_tablespace="idx_tbls",
name="book_tablespace_idx",
)
self.assertEqual(repr(index), "<Index: fields=['title']>")
self.assertEqual(
repr(named_index),
"<Index: fields=['title'] name='title_idx'>",
)
self.assertEqual(repr(multi_col_index), "<Index: fields=['title', 'author']>")
self.assertEqual(
repr(partial_index),
"<Index: fields=['title'] name='long_books_idx' "
"condition=(AND: ('pages__gt', 400))>",
)
self.assertEqual(
repr(covering_index),
"<Index: fields=['title'] name='include_idx' "
"include=('author', 'pages')>",
)
self.assertEqual(
repr(opclasses_index),
"<Index: fields=['headline', 'body'] name='opclasses_idx' "
"opclasses=['varchar_pattern_ops', 'text_pattern_ops']>",
)
self.assertEqual(
repr(func_index),
"<Index: expressions=(Lower(F(title)), F(subtitle)) "
"name='book_func_idx'>",
)
self.assertEqual(
repr(tablespace_index),
"<Index: fields=['title'] name='book_tablespace_idx' "
"db_tablespace='idx_tbls'>",
)
def test_eq(self):
index = models.Index(fields=["title"])
same_index = models.Index(fields=["title"])
another_index = models.Index(fields=["title", "author"])
index.model = Book
same_index.model = Book
another_index.model = Book
self.assertEqual(index, same_index)
self.assertEqual(index, mock.ANY)
self.assertNotEqual(index, another_index)
def test_eq_func(self):
index = models.Index(Lower("title"), models.F("author"), name="book_func_idx")
same_index = models.Index(Lower("title"), "author", name="book_func_idx")
another_index = models.Index(Lower("title"), name="book_func_idx")
self.assertEqual(index, same_index)
self.assertEqual(index, mock.ANY)
self.assertNotEqual(index, another_index)
def test_index_fields_type(self):
with self.assertRaisesMessage(
ValueError, "Index.fields must be a list or tuple."
):
models.Index(fields="title")
def test_index_fields_strings(self):
msg = "Index.fields must contain only strings with field names."
with self.assertRaisesMessage(ValueError, msg):
models.Index(fields=[models.F("title")])
def test_fields_tuple(self):
self.assertEqual(models.Index(fields=("title",)).fields, ["title"])
def test_requires_field_or_expression(self):
msg = "At least one field or expression is required to define an index."
with self.assertRaisesMessage(ValueError, msg):
models.Index()
def test_expressions_and_fields_mutually_exclusive(self):
msg = "Index.fields and expressions are mutually exclusive."
with self.assertRaisesMessage(ValueError, msg):
models.Index(Upper("foo"), fields=["field"])
def test_opclasses_requires_index_name(self):
with self.assertRaisesMessage(
ValueError, "An index must be named to use opclasses."
):
models.Index(opclasses=["jsonb_path_ops"])
def test_opclasses_requires_list_or_tuple(self):
with self.assertRaisesMessage(
ValueError, "Index.opclasses must be a list or tuple."
):
models.Index(
name="test_opclass", fields=["field"], opclasses="jsonb_path_ops"
)
def test_opclasses_and_fields_same_length(self):
msg = "Index.fields and Index.opclasses must have the same number of elements."
with self.assertRaisesMessage(ValueError, msg):
models.Index(
name="test_opclass",
fields=["field", "other"],
opclasses=["jsonb_path_ops"],
)
def test_condition_requires_index_name(self):
with self.assertRaisesMessage(
ValueError, "An index must be named to use condition."
):
models.Index(condition=models.Q(pages__gt=400))
def test_expressions_requires_index_name(self):
msg = "An index must be named to use expressions."
with self.assertRaisesMessage(ValueError, msg):
models.Index(Lower("field"))
def test_expressions_with_opclasses(self):
msg = (
"Index.opclasses cannot be used with expressions. Use "
"django.contrib.postgres.indexes.OpClass() instead."
)
with self.assertRaisesMessage(ValueError, msg):
models.Index(
Lower("field"),
name="test_func_opclass",
opclasses=["jsonb_path_ops"],
)
def test_condition_must_be_q(self):
with self.assertRaisesMessage(
ValueError, "Index.condition must be a Q instance."
):
models.Index(condition="invalid", name="long_book_idx")
def test_include_requires_list_or_tuple(self):
msg = "Index.include must be a list or tuple."
with self.assertRaisesMessage(ValueError, msg):
models.Index(name="test_include", fields=["field"], include="other")
def test_include_requires_index_name(self):
msg = "A covering index must be named."
with self.assertRaisesMessage(ValueError, msg):
models.Index(fields=["field"], include=["other"])
def test_name_auto_generation(self):
index = models.Index(fields=["author"])
index.set_name_with_model(Book)
self.assertEqual(index.name, "model_index_author_0f5565_idx")
# '-' for DESC columns should be accounted for in the index name.
index = models.Index(fields=["-author"])
index.set_name_with_model(Book)
self.assertEqual(index.name, "model_index_author_708765_idx")
# fields may be truncated in the name. db_column is used for naming.
long_field_index = models.Index(fields=["pages"])
long_field_index.set_name_with_model(Book)
self.assertEqual(long_field_index.name, "model_index_page_co_69235a_idx")
# suffix can't be longer than 3 characters.
long_field_index.suffix = "suff"
msg = (
"Index too long for multiple database support. Is self.suffix "
"longer than 3 characters?"
)
with self.assertRaisesMessage(ValueError, msg):
long_field_index.set_name_with_model(Book)
@isolate_apps("model_indexes")
def test_name_auto_generation_with_quoted_db_table(self):
class QuotedDbTable(models.Model):
name = models.CharField(max_length=50)
class Meta:
db_table = '"t_quoted"'
index = models.Index(fields=["name"])
index.set_name_with_model(QuotedDbTable)
self.assertEqual(index.name, "t_quoted_name_e4ed1b_idx")
def test_deconstruction(self):
index = models.Index(fields=["title"], db_tablespace="idx_tbls")
index.set_name_with_model(Book)
path, args, kwargs = index.deconstruct()
self.assertEqual(path, "django.db.models.Index")
self.assertEqual(args, ())
self.assertEqual(
kwargs,
{
"fields": ["title"],
"name": "model_index_title_196f42_idx",
"db_tablespace": "idx_tbls",
},
)
def test_deconstruct_with_condition(self):
index = models.Index(
name="big_book_index",
fields=["title"],
condition=models.Q(pages__gt=400),
)
index.set_name_with_model(Book)
path, args, kwargs = index.deconstruct()
self.assertEqual(path, "django.db.models.Index")
self.assertEqual(args, ())
self.assertEqual(
kwargs,
{
"fields": ["title"],
"name": "model_index_title_196f42_idx",
"condition": models.Q(pages__gt=400),
},
)
def test_deconstruct_with_include(self):
index = models.Index(
name="book_include_idx",
fields=["title"],
include=["author"],
)
index.set_name_with_model(Book)
path, args, kwargs = index.deconstruct()
self.assertEqual(path, "django.db.models.Index")
self.assertEqual(args, ())
self.assertEqual(
kwargs,
{
"fields": ["title"],
"name": "model_index_title_196f42_idx",
"include": ("author",),
},
)
def test_deconstruct_with_expressions(self):
index = models.Index(Upper("title"), name="book_func_idx")
path, args, kwargs = index.deconstruct()
self.assertEqual(path, "django.db.models.Index")
self.assertEqual(args, (Upper("title"),))
self.assertEqual(kwargs, {"name": "book_func_idx"})
def test_clone(self):
index = models.Index(fields=["title"])
new_index = index.clone()
self.assertIsNot(index, new_index)
self.assertEqual(index.fields, new_index.fields)
def test_clone_with_expressions(self):
index = models.Index(Upper("title"), name="book_func_idx")
new_index = index.clone()
self.assertIsNot(index, new_index)
self.assertEqual(index.expressions, new_index.expressions)
def test_name_set(self):
index_names = [index.name for index in Book._meta.indexes]
self.assertCountEqual(
index_names,
[
"model_index_title_196f42_idx",
"model_index_isbn_34f975_idx",
"model_indexes_book_barcode_idx",
],
)
def test_abstract_children(self):
index_names = [index.name for index in ChildModel1._meta.indexes]
self.assertEqual(
index_names,
["model_index_name_440998_idx", "model_indexes_childmodel1_idx"],
)
index_names = [index.name for index in ChildModel2._meta.indexes]
self.assertEqual(
index_names,
["model_index_name_b6c374_idx", "model_indexes_childmodel2_idx"],
)
@override_settings(DEFAULT_TABLESPACE=None)
| SimpleIndexesTests |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 133819,
"end": 146998
} | class ____:
@pytest.mark.parametrize('dtype', [None, 'float32', 'float64'])
def test_basic(self, dtype, xp):
x = np.arange(8) * 0.5
np.random.shuffle(x)
dtype = xp_default_dtype(xp) if dtype is None else getattr(xp, dtype)
xp_assert_equal(stats.iqr(xp.asarray(x, dtype=dtype)),
xp.asarray(1.75, dtype=dtype))
def test_api(self, xp):
d = xp.ones((5, 5))
stats.iqr(d)
stats.iqr(d, None)
stats.iqr(d, 1)
stats.iqr(d, (0, 1))
stats.iqr(d, None, (10, 90))
stats.iqr(d, None, (30, 20), 1.0)
stats.iqr(d, None, (25, 75), 1.5, 'propagate')
@pytest.mark.skip_xp_backends('jax.numpy', reason='lazy -> no nan_policy')
def test_api_eager(self, xp):
d = xp.ones((5, 5))
stats.iqr(d, None, (50, 50), 'normal', 'raise', 'linear')
stats.iqr(d, None, (25, 75), -0.4, 'omit', 'lower', True)
@pytest.mark.parametrize('x', [[], np.arange(0)])
def test_empty(self, x, xp):
with eager_warns(SmallSampleWarning, match=too_small_1d_not_omit, xp=xp):
xp_assert_equal(stats.iqr(xp.asarray(x)), xp.asarray(xp.nan))
def test_constant(self, xp):
# Constant array always gives 0
x = xp.ones((7, 4))
zero = xp.asarray(0.0)
xp_assert_equal(stats.iqr(x), zero)
xp_assert_equal(stats.iqr(x, axis=0), xp.zeros(4))
xp_assert_equal(stats.iqr(x, axis=1), xp.zeros(7))
xp_assert_equal(stats.iqr(x, interpolation='linear'), zero)
xp_assert_equal(stats.iqr(x, interpolation='midpoint'), zero)
xp_assert_equal(stats.iqr(x, interpolation='nearest'), zero)
xp_assert_equal(stats.iqr(x, interpolation='lower'), zero)
xp_assert_equal(stats.iqr(x, interpolation='higher'), zero)
# 0 only along constant dimensions
# This also tests much of `axis`
y = xp.ones((4, 5, 6)) * xp.arange(6.)
xp_assert_equal(stats.iqr(y, axis=0), xp.zeros((5, 6)))
xp_assert_equal(stats.iqr(y, axis=1), xp.zeros((4, 6)))
xp_assert_equal(stats.iqr(y, axis=2), xp.full((4, 5), 2.5))
xp_assert_equal(stats.iqr(y, axis=(0, 1)), xp.zeros(6))
xp_assert_equal(stats.iqr(y, axis=(0, 2)), xp.full(5, 3.))
xp_assert_equal(stats.iqr(y, axis=(1, 2)), xp.full(4, 3.))
def test_scalarlike(self, xp):
x = xp.arange(1.) + 7.0
xp_assert_equal(stats.iqr(x[0]), xp.asarray(0.0))
xp_assert_equal(stats.iqr(x), xp.asarray(0.0))
xp_assert_equal(stats.iqr(x, keepdims=True), xp.asarray([0.0]))
def test_2D(self, xp):
x = xp.reshape(xp.arange(15), (3, 5))
xp_assert_equal(stats.iqr(x), xp.asarray(7.0))
xp_assert_equal(stats.iqr(x, axis=0), xp.full(5, 5.))
xp_assert_equal(stats.iqr(x, axis=1), xp.full(3, 2.))
xp_assert_equal(stats.iqr(x, axis=(0, 1)), xp.asarray(7.0))
xp_assert_equal(stats.iqr(x, axis=(1, 0)), xp.asarray(7.0))
def test_axis(self, xp):
# The `axis` keyword is also put through its paces in `test_keepdims`.
o = np.random.normal(size=(71, 23))
x = np.dstack([o] * 10) # x.shape = (71, 23, 10)
o, x = xp.asarray(o), xp.asarray(x)
q = xp.broadcast_to(stats.iqr(o), (10,))
xp_assert_equal(stats.iqr(x, axis=(0, 1)), q)
x = xp.moveaxis(x, -1, 0) # x.shape = (10, 71, 23)
xp_assert_equal(stats.iqr(x, axis=(2, 1)), q)
x = xp_swapaxes(x,0, 1, xp=xp) # x.shape = (71, 10, 23)
xp_assert_equal(stats.iqr(x, axis=(0, 2)), q)
x = xp_swapaxes(x,0, 1, xp=xp) # x.shape = (10, 71, 23)
xp_assert_equal(stats.iqr(x, axis=(0, 1, 2)),
stats.iqr(x, axis=None))
xp_assert_equal(stats.iqr(x, axis=(0,)),
stats.iqr(x, axis=0))
d = np.arange(3 * 5 * 7 * 11)
# Older versions of numpy only shuffle along axis=0.
# Not sure about newer, don't care.
np.random.shuffle(d)
d = d.reshape((3, 5, 7, 11))
d = xp.asarray(d)
xp_assert_equal(stats.iqr(d, axis=(0, 1, 2))[0],
stats.iqr(xp_ravel(d[:,:,:, 0])))
xp_assert_equal(stats.iqr(d, axis=(0, 1, 3))[1],
stats.iqr(xp_ravel(d[:,:, 1,:])))
xp_assert_equal(stats.iqr(d, axis=(3, 1, -4))[2],
stats.iqr(xp_ravel(d[:,:, 2,:])))
xp_assert_equal(stats.iqr(d, axis=(3, 1, 2))[2],
stats.iqr(xp_ravel(d[2,:,:,:])))
xp_assert_equal(stats.iqr(d, axis=(3, 2))[2, 1],
stats.iqr(xp_ravel(d[2, 1,:,:])))
xp_assert_equal(stats.iqr(d, axis=(1, -2))[2, 1],
stats.iqr(xp_ravel(d[2, :, :, 1])))
xp_assert_equal(stats.iqr(d, axis=(1, 3))[2, 2],
stats.iqr(xp_ravel(d[2, :, 2,:])))
with pytest.raises(AxisError, match='`axis` is out of bounds...'):
stats.iqr(d, axis=4)
with pytest.raises(ValueError, match='`axis` must contain only...'):
stats.iqr(d, axis=(0, 0))
def test_rng(self, xp):
x = xp.arange(5)
xp_assert_equal(stats.iqr(x), xp.asarray(2.))
xp_assert_equal(stats.iqr(x, rng=(25, 87.5)), xp.asarray(2.5))
xp_assert_equal(stats.iqr(x, rng=(12.5, 75)), xp.asarray(2.5))
xp_assert_equal(stats.iqr(x, rng=(10, 50)), xp.asarray(1.6)) # 3-1.4
message = r"Elements of `rng` must be in the range \[0, 100\]."
with pytest.raises(ValueError, match=message):
stats.iqr(x, rng=(0, 101))
message = "`rng` must not contain NaNs."
with pytest.raises(ValueError, match=message):
stats.iqr(x, rng=(np.nan, 25))
message = "`rng` must be a two element sequence."
with pytest.raises(TypeError, match=message):
stats.iqr(x, rng=(0, 50, 60))
def test_interpolation(self, xp):
x = xp.arange(5)
y = xp.arange(4)
# Default
xp_assert_equal(stats.iqr(x), xp.asarray(2.))
xp_assert_equal(stats.iqr(y), xp.asarray(1.5))
# Linear
xp_assert_equal(stats.iqr(x, interpolation='linear'), xp.asarray(2.))
xp_assert_equal(stats.iqr(y, interpolation='linear'), xp.asarray(1.5))
# Higher
xp_assert_equal(stats.iqr(x, interpolation='higher'), xp.asarray(2.))
xp_assert_equal(stats.iqr(x, rng=(25, 80), interpolation='higher'),
xp.asarray(3.))
xp_assert_equal(stats.iqr(y, interpolation='higher'), xp.asarray(2.))
# Lower (will generally, but not always be the same as higher)
xp_assert_equal(stats.iqr(x, interpolation='lower'), xp.asarray(2.))
xp_assert_equal(stats.iqr(x, rng=(25, 80), interpolation='lower'),
xp.asarray(2.))
xp_assert_equal(stats.iqr(y, interpolation='lower'), xp.asarray(2.))
# Nearest
xp_assert_equal(stats.iqr(x, interpolation='nearest'), xp.asarray(2.))
xp_assert_equal(stats.iqr(y, interpolation='nearest'), xp.asarray(1.))
# Midpoint
xp_assert_equal(stats.iqr(x, interpolation='midpoint'), xp.asarray(2.))
xp_assert_equal(stats.iqr(x, rng=(25, 80), interpolation='midpoint'),
xp.asarray(2.5))
xp_assert_equal(stats.iqr(y, interpolation='midpoint'), xp.asarray(2.))
# Check all method= values new in numpy 1.22.0 are accepted
for method in ('inverted_cdf', 'averaged_inverted_cdf',
'closest_observation', 'interpolated_inverted_cdf',
'hazen', 'weibull', 'median_unbiased',
'normal_unbiased'):
stats.iqr(y, interpolation=method)
with pytest.raises(ValueError, match='`method` must be one of...'):
stats.iqr(x, interpolation='foobar')
def test_keepdims(self, xp):
# Also tests most of `axis`
x = xp.ones((3, 5, 7, 11))
assert_equal(stats.iqr(x, axis=None, keepdims=False).shape, ())
assert_equal(stats.iqr(x, axis=2, keepdims=False).shape, (3, 5, 11))
assert_equal(stats.iqr(x, axis=(0, 1), keepdims=False).shape, (7, 11))
assert_equal(stats.iqr(x, axis=(0, 3), keepdims=False).shape, (5, 7))
assert_equal(stats.iqr(x, axis=(1,), keepdims=False).shape, (3, 7, 11))
assert_equal(stats.iqr(x, (0, 1, 2, 3), keepdims=False).shape, ())
assert_equal(stats.iqr(x, axis=(0, 1, 3), keepdims=False).shape, (7,))
assert_equal(stats.iqr(x, axis=None, keepdims=True).shape, (1, 1, 1, 1))
assert_equal(stats.iqr(x, axis=2, keepdims=True).shape, (3, 5, 1, 11))
assert_equal(stats.iqr(x, axis=(0, 1), keepdims=True).shape, (1, 1, 7, 11))
assert_equal(stats.iqr(x, axis=(0, 3), keepdims=True).shape, (1, 5, 7, 1))
assert_equal(stats.iqr(x, axis=(1,), keepdims=True).shape, (3, 1, 7, 11))
assert_equal(stats.iqr(x, (0, 1, 2, 3), keepdims=True).shape, (1, 1, 1, 1))
assert_equal(stats.iqr(x, axis=(0, 1, 3), keepdims=True).shape, (1, 1, 7, 1))
def test_nanpolicy(self, xp):
x = xp.reshape(xp.arange(15.0), (3, 5))
# No NaNs
xp_assert_equal(stats.iqr(x, nan_policy='propagate'), xp.asarray(7.))
xp_assert_equal(stats.iqr(x, nan_policy='omit'), xp.asarray(7.))
xp_assert_equal(stats.iqr(x, nan_policy='raise'), xp.asarray(7.))
# Yes NaNs
x = xpx.at(x)[1, 2].set(xp.nan)
xp_assert_equal(stats.iqr(x, nan_policy='propagate'),
xp.asarray(xp.nan))
xp_assert_equal(stats.iqr(x, axis=0, nan_policy='propagate'),
xp.asarray([5, 5, xp.nan, 5, 5]))
xp_assert_equal(stats.iqr(x, axis=1, nan_policy='propagate'),
xp.asarray([2, xp.nan, 2]))
xp_assert_equal(stats.iqr(x, nan_policy='omit'), xp.asarray(7.5))
message = "The input contains nan values"
with pytest.raises(ValueError, match=message):
stats.iqr(x, nan_policy='raise')
# Bad policy
message = "nan_policy must be one of..."
with pytest.raises(ValueError, match=message):
stats.iqr(x, nan_policy='barfood')
@pytest.mark.skip_xp_backends(np_only=True,
reason="nan_policy w/ multidimensional arrays only available w/ NumPy")
def test_nanpolicy_nd(self, xp):
x = xp.reshape(xp.arange(15.0), (3, 5))
x[1, 2] = xp.nan
xp_assert_equal(stats.iqr(x, axis=0, nan_policy='omit'),
xp.full(5, 5.))
xp_assert_equal(stats.iqr(x, axis=1, nan_policy='omit'),
xp.asarray([2, 2.5, 2]))
message = "The input contains nan values"
with pytest.raises(ValueError, match=message):
stats.iqr(x, axis=0, nan_policy='raise')
with pytest.raises(ValueError, match=message):
stats.iqr(x, axis=1, nan_policy='raise')
def test_scale(self, xp):
x = xp.reshape(xp.arange(15.0), (3, 5))
# No NaNs
xp_assert_equal(stats.iqr(x, scale=1.0), xp.asarray(7.))
xp_assert_close(stats.iqr(x, scale='normal'), xp.asarray(7 / 1.3489795))
xp_assert_equal(stats.iqr(x, scale=2.0), xp.asarray(3.5))
# Yes NaNs
x = xpx.at(x)[1, 2].set(xp.nan)
nan = xp.asarray(xp.nan)
xp_assert_equal(stats.iqr(x, scale=1.0, nan_policy='propagate'), nan)
xp_assert_equal(stats.iqr(x, scale='normal', nan_policy='propagate'), nan)
xp_assert_equal(stats.iqr(x, scale=2.0, nan_policy='propagate'), nan)
xp_assert_equal(stats.iqr(x, scale=1.0, nan_policy='omit'), xp.asarray(7.5))
xp_assert_close(stats.iqr(x, scale='normal', nan_policy='omit'),
xp.asarray(7.5 / 1.3489795))
xp_assert_equal(stats.iqr(x, scale=2.0, nan_policy='omit'), xp.asarray(3.75))
# # Bad scale
message = "foobar not a valid scale for `iqr`"
with pytest.raises(ValueError, match=message):
stats.iqr(x, scale='foobar')
@pytest.mark.skip_xp_backends(np_only=True,
reason="nan_policy w/ multidimensional arrays only available w/ NumPy")
def test_scale_nanpolicy_nd(self, xp):
# axis=1 chosen to show behavior with both nans and without
x = xp.reshape(xp.arange(15.0), (3, 5))
x = xpx.at(x)[1, 2].set(xp.nan)
xp_assert_equal(stats.iqr(x, axis=1, scale=1.0, nan_policy='propagate'),
xp.asarray([2, np.nan, 2]))
xp_assert_close(stats.iqr(x, axis=1, scale='normal', nan_policy='propagate'),
xp.asarray([2, np.nan, 2]) / 1.3489795)
xp_assert_equal(stats.iqr(x, axis=1, scale=2.0, nan_policy='propagate'),
xp.asarray([1, np.nan, 1]))
def test_rng_order(self, xp):
# test that order of `rng` doesn't matter (as documented)
x = xp.arange(8.) * 0.5
res = stats.iqr(x, rng=(75, 25))
ref = stats.iqr(x)
xp_assert_equal(res, ref)
@make_xp_test_case(stats.moment)
| TestIQR |
python | tornadoweb__tornado | tornado/test/routing_test.py | {
"start": 1812,
"end": 1979
} | class ____(RequestHandler):
def get(self, path):
if path not in resources:
raise HTTPError(404)
self.finish(resources[path])
| GetResource |
python | faif__python-patterns | patterns/structural/adapter.py | {
"start": 1520,
"end": 1649
} | class ____:
def __init__(self) -> None:
self.name = "Human"
def speak(self) -> str:
return "'hello'"
| Human |
python | ray-project__ray | rllib/algorithms/sac/sac_tf_model.py | {
"start": 533,
"end": 12619
} | class ____(TFModelV2):
"""Extension of the standard TFModelV2 for SAC.
To customize, do one of the following:
- sub-class SACTFModel and override one or more of its methods.
- Use SAC's `q_model_config` and `policy_model` keys to tweak the default model
behaviors (e.g. fcnet_hiddens, conv_filters, etc..).
- Use SAC's `q_model_config->custom_model` and `policy_model->custom_model` keys
to specify your own custom Q-model(s) and policy-models, which will be
created within this SACTFModel (see `build_policy_model` and
`build_q_model`.
Note: It is not recommended to override the `forward` method for SAC. This
would lead to shared weights (between policy and Q-nets), which will then
not be optimized by either of the critic- or actor-optimizers!
Data flow:
`obs` -> forward() (should stay a noop method!) -> `model_out`
`model_out` -> get_policy_output() -> pi(actions|obs)
`model_out`, `actions` -> get_q_values() -> Q(s, a)
`model_out`, `actions` -> get_twin_q_values() -> Q_twin(s, a)
"""
def __init__(
self,
obs_space: gym.spaces.Space,
action_space: gym.spaces.Space,
num_outputs: Optional[int],
model_config: ModelConfigDict,
name: str,
policy_model_config: ModelConfigDict = None,
q_model_config: ModelConfigDict = None,
twin_q: bool = False,
initial_alpha: float = 1.0,
target_entropy: Optional[float] = None,
):
"""Initialize a SACTFModel instance.
Args:
policy_model_config: The config dict for the
policy network.
q_model_config: The config dict for the
Q-network(s) (2 if twin_q=True).
twin_q: Build twin Q networks (Q-net and target) for more
stable Q-learning.
initial_alpha: The initial value for the to-be-optimized
alpha parameter (default: 1.0).
target_entropy (Optional[float]): A target entropy value for
the to-be-optimized alpha parameter. If None, will use the
defaults described in the papers for SAC (and discrete SAC).
Note that the core layers for forward() are not defined here, this
only defines the layers for the output heads. Those layers for
forward() should be defined in subclasses of SACModel.
"""
super(SACTFModel, self).__init__(
obs_space, action_space, num_outputs, model_config, name
)
if isinstance(action_space, Discrete):
self.action_dim = action_space.n
self.discrete = True
action_outs = q_outs = self.action_dim
elif isinstance(action_space, Box):
self.action_dim = np.prod(action_space.shape)
self.discrete = False
action_outs = 2 * self.action_dim
q_outs = 1
else:
assert isinstance(action_space, Simplex)
self.action_dim = np.prod(action_space.shape)
self.discrete = False
action_outs = self.action_dim
q_outs = 1
self.action_model = self.build_policy_model(
self.obs_space, action_outs, policy_model_config, "policy_model"
)
self.q_net = self.build_q_model(
self.obs_space, self.action_space, q_outs, q_model_config, "q"
)
if twin_q:
self.twin_q_net = self.build_q_model(
self.obs_space, self.action_space, q_outs, q_model_config, "twin_q"
)
else:
self.twin_q_net = None
self.log_alpha = tf.Variable(
np.log(initial_alpha), dtype=tf.float32, name="log_alpha"
)
self.alpha = tf.exp(self.log_alpha)
# Auto-calculate the target entropy.
if target_entropy is None or target_entropy == "auto":
# See hyperparams in [2] (README.md).
if self.discrete:
target_entropy = 0.98 * np.array(
-np.log(1.0 / action_space.n), dtype=np.float32
)
# See [1] (README.md).
else:
target_entropy = -np.prod(action_space.shape)
self.target_entropy = target_entropy
@override(TFModelV2)
def forward(
self,
input_dict: Dict[str, TensorType],
state: List[TensorType],
seq_lens: TensorType,
) -> (TensorType, List[TensorType]):
"""The common (Q-net and policy-net) forward pass.
NOTE: It is not(!) recommended to override this method as it would
introduce a shared pre-network, which would be updated by both
actor- and critic optimizers.
"""
return input_dict["obs"], state
def build_policy_model(self, obs_space, num_outputs, policy_model_config, name):
"""Builds the policy model used by this SAC.
Override this method in a sub-class of SACTFModel to implement your
own policy net. Alternatively, simply set `custom_model` within the
top level SAC `policy_model` config key to make this default
implementation of `build_policy_model` use your custom policy network.
Returns:
TFModelV2: The TFModelV2 policy sub-model.
"""
model = ModelCatalog.get_model_v2(
obs_space,
self.action_space,
num_outputs,
policy_model_config,
framework="tf",
name=name,
)
return model
def build_q_model(self, obs_space, action_space, num_outputs, q_model_config, name):
"""Builds one of the (twin) Q-nets used by this SAC.
Override this method in a sub-class of SACTFModel to implement your
own Q-nets. Alternatively, simply set `custom_model` within the
top level SAC `q_model_config` config key to make this default implementation
of `build_q_model` use your custom Q-nets.
Returns:
TFModelV2: The TFModelV2 Q-net sub-model.
"""
self.concat_obs_and_actions = False
if self.discrete:
input_space = obs_space
else:
orig_space = getattr(obs_space, "original_space", obs_space)
if isinstance(orig_space, Box) and len(orig_space.shape) == 1:
input_space = Box(
float("-inf"),
float("inf"),
shape=(orig_space.shape[0] + action_space.shape[0],),
)
self.concat_obs_and_actions = True
else:
input_space = gym.spaces.Tuple([orig_space, action_space])
model = ModelCatalog.get_model_v2(
input_space,
action_space,
num_outputs,
q_model_config,
framework="tf",
name=name,
)
return model
def get_q_values(
self, model_out: TensorType, actions: Optional[TensorType] = None
) -> TensorType:
"""Returns Q-values, given the output of self.__call__().
This implements Q(s, a) -> [single Q-value] for the continuous case and
Q(s) -> [Q-values for all actions] for the discrete case.
Args:
model_out: Feature outputs from the model layers
(result of doing `self.__call__(obs)`).
actions (Optional[TensorType]): Continuous action batch to return
Q-values for. Shape: [BATCH_SIZE, action_dim]. If None
(discrete action case), return Q-values for all actions.
Returns:
TensorType: Q-values tensor of shape [BATCH_SIZE, 1].
"""
return self._get_q_value(model_out, actions, self.q_net)
def get_twin_q_values(
self, model_out: TensorType, actions: Optional[TensorType] = None
) -> TensorType:
"""Same as get_q_values but using the twin Q net.
This implements the twin Q(s, a).
Args:
model_out: Feature outputs from the model layers
(result of doing `self.__call__(obs)`).
actions (Optional[Tensor]): Actions to return the Q-values for.
Shape: [BATCH_SIZE, action_dim]. If None (discrete action
case), return Q-values for all actions.
Returns:
TensorType: Q-values tensor of shape [BATCH_SIZE, 1].
"""
return self._get_q_value(model_out, actions, self.twin_q_net)
def _get_q_value(self, model_out, actions, net):
# Model outs may come as original Tuple/Dict observations, concat them
# here if this is the case.
if isinstance(net.obs_space, Box):
if isinstance(model_out, (list, tuple)):
model_out = tf.concat(model_out, axis=-1)
elif isinstance(model_out, dict):
model_out = tf.concat(list(model_out.values()), axis=-1)
# Continuous case -> concat actions to model_out.
if actions is not None:
if self.concat_obs_and_actions:
input_dict = {"obs": tf.concat([model_out, actions], axis=-1)}
else:
# TODO(junogng) : SampleBatch doesn't support list columns yet.
# Use ModelInputDict.
input_dict = {"obs": (model_out, actions)}
# Discrete case -> return q-vals for all actions.
else:
input_dict = {"obs": model_out}
# Switch on training mode (when getting Q-values, we are usually in
# training).
input_dict["is_training"] = True
return net(input_dict, [], None)
def get_action_model_outputs(
self,
model_out: TensorType,
state_in: List[TensorType] = None,
seq_lens: TensorType = None,
) -> (TensorType, List[TensorType]):
"""Returns distribution inputs and states given the output of
policy.model().
For continuous action spaces, these will be the mean/stddev
distribution inputs for the (SquashedGaussian) action distribution.
For discrete action spaces, these will be the logits for a categorical
distribution.
Args:
model_out: Feature outputs from the model layers
(result of doing `model(obs)`).
state_in List(TensorType): State input for recurrent cells
seq_lens: Sequence lengths of input- and state
sequences
Returns:
TensorType: Distribution inputs for sampling actions.
"""
def concat_obs_if_necessary(obs: TensorStructType):
"""Concat model outs if they are original tuple observations."""
if isinstance(obs, (list, tuple)):
obs = tf.concat(obs, axis=-1)
elif isinstance(obs, dict):
obs = tf.concat(
[
tf.expand_dims(val, 1) if len(val.shape) == 1 else val
for val in tree.flatten(obs.values())
],
axis=-1,
)
return obs
if state_in is None:
state_in = []
if isinstance(model_out, dict) and "obs" in model_out:
# Model outs may come as original Tuple observations
if isinstance(self.action_model.obs_space, Box):
model_out["obs"] = concat_obs_if_necessary(model_out["obs"])
return self.action_model(model_out, state_in, seq_lens)
else:
if isinstance(self.action_model.obs_space, Box):
model_out = concat_obs_if_necessary(model_out)
return self.action_model({"obs": model_out}, state_in, seq_lens)
def policy_variables(self):
"""Return the list of variables for the policy net."""
return self.action_model.variables()
def q_variables(self):
"""Return the list of variables for Q / twin Q nets."""
return self.q_net.variables() + (
self.twin_q_net.variables() if self.twin_q_net else []
)
| SACTFModel |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_name/invalid_name_enum.py | {
"start": 165,
"end": 826
} | class ____(Enum):
"""Represents colors as (red, green, blue) tuples."""
YELLOW = 250, 250, 0
KHAKI = 250, 250, 125
MAGENTA = 250, 0, 250
VIOLET = 250, 125, 250
CYAN = 0, 250, 250
aquamarine = 125, 250, 250 # [invalid-name]
red: int
green: int
blue: int
def __init__(self, red: int, green: int, blue: int) -> None:
self.red = red
self.green = green
self.blue = blue
@property
def as_hex(self) -> str:
"""Get hex 'abcdef' representation for a color."""
return f'{self.red:0{2}x}{self.green:0{2}x}{self.blue:0{2}x}'
@dataclass
| Color |
python | fluentpython__example-code | attic/iterables/paragraph.py | {
"start": 841,
"end": 1209
} | class ____:
def __init__(self, text):
self.text = text
def __repr__(self):
return 'Paragraph(%s)' % reprlib.repr(self.text)
def __iter__(self):
for match in RE_SENTENCE.finditer(self.text):
yield Sentence(match.group().strip())
def words(self):
for sentence in self:
yield from sentence
| Paragraph |
python | ethereum__web3.py | web3/_utils/threads.py | {
"start": 340,
"end": 2595
} | class ____(Exception):
"""
A limited subset of the `gevent.Timeout` context manager.
"""
seconds = None
exception = None
begun_at = None
is_running = None
def __init__(
self,
seconds: float = None,
exception: type[BaseException] = None,
*args: Any,
**kwargs: Any,
) -> None:
self.seconds = seconds
self.exception = exception
def __enter__(self) -> "Timeout":
self.start()
return self
def __exit__(
self,
exc_type: type[BaseException],
exc_val: BaseException,
exc_tb: TracebackType,
) -> Literal[False]:
return False
def __str__(self) -> str:
if self.seconds is None:
return ""
return f"{self.seconds} seconds"
@property
def expire_at(self) -> int:
if self.seconds is None:
raise Web3ValueError(
"Timeouts with `seconds == None` do not have an expiration time"
)
elif self.begun_at is None:
raise Web3ValueError("Timeout has not been started")
return self.begun_at + self.seconds
def start(self) -> None:
if self.is_running is not None:
raise Web3ValueError("Timeout has already been started")
self.begun_at = time.time()
self.is_running = True
def check(self) -> None:
if self.is_running is None:
raise Web3ValueError("Timeout has not been started")
elif self.is_running is False:
raise Web3ValueError("Timeout has already been cancelled")
elif self.seconds is None:
return
elif time.time() > self.expire_at:
self.is_running = False
if isinstance(self.exception, type):
raise self.exception(str(self))
elif isinstance(self.exception, Exception):
raise self.exception
else:
raise self
def cancel(self) -> None:
self.is_running = False
def sleep(self, seconds: float) -> None:
time.sleep(seconds)
self.check()
async def async_sleep(self, seconds: float) -> None:
await asyncio.sleep(seconds)
self.check()
| Timeout |
python | jazzband__django-redis | django_redis/compressors/gzip.py | {
"start": 124,
"end": 516
} | class ____(BaseCompressor):
min_length = 15
def compress(self, value: bytes) -> bytes:
if len(value) > self.min_length:
return gzip.compress(value)
return value
def decompress(self, value: bytes) -> bytes:
try:
return gzip.decompress(value)
except gzip.BadGzipFile as e:
raise CompressorError from e
| GzipCompressor |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 70132,
"end": 70576
} | class ____(BaseModel):
"""
Message send failures for a particular peer
"""
count: int = Field(..., description="Message send failures for a particular peer")
latest_error: Optional[str] = Field(default=None, description="Message send failures for a particular peer")
latest_error_timestamp: Optional[Union[datetime, date]] = Field(
default=None, description="Timestamp of the latest error"
)
| MessageSendErrors |
python | huggingface__transformers | tests/models/marian/test_modeling_marian.py | {
"start": 22748,
"end": 23265
} | class ____(MarianIntegrationTest):
src = "fi"
tgt = "en"
src_text = [
"minä tykkään kirjojen lukemisesta",
"Pidän jalkapallon katsomisesta",
]
expected_text = ["I like to read books", "I like watching football"]
@classmethod
def setUpClass(cls) -> None:
cls.model_name = "hf-internal-testing/test-opus-tatoeba-fi-en-v2"
return cls
@slow
def test_batch_generation_fi_en(self):
self._assert_generated_batch_equal_expected()
| TestMarian_FI_EN_V2 |
python | pytorch__pytorch | test/inductor/test_split_cat_fx_passes.py | {
"start": 849,
"end": 52864
} | class ____(TestCase):
@torch._inductor.config.patch(
pre_grad_fusion_options={
"normalization_pass": {},
},
post_grad_fusion_options={},
)
def test_split_normalization(self):
def arg_only(x):
return [torch.relu(s) for s in torch.split(x, 2, 1)]
def arg_only_dim0(x):
return [torch.relu(s) for s in torch.split(x, 2, 0)]
def kwarg1(x):
return [torch.relu(s) for s in torch.split(x, 2, dim=1)]
def kwarg2(x):
return [
torch.relu(s) for s in torch.split(x, split_size_or_sections=2, dim=1)
]
def kwarg3(x):
return [
torch.relu(s)
for s in torch.split(tensor=x, split_size_or_sections=2, dim=-1)
]
def list_replace(x):
return [torch.relu(s) for s in torch.split(x, [16, 16], dim=1)]
def multi_split(x):
return [torch.split(s, 2, 1) for s in torch.split(x, 2, 1)]
def unequal_split(x):
return [torch.relu(s) for s in torch.split(x, 3, 1)]
def arg_only_cm(x):
return [torch.relu(s) for s in x.split(2, 1)]
def kwarg1_cm(x):
return [torch.relu(s) for s in x.split(2, dim=1)]
def kwarg2_cm(x):
return [torch.relu(s) for s in x.split(split_size=2, dim=1)]
def multi_split_cm(x):
return [s.split(2, 1) for s in x.split(2, 1)]
def unequal_split_cm(x):
return [torch.relu(s) for s in x.split(3, 1)]
def cm_with_list(x):
return [torch.relu(s) for s in x.split([16, 16], dim=-1)]
def normalize_reshape_with_dynamic_shape(x):
return x.reshape(4, 16)
args = [
torch.randn(2, 32),
]
for fn, dynamic, expected_split_norm_count in [
(arg_only, False, 1),
(arg_only_dim0, False, 1),
(kwarg1, False, 1),
(kwarg2, False, 1),
(kwarg3, False, 1),
(list_replace, False, 0),
(multi_split, False, 17),
(unequal_split, False, 1),
(arg_only_cm, False, 1),
(kwarg1_cm, False, 1),
(kwarg2_cm, False, 1),
(multi_split_cm, False, 17),
(unequal_split_cm, False, 1),
(cm_with_list, False, 1),
(normalize_reshape_with_dynamic_shape, True, 0),
]:
expected = fn(*args)
actual = torch.compile(fn, dynamic=dynamic)(*args)
torch.testing.assert_close(actual, expected)
self.assertEqual(
counters["inductor"]["normalization_pass"],
expected_split_norm_count,
msg=f"for {fn}",
)
counters.clear()
@torch._inductor.config.patch(
pre_grad_fusion_options={
"normalization_pass": {},
},
post_grad_fusion_options={},
)
def test_cat_normalization(self):
def caoncat_only(x):
return torch.concat(list(torch.split(x, 2, 1)), dim=1)
args = [
torch.randn(2, 32),
]
for fn, dynamic, expected_cat_norm_count in [
(caoncat_only, False, 2),
]:
expected = fn(*args)
actual = torch.compile(fn, dynamic=dynamic)(*args)
torch.testing.assert_close(actual, expected)
self.assertEqual(
counters["inductor"]["normalization_pass"],
expected_cat_norm_count,
msg=f"for {fn}",
)
counters.clear()
@patch
def test_consecutive_split_merge(self):
def multi_split(x):
return [torch.split(s, 2, 1) for s in torch.split(x, 2, 1)]
def multi_split_2(x):
return [torch.split(s, 1, 1) for s in torch.split(x, 2, 1)]
def multi_split_2_neg_dim(x):
return [torch.split(s, 1, 1) for s in torch.split(x, 2, -1)]
def multi_split_with_sizes(x):
return [torch.split(s, 2, 1) for s in torch.split(x, [16, 16], 1)]
def multi_split_kwarg1(x):
return [torch.split(s, 2, dim=1) for s in torch.split(x, 2, dim=1)]
def multi_split_kwarg2(x):
return [
torch.split(s, split_size_or_sections=2, dim=1)
for s in torch.split(x, split_size_or_sections=2, dim=1)
]
def unequal_multi_split(x):
fs = torch.split(x, [10, 10, 12], dim=1)
item0 = fs[0]
item1 = fs[1]
item2 = fs[2]
final_items = []
final_items.extend(item0.split([4, 6], 1))
final_items.extend(item1.split([6, 4], 1))
final_items.extend(item2.split([4, 4, 4], 1))
return [torch.relu(s) for s in final_items]
def unequal_multi_split_neg_index(x):
fs = torch.split(x, [10, 10, 12], dim=1)
item0 = fs[-3]
item1 = fs[-2]
item2 = fs[-1]
final_items = []
final_items.extend(item0.split([4, 6], 1))
final_items.extend(item1.split([6, 4], 1))
final_items.extend(item2.split([4, 4, 4], 1))
return [torch.relu(s) for s in final_items]
# Shouldn't merge
def diff_dims(x):
return [torch.split(s, 2, dim=0) for s in torch.split(x, 2, dim=1)]
def some_users_not_splits(x):
fs = torch.split(x, [10, 10, 12], dim=1)
item0 = fs[0]
item1 = fs[1]
item2 = fs[2]
final_items = []
final_items.extend(item0.split([4, 6], 1))
final_items.extend(item1.split([6, 4], 1))
final_items.append(torch.sin(item2))
return [torch.relu(s) for s in final_items]
def split_with_cat(x):
fs = torch.split(x, [4, 4, 24], dim=1)
item0 = fs[0]
item1 = fs[1]
item2 = fs[2]
final_items = [item0, item1]
final_items.extend(item2.split((4, 4, 4, 4, 4, 4), 1))
return torch.cat(final_items, dim=1)
def duplicate_getitems(x):
fs = torch.split(x, [10, 10, 12], dim=1)
item0 = fs[0]
item1_1 = fs[1]
item1_2 = fs[1]
item2 = fs[2]
final_items = []
final_items.extend(item0.split([4, 6], 1))
final_items.extend(item1_1.split([6, 4], 1))
final_items.extend(item1_2)
final_items.append(torch.sin(item2))
return [torch.relu(s) for s in final_items]
def duplicate_getitems_neg_index(x):
fs = torch.split(x, [10, 10, 12], dim=1)
item0 = fs[0]
item1_1 = fs[1]
item1_2 = fs[-2] # negative index
item2 = fs[2]
final_items = []
final_items.extend(item0.split([4, 6], 1))
final_items.extend(item1_1.split([6, 4], 1))
final_items.extend(item1_2)
final_items.append(torch.sin(item2))
return [torch.relu(s) for s in final_items]
def split_getitem_gap(x):
fs = torch.split(x, [4, 4, 24], dim=1)
item0 = fs[0]
item2 = fs[2]
final_items = [
item0,
]
final_items.extend(item2.split((4, 4, 4, 4, 4, 4), 1))
return torch.cat(final_items, dim=1)
def split_getitem_out_of_order(x):
fs = torch.split(x, [4, 4, 4, 20], dim=1)
item0 = fs[0]
item2 = fs[2]
item1 = fs[1]
item3 = fs[3]
final_items = [item0, item2, item1]
final_items.extend(item3.split((4, 4, 4, 4, 4), 1))
return torch.cat(final_items, dim=1)
def split_partial_getitem_cat(x):
fs = torch.split(x, [4, 4, 24], dim=1)
item0 = fs[0]
item2 = fs[2]
final_items = [
item0,
]
final_items.extend(item2.split((4, 4, 4, 4, 4, 4), 1))
return torch.cat(final_items, dim=1)
def next_split_getitem_partial_used(x):
fs = torch.split(x, [4, 4, 24], dim=1)
item0 = fs[0]
item2 = fs[2]
final_items = [item0]
ns = item2.split((4, 4, 4, 4, 4, 4), 1)
final_items.extend(ns[0:1])
final_items.extend(ns[3:4])
return torch.cat(final_items, dim=1)
args = [
torch.randn(2, 32),
]
for fn, expected_split_merged in [
(multi_split, 0),
(multi_split_2, 16),
(multi_split_2_neg_dim, 16),
(multi_split_with_sizes, 2),
(multi_split_kwarg1, 0),
(multi_split_kwarg2, 0),
(unequal_multi_split, 3),
(unequal_multi_split_neg_index, 3),
(diff_dims, 0),
(some_users_not_splits, 2),
(split_with_cat, 1),
(duplicate_getitems, 1),
(duplicate_getitems_neg_index, 1),
(split_getitem_gap, 1),
(split_getitem_out_of_order, 1),
(next_split_getitem_partial_used, 1),
(split_partial_getitem_cat, 1),
]:
expected = fn(*args)
actual = torch.compile(fn)(*args)
torch.testing.assert_close(actual, expected)
self.assertEqual(
counters["inductor"]["merge_splits_pass"],
expected_split_merged,
)
counters.clear()
@patch
def test_split_cat_merge(self):
def simple_split_cat(x):
return torch.cat(torch.split(x, 4, dim=1), dim=1)
def simple_split_cat_argspec1(x):
return torch.cat(torch.split(x, 4, dim=1), 1)
def simple_split_cat_argspec2(x):
return torch.cat(tensors=torch.split(x, 4, dim=1), dim=1)
def simple_split_cat_argspec3(x):
return torch.cat(torch.split(x, 4, dim=1), -2)
def simple_split_cat_argspec4(x):
return torch.cat(tensors=torch.split(x, 4, dim=1), dim=-2)
def simple_split_stack(x):
return torch.stack(torch.split(x, 4, dim=1), dim=1)
def simple_split_stack_argspec1(x):
return torch.stack(torch.split(x, 4, dim=1), 1)
def simple_split_stack_argspec2(x):
return torch.stack(tensors=torch.split(x, 4, dim=1), dim=1)
def split_cat_addn_args(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.cat(
[torch.ones(2, 5, 32, 16)] + split_output + [torch.ones(2, 6, 32, 16)],
dim=1,
)
def split_stack_addn_args(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.stack(
[torch.ones(2, 4, 32, 16)]
+ split_output
+ [torch.ones(2, 4, 32, 16), torch.ones(2, 4, 32, 16)],
dim=1,
)
def split_cat_addn_args_dim2(x):
split_output = list(torch.split(x, 4, dim=2))
return torch.cat(
[torch.ones(2, 32, 5, 16)] + split_output + [torch.ones(2, 32, 6, 16)],
dim=2,
)
# split_dim=1, cat_dim=2
def split_cat_dim_mismatch(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.cat(
[torch.ones(2, 4, 32, 16)] + split_output + [torch.ones(2, 4, 32, 16)],
dim=2,
)
def split_stack_dim_mismatch(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.stack(
[torch.ones(2, 4, 32, 16)] + split_output + [torch.ones(2, 4, 32, 16)],
dim=2,
)
# split_dim=1, cat_dim=3
def split_cat_dim_mismatch2(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.cat(
[torch.ones(2, 4, 32, 16)] + split_output + [torch.ones(2, 4, 32, 16)],
dim=3,
)
def split_stack_dim_mismatch2(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.stack(
[torch.ones(2, 4, 32, 16)] + split_output + [torch.ones(2, 4, 32, 16)],
dim=3,
)
# split_dim=2, cat_dim=0
def split_cat_dim_mismatch3(x):
split_output = list(torch.split(x, 4, dim=2))
return torch.cat(
[torch.ones(2, 32, 4, 16)] + split_output + [torch.ones(2, 32, 4, 16)],
dim=0,
)
def split_stack_dim_mismatch3(x):
split_output = list(torch.split(x, 4, dim=2))
return torch.stack(
[torch.ones(2, 32, 4, 16)] + split_output + [torch.ones(2, 32, 4, 16)],
dim=0,
)
def input_shuffling(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.cat(
[torch.ones(2, 4, 32, 16)]
+ [split_output[1], split_output[2], split_output[3]]
+ [torch.ones(2, 4, 32, 16)]
+ [split_output[5], split_output[6], split_output[7]]
+ [torch.ones(2, 4, 32, 16)],
dim=1,
)
def input_shuffling_stack(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.stack(
[torch.ones(2, 4, 32, 16)]
+ [split_output[1], split_output[2], split_output[3]]
+ [torch.ones(2, 4, 32, 16)]
+ [split_output[5], split_output[6], split_output[7]]
+ [torch.ones(2, 4, 32, 16)],
dim=1,
)
def input_shuffling_dim_mismatch(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.cat(
[torch.ones(2, 4, 32, 16)]
+ [split_output[1], split_output[2], split_output[3]]
+ [torch.ones(2, 4, 32, 16)]
+ [split_output[5], split_output[6], split_output[7]]
+ [torch.ones(2, 4, 32, 16)],
dim=2,
)
def input_shuffling_dim_mismatch_stack(x):
split_output = list(torch.split(x, 4, dim=1))
return torch.stack(
[torch.ones(2, 4, 32, 16)]
+ [split_output[1], split_output[2], split_output[3]]
+ [torch.ones(2, 4, 32, 16)]
+ [split_output[5], split_output[6], split_output[7]]
+ [torch.ones(2, 4, 32, 16)],
dim=2,
)
def input_shuffling_multiple_output(x):
split_output = list(torch.split(x, 4, dim=1))
cat1 = torch.cat(
[torch.ones(2, 4, 32, 16)]
+ [split_output[1], split_output[2], split_output[3]]
+ [torch.ones(2, 4, 32, 16)],
dim=2,
)
stack1 = torch.stack(
[
torch.ones(2, 4, 32, 16),
split_output[4],
split_output[5],
torch.ones(2, 4, 32, 16),
],
dim=1,
)
relu1 = torch.relu(split_output[6])
return cat1, stack1, relu1
def input_shuffling_direct_output(x):
split_output = list(torch.split(x, 4, dim=1))
cat1 = torch.cat(
[torch.ones(2, 4, 32, 16)]
+ [split_output[1], split_output[2], split_output[3]]
+ [torch.ones(2, 4, 32, 16)],
dim=2,
)
stack1 = torch.stack(
[
torch.ones(2, 4, 32, 16),
split_output[4],
split_output[5],
torch.ones(2, 4, 32, 16),
],
dim=1,
)
return cat1, stack1, split_output[6]
def input_shuffling_multiple_output_same_ranges(x):
split_output = list(torch.split(x, 4, dim=1))
cat1 = torch.cat(
[torch.ones(2, 4, 32, 16)]
+ [split_output[1], split_output[2], split_output[3]]
+ [torch.ones(2, 4, 32, 16)],
dim=2,
)
cat2 = torch.cat(
[torch.ones(2, 4, 32, 16)]
+ [split_output[1], split_output[2], split_output[3]]
+ [torch.ones(2, 4, 32, 16)],
dim=2,
)
stack1 = torch.stack(
[
torch.ones(2, 4, 32, 16),
split_output[4],
split_output[5],
torch.ones(2, 4, 32, 16),
],
dim=1,
)
relu1 = torch.relu(split_output[6])
return cat1, cat2, stack1, relu1
def unequal_split_multiple_output(x):
split_output = list(torch.split(x, [2, 4, 4, 4, 4, 4, 8, 2], dim=1))
cat1 = torch.cat(
[torch.ones(2, 4, 32, 16)]
+ [split_output[1], split_output[2], split_output[3]]
+ [torch.ones(2, 4, 32, 16)],
dim=2,
)
stack1 = torch.stack(
[
torch.ones(2, 4, 32, 16),
split_output[4],
split_output[5],
torch.ones(2, 4, 32, 16),
],
dim=1,
)
relu1 = torch.relu(split_output[6])
return cat1, stack1, relu1
def multi_split_cat(x1, x2):
split_output_1 = list(torch.split(x1, 4, dim=1))
split_output_2 = list(torch.split(x2, 4, dim=1))
cat1 = torch.cat(
[torch.ones(2, 4, 32, 16)]
+ [split_output_1[1], split_output_1[2], split_output_1[3]]
+ [torch.ones(2, 4, 32, 16)]
+ [split_output_2[1], split_output_2[2], split_output_2[3]]
+ [torch.ones(2, 4, 32, 16)],
dim=2,
)
stack1 = torch.stack(
[
torch.ones(2, 4, 32, 16),
split_output_1[4],
split_output_1[5],
torch.ones(2, 4, 32, 16),
split_output_2[4],
split_output_2[5],
torch.ones(2, 4, 32, 16),
],
dim=1,
)
relu1 = torch.relu(split_output_1[6])
relu2 = torch.relu(split_output_2[6])
return cat1, stack1, relu1, relu2
# TODO: Add more tests:
# * Cases where replacement shouldn't happen
default_args = [
torch.randn(2, 32, 32, 16),
]
multi_args = [
torch.randn(2, 32, 32, 16),
torch.randn(2, 32, 32, 16),
]
for (
fn,
expected_split_added,
expected_split_removed,
expected_cat_added,
expected_cat_removed,
expected_sections_removed,
args,
) in [
(simple_split_cat, 0, 0, 0, 0, 0, default_args),
(simple_split_cat_argspec1, 0, 0, 0, 0, 0, default_args),
(simple_split_cat_argspec2, 0, 0, 0, 0, 0, default_args),
(simple_split_cat_argspec3, 0, 1, 0, 1, 7, default_args),
(simple_split_cat_argspec4, 0, 1, 0, 1, 7, default_args),
(simple_split_stack, 0, 1, 0, 1, 7, default_args),
(simple_split_stack_argspec1, 0, 1, 0, 1, 7, default_args),
(simple_split_stack_argspec2, 0, 1, 0, 1, 7, default_args),
(split_cat_addn_args, 0, 1, 1, 1, 7, default_args),
(split_stack_addn_args, 0, 1, 1, 1, 7, default_args),
(split_cat_addn_args_dim2, 0, 1, 1, 1, 7, default_args),
(split_cat_dim_mismatch, 0, 1, 1, 1, 7, default_args),
(split_stack_dim_mismatch, 0, 1, 1, 1, 7, default_args),
(split_cat_dim_mismatch2, 0, 1, 1, 1, 7, default_args),
(split_stack_dim_mismatch2, 0, 1, 1, 1, 7, default_args),
(split_cat_dim_mismatch3, 0, 1, 1, 1, 7, default_args),
(split_stack_dim_mismatch3, 0, 1, 1, 1, 7, default_args),
(input_shuffling, 1, 1, 1, 1, 4, default_args),
(input_shuffling_stack, 1, 1, 1, 1, 4, default_args),
(input_shuffling_dim_mismatch, 1, 1, 1, 1, 4, default_args),
(input_shuffling_dim_mismatch_stack, 1, 1, 1, 1, 4, default_args),
(input_shuffling_multiple_output, 1, 1, 2, 2, 3, default_args),
(input_shuffling_direct_output, 1, 1, 2, 2, 3, default_args),
(unequal_split_multiple_output, 1, 1, 2, 2, 3, default_args),
(multi_split_cat, 1, 1, 2, 2, 3, multi_args),
]:
expected = fn(*args)
actual = torch.compile(fn)(*args)
torch.testing.assert_close(actual, expected)
self.assertEqual(
counters["inductor"]["scmerge_split_added"],
expected_split_added,
)
self.assertEqual(
counters["inductor"]["scmerge_split_removed"],
expected_split_removed,
)
self.assertEqual(
counters["inductor"]["scmerge_cat_added"],
expected_cat_added,
)
self.assertEqual(
counters["inductor"]["scmerge_cat_removed"],
expected_cat_removed,
)
self.assertEqual(
counters["inductor"]["scmerge_split_sections_removed"],
expected_sections_removed,
)
counters.clear()
@torch._inductor.config.patch(
pre_grad_fusion_options={},
post_grad_fusion_options={},
)
def test_config_flag_is_respected(self):
def split_with_cat(x):
fs = torch.split(x, [4, 4, 24], dim=-1)
item0 = fs[0]
item1 = fs[1]
item2 = fs[2]
final_items = [item0, item1]
final_items.extend(item2.split((4, 4, 4, 4, 4, 4), 1))
return torch.cat(final_items, dim=1)
args = [
torch.randn(2, 32),
]
expected = split_with_cat(*args)
actual = torch.compile(split_with_cat)(*args)
torch.testing.assert_close(actual, expected)
self.assertEqual(
counters["inductor"]["merge_splits_pass"],
0,
)
self.assertEqual(
counters["inductor"]["normalization_pass"],
0,
)
@patch
def test_split_cat_merge_mutation(self):
args = [
torch.randn(2, 32, 32, 16),
]
def split_cat_mutation(x):
splits = torch.split(x, 4, dim=1)
splits[1].copy_(splits[0])
return torch.cat(splits, dim=1)
expected = split_cat_mutation(*args)
actual = torch.compile(split_cat_mutation)(*args)
torch.testing.assert_close(actual, expected)
self.assertEqual(counters["inductor"]["scmerge_split_removed"], 0)
self.assertEqual(counters["inductor"]["scmerge_cat_removed"], 0)
@patch
def test_split_squeeze(self):
def split_squeeze_stack(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, 1) for s in items]
return torch.stack(split_items)
def split_squeeze_stack_callmethod(x):
items = list(torch.split(x, 1, dim=1))
split_items = [s.squeeze(1) for s in items]
return torch.stack(split_items)
def split_squeeze_stack_callmethod_none_dim(x):
items = list(torch.split(x, 1, dim=1))
split_items = [s.squeeze() for s in items]
return torch.stack(split_items)
def split_squeeze_stack_kwarg1(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, dim=1) for s in items]
return torch.stack(split_items)
def split_squeeze_stack_kwarg1_callmethod(x):
items = list(torch.split(x, 1, dim=1))
split_items = [s.squeeze(dim=1) for s in items]
return torch.stack(split_items)
def split_squeeze_multi_squeeze_users(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, 1) for s in items]
return (
torch.stack(split_items),
torch.relu(split_items[0]),
torch.tanh(split_items[1]),
)
def split_size_not_1(x):
items = list(torch.split(x, 2, dim=1))
split_items = [torch.squeeze(s, 1) for s in items]
return torch.stack(split_items)
def dim_mismatch(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, 0) for s in items]
return torch.stack(split_items)
def other_users(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, 1) for s in items]
return torch.stack(split_items), torch.relu(items[0])
def other_users_2(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, 1) for s in items[1:]]
return torch.stack(split_items), torch.relu(items[0])
def graph_should_be_topological_sorted(x):
output = []
for t in x.split(1):
output.append(torch.sin(t.squeeze(dim=0)))
output = torch.stack(output)
return output
args = [
torch.randn(2, 32),
]
for fn, split_squeeze_replaced in [
(split_squeeze_stack, 1),
(split_squeeze_stack_callmethod, 1),
# TODO handle none dim
(split_squeeze_stack_callmethod_none_dim, 0),
(split_squeeze_stack_kwarg1, 1),
(split_squeeze_stack_kwarg1_callmethod, 1),
(split_squeeze_multi_squeeze_users, 1),
(split_size_not_1, 0),
(dim_mismatch, 0),
(other_users, 0),
(other_users_2, 0),
(graph_should_be_topological_sorted, 1),
]:
expected = fn(*args)
actual = torch.compile(fn)(*args)
torch.testing.assert_close(actual, expected)
self.assertEqual(
counters["inductor"]["split_cat_pass"],
split_squeeze_replaced,
)
counters.clear()
@patch
def test_unbind_stack(self):
def unbind_stack(x):
return torch.stack(torch.unbind(x, 1), 1)
def unbind_cat(x): # noqa: F841
return torch.cat(torch.unbind(x, dim=-3), 1)
def unbind_stack_argspec1(x):
return torch.stack(torch.unbind(input=x, dim=1), dim=1)
def unbind_stack_argspec2(x):
return torch.stack(tensors=torch.unbind(x, dim=1), dim=1)
def dim_mismatch(x):
return torch.stack(torch.unbind(x, dim=1), 0)
def split_squeeze_stack(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, 1) for s in items]
return torch.stack(split_items, 1)
def split_squeeze_stack_callmethod(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, 1) for s in items]
return torch.stack(split_items, 1)
def other_users(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, 1) for s in items]
return torch.stack(split_items, 1), torch.relu(items[0])
def other_users_2(x):
items = list(torch.split(x, 1, dim=1))
split_items = [torch.squeeze(s, 1) for s in items[1:]]
return torch.stack(split_items, 1), torch.relu(items[0])
def unbind_cat_addn_args(x):
split_output = list(torch.unbind(x, dim=1))
return torch.cat(
[torch.ones(2, 32, 16)] + split_output + [torch.ones(2, 32, 16)],
dim=1,
)
def unbind_stack_addn_args(x):
split_output = list(torch.unbind(x, dim=1))
return torch.stack(
[torch.ones(2, 32, 16)]
+ split_output
+ [torch.ones(2, 32, 16), torch.ones(2, 32, 16)],
dim=1,
)
def unbind_cat_addn_args_dim2(x):
split_output = list(torch.unbind(x, dim=2))
return torch.cat(
[torch.ones(2, 32, 16)] + split_output + [torch.ones(2, 32, 16)],
dim=2,
)
# split_dim=1, cat_dim=2
def unbind_cat_dim_mismatch(x):
split_output = list(torch.unbind(x, dim=1))
return torch.cat(
[torch.ones(2, 32, 16)] + split_output + [torch.ones(2, 32, 16)],
dim=2,
)
def unbind_stack_dim_mismatch(x):
split_output = list(torch.unbind(x, dim=1))
return torch.stack(
[torch.ones(2, 32, 16)] + split_output + [torch.ones(2, 32, 16)],
dim=2,
)
def unbind_cat_multi_users(x):
split_output = list(torch.unbind(x, dim=1))
return torch.cat(
[torch.ones(2, 32, 16)] + split_output + [torch.ones(2, 32, 16)],
dim=1,
), torch.stack(
[torch.ones(2, 32, 16)]
+ split_output
+ [torch.ones(2, 32, 16), torch.ones(2, 32, 16)],
dim=1,
)
def unbind_cat_multi_users_diff_dims(x):
split_output = list(torch.unbind(x, dim=1))
return torch.cat(
[torch.ones(2, 32, 16)] + split_output + [torch.ones(2, 32, 16)],
dim=1,
), torch.stack(
[torch.ones(2, 32, 16)] + split_output + [torch.ones(2, 32, 16)],
dim=2,
)
args = [
torch.randn(2, 32, 32, 16),
]
for (
fn,
expected_unbind_added,
expected_unbind_removed,
expected_cat_added,
expected_cat_removed,
expected_sections_removed,
expected_unbind_normalized,
) in [
(unbind_stack, 0, 1, 0, 1, 31, 2),
(unbind_stack_argspec1, 0, 1, 0, 1, 31, 2),
(unbind_stack_argspec2, 0, 1, 0, 1, 31, 2),
(dim_mismatch, 0, 1, 0, 1, 31, 2),
(split_squeeze_stack, 0, 1, 0, 1, 31, 2),
(split_squeeze_stack_callmethod, 0, 1, 0, 1, 31, 2),
(other_users, 0, 0, 0, 0, 0, 2),
(other_users_2, 0, 0, 0, 0, 0, 2),
(unbind_cat_addn_args, 0, 1, 1, 1, 31, 1),
(unbind_stack_addn_args, 0, 1, 1, 1, 31, 2),
(unbind_cat_addn_args_dim2, 0, 1, 1, 1, 31, 1),
(unbind_cat_dim_mismatch, 0, 1, 1, 1, 31, 1),
(unbind_stack_dim_mismatch, 0, 1, 1, 1, 31, 2),
(unbind_cat_multi_users, 0, 1, 2, 2, 31, 2),
(unbind_cat_multi_users_diff_dims, 0, 1, 2, 2, 31, 2),
]:
expected = fn(*args)
actual = torch.compile(fn)(*args)
torch.testing.assert_close(actual, expected)
self.assertEqual(
counters["inductor"]["scmerge_split_added"],
expected_unbind_added,
msg=f"for {fn}",
)
self.assertEqual(
counters["inductor"]["scmerge_split_removed"],
expected_unbind_removed,
msg=f"for {fn}",
)
self.assertEqual(
counters["inductor"]["scmerge_cat_added"],
expected_cat_added,
msg=f"for {fn}",
)
self.assertEqual(
counters["inductor"]["scmerge_cat_removed"],
expected_cat_removed,
msg=f"for {fn}",
)
self.assertEqual(
counters["inductor"]["scmerge_split_sections_removed"],
expected_sections_removed,
msg=f"for {fn}",
)
self.assertEqual(
counters["inductor"]["normalization_pass"],
expected_unbind_normalized,
msg=f"for {fn}",
)
counters.clear()
@patch
def test_split_cat_new_patterns(self):
def split_cat_split(x):
l1_out = torch.split(x, [200, 50, 50, 20, 20, 20, 20, 20, 20, 50, 30], 1)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
item5 = l1_out[5]
item6 = l1_out[6]
item7 = l1_out[7]
item8 = l1_out[8]
item9 = l1_out[9]
item10 = l1_out[10]
cat_1 = torch.cat((item0, item1), 1)
cat_2 = torch.cat((item9, item10), 1)
l2_out = torch.split(cat_1, [50, 120, 80], 1)
l3_out = torch.split(cat_2, [10, 20, 50], 1)
item11 = l2_out[0]
item12 = l2_out[1]
item13 = l2_out[2]
item14 = l3_out[0]
item15 = l3_out[1]
item16 = l3_out[2]
output = torch.cat(
[
item11,
item12,
item13,
item14,
item15,
item16,
item2,
item3,
item4,
item5,
item6,
item7,
item8,
],
1,
)
return output
def split_cat_split_kwarg(x):
l1_out = torch.split(
x, [200, 50, 50, 20, 20, 20, 20, 20, 20, 50, 30], dim=1
)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
item5 = l1_out[5]
item6 = l1_out[6]
item7 = l1_out[7]
item8 = l1_out[8]
item9 = l1_out[9]
item10 = l1_out[10]
cat_1 = torch.cat((item0, item1), dim=1)
cat_2 = torch.cat((item9, item10), dim=1)
l2_out = torch.split(cat_1, [50, 120, 80], dim=1)
l3_out = torch.split(cat_2, [10, 20, 50], dim=1)
item11 = l2_out[0]
item12 = l2_out[1]
item13 = l2_out[2]
item14 = l3_out[0]
item15 = l3_out[1]
item16 = l3_out[2]
output = torch.cat(
[
item11,
item12,
item13,
item14,
item15,
item16,
item2,
item3,
item4,
item5,
item6,
item7,
item8,
],
dim=1,
)
return output
def remove_cat_node_with_all_getitmes(x):
l1_out = torch.split(
x, [50, 50, 200, 20, 20, 20, 20, 20, 40, 10, 50], dim=0
)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
item5 = l1_out[5]
item6 = l1_out[6]
item7 = l1_out[7]
item8 = l1_out[8]
item9 = l1_out[9]
item10 = l1_out[10]
cat = torch.cat(
(
item0,
item1,
item2,
item3,
item4,
item5,
item6,
item7,
item8,
item9,
item10,
),
dim=0,
)
cat_1 = torch.cat((item0, item1), dim=0)
cat_2 = torch.cat((item0, item10), dim=0)
l2_out = torch.split(cat_1, [20, 30, 50], dim=0)
l3_out = torch.split(cat_2, [10, 60, 30], dim=0)
item11 = l2_out[0]
item12 = l2_out[1]
item13 = l2_out[2]
item14 = l3_out[0]
item15 = l3_out[1]
item16 = l3_out[2]
output = torch.cat(
[
item11,
item12,
item13,
item14,
item15,
item16,
item2,
item3,
item4,
item5,
item6,
item7,
item8,
],
dim=0,
)
return torch.cat((output, cat), dim=0)
def mutate_cat_node_with_some_getitmes(x):
l1_out = torch.split(
x, [50, 50, 200, 20, 20, 20, 20, 20, 40, 10, 50], dim=0
)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
item5 = l1_out[5]
item6 = l1_out[6]
item7 = l1_out[7]
item8 = l1_out[8]
item9 = l1_out[9]
item10 = l1_out[10]
cat = torch.cat(
(
item6,
item7,
item8,
item9,
item10,
item2,
item3,
item4,
item5,
),
dim=0,
)
cat_1 = torch.cat((item0, item1), dim=0)
cat_2 = torch.cat((item0, item10), dim=0)
l2_out = torch.split(cat_1, [20, 30, 50], dim=0)
l3_out = torch.split(cat_2, [10, 60, 30], dim=0)
item11 = l2_out[0]
item12 = l2_out[1]
item13 = l2_out[2]
item14 = l3_out[0]
item15 = l3_out[1]
item16 = l3_out[2]
output = torch.cat(
[
item11,
item12,
item13,
item14,
item15,
item16,
item2,
],
dim=0,
)
return torch.cat((output, cat), dim=0)
@torch._inductor.config.patch(
pre_grad_fusion_options={
"split_cat_to_slices_pass": {},
},
post_grad_fusion_options={},
)
def split_cat_to_slices(x):
x_c = x.clone()
x_c_2 = x.clone()
l1_out = torch.split(x, [50, 50, 50, 50, 50, 50, 50, 50, 50, 50], dim=0)
l2_out = torch.split(x_c, [50, 50, 50, 50, 50, 50, 50, 50, 50, 50], dim=0)
l3_out = torch.split(x_c_2, [100, 100, 100, 100, 100], dim=0)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
item5 = l1_out[5]
item6 = l1_out[6]
item7 = l1_out[7]
item8 = l1_out[8]
item9 = l1_out[9]
item0_c = l2_out[0]
item1_c = l2_out[1]
item2_c = l2_out[2]
item3_c = l2_out[3]
item4_c = l2_out[4]
item5_c = l2_out[5]
item6_c = l2_out[6]
item7_c = l2_out[7]
item8_c = l2_out[8]
item9_c = l2_out[9]
item0_c_2 = l3_out[0]
item1_c_2 = l3_out[1]
item2_c_2 = l3_out[2]
item3_c_2 = l3_out[3]
item4_c_2 = l3_out[4]
other = item0.clone()
return torch.cat(
[
other,
item0,
item1,
item2,
item3,
item4,
item5,
item6,
item7,
item8,
item9,
item4_c,
item5_c,
item6_c,
item7_c,
item8_c,
item9_c,
item0_c,
item1_c,
item2_c,
item3_c,
item0_c_2,
item1_c_2,
item2_c_2,
item3_c_2,
item4_c_2,
],
dim=0,
)
@torch._inductor.config.patch(
pre_grad_fusion_options={
"unbind_cat_to_view_pass": {},
},
post_grad_fusion_options={},
)
def unbind_cat_to_view(x):
y = x.view(10, 50, 500)
z = x.view(10, 50, 500)
l1_out = torch.unbind(y, dim=0)
l2_out = torch.unbind(z, dim=0)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
item5 = l1_out[5]
item6 = l1_out[6]
item7 = l1_out[7]
item8 = l1_out[8]
item9 = l1_out[9]
item2_0 = l2_out[0]
item2_1 = l2_out[1]
item2_2 = l2_out[2]
item2_3 = l2_out[3]
item2_4 = l2_out[4]
item2_5 = l2_out[5]
item2_6 = l2_out[6]
item2_7 = l2_out[7]
item2_8 = l2_out[8]
item2_9 = l2_out[9]
other1 = item7.clone()
other2 = item8.clone()
other3 = item9.clone()
cat = torch.cat(
[
item0,
item1,
item2,
item3,
item4,
item5,
item6,
other1,
item2_0,
item2_1,
item2_2,
item2_3,
item2_4,
item2_5,
item2_6,
item2_7,
item2_8,
item2_9,
other2,
other3,
],
dim=1,
)
return cat
@torch._inductor.config.patch(
pre_grad_fusion_options={
"split_stack_to_cats_pass": {},
},
post_grad_fusion_options={},
)
def split_stack_to_cats_same_dim(x):
x_c = x.view(10, 50, 500)
l1_out = torch.unbind(x_c, dim=0)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
item5 = l1_out[5]
split1 = torch.split(item0, [250, 250], dim=1)
split2 = torch.split(item1, [250, 250], dim=1)
split3 = torch.split(item2, [250, 250], dim=1)
split4 = torch.split(item3, [250, 250], dim=1)
split5 = torch.split(item4, [250, 250], dim=1)
split6 = torch.split(item5, [250, 250], dim=1)
getitem0, getitem1 = split1[0], split1[1]
getitem2, getitem3 = split2[0], split2[1]
getitem4, getitem5 = split3[0], split3[1]
getitem6, getitem7 = split4[0], split4[1]
getitem8, getitem9 = split5[0], split5[1]
getitem10, getitem11 = split6[0], split6[1]
getitem0_c = getitem0.clone()
getitem1_c = getitem1.clone()
getitem2_c = getitem2.clone()
return torch.stack(
(
getitem0,
getitem1,
getitem2,
getitem3,
getitem4,
getitem5,
getitem0_c,
getitem1_c,
getitem6,
getitem7,
getitem8,
getitem9,
getitem10,
getitem11,
getitem2_c,
),
dim=1,
)
@torch._inductor.config.patch(
pre_grad_fusion_options={
"split_stack_to_cats_pass": {},
},
post_grad_fusion_options={},
)
def split_stack_to_cats_different_dim(x):
l1_out = torch.split(x, [100, 100, 100, 100, 100], dim=1)
x_c = x.clone()
l2_out = torch.split(x_c, [100, 100, 100, 100, 100], dim=1)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
item0_c = l2_out[0]
item1_c = l2_out[1]
item2_c = l2_out[2]
item3_c = l2_out[3]
item4_c = l2_out[4]
other_1 = item0.clone()
other_2 = item1.clone()
other_3 = item2.clone()
return torch.stack(
(
other_1,
other_2,
other_3,
item0,
item1,
item2,
item3,
item4,
item0_c,
item1_c,
item2_c,
item3_c,
item4_c,
),
dim=2,
)
@torch._inductor.config.patch(
pre_grad_fusion_options={
"unbind_stack_to_slices_pass": {},
},
post_grad_fusion_options={},
)
def unbind_stack_to_slices(x):
x_1 = x.view(50, 10, 500)
l1_out = torch.unbind(x_1, dim=1)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
item5 = l1_out[5]
item6 = l1_out[6]
item7 = l1_out[7]
item8 = l1_out[8]
item9 = l1_out[9]
other_1 = item0.clone()
other_2 = item1.clone()
other_3 = item2.clone()
return torch.stack(
(
other_1,
other_2,
other_3,
item0,
item1,
item2,
item3,
item4,
item5,
item6,
item7,
item8,
item9,
),
dim=1,
)
@torch._inductor.config.patch(
pre_grad_fusion_options={
"normalization_pass": {},
"move_reshape_out_of_split_stack_pass": {},
},
post_grad_fusion_options={},
)
def move_reshape_out_of_split_stack(x):
x_c = x.view(50000, 5)
l1_out = torch.split(x_c, [1, 1, 1, 1, 1], dim=1)
item0 = l1_out[0]
item1 = l1_out[1]
item2 = l1_out[2]
item3 = l1_out[3]
item4 = l1_out[4]
reshape0 = item0.reshape(-1, 5)
reshape1 = item1.reshape(-1, 5)
reshape2 = item2.reshape(-1, 5)
reshape3 = item3.reshape(-1, 5)
reshape4 = item4.reshape(-1, 5)
other0 = reshape0.clone()
other1 = reshape1.clone()
other2 = reshape2.clone()
other3 = reshape3.clone()
return torch.stack(
(
other0,
other1,
other2,
reshape0,
reshape1,
reshape2,
reshape3,
reshape4,
other3,
),
dim=0,
)
args = [
torch.randn(500, 500),
]
for (
fn,
expected_getitem_cat_merged,
expected_cat_removed,
expected_split_cat_to_slices,
exptected_unbind_to_cat_view,
expected_split_stack_to_cats,
exptected_unbind_stack_to_slices,
expected_move_reshape_out_of_split_stack,
) in [
(split_cat_split, 2, 0, 0, 0, 0, 0, 0),
(split_cat_split_kwarg, 2, 0, 0, 0, 0, 0, 0),
(remove_cat_node_with_all_getitmes, 0, 2, 0, 0, 0, 0, 0),
(mutate_cat_node_with_some_getitmes, 0, 1, 0, 0, 0, 0, 0),
(split_cat_to_slices, 0, 0, 1, 0, 0, 0, 0),
(unbind_cat_to_view, 0, 0, 0, 1, 0, 0, 0),
(split_stack_to_cats_same_dim, 0, 0, 0, 0, 1, 0, 0),
(split_stack_to_cats_different_dim, 0, 0, 0, 0, 1, 0, 0),
(unbind_stack_to_slices, 0, 0, 0, 0, 0, 1, 0),
(move_reshape_out_of_split_stack, 0, 0, 0, 0, 0, 0, 1),
]:
expected = fn(*args)
actual = torch.compile(fn)(*args)
torch.testing.assert_close(actual, expected)
self.assertEqual(
counters["inductor"]["merge_getitem_cat_pass"],
expected_getitem_cat_merged,
)
self.assertEqual(
counters["inductor"]["mutate_cat_pass"],
expected_cat_removed,
)
self.assertEqual(
counters["inductor"]["split_cat_to_slices_pass"],
expected_split_cat_to_slices,
)
self.assertEqual(
counters["inductor"]["unbind_cat_to_view_pass"],
exptected_unbind_to_cat_view,
)
self.assertEqual(
counters["inductor"]["split_stack_to_cats_pass"],
expected_split_stack_to_cats,
)
self.assertEqual(
counters["inductor"]["unbind_stack_to_slices_pass"],
exptected_unbind_stack_to_slices,
)
self.assertEqual(
counters["inductor"]["move_reshape_out_of_split_stack_pass"],
expected_move_reshape_out_of_split_stack,
)
counters.clear()
def test_numpy_compat_normalization(self):
def fn(x, y):
a = torch.stack([x, y], axis=1)
b = torch.mul(x, x2=y)
c = torch.mul(x, x2=y)
d = torch.mul(x, x2=y)
e = torch.max(x, dim=1, keepdims=True)
f = torch.dropout(x=x, p=0.5, train=True)
return a, b, c, d, e, f
fn_t = torch.fx.symbolic_trace(fn)
numpy_compat_normalization(fn_t.graph)
for n in fn_t.graph.nodes:
for k in n.kwargs:
self.assertTrue(k not in {"x", "x1", "x2", "a", "axis", "keepdims"})
@patch
@requires_gpu
def test_stack_normalization_axis_kwarg(self):
def fn(x, y):
return torch.stack([x, y], axis=1)
x, y = (torch.rand((4, 4), device=GPU_TYPE) for _ in range(2))
expected = fn(x, y)
actual = torch.compile(fn)(x, y)
self.assertEqual(actual, expected)
if __name__ == "__main__":
if IS_LINUX and HAS_GPU:
run_tests()
| TestSplitCatFxPasses |
python | PrefectHQ__prefect | tests/utilities/test_callables.py | {
"start": 15724,
"end": 19529
} | class ____:
def test_methods_with_no_arguments(self):
class Foo:
def f(self):
pass
@classmethod
def g(cls):
pass
@staticmethod
def h():
pass
for method in [Foo().f, Foo.g, Foo.h]:
schema = callables.parameter_schema(method)
assert schema.model_dump_for_openapi() == {
"properties": {},
"title": "Parameters",
"type": "object",
"definitions": {},
}
def test_methods_with_enum_arguments(self):
class Color(Enum):
RED = "RED"
GREEN = "GREEN"
BLUE = "BLUE"
class Foo:
def f(self, color: Color = "RED"):
pass
@classmethod
def g(cls, color: Color = "RED"):
pass
@staticmethod
def h(color: Color = "RED"):
pass
for method in [Foo().f, Foo.g, Foo.h]:
schema = callables.parameter_schema(method)
expected_schema = {
"title": "Parameters",
"type": "object",
"properties": {
"color": {
"$ref": "#/definitions/Color",
"default": "RED",
"position": 0,
"title": "color",
}
},
"definitions": {
"Color": {
"enum": ["RED", "GREEN", "BLUE"],
"title": "Color",
"type": "string",
}
},
}
assert schema.model_dump_for_openapi() == expected_schema
def test_methods_with_complex_arguments(self):
class Foo:
def f(self, x: datetime.datetime, y: int = 42, z: Optional[bool] = None):
pass
@classmethod
def g(cls, x: datetime.datetime, y: int = 42, z: Optional[bool] = None):
pass
@staticmethod
def h(x: datetime.datetime, y: int = 42, z: Optional[bool] = None):
pass
for method in [Foo().f, Foo.g, Foo.h]:
schema = callables.parameter_schema(method)
expected_schema = {
"title": "Parameters",
"type": "object",
"properties": {
"x": {
"format": "date-time",
"position": 0,
"title": "x",
"type": "string",
},
"y": {
"default": 42,
"position": 1,
"title": "y",
"type": "integer",
},
"z": {
"default": None,
"position": 2,
"title": "z",
"anyOf": [{"type": "boolean"}, {"type": "null"}],
},
},
"required": ["x"],
"definitions": {},
}
assert schema.model_dump_for_openapi() == expected_schema
def test_method_with_kwargs_only(self):
def f(
*,
x: int,
):
pass
schema = callables.parameter_schema(f)
assert schema.model_dump_for_openapi() == {
"properties": {"x": {"title": "x", "position": 0, "type": "integer"}},
"title": "Parameters",
"type": "object",
"definitions": {},
"required": ["x"],
}
| TestMethodToSchema |
python | celery__celery | celery/utils/objects.py | {
"start": 167,
"end": 1423
} | class ____:
"""Object that enables you to modify attributes."""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def mro_lookup(cls, attr, stop=None, monkey_patched=None):
"""Return the first node by MRO order that defines an attribute.
Arguments:
cls (Any): Child class to traverse.
attr (str): Name of attribute to find.
stop (Set[Any]): A set of types that if reached will stop
the search.
monkey_patched (Sequence): Use one of the stop classes
if the attributes module origin isn't in this list.
Used to detect monkey patched attributes.
Returns:
Any: The attribute value, or :const:`None` if not found.
"""
stop = set() if not stop else stop
monkey_patched = [] if not monkey_patched else monkey_patched
for node in cls.mro():
if node in stop:
try:
value = node.__dict__[attr]
module_origin = value.__module__
except (AttributeError, KeyError):
pass
else:
if module_origin not in monkey_patched:
return node
return
if attr in node.__dict__:
return node
| Bunch |
python | simonw__sqlite-utils | sqlite_utils/utils.py | {
"start": 5545,
"end": 5620
} | class ____(enum.Enum):
CSV = 1
TSV = 2
JSON = 3
NL = 4
| Format |
python | pyinstaller__pyinstaller | PyInstaller/archive/writers.py | {
"start": 4250,
"end": 14825
} | class ____:
"""
Writer for PyInstaller's CArchive (PKG) archive.
This archive contains all files that are bundled within an executable; a PYZ (ZlibArchive), DLLs, Python C
extensions, and other data files that are bundled in onefile mode.
The archive can be read from either C (bootloader code at application's run-time) or Python (for debug purposes).
"""
_COOKIE_MAGIC_PATTERN = b'MEI\014\013\012\013\016'
# For cookie and TOC entry structure, see `PyInstaller.archive.readers.CArchiveReader`.
_COOKIE_FORMAT = '!8sIIII64s'
_COOKIE_LENGTH = struct.calcsize(_COOKIE_FORMAT)
_TOC_ENTRY_FORMAT = '!IIIIBc'
_TOC_ENTRY_LENGTH = struct.calcsize(_TOC_ENTRY_FORMAT)
_COMPRESSION_LEVEL = 9 # zlib compression level
def __init__(self, filename, entries, pylib_name):
"""
filename
Target filename of the archive.
entries
An iterable containing entries in the form of tuples: (dest_name, src_name, compress, typecode), where
`dest_name` is the name under which the resource is stored in the archive (and name under which it is
extracted at runtime), `src_name` is name of the file from which the resouce is read, `compress` is a
boolean compression flag, and `typecode` is the Analysis-level TOC typecode.
pylib_name
Name of the python shared library.
"""
self._collected_names = set() # Track collected names for strict package mode.
with open(filename, "wb") as fp:
# Write entries' data and collect TOC entries
toc = []
for entry in entries:
toc_entry = self._write_entry(fp, entry)
toc.append(toc_entry)
# Write TOC
toc_offset = fp.tell()
toc_data = self._serialize_toc(toc)
toc_length = len(toc_data)
fp.write(toc_data)
# Write cookie
archive_length = toc_offset + toc_length + self._COOKIE_LENGTH
pyvers = sys.version_info[0] * 100 + sys.version_info[1]
cookie_data = struct.pack(
self._COOKIE_FORMAT,
self._COOKIE_MAGIC_PATTERN,
archive_length,
toc_offset,
toc_length,
pyvers,
pylib_name.encode('ascii'),
)
fp.write(cookie_data)
def _write_entry(self, fp, entry):
dest_name, src_name, compress, typecode = entry
# Write OPTION entries as-is, without normalizing them. This also exempts them from duplication check,
# allowing them to be specified multiple times.
if typecode == 'o':
return self._write_blob(fp, b"", dest_name, typecode)
# Ensure forward slashes in paths are on Windows converted to back slashes '\\', as on Windows the bootloader
# works only with back slashes.
dest_name = os.path.normpath(dest_name)
if is_win and os.path.sep == '/':
# When building under MSYS, the above path normalization uses Unix-style separators, so replace them
# manually.
dest_name = dest_name.replace(os.path.sep, '\\')
# For symbolic link entries, also ensure that the symlink target path (stored in src_name) is using
# Windows-style back slash separators.
if typecode == 'n':
src_name = src_name.replace(os.path.sep, '\\')
# Strict pack/collect mode: keep track of the destination names, and raise an error if we try to add a duplicate
# (a file with same destination name, subject to OS case normalization rules).
if strict_collect_mode:
normalized_dest = None
if typecode in {'s', 's1', 's2', 'm', 'M'}:
# Exempt python source scripts and modules from the check.
pass
else:
# Everything else; normalize the case
normalized_dest = os.path.normcase(dest_name)
# Check for existing entry, if applicable
if normalized_dest:
if normalized_dest in self._collected_names:
raise ValueError(
f"Attempting to collect a duplicated file into CArchive: {normalized_dest} (type: {typecode})"
)
self._collected_names.add(normalized_dest)
if typecode == 'd':
# Dependency; merge src_name (= reference path prefix) and dest_name (= name) into single-string format that
# is parsed by bootloader.
return self._write_blob(fp, b"", f"{src_name}:{dest_name}", typecode)
elif typecode in {'s', 's1', 's2'}:
# If it is a source code file, compile it to a code object and marshal the object, so it can be unmarshalled
# by the bootloader. For that, we need to know target optimization level, which is stored in typecode.
optim_level = {'s': 0, 's1': 1, 's2': 2}[typecode]
code = get_code_object(dest_name, src_name, optimize=optim_level)
# Construct new `co_filename` by taking destination name, and replace its suffix with the one from the code
# object's co_filename; this should cover all of the following cases:
# - run-time hook script: the source name has a suffix (that is also present in `co_filename` produced by
# `get_code_object`), destination name has no suffix.
# - entry-point script with a suffix: both source name and destination name have the same suffix (and the
# same suffix is also in `co_filename` produced by `get_code_object`)
# - entry-point script without a suffix: neither source name nor destination name have a suffix, but
# `get_code_object` adds a .py suffix to `co_filename` to mitigate potential issues with POSIX
# executables and `traceback` module; we want to preserve this behavior.
co_filename = os.path.splitext(dest_name)[0] + os.path.splitext(code.co_filename)[1]
code = replace_filename_in_code_object(code, co_filename)
return self._write_blob(fp, marshal.dumps(code), dest_name, 's', compress=compress)
elif typecode in ('m', 'M'):
# Read the PYC file. We do not perform compilation here (in contrast to script files in the above branch),
# so typecode does not contain optimization level information.
with open(src_name, "rb") as in_fp:
data = in_fp.read()
assert data[:4] == BYTECODE_MAGIC
# Skip the PYC header, load the code object.
code = marshal.loads(data[16:])
co_filename = dest_name + '.py' # Use dest name with added .py suffix.
code = replace_filename_in_code_object(code, co_filename)
# These module entries are loaded and executed within the bootloader, which requires only the code
# object, without the PYC header.
return self._write_blob(fp, marshal.dumps(code), dest_name, typecode, compress=compress)
elif typecode == 'n':
# Symbolic link; store target name (as NULL-terminated string)
data = src_name.encode('utf-8') + b'\x00'
return self._write_blob(fp, data, dest_name, typecode, compress=compress)
else:
return self._write_file(fp, src_name, dest_name, typecode, compress=compress)
def _write_blob(self, out_fp, blob: bytes, dest_name, typecode, compress=False):
"""
Write the binary contents (**blob**) of a small file to the archive and return the corresponding CArchive TOC
entry.
"""
data_offset = out_fp.tell()
data_length = len(blob)
if compress:
blob = zlib.compress(blob, level=self._COMPRESSION_LEVEL)
out_fp.write(blob)
return (data_offset, len(blob), data_length, int(compress), typecode, dest_name)
def _write_file(self, out_fp, src_name, dest_name, typecode, compress=False):
"""
Stream copy a large file into the archive and return the corresponding CArchive TOC entry.
"""
data_offset = out_fp.tell()
data_length = os.stat(src_name).st_size
with open(src_name, 'rb') as in_fp:
if compress:
tmp_buffer = bytearray(16 * 1024)
compressor = zlib.compressobj(self._COMPRESSION_LEVEL)
while True:
num_read = in_fp.readinto(tmp_buffer)
if not num_read:
break
out_fp.write(compressor.compress(tmp_buffer[:num_read]))
out_fp.write(compressor.flush())
else:
shutil.copyfileobj(in_fp, out_fp)
return (data_offset, out_fp.tell() - data_offset, data_length, int(compress), typecode, dest_name)
@classmethod
def _serialize_toc(cls, toc):
serialized_toc = []
for toc_entry in toc:
data_offset, compressed_length, data_length, compress, typecode, name = toc_entry
# Encode names as UTF-8. This should be safe as standard python modules only contain ASCII-characters (and
# standard shared libraries should have the same), and thus the C-code still can handle this correctly.
name = name.encode('utf-8')
name_length = len(name) + 1 # Add 1 for string-terminating zero byte.
# Ensure TOC entries are aligned on 16-byte boundary, so they can be read by bootloader (C code) on
# platforms with strict data alignment requirements (for example linux on `armhf`/`armv7`, such as 32-bit
# Debian Buster on Raspberry Pi).
entry_length = cls._TOC_ENTRY_LENGTH + name_length
if entry_length % 16 != 0:
padding_length = 16 - (entry_length % 16)
name_length += padding_length
# Serialize
serialized_entry = struct.pack(
cls._TOC_ENTRY_FORMAT + f"{name_length}s", # "Ns" format automatically pads the string with zero bytes.
cls._TOC_ENTRY_LENGTH + name_length,
data_offset,
compressed_length,
data_length,
compress,
typecode.encode('ascii'),
name,
)
serialized_toc.append(serialized_entry)
return b''.join(serialized_toc)
| CArchiveWriter |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 60423,
"end": 61486
} | class ____:
RETRY_ARGS = dict(
wait=tenacity.wait_fixed(0.1),
stop=tenacity.stop_after_attempt(5),
)
def _fail(self):
raise NotImplementedError()
@retry(**RETRY_ARGS)
def _decorated_fail(self):
self._fail()
@pytest.fixture()
def mock_sleep(self, monkeypatch):
class MockSleep:
call_count = 0
def __call__(self, seconds):
self.call_count += 1
sleep = MockSleep()
monkeypatch.setattr(tenacity.nap.time, "sleep", sleep)
yield sleep
def test_decorated(self, mock_sleep):
with pytest.raises(RetryError):
self._decorated_fail()
assert mock_sleep.call_count == 4
def test_decorated_retry_with(self, mock_sleep):
fail_faster = self._decorated_fail.retry_with(
stop=tenacity.stop_after_attempt(2),
)
with pytest.raises(RetryError):
fail_faster()
assert mock_sleep.call_count == 1
if __name__ == "__main__":
unittest.main()
| TestMockingSleep |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydoclint/DOC403_numpy.py | {
"start": 345,
"end": 1290
} | class ____:
# DOC403
def foo(self) -> str:
"""
Do something
Parameters
----------
num : int
A number
Yields
-------
str
A string
"""
print('test')
# OK
def bar(self) -> str:
"""
Do something
Parameters
----------
num : int
A number
"""
print('test')
import typing
# OK
def foo() -> typing.Generator[None, None, None]:
"""
Do something
Yields
------
When X.
"""
yield None
# OK
def foo() -> typing.Generator[None, None, None]:
"""
Do something
Yields
------
When X.
"""
yield
# OK
def foo():
"""
Do something
Yields
------
When X.
"""
yield None
# OK
def foo():
"""
Do something
Yields
------
When X.
"""
yield
| Bar |
python | numpy__numpy | numpy/f2py/tests/test_array_from_pyobj.py | {
"start": 4434,
"end": 6994
} | class ____:
_type_cache = {}
def __new__(cls, name):
if isinstance(name, np.dtype):
dtype0 = name
name = None
for n, i in c_names_dict.items():
if not isinstance(i, type) and dtype0.type is i.type:
name = n
break
obj = cls._type_cache.get(name.upper(), None)
if obj is not None:
return obj
obj = object.__new__(cls)
obj._init(name)
cls._type_cache[name.upper()] = obj
return obj
def _init(self, name):
self.NAME = name.upper()
if self.NAME == 'CHARACTER':
info = c_names_dict[self.NAME]
self.type_num = wrap.NPY_STRING
self.elsize = 1
self.dtype = np.dtype('c')
elif self.NAME.startswith('STRING'):
info = c_names_dict[self.NAME[:6]]
self.type_num = wrap.NPY_STRING
self.elsize = int(self.NAME[6:] or 0)
self.dtype = np.dtype(f'S{self.elsize}')
else:
info = c_names_dict[self.NAME]
self.type_num = getattr(wrap, 'NPY_' + self.NAME)
self.elsize = info.itemsize
self.dtype = np.dtype(info.type)
assert self.type_num == info.num
self.type = info.type
self.dtypechar = info.char
def __repr__(self):
return (f"Type({self.NAME})|type_num={self.type_num},"
f" dtype={self.dtype},"
f" type={self.type}, elsize={self.elsize},"
f" dtypechar={self.dtypechar}")
def cast_types(self):
return [self.__class__(_m) for _m in _cast_dict[self.NAME]]
def all_types(self):
return [self.__class__(_m) for _m in _type_names]
def smaller_types(self):
bits = c_names_dict[self.NAME].alignment
types = []
for name in _type_names:
if c_names_dict[name].alignment < bits:
types.append(Type(name))
return types
def equal_types(self):
bits = c_names_dict[self.NAME].alignment
types = []
for name in _type_names:
if name == self.NAME:
continue
if c_names_dict[name].alignment == bits:
types.append(Type(name))
return types
def larger_types(self):
bits = c_names_dict[self.NAME].alignment
types = []
for name in _type_names:
if c_names_dict[name].alignment > bits:
types.append(Type(name))
return types
| Type |
python | html5lib__html5lib-python | html5lib/html5parser.py | {
"start": 104428,
"end": 105628
} | class ____(Phase):
__slots__ = tuple()
def processEOF(self):
pass
def processComment(self, token):
self.tree.insertComment(token, self.tree.document)
def processSpaceCharacters(self, token):
return self.parser.phases["inBody"].processSpaceCharacters(token)
def processCharacters(self, token):
self.parser.parseError("expected-eof-but-got-char")
self.parser.phase = self.parser.phases["inBody"]
return token
def startTagHtml(self, token):
return self.parser.phases["inBody"].processStartTag(token)
def startTagOther(self, token):
self.parser.parseError("expected-eof-but-got-start-tag",
{"name": token["name"]})
self.parser.phase = self.parser.phases["inBody"]
return token
def processEndTag(self, token):
self.parser.parseError("expected-eof-but-got-end-tag",
{"name": token["name"]})
self.parser.phase = self.parser.phases["inBody"]
return token
startTagHandler = _utils.MethodDispatcher([
("html", startTagHtml)
])
startTagHandler.default = startTagOther
| AfterAfterBodyPhase |
python | django-extensions__django-extensions | django_extensions/management/commands/drop_test_database.py | {
"start": 588,
"end": 9268
} | class ____(BaseCommand):
help = "Drops test database for this project."
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--noinput",
"--no-input",
action="store_false",
dest="interactive",
default=True,
help="Tells Django to NOT prompt the user for input of any kind.",
)
parser.add_argument(
"-U",
"--user",
action="store",
dest="user",
default=None,
help="Use another user for the database then defined in settings.py",
)
parser.add_argument(
"-P",
"--password",
action="store",
dest="password",
default=None,
help="Use another password for the database then defined in settings.py",
)
parser.add_argument(
"-D",
"--dbname",
action="store",
dest="dbname",
default=None,
help="Use another database name then defined in settings.py",
)
parser.add_argument(
"-R",
"--router",
action="store",
dest="router",
default=DEFAULT_DB_ALIAS,
help="Use this router-database other then defined in settings.py",
)
parser.add_argument(
"--database",
default=DEFAULT_DB_ALIAS,
help=(
"Nominates a database to run command for. "
'Defaults to the "%s" database.'
)
% DEFAULT_DB_ALIAS,
)
@signalcommand
def handle(self, *args, **options):
"""Drop test database for this project."""
database = options["database"]
if options["router"] != DEFAULT_DB_ALIAS:
warnings.warn(
"--router is deprecated. You should use --database.",
RemovedInNextVersionWarning,
stacklevel=2,
)
database = options["router"]
dbinfo = settings.DATABASES.get(database)
if dbinfo is None:
raise CommandError("Unknown database %s" % database)
engine = dbinfo.get("ENGINE")
user = password = database_name = database_host = database_port = ""
if engine == "mysql":
(user, password, database_name, database_host, database_port) = (
parse_mysql_cnf(dbinfo)
)
user = options["user"] or dbinfo.get("USER") or user
password = options["password"] or dbinfo.get("PASSWORD") or password
try:
database_name = dbinfo["TEST"]["NAME"]
except KeyError:
database_name = None
if database_name is None:
database_name = TEST_DATABASE_PREFIX + (
options["dbname"] or dbinfo.get("NAME")
)
if database_name is None or database_name == "":
raise CommandError(
"You need to specify DATABASE_NAME in your Django settings file."
)
database_host = dbinfo.get("HOST") or database_host
database_port = dbinfo.get("PORT") or database_port
verbosity = options["verbosity"]
if options["interactive"]:
confirm = input(
"""
You have requested to drop all test databases.
This will IRREVERSIBLY DESTROY
ALL data in the database "{db_name}"
and all cloned test databases generated via
the "--parallel" flag (these are sequentially
named "{db_name}_1", "{db_name}_2", etc.).
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: """.format(db_name=database_name)
)
else:
confirm = "yes"
if confirm != "yes":
print("Reset cancelled.")
return
def get_database_names(formatter):
"""
Return a generator of all possible test database names.
e.g., 'test_foo', 'test_foo_1', test_foo_2', etc.
formatter: func returning a clone db name given the primary db name
and the clone's number, e.g., 'test_foo_1' for mysql/postgres, and
'test_foo_1..sqlite3' for sqlite (re: double dots, see comments).
"""
yield database_name
yield from (formatter(database_name, n) for n in count(1))
if engine in SQLITE_ENGINES:
# By default all sqlite test databases are created in memory.
# There will only be database files to delete if the developer has
# specified a test database name, which forces files to be written
# to disk.
logging.info("Unlinking %s databases" % engine)
def format_filename(name, number):
filename, ext = os.path.splitext(name)
# Since splitext() includes the dot in 'ext', the inclusion of
# the dot in the format string below is incorrect and creates a
# double dot. Django makes this mistake, so it must be
# replicated here. If fixed in Django, this code should be
# updated accordingly.
# Reference: https://code.djangoproject.com/ticket/32582
return "{}_{}.{}".format(filename, number, ext)
try:
for db_name in get_database_names(format_filename):
if not os.path.isfile(db_name):
break
logging.info('Unlinking database named "%s"' % db_name)
os.unlink(db_name)
except OSError:
return
elif engine in MYSQL_ENGINES:
import MySQLdb as Database
kwargs = {
"user": user,
"passwd": password,
}
if database_host.startswith("/"):
kwargs["unix_socket"] = database_host
else:
kwargs["host"] = database_host
if database_port:
kwargs["port"] = int(database_port)
connection = Database.connect(**kwargs)
cursor = connection.cursor()
for db_name in get_database_names("{}_{}".format):
exists_query = (
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA "
"WHERE SCHEMA_NAME='%s';" % db_name
)
row_count = cursor.execute(exists_query)
if row_count < 1:
break
drop_query = "DROP DATABASE IF EXISTS `%s`" % db_name
logging.info('Executing: "' + drop_query + '"')
cursor.execute(drop_query)
elif engine in POSTGRESQL_ENGINES:
has_psycopg3 = importlib.util.find_spec("psycopg")
if has_psycopg3:
import psycopg as Database # NOQA
else:
import psycopg2 as Database # NOQA
conn_params = {"dbname": "template1"}
if user:
conn_params["user"] = user
if password:
conn_params["password"] = password
if database_host:
conn_params["host"] = database_host
if database_port:
conn_params["port"] = database_port
connection = Database.connect(**conn_params)
if has_psycopg3:
connection.autocommit = True
else:
connection.set_isolation_level(0) # autocommit false
cursor = connection.cursor()
for db_name in get_database_names("{}_{}".format):
exists_query = (
"SELECT datname FROM pg_catalog.pg_database WHERE datname='%s';"
% db_name
)
try:
cursor.execute(exists_query)
# NOTE: Unlike MySQLdb, the psycopg2 cursor does not return the row
# count however both cursors provide it as a property
if cursor.rowcount < 1:
break
drop_query = 'DROP DATABASE IF EXISTS "%s";' % db_name
logging.info('Executing: "' + drop_query + '"')
cursor.execute(drop_query)
except Database.ProgrammingError as e:
logging.exception("Error: %s" % str(e))
return
else:
raise CommandError("Unknown database engine %s" % engine)
if verbosity >= 2 or options["interactive"]:
print("Reset successful.")
| Command |
python | tensorflow__tensorflow | tensorflow/python/ops/autograph_ops_test.py | {
"start": 874,
"end": 1423
} | class ____(test.TestCase):
def test_wrap_py_func_dummy_return(self):
side_counter = [0]
def test_fn(_):
side_counter[0] += 1
with self.cached_session():
result = autograph_ops.wrap_py_func(test_fn, (5,))
self.assertEqual(1, self.evaluate(result))
self.assertEqual([1], side_counter)
result = autograph_ops.wrap_py_func(test_fn, (constant_op.constant(5),))
self.assertEqual(1, self.evaluate(result))
self.assertEqual([2], side_counter)
if __name__ == '__main__':
test.main()
| AutographOpsTest |
python | ansible__ansible | test/lib/ansible_test/_util/controller/sanity/validate-modules/validate_modules/module_args.py | {
"start": 1515,
"end": 6301
} | class ____:
def __init__(self):
self.args = tuple()
self.kwargs = {}
self.called = False
def __call__(self, *args, **kwargs):
if args and isinstance(args[0], AnsibleModule):
# Make sure, due to creative calling, that we didn't end up with
# ``self`` in ``args``
self.args = args[1:]
else:
self.args = args
self.kwargs = kwargs
self.called = True
raise AnsibleModuleCallError('AnsibleModuleCallError')
def _fake_load_params():
pass
@contextmanager
def setup_env(filename):
# Used to clean up imports later
pre_sys_modules = list(sys.modules.keys())
fake = _FakeAnsibleModuleInit()
module = __import__('ansible.module_utils.basic').module_utils.basic
_original_init = module.AnsibleModule.__init__
_original_load_params = module._load_params
setattr(module.AnsibleModule, '__init__', fake)
setattr(module, '_load_params', _fake_load_params)
try:
yield fake
finally:
setattr(module.AnsibleModule, '__init__', _original_init)
setattr(module, '_load_params', _original_load_params)
# Clean up imports to prevent issues with mutable data being used in modules
for k in list(sys.modules.keys()):
# It's faster if we limit to items in ansible.module_utils
# But if this causes problems later, we should remove it
if k not in pre_sys_modules and k.startswith('ansible.module_utils.'):
del sys.modules[k]
def get_ps_argument_spec(filename, collection):
fqc_name = get_module_name_from_filename(filename, collection)
pwsh = find_executable('pwsh')
if not pwsh:
raise FileNotFoundError('Required program for PowerShell arg spec inspection "pwsh" not found.')
module_path = os.path.join(os.getcwd(), filename)
b_module_path = to_bytes(module_path, errors='surrogate_or_strict')
with open(b_module_path, mode='rb') as module_fd:
b_module_data = module_fd.read()
ps_dep_finder = PSModuleDepFinder()
module_deps = ps_dep_finder.scan_module(b_module_data, fqn=fqc_name)
ansible_basic = ''
ps_utils = {}
for dep in module_deps:
dep_info = ps_dep_finder.scripts[dep]
if dep == 'Ansible.Basic.cs':
ansible_basic = dep_info.path
elif dep.endswith('.psm1'):
ps_utils[dep] = dep_info.path
util_manifest = json.dumps({
'module_path': to_text(module_path, errors='surrogate_or_strict'),
'ansible_basic': ansible_basic,
'ps_utils': ps_utils,
})
script_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ps_argspec.ps1')
proc = subprocess.run(['pwsh', script_path, util_manifest], stdin=subprocess.DEVNULL, capture_output=True, text=True, check=False)
if proc.returncode != 0:
raise AnsibleModuleImportError("STDOUT:\n%s\nSTDERR:\n%s" % (proc.stdout, proc.stderr))
kwargs = json.loads(proc.stdout)
# the validate-modules code expects the options spec to be under the argument_spec key not options as set in PS
kwargs['argument_spec'] = kwargs.pop('options', {})
return kwargs['argument_spec'], kwargs
def get_py_argument_spec(filename, collection):
name = get_module_name_from_filename(filename, collection)
with setup_env(filename) as fake:
try:
with CaptureStd():
runpy.run_module(name, run_name='__main__', alter_sys=True)
except AnsibleModuleCallError:
pass
except BaseException as e:
# we want to catch all exceptions here, including sys.exit
raise AnsibleModuleImportError from e
if not fake.called:
raise AnsibleModuleNotInitialized()
try:
# Convert positional arguments to kwargs to make sure that all parameters are actually checked
for arg, arg_name in zip(fake.args, ANSIBLE_MODULE_CONSTRUCTOR_ARGS):
fake.kwargs[arg_name] = arg
# for ping kwargs == {'argument_spec':{'data':{'type':'str','default':'pong'}}, 'supports_check_mode':True}
argument_spec = fake.kwargs.get('argument_spec') or {}
# If add_file_common_args is truish, add options from FILE_COMMON_ARGUMENTS when not present.
# This is the only modification to argument_spec done by AnsibleModule itself, and which is
# not caught by setup_env's AnsibleModule replacement
if fake.kwargs.get('add_file_common_args'):
for k, v in FILE_COMMON_ARGUMENTS.items():
if k not in argument_spec:
argument_spec[k] = v
return argument_spec, fake.kwargs
except (TypeError, IndexError):
return {}, {}
| _FakeAnsibleModuleInit |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-gaudi/llama_index/embeddings/gaudi/base.py | {
"start": 1762,
"end": 4704
} | class ____(BaseEmbedding):
max_length: int = Field(
default=DEFAULT_HUGGINGFACE_LENGTH, description="Maximum length of input.", gt=0
)
normalize: bool = Field(default=True, description="Normalize embeddings or not.")
query_instruction: Optional[str] = Field(
description="Instruction to prepend to query text."
)
text_instruction: Optional[str] = Field(
description="Instruction to prepend to text."
)
_model: Any = PrivateAttr()
def __init__(
self,
model_name: str = DEFAULT_HUGGINGFACE_EMBEDDING_MODEL,
max_length: Optional[int] = DEFAULT_HUGGINGFACE_LENGTH,
normalize: bool = True,
query_instruction: Optional[str] = None,
text_instruction: Optional[str] = None,
tokenizer: Optional[Any] = None,
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
callback_manager: Optional[CallbackManager] = None,
**model_kwargs,
) -> None:
model = GaudiSentenceTransformer(
model_name,
cache_folder=get_cache_dir(),
# prompts={
# "query": query_instruction
# or get_query_instruct_for_model_name(model_name),
# "text": text_instruction
# or get_text_instruct_for_model_name(model_name),
# },
**model_kwargs,
)
super().__init__(
embed_batch_size=embed_batch_size,
callback_manager=callback_manager,
max_length=max_length,
normalize=normalize,
query_instruction=query_instruction,
text_instruction=text_instruction,
)
self._model = model
@classmethod
def class_name(cls) -> str:
return "GaudiEmbedding"
def _embed(
self,
sentences: List[str],
prompt_name: Optional[str] = None,
) -> List[List[float]]:
"""Embed sentences."""
return self._model.encode(
sentences,
batch_size=self.embed_batch_size,
prompt_name=prompt_name,
normalize_embeddings=self.normalize,
).tolist()
def _get_query_embedding(self, query: str) -> List[float]:
"""Get query embedding."""
return self._embed(query, prompt_name=None)
async def _aget_query_embedding(self, query: str) -> List[float]:
"""Get query embedding async."""
return self._get_query_embedding(query)
async def _aget_text_embedding(self, text: str) -> List[float]:
"""Get text embedding async."""
return self._get_text_embedding(text)
def _get_text_embedding(self, text: str) -> List[float]:
"""Get text embedding."""
return self._embed(text, prompt_name=None)
def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Get text embeddings."""
return self._embed(texts, prompt_name=None)
| GaudiEmbedding |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/spark_datasource.py | {
"start": 2206,
"end": 6142
} | class ____(Datasource):
# instance attributes
spark_config: Union[SparkConfig, None] = None
force_reuse_spark_context: bool = True
persist: bool = True
# private attrs
_spark: Union[SparkSession, None] = pydantic.PrivateAttr(None)
@pydantic.validator("force_reuse_spark_context")
@classmethod
def _force_reuse_spark_context_deprecation_warning(cls, v: bool) -> bool:
if v is not None:
# deprecated-v1.0.0
warnings.warn(
"force_reuse_spark_context is deprecated and will be removed in version 1.0. "
"In environments that allow it, the existing Spark context will be reused, adding the " # noqa: E501 # FIXME CoP
"spark_config options that have been passed. If the Spark context cannot be updated with " # noqa: E501 # FIXME CoP
"the spark_config, the context will be stopped and restarted with the new spark_config.", # noqa: E501 # FIXME CoP
category=DeprecationWarning,
)
return v
@classmethod
@override
def update_forward_refs(cls) -> None: # type: ignore[override] # FIXME CoP
from great_expectations.compatibility.pyspark import SparkSession
super().update_forward_refs(SparkSession=SparkSession)
@staticmethod
@override
def _update_asset_forward_refs(asset_type: Type[_DataAssetT]) -> None:
# Only update forward refs if pyspark types are available
if pyspark:
asset_type.update_forward_refs()
# Abstract Methods
@property
@override
def execution_engine_type(self) -> Type[SparkDFExecutionEngine]:
"""Return the SparkDFExecutionEngine unless the override is set"""
from great_expectations.execution_engine.sparkdf_execution_engine import (
SparkDFExecutionEngine,
)
return SparkDFExecutionEngine
def get_spark(self) -> SparkSession:
# circular imports require us to import SparkSession and update_forward_refs
# only when assigning to self._spark for SparkSession isinstance check
self.update_forward_refs()
self._spark: SparkSession = self.execution_engine_type.get_or_create_spark_session(
spark_config=self.spark_config,
)
return self._spark
@override
def get_execution_engine(self) -> SparkDFExecutionEngine:
# Method override is required because PrivateAttr _spark won't be passed into Execution Engine # noqa: E501 # FIXME CoP
# unless it is passed explicitly.
current_execution_engine_kwargs = self.dict(
exclude=self._get_exec_engine_excludes(),
config_provider=self._config_provider,
)
if (
current_execution_engine_kwargs != self._cached_execution_engine_kwargs
or not self._execution_engine
):
if self._spark:
self._execution_engine = self._execution_engine_type()(
spark=self._spark, **current_execution_engine_kwargs
)
else:
self._execution_engine = self._execution_engine_type()(
**current_execution_engine_kwargs
)
self._cached_execution_engine_kwargs = current_execution_engine_kwargs
return self._execution_engine
@override
def test_connection(self, test_assets: bool = True) -> None:
"""Test the connection for the _SparkDatasource.
Args:
test_assets: If assets have been passed to the _SparkDatasource,
an attempt can be made to test them as well.
Raises:
TestConnectionError: If the connection test fails.
"""
try:
self.get_spark()
except Exception as e:
raise TestConnectionError(cause=e) from e
# End Abstract Methods
@public_api
| _SparkDatasource |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_config_types.py | {
"start": 3734,
"end": 27388
} | class ____(NonLaunchableGraphQLContextTestMatrix):
def test_pipeline_not_found(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="nope",
run_config={},
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "PipelineNotFoundError"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "nope"
def test_basic_valid_config(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="csv_hello_world",
run_config=csv_hello_world_ops_config(),
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "PipelineConfigValidationValid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
def test_basic_valid_config_serialized_config(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="csv_hello_world",
run_config=json.dumps(csv_hello_world_ops_config()),
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "PipelineConfigValidationValid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
def test_basic_valid_config_empty_string_config(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="csv_hello_world",
run_config="",
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid", (
result.data
)
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
def test_basic_valid_config_non_dict_config(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="csv_hello_world",
run_config="daggy",
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
def test_root_field_not_defined(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="csv_hello_world",
run_config={
"ops": {
"sum_op": {"inputs": {"num": file_relative_path(__file__, "../data/num.csv")}}
},
"nope": {},
},
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
errors = result.data["isPipelineConfigValid"]["errors"]
assert len(errors) == 1
error = errors[0]
assert error["__typename"] == "FieldNotDefinedConfigError"
assert error["fieldName"] == "nope"
assert not error["stack"]["entries"]
def test_basic_invalid_not_defined_field(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="csv_hello_world",
run_config={"ops": {"sum_op": {"inputs": {"num": "foo.txt", "extra": "nope"}}}},
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
assert len(result.data["isPipelineConfigValid"]["errors"]) == 1
error_data = result.data["isPipelineConfigValid"]["errors"][0]
assert ["ops", "sum_op", "inputs"] == field_stack(error_data)
assert error_data["reason"] == "FIELD_NOT_DEFINED"
assert error_data["fieldName"] == "extra"
def test_multiple_not_defined_fields(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="csv_hello_world",
run_config={
"ops": {
"sum_op": {
"inputs": {"num": "foo.txt", "extra_one": "nope", "extra_two": "nope"}
}
}
},
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
assert len(result.data["isPipelineConfigValid"]["errors"]) == 1
error_data = result.data["isPipelineConfigValid"]["errors"][0]
assert ["ops", "sum_op", "inputs"] == field_stack(error_data)
assert error_data["reason"] == "FIELDS_NOT_DEFINED"
assert error_data["fieldNames"] == ["extra_one", "extra_two"]
def test_root_wrong_type(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(graphql_context, job_name="csv_hello_world", run_config=123)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
assert len(result.data["isPipelineConfigValid"]["errors"]) == 1
error_data = result.data["isPipelineConfigValid"]["errors"][0]
assert error_data["reason"] == "RUNTIME_TYPE_MISMATCH"
def test_basic_invalid_config_type_mismatch(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="csv_hello_world",
run_config={"ops": {"sum_op": {"inputs": {"num": 123}}}},
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
assert len(result.data["isPipelineConfigValid"]["errors"]) == 1
error_data = result.data["isPipelineConfigValid"]["errors"][0]
assert error_data["message"]
assert error_data["stack"]
assert error_data["stack"]["entries"]
assert error_data["reason"] == "RUNTIME_TYPE_MISMATCH"
assert error_data["valueRep"] == "123"
assert ["ops", "sum_op", "inputs", "num"] == field_stack(error_data)
def test_basic_invalid_config_missing_field(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="csv_hello_world",
run_config={"ops": {"sum_op": {"inputs": {}}}},
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "csv_hello_world"
assert len(result.data["isPipelineConfigValid"]["errors"]) == 1
error_data = result.data["isPipelineConfigValid"]["errors"][0]
assert ["ops", "sum_op", "inputs"] == field_stack(error_data)
assert error_data["reason"] == "MISSING_REQUIRED_FIELD"
assert error_data["field"]["name"] == "num"
def test_resource_config_works(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="required_resource_job",
run_config={"resources": {"R1": {"config": 2}}},
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "PipelineConfigValidationValid"
assert result.data["isPipelineConfigValid"]["pipelineName"] == "required_resource_job"
def test_missing_resource(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="required_resource_config_job",
run_config={"resources": {}},
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid"
error_data = single_error_data(result)
assert error_data["reason"] == "MISSING_REQUIRED_FIELD"
assert error_data["field"]["name"] == "R1"
def test_undefined_resource(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="required_resource_job",
run_config={"resources": {"nope": {}}},
)
assert not result.errors
assert result.data
assert result.data["isPipelineConfigValid"]["__typename"] == "RunConfigValidationInvalid"
assert {"FieldNotDefinedConfigError"} == {
error_data["__typename"]
for error_data in result.data["isPipelineConfigValid"]["errors"]
}
def test_more_complicated_works(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="more_complicated_nested_config",
run_config={
"ops": {
"op_with_multilayered_config": {
"config": {
"field_any": {"123": 123},
"field_one": "foo.txt",
"field_two": "yup",
"field_three": "mmmhmmm",
"nested_field": {"field_four_str": "yaya", "field_five_int": 234},
}
}
}
},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "PipelineConfigValidationValid"
assert valid_data["pipelineName"] == "more_complicated_nested_config"
def test_multiple_missing_fields(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="more_complicated_nested_config",
run_config={"ops": {"op_with_multilayered_config": {"config": {}}}},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "RunConfigValidationInvalid"
assert valid_data["pipelineName"] == "more_complicated_nested_config"
assert len(valid_data["errors"]) == 1
error_data = valid_data["errors"][0]
missing_names = {field_data["name"] for field_data in error_data["fields"]}
assert missing_names == {"nested_field", "field_one", "field_any"}
assert field_stack(error_data) == ["ops", "op_with_multilayered_config", "config"]
def test_more_complicated_multiple_errors(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="more_complicated_nested_config",
run_config={
"ops": {
"op_with_multilayered_config": {
"config": {
"field_any": [],
# 'field_one': 'foo.txt', # missing
"field_two": "yup",
"field_three": "mmmhmmm",
"extra_one": "kjsdkfjd", # extra
"nested_field": {
"field_four_str": 23434, # runtime type
"field_five_int": 234,
"extra_two": "ksjdkfjd", # another extra
},
}
}
}
},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "RunConfigValidationInvalid"
assert valid_data["pipelineName"] == "more_complicated_nested_config"
assert len(valid_data["errors"]) == 4
missing_error_one = find_error(
result,
["ops", "op_with_multilayered_config", "config"],
"MISSING_REQUIRED_FIELD",
)
assert ["ops", "op_with_multilayered_config", "config"] == field_stack(missing_error_one)
assert missing_error_one["reason"] == "MISSING_REQUIRED_FIELD"
assert missing_error_one["field"]["name"] == "field_one"
not_defined_one = find_error(
result, ["ops", "op_with_multilayered_config", "config"], "FIELD_NOT_DEFINED"
)
assert ["ops", "op_with_multilayered_config", "config"] == field_stack(not_defined_one)
assert not_defined_one["reason"] == "FIELD_NOT_DEFINED"
assert not_defined_one["fieldName"] == "extra_one"
dagster_type_error = find_error(
result,
[
"ops",
"op_with_multilayered_config",
"config",
"nested_field",
"field_four_str",
],
"RUNTIME_TYPE_MISMATCH",
)
assert [
"ops",
"op_with_multilayered_config",
"config",
"nested_field",
"field_four_str",
] == field_stack(dagster_type_error)
assert dagster_type_error["reason"] == "RUNTIME_TYPE_MISMATCH"
assert dagster_type_error["valueRep"] == "23434"
not_defined_two = find_error(
result,
["ops", "op_with_multilayered_config", "config", "nested_field"],
"FIELD_NOT_DEFINED",
)
assert [
"ops",
"op_with_multilayered_config",
"config",
"nested_field",
] == field_stack(not_defined_two)
assert not_defined_two["reason"] == "FIELD_NOT_DEFINED"
assert not_defined_two["fieldName"] == "extra_two"
# TODO: two more errors
def test_config_list(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="job_with_list",
run_config={"ops": {"op_with_list": {"config": [1, 2]}}},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "PipelineConfigValidationValid"
assert valid_data["pipelineName"] == "job_with_list"
def test_config_list_invalid(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="job_with_list",
run_config={"ops": {"op_with_list": {"config": "foo"}}},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "RunConfigValidationInvalid"
assert valid_data["pipelineName"] == "job_with_list"
assert len(valid_data["errors"]) == 1
assert ["ops", "op_with_list", "config"] == field_stack(valid_data["errors"][0])
def test_config_list_item_invalid(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="job_with_list",
run_config={"ops": {"op_with_list": {"config": [1, "foo"]}}},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "RunConfigValidationInvalid"
assert valid_data["pipelineName"] == "job_with_list"
assert len(valid_data["errors"]) == 1
entries = valid_data["errors"][0]["stack"]["entries"]
assert len(entries) == 4
assert ["ops", "op_with_list", "config"] == field_stack(valid_data["errors"][0])
last_entry = entries[3]
assert last_entry["__typename"] == "EvaluationStackListItemEntry"
assert last_entry["listIndex"] == 1
def test_config_map(self, graphql_context: WorkspaceRequestContext):
# Check validity
result = execute_config_graphql(
graphql_context,
job_name="config_with_map",
run_config={"ops": {"op_with_map_config": {"config": {"field_one": {"test": 5}}}}},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "PipelineConfigValidationValid"
assert valid_data["pipelineName"] == "config_with_map"
# Sanity check GraphQL result for types
selector = infer_job_selector(graphql_context, "config_with_map")
result = execute_dagster_graphql(
graphql_context,
ALL_CONFIG_TYPES_QUERY,
{"selector": selector, "mode": "default"},
)
config_types_data = result.data["runConfigSchemaOrError"]["allConfigTypes"]
# Ensure the first config type, Map(str, int, name="username") is in the result
assert any(
config_type_data.get("keyLabelName") == "username"
and config_type_data.get("keyType", {}).get("key", "") == "String"
and config_type_data.get("valueType", {}).get("key", "") == "Int"
for config_type_data in config_types_data
)
def test_config_map_invalid(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="config_with_map",
run_config={"ops": {"op_with_map_config": {"config": {"field_one": "not_a_map"}}}},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "RunConfigValidationInvalid"
assert valid_data["pipelineName"] == "config_with_map"
assert len(valid_data["errors"]) == 1
assert ["ops", "op_with_map_config", "config", "field_one"] == field_stack(
valid_data["errors"][0]
)
def test_config_map_key_invalid(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="config_with_map",
run_config={"ops": {"op_with_map_config": {"config": {"field_one": {5: 5}}}}},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "RunConfigValidationInvalid"
assert valid_data["pipelineName"] == "config_with_map"
assert len(valid_data["errors"]) == 1
entries = valid_data["errors"][0]["stack"]["entries"]
assert len(entries) == 5
assert ["ops", "op_with_map_config", "config", "field_one"] == field_stack(
valid_data["errors"][0]
)
last_entry = entries[4]
assert last_entry["__typename"] == "EvaluationStackMapKeyEntry"
assert last_entry["mapKey"] == 5
def test_config_map_value_invalid(self, graphql_context: WorkspaceRequestContext):
result = execute_config_graphql(
graphql_context,
job_name="config_with_map",
run_config={
"ops": {
"op_with_map_config": {
"config": {"field_one": {"test": "not_a_valid_int_value"}}
}
}
},
)
assert not result.errors
assert result.data
valid_data = result.data["isPipelineConfigValid"]
assert valid_data["__typename"] == "RunConfigValidationInvalid"
assert valid_data["pipelineName"] == "config_with_map"
assert len(valid_data["errors"]) == 1
entries = valid_data["errors"][0]["stack"]["entries"]
assert len(entries) == 5
assert ["ops", "op_with_map_config", "config", "field_one"] == field_stack(
valid_data["errors"][0]
)
last_entry = entries[4]
assert last_entry["__typename"] == "EvaluationStackMapValueEntry"
assert last_entry["mapKey"] == "test"
def test_smoke_test_config_type_system(self, graphql_context: WorkspaceRequestContext):
selector = infer_job_selector(graphql_context, "more_complicated_nested_config")
result = execute_dagster_graphql(
graphql_context,
ALL_CONFIG_TYPES_QUERY,
{"selector": selector, "mode": "default"},
)
config_types_data = result.data["runConfigSchemaOrError"]["allConfigTypes"]
assert has_config_type_with_key_prefix(config_types_data, "Shape.")
for builtin_config_type in ALL_CONFIG_BUILTINS:
assert has_config_type(config_types_data, builtin_config_type.given_name)
def pipeline_named(result, name):
for pipeline_data in result.data["pipelines"]["nodes"]:
if pipeline_data["name"] == name:
return pipeline_data
check.failed("Did not find")
def has_config_type_with_key_prefix(config_types_data, prefix):
for config_type_data in config_types_data:
if config_type_data["key"].startswith(prefix):
return True
return False
def has_config_type(config_types_data, name):
for config_type_data in config_types_data:
if config_type_data.get("givenName") == name:
return True
return False
ALL_CONFIG_TYPES_QUERY = """
fragment configTypeFragment on ConfigType {
__typename
key
description
isSelector
typeParamKeys
recursiveConfigTypes {
key
description
... on CompositeConfigType {
fields {
name
isRequired
description
}
}
... on WrappingConfigType {
ofType { key }
}
}
... on EnumConfigType {
givenName
values {
value
description
}
}
... on RegularConfigType {
givenName
}
... on CompositeConfigType {
fields {
name
isRequired
description
}
}
... on WrappingConfigType {
ofType { key }
}
... on MapConfigType {
keyType { key }
valueType { key }
keyLabelName
}
... on ScalarUnionConfigType {
scalarType { key }
nonScalarType { key }
}
}
query allConfigTypes($selector: PipelineSelector!, $mode: String!) {
runConfigSchemaOrError(selector: $selector, mode: $mode ) {
... on RunConfigSchema {
allConfigTypes {
...configTypeFragment
}
}
}
}
"""
def get_field_data(config_type_data, name):
for field_data in config_type_data["fields"]:
if field_data["name"] == name:
return field_data
def get_field_names(config_type_data):
return {field_data["name"] for field_data in config_type_data.get("fields", [])}
| TestConfigTypes |
python | tensorflow__tensorflow | tensorflow/python/debug/wrappers/framework.py | {
"start": 5342,
"end": 5719
} | class ____:
"""Request to an on-session-init callback.
This callback is invoked during the __init__ call to a debug-wrapper session.
"""
def __init__(self, sess):
"""Constructor.
Args:
sess: A tensorflow Session object.
"""
_check_type(sess, (session.BaseSession, monitored_session.MonitoredSession))
self.session = sess
| OnSessionInitRequest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/dynamic.py | {
"start": 3450,
"end": 3528
} | class ____(_WriteOnlyLoader):
impl_class = _DynamicAttributeImpl
| _DynaLoader |
python | sqlalchemy__sqlalchemy | test/engine/test_execute.py | {
"start": 50095,
"end": 57544
} | class ____(fixtures.TestBase):
def test_engine_level_options(self):
eng = engines.testing_engine(
options={"execution_options": {"foo": "bar"}}
)
with eng.connect() as conn:
eq_(conn._execution_options["foo"], "bar")
eq_(
conn.execution_options(bat="hoho")._execution_options["foo"],
"bar",
)
eq_(
conn.execution_options(bat="hoho")._execution_options["bat"],
"hoho",
)
eq_(
conn.execution_options(foo="hoho")._execution_options["foo"],
"hoho",
)
eng.update_execution_options(foo="hoho")
conn = eng.connect()
eq_(conn._execution_options["foo"], "hoho")
def test_generative_engine_execution_options(self):
eng = engines.testing_engine(
options={"execution_options": {"base": "x1"}}
)
is_(eng.engine, eng)
eng1 = eng.execution_options(foo="b1")
is_(eng1.engine, eng1)
eng2 = eng.execution_options(foo="b2")
eng1a = eng1.execution_options(bar="a1")
eng2a = eng2.execution_options(foo="b3", bar="a2")
is_(eng2a.engine, eng2a)
eq_(eng._execution_options, {"base": "x1"})
eq_(eng1._execution_options, {"base": "x1", "foo": "b1"})
eq_(eng2._execution_options, {"base": "x1", "foo": "b2"})
eq_(eng1a._execution_options, {"base": "x1", "foo": "b1", "bar": "a1"})
eq_(eng2a._execution_options, {"base": "x1", "foo": "b3", "bar": "a2"})
is_(eng1a.pool, eng.pool)
# test pool is shared
eng2.dispose()
is_(eng1a.pool, eng2.pool)
is_(eng.pool, eng2.pool)
def test_autocommit_option_preserved_first_connect(self, testing_engine):
eng = testing_engine()
eng.update_execution_options(autocommit=True)
conn = eng.connect()
eq_(conn._execution_options, {"autocommit": True})
conn.close()
def test_initialize_rollback(self, testing_engine):
"""test a rollback happens during first connect"""
eng = testing_engine()
with patch.object(eng.dialect, "do_rollback") as do_rollback:
assert do_rollback.call_count == 0
connection = eng.connect()
assert do_rollback.call_count == 1
connection.close()
def test_dialect_init_uses_options(self, testing_engine):
eng = testing_engine()
def my_init(connection):
connection.execution_options(foo="bar").execute(select(1))
with patch.object(eng.dialect, "initialize", my_init):
conn = eng.connect()
eq_(conn._execution_options, {})
conn.close()
@testing.combinations(
({}, {}, {}),
({"a": "b"}, {}, {"a": "b"}),
({"a": "b", "d": "e"}, {"a": "c"}, {"a": "c", "d": "e"}),
argnames="conn_opts, exec_opts, expected",
)
def test_execution_opts_per_invoke(
self, connection, conn_opts, exec_opts, expected
):
opts = []
@event.listens_for(connection, "before_cursor_execute")
def before_cursor_execute(
conn, cursor, statement, parameters, context, executemany
):
opts.append(context.execution_options)
if conn_opts:
connection = connection.execution_options(**conn_opts)
if exec_opts:
connection.execute(select(1), execution_options=exec_opts)
else:
connection.execute(select(1))
eq_(opts, [expected])
@testing.combinations(
({}, {}, {}, {}),
({}, {"a": "b"}, {}, {"a": "b"}),
({}, {"a": "b", "d": "e"}, {"a": "c"}, {"a": "c", "d": "e"}),
(
{"q": "z", "p": "r"},
{"a": "b", "p": "x", "d": "e"},
{"a": "c"},
{"q": "z", "p": "x", "a": "c", "d": "e"},
),
argnames="stmt_opts, conn_opts, exec_opts, expected",
)
def test_execution_opts_per_invoke_execute_events(
self, connection, stmt_opts, conn_opts, exec_opts, expected
):
opts = []
@event.listens_for(connection, "before_execute")
def before_execute(
conn, clauseelement, multiparams, params, execution_options
):
opts.append(("before", execution_options))
@event.listens_for(connection, "after_execute")
def after_execute(
conn,
clauseelement,
multiparams,
params,
execution_options,
result,
):
opts.append(("after", execution_options))
stmt = select(1)
if stmt_opts:
stmt = stmt.execution_options(**stmt_opts)
if conn_opts:
connection = connection.execution_options(**conn_opts)
if exec_opts:
connection.execute(stmt, execution_options=exec_opts)
else:
connection.execute(stmt)
eq_(opts, [("before", expected), ("after", expected)])
def test_dialect_conn_options(self, testing_engine):
engine = testing_engine("sqlite://", options=dict(_initialize=False))
engine.dialect = Mock()
with engine.connect() as conn:
c2 = conn.execution_options(foo="bar")
eq_(
engine.dialect.set_connection_execution_options.mock_calls,
[call(c2, {"foo": "bar"})],
)
def test_dialect_engine_options(self, testing_engine):
engine = testing_engine("sqlite://")
engine.dialect = Mock()
e2 = engine.execution_options(foo="bar")
eq_(
engine.dialect.set_engine_execution_options.mock_calls,
[call(e2, {"foo": "bar"})],
)
def test_dialect_engine_construction_options(self):
dialect = Mock()
engine = Engine(
Mock(), dialect, Mock(), execution_options={"foo": "bar"}
)
eq_(
dialect.set_engine_execution_options.mock_calls,
[call(engine, {"foo": "bar"})],
)
def test_propagate_engine_to_connection(self, testing_engine):
engine = testing_engine(
"sqlite://", options=dict(execution_options={"foo": "bar"})
)
with engine.connect() as conn:
eq_(conn._execution_options, {"foo": "bar"})
def test_propagate_option_engine_to_connection(self, testing_engine):
e1 = testing_engine(
"sqlite://", options=dict(execution_options={"foo": "bar"})
)
e2 = e1.execution_options(bat="hoho")
c1 = e1.connect()
c2 = e2.connect()
eq_(c1._execution_options, {"foo": "bar"})
eq_(c2._execution_options, {"foo": "bar", "bat": "hoho"})
c1.close()
c2.close()
def test_get_engine_execution_options(self, testing_engine):
engine = testing_engine("sqlite://")
engine.dialect = Mock()
e2 = engine.execution_options(foo="bar")
eq_(e2.get_execution_options(), {"foo": "bar"})
def test_get_connection_execution_options(self, testing_engine):
engine = testing_engine("sqlite://", options=dict(_initialize=False))
engine.dialect = Mock()
with engine.connect() as conn:
c = conn.execution_options(foo="bar")
eq_(c.get_execution_options(), {"foo": "bar"})
| ExecutionOptionsTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 1767,
"end": 1964
} | class ____(IncrementalShopifyStreamWithDeletedEvents):
cursor_field = "id"
order_field = "id"
data_field = "blogs"
filter_field = "since_id"
deleted_events_api_name = "Blog"
| Blogs |
python | django-haystack__django-haystack | test_haystack/core/models.py | {
"start": 1690,
"end": 1910
} | class ____(models.Model):
author = models.CharField(max_length=255)
deleted = models.BooleanField(default=False)
objects = SoftDeleteManager()
def __str__(self):
return self.author
| AFifthMockModel |
python | doocs__leetcode | solution/1900-1999/1958.Check if Move is Legal/Solution.py | {
"start": 0,
"end": 638
} | class ____:
def checkMove(
self, board: List[List[str]], rMove: int, cMove: int, color: str
) -> bool:
for a in range(-1, 2):
for b in range(-1, 2):
if a == 0 and b == 0:
continue
i, j = rMove, cMove
cnt = 0
while 0 <= i + a < 8 and 0 <= j + b < 8:
cnt += 1
i, j = i + a, j + b
if cnt > 1 and board[i][j] == color:
return True
if board[i][j] in (color, "."):
break
return False
| Solution |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_pprint.py | {
"start": 3845,
"end": 4723
} | class ____(BaseEstimator):
def __init__(
self,
C=1.0,
kernel="rbf",
degree=3,
gamma="auto_deprecated",
coef0=0.0,
shrinking=True,
probability=False,
tol=1e-3,
cache_size=200,
class_weight=None,
verbose=False,
max_iter=-1,
decision_function_shape="ovr",
random_state=None,
):
self.kernel = kernel
self.degree = degree
self.gamma = gamma
self.coef0 = coef0
self.tol = tol
self.C = C
self.shrinking = shrinking
self.probability = probability
self.cache_size = cache_size
self.class_weight = class_weight
self.verbose = verbose
self.max_iter = max_iter
self.decision_function_shape = decision_function_shape
self.random_state = random_state
| SVC |
python | django-extensions__django-extensions | tests/management/commands/test_sqldsn.py | {
"start": 1262,
"end": 1616
} | class ____(TestCase):
"""Tests for sqldsn management command exceptions."""
@override_settings(DATABASES={})
def test_should_raise_CommandError_if_unknown_database_does_not_exist(self):
with self.assertRaisesRegex(CommandError, "Unknown database unknown"):
call_command("sqldsn", "--database=unknown")
| SqlDsnExceptionsTests |
python | huggingface__transformers | src/transformers/models/dpt/configuration_dpt.py | {
"start": 942,
"end": 13976
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DPTModel`]. It is used to instantiate an DPT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the DPT
[Intel/dpt-large](https://huggingface.co/Intel/dpt-large) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
image_size (`int`, *optional*, defaults to 384):
The size (resolution) of each image.
patch_size (`int`, *optional*, defaults to 16):
The size (resolution) of each patch.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
is_hybrid (`bool`, *optional*, defaults to `False`):
Whether to use a hybrid backbone. Useful in the context of loading DPT-Hybrid models.
qkv_bias (`bool`, *optional*, defaults to `True`):
Whether to add a bias to the queries, keys and values.
backbone_out_indices (`list[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
Indices of the intermediate hidden states to use from backbone.
readout_type (`str`, *optional*, defaults to `"project"`):
The readout type to use when processing the readout token (CLS token) of the intermediate hidden states of
the ViT backbone. Can be one of [`"ignore"`, `"add"`, `"project"`].
- "ignore" simply ignores the CLS token.
- "add" passes the information from the CLS token to all other tokens by adding the representations.
- "project" passes information to the other tokens by concatenating the readout to all other tokens before
projecting the
representation to the original feature dimension D using a linear layer followed by a GELU non-linearity.
reassemble_factors (`list[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
The up/downsampling factors of the reassemble layers.
neck_hidden_sizes (`list[str]`, *optional*, defaults to `[96, 192, 384, 768]`):
The hidden sizes to project to for the feature maps of the backbone.
fusion_hidden_size (`int`, *optional*, defaults to 256):
The number of channels before fusion.
head_in_index (`int`, *optional*, defaults to -1):
The index of the features to use in the heads.
use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`):
Whether to use batch normalization in the pre-activate residual units of the fusion blocks.
use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`):
Whether to use bias in the pre-activate residual units of the fusion blocks.
add_projection (`bool`, *optional*, defaults to `False`):
Whether to add a projection layer before the depth estimation head.
use_auxiliary_head (`bool`, *optional*, defaults to `True`):
Whether to use an auxiliary head during training.
auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
Weight of the cross-entropy loss of the auxiliary head.
semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
The index that is ignored by the loss function of the semantic segmentation model.
semantic_classifier_dropout (`float`, *optional*, defaults to 0.1):
The dropout ratio for the semantic classification head.
backbone_featmap_shape (`list[int]`, *optional*, defaults to `[1, 1024, 24, 24]`):
Used only for the `hybrid` embedding type. The shape of the feature maps of the backbone.
neck_ignore_stages (`list[int]`, *optional*, defaults to `[0, 1]`):
Used only for the `hybrid` embedding type. The stages of the readout layers to ignore.
backbone_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*):
The configuration of the backbone model. Only used in case `is_hybrid` is `True` or in case you want to
leverage the [`AutoBackbone`] API.
backbone (`str`, *optional*):
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
Whether to use pretrained weights for the backbone.
use_timm_backbone (`bool`, *optional*, defaults to `False`):
Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
library.
backbone_kwargs (`dict`, *optional*):
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
pooler_output_size (`int`, *optional*):
Dimensionality of the pooler layer. If None, defaults to `hidden_size`.
pooler_act (`str`, *optional*, defaults to `"tanh"`):
The activation function to be used by the pooler.
Example:
```python
>>> from transformers import DPTModel, DPTConfig
>>> # Initializing a DPT dpt-large style configuration
>>> configuration = DPTConfig()
>>> # Initializing a model from the dpt-large style configuration
>>> model = DPTModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "dpt"
sub_configs = {"backbone_config": AutoConfig}
def __init__(
self,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.0,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
layer_norm_eps=1e-12,
image_size=384,
patch_size=16,
num_channels=3,
is_hybrid=False,
qkv_bias=True,
backbone_out_indices=[2, 5, 8, 11],
readout_type="project",
reassemble_factors=[4, 2, 1, 0.5],
neck_hidden_sizes=[96, 192, 384, 768],
fusion_hidden_size=256,
head_in_index=-1,
use_batch_norm_in_fusion_residual=False,
use_bias_in_fusion_residual=None,
add_projection=False,
use_auxiliary_head=True,
auxiliary_loss_weight=0.4,
semantic_loss_ignore_index=255,
semantic_classifier_dropout=0.1,
backbone_featmap_shape=[1, 1024, 24, 24],
neck_ignore_stages=[0, 1],
backbone_config=None,
backbone=None,
use_pretrained_backbone=False,
use_timm_backbone=False,
backbone_kwargs=None,
pooler_output_size=None,
pooler_act="tanh",
**kwargs,
):
self.hidden_size = hidden_size
self.is_hybrid = is_hybrid
use_autobackbone = False
if self.is_hybrid:
if backbone_config is None:
backbone_config = {
"global_padding": "same",
"layer_type": "bottleneck",
"depths": [3, 4, 9],
"out_features": ["stage1", "stage2", "stage3"],
"embedding_dynamic_padding": True,
}
if isinstance(backbone_config, dict):
logger.info("Initializing the config with a `BiT` backbone.")
backbone_config = BitConfig(**backbone_config)
elif not isinstance(backbone_config, PreTrainedConfig):
raise ValueError(
f"backbone_config must be a dictionary or a `PreTrainedConfig`, got {backbone_config.__class__}."
)
self.backbone_config = backbone_config
self.backbone_featmap_shape = backbone_featmap_shape
self.neck_ignore_stages = neck_ignore_stages
if readout_type != "project":
raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode.")
elif backbone is not None or backbone_config is not None:
use_autobackbone = True
if isinstance(backbone_config, dict):
backbone_model_type = backbone_config.get("model_type")
config_class = CONFIG_MAPPING[backbone_model_type]
backbone_config = config_class.from_dict(backbone_config)
self.backbone_config = backbone_config
self.backbone_featmap_shape = None
self.neck_ignore_stages = []
# We only use load_backbone when config.is_hydrid is False
verify_backbone_config_arguments(
use_timm_backbone=use_timm_backbone,
use_pretrained_backbone=use_pretrained_backbone,
backbone=backbone,
backbone_config=backbone_config,
backbone_kwargs=backbone_kwargs,
)
else:
self.backbone_config = None
self.backbone_featmap_shape = None
self.neck_ignore_stages = []
self.backbone = backbone
self.use_pretrained_backbone = use_pretrained_backbone
self.use_timm_backbone = use_timm_backbone
self.backbone_kwargs = backbone_kwargs
# ViT parameters used if not using a hybrid backbone
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.layer_norm_eps = layer_norm_eps
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.qkv_bias = qkv_bias
self.use_autobackbone = use_autobackbone
self.backbone_out_indices = None if use_autobackbone else backbone_out_indices
if readout_type not in ["ignore", "add", "project"]:
raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']")
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.readout_type = readout_type
self.reassemble_factors = reassemble_factors
self.neck_hidden_sizes = neck_hidden_sizes
self.fusion_hidden_size = fusion_hidden_size
self.head_in_index = head_in_index
self.use_batch_norm_in_fusion_residual = use_batch_norm_in_fusion_residual
self.use_bias_in_fusion_residual = use_bias_in_fusion_residual
self.add_projection = add_projection
# auxiliary head attributes (semantic segmentation)
self.use_auxiliary_head = use_auxiliary_head
self.auxiliary_loss_weight = auxiliary_loss_weight
self.semantic_loss_ignore_index = semantic_loss_ignore_index
self.semantic_classifier_dropout = semantic_classifier_dropout
self.pooler_output_size = pooler_output_size if pooler_output_size else hidden_size
self.pooler_act = pooler_act
super().__init__(**kwargs)
__all__ = ["DPTConfig"]
| DPTConfig |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 35895,
"end": 36077
} | class ____(BoringModel):
def on_train_batch_end(self, outputs, batch, batch_idx):
if batch_idx == 1:
raise RuntimeError("Trouble!")
| TroubledModelOnTrainBatchEnd |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modular_glm4v_moe.py | {
"start": 2133,
"end": 2191
} | class ____(Glm4vVisionConfig):
pass
| Glm4vMoeVisionConfig |
python | falconry__falcon | tests/test_cmd_inspect_app.py | {
"start": 1049,
"end": 3021
} | class ____:
@pytest.mark.parametrize(
'args, exp',
(
(
['foo'],
Namespace(
app_module='foo', route_only=False, verbose=False, internal=False
),
),
(
['foo', '-r'],
Namespace(
app_module='foo', route_only=True, verbose=False, internal=False
),
),
(
['foo', '--route_only'],
Namespace(
app_module='foo', route_only=True, verbose=False, internal=False
),
),
(
['foo', '-v'],
Namespace(
app_module='foo', route_only=False, verbose=True, internal=False
),
),
(
['foo', '--verbose'],
Namespace(
app_module='foo', route_only=False, verbose=True, internal=False
),
),
(
['foo', '-i'],
Namespace(
app_module='foo', route_only=False, verbose=False, internal=True
),
),
(
['foo', '--internal'],
Namespace(
app_module='foo', route_only=False, verbose=False, internal=True
),
),
(
['foo', '-r', '-v', '-i'],
Namespace(
app_module='foo', route_only=True, verbose=True, internal=True
),
),
),
)
def test_make_parser(self, args, exp):
parser = inspect_app.make_parser()
actual = parser.parse_args(args)
assert actual == exp
def test_make_parser_error(self):
parser = inspect_app.make_parser()
with pytest.raises(SystemExit):
parser.parse_args([])
| TestMakeParser |
python | doocs__leetcode | solution/2400-2499/2463.Minimum Total Distance Traveled/Solution.py | {
"start": 0,
"end": 668
} | class ____:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
@cache
def dfs(i, j):
if i == len(robot):
return 0
if j == len(factory):
return inf
ans = dfs(i, j + 1)
t = 0
for k in range(factory[j][1]):
if i + k == len(robot):
break
t += abs(robot[i + k] - factory[j][0])
ans = min(ans, t + dfs(i + k + 1, j + 1))
return ans
robot.sort()
factory.sort()
ans = dfs(0, 0)
dfs.cache_clear()
return ans
| Solution |
python | scipy__scipy | scipy/stats/tests/test_multivariate.py | {
"start": 20068,
"end": 49511
} | class ____:
def test_input_shape(self):
mu = np.arange(3)
cov = np.identity(2)
assert_raises(ValueError, multivariate_normal.pdf, (0, 1), mu, cov)
assert_raises(ValueError, multivariate_normal.pdf, (0, 1, 2), mu, cov)
assert_raises(ValueError, multivariate_normal.cdf, (0, 1), mu, cov)
assert_raises(ValueError, multivariate_normal.cdf, (0, 1, 2), mu, cov)
def test_scalar_values(self):
rng = np.random.default_rng(1234)
# When evaluated on scalar data, the pdf should return a scalar
x, mean, cov = 1.5, 1.7, 2.5
pdf = multivariate_normal.pdf(x, mean, cov)
assert_equal(pdf.ndim, 0)
# When evaluated on a single vector, the pdf should return a scalar
x = rng.standard_normal(5)
mean = rng.standard_normal(5)
cov = np.abs(rng.standard_normal(5)) # Diagonal values for cov. matrix
pdf = multivariate_normal.pdf(x, mean, cov)
assert_equal(pdf.ndim, 0)
# When evaluated on scalar data, the cdf should return a scalar
x, mean, cov = 1.5, 1.7, 2.5
cdf = multivariate_normal.cdf(x, mean, cov)
assert_equal(cdf.ndim, 0)
# When evaluated on a single vector, the cdf should return a scalar
x = rng.standard_normal(5)
mean = rng.standard_normal(5)
cov = np.abs(rng.standard_normal(5)) # Diagonal values for cov. matrix
cdf = multivariate_normal.cdf(x, mean, cov)
assert_equal(cdf.ndim, 0)
def test_logpdf(self):
# Check that the log of the pdf is in fact the logpdf
rng = np.random.default_rng(1234)
x = rng.standard_normal(5)
mean = rng.standard_normal(5)
cov = np.abs(rng.standard_normal(5))
d1 = multivariate_normal.logpdf(x, mean, cov)
d2 = multivariate_normal.pdf(x, mean, cov)
assert_allclose(d1, np.log(d2))
def test_logpdf_default_values(self):
# Check that the log of the pdf is in fact the logpdf
# with default parameters Mean=None and cov = 1
rng = np.random.default_rng(1234)
x = rng.standard_normal(5)
d1 = multivariate_normal.logpdf(x)
d2 = multivariate_normal.pdf(x)
# check whether default values are being used
d3 = multivariate_normal.logpdf(x, None, 1)
d4 = multivariate_normal.pdf(x, None, 1)
assert_allclose(d1, np.log(d2))
assert_allclose(d3, np.log(d4))
def test_logcdf(self):
# Check that the log of the cdf is in fact the logcdf
rng = np.random.default_rng(1234)
x = rng.standard_normal(5)
mean = rng.standard_normal(5)
cov = np.abs(rng.standard_normal(5))
d1 = multivariate_normal.logcdf(x, mean, cov)
d2 = multivariate_normal.cdf(x, mean, cov)
assert_allclose(d1, np.log(d2))
def test_logcdf_default_values(self):
# Check that the log of the cdf is in fact the logcdf
# with default parameters Mean=None and cov = 1
rng = np.random.default_rng(1234)
x = rng.standard_normal(5)
d1 = multivariate_normal.logcdf(x)
d2 = multivariate_normal.cdf(x)
# check whether default values are being used
d3 = multivariate_normal.logcdf(x, None, 1)
d4 = multivariate_normal.cdf(x, None, 1)
assert_allclose(d1, np.log(d2))
assert_allclose(d3, np.log(d4))
def test_rank(self):
# Check that the rank is detected correctly.
rng = np.random.default_rng(1234)
n = 4
mean = rng.standard_normal(n)
for expected_rank in range(1, n + 1):
s = rng.standard_normal((n, expected_rank))
cov = np.dot(s, s.T)
distn = multivariate_normal(mean, cov, allow_singular=True)
assert_equal(distn.cov_object.rank, expected_rank)
def test_degenerate_distributions(self):
rng = np.random.default_rng(1234)
for n in range(1, 5):
z = rng.standard_normal(n)
for k in range(1, n):
# Sample a small covariance matrix.
s = rng.standard_normal((k, k))
cov_kk = np.dot(s, s.T)
# Embed the small covariance matrix into a larger singular one.
cov_nn = np.zeros((n, n))
cov_nn[:k, :k] = cov_kk
# Embed part of the vector in the same way
x = np.zeros(n)
x[:k] = z[:k]
# Define a rotation of the larger low rank matrix.
u = _sample_orthonormal_matrix(n)
cov_rr = np.dot(u, np.dot(cov_nn, u.T))
y = np.dot(u, x)
# Check some identities.
distn_kk = multivariate_normal(np.zeros(k), cov_kk,
allow_singular=True)
distn_nn = multivariate_normal(np.zeros(n), cov_nn,
allow_singular=True)
distn_rr = multivariate_normal(np.zeros(n), cov_rr,
allow_singular=True)
assert_equal(distn_kk.cov_object.rank, k)
assert_equal(distn_nn.cov_object.rank, k)
assert_equal(distn_rr.cov_object.rank, k)
pdf_kk = distn_kk.pdf(x[:k])
pdf_nn = distn_nn.pdf(x)
pdf_rr = distn_rr.pdf(y)
assert_allclose(pdf_kk, pdf_nn)
assert_allclose(pdf_kk, pdf_rr)
logpdf_kk = distn_kk.logpdf(x[:k])
logpdf_nn = distn_nn.logpdf(x)
logpdf_rr = distn_rr.logpdf(y)
assert_allclose(logpdf_kk, logpdf_nn)
assert_allclose(logpdf_kk, logpdf_rr)
# Add an orthogonal component and find the density
y_orth = y + u[:, -1]
pdf_rr_orth = distn_rr.pdf(y_orth)
logpdf_rr_orth = distn_rr.logpdf(y_orth)
# Ensure that this has zero probability
assert_equal(pdf_rr_orth, 0.0)
assert_equal(logpdf_rr_orth, -np.inf)
def test_degenerate_array(self):
# Test that we can generate arrays of random variate from a degenerate
# multivariate normal, and that the pdf for these samples is non-zero
# (i.e. samples from the distribution lie on the subspace)
k = 10
for n in range(2, 6):
for r in range(1, n):
mn = np.zeros(n)
u = _sample_orthonormal_matrix(n)[:, :r]
vr = np.dot(u, u.T)
X = multivariate_normal.rvs(mean=mn, cov=vr, size=k)
pdf = multivariate_normal.pdf(X, mean=mn, cov=vr,
allow_singular=True)
assert_equal(pdf.size, k)
assert np.all(pdf > 0.0)
logpdf = multivariate_normal.logpdf(X, mean=mn, cov=vr,
allow_singular=True)
assert_equal(logpdf.size, k)
assert np.all(logpdf > -np.inf)
def test_large_pseudo_determinant(self):
# Check that large pseudo-determinants are handled appropriately.
# Construct a singular diagonal covariance matrix
# whose pseudo determinant overflows double precision.
large_total_log = 1000.0
npos = 100
nzero = 2
large_entry = np.exp(large_total_log / npos)
n = npos + nzero
cov = np.zeros((n, n), dtype=float)
np.fill_diagonal(cov, large_entry)
cov[-nzero:, -nzero:] = 0
# Check some determinants.
assert_equal(scipy.linalg.det(cov), 0)
assert_equal(scipy.linalg.det(cov[:npos, :npos]), np.inf)
assert_allclose(np.linalg.slogdet(cov[:npos, :npos]),
(1, large_total_log))
# Check the pseudo-determinant.
psd = _PSD(cov)
assert_allclose(psd.log_pdet, large_total_log)
def test_broadcasting(self):
rng = np.random.RandomState(1234)
n = 4
# Construct a random covariance matrix.
data = rng.randn(n, n)
cov = np.dot(data, data.T)
mean = rng.randn(n)
# Construct an ndarray which can be interpreted as
# a 2x3 array whose elements are random data vectors.
X = rng.randn(2, 3, n)
# Check that multiple data points can be evaluated at once.
desired_pdf = multivariate_normal.pdf(X, mean, cov)
desired_cdf = multivariate_normal.cdf(X, mean, cov)
for i in range(2):
for j in range(3):
actual = multivariate_normal.pdf(X[i, j], mean, cov)
assert_allclose(actual, desired_pdf[i,j])
# Repeat for cdf
actual = multivariate_normal.cdf(X[i, j], mean, cov)
assert_allclose(actual, desired_cdf[i,j], rtol=1e-3)
def test_normal_1D(self):
# The probability density function for a 1D normal variable should
# agree with the standard normal distribution in scipy.stats.distributions
x = np.linspace(0, 2, 10)
mean, cov = 1.2, 0.9
scale = cov**0.5
d1 = norm.pdf(x, mean, scale)
d2 = multivariate_normal.pdf(x, mean, cov)
assert_allclose(d1, d2)
# The same should hold for the cumulative distribution function
d1 = norm.cdf(x, mean, scale)
d2 = multivariate_normal.cdf(x, mean, cov)
assert_allclose(d1, d2)
def test_marginalization(self):
# Integrating out one of the variables of a 2D Gaussian should
# yield a 1D Gaussian
mean = np.array([2.5, 3.5])
cov = np.array([[.5, 0.2], [0.2, .6]])
n = 2 ** 8 + 1 # Number of samples
delta = 6 / (n - 1) # Grid spacing
v = np.linspace(0, 6, n)
xv, yv = np.meshgrid(v, v)
pos = np.empty((n, n, 2))
pos[:, :, 0] = xv
pos[:, :, 1] = yv
pdf = multivariate_normal.pdf(pos, mean, cov)
# Marginalize over x and y axis
margin_x = romb(pdf, delta, axis=0)
margin_y = romb(pdf, delta, axis=1)
# Compare with standard normal distribution
gauss_x = norm.pdf(v, loc=mean[0], scale=cov[0, 0] ** 0.5)
gauss_y = norm.pdf(v, loc=mean[1], scale=cov[1, 1] ** 0.5)
assert_allclose(margin_x, gauss_x, rtol=1e-2, atol=1e-2)
assert_allclose(margin_y, gauss_y, rtol=1e-2, atol=1e-2)
def test_frozen(self):
# The frozen distribution should agree with the regular one
rng = np.random.default_rng(1234)
x = rng.standard_normal(5)
mean = rng.standard_normal(5)
cov = np.abs(rng.standard_normal(5))
norm_frozen = multivariate_normal(mean, cov)
assert_allclose(norm_frozen.pdf(x), multivariate_normal.pdf(x, mean, cov))
assert_allclose(norm_frozen.logpdf(x),
multivariate_normal.logpdf(x, mean, cov))
assert_allclose(norm_frozen.cdf(x), multivariate_normal.cdf(x, mean, cov))
assert_allclose(norm_frozen.logcdf(x),
multivariate_normal.logcdf(x, mean, cov))
@pytest.mark.parametrize(
'covariance',
[
np.eye(2),
Covariance.from_diagonal([1, 1]),
]
)
def test_frozen_multivariate_normal_exposes_attributes(self, covariance):
mean = np.ones((2,))
cov_should_be = np.eye(2)
norm_frozen = multivariate_normal(mean, covariance)
assert np.allclose(norm_frozen.mean, mean)
assert np.allclose(norm_frozen.cov, cov_should_be)
def test_pseudodet_pinv(self):
# Make sure that pseudo-inverse and pseudo-det agree on cutoff
# Assemble random covariance matrix with large and small eigenvalues
rng = np.random.default_rng(1234)
n = 7
x = rng.standard_normal((n, n))
cov = np.dot(x, x.T)
s, u = scipy.linalg.eigh(cov)
s = np.full(n, 0.5)
s[0] = 1.0
s[-1] = 1e-7
cov = np.dot(u, np.dot(np.diag(s), u.T))
# Set cond so that the lowest eigenvalue is below the cutoff
cond = 1e-5
psd = _PSD(cov, cond=cond)
psd_pinv = _PSD(psd.pinv, cond=cond)
# Check that the log pseudo-determinant agrees with the sum
# of the logs of all but the smallest eigenvalue
assert_allclose(psd.log_pdet, np.sum(np.log(s[:-1])))
# Check that the pseudo-determinant of the pseudo-inverse
# agrees with 1 / pseudo-determinant
assert_allclose(-psd.log_pdet, psd_pinv.log_pdet)
def test_exception_nonsquare_cov(self):
cov = [[1, 2, 3], [4, 5, 6]]
assert_raises(ValueError, _PSD, cov)
def test_exception_nonfinite_cov(self):
cov_nan = [[1, 0], [0, np.nan]]
assert_raises(ValueError, _PSD, cov_nan)
cov_inf = [[1, 0], [0, np.inf]]
assert_raises(ValueError, _PSD, cov_inf)
def test_exception_non_psd_cov(self):
cov = [[1, 0], [0, -1]]
assert_raises(ValueError, _PSD, cov)
def test_exception_singular_cov(self):
rng = np.random.default_rng(1234)
x = rng.standard_normal(5)
mean = rng.standard_normal(5)
cov = np.ones((5, 5))
e = np.linalg.LinAlgError
assert_raises(e, multivariate_normal, mean, cov)
assert_raises(e, multivariate_normal.pdf, x, mean, cov)
assert_raises(e, multivariate_normal.logpdf, x, mean, cov)
assert_raises(e, multivariate_normal.cdf, x, mean, cov)
assert_raises(e, multivariate_normal.logcdf, x, mean, cov)
# Message used to be "singular matrix", but this is more accurate.
# See gh-15508
cov = [[1., 0.], [1., 1.]]
msg = "When `allow_singular is False`, the input matrix"
with pytest.raises(np.linalg.LinAlgError, match=msg):
multivariate_normal(cov=cov)
def test_R_values(self):
# Compare the multivariate pdf with some values precomputed
# in R version 3.0.1 (2013-05-16) on Mac OS X 10.6.
# The values below were generated by the following R-script:
# > library(mnormt)
# > x <- seq(0, 2, length=5)
# > y <- 3*x - 2
# > z <- x + cos(y)
# > mu <- c(1, 3, 2)
# > Sigma <- matrix(c(1,2,0,2,5,0.5,0,0.5,3), 3, 3)
# > r_pdf <- dmnorm(cbind(x,y,z), mu, Sigma)
r_pdf = np.array([0.0002214706, 0.0013819953, 0.0049138692,
0.0103803050, 0.0140250800])
x = np.linspace(0, 2, 5)
y = 3 * x - 2
z = x + np.cos(y)
r = np.array([x, y, z]).T
mean = np.array([1, 3, 2], 'd')
cov = np.array([[1, 2, 0], [2, 5, .5], [0, .5, 3]], 'd')
pdf = multivariate_normal.pdf(r, mean, cov)
assert_allclose(pdf, r_pdf, atol=1e-10)
# Compare the multivariate cdf with some values precomputed
# in R version 3.3.2 (2016-10-31) on Debian GNU/Linux.
# The values below were generated by the following R-script:
# > library(mnormt)
# > x <- seq(0, 2, length=5)
# > y <- 3*x - 2
# > z <- x + cos(y)
# > mu <- c(1, 3, 2)
# > Sigma <- matrix(c(1,2,0,2,5,0.5,0,0.5,3), 3, 3)
# > r_cdf <- pmnorm(cbind(x,y,z), mu, Sigma)
r_cdf = np.array([0.0017866215, 0.0267142892, 0.0857098761,
0.1063242573, 0.2501068509])
cdf = multivariate_normal.cdf(r, mean, cov)
assert_allclose(cdf, r_cdf, atol=2e-5)
# Also test bivariate cdf with some values precomputed
# in R version 3.3.2 (2016-10-31) on Debian GNU/Linux.
# The values below were generated by the following R-script:
# > library(mnormt)
# > x <- seq(0, 2, length=5)
# > y <- 3*x - 2
# > mu <- c(1, 3)
# > Sigma <- matrix(c(1,2,2,5), 2, 2)
# > r_cdf2 <- pmnorm(cbind(x,y), mu, Sigma)
r_cdf2 = np.array([0.01262147, 0.05838989, 0.18389571,
0.40696599, 0.66470577])
r2 = np.array([x, y]).T
mean2 = np.array([1, 3], 'd')
cov2 = np.array([[1, 2], [2, 5]], 'd')
cdf2 = multivariate_normal.cdf(r2, mean2, cov2)
assert_allclose(cdf2, r_cdf2, atol=1e-5)
def test_multivariate_normal_rvs_zero_covariance(self):
mean = np.zeros(2)
covariance = np.zeros((2, 2))
model = multivariate_normal(mean, covariance, allow_singular=True)
sample = model.rvs()
assert_equal(sample, [0, 0])
def test_rvs_shape(self):
# Check that rvs parses the mean and covariance correctly, and returns
# an array of the right shape
N = 300
d = 4
sample = multivariate_normal.rvs(mean=np.zeros(d), cov=1, size=N)
assert_equal(sample.shape, (N, d))
sample = multivariate_normal.rvs(mean=None,
cov=np.array([[2, .1], [.1, 1]]),
size=N)
assert_equal(sample.shape, (N, 2))
u = multivariate_normal(mean=0, cov=1)
sample = u.rvs(N)
assert_equal(sample.shape, (N, ))
def test_large_sample(self):
# Generate large sample and compare sample mean and sample covariance
# with mean and covariance matrix.
rng = np.random.RandomState(2846)
n = 3
mean = rng.randn(n)
M = rng.randn(n, n)
cov = np.dot(M, M.T)
size = 5000
sample = multivariate_normal.rvs(mean, cov, size, random_state=rng)
assert_allclose(np.cov(sample.T), cov, rtol=1e-1)
assert_allclose(sample.mean(0), mean, rtol=1e-1)
def test_entropy(self):
rng = np.random.RandomState(2846)
n = 3
mean = rng.randn(n)
M = rng.randn(n, n)
cov = np.dot(M, M.T)
rv = multivariate_normal(mean, cov)
# Check that frozen distribution agrees with entropy function
assert_almost_equal(rv.entropy(), multivariate_normal.entropy(mean, cov))
# Compare entropy with manually computed expression involving
# the sum of the logs of the eigenvalues of the covariance matrix
eigs = np.linalg.eig(cov)[0]
desired = 1 / 2 * (n * (np.log(2 * np.pi) + 1) + np.sum(np.log(eigs)))
assert_almost_equal(desired, rv.entropy())
def test_lnB(self):
alpha = np.array([1, 1, 1])
desired = .5 # e^lnB = 1/2 for [1, 1, 1]
assert_almost_equal(np.exp(_lnB(alpha)), desired)
def test_cdf_with_lower_limit_arrays(self):
# test CDF with lower limit in several dimensions
rng = np.random.default_rng(2408071309372769818)
mean = [0, 0]
cov = np.eye(2)
a = rng.random((4, 3, 2))*6 - 3
b = rng.random((4, 3, 2))*6 - 3
cdf1 = multivariate_normal.cdf(b, mean, cov, lower_limit=a)
cdf2a = multivariate_normal.cdf(b, mean, cov)
cdf2b = multivariate_normal.cdf(a, mean, cov)
ab1 = np.concatenate((a[..., 0:1], b[..., 1:2]), axis=-1)
ab2 = np.concatenate((a[..., 1:2], b[..., 0:1]), axis=-1)
cdf2ab1 = multivariate_normal.cdf(ab1, mean, cov)
cdf2ab2 = multivariate_normal.cdf(ab2, mean, cov)
cdf2 = cdf2a + cdf2b - cdf2ab1 - cdf2ab2
assert_allclose(cdf1, cdf2)
def test_cdf_with_lower_limit_consistency(self):
# check that multivariate normal CDF functions are consistent
rng = np.random.default_rng(2408071309372769818)
mean = rng.random(3)
cov = rng.random((3, 3))
cov = cov @ cov.T
a = rng.random((2, 3))*6 - 3
b = rng.random((2, 3))*6 - 3
cdf1 = multivariate_normal.cdf(b, mean, cov, lower_limit=a)
cdf2 = multivariate_normal(mean, cov).cdf(b, lower_limit=a)
cdf3 = np.exp(multivariate_normal.logcdf(b, mean, cov, lower_limit=a))
cdf4 = np.exp(multivariate_normal(mean, cov).logcdf(b, lower_limit=a))
assert_allclose(cdf2, cdf1, rtol=1e-4)
assert_allclose(cdf3, cdf1, rtol=1e-4)
assert_allclose(cdf4, cdf1, rtol=1e-4)
def test_cdf_signs(self):
# check that sign of output is correct when np.any(lower > x)
mean = np.zeros(3)
cov = np.eye(3)
b = [[1, 1, 1], [0, 0, 0], [1, 0, 1], [0, 1, 0]]
a = [[0, 0, 0], [1, 1, 1], [0, 1, 0], [1, 0, 1]]
# when odd number of elements of b < a, output is negative
expected_signs = np.array([1, -1, -1, 1])
cdf = multivariate_normal.cdf(b, mean, cov, lower_limit=a)
assert_allclose(cdf, cdf[0]*expected_signs)
@pytest.mark.slow
@pytest.mark.parametrize("ndim", [2, 3])
def test_cdf_vs_cubature(self, ndim):
rng = np.random.default_rng(123)
a = rng.uniform(size=(ndim, ndim))
cov = a.T @ a
m = rng.uniform(size=ndim)
dist = multivariate_normal(mean=m, cov=cov)
x = rng.uniform(low=-3, high=3, size=(ndim,))
cdf = dist.cdf(x)
dist_i = multivariate_normal(mean=[0]*ndim, cov=cov)
cdf_i = cubature(dist_i.pdf, [-np.inf]*ndim, x - m).estimate
assert_allclose(cdf, cdf_i, atol=5e-6)
def test_cdf_known(self):
# https://github.com/scipy/scipy/pull/17410#issuecomment-1312628547
for ndim in range(2, 12):
cov = np.full((ndim, ndim), 0.5)
np.fill_diagonal(cov, 1.)
dist = multivariate_normal([0]*ndim, cov=cov)
assert_allclose(
dist.cdf([0]*ndim),
1. / (1. + ndim),
atol=5e-5
)
@pytest.mark.parametrize("ndim", range(2, 10))
@pytest.mark.parametrize("seed", [0xdeadbeef, 0xdd24528764c9773579731c6b022b48e2])
def test_cdf_vs_univariate(self, seed, ndim):
rng = np.random.default_rng(seed)
case = MVNProblem.generate_semigeneral(ndim=ndim, rng=rng)
assert (case.low == -np.inf).all()
dist = multivariate_normal(mean=[0]*ndim, cov=case.covar)
cdf_val = dist.cdf(case.high, rng=rng)
assert_allclose(cdf_val, case.target_val, atol=5e-5)
@pytest.mark.parametrize("ndim", range(2, 11))
@pytest.mark.parametrize("seed", [0xdeadbeef, 0xdd24528764c9773579731c6b022b48e2])
def test_cdf_vs_univariate_2(self, seed, ndim):
rng = np.random.default_rng(seed)
case = MVNProblem.generate_constant(ndim=ndim, rng=rng)
assert (case.low == -np.inf).all()
dist = multivariate_normal(mean=[0]*ndim, cov=case.covar)
cdf_val = dist.cdf(case.high, rng=rng)
assert_allclose(cdf_val, case.target_val, atol=5e-5)
@pytest.mark.parametrize("ndim", range(4, 11))
@pytest.mark.parametrize("seed", [0xdeadbeef, 0xdd24528764c9773579731c6b022b48e4])
def test_cdf_vs_univariate_singular(self, seed, ndim):
# NB: ndim = 2, 3 has much poorer accuracy than ndim > 3 for many seeds.
# No idea why.
rng = np.random.default_rng(seed)
case = SingularMVNProblem.generate_semiinfinite(ndim=ndim, rng=rng)
assert (case.low == -np.inf).all()
dist = multivariate_normal(mean=[0]*ndim, cov=case.covar, allow_singular=True,
# default maxpts is too slow, limit it here
maxpts=10_000*case.covar.shape[0]
)
cdf_val = dist.cdf(case.high, rng=rng)
assert_allclose(cdf_val, case.target_val, atol=1e-3)
def test_mean_cov(self):
# test the interaction between a Covariance object and mean
P = np.diag(1 / np.array([1, 2, 3]))
cov_object = _covariance.CovViaPrecision(P)
message = "`cov` represents a covariance matrix in 3 dimensions..."
with pytest.raises(ValueError, match=message):
multivariate_normal.entropy([0, 0], cov_object)
with pytest.raises(ValueError, match=message):
multivariate_normal([0, 0], cov_object)
x = [0.5, 0.5, 0.5]
ref = multivariate_normal.pdf(x, [0, 0, 0], cov_object)
assert_equal(multivariate_normal.pdf(x, cov=cov_object), ref)
ref = multivariate_normal.pdf(x, [1, 1, 1], cov_object)
assert_equal(multivariate_normal.pdf(x, 1, cov=cov_object), ref)
def test_fit_wrong_fit_data_shape(self):
data = [1, 3]
error_msg = "`x` must be two-dimensional."
with pytest.raises(ValueError, match=error_msg):
multivariate_normal.fit(data)
@pytest.mark.parametrize('dim', (3, 5))
def test_fit_correctness(self, dim):
rng = np.random.default_rng(4385269356937404)
x = rng.random((100, dim))
mean_est, cov_est = multivariate_normal.fit(x)
mean_ref, cov_ref = np.mean(x, axis=0), np.cov(x.T, ddof=0)
assert_allclose(mean_est, mean_ref, atol=1e-15)
assert_allclose(cov_est, cov_ref, rtol=1e-15)
def test_fit_both_parameters_fixed(self):
data = np.full((2, 1), 3)
mean_fixed = 1.
cov_fixed = np.atleast_2d(1.)
mean, cov = multivariate_normal.fit(data, fix_mean=mean_fixed,
fix_cov=cov_fixed)
assert_equal(mean, mean_fixed)
assert_equal(cov, cov_fixed)
@pytest.mark.parametrize('fix_mean', [np.zeros((2, 2)),
np.zeros((3, ))])
def test_fit_fix_mean_input_validation(self, fix_mean):
msg = ("`fix_mean` must be a one-dimensional array the same "
"length as the dimensionality of the vectors `x`.")
with pytest.raises(ValueError, match=msg):
multivariate_normal.fit(np.eye(2), fix_mean=fix_mean)
@pytest.mark.parametrize('fix_cov', [np.zeros((2, )),
np.zeros((3, 2)),
np.zeros((4, 4))])
def test_fit_fix_cov_input_validation_dimension(self, fix_cov):
msg = ("`fix_cov` must be a two-dimensional square array "
"of same side length as the dimensionality of the "
"vectors `x`.")
with pytest.raises(ValueError, match=msg):
multivariate_normal.fit(np.eye(3), fix_cov=fix_cov)
def test_fit_fix_cov_not_positive_semidefinite(self):
error_msg = "`fix_cov` must be symmetric positive semidefinite."
with pytest.raises(ValueError, match=error_msg):
fix_cov = np.array([[1., 0.], [0., -1.]])
multivariate_normal.fit(np.eye(2), fix_cov=fix_cov)
def test_fit_fix_mean(self):
rng = np.random.default_rng(4385269356937404)
loc = rng.random(3)
A = rng.random((3, 3))
cov = np.dot(A, A.T)
samples = multivariate_normal.rvs(mean=loc, cov=cov, size=100,
random_state=rng)
mean_free, cov_free = multivariate_normal.fit(samples)
logp_free = multivariate_normal.logpdf(samples, mean=mean_free,
cov=cov_free).sum()
mean_fix, cov_fix = multivariate_normal.fit(samples, fix_mean=loc)
assert_equal(mean_fix, loc)
logp_fix = multivariate_normal.logpdf(samples, mean=mean_fix,
cov=cov_fix).sum()
# test that fixed parameters result in lower likelihood than free
# parameters
assert logp_fix < logp_free
# test that a small perturbation of the resulting parameters
# has lower likelihood than the estimated parameters
A = rng.random((3, 3))
m = 1e-8 * np.dot(A, A.T)
cov_perturbed = cov_fix + m
logp_perturbed = (multivariate_normal.logpdf(samples,
mean=mean_fix,
cov=cov_perturbed)
).sum()
assert logp_perturbed < logp_fix
def test_fit_fix_cov(self):
rng = np.random.default_rng(4385269356937404)
loc = rng.random(3)
A = rng.random((3, 3))
cov = np.dot(A, A.T)
samples = multivariate_normal.rvs(mean=loc, cov=cov,
size=100, random_state=rng)
mean_free, cov_free = multivariate_normal.fit(samples)
logp_free = multivariate_normal.logpdf(samples, mean=mean_free,
cov=cov_free).sum()
mean_fix, cov_fix = multivariate_normal.fit(samples, fix_cov=cov)
assert_equal(mean_fix, np.mean(samples, axis=0))
assert_equal(cov_fix, cov)
logp_fix = multivariate_normal.logpdf(samples, mean=mean_fix,
cov=cov_fix).sum()
# test that fixed parameters result in lower likelihood than free
# parameters
assert logp_fix < logp_free
# test that a small perturbation of the resulting parameters
# has lower likelihood than the estimated parameters
mean_perturbed = mean_fix + 1e-8 * rng.random(3)
logp_perturbed = (multivariate_normal.logpdf(samples,
mean=mean_perturbed,
cov=cov_fix)
).sum()
assert logp_perturbed < logp_fix
| TestMultivariateNormal |
python | pyinstaller__pyinstaller | PyInstaller/lib/modulegraph/modulegraph.py | {
"start": 26357,
"end": 26740
} | class ____(BaseModule):
def __init__(self, *args, **kwds):
warnings.warn(
"This class will be removed in a future version of modulegraph",
DeprecationWarning)
super(FlatPackage, *args, **kwds)
#FIXME: Safely removable. We don't actually use this anywhere. After removing
#this class, remove the corresponding entry from "compat".
| FlatPackage |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py | {
"start": 5706,
"end": 6053
} | class ____:
@classmethod
def good_cls_method_with_mixed_annotations(cls: "type[Self]", arg: str) -> Self: ...
@staticmethod
def good_static_method_with_string_annotations(arg: "_S") -> "_S": ...
@classmethod
def good_class_method_with_args_string_annotations(cls, arg1: "_S", arg2: "_S") -> "_S": ...
| GoodClassWiStringTypeHints |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.