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 | weaviate__weaviate-python-client | weaviate/embedded.py | {
"start": 11821,
"end": 13714
} | class ____(_EmbeddedBase):
def is_listening(self) -> bool:
up = self.__is_listening()
return up[0] and up[1]
def __is_listening(self) -> Tuple[bool, bool]:
http_listening, grpc_listening = False, False
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect((self.options.hostname, self.options.port))
http_listening = True
except (socket.error, ConnectionRefusedError):
pass
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect((self.options.hostname, self.grpc_port))
grpc_listening = True
except (socket.error, ConnectionRefusedError):
pass
return (http_listening, grpc_listening)
def start(self) -> None:
up = self.__is_listening()
if up[0] and up[1]:
raise WeaviateStartUpError(
f"Embedded DB did not start because processes are already listening on ports http:{self.options.port} and grpc:{self.grpc_port}"
f"use weaviate.connect_to_local(port={self.options.port}, grpc_port={self.options.grpc_port}) to connect to the existing instance"
)
elif up[0] and not up[1]:
raise WeaviateStartUpError(
f"Embedded DB did not start because a process is already listening on port http:{self.options.port}"
"look for another free port for the HTTP connection to you embedded instance"
)
elif up[1] and not up[0]:
raise WeaviateStartUpError(
f"Embedded DB did not start because a process is already listening on port grpc:{self.grpc_port}"
"look for another free port for the gRPC connection to your embedded instance"
)
super().start()
| EmbeddedV4 |
python | pytorch__pytorch | torch/_inductor/mock_cache.py | {
"start": 4663,
"end": 8587
} | class ____(contextlib.AbstractContextManager):
@classmethod
def setUp(cls):
# If this test is using PatchCaches then disable all the caches by
# default, letting the tests turn them on explicitly. This is because
# tests using PatchCaches will often want to check stats explicitly.
cls._savedCacheState = {}
for name in _CACHE_CONFIG_EN:
if hasattr(config, name):
cls._savedCacheState[name] = getattr(config, name)
setattr(config, name, False)
@classmethod
def tearDown(cls):
# Restore cache defaults
for name in _CACHE_CONFIG_EN:
delattr(config, name)
if name in cls._savedCacheState:
setattr(config, name, cls._savedCacheState[name])
def __init__(self) -> None:
self._stack = contextlib.ExitStack()
def __enter__(self) -> Self:
global_stats.reset()
self._stack.__enter__()
ctx = patch(
"torch._inductor.runtime.autotune_cache.LocalAutotuneCache.backend_override_cls",
MockBackend.with_name("autotune_local"),
)
self._stack.enter_context(ctx)
ctx = patch(
"torch._inductor.remote_cache.RemoteAutotuneCache.backend_override_cls",
MockBackend.with_name("autotune_remote"),
)
self._stack.enter_context(ctx)
ctx = patch(
"torch._inductor.remote_cache.RemoteBundledAutotuneCache.backend_override_cls",
MockBackend.with_name("bundled_autotune"),
)
self._stack.enter_context(ctx)
ctx = patch(
"torch._inductor.remote_cache.RemoteFxGraphCache.backend_override_cls",
MockBackend.with_name("fx_graph"),
)
self._stack.enter_context(ctx)
ctx = patch(
"torch._inductor.remote_cache.RemoteAOTAutogradCache.backend_override_cls",
MockBackend.with_name("aot_autograd"),
)
self._stack.enter_context(ctx)
ctx = patch(
"torch._inductor.remote_cache.RemoteDynamoPGOCache.backend_override_cls",
MockBackend.with_name("dynamo_pgo"),
)
self._stack.enter_context(ctx)
if config.is_fbcode():
ctx = patch(
"torch._inductor.fb.remote_cache.FbRemoteAutotuneCache.backend_override_cls",
MockBackend.with_name("autotune_remote"),
)
self._stack.enter_context(ctx)
ctx = patch(
"torch._inductor.fb.remote_cache.FbRemoteBundledAutotuneCache.backend_override_cls",
MockBackend.with_name("bundled_autotune"),
)
self._stack.enter_context(ctx)
ctx = patch(
"torch._inductor.fb.remote_cache.FbRemoteFxGraphCache.backend_override_cls",
MockBackend.with_name("fx_graph"),
)
self._stack.enter_context(ctx)
ctx = patch(
"triton.fb.fb_memcache.FbMemcacheRemoteKernelCache.backend_override_cls",
MockBackend.with_name("triton"),
)
self._stack.enter_context(ctx)
ctx = patch(
"torch._inductor.fb.remote_cache.FbRemoteAOTAutogradCache.backend_override_cls",
MockBackend.with_name("aot_autograd"),
)
self._stack.enter_context(ctx)
ctx = patch(
"torch._inductor.fb.remote_cache.FbRemoteDynamoPGOCache.backend_override_cls",
MockBackend.with_name("dynamo_pgo"),
)
self._stack.enter_context(ctx)
return self
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> None:
self._stack.__exit__(exc_type, exc_value, traceback)
| PatchCaches |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/recurrent.py | {
"start": 102669,
"end": 107538
} | class ____(LSTMCell):
"""Equivalent to LSTMCell class but adds peephole connections.
Peephole connections allow the gates to utilize the previous internal state as
well as the previous hidden state (which is what LSTMCell is limited to).
This allows PeepholeLSTMCell to better learn precise timings over LSTMCell.
From [Gers et al., 2002](
http://www.jmlr.org/papers/volume3/gers02a/gers02a.pdf):
"We find that LSTM augmented by 'peephole connections' from its internal
cells to its multiplicative gates can learn the fine distinction between
sequences of spikes spaced either 50 or 49 time steps apart without the help
of any short training exemplars."
The peephole implementation is based on:
[Sak et al., 2014](https://research.google.com/pubs/archive/43905.pdf)
Example:
```python
# Create 2 PeepholeLSTMCells
peephole_lstm_cells = [PeepholeLSTMCell(size) for size in [128, 256]]
# Create a layer composed sequentially of the peephole LSTM cells.
layer = RNN(peephole_lstm_cells)
input = keras.Input((timesteps, input_dim))
output = layer(input)
```
"""
def __init__(self,
units,
activation='tanh',
recurrent_activation='hard_sigmoid',
use_bias=True,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros',
unit_forget_bias=True,
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
dropout=0.,
recurrent_dropout=0.,
**kwargs):
warnings.warn('`tf.keras.experimental.PeepholeLSTMCell` is deprecated '
'and will be removed in a future version. '
'Please use tensorflow_addons.rnn.PeepholeLSTMCell '
'instead.')
super(PeepholeLSTMCell, self).__init__(
units=units,
activation=activation,
recurrent_activation=recurrent_activation,
use_bias=use_bias,
kernel_initializer=kernel_initializer,
recurrent_initializer=recurrent_initializer,
bias_initializer=bias_initializer,
unit_forget_bias=unit_forget_bias,
kernel_regularizer=kernel_regularizer,
recurrent_regularizer=recurrent_regularizer,
bias_regularizer=bias_regularizer,
kernel_constraint=kernel_constraint,
recurrent_constraint=recurrent_constraint,
bias_constraint=bias_constraint,
dropout=dropout,
recurrent_dropout=recurrent_dropout,
implementation=kwargs.pop('implementation', 1),
**kwargs)
def build(self, input_shape):
super(PeepholeLSTMCell, self).build(input_shape)
# The following are the weight matrices for the peephole connections. These
# are multiplied with the previous internal state during the computation of
# carry and output.
self.input_gate_peephole_weights = self.add_weight(
shape=(self.units,),
name='input_gate_peephole_weights',
initializer=self.kernel_initializer)
self.forget_gate_peephole_weights = self.add_weight(
shape=(self.units,),
name='forget_gate_peephole_weights',
initializer=self.kernel_initializer)
self.output_gate_peephole_weights = self.add_weight(
shape=(self.units,),
name='output_gate_peephole_weights',
initializer=self.kernel_initializer)
def _compute_carry_and_output(self, x, h_tm1, c_tm1):
x_i, x_f, x_c, x_o = x
h_tm1_i, h_tm1_f, h_tm1_c, h_tm1_o = h_tm1
i = self.recurrent_activation(
x_i + backend.dot(h_tm1_i, self.recurrent_kernel[:, :self.units]) +
self.input_gate_peephole_weights * c_tm1)
f = self.recurrent_activation(x_f + backend.dot(
h_tm1_f, self.recurrent_kernel[:, self.units:self.units * 2]) +
self.forget_gate_peephole_weights * c_tm1)
c = f * c_tm1 + i * self.activation(x_c + backend.dot(
h_tm1_c, self.recurrent_kernel[:, self.units * 2:self.units * 3]))
o = self.recurrent_activation(
x_o + backend.dot(h_tm1_o, self.recurrent_kernel[:, self.units * 3:]) +
self.output_gate_peephole_weights * c)
return c, o
def _compute_carry_and_output_fused(self, z, c_tm1):
z0, z1, z2, z3 = z
i = self.recurrent_activation(z0 +
self.input_gate_peephole_weights * c_tm1)
f = self.recurrent_activation(z1 +
self.forget_gate_peephole_weights * c_tm1)
c = f * c_tm1 + i * self.activation(z2)
o = self.recurrent_activation(z3 + self.output_gate_peephole_weights * c)
return c, o
| PeepholeLSTMCell |
python | langchain-ai__langchain | libs/core/tests/unit_tests/runnables/test_runnable.py | {
"start": 6420,
"end": 6680
} | class ____(RunnableSerializable[str, int]):
hello: str = ""
@override
def invoke(
self,
input: str,
config: RunnableConfig | None = None,
**kwargs: Any,
) -> int:
return len(input)
| FakeRunnableSerializable |
python | matplotlib__matplotlib | lib/matplotlib/_type1font.py | {
"start": 2261,
"end": 2369
} | class ____(_Token):
kind = 'boolean'
def value(self):
return self.raw == 'true'
| _BooleanToken |
python | vyperlang__vyper | vyper/utils.py | {
"start": 11711,
"end": 19750
} | class ____:
MAX_INT128 = 2**127 - 1
MIN_INT128 = -(2**127)
MAX_INT256 = 2**255 - 1
MIN_INT256 = -(2**255)
MAXDECIMAL = 2**167 - 1 # maxdecimal as EVM value
MINDECIMAL = -(2**167) # mindecimal as EVM value
# min decimal allowed as Python value
MIN_AST_DECIMAL = -decimal.Decimal(2**167) / DECIMAL_DIVISOR
# max decimal allowed as Python value
MAX_AST_DECIMAL = decimal.Decimal(2**167 - 1) / DECIMAL_DIVISOR
MAX_UINT8 = 2**8 - 1
MAX_UINT256 = 2**256 - 1
CEILING_UINT256 = 2**256
def quantize(d: decimal.Decimal, places=MAX_DECIMAL_PLACES, rounding_mode=decimal.ROUND_DOWN):
quantizer = decimal.Decimal(f"{1:0.{places}f}")
return d.quantize(quantizer, rounding_mode)
# List of valid IR macros.
# TODO move this somewhere else, like ir_node.py
VALID_IR_MACROS = {
"assert",
"break",
"iload",
"istore",
"dload",
"dloadbytes",
"ceil32",
"continue",
"debugger",
"ge",
"if",
"select",
"le",
"deploy",
"ne",
"pass",
"repeat",
"seq",
"set",
"sge",
"sha3_32",
"sha3_64",
"sle",
"with",
"label",
"goto",
"djump", # "dynamic jump", i.e. constrained, multi-destination jump
"~extcode",
"~selfcode",
"~calldata",
"~empty",
"var_list",
}
EIP_170_LIMIT = 0x6000 # 24kb
EIP_3860_LIMIT = EIP_170_LIMIT * 2
ERC5202_PREFIX = b"\xFE\x71\x00" # default prefix from ERC-5202
assert EIP_3860_LIMIT == 49152 # directly from the EIP
SHA3_BASE = 30
SHA3_PER_WORD = 6
def indent(text: str, indent_chars: Union[str, List[str]] = " ", level: int = 1) -> str:
"""
Indent lines of text in the string ``text`` using the indentation
character(s) given in ``indent_chars`` ``level`` times.
:param text: A string containing the lines of text to be indented.
:param level: The number of times to indent lines in ``text``.
:param indent_chars: The characters to use for indentation. If a string,
uses repetitions of that string for indentation. If a list of strings,
uses repetitions of each string to indent each line.
:return: The indented text.
"""
text_lines = text.splitlines(keepends=True)
if isinstance(indent_chars, str):
indented_lines = [indent_chars * level + line for line in text_lines]
elif isinstance(indent_chars, list):
if len(indent_chars) != len(text_lines):
raise ValueError("Must provide indentation chars for each line")
indented_lines = [ind * level + line for ind, line in zip(indent_chars, text_lines)]
else:
raise ValueError("Unrecognized indentation characters value")
return "".join(indented_lines)
@contextlib.contextmanager
def timeit(msg): # pragma: nocover
start_time = time.perf_counter()
yield
end_time = time.perf_counter()
total_time = end_time - start_time
print(f"{msg}: Took {total_time:.6f} seconds", file=sys.stderr)
_CUMTIMES = None
def _dump_cumtime(): # pragma: nocover
global _CUMTIMES
for msg, total_time in _CUMTIMES.items():
print(f"{msg}: Cumulative time {total_time:.3f} seconds", file=sys.stderr)
@contextlib.contextmanager
def cumtimeit(msg): # pragma: nocover
import atexit
from collections import defaultdict
global _CUMTIMES
if _CUMTIMES is None:
warnings.warn("timing code, disable me before pushing!", stacklevel=2)
_CUMTIMES = defaultdict(int)
atexit.register(_dump_cumtime)
start_time = time.perf_counter()
yield
end_time = time.perf_counter()
total_time = end_time - start_time
_CUMTIMES[msg] += total_time
_PROF = None
def _dump_profile(): # pragma: nocover
global _PROF
_PROF.disable() # don't profile dumping stats
_PROF.dump_stats("stats")
from pstats import Stats
stats = Stats("stats", stream=sys.stderr)
stats.sort_stats("time")
stats.print_stats()
@contextlib.contextmanager
def profileit(): # pragma: nocover
"""
Helper function for local dev use, is not intended to ever be run in
production build
"""
import atexit
from cProfile import Profile
global _PROF
if _PROF is None:
warnings.warn("profiling code, disable me before pushing!", stacklevel=2)
_PROF = Profile()
_PROF.disable()
atexit.register(_dump_profile)
try:
_PROF.enable()
yield
finally:
_PROF.disable()
def annotate_source_code(
source_code: str,
lineno: int,
col_offset: int = None,
context_lines: int = 0,
line_numbers: bool = False,
) -> str:
"""
Annotate the location specified by ``lineno`` and ``col_offset`` in the
source code given by ``source_code`` with a location marker and optional
line numbers and context lines.
:param source_code: The source code containing the source location.
:param lineno: The 1-indexed line number of the source location.
:param col_offset: The 0-indexed column offset of the source location.
:param context_lines: The number of contextual lines to include above and
below the source location.
:param line_numbers: If true, line numbers are included in the location
representation.
:return: A string containing the annotated source code location.
"""
if lineno is None:
return ""
source_lines = source_code.splitlines(keepends=True)
if lineno < 1 or lineno > len(source_lines):
raise ValueError("Line number is out of range")
line_offset = lineno - 1
start_offset = max(0, line_offset - context_lines)
end_offset = min(len(source_lines), line_offset + context_lines + 1)
line_repr = source_lines[line_offset]
if "\n" not in line_repr[-2:]: # Handle certain edge cases
line_repr += "\n"
if col_offset is None:
mark_repr = ""
else:
mark_repr = "-" * col_offset + "^" + "\n"
before_lines = "".join(source_lines[start_offset:line_offset])
after_lines = "".join(source_lines[line_offset + 1 : end_offset])
location_repr = "".join((before_lines, line_repr, mark_repr, after_lines))
if line_numbers:
# Create line numbers
lineno_reprs = [f"{i} " for i in range(start_offset + 1, end_offset + 1)]
# Highlight line identified by `lineno`
local_line_off = line_offset - start_offset
lineno_reprs[local_line_off] = "---> " + lineno_reprs[local_line_off]
# Calculate width of widest line no
max_len = max(len(i) for i in lineno_reprs)
# Justify all line nos according to this width
justified_reprs = [i.rjust(max_len) for i in lineno_reprs]
if col_offset is not None:
justified_reprs.insert(local_line_off + 1, "-" * max_len)
location_repr = indent(location_repr, indent_chars=justified_reprs)
# Ensure no trailing whitespace and trailing blank lines are only included
# if they are part of the source code
if col_offset is None:
# Number of lines doesn't include column marker line
num_lines = end_offset - start_offset
else:
num_lines = end_offset - start_offset + 1
cleanup_lines = [line.rstrip() for line in location_repr.splitlines()]
cleanup_lines += [""] * (num_lines - len(cleanup_lines))
return "\n".join(cleanup_lines)
def safe_relpath(path):
try:
return os.path.relpath(path)
except ValueError:
# on Windows, if path and curdir are on different drives, an exception
# can be thrown
return path
def all2(iterator):
"""
This function checks if all elements in the given `iterable` are truthy,
similar to Python's built-in `all()` function. However, `all2` differs
in the case where there are no elements in the iterable. `all()` returns
`True` for the empty iterable, but `all2()` returns False.
"""
try:
s = next(iterator)
except StopIteration:
return False
return bool(s) and all(iterator)
| SizeLimits |
python | marshmallow-code__marshmallow | tests/test_error_store.py | {
"start": 243,
"end": 5211
} | class ____:
def test_merging_none_and_string(self):
assert merge_errors(None, "error1") == "error1"
def test_merging_none_and_custom_error(self):
assert CustomError(123, "error1") == merge_errors(
None, CustomError(123, "error1")
)
def test_merging_none_and_list(self):
assert merge_errors(None, ["error1", "error2"]) == ["error1", "error2"]
def test_merging_none_and_dict(self):
assert merge_errors(None, {"field1": "error1"}) == {"field1": "error1"}
def test_merging_string_and_none(self):
assert merge_errors("error1", None) == "error1"
def test_merging_custom_error_and_none(self):
assert CustomError(123, "error1") == merge_errors(
CustomError(123, "error1"), None
)
def test_merging_list_and_none(self):
assert merge_errors(["error1", "error2"], None) == ["error1", "error2"]
def test_merging_dict_and_none(self):
assert merge_errors({"field1": "error1"}, None) == {"field1": "error1"}
def test_merging_string_and_string(self):
assert merge_errors("error1", "error2") == ["error1", "error2"]
def test_merging_custom_error_and_string(self):
assert [CustomError(123, "error1"), "error2"] == merge_errors(
CustomError(123, "error1"), "error2"
)
def test_merging_string_and_custom_error(self):
assert ["error1", CustomError(123, "error2")] == merge_errors(
"error1", CustomError(123, "error2")
)
def test_merging_custom_error_and_custom_error(self):
assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors(
CustomError(123, "error1"), CustomError(456, "error2")
)
def test_merging_string_and_list(self):
assert merge_errors("error1", ["error2"]) == ["error1", "error2"]
def test_merging_string_and_dict(self):
assert merge_errors("error1", {"field1": "error2"}) == {
"_schema": "error1",
"field1": "error2",
}
def test_merging_string_and_dict_with_schema_error(self):
assert merge_errors("error1", {"_schema": "error2", "field1": "error3"}) == {
"_schema": ["error1", "error2"],
"field1": "error3",
}
def test_merging_custom_error_and_list(self):
assert [CustomError(123, "error1"), "error2"] == merge_errors(
CustomError(123, "error1"), ["error2"]
)
def test_merging_custom_error_and_dict(self):
assert {
"_schema": CustomError(123, "error1"),
"field1": "error2",
} == merge_errors(CustomError(123, "error1"), {"field1": "error2"})
def test_merging_custom_error_and_dict_with_schema_error(self):
assert {
"_schema": [CustomError(123, "error1"), "error2"],
"field1": "error3",
} == merge_errors(
CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"}
)
def test_merging_list_and_string(self):
assert merge_errors(["error1"], "error2") == ["error1", "error2"]
def test_merging_list_and_custom_error(self):
assert ["error1", CustomError(123, "error2")] == merge_errors(
["error1"], CustomError(123, "error2")
)
def test_merging_list_and_list(self):
assert merge_errors(["error1"], ["error2"]) == ["error1", "error2"]
def test_merging_list_and_dict(self):
assert merge_errors(["error1"], {"field1": "error2"}) == {
"_schema": ["error1"],
"field1": "error2",
}
def test_merging_list_and_dict_with_schema_error(self):
assert merge_errors(["error1"], {"_schema": "error2", "field1": "error3"}) == {
"_schema": ["error1", "error2"],
"field1": "error3",
}
def test_merging_dict_and_string(self):
assert merge_errors({"field1": "error1"}, "error2") == {
"_schema": "error2",
"field1": "error1",
}
def test_merging_dict_and_custom_error(self):
assert {
"_schema": CustomError(123, "error2"),
"field1": "error1",
} == merge_errors({"field1": "error1"}, CustomError(123, "error2"))
def test_merging_dict_and_list(self):
assert merge_errors({"field1": "error1"}, ["error2"]) == {
"_schema": ["error2"],
"field1": "error1",
}
def test_merging_dict_and_dict(self):
assert merge_errors(
{"field1": "error1", "field2": "error2"},
{"field2": "error3", "field3": "error4"},
) == {
"field1": "error1",
"field2": ["error2", "error3"],
"field3": "error4",
}
def test_deep_merging_dicts(self):
assert merge_errors(
{"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}}
) == {"field1": {"field2": ["error1", "error2"]}}
| TestMergeErrors |
python | sqlalchemy__sqlalchemy | test/base/test_except.py | {
"start": 848,
"end": 13768
} | class ____(fixtures.TestBase):
def test_version_token(self):
assert sa_exceptions._version_token in (
"13",
"14",
"15",
"16",
"20",
"21",
"22",
)
def _translating_dialect_fixture(self):
d = default.DefaultDialect()
d.dbapi_exception_translation_map = {
"WrongNameError": "IntegrityError"
}
return d
def test_db_error_normal(self):
try:
raise sa_exceptions.DBAPIError.instance(
"", [], OperationalError(), DatabaseError
)
except sa_exceptions.DBAPIError:
self.assert_(True)
def test_tostring(self):
try:
raise sa_exceptions.DBAPIError.instance(
"this is a message", None, OperationalError(), DatabaseError
)
except sa_exceptions.DBAPIError as exc:
eq_(
str(exc),
"(test.base.test_except.OperationalError) \n"
"[SQL: this is a message]\n"
"(Background on this error at: https://sqlalche.me/e/%s/e3q8)"
% sa_exceptions._version_token,
)
def test_tostring_with_newlines(self):
try:
raise sa_exceptions.DBAPIError.instance(
"this is a message\nthis is the next line\nthe last line",
None,
OperationalError(),
DatabaseError,
)
except sa_exceptions.DBAPIError as exc:
eq_(
str(exc),
"(test.base.test_except.OperationalError) \n"
"[SQL: this is a message\nthis is the next line\n"
"the last line]\n"
"(Background on this error at: https://sqlalche.me/e/%s/e3q8)"
% sa_exceptions._version_token,
)
def test_statement_error_no_code(self):
try:
raise sa_exceptions.DBAPIError.instance(
"select * from table",
[{"x": 1}],
sa_exceptions.InvalidRequestError("hello"),
DatabaseError,
)
except sa_exceptions.StatementError as err:
eq_(
str(err),
"(sqlalchemy.exc.InvalidRequestError) hello\n"
"[SQL: select * from table]\n[parameters: [{'x': 1}]]",
)
eq_(err.args, ("(sqlalchemy.exc.InvalidRequestError) hello",))
def test_statement_error_w_code(self):
try:
raise sa_exceptions.DBAPIError.instance(
"select * from table",
[{"x": 1}],
sa_exceptions.InvalidRequestError("hello", code="abcd"),
DatabaseError,
)
except sa_exceptions.StatementError as err:
eq_(
str(err),
"(sqlalchemy.exc.InvalidRequestError) hello\n"
"[SQL: select * from table]\n"
"[parameters: [{'x': 1}]]\n"
"(Background on this error at: https://sqlalche.me/e/%s/abcd)"
% sa_exceptions._version_token,
)
eq_(err.args, ("(sqlalchemy.exc.InvalidRequestError) hello",))
def test_wrap_multi_arg(self):
# this is not supported by the API but oslo_db is doing it
orig = sa_exceptions.DBAPIError(False, False, False)
orig.args = [2006, "Test raise operational error"]
eq_(
str(orig),
"(2006, 'Test raise operational error')\n"
"(Background on this error at: https://sqlalche.me/e/%s/dbapi)"
% sa_exceptions._version_token,
)
def test_wrap_unicode_arg(self):
# this is not supported by the API but oslo_db is doing it
orig = sa_exceptions.DBAPIError(False, False, False)
orig.args = ["méil"]
eq_(
str(orig),
"méil\n(Background on this error at: "
"https://sqlalche.me/e/%s/dbapi)" % sa_exceptions._version_token,
)
eq_(orig.args, ("méil",))
def test_tostring_large_dict(self):
try:
raise sa_exceptions.DBAPIError.instance(
"this is a message",
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
"g": 7,
"h": 8,
"i": 9,
"j": 10,
"k": 11,
},
OperationalError(),
DatabaseError,
)
except sa_exceptions.DBAPIError as exc:
assert str(exc).startswith(
"(test.base.test_except.OperationalError) \n"
"[SQL: this is a message]\n"
"[parameters: {"
)
def test_tostring_large_list(self):
try:
raise sa_exceptions.DBAPIError.instance(
"this is a message",
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
OperationalError(),
DatabaseError,
)
except sa_exceptions.DBAPIError as ex:
assert str(ex).startswith(
"(test.base.test_except.OperationalError) \n"
"[SQL: this is a message]\n[parameters: "
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]"
)
def test_tostring_large_executemany(self):
try:
raise sa_exceptions.DBAPIError.instance(
"this is a message",
[
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
],
OperationalError("sql error"),
DatabaseError,
)
except sa_exceptions.DBAPIError as exc:
eq_(
str(exc),
"(test.base.test_except.OperationalError) sql error\n"
"[SQL: this is a message]\n"
"[parameters: [{1: 1}, {1: 1}, {1: 1}, {1: 1}, {1: 1},"
" {1: 1}, {1: 1}, {1: 1}, {1: 1}, {1: 1}]]\n"
"(Background on this error at: https://sqlalche.me/e/%s/e3q8)"
% sa_exceptions._version_token,
)
eq_(
exc.args,
("(test.base.test_except.OperationalError) sql error",),
)
try:
raise sa_exceptions.DBAPIError.instance(
"this is a message",
[
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
{1: 1},
],
OperationalError(),
DatabaseError,
ismulti=True,
)
except sa_exceptions.DBAPIError as exc:
eq_(
str(exc),
"(test.base.test_except.OperationalError) \n"
"[SQL: this is a message]\n"
"[parameters: [{1: 1}, "
"{1: 1}, {1: 1}, {1: 1}, {1: 1}, {1: 1}, "
"{1: 1}, {1: 1} ... displaying 10 of 11 total "
"bound parameter sets ... {1: 1}, {1: 1}]]\n"
"(Background on this error at: https://sqlalche.me/e/%s/e3q8)"
% sa_exceptions._version_token,
)
try:
raise sa_exceptions.DBAPIError.instance(
"this is a message",
[(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)],
OperationalError(),
DatabaseError,
)
except sa_exceptions.DBAPIError as exc:
eq_(
str(exc),
"(test.base.test_except.OperationalError) \n"
"[SQL: this is a message]\n"
"[parameters: [(1,), "
"(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)]]\n"
"(Background on this error at: https://sqlalche.me/e/%s/e3q8)"
% sa_exceptions._version_token,
)
try:
raise sa_exceptions.DBAPIError.instance(
"this is a message",
[
(1,),
(1,),
(1,),
(1,),
(1,),
(1,),
(1,),
(1,),
(1,),
(1,),
(1,),
],
OperationalError(),
DatabaseError,
ismulti=True,
)
except sa_exceptions.DBAPIError as exc:
eq_(
str(exc),
"(test.base.test_except.OperationalError) \n"
"[SQL: this is a message]\n"
"[parameters: [(1,), "
"(1,), (1,), (1,), (1,), (1,), (1,), (1,) "
"... displaying 10 of 11 total bound "
"parameter sets ... (1,), (1,)]]\n"
"(Background on this error at: https://sqlalche.me/e/%s/e3q8)"
% sa_exceptions._version_token,
)
def test_db_error_busted_dbapi(self):
try:
raise sa_exceptions.DBAPIError.instance(
"", [], ProgrammingError(), DatabaseError
)
except sa_exceptions.DBAPIError as e:
self.assert_(True)
self.assert_("Error in str() of DB-API" in e.args[0])
def test_db_error_noncompliant_dbapi(self):
try:
raise sa_exceptions.DBAPIError.instance(
"", [], OutOfSpec(), DatabaseError
)
except sa_exceptions.DBAPIError as e:
# OutOfSpec subclasses DatabaseError
self.assert_(e.__class__ is sa_exceptions.DatabaseError)
except OutOfSpec:
self.assert_(False)
try:
raise sa_exceptions.DBAPIError.instance(
"", [], sa_exceptions.ArgumentError(), DatabaseError
)
except sa_exceptions.DBAPIError as e:
self.assert_(e.__class__ is sa_exceptions.DBAPIError)
except sa_exceptions.ArgumentError:
self.assert_(False)
dialect = self._translating_dialect_fixture()
try:
raise sa_exceptions.DBAPIError.instance(
"",
[],
sa_exceptions.ArgumentError(),
DatabaseError,
dialect=dialect,
)
except sa_exceptions.DBAPIError as e:
self.assert_(e.__class__ is sa_exceptions.DBAPIError)
except sa_exceptions.ArgumentError:
self.assert_(False)
def test_db_error_dbapi_uses_wrong_names(self):
dialect = self._translating_dialect_fixture()
try:
raise sa_exceptions.DBAPIError.instance(
"", [], IntegrityError(), DatabaseError, dialect=dialect
)
except sa_exceptions.DBAPIError as e:
self.assert_(e.__class__ is sa_exceptions.IntegrityError)
try:
raise sa_exceptions.DBAPIError.instance(
"",
[],
SpecificIntegrityError(),
DatabaseError,
dialect=dialect,
)
except sa_exceptions.DBAPIError as e:
self.assert_(e.__class__ is sa_exceptions.IntegrityError)
try:
raise sa_exceptions.DBAPIError.instance(
"", [], SpecificIntegrityError(), DatabaseError
)
except sa_exceptions.DBAPIError as e:
# doesn't work without a dialect
self.assert_(e.__class__ is not sa_exceptions.IntegrityError)
def test_db_error_keyboard_interrupt(self):
try:
raise sa_exceptions.DBAPIError.instance(
"", [], KeyboardInterrupt(), DatabaseError
)
except sa_exceptions.DBAPIError:
self.assert_(False)
except KeyboardInterrupt:
self.assert_(True)
def test_db_error_system_exit(self):
try:
raise sa_exceptions.DBAPIError.instance(
"", [], SystemExit(), DatabaseError
)
except sa_exceptions.DBAPIError:
self.assert_(False)
except SystemExit:
self.assert_(True)
def details(cls):
inst = cls("msg", "stmt", (), "orig")
inst.add_detail("d1")
inst.add_detail("d2")
return inst
| WrapTest |
python | google__jax | jax/_src/api_util.py | {
"start": 26920,
"end": 28730
} | class ____:
__slots__ = ['val']
def __init__(self, val):
self.val = val
def __hash__(self):
return id(self.val)
def __eq__(self, other):
return self.val is other.val
# TODO(mattjj): make this function faster
def check_no_aliased_ref_args(dbg_fn: Callable[[], core.DebugInfo],
maybe_avals, args) -> None:
assert config.mutable_array_checks.value
refs: dict[int, int] = {}
for i, (a, x) in enumerate(zip(maybe_avals, args)):
if (isinstance(a, AbstractRef) and
(dup_idx := refs.setdefault(id(core.get_referent(x)), i)) != i):
dbg = dbg_fn()
raise ValueError(
"only one reference to a mutable array may be passed as an argument "
f"to a function, but when tracing {dbg.func_src_info} for {dbg.traced_for} "
f"the mutable array reference of type {a.str_short()} appeared at both "
f"{dbg.arg_names[dup_idx] if dbg.arg_names is not None else 'unknown'} "
f"and {dbg.arg_names[i] if dbg.arg_names is not None else 'unknown'}."
if dbg else
f"at both flat index {dup_idx} and flat index {i}") from None
def _check_no_aliased_closed_over_refs(dbg: core.DebugInfo, consts, args) -> None:
assert config.mutable_array_checks.value
refs: set[int] = {id(core.get_referent(c)) for c in consts
if isinstance(core.get_aval(c), AbstractRef)}
for i, x in enumerate(args):
if id(core.get_referent(x)) in refs:
a = core.shaped_abstractify(x)
raise ValueError(
f"when tracing {dbg.func_src_info} for {dbg.traced_for}, a mutable "
f"array reference of type {a.str_short()} was both closed over and "
f"passed as the argument "
f"{dbg.safe_arg_names(len(args))[i]}" if dbg else "at flat index {i}")
| _HashableByObjectId |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/sql_dataset_test.py | {
"start": 4513,
"end": 28130
} | class ____(SqlDatasetTestBase, parameterized.TestCase):
# Test that SqlDataset can read from a database table.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSet(self):
for _ in range(2): # Run twice to verify statelessness of db operations.
dataset = self._createSqlDataset(
query="SELECT first_name, last_name, motto FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.string, dtypes.string),
num_repeats=2)
self.assertDatasetProduces(
dataset,
expected_output=[(b"John", b"Doe", b"Hi!"),
(b"Jane", b"Moe", b"Hi again!")] * 2,
num_test_iterations=2)
# Test that SqlDataset works on a join query.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetJoinQuery(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT students.first_name, state, motto FROM students "
"INNER JOIN people "
"ON students.first_name = people.first_name "
"AND students.last_name = people.last_name",
output_types=(dtypes.string, dtypes.string, dtypes.string)))
self.assertEqual((b"John", b"California", b"Hi!"),
self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that SqlDataset can read a database entry with a null-terminator
# in the middle of the text and place the entry in a `string` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetNullTerminator(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, last_name, favorite_nonsense_word "
"FROM students ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.string, dtypes.string)))
self.assertEqual((b"John", b"Doe", b"n\0nsense"), self.evaluate(get_next()))
self.assertEqual((b"Jane", b"Moe", b"nonsense\0"),
self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that SqlDataset works when used on two different queries.
# Because the output types of the dataset must be determined at graph-creation
# time, the two queries must have the same number and types of columns.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetReuseSqlDataset(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, last_name, motto FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.string, dtypes.string)))
self.assertEqual((b"John", b"Doe", b"Hi!"), self.evaluate(get_next()))
self.assertEqual((b"Jane", b"Moe", b"Hi again!"), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, last_name, state FROM people "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.string, dtypes.string)))
self.assertEqual((b"John", b"Doe", b"California"),
self.evaluate(get_next()))
self.assertEqual((b"Benjamin", b"Franklin", b"Pennsylvania"),
self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that an `OutOfRangeError` is raised on the first call to
# `get_next_str_only` if result set is empty.
@combinations.generate(test_base.default_test_combinations())
def testReadEmptyResultSet(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, last_name, motto FROM students "
"WHERE first_name = 'Nonexistent'",
output_types=(dtypes.string, dtypes.string, dtypes.string)))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that an error is raised when `driver_name` is invalid.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetWithInvalidDriverName(self):
with self.assertRaises(errors.InvalidArgumentError):
dataset = self._createSqlDataset(
driver_name="sqlfake",
query="SELECT first_name, last_name, motto FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.string, dtypes.string))
self.assertDatasetProduces(dataset, expected_output=[])
# Test that an error is raised when a column name in `query` is nonexistent
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetWithInvalidColumnName(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, last_name, fake_column FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.string, dtypes.string)))
with self.assertRaises(errors.UnknownError):
self.evaluate(get_next())
# Test that an error is raised when there is a syntax error in `query`.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetOfQueryWithSyntaxError(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELEmispellECT first_name, last_name, motto FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.string, dtypes.string)))
with self.assertRaises(errors.UnknownError):
self.evaluate(get_next())
# Test that an error is raised when the number of columns in `query`
# does not match the length of `, output_types`.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetWithMismatchBetweenColumnsAndOutputTypes(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, last_name FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.string, dtypes.string)))
with self.assertRaises(errors.InvalidArgumentError):
self.evaluate(get_next())
# Test that no results are returned when `query` is an insert query rather
# than a select query. In particular, the error refers to the number of
# output types passed to the op not matching the number of columns in the
# result set of the query (namely, 0 for an insert statement.)
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetOfInsertQuery(self):
get_next = self.getNext(
self._createSqlDataset(
query="INSERT INTO students (first_name, last_name, motto) "
"VALUES ('Foo', 'Bar', 'Baz'), ('Fizz', 'Buzz', 'Fizzbuzz')",
output_types=(dtypes.string, dtypes.string, dtypes.string)))
with self.assertRaises(errors.InvalidArgumentError):
self.evaluate(get_next())
# Test that `SqlDataset` can read an integer from a SQLite database table and
# place it in an `int8` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt8(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, desk_number FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int8)))
self.assertEqual((b"John", 9), self.evaluate(get_next()))
self.assertEqual((b"Jane", 127), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a negative or 0-valued integer from a
# SQLite database table and place it in an `int8` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt8NegativeAndZero(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, income, favorite_negative_number "
"FROM students "
"WHERE first_name = 'John' ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int8, dtypes.int8)))
self.assertEqual((b"John", 0, -2), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a large (positive or negative) integer from
# a SQLite database table and place it in an `int8` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt8MaxValues(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT desk_number, favorite_negative_number FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.int8, dtypes.int8)))
self.assertEqual((9, -2), self.evaluate(get_next()))
# Max and min values of int8
self.assertEqual((127, -128), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read an integer from a SQLite database table and
# place it in an `int16` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt16(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, desk_number FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int16)))
self.assertEqual((b"John", 9), self.evaluate(get_next()))
self.assertEqual((b"Jane", 127), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a negative or 0-valued integer from a
# SQLite database table and place it in an `int16` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt16NegativeAndZero(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, income, favorite_negative_number "
"FROM students "
"WHERE first_name = 'John' ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int16, dtypes.int16)))
self.assertEqual((b"John", 0, -2), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a large (positive or negative) integer from
# a SQLite database table and place it in an `int16` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt16MaxValues(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, favorite_medium_sized_number "
"FROM students ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int16)))
# Max value of int16
self.assertEqual((b"John", 32767), self.evaluate(get_next()))
# Min value of int16
self.assertEqual((b"Jane", -32768), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read an integer from a SQLite database table and
# place it in an `int32` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt32(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, desk_number FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int32)))
self.assertEqual((b"John", 9), self.evaluate(get_next()))
self.assertEqual((b"Jane", 127), self.evaluate(get_next()))
# Test that `SqlDataset` can read a negative or 0-valued integer from a
# SQLite database table and place it in an `int32` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt32NegativeAndZero(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, income FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int32)))
self.assertEqual((b"John", 0), self.evaluate(get_next()))
self.assertEqual((b"Jane", -20000), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a large (positive or negative) integer from
# a SQLite database table and place it in an `int32` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt32MaxValues(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, favorite_number FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int32)))
# Max value of int32
self.assertEqual((b"John", 2147483647), self.evaluate(get_next()))
# Min value of int32
self.assertEqual((b"Jane", -2147483648), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a numeric `varchar` from a SQLite database
# table and place it in an `int32` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt32VarCharColumnAsInt(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, school_id FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int32)))
self.assertEqual((b"John", 123), self.evaluate(get_next()))
self.assertEqual((b"Jane", 1000), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read an integer from a SQLite database table
# and place it in an `int64` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt64(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, desk_number FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int64)))
self.assertEqual((b"John", 9), self.evaluate(get_next()))
self.assertEqual((b"Jane", 127), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a negative or 0-valued integer from a
# SQLite database table and place it in an `int64` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt64NegativeAndZero(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, income FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int64)))
self.assertEqual((b"John", 0), self.evaluate(get_next()))
self.assertEqual((b"Jane", -20000), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a large (positive or negative) integer from
# a SQLite database table and place it in an `int64` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetInt64MaxValues(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, favorite_big_number FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.int64)))
# Max value of int64
self.assertEqual((b"John", 9223372036854775807), self.evaluate(get_next()))
# Min value of int64
self.assertEqual((b"Jane", -9223372036854775808), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read an integer from a SQLite database table and
# place it in a `uint8` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetUInt8(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, desk_number FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.uint8)))
self.assertEqual((b"John", 9), self.evaluate(get_next()))
self.assertEqual((b"Jane", 127), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read the minimum and maximum uint8 values from a
# SQLite database table and place them in `uint8` tensors.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetUInt8MinAndMaxValues(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, brownie_points FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.uint8)))
# Min value of uint8
self.assertEqual((b"John", 0), self.evaluate(get_next()))
# Max value of uint8
self.assertEqual((b"Jane", 255), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read an integer from a SQLite database table
# and place it in a `uint16` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetUInt16(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, desk_number FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.uint16)))
self.assertEqual((b"John", 9), self.evaluate(get_next()))
self.assertEqual((b"Jane", 127), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read the minimum and maximum uint16 values from a
# SQLite database table and place them in `uint16` tensors.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetUInt16MinAndMaxValues(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, account_balance FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.uint16)))
# Min value of uint16
self.assertEqual((b"John", 0), self.evaluate(get_next()))
# Max value of uint16
self.assertEqual((b"Jane", 65535), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a 0-valued and 1-valued integer from a
# SQLite database table and place them as `True` and `False` respectively
# in `bool` tensors.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetBool(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, registration_complete FROM students "
"ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.bool)))
self.assertEqual((b"John", True), self.evaluate(get_next()))
self.assertEqual((b"Jane", False), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read an integer that is not 0-valued or 1-valued
# from a SQLite database table and place it as `True` in a `bool` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetBoolNotZeroOrOne(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, favorite_medium_sized_number "
"FROM students ORDER BY first_name DESC",
output_types=(dtypes.string, dtypes.bool)))
self.assertEqual((b"John", True), self.evaluate(get_next()))
self.assertEqual((b"Jane", True), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a float from a SQLite database table
# and place it in a `float64` tensor.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetFloat64(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, last_name, victories FROM townspeople "
"ORDER BY first_name",
output_types=(dtypes.string, dtypes.string, dtypes.float64)))
self.assertEqual((b"George", b"Washington", 20.0),
self.evaluate(get_next()))
self.assertEqual((b"John", b"Adams", -19.95), self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a float from a SQLite database table beyond
# the precision of 64-bit IEEE, without throwing an error. Test that
# `SqlDataset` identifies such a value as equal to itself.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetFloat64OverlyPrecise(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, last_name, accolades FROM townspeople "
"ORDER BY first_name",
output_types=(dtypes.string, dtypes.string, dtypes.float64)))
self.assertEqual(
(b"George", b"Washington",
1331241.321342132321324589798264627463827647382647382643874),
self.evaluate(get_next()))
self.assertEqual(
(b"John", b"Adams",
1331241321342132321324589798264627463827647382647382643874.0),
self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that `SqlDataset` can read a float from a SQLite database table,
# representing the largest integer representable as a 64-bit IEEE float
# such that the previous integer is also representable as a 64-bit IEEE float.
# Test that `SqlDataset` can distinguish these two numbers.
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetFloat64LargestConsecutiveWholeNumbersNotEqual(self):
get_next = self.getNext(
self._createSqlDataset(
query="SELECT first_name, last_name, triumphs FROM townspeople "
"ORDER BY first_name",
output_types=(dtypes.string, dtypes.string, dtypes.float64)))
self.assertNotEqual((b"George", b"Washington", 9007199254740992.0),
self.evaluate(get_next()))
self.assertNotEqual((b"John", b"Adams", 9007199254740991.0),
self.evaluate(get_next()))
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
# Test that SqlDataset can stop correctly when combined with batch
@combinations.generate(test_base.default_test_combinations())
def testReadResultSetWithBatchStop(self):
dataset = self._createSqlDataset(
query="SELECT * FROM data", output_types=(dtypes.int32))
dataset = dataset.map(lambda x: array_ops.identity(x))
get_next = self.getNext(dataset.batch(2))
self.assertAllEqual(self.evaluate(get_next()), [0, 1])
self.assertAllEqual(self.evaluate(get_next()), [2])
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(get_next())
| SqlDatasetTest |
python | lazyprogrammer__machine_learning_examples | recommenders/rbm_tf_k.py | {
"start": 2251,
"end": 8528
} | class ____(object):
def __init__(self, D, M, K):
self.D = D # input feature size
self.M = M # hidden size
self.K = K # number of ratings
self.build(D, M, K)
def build(self, D, M, K):
# params
self.W = tf.Variable(tf.random.normal(shape=(D, K, M)) * np.sqrt(2.0 / M))
self.c = tf.Variable(np.zeros(M).astype(np.float32))
self.b = tf.Variable(np.zeros((D, K)).astype(np.float32))
# data
self.X_in = tf.compat.v1.placeholder(tf.float32, shape=(None, D, K))
self.mask = tf.compat.v1.placeholder(tf.float32, shape=(None, D, K))
# conditional probabilities
# NOTE: tf.contrib.distributions.Bernoulli API has changed in Tensorflow v1.2
V = self.X_in
p_h_given_v = tf.nn.sigmoid(dot1(V, self.W) + self.c)
self.p_h_given_v = p_h_given_v # save for later
# draw a sample from p(h | v)
r = tf.random.uniform(shape=tf.shape(input=p_h_given_v))
H = tf.cast(r < p_h_given_v, dtype=tf.float32)
# draw a sample from p(v | h)
# note: we don't have to actually do the softmax
logits = dot2(H, self.W) + self.b
cdist = tf.compat.v1.distributions.Categorical(logits=logits)
X_sample = cdist.sample() # shape is (N, D)
X_sample = tf.one_hot(X_sample, depth=K) # turn it into (N, D, K)
X_sample = X_sample * self.mask # missing ratings shouldn't contribute to objective
# build the objective
objective = tf.reduce_mean(input_tensor=self.free_energy(self.X_in)) - tf.reduce_mean(input_tensor=self.free_energy(X_sample))
self.train_op = tf.compat.v1.train.AdamOptimizer(1e-2).minimize(objective)
# self.train_op = tf.train.GradientDescentOptimizer(1e-3).minimize(objective)
# build the cost
# we won't use this to optimize the model parameters
# just to observe what happens during training
logits = self.forward_logits(self.X_in)
self.cost = tf.reduce_mean(
input_tensor=tf.nn.softmax_cross_entropy_with_logits(
labels=tf.stop_gradient(self.X_in),
logits=logits,
)
)
# to get the output
self.output_visible = self.forward_output(self.X_in)
initop = tf.compat.v1.global_variables_initializer()
self.session = tf.compat.v1.Session()
self.session.run(initop)
def fit(self, X, mask, X_test, mask_test, epochs=10, batch_sz=256, show_fig=True):
N, D = X.shape
n_batches = N // batch_sz
costs = []
test_costs = []
for i in range(epochs):
t0 = datetime.now()
print("epoch:", i)
X, mask, X_test, mask_test = shuffle(X, mask, X_test, mask_test) # everything has to be shuffled accordingly
for j in range(n_batches):
x = X[j*batch_sz:(j*batch_sz + batch_sz)].toarray()
m = mask[j*batch_sz:(j*batch_sz + batch_sz)].toarray()
# both visible units and mask have to be in one-hot form
# N x D --> N x D x K
batch_one_hot = one_hot_encode(x, self.K)
m = one_hot_mask(m, self.K)
_, c = self.session.run(
(self.train_op, self.cost),
feed_dict={self.X_in: batch_one_hot, self.mask: m}
)
if j % 100 == 0:
print("j / n_batches:", j, "/", n_batches, "cost:", c)
print("duration:", datetime.now() - t0)
# calculate the true train and test cost
t0 = datetime.now()
sse = 0
test_sse = 0
n = 0
test_n = 0
for j in range(n_batches):
x = X[j*batch_sz:(j*batch_sz + batch_sz)].toarray()
m = mask[j*batch_sz:(j*batch_sz + batch_sz)].toarray()
# only visible input has to be in one-hot form
xoh = one_hot_encode(x, self.K)
probs = self.get_visible(xoh)
xhat = convert_probs_to_ratings(probs)
sse += (m * (xhat - x)*(xhat - x)).sum()
n += m.sum()
# the test PREDICTIONS come from the train data!
# X_test and mask_test are only used for targets
xt = X_test[j*batch_sz:(j*batch_sz + batch_sz)].toarray()
mt = mask_test[j*batch_sz:(j*batch_sz + batch_sz)].toarray()
test_sse += (mt * (xhat - xt) * (xhat - xt)).sum()
test_n += mt.sum()
c = sse/n
ct = test_sse/test_n
print("train mse:", c)
print("test mse:", ct)
print("calculate cost duration:", datetime.now() - t0)
costs.append(c)
test_costs.append(ct)
if show_fig:
plt.plot(costs, label='train mse')
plt.plot(test_costs, label='test mse')
plt.legend()
plt.show()
def free_energy(self, V):
first_term = -tf.reduce_sum(input_tensor=dot1(V, self.b))
second_term = -tf.reduce_sum(
# tf.log(1 + tf.exp(tf.matmul(V, self.W) + self.c)),
input_tensor=tf.nn.softplus(dot1(V, self.W) + self.c),
axis=1
)
return first_term + second_term
def forward_hidden(self, X):
return tf.nn.sigmoid(dot1(X, self.W) + self.c)
def forward_logits(self, X):
Z = self.forward_hidden(X)
return dot2(Z, self.W) + self.b
def forward_output(self, X):
return tf.nn.softmax(self.forward_logits(X))
def transform(self, X):
# accepts and returns a real numpy array
# unlike forward_hidden and forward_output
# which deal with tensorflow variables
return self.session.run(self.p_h_given_v, feed_dict={self.X_in: X})
def get_visible(self, X):
return self.session.run(self.output_visible, feed_dict={self.X_in: X})
def main():
A = load_npz("Atrain.npz")
A_test = load_npz("Atest.npz")
mask = (A > 0) * 1.0
mask_test = (A_test > 0) * 1.0
N, M = A.shape
rbm = RBM(M, 50, 10)
rbm.fit(A, mask, A_test, mask_test)
if __name__ == '__main__':
main()
| RBM |
python | allegroai__clearml | clearml/backend_api/services/v2_23/frames.py | {
"start": 133918,
"end": 149790
} | class ____(Response):
"""
Response of frames.get_by_ids endpoint.
:param frames: Frames data
:type frames: Sequence[Frame]
"""
_service = "frames"
_action = "get_by_ids"
_version = "2.23"
_schema = {
"definitions": {
"augmentation": {
"properties": {
"arguments": {
"additionalProperties": True,
"description": "Arguments dictionary, passed to custom augmentations.",
"type": ["object", "null"],
},
"cls": {
"description": "Augmentation class (see global definitions)",
"type": ["string", "null"],
},
"params": {
"description": (
"Transform parameters, an array ot 3 randomly generated values. Fixed values are passed in"
" case of affine reflect augmentation."
),
"items": {"type": "number"},
"type": ["array", "null"],
},
"strength": {
"description": "Transform strength. Required for pixel transforms.",
"type": ["number", "null"],
},
"trans_mat": {
"description": "Transform matrix (list of lists). Required for affine transforms.",
"items": {"items": {"type": "number"}, "type": "array"},
"type": ["array", "null"],
},
"type": {
"description": "Augmentation type (see global definitions)",
"type": ["string", "null"],
},
},
"type": "object",
},
"dataset_version": {
"properties": {
"id": {"description": "Dataset id", "type": ["string", "null"]},
"version": {
"description": "Dataset version id",
"type": ["string", "null"],
},
},
"type": "object",
},
"frame": {
"properties": {
"augmentation": {
"description": "List of augmentations",
"items": {"$ref": "#/definitions/augmentation"},
"type": ["array", "null"],
},
"blob": {
"description": "Raw data (blob) for the frame",
"type": ["string", "null"],
},
"context_id": {
"description": (
"Context ID. Used for the default frames sorting. If not set then it is filled from the uri"
" of the first source."
),
"type": ["string", "null"],
},
"dataset": {
"description": "Frame's dataset version",
"oneOf": [
{"$ref": "#/definitions/dataset_version"},
{"type": "null"},
],
},
"id": {"description": "Frame id", "type": ["string", "null"]},
"is_key_frame": {
"description": "Is this a key frame (only applicable in frames who'se src is a video)",
"type": ["boolean", "null"],
},
"key_frame": {
"description": "ID of the key frame that this frame belongs to",
"type": ["string", "null"],
},
"label_rule_counts": {
"additionalProperties": True,
"description": "The number of matched roi per lable rule",
"type": ["object", "null"],
},
"labels_size": {
"description": "Number of labels returned",
"type": ["integer", "null"],
},
"meta": {
"additionalProperties": True,
"description": (
"Additional metadata dictionary for the frame. Please note that using this field"
" effectively defines a schema (dictionary structure and types used as values) - frames"
" within the same dataset cannot use conflicting schemas for this field (see documentation"
" for more details)."
),
"type": ["object", "null"],
},
"meta_blob": {
"additionalProperties": True,
"description": (
"Non searchable metadata dictionary for the frame. The fields in this object cannot be"
" searched by and are not added to the frame schema"
),
"type": ["object", "null"],
},
"new_ver": {
"description": "Newer version of this frame, if asked to merge",
"oneOf": [{"$ref": "#/definitions/frame"}, {"type": "null"}],
},
"rois": {
"description": "Frame regions of interest",
"items": {"$ref": "#/definitions/roi"},
"type": ["array", "null"],
},
"rule_name": {
"description": (
"Name of the filtering rule according to which this frame was provided (if applicable)"
),
"type": ["string", "null"],
},
"saved": {
"description": "Last time frame was saved (timestamp)",
"type": ["integer", "null"],
},
"saved_in_version": {
"description": "Last version this frame was saved in (version ID)",
"type": ["string", "null"],
},
"sources": {
"description": "Sources of this frame",
"items": {"$ref": "#/definitions/source"},
"type": ["array", "null"],
},
"timestamp": {
"description": (
"Frame's offset in milliseconds, used primarily for video content. Used for the default"
" frames sorting as the secondary key (with the primary key being 'context_id'). For"
" images, this value should typically be 0. If not set, value is filled from the timestamp"
" of the first source. We recommend using this field only in cases concerning the default"
" sorting behavior."
),
"type": ["integer", "null"],
},
"updated": {
"description": "Last time frame was saved (timestamp)",
"type": ["integer", "null"],
},
"updated_in_version": {
"description": "Last version this frame was updated in (version ID)",
"type": ["string", "null"],
},
"video_gop": {
"description": (
"Video encoding GOP value for the source of this frame. Only valid for video frames"
),
"type": ["number", "null"],
},
},
"type": "object",
},
"mask": {
"properties": {
"content_type": {
"description": "Content type (e.g. 'image/jpeg', 'image/png')",
"type": ["string", "null"],
},
"height": {
"description": "Height in pixels",
"type": ["integer", "null"],
},
"id": {
"description": "unique ID (in this frame)",
"type": ["string", "null"],
},
"timestamp": {
"default": 0,
"description": (
"Timestamp in the source data (for video content. for images, this value should be 0)"
),
"type": ["integer", "null"],
},
"uri": {"description": "Data URI", "type": ["string", "null"]},
"width": {
"description": "Width in pixels",
"type": ["integer", "null"],
},
},
"type": "object",
},
"preview": {
"properties": {
"content_type": {
"description": "Content type (e.g. 'image/jpeg', 'image/png')",
"type": ["string", "null"],
},
"height": {
"description": "Height in pixels",
"type": ["integer", "null"],
},
"timestamp": {
"default": 0,
"description": (
"Timestamp in the source data (for video content. for images, this value should be 0)"
),
"type": ["integer", "null"],
},
"uri": {"description": "Data URI", "type": ["string", "null"]},
"width": {
"description": "Width in pixels",
"type": ["integer", "null"],
},
},
"type": "object",
},
"roi": {
"properties": {
"area": {
"description": "ROI area (not used)",
"type": ["integer", "null"],
},
"confidence": {
"description": "ROI confidence",
"type": ["number", "null"],
},
"id": {"description": "ROI id", "type": ["string", "null"]},
"label": {
"description": "ROI labels",
"items": {"type": "string"},
"type": ["array", "null"],
},
"label_num": {
"description": (
"Label number according to the specified labels mapping Used only when ROI is returned as"
" part of a task's frame."
),
"type": ["integer", "null"],
},
"mask": {
"description": "Mask info for this ROI",
"oneOf": [{"$ref": "#/definitions/roi_mask"}, {"type": "null"}],
},
"meta": {
"additionalProperties": True,
"description": "Additional metadata dictionary for the roi",
"type": ["object", "null"],
},
"poly": {
"description": "ROI polygon (x0, y0, ..., xn, yn)",
"items": {"type": "number"},
"type": ["array", "null"],
},
"sources": {
"description": "Sources that this ROI belongs to",
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"type": "object",
},
"roi_mask": {
"properties": {
"id": {"description": "Mask ID", "type": "string"},
"value": {
"description": "Mask value",
"items": {"type": "integer"},
"type": "array",
},
},
"required": ["id", "value"],
"type": "object",
},
"source": {
"properties": {
"content_type": {
"description": "Content type (e.g. 'image/jpeg', 'image/png')",
"type": ["string", "null"],
},
"height": {
"description": "Height in pixels",
"type": ["integer", "null"],
},
"id": {
"description": "unique ID (in this frame)",
"type": ["string", "null"],
},
"masks": {
"items": {"$ref": "#/definitions/mask"},
"type": ["array", "null"],
},
"meta": {
"additionalProperties": True,
"description": "Additional metadata dictionary for the source",
"type": ["object", "null"],
},
"preview": {
"oneOf": [{"$ref": "#/definitions/preview"}, {"type": "null"}]
},
"timestamp": {
"default": 0,
"description": (
"Timestamp in the source data (for video content. for images, this value should be 0)"
),
"type": ["integer", "null"],
},
"uri": {"description": "Data URI", "type": ["string", "null"]},
"width": {
"description": "Width in pixels",
"type": ["integer", "null"],
},
},
"type": "object",
},
},
"properties": {
"frames": {
"description": "Frames data",
"items": {"$ref": "#/definitions/frame"},
"type": ["array", "null"],
}
},
"type": "object",
}
def __init__(self, frames=None, **kwargs):
super(GetByIdsResponse, self).__init__(**kwargs)
self.frames = frames
@schema_property("frames")
def frames(self):
return self._property_frames
@frames.setter
def frames(self, value):
if value is None:
self._property_frames = None
return
self.assert_isinstance(value, "frames", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [Frame.from_dict(v) if isinstance(v, dict) else v for v in value]
else:
self.assert_isinstance(value, "frames", Frame, is_array=True)
self._property_frames = value
| GetByIdsResponse |
python | chroma-core__chroma | chromadb/test/property/strategies.py | {
"start": 24087,
"end": 25453
} | class ____(TypedDict):
where: Optional[types.Where]
ids: Optional[Union[str, List[str]]]
where_document: Optional[types.WhereDocument]
@st.composite
def filters(
draw: st.DrawFn,
collection_st: st.SearchStrategy[Collection],
recordset_st: st.SearchStrategy[RecordSet],
include_all_ids: bool = False,
) -> Filter:
collection = draw(collection_st)
recordset = draw(recordset_st)
where_clause = draw(st.one_of(st.none(), recursive_where_clause(collection)))
where_document_clause = draw(
st.one_of(st.none(), recursive_where_doc_clause(collection))
)
ids: Optional[Union[List[types.ID], types.ID]]
# Record sets can be a value instead of a list of values if there is only one record
if isinstance(recordset["ids"], str):
ids = [recordset["ids"]]
else:
ids = recordset["ids"]
if not include_all_ids:
ids = draw(st.one_of(st.none(), st.lists(st.sampled_from(ids), min_size=1)))
if ids is not None:
# Remove duplicates since hypothesis samples with replacement
ids = list(set(ids))
# Test both the single value list and the unwrapped single value case
if ids is not None and len(ids) == 1 and draw(st.booleans()):
ids = ids[0]
return {"where": where_clause, "where_document": where_document_clause, "ids": ids}
| Filter |
python | getsentry__sentry | src/sentry/preprod/analytics.py | {
"start": 473,
"end": 652
} | class ____(analytics.Event):
organization_id: int
project_id: int
@analytics.eventclass("preprod_artifact.api.size_analysis_download")
| PreprodArtifactApiAssembleGenericEvent |
python | PyCQA__pylint | pylint/lint/message_state_handler.py | {
"start": 896,
"end": 17960
} | class ____:
"""Class that handles message disabling & enabling and processing of inline
pragma's.
"""
def __init__(self, linter: PyLinter) -> None:
self.linter = linter
self.default_enabled_messages: dict[str, MessageDefinitionTuple] = {
k: v
for k, v in self.linter.msgs.items()
if len(v) == 3 or v[3].get("default_enabled", True)
}
self._msgs_state: dict[str, bool] = {}
self._options_methods = {
"enable": self.enable,
"disable": self.disable,
"disable-next": self.disable_next,
}
self._bw_options_methods = {
"disable-msg": self._options_methods["disable"],
"enable-msg": self._options_methods["enable"],
}
self._pragma_lineno: dict[str, int] = {}
self._stashed_messages: defaultdict[
tuple[str, str], list[tuple[str | None, str]]
] = defaultdict(list)
"""Some messages in the options (for --enable and --disable) are encountered
too early to warn about them.
i.e. before all option providers have been fully parsed. Thus, this dict stores
option_value and msg_id needed to (later) emit the messages keyed on module names.
"""
def _set_one_msg_status(
self, scope: str, msg: MessageDefinition, line: int | None, enable: bool
) -> None:
"""Set the status of an individual message."""
if scope in {"module", "line"}:
assert isinstance(line, int) # should always be int inside module scope
self.linter.file_state.set_msg_status(msg, line, enable, scope)
if not enable and msg.symbol != "locally-disabled":
self.linter.add_message(
"locally-disabled", line=line, args=(msg.symbol, msg.msgid)
)
else:
msgs = self._msgs_state
msgs[msg.msgid] = enable
def _get_messages_to_set(
self, msgid: str, enable: bool, ignore_unknown: bool = False
) -> list[MessageDefinition]:
"""Do some tests and find the actual messages of which the status should be set."""
message_definitions: list[MessageDefinition] = []
if msgid == "all":
for _msgid in MSG_TYPES:
message_definitions.extend(
self._get_messages_to_set(_msgid, enable, ignore_unknown)
)
if not enable:
# "all" should not disable pylint's own warnings
message_definitions = list(
filter(
lambda m: m.msgid not in self.default_enabled_messages,
message_definitions,
)
)
return message_definitions
# msgid is a category?
category_id = msgid.upper()
if category_id not in MSG_TYPES:
category_id_formatted = MSG_TYPES_LONG.get(category_id)
else:
category_id_formatted = category_id
if category_id_formatted is not None:
for _msgid in self.linter.msgs_store._msgs_by_category[
category_id_formatted
]:
message_definitions.extend(
self._get_messages_to_set(_msgid, enable, ignore_unknown)
)
return message_definitions
# msgid is a checker name?
if msgid.lower() in self.linter._checkers:
for checker in self.linter._checkers[msgid.lower()]:
for _msgid in checker.msgs:
message_definitions.extend(
self._get_messages_to_set(_msgid, enable, ignore_unknown)
)
return message_definitions
# msgid is report id?
if msgid.lower().startswith("rp"):
if enable:
self.linter.enable_report(msgid)
else:
self.linter.disable_report(msgid)
return message_definitions
try:
# msgid is a symbolic or numeric msgid.
message_definitions = self.linter.msgs_store.get_message_definitions(msgid)
except exceptions.UnknownMessageError:
if not ignore_unknown:
raise
return message_definitions
def _set_msg_status(
self,
msgid: str,
enable: bool,
scope: str = "package",
line: int | None = None,
ignore_unknown: bool = False,
) -> None:
"""Do some tests and then iterate over message definitions to set state."""
assert scope in {"package", "module", "line"}
message_definitions = self._get_messages_to_set(msgid, enable, ignore_unknown)
for message_definition in message_definitions:
self._set_one_msg_status(scope, message_definition, line, enable)
# sync configuration object
self.linter.config.enable = []
self.linter.config.disable = []
for msgid_or_symbol, is_enabled in self._msgs_state.items():
symbols = [
m.symbol
for m in self.linter.msgs_store.get_message_definitions(msgid_or_symbol)
]
if is_enabled:
self.linter.config.enable += symbols
else:
self.linter.config.disable += symbols
def _register_by_id_managed_msg(
self, msgid_or_symbol: str, line: int | None, is_disabled: bool = True
) -> None:
"""If the msgid is a numeric one, then register it to inform the user
it could furnish instead a symbolic msgid.
"""
if msgid_or_symbol[1:].isdigit():
try:
symbol = self.linter.msgs_store.message_id_store.get_symbol(
msgid=msgid_or_symbol
)
except exceptions.UnknownMessageError:
return
managed = ManagedMessage(
self.linter.current_name, msgid_or_symbol, symbol, line, is_disabled
)
self.linter._by_id_managed_msgs.append(managed)
def disable(
self,
msgid: str,
scope: str = "package",
line: int | None = None,
ignore_unknown: bool = False,
) -> None:
"""Disable a message for a scope."""
self._set_msg_status(
msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown
)
self._register_by_id_managed_msg(msgid, line)
def disable_next(
self,
msgid: str,
_: str = "package",
line: int | None = None,
ignore_unknown: bool = False,
) -> None:
"""Disable a message for the next line."""
if not line:
raise exceptions.NoLineSuppliedError
self._set_msg_status(
msgid,
enable=False,
scope="line",
line=line + 1,
ignore_unknown=ignore_unknown,
)
self._register_by_id_managed_msg(msgid, line + 1)
def enable(
self,
msgid: str,
scope: str = "package",
line: int | None = None,
ignore_unknown: bool = False,
) -> None:
"""Enable a message for a scope."""
self._set_msg_status(
msgid, enable=True, scope=scope, line=line, ignore_unknown=ignore_unknown
)
self._register_by_id_managed_msg(msgid, line, is_disabled=False)
def disable_noerror_messages(self) -> None:
"""Disable message categories other than `error` and `fatal`."""
for msgcat in self.linter.msgs_store._msgs_by_category:
if msgcat in {"E", "F"}:
continue
self.disable(msgcat)
def list_messages_enabled(self) -> None:
emittable, non_emittable = self.linter.msgs_store.find_emittable_messages()
enabled: list[str] = []
disabled: list[str] = []
for message in emittable:
if self.is_message_enabled(message.msgid):
enabled.append(f" {message.symbol} ({message.msgid})")
else:
disabled.append(f" {message.symbol} ({message.msgid})")
print("Enabled messages:")
for msg in enabled:
print(msg)
print("\nDisabled messages:")
for msg in disabled:
print(msg)
print("\nNon-emittable messages with current interpreter:")
for msg_def in non_emittable:
print(f" {msg_def.symbol} ({msg_def.msgid})")
print("")
def _get_message_state_scope(
self,
msgid: str,
line: int | None = None,
confidence: interfaces.Confidence | None = None,
) -> Literal[0, 1, 2] | None:
"""Returns the scope at which a message was enabled/disabled."""
if confidence is None:
confidence = interfaces.UNDEFINED
if confidence.name not in self.linter.config.confidence:
return MSG_STATE_CONFIDENCE # type: ignore[return-value] # mypy does not infer Literal correctly
try:
if line in self.linter.file_state._module_msgs_state[msgid]:
return MSG_STATE_SCOPE_MODULE # type: ignore[return-value]
except (KeyError, TypeError):
return MSG_STATE_SCOPE_CONFIG # type: ignore[return-value]
return None
def _is_one_message_enabled(self, msgid: str, line: int | None) -> bool:
"""Checks state of a single message for the current file.
This function can't be cached as it depends on self.file_state which can
change.
"""
if line is None:
return self._msgs_state.get(msgid, True)
try:
return self.linter.file_state._module_msgs_state[msgid][line]
except KeyError:
# Check if the message's line is after the maximum line existing in ast tree.
# This line won't appear in the ast tree and won't be referred in
# self.file_state._module_msgs_state
# This happens for example with a commented line at the end of a module.
max_line_number = self.linter.file_state.get_effective_max_line_number()
if max_line_number and line > max_line_number:
fallback = True
lines = self.linter.file_state._raw_module_msgs_state.get(msgid, {})
# Doesn't consider scopes, as a 'disable' can be in a
# different scope than that of the current line.
closest_lines = reversed(
[
(message_line, enable)
for message_line, enable in lines.items()
if message_line <= line
]
)
_, fallback_iter = next(closest_lines, (None, None))
if fallback_iter is not None:
fallback = fallback_iter
return self._msgs_state.get(msgid, fallback)
return self._msgs_state.get(msgid, True)
def is_message_enabled(
self,
msg_descr: str,
line: int | None = None,
confidence: interfaces.Confidence | None = None,
) -> bool:
"""Is this message enabled for the current file ?
Optionally, is it enabled for this line and confidence level ?
The current file is implicit and mandatory. As a result this function
can't be cached right now as the line is the line of the currently
analysed file (self.file_state), if it changes, then the result for
the same msg_descr/line might need to change.
:param msg_descr: Either the msgid or the symbol for a MessageDefinition
:param line: The line of the currently analysed file
:param confidence: The confidence of the message
"""
if confidence and confidence.name not in self.linter.config.confidence:
return False
try:
msgids = self.linter.msgs_store.message_id_store.get_active_msgids(
msg_descr
)
except exceptions.UnknownMessageError:
# The linter checks for messages that are not registered
# due to version mismatch, just treat them as message IDs
# for now.
msgids = [msg_descr]
return any(self._is_one_message_enabled(msgid, line) for msgid in msgids)
def process_tokens(self, tokens: list[tokenize.TokenInfo]) -> None:
"""Process tokens from the current module to search for module/block level
options.
See func_block_disable_msg.py test case for expected behaviour.
"""
control_pragmas = {"disable", "disable-next", "enable"}
prev_line = None
saw_newline = True
seen_newline = True
for tok_type, content, start, _, _ in tokens:
if prev_line and prev_line != start[0]:
saw_newline = seen_newline
seen_newline = False
prev_line = start[0]
if tok_type in (tokenize.NL, tokenize.NEWLINE):
seen_newline = True
if tok_type != tokenize.COMMENT:
continue
match = OPTION_PO.search(content)
if match is None:
continue
try: # pylint: disable = too-many-try-statements
for pragma_repr in parse_pragma(match.group(2)):
if pragma_repr.action in {"disable-all", "skip-file"}:
if pragma_repr.action == "disable-all":
self.linter.add_message(
"deprecated-pragma",
line=start[0],
args=("disable-all", "skip-file"),
)
self.linter.add_message("file-ignored", line=start[0])
self._ignore_file: bool = True
return
try:
meth = self._options_methods[pragma_repr.action]
except KeyError:
meth = self._bw_options_methods[pragma_repr.action]
# found a "(dis|en)able-msg" pragma deprecated suppression
self.linter.add_message(
"deprecated-pragma",
line=start[0],
args=(
pragma_repr.action,
pragma_repr.action.replace("-msg", ""),
),
)
for msgid in pragma_repr.messages:
# Add the line where a control pragma was encountered.
if pragma_repr.action in control_pragmas:
self._pragma_lineno[msgid] = start[0]
if (pragma_repr.action, msgid) == ("disable", "all"):
self.linter.add_message(
"deprecated-pragma",
line=start[0],
args=("disable=all", "skip-file"),
)
self.linter.add_message("file-ignored", line=start[0])
self._ignore_file = True
return
# If we did not see a newline between the previous line and now,
# we saw a backslash so treat the two lines as one.
l_start = start[0]
if not saw_newline:
l_start -= 1
try:
meth(msgid, "module", l_start)
except (
exceptions.DeletedMessageError,
exceptions.MessageBecameExtensionError,
) as e:
self.linter.add_message(
"useless-option-value",
args=(pragma_repr.action, e),
line=start[0],
confidence=HIGH,
)
except exceptions.UnknownMessageError:
self.linter.add_message(
"unknown-option-value",
args=(pragma_repr.action, msgid),
line=start[0],
confidence=HIGH,
)
except UnRecognizedOptionError as err:
self.linter.add_message(
"unrecognized-inline-option", args=err.token, line=start[0]
)
continue
except InvalidPragmaError as err:
self.linter.add_message(
"bad-inline-option", args=err.token, line=start[0]
)
continue
| _MessageStateHandler |
python | pydata__xarray | xarray/tests/test_utils.py | {
"start": 399,
"end": 1438
} | class ____:
def test(self):
def new_method():
pass
old_method = utils.alias(new_method, "old_method")
assert "deprecated" in old_method.__doc__ # type: ignore[operator]
with pytest.warns(Warning, match="deprecated"):
old_method()
@pytest.mark.parametrize(
["a", "b", "expected"],
[
[np.array(["a"]), np.array(["b"]), np.array(["a", "b"])],
[np.array([1], dtype="int64"), np.array([2], dtype="int64"), pd.Index([1, 2])],
],
)
def test_maybe_coerce_to_str(a, b, expected):
index = pd.Index(a).append(pd.Index(b))
actual = utils.maybe_coerce_to_str(index, [a, b])
assert_array_equal(expected, actual)
assert expected.dtype == actual.dtype
def test_maybe_coerce_to_str_minimal_str_dtype():
a = np.array(["a", "a_long_string"])
index = pd.Index(["a"])
actual = utils.maybe_coerce_to_str(index, [a])
expected = np.array("a")
assert_array_equal(expected, actual)
assert expected.dtype == actual.dtype
| TestAlias |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/lambda3.py | {
"start": 332,
"end": 563
} | class ____(Protocol):
def __call__(self, y: int, a: int = 0) -> bool: ...
lambda1: Callable[[int, int], bool] = lambda y, a=0: a == y
lambda2: MyCallback = lambda y, a=0: a == y
lambda1(20)
lambda2(20)
lambda2(20, 30)
| MyCallback |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_webagg_core.py | {
"start": 14867,
"end": 16451
} | class ____(backend_bases.NavigationToolbar2):
# Use the standard toolbar items + download button
toolitems = [
(text, tooltip_text, image_file, name_of_method)
for text, tooltip_text, image_file, name_of_method
in (*backend_bases.NavigationToolbar2.toolitems,
('Download', 'Download plot', 'filesave', 'download'))
if name_of_method in _ALLOWED_TOOL_ITEMS
]
def __init__(self, canvas):
self.message = ''
super().__init__(canvas)
def set_message(self, message):
if message != self.message:
self.canvas.send_event("message", message=message)
self.message = message
def draw_rubberband(self, event, x0, y0, x1, y1):
self.canvas.send_event("rubberband", x0=x0, y0=y0, x1=x1, y1=y1)
def remove_rubberband(self):
self.canvas.send_event("rubberband", x0=-1, y0=-1, x1=-1, y1=-1)
def save_figure(self, *args):
"""Save the current figure."""
self.canvas.send_event('save')
return self.UNKNOWN_SAVED_STATUS
def pan(self):
super().pan()
self.canvas.send_event('navigate_mode', mode=self.mode.name)
def zoom(self):
super().zoom()
self.canvas.send_event('navigate_mode', mode=self.mode.name)
def set_history_buttons(self):
can_backward = self._nav_stack._pos > 0
can_forward = self._nav_stack._pos < len(self._nav_stack) - 1
self.canvas.send_event('history_buttons',
Back=can_backward, Forward=can_forward)
| NavigationToolbar2WebAgg |
python | oauthlib__oauthlib | oauthlib/openid/connect/core/grant_types/base.py | {
"start": 221,
"end": 15503
} | class ____:
# Just proxy the majority of method calls through to the
# proxy_target grant type handler, which will usually be either
# the standard OAuth2 AuthCode or Implicit grant types.
def __getattr__(self, attr):
return getattr(self.proxy_target, attr)
def __setattr__(self, attr, value):
proxied_attrs = {'refresh_token', 'response_types'}
if attr in proxied_attrs:
setattr(self.proxy_target, attr, value)
else:
super(OpenIDConnectBase, self).__setattr__(attr, value)
def validate_authorization_request(self, request):
"""Validates the OpenID Connect authorization request parameters.
:returns: (list of scopes, dict of request info)
"""
return self.proxy_target.validate_authorization_request(request)
def _inflate_claims(self, request):
# this may be called multiple times in a single request so make sure we only de-serialize the claims once
if request.claims and not isinstance(request.claims, dict):
# specific claims are requested during the Authorization Request and may be requested for inclusion
# in either the id_token or the UserInfo endpoint response
# see http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter
try:
request.claims = loads(request.claims)
except Exception as ex:
raise InvalidRequestError(description="Malformed claims parameter",
uri="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter")
def id_token_hash(self, value, hashfunc=hashlib.sha256):
"""
Its value is the base64url encoding of the left-most half of the
hash of the octets of the ASCII representation of the access_token
value, where the hash algorithm used is the hash algorithm used in
the alg Header Parameter of the ID Token's JOSE Header.
For instance, if the alg is RS256, hash the access_token value
with SHA-256, then take the left-most 128 bits and
base64url-encode them.
For instance, if the alg is HS512, hash the code value with
SHA-512, then take the left-most 256 bits and base64url-encode
them. The c_hash value is a case-sensitive string.
Example of hash from OIDC specification (bound to a JWS using RS256):
code:
Qcb0Orv1zh30vL1MPRsbm-diHiMwcLyZvn1arpZv-Jxf_11jnpEX3Tgfvk
c_hash:
LDktKdoQak3Pk0cnXxCltA
"""
digest = hashfunc(value.encode()).digest()
left_most = len(digest) // 2
return base64.urlsafe_b64encode(digest[:left_most]).decode().rstrip("=")
def add_id_token(self, token, token_handler, request, nonce=None):
"""
Construct an initial version of id_token, and let the
request_validator sign or encrypt it.
The initial version can contain the fields below, accordingly
to the spec:
- aud
- iat
- nonce
- at_hash
- c_hash
"""
# Treat it as normal OAuth 2 auth code request if openid is not present
if not request.scopes or 'openid' not in request.scopes:
return token
# Only add an id token on auth/token step if asked for.
if request.response_type and 'id_token' not in request.response_type:
return token
# Implementation mint its own id_token without help.
id_token = self.request_validator.get_id_token(token, token_handler, request)
if id_token:
token['id_token'] = id_token
return token
# Fallback for asking some help from oauthlib framework.
# Start with technicals fields bound to the specification.
id_token = {}
id_token['aud'] = request.client_id
id_token['iat'] = int(time.time())
# nonce is REQUIRED when response_type value is:
# - id_token token (Implicit)
# - id_token (Implicit)
# - code id_token (Hybrid)
# - code id_token token (Hybrid)
#
# nonce is OPTIONAL when response_type value is:
# - code (Authorization Code)
# - code token (Hybrid)
if nonce is not None:
id_token["nonce"] = nonce
# at_hash is REQUIRED when response_type value is:
# - id_token token (Implicit)
# - code id_token token (Hybrid)
#
# at_hash is OPTIONAL when:
# - code (Authorization code)
# - code id_token (Hybrid)
# - code token (Hybrid)
#
# at_hash MAY NOT be used when:
# - id_token (Implicit)
if "access_token" in token:
id_token["at_hash"] = self.id_token_hash(token["access_token"])
# c_hash is REQUIRED when response_type value is:
# - code id_token (Hybrid)
# - code id_token token (Hybrid)
#
# c_hash is OPTIONAL for others.
if "code" in token:
id_token["c_hash"] = self.id_token_hash(token["code"])
# Call request_validator to complete/sign/encrypt id_token
token['id_token'] = self.request_validator.finalize_id_token(id_token, token, token_handler, request)
return token
def openid_authorization_validator(self, request):
"""Perform OpenID Connect specific authorization request validation.
nonce
OPTIONAL. String value used to associate a Client session with
an ID Token, and to mitigate replay attacks. The value is
passed through unmodified from the Authentication Request to
the ID Token. Sufficient entropy MUST be present in the nonce
values used to prevent attackers from guessing values
display
OPTIONAL. ASCII string value that specifies how the
Authorization Server displays the authentication and consent
user interface pages to the End-User. The defined values are:
page - The Authorization Server SHOULD display the
authentication and consent UI consistent with a full User
Agent page view. If the display parameter is not specified,
this is the default display mode.
popup - The Authorization Server SHOULD display the
authentication and consent UI consistent with a popup User
Agent window. The popup User Agent window should be of an
appropriate size for a login-focused dialog and should not
obscure the entire window that it is popping up over.
touch - The Authorization Server SHOULD display the
authentication and consent UI consistent with a device that
leverages a touch interface.
wap - The Authorization Server SHOULD display the
authentication and consent UI consistent with a "feature
phone" type display.
The Authorization Server MAY also attempt to detect the
capabilities of the User Agent and present an appropriate
display.
prompt
OPTIONAL. Space delimited, case sensitive list of ASCII string
values that specifies whether the Authorization Server prompts
the End-User for reauthentication and consent. The defined
values are:
none - The Authorization Server MUST NOT display any
authentication or consent user interface pages. An error is
returned if an End-User is not already authenticated or the
Client does not have pre-configured consent for the
requested Claims or does not fulfill other conditions for
processing the request. The error code will typically be
login_required, interaction_required, or another code
defined in Section 3.1.2.6. This can be used as a method to
check for existing authentication and/or consent.
login - The Authorization Server SHOULD prompt the End-User
for reauthentication. If it cannot reauthenticate the
End-User, it MUST return an error, typically
login_required.
consent - The Authorization Server SHOULD prompt the
End-User for consent before returning information to the
Client. If it cannot obtain consent, it MUST return an
error, typically consent_required.
select_account - The Authorization Server SHOULD prompt the
End-User to select a user account. This enables an End-User
who has multiple accounts at the Authorization Server to
select amongst the multiple accounts that they might have
current sessions for. If it cannot obtain an account
selection choice made by the End-User, it MUST return an
error, typically account_selection_required.
The prompt parameter can be used by the Client to make sure
that the End-User is still present for the current session or
to bring attention to the request. If this parameter contains
none with any other value, an error is returned.
max_age
OPTIONAL. Maximum Authentication Age. Specifies the allowable
elapsed time in seconds since the last time the End-User was
actively authenticated by the OP. If the elapsed time is
greater than this value, the OP MUST attempt to actively
re-authenticate the End-User. (The max_age request parameter
corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] max_auth_age
request parameter.) When max_age is used, the ID Token returned
MUST include an auth_time Claim Value.
ui_locales
OPTIONAL. End-User's preferred languages and scripts for the
user interface, represented as a space-separated list of BCP47
[RFC5646] language tag values, ordered by preference. For
instance, the value "fr-CA fr en" represents a preference for
French as spoken in Canada, then French (without a region
designation), followed by English (without a region
designation). An error SHOULD NOT result if some or all of the
requested locales are not supported by the OpenID Provider.
id_token_hint
OPTIONAL. ID Token previously issued by the Authorization
Server being passed as a hint about the End-User's current or
past authenticated session with the Client. If the End-User
identified by the ID Token is logged in or is logged in by the
request, then the Authorization Server returns a positive
response; otherwise, it SHOULD return an error, such as
login_required. When possible, an id_token_hint SHOULD be
present when prompt=none is used and an invalid_request error
MAY be returned if it is not; however, the server SHOULD
respond successfully when possible, even if it is not present.
The Authorization Server need not be listed as an audience of
the ID Token when it is used as an id_token_hint value. If the
ID Token received by the RP from the OP is encrypted, to use it
as an id_token_hint, the Client MUST decrypt the signed ID
Token contained within the encrypted ID Token. The Client MAY
re-encrypt the signed ID token to the Authentication Server
using a key that enables the server to decrypt the ID Token,
and use the re-encrypted ID token as the id_token_hint value.
login_hint
OPTIONAL. Hint to the Authorization Server about the login
identifier the End-User might use to log in (if necessary).
This hint can be used by an RP if it first asks the End-User
for their e-mail address (or other identifier) and then wants
to pass that value as a hint to the discovered authorization
service. It is RECOMMENDED that the hint value match the value
used for discovery. This value MAY also be a phone number in
the format specified for the phone_number Claim. The use of
this parameter is left to the OP's discretion.
acr_values
OPTIONAL. Requested Authentication Context Class Reference
values. Space-separated string that specifies the acr values
that the Authorization Server is being requested to use for
processing this Authentication Request, with the values
appearing in order of preference. The Authentication Context
Class satisfied by the authentication performed is returned as
the acr Claim Value, as specified in Section 2. The acr Claim
is requested as a Voluntary Claim by this parameter.
"""
# Treat it as normal OAuth 2 auth code request if openid is not present
if not request.scopes or 'openid' not in request.scopes:
return {}
prompt = request.prompt if request.prompt else []
if hasattr(prompt, 'split'):
prompt = prompt.strip().split()
prompt = set(prompt)
if 'none' in prompt:
if len(prompt) > 1:
msg = "Prompt none is mutually exclusive with other values."
raise InvalidRequestError(request=request, description=msg)
if not self.request_validator.validate_silent_login(request):
raise LoginRequired(request=request)
if not self.request_validator.validate_silent_authorization(request):
raise ConsentRequired(request=request)
self._inflate_claims(request)
if not self.request_validator.validate_user_match(
request.id_token_hint, request.scopes, request.claims, request):
msg = "Session user does not match client supplied user."
raise LoginRequired(request=request, description=msg)
ui_locales = request.ui_locales if request.ui_locales else []
if hasattr(ui_locales, 'split'):
ui_locales = ui_locales.strip().split()
request_info = {
'display': request.display,
'nonce': request.nonce,
'prompt': prompt,
'ui_locales': ui_locales,
'id_token_hint': request.id_token_hint,
'login_hint': request.login_hint,
'claims': request.claims
}
return request_info
OpenIDConnectBase = GrantTypeBase
| GrantTypeBase |
python | huggingface__transformers | tests/models/deepseek_v2/test_modeling_deepseek_v2.py | {
"start": 1798,
"end": 7391
} | class ____(CausalLMModelTest, unittest.TestCase):
test_all_params_have_gradient = False
model_tester_class = DeepseekV2ModelTester
model_split_percents = [0.5, 0.7, 0.8]
# used in `test_torch_compile_for_training`
_torch_compile_train_cls = DeepseekV2ForCausalLM if is_torch_available() else None
def _check_past_key_values_for_generate(self, batch_size, past_key_values, seq_length, config):
"""Needs to be overridden as deepseek has special MLA cache format (though we don't really use the MLA)"""
self.assertIsInstance(past_key_values, Cache)
# (batch, head, seq_length, head_features)
expected_common_shape = (
batch_size,
getattr(config, "num_key_value_heads", config.num_attention_heads),
seq_length,
)
expected_key_shape = expected_common_shape + (config.qk_nope_head_dim + config.qk_rope_head_dim,)
expected_value_shape = expected_common_shape + (config.v_head_dim,)
for layer in past_key_values.layers:
self.assertEqual(layer.keys.shape, expected_key_shape)
self.assertEqual(layer.values.shape, expected_value_shape)
def test_model_rope_scaling_frequencies(self):
"""
Overwritten: DeepseekV2 implements RoPE in the complex domain, as opposed to in the real domain with
`sin` and `cos`. Nevertheless, the checks are the same as in the original test.
"""
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
scaling_factor = 10
short_input_length = 10
long_input_length = int(config.max_position_embeddings * 1.5)
# Inputs
x = torch.randn(
1, dtype=torch.float32, device=torch_device
) # used exclusively to get the dtype and the device
position_ids_short = torch.arange(short_input_length, dtype=torch.long, device=torch_device)
position_ids_short = position_ids_short.unsqueeze(0)
position_ids_long = torch.arange(long_input_length, dtype=torch.long, device=torch_device)
position_ids_long = position_ids_long.unsqueeze(0)
# Sanity check original RoPE
original_rope = DeepseekV2RotaryEmbedding(config=config).to(torch_device)
original_freqs_cis_short = original_rope(x, position_ids_short)
original_freqs_cis_long = original_rope(x, position_ids_long)
torch.testing.assert_close(original_freqs_cis_short, original_freqs_cis_long[:, :short_input_length, :])
# Sanity check linear RoPE scaling
# New position "x" should match original position with index "x/scaling_factor"
config.rope_parameters = {"rope_type": "linear", "rope_theta": 10000.0, "factor": scaling_factor}
linear_scaling_rope = DeepseekV2RotaryEmbedding(config=config).to(torch_device)
linear_freqs_cis_short = linear_scaling_rope(x, position_ids_short)
linear_freqs_cis_long = linear_scaling_rope(x, position_ids_long)
torch.testing.assert_close(linear_freqs_cis_short, linear_freqs_cis_long[:, :short_input_length, :])
# Sanity check Dynamic NTK RoPE scaling
# Scaling should only be observed after a long input is fed. We can observe that the frequencies increase
# with scaling_factor (or that `inv_freq` decreases)
config.rope_parameters = {"rope_type": "dynamic", "rope_theta": 10000.0, "factor": scaling_factor}
ntk_scaling_rope = DeepseekV2RotaryEmbedding(config=config).to(torch_device)
ntk_freqs_cis_short = ntk_scaling_rope(x, position_ids_short)
ntk_freqs_cis_long = ntk_scaling_rope(x, position_ids_long)
torch.testing.assert_close(ntk_freqs_cis_short, original_freqs_cis_short)
with self.assertRaises(AssertionError):
torch.testing.assert_close(ntk_freqs_cis_long, original_freqs_cis_long)
self.assertTrue((ntk_scaling_rope.inv_freq <= original_rope.inv_freq).all())
# Sanity check Yarn RoPE scaling
# Scaling should be over the entire input
config.rope_parameters = {"rope_type": "yarn", "rope_theta": 10000.0, "factor": scaling_factor}
yarn_scaling_rope = DeepseekV2RotaryEmbedding(config=config).to(torch_device)
yarn_freqs_cis_short = yarn_scaling_rope(x, position_ids_short)
yarn_freqs_cis_long = yarn_scaling_rope(x, position_ids_long)
torch.testing.assert_close(yarn_freqs_cis_short, yarn_freqs_cis_long[:, :short_input_length, :])
with self.assertRaises(AssertionError):
torch.testing.assert_close(yarn_freqs_cis_short, original_freqs_cis_short)
with self.assertRaises(AssertionError):
torch.testing.assert_close(yarn_freqs_cis_long, original_freqs_cis_long)
@unittest.skip("Dynamic control flow in MoE")
@pytest.mark.torch_compile_test
def test_torch_compile_for_training(self):
pass
def test_tp_plan_matches_params(self):
"""Need to overwrite as the plan contains keys that are valid but depend on some configs flags and cannot
be valid all at the same time"""
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
# The key is valid but not always used based on the flag
if config.q_lora_rank is not None:
config.base_model_tp_plan.pop("layers.*.self_attn.q_proj")
super().test_tp_plan_matches_params()
# Put them back in class attribute
config.base_model_tp_plan.update({"layers.*.self_attn.q_proj": "colwise"})
@slow
@require_read_token
@require_torch_accelerator
| DeepseekV2ModelTest |
python | gevent__gevent | src/greentest/3.14/test_socket.py | {
"start": 234221,
"end": 235082
} | class ____(unittest.TestCase):
def testExceptionTree(self):
self.assertIsSubclass(OSError, Exception)
self.assertIsSubclass(socket.herror, OSError)
self.assertIsSubclass(socket.gaierror, OSError)
self.assertIsSubclass(socket.timeout, OSError)
self.assertIs(socket.error, OSError)
self.assertIs(socket.timeout, TimeoutError)
def test_setblocking_invalidfd(self):
# Regression test for issue #28471
sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM, 0, sock0.fileno())
sock0.close()
self.addCleanup(sock.detach)
with self.assertRaises(OSError):
sock.setblocking(False)
@unittest.skipUnless(sys.platform in ('linux', 'android'), 'Linux specific test')
| TestExceptions |
python | huggingface__transformers | src/transformers/models/lxmert/modeling_lxmert.py | {
"start": 1547,
"end": 4777
} | class ____(ModelOutput):
r"""
language_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the language encoder.
vision_output (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the visual encoder.
pooled_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
Last layer hidden-state of the first token of the sequence (classification, CLS, token) further processed
by a Linear layer and a Tanh activation function. The Linear
language_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
shape `(batch_size, sequence_length, hidden_size)`.
vision_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for input features + one for the output of each cross-modality layer) of
shape `(batch_size, sequence_length, hidden_size)`.
language_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.
vision_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.
cross_encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.
"""
language_output: Optional[torch.FloatTensor] = None
vision_output: Optional[torch.FloatTensor] = None
pooled_output: Optional[torch.FloatTensor] = None
language_hidden_states: Optional[tuple[torch.FloatTensor]] = None
vision_hidden_states: Optional[tuple[torch.FloatTensor]] = None
language_attentions: Optional[tuple[torch.FloatTensor]] = None
vision_attentions: Optional[tuple[torch.FloatTensor]] = None
cross_encoder_attentions: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`LxmertForQuestionAnswering`].
"""
)
| LxmertModelOutput |
python | sympy__sympy | sympy/core/relational.py | {
"start": 27701,
"end": 29755
} | class ____(Relational):
"""Internal base class for all *Than types.
Each subclass must implement _eval_relation to provide the method for
comparing two real numbers.
"""
__slots__ = ()
if TYPE_CHECKING:
@property
def args(self) -> tuple[Expr, Expr]:
...
@property
def lhs(self) -> Expr:
...
@property
def rhs(self) -> Expr:
...
def __new__(cls, lhs: Expr | complex, rhs: Expr | complex, **options) -> Self | BooleanTrue | BooleanFalse: # type: ignore
try:
lhs_e = _sympify(lhs)
rhs_e = _sympify(rhs)
except SympifyError:
return NotImplemented
evaluate = options.pop('evaluate', global_parameters.evaluate)
if evaluate:
for me in (lhs_e, rhs_e):
if me.is_extended_real is False:
raise TypeError("Invalid comparison of non-real %s" % me)
if me is S.NaN:
raise TypeError("Invalid NaN comparison")
# First we invoke the appropriate inequality method of `lhs`
# (e.g., `lhs.__lt__`). That method will try to reduce to
# boolean or raise an exception. It may keep calling
# superclasses until it reaches `Expr` (e.g., `Expr.__lt__`).
# In some cases, `Expr` will just invoke us again (if neither it
# nor a subclass was able to reduce to boolean or raise an
# exception). In that case, it must call us with
# `evaluate=False` to prevent infinite recursion.
return cls._eval_relation(lhs_e, rhs_e, **options)
# make a "non-evaluated" Expr for the inequality
return Relational.__new__(cls, lhs_e, rhs_e, **options)
@classmethod
def _eval_relation(cls, lhs, rhs, **options):
val = cls._eval_fuzzy_relation(lhs, rhs)
if val is None:
return cls(lhs, rhs, evaluate=False)
else:
return _sympify(val)
| _Inequality |
python | google__flatbuffers | tests/MyGame/Example/Referrable.py | {
"start": 176,
"end": 1522
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Referrable()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsReferrable(cls, buf, offset=0):
"""This method is deprecated. Please switch to GetRootAs."""
return cls.GetRootAs(buf, offset)
@classmethod
def ReferrableBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed)
# Referrable
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# Referrable
def Id(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos)
return 0
def ReferrableStart(builder):
builder.StartObject(1)
def Start(builder):
ReferrableStart(builder)
def ReferrableAddId(builder, id):
builder.PrependUint64Slot(0, id, 0)
def AddId(builder, id):
ReferrableAddId(builder, id)
def ReferrableEnd(builder):
return builder.EndObject()
def End(builder):
return ReferrableEnd(builder)
| Referrable |
python | pytorch__pytorch | torch/_inductor/fx_passes/group_batch_fusion.py | {
"start": 19915,
"end": 25307
} | class ____(BatchFusion):
"""
Batch linear left-hand side fusion. This pass tries to fuse the following patterns:
torch.nn.functional.linear(x, w1), linear(x, w2),... * linear(x, wn)
-> torch.mm(x, torch.cat([w1, w2,... * wn]).transpose(0, 1))
We have a separate pass to eliminate contiguous transpose in a generic way.
"""
def match(self, node: torch.fx.Node) -> tuple[str, bool, Any] | None:
if CallFunctionVarArgs(torch.nn.functional.linear).match(
node
) and is_linear_node_can_be_fused(node):
input = get_arg_value(node, 0, "input")
bias = get_arg_value(node, 2, "bias")
group_key = ("batch_linear_lhs", bias is None, input)
else:
group_key = None
return group_key
def fuse(self, graph: torch.fx.GraphModule, subset: list[torch.fx.Node]):
batch_nodes = []
batch_input = None
batch_weights, batch_weights_meta = [], []
batch_biases, batch_biases_meta = [], []
split_sections = []
for node in subset:
input = get_arg_value(node, 0, "input")
weight = get_arg_value(node, 1, "weight")
bias = get_arg_value(node, 2, "bias")
batch_nodes.append(node)
if batch_input is None:
batch_input = input
else:
assert batch_input is input
batch_weights.append(weight)
batch_weights_meta.append(weight.meta["example_value"])
if bias:
batch_biases.append(bias)
batch_biases_meta.append(bias.meta["example_value"])
split_sections.append(weight.meta["example_value"].shape[0])
with graph.inserting_before(subset[0]): # type: ignore[operator]
cat_weights = graph.call_function( # type: ignore[operator]
torch.cat, args=(batch_weights,), kwargs={"dim": 0}
)
cat_weights.meta["example_value"] = torch.cat(batch_weights_meta, dim=0)
transposed_weights = graph.call_function( # type: ignore[operator]
torch.transpose, args=(cat_weights, 0, 1)
)
transposed_weights.meta["example_value"] = torch.transpose(
cat_weights.meta["example_value"], 0, 1
)
if len(batch_biases) > 0:
cat_biases = graph.call_function( # type: ignore[operator]
torch.cat, args=(batch_biases,), kwargs={"dim": 0}
)
cat_biases.meta["example_value"] = torch.cat(batch_biases_meta, dim=0)
fused_lhs = graph.call_function( # type: ignore[operator]
torch.addmm,
args=(cat_biases, batch_input, transposed_weights),
)
fused_lhs.meta["example_value"] = torch.addmm(
cat_biases.meta["example_value"],
batch_input.meta["example_value"], # type: ignore[union-attr]
transposed_weights.meta["example_value"],
)
else:
fused_lhs = graph.call_function( # type: ignore[operator]
torch.mm,
args=(batch_input, transposed_weights),
)
fused_lhs.meta["example_value"] = torch.mm(
batch_input.meta["example_value"], # type: ignore[union-attr]
transposed_weights.meta["example_value"],
)
fused_lhs_list = graph.call_function( # type: ignore[operator]
torch.split, args=(fused_lhs, split_sections), kwargs={"dim": 1}
)
for i, node in enumerate(batch_nodes):
with graph.inserting_after(fused_lhs_list): # type: ignore[operator]
new_node = graph.call_function( # type: ignore[operator]
operator.getitem, args=(fused_lhs_list, i)
)
node.replace_all_uses_with(new_node)
new_node.meta.update(node.meta)
graph.erase_node(node) # type: ignore[operator]
counters["inductor"]["batch_linear_lhs"] += 1
# Poor person's check for if a node in the graph mutates its input.
# (the graph is torch IR, so we will see torch fns and python operators)
def _is_mutable_node(tgt):
if str(tgt).endswith("_"):
# e.g. torch.mul_, torch.Tensor.mul_
return True
if (
hasattr(tgt, "__module__")
and tgt.__module__ == "_operator"
and tgt.__name__.startswith("i")
):
# e.g. operator.iand, operator.imul
return True
return False
def is_linear_node_can_be_fused(node: torch.fx.Node):
input = get_arg_value(node, 0, "input")
weight = get_arg_value(node, 1, "weight")
return (
is_node_meta_valid(node)
and is_node_meta_valid(input)
and is_node_meta_valid(weight)
and len(input.meta["example_value"].shape) == 2
and len(weight.meta["example_value"].shape) == 2
# the mm -> bmm transform adds an unbind() op,
# which is not safe for autograd when the output of the mm is mutated.
# don't pattern match if any users of the mm mutate the input.
and not any(_is_mutable_node(user.target) for user in node.users)
)
@register_fusion("batch_linear")
| BatchLinearLHSFusion |
python | django-guardian__django-guardian | example_project/core/migrations/0001_initial.py | {
"start": 150,
"end": 4282
} | class ____(migrations.Migration):
dependencies = [
("auth", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="CustomUser",
fields=[
("id", models.AutoField(verbose_name="ID", serialize=False, auto_created=True, primary_key=True)),
("password", models.CharField(max_length=128, verbose_name="password")),
("last_login", models.DateTimeField(null=True, verbose_name="last login", blank=True)),
(
"is_superuser",
models.BooleanField(
default=False,
help_text="Designates that this user has all permissions without explicitly assigning them.",
verbose_name="superuser status",
),
),
(
"username",
models.CharField(
error_messages={"unique": "A user with that username already exists."},
max_length=30,
validators=[
django.core.validators.RegexValidator(
"^[\\w.@+-]+$",
"Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.",
"invalid",
)
],
help_text="Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.",
unique=True,
verbose_name="username",
),
),
("first_name", models.CharField(max_length=30, verbose_name="first name", blank=True)),
("last_name", models.CharField(max_length=30, verbose_name="last name", blank=True)),
("email", models.EmailField(max_length=254, verbose_name="email address", blank=True)),
(
"is_staff",
models.BooleanField(
default=False,
help_text="Designates whether the user can log into this admin site.",
verbose_name="staff status",
),
),
(
"is_active",
models.BooleanField(
default=True,
help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
verbose_name="active",
),
),
("date_joined", models.DateTimeField(default=django.utils.timezone.now, verbose_name="date joined")),
("birth_date", models.DateField(null=True, blank=True)),
(
"groups",
models.ManyToManyField(
related_query_name="user",
related_name="user_set",
to="auth.Group",
blank=True,
help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
verbose_name="groups",
),
),
(
"user_permissions",
models.ManyToManyField(
related_query_name="user",
related_name="user_set",
to="auth.Permission",
blank=True,
help_text="Specific permissions for this user.",
verbose_name="user permissions",
),
),
],
options={
"abstract": False,
"verbose_name": "user",
"verbose_name_plural": "users",
},
managers=[
("objects", django.contrib.auth.models.UserManager()),
],
),
]
| Migration |
python | huggingface__transformers | src/transformers/models/olmo3/configuration_olmo3.py | {
"start": 1304,
"end": 9364
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Olmo3Model`]. It is used to instantiate an OLMo3
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 [allenai/OLMo-3-0725-1B](https://huggingface.co/allenai/OLMo-3-0725-1B).
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 50304):
Vocabulary size of the Olmo3 model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`Olmo3Model`]
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 11008):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer decoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer decoder.
num_key_value_heads (`int`, *optional*):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details, check out [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
`num_attention_heads`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 2048):
The maximum sequence length that this model might ever be used with.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
pad_token_id (`int`, *optional*, defaults to 1):
Padding token id.
bos_token_id (`int`, *optional*):
Beginning of stream token id.
eos_token_id (`int`, *optional*, defaults to 50279):
End of stream token id.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether to tie weight embeddings
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
Whether to use a bias in the query, key, value and output projection layers during self-attention.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the rms normalization layers.
sliding_window (`int`, *optional*, defaults to 4096):
Size of the sliding window for sliding window attention.
layer_types (`list`, *optional*):
Attention pattern for each layer. Defaults to sliding window attention
for 3 out of 4 layers, and full attention for every 4th layer.
```python
>>> from transformers import Olmo3Model, Olmo3Config
>>> # Initializing a Olmo3 7B style configuration
>>> configuration = Olmo3Config()
>>> # Initializing a model from the Olmo3 7B style configuration
>>> model = Olmo3Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```
"""
model_type = "olmo3"
keys_to_ignore_at_inference = ["past_key_values"]
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
"layers.*.self_attn.k_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
"layers.*.self_attn.v_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k
"layers.*.self_attn.o_proj": "rowwise_rep", # we need to replicate here due to the added norm on q and k
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
vocab_size: Optional[int] = 50304,
hidden_size: Optional[int] = 4096,
intermediate_size: Optional[int] = 11008,
num_hidden_layers: Optional[int] = 32,
num_attention_heads: Optional[int] = 32,
num_key_value_heads: Optional[int] = None,
hidden_act: Optional[str] = "silu",
max_position_embeddings: Optional[int] = 2048,
initializer_range: Optional[float] = 0.02,
use_cache: Optional[bool] = True,
pad_token_id: Optional[int] = 1,
bos_token_id: Optional[int] = None,
eos_token_id: Optional[int] = 50279,
tie_word_embeddings: Optional[bool] = False,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
attention_bias: Optional[bool] = False,
attention_dropout: Optional[float] = 0.0,
rms_norm_eps: Optional[float] = 1e-5,
sliding_window: Optional[int] = 4096,
layer_types: Optional[list[str]] = None,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.use_cache = use_cache
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.rms_norm_eps = rms_norm_eps
self.sliding_window = sliding_window
self.layer_types = layer_types
if self.layer_types is None:
self.layer_types = [
"sliding_attention" if (i + 1) % 4 != 0 else "full_attention" for i in range(self.num_hidden_layers)
]
layer_type_validation(self.layer_types, self.num_hidden_layers)
self.rope_parameters = rope_parameters
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
__all__ = ["Olmo3Config"]
| Olmo3Config |
python | dateutil__dateutil | tests/test_tz.py | {
"start": 94161,
"end": 95318
} | class ____(unittest.TestCase):
def testNoTzSpecified(self):
with self.assertRaises(ValueError):
tz.datetime_exists(datetime(2016, 4, 1, 2, 9))
def testInGapNaive(self):
tzi = tz.gettz('Australia/Sydney')
dt = datetime(2012, 10, 7, 2, 30)
self.assertFalse(tz.datetime_exists(dt, tz=tzi))
def testInGapAware(self):
tzi = tz.gettz('Australia/Sydney')
dt = datetime(2012, 10, 7, 2, 30, tzinfo=tzi)
self.assertFalse(tz.datetime_exists(dt))
def testExistsNaive(self):
tzi = tz.gettz('Australia/Sydney')
dt = datetime(2012, 10, 7, 10, 30)
self.assertTrue(tz.datetime_exists(dt, tz=tzi))
def testExistsAware(self):
tzi = tz.gettz('Australia/Sydney')
dt = datetime(2012, 10, 7, 10, 30, tzinfo=tzi)
self.assertTrue(tz.datetime_exists(dt))
def testSpecifiedTzOverridesAttached(self):
EST = tz.gettz('US/Eastern')
AEST = tz.gettz('Australia/Sydney')
dt = datetime(2012, 10, 7, 2, 30, tzinfo=EST) # This time exists
self.assertFalse(tz.datetime_exists(dt, tz=AEST))
| DatetimeExistsTest |
python | cython__cython | Cython/Debugger/Tests/test_libcython_in_gdb.py | {
"start": 15247,
"end": 15525
} | class ____(DebugTestCase):
def test_cyset(self):
self.break_and_run('os.path.join("foo", "bar")')
gdb.execute('cy set a = $cy_eval("{None: []}")')
stringvalue = self.read_var("a", cast_to=str)
self.assertEqual(stringvalue, "{None: []}")
| CySet |
python | walkccc__LeetCode | solutions/300. Longest Increasing Subsequence/300-2.py | {
"start": 0,
"end": 351
} | class ____:
def lengthOfLIS(self, nums: list[int]) -> int:
# tails[i] := the minimum tails of all the increasing subsequences having
# length i + 1
tails = []
for num in nums:
if not tails or num > tails[-1]:
tails.append(num)
else:
tails[bisect.bisect_left(tails, num)] = num
return len(tails)
| Solution |
python | doocs__leetcode | solution/1600-1699/1679.Max Number of K-Sum Pairs/Solution.py | {
"start": 0,
"end": 383
} | class ____:
def maxOperations(self, nums: List[int], k: int) -> int:
nums.sort()
l, r, ans = 0, len(nums) - 1, 0
while l < r:
s = nums[l] + nums[r]
if s == k:
ans += 1
l, r = l + 1, r - 1
elif s > k:
r -= 1
else:
l += 1
return ans
| Solution |
python | django__django | tests/reverse_lookup/models.py | {
"start": 196,
"end": 326
} | class ____(models.Model):
question = models.CharField(max_length=200)
creator = models.ForeignKey(User, models.CASCADE)
| Poll |
python | pytorch__pytorch | torch/ao/nn/intrinsic/modules/fused.py | {
"start": 1250,
"end": 1817
} | class ____(_FusedModule):
r"""This is a sequential container which calls the Conv2d and ReLU modules.
During quantization this will be replaced with the corresponding fused module."""
def __init__(self, conv, relu):
assert (
type_before_parametrizations(conv) == Conv2d
and type_before_parametrizations(relu) == ReLU
), (
f"Incorrect types for input modules{type_before_parametrizations(conv)}"
f"{type_before_parametrizations(relu)}"
)
super().__init__(conv, relu)
| ConvReLU2d |
python | pydantic__pydantic | pydantic-core/tests/validators/test_typed_dict.py | {
"start": 32703,
"end": 47957
} | class ____:
def test_on_error_bad_omit(self):
with pytest.raises(SchemaError, match="Field 'x': 'on_error = omit' cannot be set for required fields"):
SchemaValidator(
schema=core_schema.typed_dict_schema(
fields={
'x': core_schema.typed_dict_field(
schema=core_schema.with_default_schema(schema=core_schema.str_schema(), on_error='omit')
)
}
)
)
def test_on_error_bad_default(self):
with pytest.raises(SchemaError, match="'on_error = default' requires a `default` or `default_factory`"):
SchemaValidator(
schema=core_schema.typed_dict_schema(
fields={
'x': core_schema.typed_dict_field(
schema=core_schema.with_default_schema(schema=core_schema.str_schema(), on_error='default')
)
}
)
)
def test_on_error_raise_by_default(self, py_and_json: PyAndJson):
v = py_and_json(
{'type': 'typed-dict', 'fields': {'x': {'type': 'typed-dict-field', 'schema': {'type': 'str'}}}}
)
assert v.validate_test({'x': 'foo'}) == {'x': 'foo'}
with pytest.raises(ValidationError) as exc_info:
v.validate_test({'x': ['foo']})
assert exc_info.value.errors(include_url=False) == [
{'input': ['foo'], 'type': 'string_type', 'loc': ('x',), 'msg': 'Input should be a valid string'}
]
def test_on_error_raise_explicit(self, py_and_json: PyAndJson):
v = py_and_json(
{
'type': 'typed-dict',
'fields': {
'x': {
'type': 'typed-dict-field',
'schema': {'type': 'default', 'schema': {'type': 'str'}, 'on_error': 'raise'},
}
},
}
)
assert v.validate_test({'x': 'foo'}) == {'x': 'foo'}
with pytest.raises(ValidationError) as exc_info:
v.validate_test({'x': ['foo']})
assert exc_info.value.errors(include_url=False) == [
{'input': ['foo'], 'type': 'string_type', 'loc': ('x',), 'msg': 'Input should be a valid string'}
]
def test_on_error_omit(self, py_and_json: PyAndJson):
v = py_and_json(
{
'type': 'typed-dict',
'fields': {
'x': {
'type': 'typed-dict-field',
'schema': {'type': 'default', 'schema': {'type': 'str'}, 'on_error': 'omit'},
'required': False,
}
},
}
)
assert v.validate_test({'x': 'foo'}) == {'x': 'foo'}
assert v.validate_test({}) == {}
assert v.validate_test({'x': ['foo']}) == {}
def test_on_error_omit_with_default(self, py_and_json: PyAndJson):
v = py_and_json(
{
'type': 'typed-dict',
'fields': {
'x': {
'type': 'typed-dict-field',
'schema': {'type': 'default', 'schema': {'type': 'str'}, 'on_error': 'omit', 'default': 'pika'},
'required': False,
}
},
}
)
assert v.validate_test({'x': 'foo'}) == {'x': 'foo'}
assert v.validate_test({}) == {'x': 'pika'}
assert v.validate_test({'x': ['foo']}) == {}
def test_on_error_default(self, py_and_json: PyAndJson):
v = py_and_json(
{
'type': 'typed-dict',
'fields': {
'x': {
'type': 'typed-dict-field',
'schema': {
'type': 'default',
'schema': {'type': 'str'},
'on_error': 'default',
'default': 'pika',
},
}
},
}
)
assert v.validate_test({'x': 'foo'}) == {'x': 'foo'}
assert v.validate_test({'x': ['foo']}) == {'x': 'pika'}
def test_on_error_default_factory(self, py_and_json: PyAndJson):
v = py_and_json(
{
'type': 'typed-dict',
'fields': {
'x': {
'type': 'typed-dict-field',
'schema': {
'type': 'default',
'schema': {'type': 'str'},
'on_error': 'default',
'default_factory': lambda: 'pika',
},
}
},
}
)
assert v.validate_test({'x': 'foo'}) == {'x': 'foo'}
assert v.validate_test({'x': ['foo']}) == {'x': 'pika'}
def test_wrap_on_error(self, py_and_json: PyAndJson):
def wrap_function(input_value, validator, info):
try:
return validator(input_value)
except ValidationError:
if isinstance(input_value, list):
return str(len(input_value))
else:
return repr(input_value)
v = py_and_json(
{
'type': 'typed-dict',
'fields': {
'x': {
'type': 'typed-dict-field',
'schema': {
'type': 'default',
'on_error': 'raise',
'schema': {
'type': 'function-wrap',
'function': {'type': 'with-info', 'function': wrap_function},
'schema': {'type': 'str'},
},
},
}
},
}
)
assert v.validate_test({'x': 'foo'}) == {'x': 'foo'}
assert v.validate_test({'x': ['foo']}) == {'x': '1'}
assert v.validate_test({'x': ['foo', 'bar']}) == {'x': '2'}
assert v.validate_test({'x': {'a': 'b'}}) == {'x': "{'a': 'b'}"}
@pytest.mark.parametrize(
'config,schema_extra_behavior_kw',
[
(core_schema.CoreConfig(extra_fields_behavior='allow'), {}),
(core_schema.CoreConfig(extra_fields_behavior='allow'), {'extra_behavior': None}),
(core_schema.CoreConfig(), {'extra_behavior': 'allow'}),
(None, {'extra_behavior': 'allow'}),
(core_schema.CoreConfig(extra_fields_behavior='forbid'), {'extra_behavior': 'allow'}),
],
)
@pytest.mark.parametrize(
'extras_schema_kw, expected_extra_value',
[({}, '123'), ({'extras_schema': None}, '123'), ({'extras_schema': core_schema.int_schema()}, 123)],
ids=['extras_schema=unset', 'extras_schema=None', 'extras_schema=int'],
)
def test_extra_behavior_allow(
config: Union[core_schema.CoreConfig, None],
schema_extra_behavior_kw: dict[str, Any],
extras_schema_kw: dict[str, Any],
expected_extra_value: Any,
):
v = SchemaValidator(
core_schema.typed_dict_schema(
{'f': core_schema.typed_dict_field(core_schema.str_schema())},
**schema_extra_behavior_kw,
**extras_schema_kw,
config=config,
)
)
m: dict[str, Any] = v.validate_python({'f': 'x', 'extra_field': '123'})
assert m == {'f': 'x', 'extra_field': expected_extra_value}
# We can't test the extra parameter of the validate_* functions above, since the
# extras_schema parameter isn't valid unless the models are configured with extra='allow'.
# Test the validate_* extra parameter separately here instead:
@pytest.mark.parametrize(
'config,schema_extra_behavior_kw',
[
(core_schema.CoreConfig(extra_fields_behavior='forbid'), {}),
(core_schema.CoreConfig(extra_fields_behavior='forbid'), {'extra_behavior': None}),
(core_schema.CoreConfig(), {'extra_behavior': 'forbid'}),
(None, {'extra_behavior': 'forbid'}),
(core_schema.CoreConfig(extra_fields_behavior='ignore'), {'extra_behavior': 'forbid'}),
(core_schema.CoreConfig(), {}),
(core_schema.CoreConfig(), {'extra_behavior': None}),
(None, {'extra_behavior': None}),
],
)
def test_extra_behavior_allow_with_validate_fn_override(
config: Union[core_schema.CoreConfig, None],
schema_extra_behavior_kw: dict[str, Any],
):
v = SchemaValidator(
core_schema.typed_dict_schema(
{'f': core_schema.typed_dict_field(core_schema.str_schema())},
**schema_extra_behavior_kw,
config=config,
)
)
m: dict[str, Any] = v.validate_python({'f': 'x', 'extra_field': '123'}, extra='allow')
assert m == {'f': 'x', 'extra_field': '123'}
@pytest.mark.parametrize(
'config,schema_extra_behavior_kw,validate_fn_extra_kw',
[
(core_schema.CoreConfig(extra_fields_behavior='forbid'), {}, None),
(core_schema.CoreConfig(extra_fields_behavior='forbid'), {'extra_behavior': None}, None),
(core_schema.CoreConfig(), {'extra_behavior': 'forbid'}, None),
(None, {'extra_behavior': 'forbid'}, None),
(core_schema.CoreConfig(extra_fields_behavior='allow'), {'extra_behavior': 'forbid'}, None),
(core_schema.CoreConfig(extra_fields_behavior='ignore'), {}, 'forbid'),
(core_schema.CoreConfig(extra_fields_behavior='ignore'), {'extra_behavior': None}, 'forbid'),
(core_schema.CoreConfig(), {'extra_behavior': 'ignore'}, 'forbid'),
(None, {'extra_behavior': 'ignore'}, 'forbid'),
(core_schema.CoreConfig(extra_fields_behavior='allow'), {'extra_behavior': 'ignore'}, 'forbid'),
(core_schema.CoreConfig(), {}, 'forbid'),
(core_schema.CoreConfig(), {'extra_behavior': None}, 'forbid'),
(None, {'extra_behavior': None}, 'forbid'),
],
)
def test_extra_behavior_forbid(
config: Union[core_schema.CoreConfig, None],
schema_extra_behavior_kw: dict[str, Any],
validate_fn_extra_kw: Union[ExtraBehavior, None],
):
v = SchemaValidator(
core_schema.typed_dict_schema(
{'f': core_schema.typed_dict_field(core_schema.str_schema())},
**schema_extra_behavior_kw,
config=config,
)
)
m: dict[str, Any] = v.validate_python({'f': 'x'}, extra=validate_fn_extra_kw)
assert m == {'f': 'x'}
with pytest.raises(ValidationError) as exc_info:
v.validate_python({'f': 'x', 'extra_field': 123}, extra=validate_fn_extra_kw)
assert exc_info.value.errors(include_url=False) == [
{'type': 'extra_forbidden', 'loc': ('extra_field',), 'msg': 'Extra inputs are not permitted', 'input': 123}
]
@pytest.mark.parametrize(
'config,schema_extra_behavior_kw,validate_fn_extra_kw',
[
(core_schema.CoreConfig(extra_fields_behavior='ignore'), {}, None),
(core_schema.CoreConfig(), {'extra_behavior': 'ignore'}, None),
(None, {'extra_behavior': 'ignore'}, None),
(core_schema.CoreConfig(extra_fields_behavior='forbid'), {'extra_behavior': 'ignore'}, None),
(core_schema.CoreConfig(), {}, None),
(core_schema.CoreConfig(), {'extra_behavior': None}, None),
(None, {'extra_behavior': None}, None),
(core_schema.CoreConfig(extra_fields_behavior='allow'), {}, 'ignore'),
(core_schema.CoreConfig(), {'extra_behavior': 'allow'}, 'ignore'),
(None, {'extra_behavior': 'allow'}, 'ignore'),
(core_schema.CoreConfig(extra_fields_behavior='forbid'), {'extra_behavior': 'allow'}, 'ignore'),
],
)
def test_extra_behavior_ignore(
config: Union[core_schema.CoreConfig, None],
schema_extra_behavior_kw: dict[str, Any],
validate_fn_extra_kw: Union[ExtraBehavior, None],
):
v = SchemaValidator(
core_schema.typed_dict_schema(
{'f': core_schema.typed_dict_field(core_schema.str_schema())}, **schema_extra_behavior_kw
),
config=config,
)
m: dict[str, Any] = v.validate_python({'f': 'x', 'extra_field': 123}, extra=validate_fn_extra_kw)
assert m == {'f': 'x'}
@pytest.mark.xfail(
condition=platform.python_implementation() == 'PyPy', reason='https://foss.heptapod.net/pypy/pypy/-/issues/3899'
)
@pytest.mark.skipif(platform.python_implementation() == 'GraalVM', reason='Cannot reliably trigger GC on GraalPy')
def test_leak_typed_dict():
def fn():
def validate(v, info):
return v
schema = core_schema.with_info_plain_validator_function(validate)
schema = core_schema.typed_dict_schema(
{'f': core_schema.typed_dict_field(schema)}, extra_behavior='allow', extras_schema=schema
)
# If any of the Rust validators don't implement traversal properly,
# there will be an undetectable cycle created by this assignment
# which will keep Defaulted alive
validate.__pydantic_validator__ = SchemaValidator(schema)
return validate
cycle = fn()
ref = weakref.ref(cycle)
assert ref() is not None
del cycle
assert_gc(lambda: ref() is None)
@pytest.mark.parametrize('config_by_alias', [None, True, False])
@pytest.mark.parametrize('config_by_name', [None, True, False])
@pytest.mark.parametrize('runtime_by_alias', [None, True, False])
@pytest.mark.parametrize('runtime_by_name', [None, True, False])
def test_by_alias_and_name_config_interaction(
config_by_alias: Union[bool, None],
config_by_name: Union[bool, None],
runtime_by_alias: Union[bool, None],
runtime_by_name: Union[bool, None],
) -> None:
"""This test reflects the priority that applies for config vs runtime validation alias configuration.
Runtime values take precedence over config values, when set.
By default, by_alias is True and by_name is False.
"""
if config_by_alias is False and config_by_name is False and runtime_by_alias is False and runtime_by_name is False:
pytest.skip("Can't have both by_alias and by_name as effectively False")
core_config = {
**({'validate_by_alias': config_by_alias} if config_by_alias is not None else {}),
**({'validate_by_name': config_by_name} if config_by_name is not None else {}),
}
schema = core_schema.typed_dict_schema(
fields={
'my_field': core_schema.typed_dict_field(schema=core_schema.int_schema(), validation_alias='my_alias'),
},
config=core_schema.CoreConfig(**core_config),
)
s = SchemaValidator(schema)
alias_allowed = next(x for x in (runtime_by_alias, config_by_alias, True) if x is not None)
name_allowed = next(x for x in (runtime_by_name, config_by_name, False) if x is not None)
if alias_allowed:
assert s.validate_python({'my_alias': 1}, by_alias=runtime_by_alias, by_name=runtime_by_name) == {'my_field': 1}
if name_allowed:
assert s.validate_python({'my_field': 1}, by_alias=runtime_by_alias, by_name=runtime_by_name) == {'my_field': 1}
| TestOnError |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/api_endpoints/test_user_endpoint.py | {
"start": 9417,
"end": 15484
} | class ____(TestUserEndpoint):
@pytest.mark.parametrize(
("url", "expected_usernames"),
[
("/fab/v1/users?limit=1", ["test"]),
("/fab/v1/users?limit=2", ["test", "test_no_permissions"]),
(
"/fab/v1/users?offset=5",
[
"TEST_USER4",
"TEST_USER5",
"TEST_USER6",
"TEST_USER7",
"TEST_USER8",
"TEST_USER9",
"TEST_USER10",
],
),
(
"/fab/v1/users?offset=0",
[
"test",
"test_no_permissions",
"TEST_USER1",
"TEST_USER2",
"TEST_USER3",
"TEST_USER4",
"TEST_USER5",
"TEST_USER6",
"TEST_USER7",
"TEST_USER8",
"TEST_USER9",
"TEST_USER10",
],
),
("/fab/v1/users?limit=1&offset=5", ["TEST_USER4"]),
("/fab/v1/users?limit=1&offset=1", ["test_no_permissions"]),
(
"/fab/v1/users?limit=2&offset=2",
["TEST_USER1", "TEST_USER2"],
),
],
)
def test_handle_limit_offset(self, url, expected_usernames):
users = self._create_users(10)
self.session.add_all(users)
self.session.commit()
response = self.client.get(url, environ_overrides={"REMOTE_USER": "test"})
assert response.status_code == 200
assert response.json["total_entries"] == 12
usernames = [user["username"] for user in response.json["users"] if user]
assert usernames == expected_usernames
def test_should_respect_page_size_limit_default(self):
users = self._create_users(200)
self.session.add_all(users)
self.session.commit()
response = self.client.get("/fab/v1/users", environ_overrides={"REMOTE_USER": "test"})
assert response.status_code == 200
# Explicitly add the 2 users on setUp
assert response.json["total_entries"] == 200 + len(["test", "test_no_permissions"])
assert len(response.json["users"]) == 100
def test_should_response_400_with_invalid_order_by(self):
users = self._create_users(2)
self.session.add_all(users)
self.session.commit()
response = self.client.get("/fab/v1/users?order_by=myname", environ_overrides={"REMOTE_USER": "test"})
assert response.status_code == 400
msg = "Ordering with 'myname' is disallowed or the attribute does not exist on the model"
assert response.json["detail"] == msg
def test_limit_of_zero_should_return_default(self):
users = self._create_users(200)
self.session.add_all(users)
self.session.commit()
response = self.client.get("/fab/v1/users?limit=0", environ_overrides={"REMOTE_USER": "test"})
assert response.status_code == 200
# Explicit add the 2 users on setUp
assert response.json["total_entries"] == 200 + len(["test", "test_no_permissions"])
assert len(response.json["users"]) == 50
@conf_vars({("api", "maximum_page_limit"): "150"})
def test_should_return_conf_max_if_req_max_above_conf(self):
users = self._create_users(200)
self.session.add_all(users)
self.session.commit()
response = self.client.get("/fab/v1/users?limit=180", environ_overrides={"REMOTE_USER": "test"})
assert response.status_code == 200
assert len(response.json["users"]) == 150
EXAMPLE_USER_NAME = "example_user"
EXAMPLE_USER_EMAIL = "example_user@example.com"
def _delete_user(**filters):
with create_session() as session:
user = session.scalars(select(User).filter_by(**filters)).first()
if user is None:
return
user.roles = []
session.execute(delete(User).filter_by(**filters))
@pytest.fixture
def autoclean_username():
_delete_user(username=EXAMPLE_USER_NAME)
yield EXAMPLE_USER_NAME
_delete_user(username=EXAMPLE_USER_NAME)
@pytest.fixture
def autoclean_email():
_delete_user(email=EXAMPLE_USER_EMAIL)
yield EXAMPLE_USER_EMAIL
_delete_user(email=EXAMPLE_USER_EMAIL)
@pytest.fixture
def user_with_same_username(configured_app, autoclean_username):
user = create_user(
configured_app,
username=autoclean_username,
email="another_user@example.com",
role_name="TestNoPermissions",
)
assert user, f"failed to create user '{autoclean_username} <another_user@example.com>'"
return user
@pytest.fixture
def user_with_same_email(configured_app, autoclean_email):
user = create_user(
configured_app,
username="another_user",
email=autoclean_email,
role_name="TestNoPermissions",
)
assert user, f"failed to create user 'another_user <{autoclean_email}>'"
return user
@pytest.fixture
def user_different(configured_app):
username = "another_user"
email = "another_user@example.com"
_delete_user(username=username, email=email)
user = create_user(configured_app, username=username, email=email, role_name="TestNoPermissions")
assert user, "failed to create user 'another_user <another_user@example.com>'"
yield user
_delete_user(username=username, email=email)
@pytest.fixture
def autoclean_user_payload(autoclean_username, autoclean_email):
return {
"username": autoclean_username,
"password": "resutsop",
"email": autoclean_email,
"first_name": "Tester",
"last_name": "",
}
@pytest.fixture
def autoclean_admin_user(configured_app, autoclean_user_payload):
security_manager = configured_app.appbuilder.sm
return security_manager.add_user(
role=security_manager.find_role("Admin"),
**autoclean_user_payload,
)
| TestGetUsersPagination |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 42613,
"end": 66044
} | class ____(test.TestCase):
def _DtypesToTest(self, use_gpu):
# double datatype is currently not supported for convolution ops
# on the ROCm platform
optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64]
if use_gpu and not test_util.GpuSupportsHalfMatMulAndConv():
return [dtypes.float32] + optional_float64
else:
# It is important that float32 comes before float16 here,
# as we will be using its gradients as reference for fp16 gradients.
return [dtypes.float32, dtypes.float16] + optional_float64
def _CreateNumpyTensor(self, shape):
total_size = 1
for s in shape:
total_size *= s
return np.arange(1, total_size + 1, dtype=np.float32).reshape(shape)
def _SetupValuesForDevice(
self,
tensor_in_sizes,
filter_in_sizes,
dilations,
strides,
padding,
data_format,
dtype,
use_gpu,
):
"""Verifies the output values of the convolution function.
Args:
tensor_in_sizes: Input tensor dimensions in [batch, input_rows,
input_cols, input_depth].
filter_in_sizes: Filter tensor dimensions in [kernel_rows, kernel_cols,
input_depth, output_depth].
dilations: Dilated rate: [col_dilation, row_dilation]
strides: Stride: [col_stride, row_stride]
padding: Padding type.
data_format: Format of the data tensors.
dtype: Data type for inputs and outputs.
use_gpu: True if the operations should be run on GPU
Returns:
Symbolic tensor value that can be used to execute the computation
"""
x1 = self._CreateNumpyTensor(tensor_in_sizes)
x2 = self._CreateNumpyTensor(filter_in_sizes)
with test_util.device(use_gpu):
t1 = constant_op.constant(x1, shape=tensor_in_sizes, dtype=dtype)
t2 = constant_op.constant(x2, shape=filter_in_sizes, dtype=dtype)
strides = [1] + strides + [1]
dilations = [1] + dilations + [1]
if isinstance(padding, (list, tuple)):
padding = [(0, 0)] + padding + [(0, 0)]
if data_format == "NCHW":
t1 = test_util.NHWCToNCHW(t1)
strides = test_util.NHWCToNCHW(strides)
dilations = test_util.NHWCToNCHW(dilations)
if isinstance(padding, (list, tuple)):
padding = test_util.NHWCToNCHW(padding)
conv = nn_ops.conv2d(
t1,
t2,
dilations=dilations,
strides=strides,
padding=padding,
data_format=data_format,
)
self.assertEqual(conv.dtype, dtype)
if data_format == "NCHW":
conv = test_util.NCHWToNHWC(conv)
return conv
def _CompareFwdValues(
self, tensor_in_sizes, filter_in_sizes, conv_strides, padding
):
"""Verifies that CPU and GPU produce the same values.
Args:
tensor_in_sizes: Input tensor dimensions in [batch, input_rows,
input_cols, input_depth].
filter_in_sizes: Filter tensor dimensions in [kernel_rows, kernel_cols,
input_depth, output_depth].
conv_strides: [row_stride, col_stride] for the convolution;
padding: Padding type.
"""
x1 = np.random.rand(*tensor_in_sizes).astype(np.float32)
x2 = np.random.rand(*filter_in_sizes).astype(np.float32)
def _setup_val(data_format, use_gpu):
with test_util.device(use_gpu):
t1 = constant_op.constant(x1, shape=tensor_in_sizes)
t2 = constant_op.constant(x2, shape=filter_in_sizes)
strides = [1] + conv_strides + [1]
if data_format == "NCHW":
t1 = test_util.NHWCToNCHW(t1)
strides = test_util.NHWCToNCHW(strides)
conv = nn_ops.conv2d(
t1, t2, strides=strides, padding=padding, data_format=data_format
)
if data_format == "NCHW":
conv = test_util.NCHWToNHWC(conv)
return conv
tensors = []
for data_format, use_gpu in get_test_configs():
tensors.append(_setup_val(data_format, use_gpu))
values = self.evaluate(tensors)
for i in range(1, len(values)):
self.assertAllClose(values[0], values[i], rtol=1e-3, atol=1e-3)
def _ComputeReferenceDilatedConv(
self,
tensor_in_sizes,
filter_in_sizes,
stride,
dilation,
padding,
data_format,
use_gpu,
):
x1 = self._CreateNumpyTensor(tensor_in_sizes)
x2 = self._CreateNumpyTensor(filter_in_sizes)
with test_util.device(use_gpu):
t1 = constant_op.constant(x1, shape=tensor_in_sizes)
t2 = constant_op.constant(x2, shape=filter_in_sizes)
if isinstance(stride, collections_abc.Iterable):
strides = list(stride)
else:
strides = [stride, stride]
if data_format == "NCHW":
t1 = test_util.NHWCToNCHW(t1)
full_strides = [1, 1] + strides
full_dilation = [1, 1] + dilation
else:
full_strides = [1] + strides + [1]
full_dilation = [1] + dilation + [1]
expected = nn_ops.convolution(
t1,
t2,
padding=padding,
strides=strides,
dilation_rate=dilation,
data_format=data_format,
)
computed = nn_ops.conv2d(
t1,
t2,
strides=full_strides,
dilations=full_dilation,
padding=padding,
data_format=data_format,
)
if data_format == "NCHW":
expected = test_util.NCHWToNHWC(expected)
computed = test_util.NCHWToNHWC(computed)
return expected, computed
def _VerifyDilatedConvValues(
self,
tensor_in_sizes,
filter_in_sizes,
strides,
padding,
dilations,
rtol=1e-4,
):
expected_results = []
computed_results = []
for data_format, use_gpu in get_test_configs():
expected, computed = self._ComputeReferenceDilatedConv(
tensor_in_sizes,
filter_in_sizes,
strides,
dilations,
padding,
data_format,
use_gpu,
)
expected_results.append(expected)
computed_results.append(computed)
tolerance = 1e-2 if use_gpu else 1e-5
expected_values = self.evaluate(expected_results)
computed_values = self.evaluate(computed_results)
for e_value, c_value in zip(expected_values, computed_values):
tf_logging.debug("expected = %s", e_value)
tf_logging.debug("actual = %s", c_value)
self.assertAllClose(
e_value.flatten(), c_value.flatten(), atol=tolerance, rtol=rtol
)
def _VerifyValues(
self,
tensor_in_sizes,
filter_in_sizes,
strides,
padding,
expected,
dilations=(1, 1),
gpu_only=False,
test_grappler_layout_optimizer=False,
tol=1e-5,
fp16_tol=1e-3,
):
if gpu_only and not test.is_gpu_available(cuda_only=True):
return
tensors = []
dilations = list(dilations)
for data_format, use_gpu in get_test_configs():
if gpu_only and not use_gpu:
continue
dtypes_to_test = self._DtypesToTest(use_gpu)
if not test_grappler_layout_optimizer and data_format == "NHWC":
dtypes_to_test.append(dtypes.int32)
for dtype in dtypes_to_test:
result = self._SetupValuesForDevice(
tensor_in_sizes,
filter_in_sizes,
dilations,
strides,
padding,
data_format,
dtype,
use_gpu=use_gpu,
)
if test_grappler_layout_optimizer and data_format == "NHWC" and use_gpu:
# Grappler's layout optimizer will not optimize a fetch node, so
# this identity allows Grappler to optimize the Conv2D node.
result = array_ops.identity(result)
tensors.append(result)
values = self.evaluate(tensors)
for i in range(len(tensors)):
conv = tensors[i]
value = values[i]
tf_logging.debug("expected = %s", expected)
tf_logging.debug("actual = %s", value)
tol_to_use = fp16_tol if value.dtype == np.float16 else tol
if np.issubdtype(value.dtype, np.integer):
self.assertAllEqual(np.rint(expected), np.ravel(value))
else:
self.assertAllClose(
expected, np.ravel(value), atol=tol_to_use, rtol=tol_to_use
)
self.assertShapeEqual(value, conv)
self.assertEqual(value.dtype, conv.dtype.as_numpy_dtype)
def _VerifyExplicitPaddings(
self,
tensor_in_sizes,
filter_in_sizes,
strides,
padding,
dilations=(1, 1),
test_grappler_layout_optimizer=False,
tol=1e-5,
fp16_tol=1e-3,
):
"""Verifies Conv2D with explicit padding generates correct values.
It does this by comparing with Conv2D without explicit padding. This
function assumes Conv2D without explicit padding works correctly.
Args:
tensor_in_sizes: Input tensor dimensions in [batch, input_rows,
input_cols, input_depth].
filter_in_sizes: Filter tensor dimensions in [kernel_rows, kernel_cols,
input_depth, output_depth].
strides: [row_stride, col_stride] for the convolution;
padding: Explicit padding amounts.
dilations: Dilation values
test_grappler_layout_optimizer: If True, allow the Grappler layout
optimizer to run, which turns NHWC Conv2Ds on the GPU to NCHW Conv2Ds.
tol: The absolute and relative tolerance for non-fp16 dtypes.
fp16_tol: The absolute and relative tolerance for fp16.
"""
input_tensor = self._CreateNumpyTensor(tensor_in_sizes)
filter_tensor = self._CreateNumpyTensor(filter_in_sizes)
input_tensor = array_ops.pad(input_tensor, [(0, 0)] + padding + [(0, 0)])
dilations = list(dilations)
conv2d_result = nn_ops.conv2d(
input_tensor,
filter_tensor,
[1] + list(strides) + [1],
"VALID",
dilations=[1] + dilations + [1],
)
expected = list(self.evaluate(array_ops.reshape(conv2d_result, [-1])))
self._VerifyValues(
tensor_in_sizes,
filter_in_sizes,
strides,
padding,
expected,
dilations,
test_grappler_layout_optimizer=test_grappler_layout_optimizer,
tol=tol,
fp16_tol=fp16_tol,
)
@test_util.run_in_graph_and_eager_modes
def testConv2D1x1Filter(self):
expected_output = [
30.0,
36.0,
42.0,
66.0,
81.0,
96.0,
102.0,
126.0,
150.0,
138.0,
171.0,
204.0,
174.0,
216.0,
258.0,
210.0,
261.0,
312.0,
]
self._VerifyValues(
tensor_in_sizes=[1, 2, 3, 3],
filter_in_sizes=[1, 1, 3, 3],
strides=[1, 1],
padding="VALID",
expected=expected_output,
)
@test_util.run_in_graph_and_eager_modes
def testConv2D2x2Filter2x1Dilation(self):
self._VerifyDilatedConvValues(
tensor_in_sizes=[1, 4, 4, 1],
filter_in_sizes=[2, 2, 1, 1],
strides=[1, 1],
dilations=[2, 1],
padding="VALID",
)
@test_util.run_in_graph_and_eager_modes
def testConv2DEmpty(self):
expected_output = []
self._VerifyValues(
tensor_in_sizes=[0, 2, 3, 3],
filter_in_sizes=[1, 1, 3, 3],
strides=[1, 1],
padding="VALID",
expected=expected_output,
)
@test_util.run_in_graph_and_eager_modes
def testConv2DEmptyDilation(self):
self._VerifyDilatedConvValues(
tensor_in_sizes=[0, 2, 3, 3],
filter_in_sizes=[1, 1, 3, 3],
strides=[1, 1],
dilations=[2, 1],
padding="VALID",
)
@test_util.run_in_graph_and_eager_modes
def testConv2D2x2Filter(self):
# The outputs are computed using third_party/py/IPython/notebook.
expected_output = [2271.0, 2367.0, 2463.0, 2901.0, 3033.0, 3165.0]
self._VerifyValues(
tensor_in_sizes=[1, 2, 3, 3],
filter_in_sizes=[2, 2, 3, 3],
strides=[1, 1],
padding="VALID",
expected=expected_output,
)
@test_util.run_in_graph_and_eager_modes
def testConv2D2x2FilterDilation(self):
self._VerifyDilatedConvValues(
tensor_in_sizes=[1, 2, 3, 3],
filter_in_sizes=[2, 2, 3, 3],
strides=[1, 1],
dilations=[1, 2],
padding="VALID",
)
@test_util.run_in_graph_and_eager_modes
def testConv2D1x2Filter(self):
# The outputs are computed using third_party/py/IPython/notebook.
expected_output = [
231.0,
252.0,
273.0,
384.0,
423.0,
462.0,
690.0,
765.0,
840.0,
843.0,
936.0,
1029.0,
]
self._VerifyValues(
tensor_in_sizes=[1, 2, 3, 3],
filter_in_sizes=[1, 2, 3, 3],
strides=[1, 1],
padding="VALID",
expected=expected_output,
)
@test_util.run_in_graph_and_eager_modes
def testConv2D1x2FilterDilation(self):
self._VerifyDilatedConvValues(
tensor_in_sizes=[1, 2, 3, 3],
filter_in_sizes=[1, 2, 3, 3],
strides=[1, 1],
dilations=[2, 1],
padding="VALID",
)
@test_util.run_in_graph_and_eager_modes
def testConv2D2x2FilterStride2(self):
expected_output = [2271.0, 2367.0, 2463.0]
self._VerifyValues(
tensor_in_sizes=[1, 2, 3, 3],
filter_in_sizes=[2, 2, 3, 3],
strides=[2, 2],
padding="VALID",
expected=expected_output,
)
@test_util.run_in_graph_and_eager_modes
def testConv2D2x2FilterStride2Same(self):
expected_output = [2271.0, 2367.0, 2463.0, 1230.0, 1305.0, 1380.0]
self._VerifyValues(
tensor_in_sizes=[1, 2, 3, 3],
filter_in_sizes=[2, 2, 3, 3],
strides=[2, 2],
padding="SAME",
expected=expected_output,
)
@test_util.run_in_graph_and_eager_modes
def testConv2D2x2FilterStride1x2(self):
expected_output = [58.0, 78.0, 98.0, 118.0, 138.0, 158.0]
self._VerifyValues(
tensor_in_sizes=[1, 3, 6, 1],
filter_in_sizes=[2, 2, 1, 1],
strides=[1, 2],
padding="VALID",
expected=expected_output,
)
@test_util.run_in_graph_and_eager_modes
def testConv2DKernelSmallerThanStrideValid(self):
expected_output = [65, 95, 275, 305]
self._VerifyValues(
tensor_in_sizes=[1, 7, 7, 1],
filter_in_sizes=[2, 2, 1, 1],
strides=[3, 3],
padding="VALID",
expected=expected_output,
)
@test_util.run_in_graph_and_eager_modes
def testConv2DKernelSmallerThanStrideSame(self):
self._VerifyValues(
tensor_in_sizes=[1, 3, 3, 1],
filter_in_sizes=[1, 1, 1, 1],
strides=[2, 2],
padding="SAME",
expected=[1, 3, 7, 9],
)
self._VerifyValues(
tensor_in_sizes=[1, 4, 4, 1],
filter_in_sizes=[1, 1, 1, 1],
strides=[2, 2],
padding="SAME",
expected=[1, 3, 9, 11],
)
self._VerifyValues(
tensor_in_sizes=[1, 4, 4, 1],
filter_in_sizes=[2, 2, 1, 1],
strides=[3, 3],
padding="SAME",
expected=[44, 28, 41, 16],
)
@test_util.run_in_graph_and_eager_modes
def testConv2DKernelSizeMatchesInputSize(self):
self._VerifyValues(
tensor_in_sizes=[1, 2, 2, 1],
filter_in_sizes=[2, 2, 1, 2],
strides=[1, 1],
padding="VALID",
expected=[50, 60],
)
@test_util.run_in_graph_and_eager_modes
def testConv2DKernelSizeMatchesInputSizeDilation(self):
self._VerifyDilatedConvValues(
tensor_in_sizes=[1, 3, 3, 1],
filter_in_sizes=[2, 2, 1, 2],
strides=[1, 1],
dilations=[2, 2],
padding="VALID",
)
@test_util.run_in_graph_and_eager_modes()
def testConv2D0x0Padding(self):
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 3, 3],
filter_in_sizes=[2, 2, 3, 3],
strides=[1, 1],
padding=[[0, 0], [0, 0]],
)
self._VerifyExplicitPaddings(
tensor_in_sizes=[3, 4, 3, 2],
filter_in_sizes=[1, 1, 2, 1],
strides=[2, 2],
padding=[[0, 0], [0, 0]],
)
@test_util.run_in_graph_and_eager_modes()
def testConv2D1x1Padding(self):
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 3, 2],
filter_in_sizes=[2, 2, 2, 2],
strides=[1, 1],
padding=[[1, 1], [1, 1]],
)
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 2, 1],
filter_in_sizes=[1, 1, 1, 2],
strides=[1, 1],
padding=[[1, 1], [1, 1]],
)
@test_util.run_in_graph_and_eager_modes()
def testConv2D2x2Padding(self):
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 1, 2],
filter_in_sizes=[2, 1, 2, 1],
strides=[1, 1],
padding=[[2, 2], [2, 2]],
)
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 1, 2],
filter_in_sizes=[1, 1, 2, 1],
strides=[2, 1],
padding=[[2, 2], [2, 2]],
)
@test_util.run_in_graph_and_eager_modes()
def testConv2DOnlyTopRightPadding(self):
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 3, 3],
filter_in_sizes=[2, 2, 3, 2],
strides=[1, 1],
padding=[[1, 0], [0, 2]],
tol=5e-5,
)
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 4, 2],
filter_in_sizes=[2, 2, 2, 2],
strides=[1, 3],
padding=[[1, 0], [0, 2]],
)
@test_util.run_in_graph_and_eager_modes()
def testConv2DLotsPadding(self):
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 1, 1, 3],
filter_in_sizes=[2, 2, 3, 3],
strides=[1, 1],
padding=[[3, 4], [4, 2]],
)
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 1, 1],
filter_in_sizes=[2, 2, 1, 3],
strides=[2, 1],
padding=[[3, 4], [4, 2]],
)
@test_util.run_in_graph_and_eager_modes()
def testConv2DExplicitPaddingWithDilations(self):
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 3, 2, 1],
filter_in_sizes=[1, 2, 1, 2],
strides=[1, 1],
padding=[[1, 0], [0, 1]],
dilations=[2, 1],
)
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 3, 2],
filter_in_sizes=[3, 2, 2, 1],
strides=[1, 1],
padding=[[2, 1], [1, 2]],
dilations=[2, 3],
)
def testConv2DExplicitPaddingWithLayoutOptimizer(self):
# Test with Grappler's layout optimizer, to ensure the layout optimizer
# handles explicit padding correctly.
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 3, 2, 1],
filter_in_sizes=[1, 2, 1, 2],
strides=[1, 1],
padding=[[1, 0], [0, 1]],
dilations=[2, 1],
test_grappler_layout_optimizer=True,
)
self._VerifyExplicitPaddings(
tensor_in_sizes=[1, 2, 3, 2],
filter_in_sizes=[3, 2, 2, 1],
strides=[1, 1],
padding=[[2, 1], [1, 2]],
dilations=[2, 3],
test_grappler_layout_optimizer=True,
)
# Testing for backprops
def _RunAndVerifyBackpropInput(
self,
input_sizes,
filter_sizes,
output_sizes,
strides,
padding,
expected,
data_format,
use_gpu,
err,
dilations=(1, 1),
):
if use_gpu and not test.is_gpu_available(cuda_only=True):
return
x1 = self._CreateNumpyTensor(filter_sizes)
x2 = self._CreateNumpyTensor(output_sizes)
dilations = list(dilations)
with test_util.device(use_gpu):
if data_format == "NCHW":
input_sizes = test_util.NHWCToNCHW(input_sizes)
t0 = constant_op.constant(input_sizes, shape=[len(input_sizes)])
t1 = constant_op.constant(x1, shape=filter_sizes)
t2 = constant_op.constant(x2, shape=output_sizes)
strides = [1] + strides + [1]
dilations = [1] + dilations + [1]
if isinstance(padding, (list, tuple)):
padding = [(0, 0)] + padding + [(0, 0)]
if data_format == "NCHW":
t2 = test_util.NHWCToNCHW(t2)
strides = test_util.NHWCToNCHW(strides)
dilations = test_util.NHWCToNCHW(dilations)
if isinstance(padding, (list, tuple)):
padding = test_util.NHWCToNCHW((padding))
conv = nn_ops.conv2d_backprop_input(
t0,
t1,
t2,
strides=strides,
padding=padding,
data_format=data_format,
dilations=dilations,
)
if data_format == "NCHW":
conv = test_util.NCHWToNHWC(conv)
# "values" consists of two tensors for two backprops
value = self.evaluate(conv)
self.assertShapeEqual(value, conv)
tf_logging.debug("expected = %s", expected)
tf_logging.debug("actual = %s", value)
self.assertAllCloseAccordingToType(expected, value.flatten(), atol=1e-5)
def _CompareBackpropInput(
self, input_sizes, filter_sizes, output_sizes, conv_strides, padding
):
x1 = np.random.rand(*filter_sizes).astype(np.float32)
x2 = np.random.rand(*output_sizes).astype(np.float32)
def _get_val(data_format, use_gpu):
with test_util.device(use_gpu):
if data_format == "NCHW":
new_input_sizes = test_util.NHWCToNCHW(input_sizes)
else:
new_input_sizes = input_sizes
t0 = constant_op.constant(new_input_sizes, shape=[len(new_input_sizes)])
t1 = constant_op.constant(x1, shape=filter_sizes)
t2 = constant_op.constant(x2, shape=output_sizes)
strides = [1] + conv_strides + [1]
if data_format == "NCHW":
t2 = test_util.NHWCToNCHW(t2)
strides = test_util.NHWCToNCHW(strides)
conv = nn_ops.conv2d_backprop_input(
t0,
t1,
t2,
strides=strides,
padding=padding,
data_format=data_format,
)
if data_format == "NCHW":
conv = test_util.NCHWToNHWC(conv)
ret = self.evaluate(conv)
self.assertShapeEqual(ret, conv)
return ret
values = []
for data_format, use_gpu in get_test_configs():
values.append(_get_val(data_format, use_gpu))
for i in range(1, len(values)):
self.assertAllClose(values[0], values[i], rtol=1e-2, atol=1e-2)
@test_util.run_in_graph_and_eager_modes
def testConv2DEmptyBackpropInput(self):
expected_output = []
for data_format, use_gpu in get_test_configs():
self._RunAndVerifyBackpropInput(
input_sizes=[0, 2, 3, 1],
filter_sizes=[2, 2, 1, 1],
output_sizes=[0, 1, 2, 1],
strides=[1, 1],
padding="VALID",
expected=expected_output,
data_format=data_format,
use_gpu=use_gpu,
err=1e-5,
)
@test_util.run_in_graph_and_eager_modes
def testConv2DStrideTwoFilterOneSameBackpropInput(self):
expected_output = [
1.0,
0.0,
2.0,
0.0,
0.0,
0.0,
0.0,
0.0,
3.0,
0.0,
4.0,
0.0,
0.0,
0.0,
0.0,
0.0,
]
for data_format, use_gpu in get_test_configs():
self._RunAndVerifyBackpropInput(
input_sizes=[1, 4, 4, 1],
filter_sizes=[1, 1, 1, 1],
output_sizes=[1, 2, 2, 1],
strides=[2, 2],
padding="SAME",
expected=expected_output,
data_format=data_format,
use_gpu=use_gpu,
err=1e-5,
)
| Conv2DTest |
python | gevent__gevent | src/gevent/libuv/watcher.py | {
"start": 525,
"end": 1915
} | class ____(dict):
__slots__ = ()
def remove(self, obj):
try:
del self[obj]
except KeyError: # pragma: no cover
# This has been seen to happen if the module is executed twice
# and so the callback doesn't match the storage seen by watcher objects.
print(
'gevent error: Unable to remove closing watcher from keepaliveset. '
'Has the module state been corrupted or executed more than once?',
file=sys.stderr
)
_closing_watchers = _ClosingWatchers()
# In debug mode, it would be nice to be able to clear the memory of
# the watcher (its size determined by
# libuv.uv_handle_size(ffi_watcher.type)) using memset so that if we
# are using it after it's supposedly been closed and deleted, we'd
# catch it sooner. BUT doing so breaks test__threadpool. We get errors
# about `pthread_mutex_lock[3]: Invalid argument` (and sometimes we
# crash) suggesting either that we're writing on memory that doesn't
# belong to us, somehow, or that we haven't actually lost all
# references...
_uv_close_callback = ffi.def_extern(name='_uv_close_callback')(
_closing_watchers.remove
)
_events = [(libuv.UV_READABLE, "READ"),
(libuv.UV_WRITABLE, "WRITE")]
def _events_to_str(events): # export
return _base.events_to_str(events, _events)
| _ClosingWatchers |
python | neetcode-gh__leetcode | python/0215-kth-largest-element-in-an-array.py | {
"start": 160,
"end": 492
} | class ____:
def findKthLargest(self, nums: List[int], k: int) -> int:
heapify(nums)
while len(nums) > k:
heappop(nums)
return nums[0]
# Solution: Sorting
# Time Complexity:
# - Best Case: O(n)
# - Average Case: O(n*log(n))
# - Worst Case:O(n*log(n))
# Extra Space Complexity: O(n)
| Solution |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 56673,
"end": 57108
} | class ____(themeable):
"""
Justification of legends placed on the left
Parameters
----------
theme_element : Literal["bottom", "center", "top"] | float
How to justify the entire group with 1 or more guides. i.e. How
to slide the legend along the left column.
If a float, it should be in the range `[0, 1]`, where
`0` is `"bottom"` and `1` is `"top"`.
"""
| legend_justification_left |
python | ionelmc__pytest-benchmark | src/pytest_benchmark/table.py | {
"start": 341,
"end": 7290
} | class ____:
def __init__(self, columns, sort, histogram, name_format, logger, scale_unit):
self.columns = columns
self.sort = sort
self.histogram = histogram
self.name_format = name_format
self.logger = logger
self.scale_unit = scale_unit
def display(self, tr, groups, progress_reporter=report_progress):
tr.write_line('')
report_online_progress(progress_reporter, tr, 'Computing stats ...')
for line, (group, benchmarks) in progress_reporter(groups, tr, 'Computing stats ... group {pos}/{total}'):
benchmarks = sorted(benchmarks, key=operator.itemgetter(self.sort))
for bench in benchmarks:
bench['name'] = self.name_format(bench)
worst = {}
best = {}
solo = len(benchmarks) == 1
for line1, prop in progress_reporter(
('min', 'max', 'mean', 'median', 'iqr', 'stddev', 'ops'), tr, '{line}: {value}', line=line
):
if prop == 'ops':
worst[prop] = min(bench[prop] for _, bench in progress_reporter(benchmarks, tr, '{line} ({pos}/{total})', line=line1))
best[prop] = max(bench[prop] for _, bench in progress_reporter(benchmarks, tr, '{line} ({pos}/{total})', line=line1))
else:
worst[prop] = max(bench[prop] for _, bench in progress_reporter(benchmarks, tr, '{line} ({pos}/{total})', line=line1))
best[prop] = min(bench[prop] for _, bench in progress_reporter(benchmarks, tr, '{line} ({pos}/{total})', line=line1))
for line1, prop in progress_reporter(('outliers', 'rounds', 'iterations'), tr, '{line}: {value}', line=line):
worst[prop] = max(
benchmark[prop] for _, benchmark in progress_reporter(benchmarks, tr, '{line} ({pos}/{total})', line=line1)
)
unit, adjustment = self.scale_unit(unit='seconds', benchmarks=benchmarks, best=best, worst=worst, sort=self.sort)
ops_unit, ops_adjustment = self.scale_unit(unit='operations', benchmarks=benchmarks, best=best, worst=worst, sort=self.sort)
labels = {
'name': f'Name (time in {unit}s)',
'min': 'Min',
'max': 'Max',
'mean': 'Mean',
'stddev': 'StdDev',
'rounds': 'Rounds',
'iterations': 'Iterations',
'iqr': 'IQR',
'median': 'Median',
'outliers': 'Outliers',
'ops': f'OPS ({ops_unit}ops/s)' if ops_unit else 'OPS',
}
widths = {
'name': 3 + max(len(labels['name']), max(len(benchmark['name']) for benchmark in benchmarks)),
'rounds': 2 + max(len(labels['rounds']), len(str(worst['rounds']))),
'iterations': 2 + max(len(labels['iterations']), len(str(worst['iterations']))),
'outliers': 2 + max(len(labels['outliers']), len(str(worst['outliers']))),
'ops': 2 + max(len(labels['ops']), len(NUMBER_FMT.format(best['ops'] * ops_adjustment))),
}
for prop in 'min', 'max', 'mean', 'stddev', 'median', 'iqr':
widths[prop] = 2 + max(len(labels[prop]), max(len(NUMBER_FMT.format(bench[prop] * adjustment)) for bench in benchmarks))
rpadding = 0 if solo else 10
labels_line = labels['name'].ljust(widths['name']) + ''.join(
labels[prop].rjust(widths[prop]) + (' ' * rpadding if prop not in ['outliers', 'rounds', 'iterations'] else '')
for prop in self.columns
)
report_online_progress(progress_reporter, tr, '')
tr.write_line(
' benchmark{name}: {count} tests '.format(
count=len(benchmarks),
name='' if group is None else f' {group!r}',
).center(len(labels_line), '-'),
yellow=True,
)
tr.write_line(labels_line)
tr.write_line('-' * len(labels_line), yellow=True)
for bench in benchmarks:
has_error = bench.get('has_error')
tr.write(bench['name'].ljust(widths['name']), red=has_error, invert=has_error)
for prop in self.columns:
if prop in ('min', 'max', 'mean', 'stddev', 'median', 'iqr'):
tr.write(
ALIGNED_NUMBER_FMT.format(
bench[prop] * adjustment, widths[prop], compute_baseline_scale(best[prop], bench[prop], rpadding), rpadding
),
green=not solo and bench[prop] == best.get(prop),
red=not solo and bench[prop] == worst.get(prop),
bold=True,
)
elif prop == 'ops':
tr.write(
ALIGNED_NUMBER_FMT.format(
bench[prop] * ops_adjustment,
widths[prop],
compute_baseline_scale(best[prop], bench[prop], rpadding),
rpadding,
),
green=not solo and bench[prop] == best.get(prop),
red=not solo and bench[prop] == worst.get(prop),
bold=True,
)
else:
tr.write('{0:>{1}}'.format(bench[prop], widths[prop]))
tr.write('\n')
tr.write_line('-' * len(labels_line), yellow=True)
tr.write_line('')
if self.histogram:
from .histogram import make_histogram # noqa: PLC0415
if len(benchmarks) > 75:
self.logger.warning(f'Group {group!r} has too many benchmarks. Only plotting 50 benchmarks.')
benchmarks = benchmarks[:75]
output_file = make_histogram(self.histogram, group, benchmarks, unit, adjustment)
self.logger.info(f'Generated histogram: {output_file}', bold=True)
tr.write_line('Legend:')
tr.write_line(' Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd Quartile.')
tr.write_line(' OPS: Operations Per Second, computed as 1 / Mean')
def compute_baseline_scale(baseline, value, width):
if not width:
return ''
if value == baseline:
return ' (1.0)'.ljust(width)
scale = abs(value / baseline) if baseline else float('inf')
if scale > 1000:
if isinf(scale):
return ' (inf)'.ljust(width)
else:
return ' (>1000.0)'.ljust(width)
else:
return f' ({scale:.2f})'.ljust(width)
| TableResults |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 355,
"end": 488
} | class ____(AutoEnum):
"""Operators for combining filter criteria."""
and_ = AutoEnum.auto()
or_ = AutoEnum.auto()
| Operator |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/types.py | {
"start": 3957,
"end": 4193
} | class ____(sqltypes.TypeEngine[str]):
"""Provide the PostgreSQL REGCONFIG type.
.. versionadded:: 2.0.0rc1
"""
__visit_name__ = "REGCONFIG"
operator_classes = OperatorClass.BASE | OperatorClass.COMPARISON
| REGCONFIG |
python | django__django | tests/model_fields/test_filefield.py | {
"start": 489,
"end": 8232
} | class ____(TestCase):
def test_clearable(self):
"""
FileField.save_form_data() will clear its instance attribute value if
passed False.
"""
d = Document(myfile="something.txt")
self.assertEqual(d.myfile, "something.txt")
field = d._meta.get_field("myfile")
field.save_form_data(d, False)
self.assertEqual(d.myfile, "")
def test_unchanged(self):
"""
FileField.save_form_data() considers None to mean "no change" rather
than "clear".
"""
d = Document(myfile="something.txt")
self.assertEqual(d.myfile, "something.txt")
field = d._meta.get_field("myfile")
field.save_form_data(d, None)
self.assertEqual(d.myfile, "something.txt")
def test_changed(self):
"""
FileField.save_form_data(), if passed a truthy value, updates its
instance attribute.
"""
d = Document(myfile="something.txt")
self.assertEqual(d.myfile, "something.txt")
field = d._meta.get_field("myfile")
field.save_form_data(d, "else.txt")
self.assertEqual(d.myfile, "else.txt")
def test_delete_when_file_unset(self):
"""
Calling delete on an unset FileField should not call the file deletion
process, but fail silently (#20660).
"""
d = Document()
d.myfile.delete()
def test_refresh_from_db(self):
d = Document.objects.create(myfile="something.txt")
d.refresh_from_db()
self.assertIs(d.myfile.instance, d)
@unittest.skipIf(sys.platform == "win32", "Crashes with OSError on Windows.")
def test_save_without_name(self):
with tempfile.NamedTemporaryFile(suffix=".txt") as tmp:
document = Document.objects.create(myfile="something.txt")
document.myfile = File(tmp)
msg = f"Detected path traversal attempt in '{tmp.name}'"
with self.assertRaisesMessage(SuspiciousFileOperation, msg):
document.save()
def test_save_content_file_without_name(self):
d = Document()
d.myfile = ContentFile(b"")
msg = "File for myfile must have the name attribute specified to be saved."
with self.assertRaisesMessage(FieldError, msg) as cm:
d.save()
self.assertEqual(
cm.exception.__notes__, ["Pass a 'name' argument to ContentFile."]
)
def test_delete_content_file(self):
file = ContentFile(b"", name="foo")
d = Document.objects.create(myfile=file)
d.myfile.delete()
self.assertIsNone(d.myfile.name)
msg = "The 'myfile' attribute has no file associated with it."
with self.assertRaisesMessage(ValueError, msg):
getattr(d.myfile, "file")
def test_defer(self):
Document.objects.create(myfile="something.txt")
self.assertEqual(Document.objects.defer("myfile")[0].myfile, "something.txt")
def test_unique_when_same_filename(self):
"""
A FileField with unique=True shouldn't allow two instances with the
same name to be saved.
"""
Document.objects.create(myfile="something.txt")
with self.assertRaises(IntegrityError):
Document.objects.create(myfile="something.txt")
@unittest.skipIf(
sys.platform == "win32", "Windows doesn't support moving open files."
)
# The file's source and destination must be on the same filesystem.
@override_settings(MEDIA_ROOT=temp.gettempdir())
def test_move_temporary_file(self):
"""
The temporary uploaded file is moved rather than copied to the
destination.
"""
with TemporaryUploadedFile(
"something.txt", "text/plain", 0, "UTF-8"
) as tmp_file:
tmp_file_path = tmp_file.temporary_file_path()
Document.objects.create(myfile=tmp_file)
self.assertFalse(
os.path.exists(tmp_file_path), "Temporary file still exists"
)
def test_open_returns_self(self):
"""
FieldField.open() returns self so it can be used as a context manager.
"""
d = Document.objects.create(myfile="something.txt")
# Replace the FileField's file with an in-memory ContentFile, so that
# open() doesn't write to disk.
d.myfile.file = ContentFile(b"", name="bla")
self.assertEqual(d.myfile, d.myfile.open())
def test_media_root_pathlib(self):
with tempfile.TemporaryDirectory() as tmp_dir:
with override_settings(MEDIA_ROOT=Path(tmp_dir)):
with TemporaryUploadedFile(
"foo.txt", "text/plain", 1, "utf-8"
) as tmp_file:
document = Document.objects.create(myfile=tmp_file)
self.assertIs(
document.myfile.storage.exists(
os.path.join("unused", "foo.txt")
),
True,
)
def test_pickle(self):
with tempfile.TemporaryDirectory() as tmp_dir:
with override_settings(MEDIA_ROOT=Path(tmp_dir)):
with open(__file__, "rb") as fp:
file1 = File(fp, name="test_file.py")
document = Document(myfile="test_file.py")
document.myfile.save("test_file.py", file1)
try:
dump = pickle.dumps(document)
loaded_document = pickle.loads(dump)
self.assertEqual(document.myfile, loaded_document.myfile)
self.assertEqual(
document.myfile.url,
loaded_document.myfile.url,
)
self.assertEqual(
document.myfile.storage,
loaded_document.myfile.storage,
)
self.assertEqual(
document.myfile.instance,
loaded_document.myfile.instance,
)
self.assertEqual(
document.myfile.field,
loaded_document.myfile.field,
)
myfile_dump = pickle.dumps(document.myfile)
loaded_myfile = pickle.loads(myfile_dump)
self.assertEqual(document.myfile, loaded_myfile)
self.assertEqual(document.myfile.url, loaded_myfile.url)
self.assertEqual(
document.myfile.storage,
loaded_myfile.storage,
)
self.assertEqual(
document.myfile.instance,
loaded_myfile.instance,
)
self.assertEqual(document.myfile.field, loaded_myfile.field)
finally:
document.myfile.delete()
@isolate_apps("model_fields")
def test_abstract_filefield_model(self):
"""
FileField.model returns the concrete model for fields defined in an
abstract model.
"""
class AbstractMyDocument(models.Model):
myfile = models.FileField(upload_to="unused")
class Meta:
abstract = True
class MyDocument(AbstractMyDocument):
pass
document = MyDocument(myfile="test_file.py")
self.assertEqual(document.myfile.field.model, MyDocument)
| FileFieldTests |
python | kubernetes-client__python | kubernetes/client/models/v1_persistent_volume_claim_condition.py | {
"start": 383,
"end": 9885
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'last_probe_time': 'datetime',
'last_transition_time': 'datetime',
'message': 'str',
'reason': 'str',
'status': 'str',
'type': 'str'
}
attribute_map = {
'last_probe_time': 'lastProbeTime',
'last_transition_time': 'lastTransitionTime',
'message': 'message',
'reason': 'reason',
'status': 'status',
'type': 'type'
}
def __init__(self, last_probe_time=None, last_transition_time=None, message=None, reason=None, status=None, type=None, local_vars_configuration=None): # noqa: E501
"""V1PersistentVolumeClaimCondition - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._last_probe_time = None
self._last_transition_time = None
self._message = None
self._reason = None
self._status = None
self._type = None
self.discriminator = None
if last_probe_time is not None:
self.last_probe_time = last_probe_time
if last_transition_time is not None:
self.last_transition_time = last_transition_time
if message is not None:
self.message = message
if reason is not None:
self.reason = reason
self.status = status
self.type = type
@property
def last_probe_time(self):
"""Gets the last_probe_time of this V1PersistentVolumeClaimCondition. # noqa: E501
lastProbeTime is the time we probed the condition. # noqa: E501
:return: The last_probe_time of this V1PersistentVolumeClaimCondition. # noqa: E501
:rtype: datetime
"""
return self._last_probe_time
@last_probe_time.setter
def last_probe_time(self, last_probe_time):
"""Sets the last_probe_time of this V1PersistentVolumeClaimCondition.
lastProbeTime is the time we probed the condition. # noqa: E501
:param last_probe_time: The last_probe_time of this V1PersistentVolumeClaimCondition. # noqa: E501
:type: datetime
"""
self._last_probe_time = last_probe_time
@property
def last_transition_time(self):
"""Gets the last_transition_time of this V1PersistentVolumeClaimCondition. # noqa: E501
lastTransitionTime is the time the condition transitioned from one status to another. # noqa: E501
:return: The last_transition_time of this V1PersistentVolumeClaimCondition. # noqa: E501
:rtype: datetime
"""
return self._last_transition_time
@last_transition_time.setter
def last_transition_time(self, last_transition_time):
"""Sets the last_transition_time of this V1PersistentVolumeClaimCondition.
lastTransitionTime is the time the condition transitioned from one status to another. # noqa: E501
:param last_transition_time: The last_transition_time of this V1PersistentVolumeClaimCondition. # noqa: E501
:type: datetime
"""
self._last_transition_time = last_transition_time
@property
def message(self):
"""Gets the message of this V1PersistentVolumeClaimCondition. # noqa: E501
message is the human-readable message indicating details about last transition. # noqa: E501
:return: The message of this V1PersistentVolumeClaimCondition. # noqa: E501
:rtype: str
"""
return self._message
@message.setter
def message(self, message):
"""Sets the message of this V1PersistentVolumeClaimCondition.
message is the human-readable message indicating details about last transition. # noqa: E501
:param message: The message of this V1PersistentVolumeClaimCondition. # noqa: E501
:type: str
"""
self._message = message
@property
def reason(self):
"""Gets the reason of this V1PersistentVolumeClaimCondition. # noqa: E501
reason is a unique, this should be a short, machine understandable string that gives the reason for condition's last transition. If it reports \"Resizing\" that means the underlying persistent volume is being resized. # noqa: E501
:return: The reason of this V1PersistentVolumeClaimCondition. # noqa: E501
:rtype: str
"""
return self._reason
@reason.setter
def reason(self, reason):
"""Sets the reason of this V1PersistentVolumeClaimCondition.
reason is a unique, this should be a short, machine understandable string that gives the reason for condition's last transition. If it reports \"Resizing\" that means the underlying persistent volume is being resized. # noqa: E501
:param reason: The reason of this V1PersistentVolumeClaimCondition. # noqa: E501
:type: str
"""
self._reason = reason
@property
def status(self):
"""Gets the status of this V1PersistentVolumeClaimCondition. # noqa: E501
Status is the status of the condition. Can be True, False, Unknown. More info: https://kubernetes.io/docs/reference/kubernetes-api/config-and-storage-resources/persistent-volume-claim-v1/#:~:text=state%20of%20pvc-,conditions.status,-(string)%2C%20required # noqa: E501
:return: The status of this V1PersistentVolumeClaimCondition. # noqa: E501
:rtype: str
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this V1PersistentVolumeClaimCondition.
Status is the status of the condition. Can be True, False, Unknown. More info: https://kubernetes.io/docs/reference/kubernetes-api/config-and-storage-resources/persistent-volume-claim-v1/#:~:text=state%20of%20pvc-,conditions.status,-(string)%2C%20required # noqa: E501
:param status: The status of this V1PersistentVolumeClaimCondition. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and status is None: # noqa: E501
raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501
self._status = status
@property
def type(self):
"""Gets the type of this V1PersistentVolumeClaimCondition. # noqa: E501
Type is the type of the condition. More info: https://kubernetes.io/docs/reference/kubernetes-api/config-and-storage-resources/persistent-volume-claim-v1/#:~:text=set%20to%20%27ResizeStarted%27.-,PersistentVolumeClaimCondition,-contains%20details%20about # noqa: E501
:return: The type of this V1PersistentVolumeClaimCondition. # noqa: E501
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this V1PersistentVolumeClaimCondition.
Type is the type of the condition. More info: https://kubernetes.io/docs/reference/kubernetes-api/config-and-storage-resources/persistent-volume-claim-v1/#:~:text=set%20to%20%27ResizeStarted%27.-,PersistentVolumeClaimCondition,-contains%20details%20about # noqa: E501
:param type: The type of this V1PersistentVolumeClaimCondition. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and type is None: # noqa: E501
raise ValueError("Invalid value for `type`, must not be `None`") # noqa: E501
self._type = type
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1PersistentVolumeClaimCondition):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1PersistentVolumeClaimCondition):
return True
return self.to_dict() != other.to_dict()
| V1PersistentVolumeClaimCondition |
python | Pylons__pyramid | src/pyramid/view.py | {
"start": 18463,
"end": 20651
} | class ____:
"""
.. versionadded:: 1.3
An analogue of :class:`pyramid.view.view_config` which registers a
:term:`forbidden view` using
:meth:`pyramid.config.Configurator.add_forbidden_view`.
The forbidden_view_config constructor accepts most of the same arguments
as the constructor of :class:`pyramid.view.view_config`. It can be used
in the same places, and behaves in largely the same way, except it always
registers a forbidden exception view instead of a 'normal' view.
Example:
.. code-block:: python
from pyramid.view import forbidden_view_config
from pyramid.response import Response
@forbidden_view_config()
def forbidden(request):
return Response('You are not allowed', status='403 Forbidden')
All arguments passed to this function have the same meaning as
:meth:`pyramid.view.view_config` and each predicate argument restricts
the set of circumstances under which this notfound view will be invoked.
See :ref:`changing_the_forbidden_view` for detailed usage information.
.. versionchanged:: 1.9.1
Added the ``_depth`` and ``_category`` arguments.
"""
venusian = venusian
def __init__(self, **settings):
self.__dict__.update(settings)
def __call__(self, wrapped):
settings = self.__dict__.copy()
depth = settings.pop('_depth', 0)
category = settings.pop('_category', 'pyramid')
def callback(context, name, ob):
config = context.config.with_package(info.module)
config.add_forbidden_view(view=ob, **settings)
info = self.venusian.attach(
wrapped, callback, category=category, depth=depth + 1
)
if info.scope == 'class':
# if the decorator was attached to a method in a class, or
# otherwise executed at class scope, we need to set an
# 'attr' into the settings if one isn't already in there
if settings.get('attr') is None:
settings['attr'] = wrapped.__name__
settings['_info'] = info.codeinfo # fbo "action_method"
return wrapped
| forbidden_view_config |
python | sanic-org__sanic | sanic/application/motd.py | {
"start": 1307,
"end": 1888
} | class ____(MOTD):
"""A basic MOTD display.
This is used when the terminal does not support ANSI escape codes.
"""
def display(self):
if self.logo:
logger.debug(self.logo)
lines = [f"Sanic v{__version__}"]
if self.serve_location:
lines.append(f"Goin' Fast @ {self.serve_location}")
lines += [
*(f"{key}: {value}" for key, value in self.data.items()),
*(f"{key}: {value}" for key, value in self.extra.items()),
]
for line in lines:
logger.info(line)
| MOTDBasic |
python | pytorch__pytorch | test/torch_np/test_random.py | {
"start": 3619,
"end": 4267
} | class ____(TestCase):
def test_numpy_global(self):
with control_stream(use_numpy=True):
tnp.random.seed(12345)
x = tnp.random.uniform(0, 1, size=11)
# check that the stream is identical to numpy's
_np.random.seed(12345)
x_np = _np.random.uniform(0, 1, size=11)
assert_equal(x, tnp.asarray(x_np))
# switch to the pytorch stream, variates differ
with control_stream(use_numpy=False):
tnp.random.seed(12345)
x_1 = tnp.random.uniform(0, 1, size=11)
assert not (x_1 == x).all()
if __name__ == "__main__":
run_tests()
| TestNumpyGlobal |
python | wepe__MachineLearning | DeepLearning Tutorials/mlp/mlp_with_commentate.py | {
"start": 1073,
"end": 2825
} | class ____(object):
def __init__(self, rng, input, n_in, n_out, W=None, b=None,
activation=T.tanh):
self.input = input #类HiddenLayer的input即所传递进来的input
"""
注释:
代码要兼容GPU,则必须使用 dtype=theano.config.floatX,并且定义为theano.shared
另外,W的初始化有个规则:如果使用tanh函数,则在-sqrt(6./(n_in+n_hidden))到sqrt(6./(n_in+n_hidden))之间均匀
抽取数值来初始化W,若时sigmoid函数,则以上再乘4倍。
"""
#如果W没有给定,即等于None,则根据上述的规则随机初始化。
#加入这个判断的原因是:有时候我们可以用训练好的参数来初始化W,见我的上一篇文章。
if W is None:
W_values = numpy.asarray(
rng.uniform(
low=-numpy.sqrt(6. / (n_in + n_out)),
high=numpy.sqrt(6. / (n_in + n_out)),
size=(n_in, n_out)
),
dtype=theano.config.floatX
)
if activation == theano.tensor.nnet.sigmoid:
W_values *= 4
W = theano.shared(value=W_values, name='W', borrow=True)
if b is None:
b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
b = theano.shared(value=b_values, name='b', borrow=True)
#用上面定义的W、b来初始化类HiddenLayer的W、b
self.W = W
self.b = b
#隐含层的输出
lin_output = T.dot(input, self.W) + self.b
self.output = (
lin_output if activation is None
else activation(lin_output)
)
#隐含层的参数
self.params = [self.W, self.b]
"""
定义分类层,Softmax回归
在deeplearning tutorial中,直接将LogisticRegression视为Softmax,
而我们所认识的二类别的逻辑回归就是当n_out=2时的LogisticRegression
"""
#参数说明:
#input,大小就是(n_example,n_in),其中n_example是一个batch的大小,
#因为我们训练时用的是Minibatch SGD,因此input这样定义
#n_in,即上一层(隐含层)的输出
#n_out,输出的类别数
| HiddenLayer |
python | apache__airflow | airflow-core/src/airflow/models/asset.py | {
"start": 32391,
"end": 33518
} | class ____(Base):
"""
Mapping table between AssetPartitionDagRun and AssetEvent.
PartitionedAssetKeyLog tells us which events contributed to a particular
AssetPartitionDagRun record.
"""
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(Integer, nullable=False)
asset_event_id: Mapped[int] = mapped_column(Integer, nullable=False)
asset_partition_dag_run_id: Mapped[int] = mapped_column(Integer, nullable=False)
source_partition_key: Mapped[str | None] = mapped_column(StringID(), nullable=False)
target_dag_id: Mapped[str | None] = mapped_column(StringID(), nullable=False)
target_partition_key: Mapped[str | None] = mapped_column(StringID(), nullable=False)
created_at: Mapped[datetime] = mapped_column(UtcDateTime, default=timezone.utcnow, nullable=False)
__tablename__ = "partitioned_asset_key_log"
def __repr__(self):
args = (f"{x.name}={getattr(self, x.name)!r}" for x in self.__mapper__.primary_key)
return f"{self.__class__.__name__}({', '.join(args)})"
| PartitionedAssetKeyLog |
python | sqlalchemy__sqlalchemy | test/orm/test_eager_relations.py | {
"start": 167187,
"end": 179061
} | class ____(_fixtures.FixtureTest, testing.AssertsCompiledSQL):
run_setup_mappers = "once"
run_inserts = "once"
run_deletes = None
__dialect__ = "default"
__prefer_backends__ = ("postgresql", "mysql", "oracle")
@classmethod
def setup_mappers(cls):
(
users,
Keyword,
items,
order_items,
orders,
Item,
User,
Address,
keywords,
Order,
item_keywords,
addresses,
) = (
cls.tables.users,
cls.classes.Keyword,
cls.tables.items,
cls.tables.order_items,
cls.tables.orders,
cls.classes.Item,
cls.classes.User,
cls.classes.Address,
cls.tables.keywords,
cls.classes.Order,
cls.tables.item_keywords,
cls.tables.addresses,
)
cls.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(Address, backref="user"),
"orders": relationship(Order, backref="user"), # o2m, m2o
},
)
cls.mapper_registry.map_imperatively(Address, addresses)
cls.mapper_registry.map_imperatively(
Order,
orders,
properties={
"items": relationship(
Item, secondary=order_items, order_by=items.c.id
) # m2m
},
)
cls.mapper_registry.map_imperatively(
Item,
items,
properties={
"keywords": relationship(
Keyword, secondary=item_keywords
) # m2m
},
)
cls.mapper_registry.map_imperatively(Keyword, keywords)
def test_two_entities(self):
Item, Order, User, Address = (
self.classes.Item,
self.classes.Order,
self.classes.User,
self.classes.Address,
)
sess = fixture_session()
# two FROM clauses
def go():
eq_(
[
(
User(id=9, addresses=[Address(id=5)]),
Order(
id=2, items=[Item(id=1), Item(id=2), Item(id=3)]
),
),
(
User(id=9, addresses=[Address(id=5)]),
Order(id=4, items=[Item(id=1), Item(id=5)]),
),
],
sess.query(User, Order)
.filter(User.id == Order.user_id)
.options(joinedload(User.addresses), joinedload(Order.items))
.filter(User.id == 9)
.order_by(User.id, Order.id)
.all(),
)
self.assert_sql_count(testing.db, go, 1)
# one FROM clause
def go():
eq_(
[
(
User(id=9, addresses=[Address(id=5)]),
Order(
id=2, items=[Item(id=1), Item(id=2), Item(id=3)]
),
),
(
User(id=9, addresses=[Address(id=5)]),
Order(id=4, items=[Item(id=1), Item(id=5)]),
),
],
sess.query(User, Order)
.join(User.orders)
.options(joinedload(User.addresses), joinedload(Order.items))
.filter(User.id == 9)
.order_by(User.id, Order.id)
.all(),
)
self.assert_sql_count(testing.db, go, 1)
def test_two_entities_with_joins(self):
# early versions of SQLite could not handle this test
# however as of 2018 and probably for some years before that
# it has no issue with this.
Item, Order, User, Address = (
self.classes.Item,
self.classes.Order,
self.classes.User,
self.classes.Address,
)
sess = fixture_session()
# two FROM clauses where there's a join on each one
def go():
u1 = aliased(User)
o1 = aliased(Order)
eq_(
[
(
User(
addresses=[Address(email_address="fred@fred.com")],
name="fred",
),
Order(
description="order 2",
isopen=0,
items=[
Item(description="item 1"),
Item(description="item 2"),
Item(description="item 3"),
],
),
User(
addresses=[Address(email_address="jack@bean.com")],
name="jack",
),
Order(
description="order 3",
isopen=1,
items=[
Item(description="item 3"),
Item(description="item 4"),
Item(description="item 5"),
],
),
),
(
User(
addresses=[Address(email_address="fred@fred.com")],
name="fred",
),
Order(
description="order 2",
isopen=0,
items=[
Item(description="item 1"),
Item(description="item 2"),
Item(description="item 3"),
],
),
User(
addresses=[Address(email_address="jack@bean.com")],
name="jack",
),
Order(
address_id=None,
description="order 5",
isopen=0,
items=[Item(description="item 5")],
),
),
(
User(
addresses=[Address(email_address="fred@fred.com")],
name="fred",
),
Order(
description="order 4",
isopen=1,
items=[
Item(description="item 1"),
Item(description="item 5"),
],
),
User(
addresses=[Address(email_address="jack@bean.com")],
name="jack",
),
Order(
address_id=None,
description="order 5",
isopen=0,
items=[Item(description="item 5")],
),
),
],
sess.query(User, Order, u1, o1)
.join(Order, User.orders)
.options(joinedload(User.addresses), joinedload(Order.items))
.filter(User.id == 9)
.join(o1, u1.orders)
.options(joinedload(u1.addresses), joinedload(o1.items))
.filter(u1.id == 7)
.filter(Order.id < o1.id)
.order_by(User.id, Order.id, u1.id, o1.id)
.all(),
)
self.assert_sql_count(testing.db, go, 1)
def test_aliased_entity_one(self):
Item, Order, User, Address = (
self.classes.Item,
self.classes.Order,
self.classes.User,
self.classes.Address,
)
sess = fixture_session()
oalias = sa.orm.aliased(Order)
# two FROM clauses
def go():
eq_(
[
(
User(id=9, addresses=[Address(id=5)]),
Order(
id=2, items=[Item(id=1), Item(id=2), Item(id=3)]
),
),
(
User(id=9, addresses=[Address(id=5)]),
Order(id=4, items=[Item(id=1), Item(id=5)]),
),
],
sess.query(User, oalias)
.filter(User.id == oalias.user_id)
.options(joinedload(User.addresses), joinedload(oalias.items))
.filter(User.id == 9)
.order_by(User.id, oalias.id)
.all(),
)
self.assert_sql_count(testing.db, go, 1)
def test_aliased_entity_two(self):
Item, Order, User, Address = (
self.classes.Item,
self.classes.Order,
self.classes.User,
self.classes.Address,
)
sess = fixture_session()
oalias = sa.orm.aliased(Order)
# one FROM clause
def go():
eq_(
[
(
User(id=9, addresses=[Address(id=5)]),
Order(
id=2, items=[Item(id=1), Item(id=2), Item(id=3)]
),
),
(
User(id=9, addresses=[Address(id=5)]),
Order(id=4, items=[Item(id=1), Item(id=5)]),
),
],
sess.query(User, oalias)
.join(oalias, User.orders)
.options(joinedload(User.addresses), joinedload(oalias.items))
.filter(User.id == 9)
.order_by(User.id, oalias.id)
.all(),
)
self.assert_sql_count(testing.db, go, 1)
def test_aliased_entity_three(self):
Order, User = (self.classes.Order, self.classes.User)
sess = fixture_session()
oalias = sa.orm.aliased(Order)
# improper setup: oalias in the columns clause but join to usual
# orders alias. this should create two FROM clauses even though the
# query has a from_clause set up via the join
self.assert_compile(
sess.query(User, oalias)
.join(User.orders)
.options(joinedload(oalias.items))
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.statement,
"SELECT users.id AS users_id, users.name AS users_name, "
"orders_1.id AS orders_1_id, "
"orders_1.user_id AS orders_1_user_id, "
"orders_1.address_id AS orders_1_address_id, "
"orders_1.description AS orders_1_description, "
"orders_1.isopen AS orders_1_isopen, items_1.id AS items_1_id, "
"items_1.description AS items_1_description FROM users "
"JOIN orders ON users.id = orders.user_id, "
"orders AS orders_1 LEFT OUTER JOIN (order_items AS order_items_1 "
"JOIN items AS items_1 ON items_1.id = order_items_1.item_id) "
"ON orders_1.id = order_items_1.order_id ORDER BY items_1.id",
)
| MixedEntitiesTest |
python | getsentry__sentry | src/sentry/integrations/mixins/notifications.py | {
"start": 399,
"end": 1448
} | class ____:
def send_message(self, channel_id: str, message: str) -> None:
"""
Send a message through the integration.
"""
raise NotImplementedError
def notify_remove_external_team(self, external_team: ExternalActor, team: Team) -> None:
"""
Notify through the integration that an external team has been removed.
"""
if not external_team.external_id:
logger.info(
"notify.external_team_missing_external_id",
extra={
"external_team_id": external_team.id,
"team_id": team.id,
"team_slug": team.slug,
},
)
capture_message(
f"External team {external_team.id} has no external_id",
level="warning",
)
return
self.send_message(
channel_id=external_team.external_id,
message=SUCCESS_UNLINKED_TEAM_MESSAGE.format(team=team.slug),
)
| NotifyBasicMixin |
python | django__django | tests/gis_tests/geoapp/test_functions.py | {
"start": 771,
"end": 39804
} | class ____(FuncTestMixin, TestCase):
"""
Testing functions from django/contrib/gis/db/models/functions.py.
Area/Distance/Length/Perimeter are tested in distapp/tests.
Please keep the tests in function's alphabetic order.
"""
fixtures = ["initial"]
def test_asgeojson(self):
if not connection.features.has_AsGeoJSON_function:
with self.assertRaises(NotSupportedError):
list(Country.objects.annotate(json=functions.AsGeoJSON("mpoly")))
return
pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}'
houston_json = json.loads(
'{"type":"Point","crs":{"type":"name","properties":'
'{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}'
)
victoria_json = json.loads(
'{"type":"Point",'
'"bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],'
'"coordinates":[-123.305196,48.462611]}'
)
chicago_json = json.loads(
'{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},'
'"bbox":[-87.65018,41.85039,-87.65018,41.85039],'
'"coordinates":[-87.65018,41.85039]}'
)
if "crs" in connection.features.unsupported_geojson_options:
del houston_json["crs"]
del chicago_json["crs"]
if "bbox" in connection.features.unsupported_geojson_options:
del chicago_json["bbox"]
del victoria_json["bbox"]
if "precision" in connection.features.unsupported_geojson_options:
chicago_json["coordinates"] = [-87.650175, 41.850385]
# Precision argument should only be an integer
with self.assertRaises(TypeError):
City.objects.annotate(geojson=functions.AsGeoJSON("point", precision="foo"))
# Reference queries and values.
# SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0)
# FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo';
self.assertJSONEqual(
pueblo_json,
City.objects.annotate(geojson=functions.AsGeoJSON("point"))
.get(name="Pueblo")
.geojson,
)
# SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city"
# WHERE "geoapp_city"."name" = 'Houston';
# This time we want to include the CRS by using the `crs` keyword.
self.assertJSONEqual(
City.objects.annotate(json=functions.AsGeoJSON("point", crs=True))
.get(name="Houston")
.json,
houston_json,
)
# SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city"
# WHERE "geoapp_city"."name" = 'Houston';
# This time we include the bounding box by using the `bbox` keyword.
self.assertJSONEqual(
City.objects.annotate(geojson=functions.AsGeoJSON("point", bbox=True))
.get(name="Victoria")
.geojson,
victoria_json,
)
# SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city"
# WHERE "geoapp_city"."name" = 'Chicago';
# Finally, we set every available keyword.
# MariaDB doesn't limit the number of decimals in bbox.
if connection.ops.mariadb:
chicago_json["bbox"] = [-87.650175, 41.850385, -87.650175, 41.850385]
try:
self.assertJSONEqual(
City.objects.annotate(
geojson=functions.AsGeoJSON(
"point", bbox=True, crs=True, precision=5
)
)
.get(name="Chicago")
.geojson,
chicago_json,
)
except AssertionError:
# Give a second chance with different coords rounding.
chicago_json["coordinates"][1] = 41.85038
self.assertJSONEqual(
City.objects.annotate(
geojson=functions.AsGeoJSON(
"point", bbox=True, crs=True, precision=5
)
)
.get(name="Chicago")
.geojson,
chicago_json,
)
@skipUnlessDBFeature("has_AsGeoJSON_function")
def test_asgeojson_option_0(self):
p1 = Point(1, 1, srid=4326)
p2 = Point(-87.65018, 41.85039, srid=4326)
obj = ManyPointModel.objects.create(
point1=p1,
point2=p2,
point3=p2.transform(3857, clone=True),
)
self.assertJSONEqual(
ManyPointModel.objects.annotate(geojson=functions.AsGeoJSON("point3"))
.get(pk=obj.pk)
.geojson,
# GeoJSON without CRS.
json.loads(
'{"type":"Point","coordinates":[-9757173.40553877, 5138594.87034608]}'
),
)
@skipUnlessDBFeature("has_AsGML_function")
def test_asgml(self):
# Should throw a TypeError when trying to obtain GML from a
# non-geometry field.
qs = City.objects.all()
with self.assertRaises(TypeError):
qs.annotate(gml=functions.AsGML("name"))
ptown = City.objects.annotate(gml=functions.AsGML("point", precision=9)).get(
name="Pueblo"
)
if connection.ops.oracle:
# No precision parameter for Oracle :-/
gml_regex = re.compile(
r'^<gml:Point srsName="EPSG:4326" '
r'xmlns:gml="http://www.opengis.net/gml">'
r'<gml:coordinates decimal="\." cs="," ts=" ">'
r"-104.60925\d+,38.25500\d+ "
r"</gml:coordinates></gml:Point>"
)
else:
gml_regex = re.compile(
r'^<gml:Point srsName="(urn:ogc:def:crs:)?EPSG:4326"><gml:coordinates>'
r"-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>"
)
self.assertTrue(gml_regex.match(ptown.gml))
self.assertIn(
'<gml:pos srsDimension="2">',
City.objects.annotate(gml=functions.AsGML("point", version=3))
.get(name="Pueblo")
.gml,
)
@skipUnlessDBFeature("has_AsKML_function")
def test_askml(self):
# Should throw a TypeError when trying to obtain KML from a
# non-geometry field.
with self.assertRaises(TypeError):
City.objects.annotate(kml=functions.AsKML("name"))
# Ensuring the KML is as expected.
ptown = City.objects.annotate(kml=functions.AsKML("point", precision=9)).get(
name="Pueblo"
)
self.assertEqual(
"<Point><coordinates>-104.609252,38.255001</coordinates></Point>", ptown.kml
)
@skipUnlessDBFeature("has_AsSVG_function")
def test_assvg(self):
with self.assertRaises(TypeError):
City.objects.annotate(svg=functions.AsSVG("point", precision="foo"))
# SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city
# WHERE name = 'Pueblo';
svg1 = 'cx="-104.609252" cy="-38.255001"'
# Even though relative, only one point so it's practically the same
# except for the 'c' letter prefix on the x,y values.
svg2 = svg1.replace("c", "")
self.assertEqual(
svg1,
City.objects.annotate(svg=functions.AsSVG("point")).get(name="Pueblo").svg,
)
self.assertEqual(
svg2,
City.objects.annotate(svg=functions.AsSVG("point", relative=5))
.get(name="Pueblo")
.svg,
)
@skipUnlessDBFeature("has_AsWKB_function")
def test_aswkb(self):
wkb = (
City.objects.annotate(
wkb=functions.AsWKB(Point(1, 2, srid=4326)),
)
.first()
.wkb
)
# WKB is either XDR or NDR encoded.
self.assertIn(
bytes(wkb),
(
b"\x00\x00\x00\x00\x01?\xf0\x00\x00\x00\x00\x00\x00@\x00\x00"
b"\x00\x00\x00\x00\x00",
b"\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00"
b"\x00\x00\x00\x00\x00@",
),
)
@skipUnlessDBFeature("has_AsWKT_function")
def test_aswkt(self):
wkt = (
City.objects.annotate(
wkt=functions.AsWKT(Point(1, 2, srid=4326)),
)
.first()
.wkt
)
self.assertEqual(
wkt, "POINT (1.0 2.0)" if connection.ops.oracle else "POINT(1 2)"
)
@skipUnlessDBFeature("has_Azimuth_function")
def test_azimuth(self):
# Returns the azimuth in radians.
azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(1, 1, srid=4326))
self.assertAlmostEqual(
City.objects.annotate(azimuth=azimuth_expr).first().azimuth,
math.pi / 4,
places=2,
)
# Returns None if the two points are coincident.
azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(0, 0, srid=4326))
self.assertIsNone(City.objects.annotate(azimuth=azimuth_expr).first().azimuth)
@skipUnlessDBFeature("has_BoundingCircle_function")
def test_bounding_circle(self):
def circle_num_points(num_seg):
# num_seg is the number of segments per quarter circle.
return (4 * num_seg) + 1
if connection.ops.postgis:
expected_area = 169
elif connection.ops.spatialite:
expected_area = 168
else: # Oracle.
expected_area = 171
country = Country.objects.annotate(
circle=functions.BoundingCircle("mpoly")
).order_by("name")[0]
self.assertAlmostEqual(country.circle.area, expected_area, 0)
if connection.ops.postgis:
# By default num_seg=48.
self.assertEqual(country.circle.num_points, circle_num_points(48))
tests = [12, Value(12, output_field=IntegerField())]
for num_seq in tests:
with self.subTest(num_seq=num_seq):
country = Country.objects.annotate(
circle=functions.BoundingCircle("mpoly", num_seg=num_seq),
).order_by("name")[0]
if connection.ops.postgis:
self.assertGreater(country.circle.area, 168.4, 0)
self.assertLess(country.circle.area, 169.5, 0)
self.assertEqual(country.circle.num_points, circle_num_points(12))
else:
self.assertAlmostEqual(country.circle.area, expected_area, 0)
@skipUnlessDBFeature("has_Centroid_function")
def test_centroid(self):
qs = State.objects.exclude(poly__isnull=True).annotate(
centroid=functions.Centroid("poly")
)
tol = (
1.8 if connection.ops.mysql else (0.1 if connection.ops.oracle else 0.00001)
)
for state in qs:
self.assertTrue(state.poly.centroid.equals_exact(state.centroid, tol))
with self.assertRaisesMessage(
TypeError, "'Centroid' takes exactly 1 argument (2 given)"
):
State.objects.annotate(centroid=functions.Centroid("poly", "poly"))
@skipUnlessDBFeature("has_Difference_function")
def test_difference(self):
geom = Point(5, 23, srid=4326)
qs = Country.objects.annotate(diff=functions.Difference("mpoly", geom))
# Oracle does something screwy with the Texas geometry.
if connection.ops.oracle:
qs = qs.exclude(name="Texas")
for c in qs:
self.assertTrue(c.mpoly.difference(geom).equals(c.diff))
@skipUnlessDBFeature("has_Difference_function", "has_Transform_function")
def test_difference_mixed_srid(self):
"""Testing with mixed SRID (Country has default 4326)."""
geom = Point(556597.4, 2632018.6, srid=3857) # Spherical Mercator
qs = Country.objects.annotate(difference=functions.Difference("mpoly", geom))
# Oracle does something screwy with the Texas geometry.
if connection.ops.oracle:
qs = qs.exclude(name="Texas")
for c in qs:
self.assertTrue(c.mpoly.difference(geom).equals(c.difference))
@skipUnlessDBFeature("has_Envelope_function")
def test_envelope(self):
countries = Country.objects.annotate(envelope=functions.Envelope("mpoly"))
for country in countries:
self.assertTrue(country.envelope.equals(country.mpoly.envelope))
@skipUnlessDBFeature("has_ForcePolygonCW_function")
def test_force_polygon_cw(self):
rings = (
((0, 0), (5, 0), (0, 5), (0, 0)),
((1, 1), (1, 3), (3, 1), (1, 1)),
)
rhr_rings = (
((0, 0), (0, 5), (5, 0), (0, 0)),
((1, 1), (3, 1), (1, 3), (1, 1)),
)
State.objects.create(name="Foo", poly=Polygon(*rings))
st = State.objects.annotate(
force_polygon_cw=functions.ForcePolygonCW("poly")
).get(name="Foo")
self.assertEqual(rhr_rings, st.force_polygon_cw.coords)
@skipUnlessDBFeature("has_FromWKB_function")
def test_fromwkb(self):
g = Point(56.811078, 60.608647)
pt1, pt2 = City.objects.values_list(
functions.FromWKB(Value(g.wkb.tobytes())),
functions.FromWKB(Value(g.wkb.tobytes()), srid=4326),
)[0]
self.assertIs(g.equals_exact(pt1, 0.00001), True)
self.assertIsNone(pt1.srid)
self.assertEqual(pt2.srid, 4326)
@skipUnlessDBFeature("has_FromWKT_function")
def test_fromwkt(self):
g = Point(56.811078, 60.608647)
pt1, pt2 = City.objects.values_list(
functions.FromWKT(Value(g.wkt)),
functions.FromWKT(Value(g.wkt), srid=4326),
)[0]
self.assertIs(g.equals_exact(pt1, 0.00001), True)
self.assertIsNone(pt1.srid)
self.assertEqual(pt2.srid, 4326)
@skipUnlessDBFeature("has_GeoHash_function")
def test_geohash(self):
# Reference query:
# SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston';
# SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston';
ref_hash = "9vk1mfq8jx0c8e0386z6"
h1 = City.objects.annotate(geohash=functions.GeoHash("point")).get(
name="Houston"
)
h2 = City.objects.annotate(geohash=functions.GeoHash("point", precision=5)).get(
name="Houston"
)
self.assertEqual(ref_hash, h1.geohash[: len(ref_hash)])
self.assertEqual(ref_hash[:5], h2.geohash)
@skipUnlessDBFeature("has_GeometryDistance_function")
def test_geometry_distance(self):
point = Point(-90, 40, srid=4326)
qs = City.objects.annotate(
distance=functions.GeometryDistance("point", point)
).order_by("distance")
distances = (
2.99091995527296,
5.33507274054713,
9.33852187483721,
9.91769193646233,
11.556465744884,
14.713098433352,
34.3635252198568,
276.987855073372,
)
for city, expected_distance in zip(qs, distances):
with self.subTest(city=city):
self.assertAlmostEqual(city.distance, expected_distance)
@skipUnlessDBFeature("has_Intersection_function")
def test_intersection(self):
geom = Point(5, 23, srid=4326)
qs = Country.objects.annotate(inter=functions.Intersection("mpoly", geom))
for c in qs:
if connection.features.empty_intersection_returns_none:
self.assertIsNone(c.inter)
else:
self.assertIs(c.inter.empty, True)
@skipUnlessDBFeature("supports_empty_geometries", "has_IsEmpty_function")
def test_isempty_geometry_empty(self):
empty = City.objects.create(name="Nowhere", point=Point(srid=4326))
City.objects.create(name="Somewhere", point=Point(6.825, 47.1, srid=4326))
self.assertSequenceEqual(
City.objects.annotate(isempty=functions.IsEmpty("point")).filter(
isempty=True
),
[empty],
)
self.assertSequenceEqual(City.objects.filter(point__isempty=True), [empty])
@skipUnlessDBFeature("has_IsEmpty_function")
def test_isempty_geometry_null(self):
nowhere = State.objects.create(name="Nowhere", poly=None)
qs = State.objects.annotate(isempty=functions.IsEmpty("poly"))
self.assertSequenceEqual(qs.filter(isempty=None), [nowhere])
self.assertSequenceEqual(
qs.filter(isempty=False).order_by("name").values_list("name", flat=True),
["Colorado", "Kansas"],
)
self.assertSequenceEqual(qs.filter(isempty=True), [])
self.assertSequenceEqual(State.objects.filter(poly__isempty=True), [])
@skipUnlessDBFeature("has_IsValid_function")
def test_isvalid(self):
valid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))")
invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))")
State.objects.create(name="valid", poly=valid_geom)
State.objects.create(name="invalid", poly=invalid_geom)
valid = (
State.objects.filter(name="valid")
.annotate(isvalid=functions.IsValid("poly"))
.first()
)
invalid = (
State.objects.filter(name="invalid")
.annotate(isvalid=functions.IsValid("poly"))
.first()
)
self.assertIs(valid.isvalid, True)
self.assertIs(invalid.isvalid, False)
@skipUnlessDBFeature("has_Area_function")
def test_area_with_regular_aggregate(self):
# Create projected country objects, for this test to work on all
# backends.
for c in Country.objects.all():
CountryWebMercator.objects.create(
name=c.name, mpoly=c.mpoly.transform(3857, clone=True)
)
# Test in projected coordinate system
qs = CountryWebMercator.objects.annotate(area_sum=Sum(functions.Area("mpoly")))
# Some backends (e.g. Oracle) cannot group by multipolygon values, so
# defer such fields in the aggregation query.
for c in qs.defer("mpoly"):
result = c.area_sum
# If the result is a measure object, get value.
if isinstance(result, Area):
result = result.sq_m
self.assertAlmostEqual((result - c.mpoly.area) / c.mpoly.area, 0)
@skipUnlessDBFeature("has_Area_function")
def test_area_lookups(self):
# Create projected countries so the test works on all backends.
CountryWebMercator.objects.bulk_create(
CountryWebMercator(name=c.name, mpoly=c.mpoly.transform(3857, clone=True))
for c in Country.objects.all()
)
qs = CountryWebMercator.objects.annotate(area=functions.Area("mpoly"))
self.assertEqual(
qs.get(area__lt=Area(sq_km=500000)),
CountryWebMercator.objects.get(name="New Zealand"),
)
with self.assertRaisesMessage(
ValueError, "AreaField only accepts Area measurement objects."
):
qs.get(area__lt=500000)
@skipUnlessDBFeature("has_ClosestPoint_function")
def test_closest_point(self):
qs = Country.objects.annotate(
closest_point=functions.ClosestPoint("mpoly", functions.Centroid("mpoly"))
)
for country in qs:
self.assertIsInstance(country.closest_point, Point)
self.assertEqual(
country.mpoly.intersection(country.closest_point),
country.closest_point,
)
@skipUnlessDBFeature("has_LineLocatePoint_function")
def test_line_locate_point(self):
pos_expr = functions.LineLocatePoint(
LineString((0, 0), (0, 3), srid=4326), Point(0, 1, srid=4326)
)
self.assertAlmostEqual(
State.objects.annotate(pos=pos_expr).first().pos, 0.3333333
)
@skipUnlessDBFeature("has_MakeValid_function")
def test_make_valid(self):
invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))")
State.objects.create(name="invalid", poly=invalid_geom)
invalid = (
State.objects.filter(name="invalid")
.annotate(repaired=functions.MakeValid("poly"))
.first()
)
self.assertIs(invalid.repaired.valid, True)
self.assertTrue(
invalid.repaired.equals(
fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))", srid=invalid.poly.srid)
)
)
@skipUnlessDBFeature("has_MakeValid_function")
def test_make_valid_multipolygon(self):
invalid_geom = fromstr(
"POLYGON((0 0, 0 1 , 1 1 , 1 0, 0 0), (10 0, 10 1, 11 1, 11 0, 10 0))"
)
State.objects.create(name="invalid", poly=invalid_geom)
invalid = (
State.objects.filter(name="invalid")
.annotate(
repaired=functions.MakeValid("poly"),
)
.get()
)
self.assertIs(invalid.repaired.valid, True)
self.assertTrue(
invalid.repaired.equals(
fromstr(
"MULTIPOLYGON (((0 0, 0 1, 1 1, 1 0, 0 0)), "
"((10 0, 10 1, 11 1, 11 0, 10 0)))",
srid=invalid.poly.srid,
)
)
)
self.assertEqual(len(invalid.repaired), 2)
@skipUnlessDBFeature("has_MakeValid_function")
def test_make_valid_output_field(self):
# output_field is GeometryField instance because different geometry
# types can be returned.
output_field = functions.MakeValid(
Value(Polygon(), PolygonField(srid=42)),
).output_field
self.assertIs(output_field.__class__, GeometryField)
self.assertEqual(output_field.srid, 42)
@skipUnlessDBFeature("has_MemSize_function")
def test_memsize(self):
ptown = City.objects.annotate(size=functions.MemSize("point")).get(
name="Pueblo"
)
# Exact value depends on database and version.
self.assertTrue(20 <= ptown.size <= 105)
@skipUnlessDBFeature("has_NumGeometries_function")
def test_num_geom(self):
# Both 'countries' only have two geometries.
for c in Country.objects.annotate(num_geom=functions.NumGeometries("mpoly")):
self.assertEqual(2, c.num_geom)
qs = City.objects.filter(point__isnull=False).annotate(
num_geom=functions.NumGeometries("point")
)
for city in qs:
# The results for the number of geometries on non-collections
# depends on the database.
if connection.ops.mysql or connection.ops.mariadb:
self.assertIsNone(city.num_geom)
else:
self.assertEqual(1, city.num_geom)
@skipUnlessDBFeature("has_NumDimensions_function")
def test_num_dimensions(self):
for c in Country.objects.annotate(num_dims=functions.NumDimensions("mpoly")):
self.assertEqual(2, c.num_dims)
ThreeDimensionalFeature.objects.create(
name="London", geom=Point(-0.126418, 51.500832, 0)
)
qs = ThreeDimensionalFeature.objects.annotate(
num_dims=functions.NumDimensions("geom")
)
self.assertEqual(qs[0].num_dims, 3)
qs = ThreeDimensionalFeature.objects.annotate(
num_dims=F("geom__num_dimensions")
)
self.assertEqual(qs[0].num_dims, 3)
msg = "'NumDimensions' takes exactly 1 argument (2 given)"
with self.assertRaisesMessage(TypeError, msg):
Country.objects.annotate(num_dims=functions.NumDimensions("point", "error"))
@skipUnlessDBFeature("has_NumPoints_function")
def test_num_points(self):
coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)]
Track.objects.create(name="Foo", line=LineString(coords))
qs = Track.objects.annotate(num_points=functions.NumPoints("line"))
self.assertEqual(qs.first().num_points, 2)
mpoly_qs = Country.objects.annotate(num_points=functions.NumPoints("mpoly"))
if not connection.features.supports_num_points_poly:
for c in mpoly_qs:
self.assertIsNone(c.num_points)
return
for c in mpoly_qs:
self.assertEqual(c.mpoly.num_points, c.num_points)
for c in City.objects.annotate(num_points=functions.NumPoints("point")):
self.assertEqual(c.num_points, 1)
@skipUnlessDBFeature("has_PointOnSurface_function")
def test_point_on_surface(self):
qs = Country.objects.annotate(
point_on_surface=functions.PointOnSurface("mpoly")
)
for country in qs:
self.assertTrue(country.mpoly.intersection(country.point_on_surface))
@skipUnlessDBFeature("has_Reverse_function")
def test_reverse_geom(self):
coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)]
Track.objects.create(name="Foo", line=LineString(coords))
track = Track.objects.annotate(reverse_geom=functions.Reverse("line")).get(
name="Foo"
)
coords.reverse()
self.assertEqual(tuple(coords), track.reverse_geom.coords)
@skipUnlessDBFeature("has_Rotate_function")
def test_rotate(self):
angle = math.pi
tests = [
{"angle": angle},
{"angle": angle, "origin": Point(0, 0)},
{"angle": angle, "origin": Point(1, 1)},
]
for params in tests:
with self.subTest(params=params):
qs = Country.objects.annotate(
rotated=functions.Rotate("mpoly", **params)
)
for country in qs:
for p1, p2 in zip(country.mpoly, country.rotated):
for r1, r2 in zip(p1, p2):
for c1, c2 in zip(r1.coords, r2.coords):
origin = params.get("origin")
if origin is None:
origin = Point(0, 0)
self.assertAlmostEqual(-c1[0] + 2 * origin.x, c2[0], 5)
self.assertAlmostEqual(-c1[1] + 2 * origin.y, c2[1], 5)
@skipUnlessDBFeature("has_Rotate_function")
def test_rotate_invalid_params(self):
angle = math.pi
bad_params_tests = [
{"angle": angle, "origin": 0},
{"angle": angle, "origin": [0, 0]},
]
msg = "origin argument must be a Point"
for params in bad_params_tests:
with self.subTest(params=params), self.assertRaisesMessage(TypeError, msg):
functions.Rotate("mpoly", **params)
@skipUnlessDBFeature("has_Scale_function")
def test_scale(self):
xfac, yfac = 2, 3
tol = 5 # The low precision tolerance is for SpatiaLite
qs = Country.objects.annotate(scaled=functions.Scale("mpoly", xfac, yfac))
for country in qs:
for p1, p2 in zip(country.mpoly, country.scaled):
for r1, r2 in zip(p1, p2):
for c1, c2 in zip(r1.coords, r2.coords):
self.assertAlmostEqual(c1[0] * xfac, c2[0], tol)
self.assertAlmostEqual(c1[1] * yfac, c2[1], tol)
# Test float/Decimal values
qs = Country.objects.annotate(
scaled=functions.Scale("mpoly", 1.5, Decimal("2.5"))
)
self.assertGreater(qs[0].scaled.area, qs[0].mpoly.area)
@skipUnlessDBFeature("has_SnapToGrid_function")
def test_snap_to_grid(self):
# Let's try and break snap_to_grid() with bad combinations of
# arguments.
for bad_args in ((), range(3), range(5)):
with self.assertRaises(ValueError):
Country.objects.annotate(snap=functions.SnapToGrid("mpoly", *bad_args))
for bad_args in (("1.0",), (1.0, None), tuple(map(str, range(4)))):
with self.assertRaises(TypeError):
Country.objects.annotate(snap=functions.SnapToGrid("mpoly", *bad_args))
# Boundary for San Marino, courtesy of Bjorn Sandvik of
# thematicmapping.org from the world borders dataset he provides.
wkt = (
"MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,"
"12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,"
"12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,"
"12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,"
"12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,"
"12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,"
"12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,"
"12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))"
)
Country.objects.create(name="San Marino", mpoly=fromstr(wkt))
# Because floating-point arithmetic isn't exact, we set a tolerance
# to pass into GEOS `equals_exact`.
tol = 0.000000001
# SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1))
# FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr("MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))")
self.assertTrue(
ref.equals_exact(
Country.objects.annotate(snap=functions.SnapToGrid("mpoly", 0.1))
.get(name="San Marino")
.snap,
tol,
)
)
# SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23))
# FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr(
"MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))"
)
self.assertTrue(
ref.equals_exact(
Country.objects.annotate(snap=functions.SnapToGrid("mpoly", 0.05, 0.23))
.get(name="San Marino")
.snap,
tol,
)
)
# SELECT AsText(
# ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23))
# FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr(
"MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,"
"12.45 43.87,12.4 43.87)))"
)
self.assertTrue(
ref.equals_exact(
Country.objects.annotate(
snap=functions.SnapToGrid("mpoly", 0.05, 0.23, 0.5, 0.17)
)
.get(name="San Marino")
.snap,
tol,
)
)
@skipUnlessDBFeature("has_SymDifference_function")
def test_sym_difference(self):
geom = Point(5, 23, srid=4326)
qs = Country.objects.annotate(
sym_difference=functions.SymDifference("mpoly", geom)
)
# Oracle does something screwy with the Texas geometry.
if connection.ops.oracle:
qs = qs.exclude(name="Texas")
for country in qs:
self.assertTrue(
country.mpoly.sym_difference(geom).equals(country.sym_difference)
)
@skipUnlessDBFeature("has_Transform_function")
def test_transform(self):
# Pre-transformed points for Houston and Pueblo.
ptown = fromstr("POINT(992363.390841912 481455.395105533)", srid=2774)
# Asserting the result of the transform operation with the values in
# the pre-transformed points.
h = City.objects.annotate(pt=functions.Transform("point", ptown.srid)).get(
name="Pueblo"
)
self.assertEqual(2774, h.pt.srid)
# Precision is low due to version variations in PROJ and GDAL.
self.assertLess(ptown.x - h.pt.x, 1)
self.assertLess(ptown.y - h.pt.y, 1)
@skipUnlessDBFeature("has_Translate_function")
def test_translate(self):
xfac, yfac = 5, -23
qs = Country.objects.annotate(
translated=functions.Translate("mpoly", xfac, yfac)
)
for c in qs:
for p1, p2 in zip(c.mpoly, c.translated):
for r1, r2 in zip(p1, p2):
for c1, c2 in zip(r1.coords, r2.coords):
# The low precision is for SpatiaLite
self.assertAlmostEqual(c1[0] + xfac, c2[0], 5)
self.assertAlmostEqual(c1[1] + yfac, c2[1], 5)
# Some combined function tests
@skipUnlessDBFeature(
"has_Difference_function",
"has_Intersection_function",
"has_SymDifference_function",
"has_Union_function",
)
def test_diff_intersection_union(self):
geom = Point(5, 23, srid=4326)
qs = Country.objects.annotate(
difference=functions.Difference("mpoly", geom),
sym_difference=functions.SymDifference("mpoly", geom),
union=functions.Union("mpoly", geom),
intersection=functions.Intersection("mpoly", geom),
)
if connection.ops.oracle:
# Should be able to execute the queries; however, they won't be the
# same as GEOS (because Oracle doesn't use GEOS internally like
# PostGIS or SpatiaLite).
return
for c in qs:
self.assertTrue(c.mpoly.difference(geom).equals(c.difference))
if connection.features.empty_intersection_returns_none:
self.assertIsNone(c.intersection)
else:
self.assertIs(c.intersection.empty, True)
self.assertTrue(c.mpoly.sym_difference(geom).equals(c.sym_difference))
self.assertTrue(c.mpoly.union(geom).equals(c.union))
@skipUnlessDBFeature("has_Union_function")
def test_union(self):
"""Union with all combinations of geometries/geometry fields."""
geom = Point(-95.363151, 29.763374, srid=4326)
union = (
City.objects.annotate(union=functions.Union("point", geom))
.get(name="Dallas")
.union
)
expected = fromstr(
"MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)", srid=4326
)
self.assertTrue(expected.equals(union))
union = (
City.objects.annotate(union=functions.Union(geom, "point"))
.get(name="Dallas")
.union
)
self.assertTrue(expected.equals(union))
union = (
City.objects.annotate(union=functions.Union("point", "point"))
.get(name="Dallas")
.union
)
expected = GEOSGeometry("POINT(-96.801611 32.782057)", srid=4326)
self.assertTrue(expected.equals(union))
union = (
City.objects.annotate(union=functions.Union(geom, geom))
.get(name="Dallas")
.union
)
self.assertTrue(geom.equals(union))
@skipUnlessDBFeature("has_Union_function", "has_Transform_function")
def test_union_mixed_srid(self):
"""The result SRID depends on the order of parameters."""
geom = Point(61.42915, 55.15402, srid=4326)
geom_3857 = geom.transform(3857, clone=True)
tol = 0.001
for city in City.objects.annotate(union=functions.Union("point", geom_3857)):
expected = city.point | geom
self.assertTrue(city.union.equals_exact(expected, tol))
self.assertEqual(city.union.srid, 4326)
for city in City.objects.annotate(union=functions.Union(geom_3857, "point")):
expected = geom_3857 | city.point.transform(3857, clone=True)
self.assertTrue(expected.equals_exact(city.union, tol))
self.assertEqual(city.union.srid, 3857)
def test_argument_validation(self):
with self.assertRaisesMessage(
ValueError, "SRID is required for all geometries."
):
City.objects.annotate(geo=functions.GeoFunc(Point(1, 1)))
msg = "GeoFunc function requires a GeometryField in position 1, got CharField."
with self.assertRaisesMessage(TypeError, msg):
City.objects.annotate(geo=functions.GeoFunc("name"))
msg = "GeoFunc function requires a geometric argument in position 1."
with self.assertRaisesMessage(TypeError, msg):
City.objects.annotate(union=functions.GeoFunc(1, "point")).get(
name="Dallas"
)
@skipUnlessDBFeature("has_GeometryType_function")
def test_geometry_type(self):
test_features = [
Feature(name="Point", geom=Point(0, 0)),
Feature(name="LineString", geom=LineString((0, 0), (1, 1))),
Feature(name="Polygon", geom=Polygon(((0, 0), (1, 0), (1, 1), (0, 0)))),
Feature(
name="MultiLineString",
geom=MultiLineString(
LineString((0, 0), (1, 1)), LineString((1, 1), (2, 2))
),
),
Feature(
name="MultiPolygon",
geom=MultiPolygon(
Polygon(((0, 0), (1, 0), (1, 1), (0, 0))),
Polygon(((1, 1), (2, 1), (2, 2), (1, 1))),
),
),
]
expected_results = [
("POINT", Point),
("LINESTRING", LineString),
("POLYGON", Polygon),
("MULTILINESTRING", MultiLineString),
("MULTIPOLYGON", MultiPolygon),
]
# GEOSWKTWriter_write() behavior was changed in GEOS 3.12+ to include
# parentheses for sub-members. MariaDB doesn't accept WKT
# representations with additional parentheses for MultiPoint. This is
# an accepted bug (MDEV-36166) in MariaDB that should be fixed in the
# future.
if not connection.ops.mariadb or geos_version_tuple() < (3, 12):
test_features.append(
Feature(name="MultiPoint", geom=MultiPoint(Point(0, 0), Point(1, 1)))
)
expected_results.append(("MULTIPOINT", MultiPoint))
for test_feature, (geom_type, geom_class) in zip(
test_features, expected_results, strict=True
):
with self.subTest(geom_type=geom_type, geom=test_feature.geom.wkt):
test_feature.save()
obj = (
Feature.objects.annotate(
geometry_type=functions.GeometryType("geom")
)
.filter(geom__geom_type=geom_type)
.get()
)
self.assertIsInstance(obj.geom, geom_class)
self.assertEqual(obj.geometry_type, geom_type)
| GISFunctionsTests |
python | huggingface__transformers | src/transformers/pipelines/text_to_audio.py | {
"start": 1130,
"end": 1387
} | class ____(TypedDict, total=False):
"""
audio (`AudioInput`):
The generated audio waveform.
sampling_rate (`int`):
The sampling rate of the generated audio waveform.
"""
audio: AudioInput
sampling_rate: int
| AudioOutput |
python | ray-project__ray | release/nightly_tests/dask_on_ray/large_scale_test.py | {
"start": 3093,
"end": 5133
} | class ____:
@staticmethod
def lazy_load_xarray_one_month(test_spec: TestSpec) -> xarray.Dataset:
"""
Lazily load an Xarray representing 1 month of data.
The Xarray's data variable is a dask.array that's lazily constructed.
Therefore, creating the Xarray object doesn't consume any memory.
But computing the Xarray will.
"""
dask_array_lists = list()
array_dtype = np.float32
# Create chunks with power-of-two sizes so that downstream
# FFT computations will work correctly.
rechunk_size = 2 << 23
# Create MINUTES_IN_A_MONTH number of Delayed objects where
# each Delayed object is loading an array.
for i in range(0, MINUTES_IN_A_MONTH):
dask_arr = dask.array.from_delayed(
dask.delayed(LoadRoutines.load_array_one_minute)(test_spec),
shape=INPUT_SHAPE,
dtype=array_dtype,
)
dask_array_lists.append(dask_arr)
# Return the final dask.array in an Xarray
return xarray.Dataset(
data_vars={
"data_var": (
["channel", "time"],
dask.array.rechunk(
dask.array.concatenate(dask_array_lists, axis=1),
chunks=(INPUT_SHAPE[0], rechunk_size),
),
)
},
coords={"channel": ("channel", np.arange(INPUT_SHAPE[0]))},
attrs={"hello": "world"},
)
@staticmethod
def load_array_one_minute(test_spec: TestSpec) -> np.ndarray:
"""
Load an array representing 1 minute of data. Each load consumes
~0.144GB of memory (3 * 200000 * 60 * 4 (bytes in a float)) = ~0.14GB
In real life, this is loaded from cloud storage or disk.
"""
if random.random() < test_spec.error_rate:
raise Exception("Data error!")
else:
return np.random.random(INPUT_SHAPE)
| LoadRoutines |
python | PyCQA__pylint | tests/functional/m/mapping_context.py | {
"start": 1354,
"end": 1594
} | class ____:
kwargs = None
def get_kwargs(self):
return self.kwargs
def run(self, **kwargs):
print(kwargs)
def dispatch(self):
kws = self.get_kwargs()
self.run(**kws)
# abstract class
| BaseThing |
python | sqlalchemy__sqlalchemy | test/sql/test_lambdas.py | {
"start": 58342,
"end": 64293
} | class ____(
fixtures.TestBase, testing.AssertsExecutionResults, AssertsCompiledSQL
):
__dialect__ = "default"
@testing.fails("wontfix issue #5767")
def test_detect_change_in_binds_no_tracking(self):
t1 = table("t1", column("q"), column("p"))
t2 = table("t2", column("q"), column("p"))
vv = [1, 2, 3]
# lambda produces either "t1 IN vv" or "NULL" based on the
# argument. will not produce a consistent cache key
elem = lambdas.DeferredLambdaElement(
lambda tab: tab.c.q.in_(vv) if tab.name == "t2" else null(),
roles.WhereHavingRole,
lambda_args=(t1,),
opts=lambdas.LambdaOptions(track_closure_variables=False),
)
self.assert_compile(elem.expr, "NULL")
assert_raises_message(
exc.InvalidRequestError,
r"Lambda callable at %s produced "
"a different set of bound parameters "
"than its original run: vv" % (elem.fn.__code__),
elem._resolve_with_args,
t2,
)
def test_detect_change_in_binds_tracking_positive(self):
t1 = table("t1", column("q"), column("p"))
vv = [1, 2, 3]
# lambda produces either "t1 IN vv" or "NULL" based on the
# argument. will not produce a consistent cache key
assert_raises_message(
exc.InvalidRequestError,
"Closure variable named 'vv' inside of lambda callable",
lambdas.DeferredLambdaElement,
lambda tab: tab.c.q.in_(vv) if tab.name == "t2" else None,
roles.WhereHavingRole,
opts=lambdas.LambdaOptions,
lambda_args=(t1,),
)
@testing.fails("wontfix issue #5767")
def test_detect_change_in_binds_tracking_negative(self):
t1 = table("t1", column("q"), column("p"))
t2 = table("t2", column("q"), column("p"))
vv = [1, 2, 3]
qq = [3, 4, 5]
# lambda produces either "t1 IN vv" or "t2 IN qq" based on the
# argument. will not produce a consistent cache key
elem = lambdas.DeferredLambdaElement(
lambda tab: (
tab.c.q.in_(vv) if tab.name == "t1" else tab.c.q.in_(qq)
),
roles.WhereHavingRole,
lambda_args=(t1,),
opts=lambdas.LambdaOptions(track_closure_variables=False),
)
self.assert_compile(elem.expr, "t1.q IN (__[POSTCOMPILE_vv_1])")
assert_raises_message(
exc.InvalidRequestError,
r"Lambda callable at %s produced "
"a different set of bound parameters "
"than its original run: qq" % (elem.fn.__code__),
elem._resolve_with_args,
t2,
)
def _fixture_one(self, t1):
vv = [1, 2, 3]
def go():
elem = lambdas.DeferredLambdaElement(
lambda tab: tab.c.q.in_(vv),
roles.WhereHavingRole,
lambda_args=(t1,),
opts=lambdas.LambdaOptions,
)
return elem
return go
def _fixture_two(self, t1):
def go():
elem = lambdas.DeferredLambdaElement(
lambda tab: tab.c.q == "x",
roles.WhereHavingRole,
lambda_args=(t1,),
opts=lambdas.LambdaOptions,
)
return elem
return go
def _fixture_three(self, t1):
def go():
elem = lambdas.DeferredLambdaElement(
lambda tab: tab.c.q != "x",
roles.WhereHavingRole,
lambda_args=(t1,),
opts=lambdas.LambdaOptions,
)
return elem
return go
def _fixture_four(self, t1):
def go():
elem = lambdas.DeferredLambdaElement(
lambda tab: tab.c.q.in_([1, 2, 3]),
roles.WhereHavingRole,
lambda_args=(t1,),
opts=lambdas.LambdaOptions,
)
return elem
return go
def _fixture_five(self, t1):
def go():
x = "x"
elem = lambdas.DeferredLambdaElement(
lambda tab: tab.c.q == x,
roles.WhereHavingRole,
lambda_args=(t1,),
opts=lambdas.LambdaOptions,
)
return elem
return go
def _fixture_six(self, t1):
def go():
x = "x"
elem = lambdas.DeferredLambdaElement(
lambda tab: tab.c.q != x,
roles.WhereHavingRole,
lambda_args=(t1,),
opts=lambdas.LambdaOptions,
)
return elem
return go
@testing.combinations(
("_fixture_one",),
("_fixture_two",),
("_fixture_three",),
("_fixture_four",),
("_fixture_five",),
("_fixture_six",),
)
def test_cache_key_many_different_args(self, fixture_name):
t1 = table("t1", column("q"), column("p"))
t2 = table("t2", column("q"), column("p"))
t3 = table("t3", column("q"), column("p"))
go = getattr(self, fixture_name)(t1)
g1 = go()
g2 = go()
g1key = g1._generate_cache_key()
g2key = g2._generate_cache_key()
eq_(g1key[0], g2key[0])
e1 = go()._resolve_with_args(t1)
e2 = go()._resolve_with_args(t2)
e3 = go()._resolve_with_args(t3)
e1key = e1._generate_cache_key()
e2key = e2._generate_cache_key()
e3key = e3._generate_cache_key()
e12 = go()._resolve_with_args(t1)
e32 = go()._resolve_with_args(t3)
e12key = e12._generate_cache_key()
e32key = e32._generate_cache_key()
ne_(e1key[0], e2key[0])
ne_(e2key[0], e3key[0])
eq_(e12key[0], e1key[0])
eq_(e32key[0], e3key[0])
| DeferredLambdaElementTest |
python | coleifer__peewee | tests/models.py | {
"start": 174628,
"end": 177168
} | class ____(ModelTestCase):
requires = [VL]
_data = [(1, 'one'), (2, 'two'), (3, 'three')]
def test_insert_into_select_from_vl(self):
vl = ValuesList(self._data)
cte = vl.cte('newvals', columns=['n', 's'])
res = (VL
.insert_from(cte.select(cte.c.n, cte.c.s), fields=[VL.n, VL.s])
.with_cte(cte)
.execute())
vq = VL.select().order_by(VL.n)
self.assertEqual([(v.n, v.s) for v in vq], self._data)
def test_update_vl_cte(self):
VL.insert_many(self._data).execute()
new_values = [(1, 'One'), (3, 'Three'), (4, 'Four')]
cte = ValuesList(new_values).cte('new_values', columns=('n', 's'))
# We have to use a subquery to update the individual column, as SQLite
# does not support UPDATE/FROM syntax.
subq = (cte
.select(cte.c.s)
.where(VL.n == cte.c.n))
# Perform the update, assigning extra the new value from the values
# list, and restricting the overall update using the composite pk.
res = (VL
.update(s=subq)
.where(VL.n.in_(cte.select(cte.c.n)))
.with_cte(cte)
.execute())
vq = VL.select().order_by(VL.n)
self.assertEqual([(v.n, v.s) for v in vq], [
(1, 'One'), (2, 'two'), (3, 'Three')])
def test_values_list(self):
vl = ValuesList(self._data)
query = vl.select(SQL('*'))
self.assertEqual(list(query.tuples().bind(self.database)), self._data)
@requires_postgresql
def test_values_list_named_columns(self):
vl = ValuesList(self._data).columns('idx', 'name')
query = (vl
.select(vl.c.idx, vl.c.name)
.order_by(vl.c.idx.desc()))
self.assertEqual(list(query.tuples().bind(self.database)),
self._data[::-1])
def test_values_list_named_columns_in_cte(self):
vl = ValuesList(self._data)
cte = vl.cte('val', columns=('idx', 'name'))
query = (cte
.select(cte.c.idx, cte.c.name)
.order_by(cte.c.idx.desc())
.with_cte(cte))
self.assertEqual(list(query.tuples().bind(self.database)),
self._data[::-1])
def test_named_values_list(self):
vl = ValuesList(self._data).alias('vl')
query = vl.select()
self.assertEqual(list(query.tuples().bind(self.database)), self._data)
| TestValuesListIntegration |
python | dask__distributed | distributed/comm/ucx.py | {
"start": 730,
"end": 801
} | class ____(Comm):
def __init__(self):
_raise_deprecated()
| UCX |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/preserve_defaults.py | {
"start": 1050,
"end": 1701
} | class ____:
"""docstring"""
# The properties will raise a silent SyntaxError because "lambda self: 1"
# will be detected as a function to update the default values of. However,
# only prop3 will not fail because it's on a single line whereas the others
# will fail to parse.
# fmt: off
prop1 = property(
lambda self: 1, doc='docstring')
prop2 = property(
lambda self: 2, doc='docstring'
)
prop3 = property(lambda self: 3, doc='docstring')
prop4 = (property
(lambda self: 4, doc='docstring'))
prop5 = property\
(lambda self: 5, doc='docstring') # NoQA: E211
# fmt: on
| MultiLine |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1409970,
"end": 1410367
} | class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, RepositoryAuditEntryData):
"""Audit log entry for a repo.remove_member event."""
__schema__ = github_schema
__field_names__ = ("visibility",)
visibility = sgqlc.types.Field(RepoRemoveMemberAuditEntryVisibility, graphql_name="visibility")
"""The visibility of the repository"""
| RepoRemoveMemberAuditEntry |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/proto/decode_proto_op_test_base.py | {
"start": 1196,
"end": 14405
} | class ____(test_base.ProtoOpTestBase, parameterized.TestCase):
"""Base class for testing proto decoding ops."""
def __init__(self, decode_module, methodName='runTest'): # pylint: disable=invalid-name
"""DecodeProtoOpTestBase initializer.
Args:
decode_module: a module containing the `decode_proto_op` method
methodName: the name of the test method (same as for test.TestCase)
"""
super(DecodeProtoOpTestBase, self).__init__(methodName)
self._decode_module = decode_module
def _compareValues(self, fd, vs, evs):
"""Compare lists/arrays of field values."""
if len(vs) != len(evs):
self.fail('Field %s decoded %d outputs, expected %d' %
(fd.name, len(vs), len(evs)))
for i, ev in enumerate(evs):
# Special case fuzzy match for float32. TensorFlow seems to mess with
# MAX_FLT slightly and the test doesn't work otherwise.
# TODO(nix): ask on TF list about why MAX_FLT doesn't pass through.
if fd.cpp_type == fd.CPPTYPE_FLOAT:
# Numpy isclose() is better than assertIsClose() which uses an absolute
# value comparison.
self.assertTrue(
np.isclose(vs[i], ev), 'expected %r, actual %r' % (ev, vs[i]))
elif fd.cpp_type == fd.CPPTYPE_STRING:
# In Python3 string tensor values will be represented as bytes, so we
# reencode the proto values to match that.
self.assertEqual(vs[i], ev.encode('ascii'))
else:
# Doubles and other types pass through unscathed.
self.assertEqual(vs[i], ev)
def _compareProtos(self, batch_shape, sizes, fields, field_dict):
"""Compare protos of type TestValue.
Args:
batch_shape: the shape of the input tensor of serialized messages.
sizes: int matrix of repeat counts returned by decode_proto
fields: list of test_example_pb2.FieldSpec (types and expected values)
field_dict: map from field names to decoded numpy tensors of values
"""
# Check that expected values match.
for field in fields:
values = field_dict[field.name]
self.assertEqual(dtypes.as_dtype(values.dtype), field.dtype)
if 'ext_value' in field.name:
fd = test_example_pb2.PrimitiveValue()
else:
fd = field.value.DESCRIPTOR.fields_by_name[field.name]
# Values has the same shape as the input plus an extra
# dimension for repeats.
self.assertEqual(list(values.shape)[:-1], batch_shape)
# Nested messages are represented as TF strings, requiring
# some special handling.
if field.name == 'message_value' or 'ext_value' in field.name:
vs = []
for buf in values.flat:
msg = test_example_pb2.PrimitiveValue()
msg.ParseFromString(buf)
vs.append(msg)
if 'ext_value' in field.name:
evs = field.value.Extensions[test_example_pb2.ext_value]
else:
evs = getattr(field.value, field.name)
if len(vs) != len(evs):
self.fail('Field %s decoded %d outputs, expected %d' %
(fd.name, len(vs), len(evs)))
for v, ev in zip(vs, evs):
self.assertEqual(v, ev)
continue
tf_type_to_primitive_value_field = {
dtypes.bool:
'bool_value',
dtypes.float32:
'float_value',
dtypes.float64:
'double_value',
dtypes.int8:
'int8_value',
dtypes.int32:
'int32_value',
dtypes.int64:
'int64_value',
dtypes.string:
'string_value',
dtypes.uint8:
'uint8_value',
dtypes.uint32:
'uint32_value',
dtypes.uint64:
'uint64_value',
}
if field.name in ['enum_value', 'enum_value_with_default']:
tf_field_name = 'enum_value'
else:
tf_field_name = tf_type_to_primitive_value_field.get(field.dtype)
if tf_field_name is None:
self.fail('Unhandled tensorflow type %d' % field.dtype)
self._compareValues(fd, values.flat,
getattr(field.value, tf_field_name))
def _runDecodeProtoTests(self, fields, case_sizes, batch_shape, batch,
message_type, message_format, sanitize,
force_disordered=False):
"""Run decode tests on a batch of messages.
Args:
fields: list of test_example_pb2.FieldSpec (types and expected values)
case_sizes: expected sizes array
batch_shape: the shape of the input tensor of serialized messages
batch: list of serialized messages
message_type: descriptor name for messages
message_format: format of messages, 'text' or 'binary'
sanitize: whether to sanitize binary protobuf inputs
force_disordered: whether to force fields encoded out of order.
"""
if force_disordered:
# Exercise code path that handles out-of-order fields by prepending extra
# fields with tag numbers higher than any real field. Note that this won't
# work with sanitization because that forces reserialization using a
# trusted decoder and encoder.
assert not sanitize
extra_fields = test_example_pb2.ExtraFields()
extra_fields.string_value = 'IGNORE ME'
extra_fields.bool_value = False
extra_msg = extra_fields.SerializeToString()
batch = [extra_msg + msg for msg in batch]
# Numpy silently truncates the strings if you don't specify dtype=object.
batch = np.array(batch, dtype=object)
batch = np.reshape(batch, batch_shape)
field_names = [f.name for f in fields]
output_types = [f.dtype for f in fields]
with self.cached_session() as sess:
sizes, vtensor = self._decode_module.decode_proto(
batch,
message_type=message_type,
field_names=field_names,
output_types=output_types,
message_format=message_format,
sanitize=sanitize)
vlist = sess.run([sizes] + vtensor)
sizes = vlist[0]
# Values is a list of tensors, one for each field.
value_tensors = vlist[1:]
# Check that the repeat sizes are correct.
self.assertTrue(
np.all(np.array(sizes.shape) == batch_shape + [len(field_names)]))
# Check that the decoded sizes match the expected sizes.
self.assertEqual(len(sizes.flat), len(case_sizes))
self.assertTrue(
np.all(sizes.flat == np.array(
case_sizes, dtype=np.int32)))
field_dict = dict(zip(field_names, value_tensors))
self._compareProtos(batch_shape, sizes, fields, field_dict)
@parameterized.named_parameters(*test_base.ProtoOpTestBase.named_parameters())
def testBinary(self, case):
batch = [value.SerializeToString() for value in case.values]
self._runDecodeProtoTests(
case.fields,
case.sizes,
list(case.shapes),
batch,
'tensorflow.contrib.proto.TestValue',
'binary',
sanitize=False)
@parameterized.named_parameters(*test_base.ProtoOpTestBase.named_parameters())
def testBinaryDisordered(self, case):
batch = [value.SerializeToString() for value in case.values]
self._runDecodeProtoTests(
case.fields,
case.sizes,
list(case.shapes),
batch,
'tensorflow.contrib.proto.TestValue',
'binary',
sanitize=False,
force_disordered=True)
@parameterized.named_parameters(
*test_base.ProtoOpTestBase.named_parameters(extension=False))
def testPacked(self, case):
# Now try with the packed serialization.
#
# We test the packed representations by loading the same test case using
# PackedTestValue instead of TestValue. To do this we rely on the text
# format being the same for packed and unpacked fields, and reparse the
# test message using the packed version of the proto.
packed_batch = [
# Note: float_format='.17g' is necessary to ensure preservation of
# doubles and floats in text format.
text_format.Parse(
text_format.MessageToString(value, float_format='.17g'),
test_example_pb2.PackedTestValue()).SerializeToString()
for value in case.values
]
self._runDecodeProtoTests(
case.fields,
case.sizes,
list(case.shapes),
packed_batch,
'tensorflow.contrib.proto.PackedTestValue',
'binary',
sanitize=False)
@parameterized.named_parameters(*test_base.ProtoOpTestBase.named_parameters())
def testText(self, case):
# Note: float_format='.17g' is necessary to ensure preservation of
# doubles and floats in text format.
text_batch = [
text_format.MessageToString(
value, float_format='.17g') for value in case.values
]
self._runDecodeProtoTests(
case.fields,
case.sizes,
list(case.shapes),
text_batch,
'tensorflow.contrib.proto.TestValue',
'text',
sanitize=False)
@parameterized.named_parameters(*test_base.ProtoOpTestBase.named_parameters())
def testSanitizerGood(self, case):
batch = [value.SerializeToString() for value in case.values]
self._runDecodeProtoTests(
case.fields,
case.sizes,
list(case.shapes),
batch,
'tensorflow.contrib.proto.TestValue',
'binary',
sanitize=True)
@parameterized.parameters((False), (True))
def testCorruptProtobuf(self, sanitize):
corrupt_proto = 'This is not a binary protobuf'
# Numpy silently truncates the strings if you don't specify dtype=object.
batch = np.array(corrupt_proto, dtype=object)
msg_type = 'tensorflow.contrib.proto.TestCase'
field_names = ['sizes']
field_types = [dtypes.int32]
with self.assertRaisesRegex(
errors.DataLossError, 'Unable to parse binary protobuf'
'|Failed to consume entire buffer'):
self.evaluate(
self._decode_module.decode_proto(
batch,
message_type=msg_type,
field_names=field_names,
output_types=field_types,
sanitize=sanitize))
def testUnexpectedType(self):
with self.assertRaisesRegex(
errors.InvalidArgumentError,
'Unexpected output type.*int64 to DT_STRING'):
msg = test_example_pb2.TestValue(
int64_value_with_default=3
).SerializeToString()
msg_type = 'tensorflow.contrib.proto.TestValue'
field_names = ['int64_value_with_default']
field_types = [dtypes.string]
self.evaluate(
self._decode_module.decode_proto(
msg,
message_type=msg_type,
field_names=field_names,
output_types=field_types,
)
)
def testOutOfOrderRepeated(self):
fragments = [
test_example_pb2.TestValue(double_value=[1.0]).SerializeToString(),
test_example_pb2.TestValue(
message_value=[test_example_pb2.PrimitiveValue(
string_value='abc')]).SerializeToString(),
test_example_pb2.TestValue(
message_value=[test_example_pb2.PrimitiveValue(
string_value='def')]).SerializeToString()
]
all_fields_to_parse = ['double_value', 'message_value']
field_types = {
'double_value': dtypes.double,
'message_value': dtypes.string,
}
# Test against all 3! permutations of fragments, and for each permutation
# test parsing all possible combination of 2 fields.
for indices in itertools.permutations(range(len(fragments))):
proto = b''.join(fragments[i] for i in indices)
for i in indices:
if i == 1:
expected_message_values = [
test_example_pb2.PrimitiveValue(
string_value='abc').SerializeToString(),
test_example_pb2.PrimitiveValue(
string_value='def').SerializeToString(),
]
break
if i == 2:
expected_message_values = [
test_example_pb2.PrimitiveValue(
string_value='def').SerializeToString(),
test_example_pb2.PrimitiveValue(
string_value='abc').SerializeToString(),
]
break
expected_field_values = {
'double_value': [[1.0]],
'message_value': [expected_message_values],
}
for num_fields_to_parse in range(len(all_fields_to_parse)):
for comb in itertools.combinations(
all_fields_to_parse, num_fields_to_parse):
parsed_values = self.evaluate(
self._decode_module.decode_proto(
[proto],
message_type='tensorflow.contrib.proto.TestValue',
field_names=comb,
output_types=[field_types[f] for f in comb],
sanitize=False)).values
self.assertLen(parsed_values, len(comb))
for field_name, parsed in zip(comb, parsed_values):
self.assertAllEqual(parsed, expected_field_values[field_name],
'perm: {}, comb: {}'.format(indices, comb))
| DecodeProtoOpTestBase |
python | sympy__sympy | sympy/functions/elementary/complexes.py | {
"start": 21703,
"end": 25365
} | class ____(DefinedFunction):
r"""
Returns the argument (in radians) of a complex number. The argument is
evaluated in consistent convention with ``atan2`` where the branch-cut is
taken along the negative real axis and ``arg(z)`` is in the interval
$(-\pi,\pi]$. For a positive number, the argument is always 0; the
argument of a negative number is $\pi$; and the argument of 0
is undefined and returns ``nan``. So the ``arg`` function will never nest
greater than 3 levels since at the 4th application, the result must be
nan; for a real number, nan is returned on the 3rd application.
Examples
========
>>> from sympy import arg, I, sqrt, Dummy
>>> from sympy.abc import x
>>> arg(2.0)
0
>>> arg(I)
pi/2
>>> arg(sqrt(2) + I*sqrt(2))
pi/4
>>> arg(sqrt(3)/2 + I/2)
pi/6
>>> arg(4 + 3*I)
atan(3/4)
>>> arg(0.8 + 0.6*I)
0.643501108793284
>>> arg(arg(arg(arg(x))))
nan
>>> real = Dummy(real=True)
>>> arg(arg(arg(real)))
nan
Parameters
==========
arg : Expr
Real or complex expression.
Returns
=======
value : Expr
Returns arc tangent of arg measured in radians.
"""
is_extended_real = True
is_real = True
is_finite = True
_singularities = True # non-holomorphic
@classmethod
def eval(cls, arg):
a = arg
for i in range(3):
if isinstance(a, cls):
a = a.args[0]
else:
if i == 2 and a.is_extended_real:
return S.NaN
break
else:
return S.NaN
from sympy.functions.elementary.exponential import exp, exp_polar
if isinstance(arg, exp_polar):
return periodic_argument(arg, oo)
elif isinstance(arg, exp):
i_ = im(arg.args[0])
if i_.is_comparable:
i_ %= 2*S.Pi
if i_ > S.Pi:
i_ -= 2*S.Pi
return i_
if not arg.is_Atom:
c, arg_ = factor_terms(arg).as_coeff_Mul()
if arg_.is_Mul:
arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else
sign(a) for a in arg_.args])
arg_ = sign(c)*arg_
else:
arg_ = arg
if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)):
return
from sympy.functions.elementary.trigonometric import atan2
x, y = arg_.as_real_imag()
rv = atan2(y, x)
if rv.is_number:
return rv
if arg_ != arg:
return cls(arg_, evaluate=False)
def _eval_derivative(self, t):
x, y = self.args[0].as_real_imag()
return (x * Derivative(y, t, evaluate=True) - y *
Derivative(x, t, evaluate=True)) / (x**2 + y**2)
def _eval_rewrite_as_atan2(self, arg, **kwargs):
from sympy.functions.elementary.trigonometric import atan2
x, y = self.args[0].as_real_imag()
return atan2(y, x)
def _eval_as_leading_term(self, x, logx, cdir):
arg0 = self.args[0]
t = Dummy('t', positive=True)
if cdir == 0:
cdir = 1
z = arg0.subs(x, cdir*t)
if z.is_positive:
return S.Zero
elif z.is_negative:
return S.Pi
else:
raise PoleError("Cannot expand %s around 0" % (self))
def _eval_nseries(self, x, n, logx, cdir=0):
from sympy.series.order import Order
if n <= 0:
return Order(1)
return self._eval_as_leading_term(x, logx=logx, cdir=cdir)
| arg |
python | explosion__spaCy | spacy/errors.py | {
"start": 67510,
"end": 68134
} | class ____(ValueError):
def __init__(self, key, errors):
"""Custom error for validating match patterns.
key (str): The name of the matcher rule.
errors (dict): Validation errors (sequence of strings) mapped to pattern
ID, i.e. the index of the added pattern.
"""
msg = f"Invalid token patterns for matcher rule '{key}'\n"
for pattern_idx, error_msgs in errors.items():
pattern_errors = "\n".join([f"- {e}" for e in error_msgs])
msg += f"\nPattern {pattern_idx}:\n{pattern_errors}\n"
ValueError.__init__(self, msg)
| MatchPatternError |
python | tensorflow__tensorflow | tensorflow/python/ops/image_grad_d9m_test.py | {
"start": 7632,
"end": 10239
} | class ____(test.TestCase):
"""Test d9m-unimplemented exceptions from CropAndResizeBackprop{Image|Boxes}.
Test that tf.errors.UnimplementedError is thrown or not thrown, as
appropriate, by the GPU code-paths for CropAndResizeBackprop{Image|Boxes} when
deterministic ops are enabled.
This test assumes that test_base.CropAndResizeOpTestBase runs all the same
test cases when deterministic ops are not enabled and will therefore detect
erroneous exception throwing in those cases.
"""
def _genParams(self, dtype=dtypes.float32):
batch_size = 1
image_height = 10
image_width = 10
channels = 1
image_shape = (batch_size, image_height, image_width, channels)
num_boxes = 3
boxes_shape = (num_boxes, 4)
random_seed.set_seed(123)
image = random_ops.random_normal(shape=image_shape, dtype=dtype)
boxes = random_ops.random_uniform(shape=boxes_shape, dtype=dtypes.float32)
box_indices = random_ops.random_uniform(
shape=(num_boxes,), minval=0, maxval=batch_size, dtype=dtypes.int32)
crop_size = constant_op.constant([3, 3], dtype=dtypes.int32)
return image, boxes, box_indices, crop_size
@test_util.run_in_graph_and_eager_modes
@test_util.run_gpu_only
def testExceptionThrowing(self):
for dtype in [dtypes.float16, dtypes.float32, dtypes.float64]:
image, boxes, box_indices, crop_size = self._genParams(dtype)
with backprop.GradientTape(persistent=True) as tape:
tape.watch(image)
tape.watch(boxes)
op_output = image_ops.crop_and_resize_v2(image, boxes, box_indices,
crop_size)
image_error_message = ('Deterministic GPU implementation of' +
' CropAndResizeBackpropImage not available')
with self.assertRaisesRegex(errors_impl.UnimplementedError,
image_error_message):
result = tape.gradient(op_output, image)
self.evaluate(result)
expected_error_message = ('Deterministic GPU implementation of' +
' CropAndResizeBackpropBoxes not available')
if context.executing_eagerly():
# With eager execution, the backprop-to-image code is apparently
# executed (first), even when its output is never used.
expected_error_message = image_error_message
with self.assertRaisesRegex(errors_impl.UnimplementedError,
expected_error_message):
result = tape.gradient(op_output, boxes)
self.evaluate(result)
| CropAndResizeOpDeterminismExceptionsTest |
python | numba__numba | numba/cuda/cudadrv/driver.py | {
"start": 81662,
"end": 82570
} | class ____(metaclass=ABCMeta):
griddim = 1, 1, 1
blockdim = 1, 1, 1
stream = 0
sharedmem = 0
def __init__(self, module, handle, name):
self.module = module
self.handle = handle
self.name = name
self.attrs = self.read_func_attr_all()
def __repr__(self):
return "<CUDA function %s>" % self.name
@property
def device(self):
return self.module.context.device
@abstractmethod
def cache_config(self, prefer_equal=False, prefer_cache=False,
prefer_shared=False):
"""Set the cache configuration for this function."""
@abstractmethod
def read_func_attr(self, attrid):
"""Return the value of the attribute with given ID."""
@abstractmethod
def read_func_attr_all(self):
"""Return a FuncAttr object with the values of various function
attributes."""
| Function |
python | pytorch__pytorch | torch/_inductor/runtime/caching/interfaces.py | {
"start": 5291,
"end": 11302
} | class ____(ABC):
def __init__(self) -> None:
self._lock: Lock = Lock()
def _make_key(
self,
fn: Callable[P, R],
params: Params,
ischema: context.IsolationSchema | None = None,
custom_params_encoder: Callable[P, Any] | None = None,
) -> Any:
callee: str = fn.__name__
fkey: Any = (
(callee, params)
if not custom_params_encoder
# pyrefly: ignore [invalid-param-spec]
else (callee, custom_params_encoder(*params[0], **params[1]))
)
ikey: Any = context._isolation_key(
ischema if ischema is not None else context._DEFAULT_ISOLATION_SCHEMA
)
return (fkey, ikey)
def _make_dummy_record_wrapper(self, fn: Callable[P, R]) -> Callable[P, R]:
@wraps(fn)
def dummy_wrapper(*args: Any, **kwargs: Any) -> R:
# pyrefly: ignore [invalid-param-spec]
return fn(*args, **kwargs)
# pyrefly: ignore [bad-return]
return dummy_wrapper
@abstractmethod
def _make_record_wrapper(
self,
fn: Callable[P, R],
ischema: context.IsolationSchema | None = None,
custom_params_encoder: Callable[P, Any] | None = None,
custom_result_encoder: Callable[[R], Any] | None = None,
custom_result_decoder: Callable[[Any], R] | None = None,
) -> Callable[P, R]:
pass
@abstractmethod
def _get(
self,
fn: Callable[P, R],
params: Params,
ischema: context.IsolationSchema | None = None,
custom_params_encoder: Callable[P, Any] | None = None,
custom_result_decoder: Callable[[Any], R] | None = None,
) -> impls.Hit | None:
pass
@abstractmethod
def _insert(
self,
fn: Callable[P, R],
params: Params,
result: R,
ischema: context.IsolationSchema | None = None,
custom_params_encoder: Callable[P, Any] | None = None,
custom_result_encoder: Callable[[R], Any] | None = None,
) -> bool:
pass
@property
def lock(self) -> locks._LockProtocol:
"""Get a context manager for acquiring the file lock.
Uses file locking to ensure thread safety across processes.
Args:
timeout: Optional timeout in seconds (float) for acquiring the file lock.
Returns:
A callable that returns a context manager for the file lock.
"""
def _lock_with_timeout(
timeout: float | None = None,
) -> locks._LockContextManager:
return locks._acquire_lock_with_timeout(self._lock, timeout)
return _lock_with_timeout
def get(
self,
fn: Callable[P, R],
params: Params,
ischema: context.IsolationSchema | None = None,
custom_params_encoder: Callable[P, Any] | None = None,
custom_result_decoder: Callable[[Any], R] | None = None,
) -> impls.Hit | None:
if not config.IS_CACHING_MODULE_ENABLED():
return None
start_t: float = time()
with self.lock(): # type: ignore[call-arg]
result: impls.Hit | None = self._get(
fn,
params,
ischema=ischema,
custom_params_encoder=custom_params_encoder,
custom_result_decoder=custom_result_decoder,
)
dur: float = time() - start_t
_intf_callback(
_IntfCallbackOrigin.GET,
_IntfCallbackAction.HIT if result else _IntfCallbackAction.MISS,
dur,
fn,
params,
*((result.value,) if result else ()),
)
return result
def insert(
self,
fn: Callable[P, R],
params: Params,
result: R,
ischema: context.IsolationSchema | None = None,
custom_params_encoder: Callable[P, Any] | None = None,
custom_result_encoder: Callable[[R], Any] | None = None,
) -> bool:
if not config.IS_CACHING_MODULE_ENABLED():
return False
start_t: float = time()
with self.lock(): # type: ignore[call-arg]
inserted: bool = self._insert(
fn,
params,
result,
ischema=ischema,
custom_params_encoder=custom_params_encoder,
custom_result_encoder=custom_result_encoder,
)
dur: float = time() - start_t
_intf_callback(
_IntfCallbackOrigin.INSERT,
_IntfCallbackAction.INSERTED
if inserted
else _IntfCallbackAction.NOT_INSERTED,
dur,
fn,
params,
result,
)
return inserted
def record(
self,
ischema: context.IsolationSchema | None = None,
custom_params_encoder: Callable[..., Any] | None = None,
custom_result_encoder: Callable[..., Any] | None = None,
custom_result_decoder: Callable[..., ...] | None = None,
) -> Callable[[Callable[..., ...]], Callable[..., ...]]:
if custom_result_encoder and not custom_result_decoder:
raise exceptions.CustomResultDecoderRequiredError(
"Custom result encoder provided without custom result decoder."
)
elif not custom_result_encoder and custom_result_decoder:
raise exceptions.CustomResultEncoderRequiredError(
"Custom result decoder provided without custom result encoder."
)
elif not config.IS_CACHING_MODULE_ENABLED():
return self._make_dummy_record_wrapper
else:
return partial(
self._make_record_wrapper,
ischema=ischema,
custom_params_encoder=custom_params_encoder,
custom_result_encoder=custom_result_encoder,
custom_result_decoder=custom_result_decoder,
)
| _CacheIntf |
python | huggingface__transformers | tests/models/phi4_multimodal/test_image_processing_phi4_multimodal.py | {
"start": 1200,
"end": 3939
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=100,
min_resolution=30,
max_resolution=400,
dynamic_hd=36,
do_resize=True,
size=None,
patch_size=14,
do_normalize=True,
image_mean=[0.5, 0.5, 0.5],
image_std=[0.5, 0.5, 0.5],
do_convert_rgb=True,
):
super().__init__()
size = size if size is not None else {"height": 100, "width": 100}
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_channels
self.image_size = image_size
self.min_resolution = min_resolution
self.max_resolution = max_resolution
self.dynamic_hd = dynamic_hd
self.do_resize = do_resize
self.size = size
self.patch_size = patch_size
self.do_normalize = do_normalize
self.image_mean = image_mean
self.image_std = image_std
self.do_convert_rgb = do_convert_rgb
def prepare_image_processor_dict(self):
return {
"do_resize": self.do_resize,
"size": self.size,
"patch_size": self.patch_size,
"dynamic_hd": self.dynamic_hd,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
def expected_output_image_shape(self, images):
max_num_patches = 0
for image in images:
if isinstance(image, Image.Image):
width, height = image.size
elif isinstance(image, np.ndarray):
height, width = image.shape[:2]
elif isinstance(image, torch.Tensor):
height, width = image.shape[-2:]
w_crop_num = math.ceil(width / float(self.size["width"]))
h_crop_num = math.ceil(height / float(self.size["height"]))
num_patches = min(w_crop_num * h_crop_num + 1, self.dynamic_hd)
max_num_patches = max(max_num_patches, num_patches)
num_patches = max_num_patches
return num_patches, self.num_channels, self.size["height"], self.size["width"]
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
return prepare_image_inputs(
batch_size=self.batch_size,
num_channels=self.num_channels,
min_resolution=self.min_resolution,
max_resolution=self.max_resolution,
equal_resolution=equal_resolution,
numpify=numpify,
torchify=torchify,
)
@require_torch
@require_vision
| Phi4MultimodalImageProcessingTester |
python | PyCQA__pylint | tests/regrtest_data/func_block_disable_msg.py | {
"start": 109,
"end": 2593
} | class ____:
"""block-disable test"""
def __init__(self):
self._test = "42"
def meth1(self, arg):
"""this issues a message"""
print(self)
def meth2(self, arg):
"""and this one not"""
# pylint: disable=W0613
print(self._test\
+ "foo")
def meth3(self):
"""test one line disabling"""
# no error
print(self.bla) # pylint: disable=E1101
# error
print(self.blop)
def meth4(self):
"""test re-enabling"""
# pylint: disable=E1101
# no error
print(self.bla)
print(self.blop)
# pylint: enable=E1101
# error
print(self.blip)
def meth5(self):
"""test IF sub-block re-enabling"""
# pylint: disable=E1101
# no error
print(self.bla)
if self.blop:
# pylint: enable=E1101
# error
print(self.blip)
else:
# no error
print(self.blip)
# no error
print(self.blip)
def meth6(self):
"""test TRY/EXCEPT sub-block re-enabling"""
# pylint: disable=E1101
# no error
print(self.bla)
try:
# pylint: enable=E1101
# error
print(self.blip)
except UndefinedName: # pylint: disable=E0602
# no error
print(self.blip)
# no error
print(self.blip)
def meth7(self):
"""test one line block opening disabling"""
if self.blop: # pylint: disable=E1101
# error
print(self.blip)
else:
# error
print(self.blip)
# error
print(self.blip)
def meth8(self):
"""test late disabling"""
# error
print(self.blip)
# pylint: disable=E1101
# no error
print(self.bla)
print(self.blop)
def meth9(self):
"""test re-enabling right after a block with whitespace"""
eris = 5
if eris: # pylint: disable=using-constant-test
print("In block")
# pylint: disable=E1101
# no error
print(self.bla)
print(self.blu)
# pylint: enable=E1101
# error
print(self.blip)
def meth10(self):
"""Test double disable"""
# pylint: disable=E1101
# no error
print(self.bla)
# pylint: disable=E1101
print(self.blu)
| Foo |
python | rapidsai__cudf | python/cudf/cudf_pandas_tests/test_array_function.py | {
"start": 638,
"end": 735
} | class ____:
def __array_function__(self, func, types, args, kwargs):
return "fast"
| Fast |
python | neetcode-gh__leetcode | python/1472-design-browser-history.py | {
"start": 29,
"end": 170
} | class ____:
def __init__(self, val, prev=None, next=None):
self.val = val
self.prev = prev
self.next = next
| ListNode |
python | kamyu104__LeetCode-Solutions | Python/binary-tree-preorder-traversal.py | {
"start": 182,
"end": 957
} | class ____(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result, curr = [], root
while curr:
if curr.left is None:
result.append(curr.val)
curr = curr.right
else:
node = curr.left
while node.right and node.right != curr:
node = node.right
if node.right is None:
result.append(curr.val)
node.right = curr
curr = curr.left
else:
node.right = None
curr = curr.right
return result
# Time: O(n)
# Space: O(h)
# Stack Solution
| Solution |
python | walkccc__LeetCode | solutions/1422. Maximum Score After Splitting a String/1422.py | {
"start": 0,
"end": 258
} | class ____:
def maxScore(self, s: str) -> int:
ans = 0
zeros = 0
ones = s.count('1')
for i in range(len(s) - 1):
if s[i] == '0':
zeros += 1
else:
ones -= 1
ans = max(ans, zeros + ones)
return ans
| Solution |
python | google__pytype | pytype/abstract/abstract_test.py | {
"start": 28345,
"end": 42317
} | class ____(AbstractTestBase):
def _make_func(
self,
name="_",
param_names=None,
posonly_count=0,
varargs_name=None,
kwonly_params=(),
kwargs_name=None,
defaults=(),
annotations=None,
):
return abstract.SimpleFunction.build(
name,
param_names or (),
posonly_count,
varargs_name,
kwonly_params,
kwargs_name,
defaults,
annotations or {},
self._ctx,
)
def _simple_sig(self, param_types, ret_type=None):
annots = {"_%d" % i: t for i, t in enumerate(param_types)}
params = tuple(annots.keys())
if ret_type:
annots["return"] = ret_type
return self._make_func(param_names=params, annotations=annots)
def test_simple_call(self):
f = self._simple_sig(
[self._ctx.convert.str_type], ret_type=self._ctx.convert.int_type
)
args = function.Args((
self._ctx.convert.build_string(self._ctx.root_node, "hello"),
))
node, ret = f.call(self._ctx.root_node, f, args)
self.assertIs(node, self._ctx.root_node)
(ret_val,) = ret.data
self.assertEqual(ret_val.cls, self._ctx.convert.int_type)
def test_call_with_bad_arg(self):
f = self._make_func(
param_names=("test",), annotations={"test": self._ctx.convert.str_type}
)
args = function.Args((self._ctx.convert.build_int(self._ctx.root_node),))
self.assertRaises(
error_types.WrongArgTypes, f.call, self._ctx.root_node, f, args
)
def test_call_with_no_args(self):
f = self._simple_sig(
[self._ctx.convert.str_type, self._ctx.convert.int_type]
)
args = function.Args(())
self.assertRaises(
error_types.MissingParameter, f.call, self._ctx.root_node, f, args
)
def test_call_with_multiple_arg_bindings(self):
f = self._simple_sig([self._ctx.convert.str_type])
arg = self._ctx.program.NewVariable()
arg.AddBinding(
self._ctx.convert.primitive_instances[str], [], self._ctx.root_node
)
arg.AddBinding(
self._ctx.convert.primitive_instances[int], [], self._ctx.root_node
)
args = function.Args((arg,))
node, ret = f.call(self._ctx.root_node, f, args)
self.assertIs(node, self._ctx.root_node)
self.assertIs(ret.data[0], self._ctx.convert.none)
def test_call_with_varargs(self):
f = self._make_func(
varargs_name="arg",
annotations={
"arg": self._ctx.convert.str_type,
"return": self._ctx.convert.str_type,
},
)
starargs = self._ctx.convert.build_tuple(
self._ctx.root_node,
(self._ctx.convert.build_string(self._ctx.root_node, ""),),
)
args = function.Args(posargs=(), starargs=starargs)
node, ret = f.call(self._ctx.root_node, f, args)
self.assertIs(node, self._ctx.root_node)
self.assertIs(ret.data[0].cls, self._ctx.convert.str_type)
def test_call_with_bad_varargs(self):
f = self._make_func(
varargs_name="arg", annotations={"arg": self._ctx.convert.str_type}
)
starargs = self._ctx.convert.build_tuple(
self._ctx.root_node,
(
self._ctx.convert.build_string(self._ctx.root_node, ""),
self._ctx.convert.build_int(self._ctx.root_node),
),
)
args = function.Args(posargs=(), starargs=starargs)
self.assertRaises(
error_types.WrongArgTypes, f.call, self._ctx.root_node, f, args
)
def test_call_with_multiple_varargs_bindings(self):
f = self._make_func(
varargs_name="arg", annotations={"arg": self._ctx.convert.str_type}
)
arg = self._ctx.program.NewVariable()
arg.AddBinding(
self._ctx.convert.primitive_instances[str], [], self._ctx.root_node
)
arg.AddBinding(
self._ctx.convert.primitive_instances[int], [], self._ctx.root_node
)
starargs = self._ctx.convert.build_tuple(self._ctx.root_node, (arg,))
args = function.Args(posargs=(), starargs=starargs)
f.call(self._ctx.root_node, f, args)
def test_call_with_kwargs(self):
f = self._make_func(
kwargs_name="kwarg", annotations={"kwarg": self._ctx.convert.str_type}
)
kwargs = abstract.Dict(self._ctx)
kwargs.update(
self._ctx.root_node,
{
"_1": self._ctx.convert.build_string(self._ctx.root_node, "1"),
"_2": self._ctx.convert.build_string(self._ctx.root_node, "2"),
},
)
kwargs = kwargs.to_variable(self._ctx.root_node)
args = function.Args(posargs=(), namedargs={}, starstarargs=kwargs)
f.call(self._ctx.root_node, f, args)
def test_call_with_bad_kwargs(self):
f = self._make_func(
kwargs_name="kwarg", annotations={"kwarg": self._ctx.convert.str_type}
)
kwargs = abstract.Dict(self._ctx)
kwargs.update(
self._ctx.root_node,
{"_1": self._ctx.convert.build_int(self._ctx.root_node)},
)
kwargs = kwargs.to_variable(self._ctx.root_node)
args = function.Args(posargs=(), namedargs={}, starstarargs=kwargs)
self.assertRaises(
error_types.WrongArgTypes, f.call, self._ctx.root_node, f, args
)
def test_call_with_kwonly_args(self):
f = self._make_func(
param_names=("test",),
kwonly_params=("a", "b"),
annotations={
"test": self._ctx.convert.str_type,
"a": self._ctx.convert.str_type,
"b": self._ctx.convert.str_type,
},
)
kwargs = abstract.Dict(self._ctx)
kwargs.update(
self._ctx.root_node,
{
"a": self._ctx.convert.build_string(self._ctx.root_node, "2"),
"b": self._ctx.convert.build_string(self._ctx.root_node, "3"),
},
)
kwargs = kwargs.to_variable(self._ctx.root_node)
args = function.Args(
posargs=(self._ctx.convert.build_string(self._ctx.root_node, "1"),),
namedargs={},
starstarargs=kwargs,
)
f.call(self._ctx.root_node, f, args)
kwargs = abstract.Dict(self._ctx)
kwargs.update(
self._ctx.root_node,
{"b": self._ctx.convert.build_string(self._ctx.root_node, "3")},
)
kwargs = kwargs.to_variable(self._ctx.root_node)
args = function.Args(
posargs=(
self._ctx.convert.build_string(self._ctx.root_node, "1"),
self._ctx.convert.build_int(self._ctx.root_node),
),
namedargs={},
starstarargs=kwargs,
)
self.assertRaises(
error_types.MissingParameter, f.call, self._ctx.root_node, f, args
)
def test_call_with_all_args(self):
f = self._make_func(
param_names=("a", "b"),
varargs_name="arg",
kwargs_name="kwarg",
defaults=(self._ctx.convert.build_int(self._ctx.root_node),),
annotations={
"a": self._ctx.convert.str_type,
"b": self._ctx.convert.int_type,
"arg": self._ctx.convert.primitive_classes[float],
"kwarg": self._ctx.convert.primitive_classes[bool],
},
)
posargs = (
self._ctx.convert.build_string(self._ctx.root_node, "1"),
self._ctx.convert.build_int(self._ctx.root_node),
)
float_inst = self._ctx.convert.primitive_instances[float]
stararg = self._ctx.convert.build_tuple(
self._ctx.root_node, (float_inst.to_variable(self._ctx.root_node),)
)
namedargs = {}
kwarg = abstract.Dict(self._ctx)
kwarg.update(
self._ctx.root_node,
{
"x": self._ctx.convert.build_bool(self._ctx.root_node),
"y": self._ctx.convert.build_bool(self._ctx.root_node),
},
)
kwarg = kwarg.to_variable(self._ctx.root_node)
args = function.Args(posargs, namedargs, stararg, kwarg)
f.call(self._ctx.root_node, f, args)
def test_call_with_defaults(self):
f = self._make_func(
param_names=("a", "b", "c"),
defaults=(self._ctx.convert.build_int(self._ctx.root_node),),
annotations={
"a": self._ctx.convert.int_type,
"b": self._ctx.convert.int_type,
"c": self._ctx.convert.int_type,
},
)
args = function.Args(
posargs=(
self._ctx.convert.build_int(self._ctx.root_node),
self._ctx.convert.build_int(self._ctx.root_node),
)
)
f.call(self._ctx.root_node, f, args)
args = function.Args(
posargs=(
self._ctx.convert.build_int(self._ctx.root_node),
self._ctx.convert.build_int(self._ctx.root_node),
self._ctx.convert.build_int(self._ctx.root_node),
)
)
f.call(self._ctx.root_node, f, args)
args = function.Args(
posargs=(self._ctx.convert.build_int(self._ctx.root_node),)
)
self.assertRaises(
error_types.MissingParameter, f.call, self._ctx.root_node, f, args
)
def test_call_with_bad_default(self):
f = self._make_func(
param_names=("a", "b"),
defaults=(self._ctx.convert.build_string(self._ctx.root_node, ""),),
annotations={
"a": self._ctx.convert.int_type,
"b": self._ctx.convert.str_type,
},
)
args = function.Args(
posargs=(
self._ctx.convert.build_int(self._ctx.root_node),
self._ctx.convert.build_int(self._ctx.root_node),
)
)
self.assertRaises(
error_types.WrongArgTypes, f.call, self._ctx.root_node, f, args
)
def test_call_with_duplicate_keyword(self):
f = self._simple_sig([self._ctx.convert.int_type] * 2)
args = function.Args(
posargs=(
self._ctx.convert.build_int(self._ctx.root_node),
self._ctx.convert.build_int(self._ctx.root_node),
),
namedargs={"_1": self._ctx.convert.build_int(self._ctx.root_node)},
)
self.assertRaises(
error_types.DuplicateKeyword, f.call, self._ctx.root_node, f, args
)
def test_call_with_wrong_arg_count(self):
f = self._simple_sig([self._ctx.convert.int_type])
args = function.Args(
posargs=(
self._ctx.convert.build_int(self._ctx.root_node),
self._ctx.convert.build_int(self._ctx.root_node),
)
)
self.assertRaises(
error_types.WrongArgCount, f.call, self._ctx.root_node, f, args
)
def test_change_defaults(self):
f = self._make_func(
param_names=("a", "b", "c"),
defaults=(self._ctx.convert.build_int(self._ctx.root_node),),
)
args = function.Args(
posargs=(
self._ctx.convert.build_int(self._ctx.root_node),
self._ctx.convert.build_int(self._ctx.root_node),
)
)
f.call(self._ctx.root_node, f, args)
new_defaults = self._ctx.convert.build_tuple(
self._ctx.root_node,
(
self._ctx.convert.build_int(self._ctx.root_node),
self._ctx.convert.build_int(self._ctx.root_node),
),
)
f.set_function_defaults(self._ctx.root_node, new_defaults)
f.call(self._ctx.root_node, f, args)
args = function.Args(
posargs=(self._ctx.convert.build_int(self._ctx.root_node),)
)
f.call(self._ctx.root_node, f, args)
def test_call_with_type_parameter(self):
ret_cls = abstract.ParameterizedClass(
self._ctx.convert.list_type,
{abstract_utils.T: abstract.TypeParameter(abstract_utils.T, self._ctx)},
self._ctx,
)
f = self._make_func(
param_names=("test",),
annotations={
"test": abstract.TypeParameter(abstract_utils.T, self._ctx),
"return": ret_cls,
},
)
args = function.Args(
posargs=(self._ctx.convert.build_int(self._ctx.root_node),)
)
_, ret = f.call(self._ctx.root_node, f, args)
# ret is an Instance(ParameterizedClass(list, {abstract_utils.T: int}))
# but we really only care about T.
self.assertIs(
ret.data[0].cls.formal_type_parameters[abstract_utils.T],
self._ctx.convert.int_type,
)
def test_signature_func_output_basic(self):
node = self._ctx.root_node
f = self._make_func(name="basic", param_names=("a", "b"))
fp = self._ctx.pytd_convert.value_to_pytd_def(node, f, f.name)
self.assertEqual(pytd_utils.Print(fp), "def basic(a, b) -> None: ...")
def test_signature_func_output_annotations(self):
node = self._ctx.root_node
f = self._make_func(
name="annots",
param_names=("a", "b"),
annotations={
"a": self._ctx.convert.int_type,
"b": self._ctx.convert.str_type,
"return": self._ctx.convert.int_type,
},
)
fp = self._ctx.pytd_convert.value_to_pytd_def(node, f, f.name)
self.assertEqual(
pytd_utils.Print(fp), "def annots(a: int, b: str) -> int: ..."
)
def test_signature_func_output(self):
node = self._ctx.root_node
dict_type = abstract.ParameterizedClass(
self._ctx.convert.dict_type,
{
abstract_utils.K: self._ctx.convert.str_type,
abstract_utils.V: self._ctx.convert.int_type,
},
self._ctx,
)
f = self._make_func(
name="test",
param_names=("a", "b"),
varargs_name="c",
kwonly_params=("d", "e"),
kwargs_name="f",
defaults={
"b": self._ctx.convert.build_int(node),
"d": self._ctx.convert.build_int(node),
},
annotations={
"a": self._ctx.convert.str_type,
"b": self._ctx.convert.int_type,
"c": self._ctx.convert.str_type,
"d": dict_type,
"e": self._ctx.convert.int_type,
"f": self._ctx.convert.str_type,
"return": self._ctx.convert.str_type,
},
)
fp = self._ctx.pytd_convert.value_to_pytd_def(node, f, f.name)
f_str = (
"def test(a: str, b: int = ..., *c: str, d: dict[str, int] = ...,"
" e: int, **f: str) -> str: ..."
)
self.assertEqual(pytd_utils.Print(fp), f_str)
| SimpleFunctionTest |
python | langchain-ai__langchain | libs/core/langchain_core/messages/tool.py | {
"start": 792,
"end": 5772
} | class ____(BaseMessage, ToolOutputMixin):
"""Message for passing the result of executing a tool back to a model.
`ToolMessage` objects contain the result of a tool invocation. Typically, the result
is encoded inside the `content` field.
Example: A `ToolMessage` representing a result of `42` from a tool call with id
```python
from langchain_core.messages import ToolMessage
ToolMessage(content="42", tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL")
```
Example: A `ToolMessage` where only part of the tool output is sent to the model
and the full output is passed in to artifact.
```python
from langchain_core.messages import ToolMessage
tool_output = {
"stdout": "From the graph we can see that the correlation between "
"x and y is ...",
"stderr": None,
"artifacts": {"type": "image", "base64_data": "/9j/4gIcSU..."},
}
ToolMessage(
content=tool_output["stdout"],
artifact=tool_output,
tool_call_id="call_Jja7J89XsjrOLA5r!MEOW!SL",
)
```
The `tool_call_id` field is used to associate the tool call request with the
tool call response. Useful in situations where a chat model is able
to request multiple tool calls in parallel.
"""
tool_call_id: str
"""Tool call that this message is responding to."""
type: Literal["tool"] = "tool"
"""The type of the message (used for serialization)."""
artifact: Any = None
"""Artifact of the Tool execution which is not meant to be sent to the model.
Should only be specified if it is different from the message content, e.g. if only
a subset of the full tool output is being passed as message content but the full
output is needed in other parts of the code.
"""
status: Literal["success", "error"] = "success"
"""Status of the tool invocation."""
additional_kwargs: dict = Field(default_factory=dict, repr=False)
"""Currently inherited from `BaseMessage`, but not used."""
response_metadata: dict = Field(default_factory=dict, repr=False)
"""Currently inherited from `BaseMessage`, but not used."""
@model_validator(mode="before")
@classmethod
def coerce_args(cls, values: dict) -> dict:
"""Coerce the model arguments to the correct types.
Args:
values: The model arguments.
"""
content = values["content"]
if isinstance(content, tuple):
content = list(content)
if not isinstance(content, (str, list)):
try:
values["content"] = str(content)
except ValueError as e:
msg = (
"ToolMessage content should be a string or a list of string/dicts. "
f"Received:\n\n{content=}\n\n which could not be coerced into a "
"string."
)
raise ValueError(msg) from e
elif isinstance(content, list):
values["content"] = []
for i, x in enumerate(content):
if not isinstance(x, (str, dict)):
try:
values["content"].append(str(x))
except ValueError as e:
msg = (
"ToolMessage content should be a string or a list of "
"string/dicts. Received a list but "
f"element ToolMessage.content[{i}] is not a dict and could "
f"not be coerced to a string.:\n\n{x}"
)
raise ValueError(msg) from e
else:
values["content"].append(x)
tool_call_id = values["tool_call_id"]
if isinstance(tool_call_id, (UUID, int, float)):
values["tool_call_id"] = str(tool_call_id)
return values
@overload
def __init__(
self,
content: str | list[str | dict],
**kwargs: Any,
) -> None: ...
@overload
def __init__(
self,
content: str | list[str | dict] | None = None,
content_blocks: list[types.ContentBlock] | None = None,
**kwargs: Any,
) -> None: ...
def __init__(
self,
content: str | list[str | dict] | None = None,
content_blocks: list[types.ContentBlock] | None = None,
**kwargs: Any,
) -> None:
"""Initialize a `ToolMessage`.
Specify `content` as positional arg or `content_blocks` for typing.
Args:
content: The contents of the message.
content_blocks: Typed standard content.
**kwargs: Additional fields.
"""
if content_blocks is not None:
super().__init__(
content=cast("str | list[str | dict]", content_blocks),
**kwargs,
)
else:
super().__init__(content=content, **kwargs)
| ToolMessage |
python | tensorflow__tensorflow | tensorflow/examples/custom_ops_doc/multiplex_3/multiplex_3_test.py | {
"start": 1109,
"end": 8209
} | class ____(tf.test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_sparse_kernel(self):
idx0 = tf.constant([], dtype=tf.int64, shape=[0, 1])
val0 = tf.constant([], dtype=tf.int64)
val5a = tf.constant([1, 2, 3, 4, 5], dtype=tf.int64)
idx5b = tf.constant([[10], [20], [30], [40], [50]], dtype=tf.int64)
val5b = tf.constant([10, 20, 30, 40, 50], dtype=tf.int64)
cond0 = tf.constant([], dtype=bool)
cond5 = tf.constant([True, False, True, False, True], dtype=bool)
val3a = tf.constant([1, 2, 3], dtype=tf.int64)
val3b = tf.constant([4, 5, 6], dtype=tf.int64)
idx3c = tf.constant([[10], [20], [30]], dtype=tf.int64)
idx3d = tf.constant([[30], [40], [50]], dtype=tf.int64)
idx3e = tf.constant([[10], [30], [50]], dtype=tf.int64)
cond3 = tf.constant([True, False, True], dtype=bool)
shape = tf.constant([100], dtype=tf.int64)
# all inputs empty
(result_index, result_values,
result_shape) = multiplex_3_op.examples_multiplex_sparse(
idx0, cond0, shape, idx0, val0, shape, idx0, val0, shape)
self.assertAllEqual(idx0, result_index)
self.assertAllEqual(val0, result_values)
self.assertAllEqual(shape, result_shape)
# only b is not empty
(result_index, result_values,
result_shape) = multiplex_3_op.examples_multiplex_sparse(
idx0, cond0, shape, idx0, val0, shape, idx5b, val5a, shape)
self.assertAllEqual(idx5b, result_index)
self.assertAllEqual(val5a, result_values)
self.assertAllEqual(shape, result_shape)
# all indices the same
(result_index, result_values,
result_shape) = multiplex_3_op.examples_multiplex_sparse(
idx5b, cond5, shape, idx5b, val5a, shape, idx5b, val5b, shape)
expect_values = tf.constant([1, 20, 3, 40, 5], dtype=tf.int64)
self.assertAllEqual(idx5b, result_index)
self.assertAllEqual(expect_values, result_values)
self.assertAllEqual(shape, result_shape)
# cond and a have same positions, b values after a values
(result_index, result_values,
result_shape) = multiplex_3_op.examples_multiplex_sparse(
idx3c, cond3, shape, idx3c, val3a, shape, idx3d, val3b, shape)
expect_index = tf.constant([[10], [30], [40], [50]], dtype=tf.int64)
expect_values = tf.constant([1, 3, 5, 6], dtype=tf.int64)
self.assertAllEqual(expect_index, result_index)
self.assertAllEqual(expect_values, result_values)
self.assertAllEqual(shape, result_shape)
# cond and a have same positions, b values before a values
(result_index, result_values,
result_shape) = multiplex_3_op.examples_multiplex_sparse(
idx3d, cond3, shape, idx3d, val3a, shape, idx3c, val3b, shape)
expect_index = tf.constant([[10], [20], [30], [50]], dtype=tf.int64)
expect_values = tf.constant([4, 5, 1, 3], dtype=tf.int64)
self.assertAllEqual(expect_index, result_index)
self.assertAllEqual(expect_values, result_values)
self.assertAllEqual(shape, result_shape)
# cond and b have same positions, b values after a values
(result_index, result_values,
result_shape) = multiplex_3_op.examples_multiplex_sparse(
idx3d, cond3, shape, idx3c, val3a, shape, idx3d, val3b, shape)
expect_index = tf.constant([[30], [40]], dtype=tf.int64)
expect_values = tf.constant([3, 5], dtype=tf.int64)
self.assertAllEqual(expect_index, result_index)
self.assertAllEqual(expect_values, result_values)
self.assertAllEqual(shape, result_shape)
# cond and b have same positions, b values before a values
(result_index, result_values,
result_shape) = multiplex_3_op.examples_multiplex_sparse(
idx3c, cond3, shape, idx3d, val3a, shape, idx3c, val3b, shape)
expect_index = tf.constant([[20], [30]], dtype=tf.int64)
expect_values = tf.constant([5, 1], dtype=tf.int64)
self.assertAllEqual(expect_index, result_index)
self.assertAllEqual(expect_values, result_values)
self.assertAllEqual(shape, result_shape)
# cond and a and b all have different positions
(result_index, result_values,
result_shape) = multiplex_3_op.examples_multiplex_sparse(
idx3e, cond3, shape, idx3c, val3a, shape, idx3d, val3b, shape)
expect_index = tf.constant([[10], [30], [40]], dtype=tf.int64)
expect_values = tf.constant([1, 4, 5], dtype=tf.int64)
self.assertAllEqual(expect_index, result_index)
self.assertAllEqual(expect_values, result_values)
self.assertAllEqual(shape, result_shape)
@test_util.run_in_graph_and_eager_modes
def test_sparse_op_only(self):
cond = tf.SparseTensor(
indices=[[1], [3], [6]], values=[True, False, True], dense_shape=[7])
a = tf.SparseTensor(
indices=[[1], [3], [5]], values=['a0', 'a1', 'a2'], dense_shape=[6])
b = tf.SparseTensor(
indices=[[0], [2], [3], [6]],
values=['b0', 'b1', 'b2', 'b3'],
dense_shape=[7])
result = self.evaluate(multiplex_3_op.multiplex_sparse(cond, a, b))
self.assertAllEqual([7], result.dense_shape)
self.assertAllEqual([[0], [1], [2], [3]], result.indices)
self.assertAllEqual([b'b0', b'a0', b'b1', b'b2'], result.values)
# The following tests use multiplex_2_op.multiplex, which now supports
# sparse tensors.
@test_util.run_in_graph_and_eager_modes
def test_sparse_op_same(self):
cond = tf.SparseTensor(
indices=[[1], [3], [6]], values=[True, False, True], dense_shape=[7])
a = tf.SparseTensor(
indices=[[1], [3], [6]], values=['a0', 'a1', 'a2'], dense_shape=[6])
b = tf.SparseTensor(
indices=[[1], [3], [6]], values=['b0', 'b1', 'b2'], dense_shape=[7])
result = self.evaluate(multiplex_2_op.multiplex(cond, a, b))
self.assertAllEqual([7], result.dense_shape)
self.assertAllEqual([[1], [3], [6]], result.indices)
self.assertAllEqual([b'a0', b'b1', b'a2'], result.values)
@test_util.run_in_graph_and_eager_modes
def test_sparse_op_different(self):
cond = tf.SparseTensor(
indices=[[1], [3], [6]], values=[True, False, True], dense_shape=[7])
a = tf.SparseTensor(
indices=[[1], [3], [5]], values=['a0', 'a1', 'a2'], dense_shape=[6])
b = tf.SparseTensor(
indices=[[0], [2], [3], [6]],
values=['b0', 'b1', 'b2', 'b3'],
dense_shape=[7])
result = self.evaluate(multiplex_2_op.multiplex(cond, a, b))
self.assertAllEqual([7], result.dense_shape)
self.assertAllEqual([[0], [1], [2], [3]], result.indices)
self.assertAllEqual([b'b0', b'a0', b'b1', b'b2'], result.values)
# muliplex still works on dense tensors
@test_util.run_in_graph_and_eager_modes
def test_multiplex_int(self):
a = tf.constant([1, 2, 3, 4, 5], dtype=tf.int64)
b = tf.constant([10, 20, 30, 40, 50], dtype=tf.int64)
cond = tf.constant([True, False, True, False, True], dtype=bool)
expect = np.where(self.evaluate(cond), self.evaluate(a), self.evaluate(b))
# expected result is [1, 20, 3, 40, 5]
result = multiplex_2_op.multiplex(cond, a, b)
self.assertAllEqual(result, expect)
if __name__ == '__main__':
tf.test.main()
| MultiplexOpRank1Test |
python | numba__numba | numba/misc/gdb_print_extension.py | {
"start": 5379,
"end": 5550
} | class ____:
def __init__(self, val):
self.val = val
def to_string(self):
return "%s+%sj" % (self.val['real'], self.val['imag'])
| NumbaComplexPrinter |
python | django-extensions__django-extensions | tests/management/commands/test_show_urls.py | {
"start": 363,
"end": 628
} | class ____(View):
pass
urlpatterns = [
path("lambda/view", lambda request: HttpResponse("OK")),
path("function/based/", function_based_view, name="function-based-view"),
path("class/based/", ClassView.as_view(), name="class-based-view"),
]
| ClassView |
python | pyca__cryptography | src/cryptography/hazmat/primitives/ciphers/modes.py | {
"start": 1739,
"end": 2627
} | class ____(ModeWithTweak):
name = "XTS"
def __init__(self, tweak: utils.Buffer):
utils._check_byteslike("tweak", tweak)
if len(tweak) != 16:
raise ValueError("tweak must be 128-bits (16 bytes)")
self._tweak = tweak
@property
def tweak(self) -> utils.Buffer:
return self._tweak
def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None:
if isinstance(algorithm, (algorithms.AES128, algorithms.AES256)):
raise TypeError(
"The AES128 and AES256 classes do not support XTS, please use "
"the standard AES class instead."
)
if algorithm.key_size not in (256, 512):
raise ValueError(
"The XTS specification requires a 256-bit key for AES-128-XTS"
" and 512-bit key for AES-256-XTS"
)
| XTS |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance20.py | {
"start": 300,
"end": 446
} | class ____(Generic[T]): ...
def func1(obj: object):
if isinstance(obj, ClassA):
reveal_type(obj, expected_text="ClassA[Unknown]")
| ClassA |
python | nedbat__coveragepy | tests/test_html.py | {
"start": 5172,
"end": 6370
} | class ____(HTMLParser):
"""An HTML parser for our HTML reports.
Assertions are made about the structure we expect.
"""
def __init__(self) -> None:
super().__init__()
self.lines: list[list[str]] = []
self.in_source = False
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag == "main":
assert attrs == [("id", "source")]
self.in_source = True
elif self.in_source and tag == "a":
dattrs = dict(attrs)
assert "id" in dattrs
ida = dattrs["id"]
assert ida is not None
assert ida[0] == "t"
line_no = int(ida[1:])
self.lines.append([])
assert line_no == len(self.lines)
def handle_endtag(self, tag: str) -> None:
if tag == "main":
self.in_source = False
def handle_data(self, data: str) -> None:
if self.in_source and self.lines:
self.lines[-1].append(data)
def text(self) -> list[str]:
"""Get the rendered text as a list of strings, one per line."""
return ["".join(l).rstrip() for l in self.lines]
| HtmlReportParser |
python | getsentry__sentry | src/sentry/backup/services/import_export/service.py | {
"start": 757,
"end": 5113
} | class ____(RpcService):
"""
A service for bulk importing and exporting models to and from JSON. All import/export operations
must be triggered from either a REGION or MONOLITH silo, but never from the CONTROL silo.
Unlike most other RPC services, the `..._by_model` methods in this service select their
implementations (local vs remote) based on their inputs. Specifically, they choose whether or
not to perform the underlying operation in the REGION (where all import/export operations must
start) or the CONTROL silo depending on the model being imported (aka the `model_name`
argument): if the model is a REGION model, the operation proceeds locally, whereas for CONTROL
models, an RPC call is made into the CONTROL silo.
In cases where Sentry is running in MONOLITH mode, the local implementation is always used,
since that is the only one available.
"""
key = "import_export"
local_mode = SiloMode.CONTROL
@classmethod
def get_local_implementation(cls) -> RpcService:
from sentry.backup.services.import_export.impl import UniversalImportExportService
return UniversalImportExportService()
@rpc_method
@abstractmethod
def import_by_model(
self,
*,
import_model_name: str = "",
scope: RpcImportScope | None = None,
flags: RpcImportFlags = DEFAULT_IMPORT_FLAGS,
filter_by: list[RpcFilter],
pk_map: RpcPrimaryKeyMap,
json_data: str = "",
min_ordinal: int,
) -> RpcImportResult:
"""
Import models of a certain kind from JSON source. Do not call this method directly - use
`get_importer_for_model` to select the correct implementation for the specific model being
imported.
"""
@staticmethod
def get_importer_for_model(
model: type[Model],
) -> Callable:
"""
Called should resolve their implementation of `export_by_model` by calling this method
first, rather than calling `export_by_model` directly. See this class' comment for more
information.
"""
if SiloMode.CONTROL in model._meta.silo_limit.modes: # type: ignore[attr-defined]
return import_export_service.import_by_model
return ImportExportService.get_local_implementation().import_by_model # type: ignore[attr-defined]
@rpc_method
@abstractmethod
def export_by_model(
self,
*,
export_model_name: str = "",
from_pk: int = 0,
scope: RpcExportScope | None = None,
filter_by: list[RpcFilter],
pk_map: RpcPrimaryKeyMap,
indent: int = 2,
) -> RpcExportResult:
"""
Export models of a certain kind to JSON. Do not call this method directly - use
`get_exporter_for_model` to select the correct implementation for the specific model being
exported.
"""
@staticmethod
def get_exporter_for_model(
model: type[Model],
) -> Callable:
"""
Called should resolve their implementation of `export_by_model` by calling this method
first, rather than calling `export_by_model` directly. See this class' comment for more
information.
"""
if SiloMode.CONTROL in model._meta.silo_limit.modes: # type: ignore[attr-defined]
return import_export_service.export_by_model
return ImportExportService.get_local_implementation().export_by_model # type: ignore[attr-defined]
@rpc_method
@abstractmethod
def get_all_globally_privileged_users(self) -> set[int]:
"""
Retrieves all of the "administrators" of the current instance.
A user is defined as a "globally privileged" administrator if one of the following is true
about them:
- Their `User` model has the `is_staff` flag set to `True`.
- Their `User` model has the `is_superuser` flag set to `True`.
- Their `User.id` is mentioned at least once in the `UserPermission` table (ie, they
have at least one global permission).
- Their `User.id` is mentioned at least once in the `UserRoleUser` table (ie, they have
at least one global user role).
"""
import_export_service = ImportExportService.create_delegation()
| ImportExportService |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 11375,
"end": 11742
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.l1 = torch.nn.Linear(10, 10)
self.l2 = torch.nn.ReLU()
self.l3 = torch.nn.Linear(10, 10)
self.l4 = torch.nn.ReLU()
def forward(self, x):
for _, block in self.named_children():
x = block(x)
return x
| NamedChildren |
python | viewflow__viewflow | viewflow/workflow/flow/nodes.py | {
"start": 7839,
"end": 8054
} | class ____(mixins.NodeDetailMixin, mixins.NodeCancelMixin, nodes.Obsolete):
index_view_class = views.IndexTaskView
detail_view_class = views.DetailTaskView
cancel_view_class = views.CancelTaskView
| Obsolete |
python | kamyu104__LeetCode-Solutions | Python/longest-square-streak-in-an-array.py | {
"start": 648,
"end": 1123
} | class ____(object):
def longestSquareStreak(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = collections.defaultdict(int)
nums.sort()
result = -1
for x in nums:
sqrt_x = int(x**0.5)
if sqrt_x**2 == x:
dp[x] = dp[sqrt_x]+1
else:
dp[x] = 1
result = max(result, dp[x])
return result if result != 1 else -1
| Solution2 |
python | getsentry__sentry | src/sentry/hybridcloud/models/outbox.py | {
"start": 17152,
"end": 17862
} | class ____(RegionOutboxBase):
class Meta:
app_label = "sentry"
db_table = "sentry_regionoutbox"
indexes = (
models.Index(
fields=(
"shard_scope",
"shard_identifier",
"category",
"object_identifier",
)
),
models.Index(
fields=(
"shard_scope",
"shard_identifier",
"scheduled_for",
)
),
models.Index(fields=("shard_scope", "shard_identifier", "id")),
)
# Outboxes bound from control silo -> region silo
| RegionOutbox |
python | astropy__astropy | astropy/visualization/stretch.py | {
"start": 24406,
"end": 25347
} | class ____(BaseStretch):
"""
Inverse transformation for `~astropy.visualization.HistEqStretch`.
Parameters
----------
data : array-like
The data defining the equalization.
values : array-like, optional
The input image values, which should already be normalized to
the [0:1] range.
"""
def __init__(self, data, values=None):
self.data = data[np.isfinite(data)]
if values is None:
self.values = np.linspace(0.0, 1.0, len(self.data))
else:
self.values = values
def __call__(self, values, clip=True, out=None):
values = _prepare(values, clip=clip, out=out)
values[:] = np.interp(values, self.values, self.data)
return values
@property
def inverse(self):
"""A stretch object that performs the inverse operation."""
return HistEqStretch(self.data, values=self.values)
| InvertedHistEqStretch |
python | django__django | tests/admin_views/admin.py | {
"start": 20823,
"end": 20901
} | class ____(admin.ModelAdmin):
autocomplete_fields = ["question"]
| AnswerAdmin |
python | bokeh__bokeh | src/bokeh/models/widgets/buttons.py | {
"start": 4461,
"end": 5328
} | class ____(AbstractButton):
''' A two-state toggle button.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
label = Override(default="Toggle")
active = Bool(False, help="""
The state of the toggle button.
""")
def on_click(self, handler: Callable[[bool], None]) -> None:
""" Set up a handler for button state changes (clicks).
Args:
handler (func) : handler function to call when button is toggled.
Returns:
None
"""
self.on_change('active', lambda attr, old, new: handler(new))
def js_on_click(self, handler: Callback) -> None:
""" Set up a JavaScript handler for button state changes (clicks). """
self.js_on_change('active', handler)
| Toggle |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/py_extension2/package.py | {
"start": 232,
"end": 877
} | class ____(PythonPackage):
"""A package which extends python. It also depends on another
package which extends the same package."""
homepage = "http://www.example.com"
url = "http://www.example.com/extension2-1.0.tar.gz"
# Override settings in base class
maintainers = []
extends("python")
depends_on("py-extension1", type=("build", "run"))
version("1.0", md5="00000000000000000000000000000210")
def install(self, spec, prefix):
mkdirp(prefix.bin)
with open(os.path.join(prefix.bin, "py-extension2"), "w+", encoding="utf-8") as fout:
fout.write(str(spec.version))
| PyExtension2 |
python | spyder-ide__spyder | spyder/api/preferences.py | {
"start": 553,
"end": 1961
} | class ____(BaseConfigTab):
"""
Widget that represents a tab on a preference page.
All calls to :class:`SpyderConfigPage` attributes are resolved
via delegation.
"""
# Name of the tab to display on the configuration page.
TITLE = None
def __init__(self, parent: SpyderConfigPage):
super().__init__(parent)
self.parent = parent
if self.TITLE is None or not isinstance(self.TITLE, str):
raise ValueError("TITLE must be a str")
def apply_settings(self) -> OptionSet:
"""
Hook called to manually apply settings that cannot be automatically
applied.
Reimplement this if the configuration tab has complex widgets that
cannot be created with any of the `self.create_*` calls.
"""
return set({})
def is_valid(self) -> bool:
"""
Return True if the tab contents are valid.
This method can be overriden to perform complex checks.
"""
return True
def __getattr__(self, attr):
this_class_dir = dir(self)
if attr not in this_class_dir:
return getattr(self.parent, attr)
else:
return super().__getattr__(attr)
def setLayout(self, layout):
"""Remove default margins by default."""
layout.setContentsMargins(0, 0, 0, 0)
super().setLayout(layout)
| SpyderPreferencesTab |
python | django__django | django/contrib/postgres/forms/ranges.py | {
"start": 761,
"end": 959
} | class ____(RangeWidget):
"""A widget that splits input into two <input type="hidden"> inputs."""
def __init__(self, attrs=None):
super().__init__(HiddenInput, attrs)
| HiddenRangeWidget |
python | huggingface__transformers | src/transformers/models/internvl/modeling_internvl.py | {
"start": 17514,
"end": 19105
} | class ____(InternVLVisionPreTrainedModel):
def __init__(self, config: InternVLVisionConfig) -> None:
super().__init__(config)
self.config = config
self.embeddings = InternVLVisionEmbeddings(config)
self.encoder = InternVLVisionEncoder(config)
self.layernorm = (
nn.Identity() if config.use_mean_pooling else nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embeddings.patch_embeddings
@check_model_inputs(tie_last_hidden_states=False)
@auto_docstring
def forward(
self,
pixel_values: torch.Tensor,
bool_masked_pos: Optional[torch.BoolTensor] = None,
) -> Union[tuple, InternVLVisionModelOutputWithPooling]:
r"""
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
"""
embedding_output, _ = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
encoder_outputs = self.encoder(embedding_output)
sequence_output = encoder_outputs[0]
sequence_output = self.layernorm(sequence_output)
return InternVLVisionModelOutputWithPooling(
last_hidden_state=sequence_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
@auto_docstring
| InternVLVisionModel |
python | getsentry__sentry | src/sentry/api/endpoints/index.py | {
"start": 320,
"end": 906
} | class ____(Endpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = ()
def get(self, request: Request) -> Response:
if request.user.is_authenticated:
user = User.objects.get(id=request.user.id)
user = serialize(user, user)
else:
user = None
if request.auth:
auth = {"scopes": request.auth.get_scopes()}
else:
auth = None
context = {"version": "0", "auth": auth, "user": user}
return Response(context, status=200)
| IndexEndpoint |
python | euske__pdfminer | pdfminer/pdfparser.py | {
"start": 463,
"end": 3981
} | class ____(PSStackParser):
"""
PDFParser fetch PDF objects from a file stream.
It can handle indirect references by referring to
a PDF document set by set_document method.
It also reads XRefs at the end of every PDF file.
Typical usage:
parser = PDFParser(fp)
parser.read_xref()
parser.read_xref(fallback=True) # optional
parser.set_document(doc)
parser.seek(offset)
parser.nextobject()
"""
def __init__(self, fp):
PSStackParser.__init__(self, fp)
self.doc = None
self.fallback = False
return
def set_document(self, doc):
"""Associates the parser with a PDFDocument object."""
self.doc = doc
return
KEYWORD_R = KWD(b'R')
KEYWORD_NULL = KWD(b'null')
KEYWORD_ENDOBJ = KWD(b'endobj')
KEYWORD_STREAM = KWD(b'stream')
KEYWORD_XREF = KWD(b'xref')
KEYWORD_STARTXREF = KWD(b'startxref')
def do_keyword(self, pos, token):
"""Handles PDF-related keywords."""
if token in (self.KEYWORD_XREF, self.KEYWORD_STARTXREF):
self.add_results(*self.pop(1))
elif token is self.KEYWORD_ENDOBJ:
self.add_results(*self.pop(4))
elif token is self.KEYWORD_NULL:
# null object
self.push((pos, None))
elif token is self.KEYWORD_R:
# reference to indirect object
try:
((_, objid), (_, genno)) = self.pop(2)
(objid, genno) = (int(objid), int(genno))
obj = PDFObjRef(self.doc, objid, genno)
self.push((pos, obj))
except PSSyntaxError:
pass
elif token is self.KEYWORD_STREAM:
# stream object
((_, dic),) = self.pop(1)
dic = dict_value(dic)
objlen = 0
if not self.fallback:
try:
objlen = int_value(dic['Length'])
except KeyError:
if STRICT:
raise PDFSyntaxError('/Length is undefined: %r' % dic)
self.seek(pos)
try:
(_, line) = self.nextline() # 'stream'
except PSEOF:
if STRICT:
raise PDFSyntaxError('Unexpected EOF')
return
pos += len(line)
self.fp.seek(pos)
data = self.fp.read(objlen)
self.seek(pos+objlen)
while 1:
try:
(linepos, line) = self.nextline()
except PSEOF:
if STRICT:
raise PDFSyntaxError('Unexpected EOF')
break
if b'endstream' in line:
i = line.index(b'endstream')
objlen += i
if self.fallback:
data += line[:i]
break
objlen += len(line)
if self.fallback:
data += line
self.seek(pos+objlen)
# XXX limit objlen not to exceed object boundary
if self.debug:
logging.debug('Stream: pos=%d, objlen=%d, dic=%r, data=%r...' % \
(pos, objlen, dic, data[:10]))
obj = PDFStream(dic, data, self.doc.decipher)
self.push((pos, obj))
else:
# others
self.push((pos, token))
return
## PDFStreamParser
##
| PDFParser |
python | django__django | tests/foreign_object/models/person.py | {
"start": 2081,
"end": 3122
} | class ____(models.Model):
# Table Column Fields
from_friend_country = models.ForeignKey(
Country, models.CASCADE, related_name="from_friend_country"
)
from_friend_id = models.IntegerField()
to_friend_country_id = models.IntegerField()
to_friend_id = models.IntegerField(null=True)
# Relation Fields
from_friend = models.ForeignObject(
Person,
on_delete=models.CASCADE,
from_fields=["from_friend_country", "from_friend_id"],
to_fields=["person_country_id", "id"],
related_name="from_friend",
)
to_friend_country = models.ForeignObject(
Country,
from_fields=["to_friend_country_id"],
to_fields=["id"],
related_name="to_friend_country",
on_delete=models.CASCADE,
)
to_friend = models.ForeignObject(
Person,
from_fields=["to_friend_country_id", "to_friend_id"],
to_fields=["person_country_id", "id"],
related_name="to_friend+",
on_delete=models.CASCADE,
)
| Friendship |
python | celery__celery | t/unit/utils/test_saferepr.py | {
"start": 2135,
"end": 2165
} | class ____(dict):
pass
| dict2 |
python | pytorch__pytorch | torch/nn/utils/_expanded_weights/conv_expanded_weights.py | {
"start": 572,
"end": 2925
} | class ____(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(
ctx: Any,
kwarg_names: list[str],
conv_fn: Callable[_P, _R],
*expanded_args_and_kwargs: Any,
) -> torch.Tensor:
expanded_args, expanded_kwargs = conv_args_and_kwargs(
kwarg_names, expanded_args_and_kwargs
)
orig_input = expanded_args[0]
was_same_padding = expanded_kwargs["padding"] == "same"
if isinstance(expanded_kwargs["padding"], str):
# if padding is a string, we'll do the necessary padding (slowly) using F.pad
kernel_size = expanded_args[1].shape[2:]
padding, dilation = expanded_kwargs["padding"], expanded_kwargs["dilation"]
input = conv_input_for_string_padding(
conv_fn, padding, expanded_args[0], dilation, kernel_size
)
expanded_args = (input, expanded_args[1])
# since we've already done the padding, don't need any more
expanded_kwargs["padding"] = 0
output = forward_helper(conv_fn, expanded_args, expanded_kwargs)
input, weight = expanded_args
batched_dim_size = conv_picker(conv_fn, 3, 4, 5)
if input.dim() != batched_dim_size:
raise RuntimeError(
f"Expanded Weights only support convolution with batched input, got {conv_fn} with an"
f"unbatched input of dim {input.dim()}, expected input of dim {batched_dim_size}"
)
# pyrefly: ignore [invalid-type-var]
ctx.conv_fn = conv_fn
ctx.batch_size = orig_input.shape[0]
ctx.input_required_grad = orig_input.requires_grad
ctx.orig_input_shape = orig_input.shape
ctx.was_same_padding = was_same_padding
ctx.stride, ctx.padding = expanded_kwargs["stride"], expanded_kwargs["padding"]
ctx.dilation, ctx.groups = (
expanded_kwargs["dilation"],
expanded_kwargs["groups"],
)
if isinstance(weight, ExpandedWeight):
ctx.input = input
ctx.weight = weight
ctx.bias = expanded_kwargs["bias"]
return output
@staticmethod
def backward(ctx: Any, *grad_outputs: Any) -> Any:
return conv_backward(ctx.conv_fn, ctx, grad_outputs[0])
| ConvPerSampleGrad |
python | gevent__gevent | src/greentest/3.12/test_interpreters.py | {
"start": 4011,
"end": 4591
} | class ____(TestBase):
def test_main(self):
main = interpreters.get_main()
current = interpreters.get_current()
self.assertEqual(current, main)
def test_subinterpreter(self):
main = _interpreters.get_main()
interp = interpreters.create()
out = _run_output(interp, dedent("""
from test.support import interpreters
cur = interpreters.get_current()
print(cur.id)
"""))
current = interpreters.Interpreter(int(out))
self.assertNotEqual(current, main)
| GetCurrentTests |
python | scipy__scipy | scipy/stats/tests/test_continuous.py | {
"start": 61674,
"end": 78833
} | class ____:
def test_ContinuousDistribution_only(self):
X = stats.Binomial(n=10, p=0.5)
# This is applied at the top level TransformedDistribution,
# so testing one subclass is enough
message = "Transformations are currently only supported for continuous RVs."
with pytest.raises(NotImplementedError, match=message):
stats.exp(X)
def test_truncate(self):
rng = np.random.default_rng(81345982345826)
lb = rng.random((3, 1))
ub = rng.random((3, 1))
lb, ub = np.minimum(lb, ub), np.maximum(lb, ub)
Y = stats.truncate(Normal(), lb=lb, ub=ub)
Y0 = stats.truncnorm(lb, ub)
y = Y0.rvs((3, 10), random_state=rng)
p = Y0.cdf(y)
assert_allclose(Y.logentropy(), np.log(Y0.entropy() + 0j))
assert_allclose(Y.entropy(), Y0.entropy())
assert_allclose(Y.median(), Y0.ppf(0.5))
assert_allclose(Y.mean(), Y0.mean())
assert_allclose(Y.variance(), Y0.var())
assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
assert_allclose(Y.skewness(), Y0.stats('s'))
assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
assert_allclose(Y.support(), Y0.support())
assert_allclose(Y.pdf(y), Y0.pdf(y))
assert_allclose(Y.cdf(y), Y0.cdf(y))
assert_allclose(Y.ccdf(y), Y0.sf(y))
assert_allclose(Y.icdf(p), Y0.ppf(p))
assert_allclose(Y.iccdf(p), Y0.isf(p))
assert_allclose(Y.logpdf(y), Y0.logpdf(y))
assert_allclose(Y.logcdf(y), Y0.logcdf(y))
assert_allclose(Y.logccdf(y), Y0.logsf(y))
assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
sample = Y.sample(10)
assert np.all((sample > lb) & (sample < ub))
@pytest.mark.fail_slow(10)
@given(data=strategies.data(), seed=strategies.integers(min_value=0))
def test_loc_scale(self, data, seed):
# Need tests with negative scale
rng = np.random.default_rng(seed)
class TransformedNormal(ShiftedScaledDistribution):
def __init__(self, *args, **kwargs):
super().__init__(StandardNormal(), *args, **kwargs)
tmp = draw_distribution_from_family(
TransformedNormal, data, rng, proportions=(1, 0, 0, 0), min_side=1)
dist, x, y, p, logp, result_shape, x_result_shape, xy_result_shape = tmp
loc = dist.loc
scale = dist.scale
dist0 = StandardNormal()
dist_ref = stats.norm(loc=loc, scale=scale)
x0 = (x - loc) / scale
y0 = (y - loc) / scale
a, b = dist.support()
a0, b0 = dist0.support()
assert_allclose(a, a0 + loc)
assert_allclose(b, b0 + loc)
with np.errstate(invalid='ignore', divide='ignore'):
assert_allclose(np.exp(dist.logentropy()), dist.entropy())
assert_allclose(dist.entropy(), dist_ref.entropy())
assert_allclose(dist.median(), dist0.median() + loc)
assert_allclose(dist.mode(), dist0.mode() + loc)
assert_allclose(dist.mean(), dist0.mean() + loc)
assert_allclose(dist.variance(), dist0.variance() * scale**2)
assert_allclose(dist.standard_deviation(), dist.variance()**0.5)
assert_allclose(dist.skewness(), dist0.skewness() * np.sign(scale))
assert_allclose(dist.kurtosis(), dist0.kurtosis())
assert_allclose(dist.logpdf(x), dist0.logpdf(x0) - np.log(scale))
assert_allclose(dist.pdf(x), dist0.pdf(x0) / scale)
assert_allclose(dist.logcdf(x), dist0.logcdf(x0))
assert_allclose(dist.cdf(x), dist0.cdf(x0))
assert_allclose(dist.logccdf(x), dist0.logccdf(x0))
assert_allclose(dist.ccdf(x), dist0.ccdf(x0))
assert_allclose(dist.logcdf(x, y), dist0.logcdf(x0, y0))
assert_allclose(dist.cdf(x, y), dist0.cdf(x0, y0))
assert_allclose(dist.logccdf(x, y), dist0.logccdf(x0, y0))
assert_allclose(dist.ccdf(x, y), dist0.ccdf(x0, y0))
assert_allclose(dist.ilogcdf(logp), dist0.ilogcdf(logp)*scale + loc)
assert_allclose(dist.icdf(p), dist0.icdf(p)*scale + loc)
assert_allclose(dist.ilogccdf(logp), dist0.ilogccdf(logp)*scale + loc)
assert_allclose(dist.iccdf(p), dist0.iccdf(p)*scale + loc)
for i in range(1, 5):
assert_allclose(dist.moment(i, 'raw'), dist_ref.moment(i))
assert_allclose(dist.moment(i, 'central'),
dist0.moment(i, 'central') * scale**i)
assert_allclose(dist.moment(i, 'standardized'),
dist0.moment(i, 'standardized') * np.sign(scale)**i)
# Transform back to the original distribution using all arithmetic
# operations; check that it behaves as expected.
dist = (dist - 2*loc) + loc
dist = dist/scale**2 * scale
z = np.zeros(dist._shape) # compact broadcasting
a, b = dist.support()
a0, b0 = dist0.support()
assert_allclose(a, a0 + z)
assert_allclose(b, b0 + z)
with np.errstate(invalid='ignore', divide='ignore'):
assert_allclose(dist.logentropy(), dist0.logentropy() + z)
assert_allclose(dist.entropy(), dist0.entropy() + z)
assert_allclose(dist.median(), dist0.median() + z)
assert_allclose(dist.mode(), dist0.mode() + z)
assert_allclose(dist.mean(), dist0.mean() + z)
assert_allclose(dist.variance(), dist0.variance() + z)
assert_allclose(dist.standard_deviation(), dist0.standard_deviation() + z)
assert_allclose(dist.skewness(), dist0.skewness() + z)
assert_allclose(dist.kurtosis(), dist0.kurtosis() + z)
assert_allclose(dist.logpdf(x), dist0.logpdf(x)+z)
assert_allclose(dist.pdf(x), dist0.pdf(x) + z)
assert_allclose(dist.logcdf(x), dist0.logcdf(x) + z)
assert_allclose(dist.cdf(x), dist0.cdf(x) + z)
assert_allclose(dist.logccdf(x), dist0.logccdf(x) + z)
assert_allclose(dist.ccdf(x), dist0.ccdf(x) + z)
assert_allclose(dist.ilogcdf(logp), dist0.ilogcdf(logp) + z)
assert_allclose(dist.icdf(p), dist0.icdf(p) + z)
assert_allclose(dist.ilogccdf(logp), dist0.ilogccdf(logp) + z)
assert_allclose(dist.iccdf(p), dist0.iccdf(p) + z)
for i in range(1, 5):
assert_allclose(dist.moment(i, 'raw'), dist0.moment(i, 'raw'))
assert_allclose(dist.moment(i, 'central'), dist0.moment(i, 'central'))
assert_allclose(dist.moment(i, 'standardized'),
dist0.moment(i, 'standardized'))
# These are tough to compare because of the way the shape works
# rng = np.random.default_rng(seed)
# rng0 = np.random.default_rng(seed)
# assert_allclose(dist.sample(x_result_shape, rng=rng),
# dist0.sample(x_result_shape, rng=rng0) * scale + loc)
# Should also try to test fit, plot?
@pytest.mark.fail_slow(5)
@pytest.mark.parametrize('exp_pow', ['exp', 'pow'])
def test_exp_pow(self, exp_pow):
rng = np.random.default_rng(81345982345826)
mu = rng.random((3, 1))
sigma = rng.random((3, 1))
X = Normal()*sigma + mu
if exp_pow == 'exp':
Y = stats.exp(X)
else:
Y = np.e ** X
Y0 = stats.lognorm(sigma, scale=np.exp(mu))
y = Y0.rvs((3, 10), random_state=rng)
p = Y0.cdf(y)
assert_allclose(Y.logentropy(), np.log(Y0.entropy()))
assert_allclose(Y.entropy(), Y0.entropy())
assert_allclose(Y.median(), Y0.ppf(0.5))
assert_allclose(Y.mean(), Y0.mean())
assert_allclose(Y.variance(), Y0.var())
assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
assert_allclose(Y.skewness(), Y0.stats('s'))
assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
assert_allclose(Y.support(), Y0.support())
assert_allclose(Y.pdf(y), Y0.pdf(y))
assert_allclose(Y.cdf(y), Y0.cdf(y))
assert_allclose(Y.ccdf(y), Y0.sf(y))
assert_allclose(Y.icdf(p), Y0.ppf(p))
assert_allclose(Y.iccdf(p), Y0.isf(p))
assert_allclose(Y.logpdf(y), Y0.logpdf(y))
assert_allclose(Y.logcdf(y), Y0.logcdf(y))
assert_allclose(Y.logccdf(y), Y0.logsf(y))
assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
seed = 3984593485
assert_allclose(Y.sample(rng=seed), np.exp(X.sample(rng=seed)))
@pytest.mark.fail_slow(10)
@pytest.mark.parametrize('scale', [1, 2, -1])
@pytest.mark.xfail_on_32bit("`scale=-1` fails on 32-bit; needs investigation")
def test_reciprocal(self, scale):
rng = np.random.default_rng(81345982345826)
a = rng.random((3, 1))
# Separate sign from scale. It's easy to scale the resulting
# RV with negative scale; we want to test the ability to divide
# by a RV with negative support
sign, scale = np.sign(scale), abs(scale)
# Reference distribution
InvGamma = stats.make_distribution(stats.invgamma)
Y0 = sign * scale * InvGamma(a=a)
# Test distribution
X = _Gamma(a=a) if sign > 0 else -_Gamma(a=a)
Y = scale / X
y = Y0.sample(shape=(3, 10), rng=rng)
p = Y0.cdf(y)
logp = np.log(p)
assert_allclose(Y.logentropy(), np.log(Y0.entropy()))
assert_allclose(Y.entropy(), Y0.entropy())
assert_allclose(Y.median(), Y0.median())
# moments are not finite
assert_allclose(Y.support(), Y0.support())
assert_allclose(Y.pdf(y), Y0.pdf(y))
assert_allclose(Y.cdf(y), Y0.cdf(y))
assert_allclose(Y.ccdf(y), Y0.ccdf(y))
assert_allclose(Y.icdf(p), Y0.icdf(p))
assert_allclose(Y.iccdf(p), Y0.iccdf(p))
assert_allclose(Y.logpdf(y), Y0.logpdf(y))
assert_allclose(Y.logcdf(y), Y0.logcdf(y))
assert_allclose(Y.logccdf(y), Y0.logccdf(y))
with np.errstate(divide='ignore', invalid='ignore'):
assert_allclose(Y.ilogcdf(logp), Y0.ilogcdf(logp))
assert_allclose(Y.ilogccdf(logp), Y0.ilogccdf(logp))
seed = 3984593485
assert_allclose(Y.sample(rng=seed), scale/(X.sample(rng=seed)))
@pytest.mark.fail_slow(5)
def test_log(self):
rng = np.random.default_rng(81345982345826)
a = rng.random((3, 1))
X = _Gamma(a=a)
Y0 = stats.loggamma(a)
Y = stats.log(X)
y = Y0.rvs((3, 10), random_state=rng)
p = Y0.cdf(y)
assert_allclose(Y.logentropy(), np.log(Y0.entropy()))
assert_allclose(Y.entropy(), Y0.entropy())
assert_allclose(Y.median(), Y0.ppf(0.5))
assert_allclose(Y.mean(), Y0.mean())
assert_allclose(Y.variance(), Y0.var())
assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
assert_allclose(Y.skewness(), Y0.stats('s'))
assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
assert_allclose(Y.support(), Y0.support())
assert_allclose(Y.pdf(y), Y0.pdf(y))
assert_allclose(Y.cdf(y), Y0.cdf(y))
assert_allclose(Y.ccdf(y), Y0.sf(y))
assert_allclose(Y.icdf(p), Y0.ppf(p))
assert_allclose(Y.iccdf(p), Y0.isf(p))
assert_allclose(Y.logpdf(y), Y0.logpdf(y))
assert_allclose(Y.logcdf(y), Y0.logcdf(y))
assert_allclose(Y.logccdf(y), Y0.logsf(y))
with np.errstate(invalid='ignore'):
assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
seed = 3984593485
assert_allclose(Y.sample(rng=seed), np.log(X.sample(rng=seed)))
def test_monotonic_transforms(self):
# Some tests of monotonic transforms that are better to be grouped or
# don't fit well above
X = Uniform(a=1, b=2)
X_str = "Uniform(a=1.0, b=2.0)"
assert str(stats.log(X)) == f"log({X_str})"
assert str(1 / X) == f"1/({X_str})"
assert str(stats.exp(X)) == f"exp({X_str})"
X = Uniform(a=-1, b=2)
message = "Division by a random variable is only implemented when the..."
with pytest.raises(NotImplementedError, match=message):
1 / X
message = "The logarithm of a random variable is only implemented when the..."
with pytest.raises(NotImplementedError, match=message):
stats.log(X)
message = "Raising an argument to the power of a random variable is only..."
with pytest.raises(NotImplementedError, match=message):
(-2) ** X
with pytest.raises(NotImplementedError, match=message):
1 ** X
with pytest.raises(NotImplementedError, match=message):
[0.5, 1.5] ** X
message = "Raising a random variable to the power of an argument is only"
with pytest.raises(NotImplementedError, match=message):
X ** (-2)
with pytest.raises(NotImplementedError, match=message):
X ** 0
with pytest.raises(NotImplementedError, match=message):
X ** [0.5, 1.5]
def test_arithmetic_operators(self):
rng = np.random.default_rng(2348923495832349834)
a, b, loc, scale = 0.294, 1.34, 0.57, 1.16
x = rng.uniform(-3, 3, 100)
Y = _LogUniform(a=a, b=b)
X = scale*Y + loc
assert_allclose(X.cdf(x), Y.cdf((x - loc) / scale))
X = loc + Y*scale
assert_allclose(X.cdf(x), Y.cdf((x - loc) / scale))
X = Y/scale - loc
assert_allclose(X.cdf(x), Y.cdf((x + loc) * scale))
X = loc -_LogUniform(a=a, b=b)/scale
assert_allclose(X.cdf(x), Y.ccdf((-x + loc)*scale))
def test_abs(self):
rng = np.random.default_rng(81345982345826)
loc = rng.random((3, 1))
Y = stats.abs(Normal() + loc)
Y0 = stats.foldnorm(loc)
y = Y0.rvs((3, 10), random_state=rng)
p = Y0.cdf(y)
assert_allclose(Y.logentropy(), np.log(Y0.entropy() + 0j))
assert_allclose(Y.entropy(), Y0.entropy())
assert_allclose(Y.median(), Y0.ppf(0.5))
assert_allclose(Y.mean(), Y0.mean())
assert_allclose(Y.variance(), Y0.var())
assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
assert_allclose(Y.skewness(), Y0.stats('s'))
assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
assert_allclose(Y.support(), Y0.support())
assert_allclose(Y.pdf(y), Y0.pdf(y))
assert_allclose(Y.cdf(y), Y0.cdf(y))
assert_allclose(Y.ccdf(y), Y0.sf(y))
assert_allclose(Y.icdf(p), Y0.ppf(p))
assert_allclose(Y.iccdf(p), Y0.isf(p))
assert_allclose(Y.logpdf(y), Y0.logpdf(y))
assert_allclose(Y.logcdf(y), Y0.logcdf(y))
assert_allclose(Y.logccdf(y), Y0.logsf(y))
assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
sample = Y.sample(10)
assert np.all(sample > 0)
def test_abs_finite_support(self):
# The original implementation of `FoldedDistribution` might evaluate
# the private distribution methods outside the support. Check that this
# is resolved.
Weibull = stats.make_distribution(stats.weibull_min)
X = Weibull(c=2)
Y = abs(-X)
assert_equal(X.logpdf(1), Y.logpdf(1))
assert_equal(X.pdf(1), Y.pdf(1))
assert_equal(X.logcdf(1), Y.logcdf(1))
assert_equal(X.cdf(1), Y.cdf(1))
assert_equal(X.logccdf(1), Y.logccdf(1))
assert_equal(X.ccdf(1), Y.ccdf(1))
def test_pow(self):
rng = np.random.default_rng(81345982345826)
Y = Normal()**2
Y0 = stats.chi2(df=1)
y = Y0.rvs(10, random_state=rng)
p = Y0.cdf(y)
assert_allclose(Y.logentropy(), np.log(Y0.entropy() + 0j), rtol=1e-6)
assert_allclose(Y.entropy(), Y0.entropy(), rtol=1e-6)
assert_allclose(Y.median(), Y0.median())
assert_allclose(Y.mean(), Y0.mean())
assert_allclose(Y.variance(), Y0.var())
assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
assert_allclose(Y.skewness(), Y0.stats('s'))
assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
assert_allclose(Y.support(), Y0.support())
assert_allclose(Y.pdf(y), Y0.pdf(y))
assert_allclose(Y.cdf(y), Y0.cdf(y))
assert_allclose(Y.ccdf(y), Y0.sf(y))
assert_allclose(Y.icdf(p), Y0.ppf(p))
assert_allclose(Y.iccdf(p), Y0.isf(p))
assert_allclose(Y.logpdf(y), Y0.logpdf(y))
assert_allclose(Y.logcdf(y), Y0.logcdf(y))
assert_allclose(Y.logccdf(y), Y0.logsf(y))
assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
sample = Y.sample(10)
assert np.all(sample > 0)
| TestTransforms |
python | getsentry__sentry | src/sentry/buffer/redis.py | {
"start": 2726,
"end": 4798
} | class ____:
def __init__(self, incr_batch_size: int) -> None:
self.incr_batch_size = incr_batch_size
self.default_pending_buffer = PendingBuffer(self.incr_batch_size)
# map of model_key to PendingBufferValue
self.pending_buffer_router: dict[str, PendingBufferValue] = dict()
def create_pending_buffer(self, model_key: str, generate_queue: ChooseQueueFunction) -> None:
"""
Create a PendingBuffer for the given model_key and queue name.
We assume that there will be a dedicated queue for the given model associated with the model_key.
"""
pending_buffer = PendingBuffer(self.incr_batch_size)
self.pending_buffer_router[model_key] = PendingBufferValue(
model_key=model_key, pending_buffer=pending_buffer, generate_queue=generate_queue
)
def get_pending_buffer(self, model_key: str | None) -> PendingBuffer:
"""
Get the pending buffer assigned to the given model_key.
"""
if model_key is not None and model_key in self.pending_buffer_router:
return self.pending_buffer_router[model_key].pending_buffer
return self.default_pending_buffer
def queue(self, model_key: str) -> str | None:
"""
Get the queue name for the given model_key.
"""
metrics.incr(f"pendingbuffer-router.queue.{model_key}")
if model_key in self.pending_buffer_router:
metrics.incr(f"pendingbuffer-router.queue-found.{model_key}")
generate_queue = self.pending_buffer_router[model_key].generate_queue
if generate_queue is not None:
return generate_queue(model_key)
return None
def pending_buffers(self) -> list[PendingBufferValue]:
pending_buffers = list(self.pending_buffer_router.values())
pending_buffers.append(
PendingBufferValue(
model_key=None, pending_buffer=self.default_pending_buffer, generate_queue=None
)
)
return pending_buffers
| PendingBufferRouter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.