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 | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_cache_implementation.py | {
"start": 861,
"end": 2918
} | class ____(RuleBasedStateMachine):
keys = Bundle("keys")
@initialize(max_size=st.integers(1, 8))
def create_cache(self, max_size):
self.cache = CacheWithScores(max_size)
self.__values = {}
self.__total_pins = 0
self.__pins = Counter()
self.__live = set()
self.__next_value = 0
self.__last_key = None
def on_evict(evicted_key, value, score):
assert self.__pins[evicted_key] == 0
assert score == self.cache.scores[evicted_key]
assert value == self.__values[evicted_key]
for k in self.cache:
assert (
self.__pins[k] > 0
or self.cache.scores[k] >= score
or k == self.__last_key
)
self.cache.on_evict = on_evict
@rule(key=st.integers(), score=st.integers(0, 100), target=keys)
def new_key(self, key, score):
if key not in self.cache.scores:
self.cache.scores[key] = score
return key
@rule(key=keys)
def set_key(self, key):
if self.__total_pins < self.cache.max_size or key in self.cache:
self.__last_key = key
self.cache[key] = self.__next_value
self.__values[key] = self.__next_value
self.__next_value += 1
@invariant()
def check_values(self):
self.cache.check_valid()
for key in self.cache:
assert self.__values[key] == self.cache[key]
@rule(key=keys)
def pin_key(self, key):
if key in self.cache:
self.cache.pin(key, self.__values[key])
if self.__pins[key] == 0:
self.__total_pins += 1
self.__pins[key] += 1
@rule(key=keys)
def unpin_key(self, key):
if self.__pins[key] > 0:
self.cache.unpin(key)
self.__pins[key] -= 1
if self.__pins[key] == 0:
self.__total_pins -= 1
assert self.__total_pins >= 0
TestCache = CacheRules.TestCase
| CacheRules |
python | tensorflow__tensorflow | tensorflow/python/ops/weak_tensor_ops_test.py | {
"start": 15076,
"end": 32636
} | class ____(
test_util.TensorFlowTestCase, parameterized.TestCase
):
def match_expected(self, actual, expected_val, expected_dtype):
dtype, weak = expected_dtype
expected_type = WeakTensor if weak else tensor.Tensor
self.assertIsInstance(actual, expected_type)
self.assertEqual(actual.dtype, dtype)
self.assertAllEqual(actual, expected_val)
def test_weak_tensor_add(self, a_dtype, b_dtype, expected_dtype):
def run_test_add(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
expected_val = constant_op.constant(
a, expected_dtype[0]
) + constant_op.constant(b, expected_dtype[0])
for x, y in zip(a_list, b_list):
self.match_expected(math_ops.add(x, y), expected_val, expected_dtype)
self.match_expected(math_ops.add(y, x), expected_val, expected_dtype)
if at_least_one_tensor_type(x, y):
self.match_expected(x + y, expected_val, expected_dtype)
self.match_expected(y + x, expected_val, expected_dtype)
# Limit testing values to positive numbers inputs to account for
# both unsigned and signed input types.
run_test_add(a=2, b=4)
run_test_add(a=100, b=100)
run_test_add(a=10, b=41)
def test_weak_tensor_sub(self, a_dtype, b_dtype, expected_dtype):
def run_test_sub(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = a_tensor - b_tensor
expected_val_reverse = b_tensor - a_tensor
for x, y in zip(a_list, b_list):
self.match_expected(
math_ops.subtract(x, y), expected_val, expected_dtype
)
self.match_expected(
math_ops.subtract(y, x), expected_val_reverse, expected_dtype
)
if at_least_one_tensor_type(x, y):
self.match_expected(x - y, expected_val, expected_dtype)
self.match_expected(y - x, expected_val_reverse, expected_dtype)
run_test_sub(a=4, b=2)
run_test_sub(a=41, b=0)
run_test_sub(a=100, b=50)
def test_weak_tensor_mul(self, a_dtype, b_dtype, expected_dtype):
def run_test_mul(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
expected_val = constant_op.constant(
a, expected_dtype[0]
) * constant_op.constant(b, expected_dtype[0])
for x, y in zip(a_list, b_list):
self.match_expected(
math_ops.multiply(x, y), expected_val, expected_dtype
)
self.match_expected(
math_ops.multiply(y, x), expected_val, expected_dtype
)
if at_least_one_tensor_type(a, b):
self.match_expected(x * y, expected_val, expected_dtype)
self.match_expected(y * x, expected_val, expected_dtype)
run_test_mul(a=4, b=2)
run_test_mul(a=41, b=10)
run_test_mul(a=10, b=5)
def test_weak_tensor_pow(self, a_dtype, b_dtype, expected_dtype):
def run_test_pow(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
# Skip if provided dtype is not a valid input dtype for the op.
if not output_dtype_supported_in_op("pow", expected_dtype[0]):
return
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = a_tensor**b_tensor
reverse_expected_val = b_tensor**a_tensor
for x, y in zip(a_list, b_list):
self.match_expected(math_ops.pow(x, y), expected_val, expected_dtype)
self.match_expected(
math_ops.pow(y, x), reverse_expected_val, expected_dtype
)
if at_least_one_tensor_type(x, y):
self.match_expected(x**y, expected_val, expected_dtype)
self.match_expected(y**x, reverse_expected_val, expected_dtype)
run_test_pow(a=4, b=2)
run_test_pow(a=10, b=5)
def test_weak_tensor_mod(self, a_dtype, b_dtype, expected_dtype):
def run_test_mod(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
# Skip if provided dtype is not a valid input dtype for the op.
if not output_dtype_supported_in_op("mod", expected_dtype[0]):
return
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = a_tensor % b_tensor
reverse_expected_val = b_tensor % a_tensor
for x, y in zip(a_list, b_list):
self.match_expected(math_ops.mod(x, y), expected_val, expected_dtype)
self.match_expected(
math_ops.mod(y, x), reverse_expected_val, expected_dtype
)
# math_ops.mod and gen_math_ops.floor_mod are used interchangeably.
self.match_expected(
gen_math_ops.floor_mod(x, y), expected_val, expected_dtype
)
self.match_expected(
gen_math_ops.floor_mod(y, x), reverse_expected_val, expected_dtype
)
if at_least_one_tensor_type(x, y):
self.match_expected(x % y, expected_val, expected_dtype)
self.match_expected(y % x, reverse_expected_val, expected_dtype)
run_test_mod(a=4, b=2)
run_test_mod(a=41, b=124)
run_test_mod(a=2, b=6)
def test_weak_tensor_floor_div(self, a_dtype, b_dtype, expected_dtype):
def run_test_floor_div(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
# Skip if provided dtype is not a valid input dtype for the op.
if not output_dtype_supported_in_op("floor_div", expected_dtype[0]):
return
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = a_tensor // b_tensor
reverse_expected_val = b_tensor // a_tensor
for x, y in zip(a_list, b_list):
self.match_expected(
math_ops.floordiv(x, y), expected_val, expected_dtype
)
self.match_expected(
math_ops.floordiv(y, x), reverse_expected_val, expected_dtype
)
# math_ops.floordiv and math_ops.floor_div are used interchangeably.
self.match_expected(
math_ops.floor_div(x, y), expected_val, expected_dtype
)
self.match_expected(
math_ops.floor_div(y, x), reverse_expected_val, expected_dtype
)
if at_least_one_tensor_type(x, y):
self.match_expected(x // y, expected_val, expected_dtype)
self.match_expected(y // x, reverse_expected_val, expected_dtype)
run_test_floor_div(a=124, b=123)
run_test_floor_div(a=41, b=20)
run_test_floor_div(a=2, b=6)
def test_weak_tensor_real_div(self, a_dtype, b_dtype, expected_dtype):
def run_test_real_div(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
# Skip if provided dtype is not a valid input dtype for the op.
if not output_dtype_supported_in_op("real_div", expected_dtype[0]):
return
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = math_ops.real_div(a_tensor, b_tensor)
reverse_expected_val = math_ops.real_div(b_tensor, a_tensor)
for x, y in zip(a_list, b_list):
self.match_expected(
math_ops.realdiv(x, y), expected_val, expected_dtype
)
self.match_expected(
math_ops.realdiv(y, x), reverse_expected_val, expected_dtype
)
# math_ops.realdiv and gen_math_ops.real_div are used interchangeably.
self.match_expected(
gen_math_ops.real_div(x, y), expected_val, expected_dtype
)
self.match_expected(
gen_math_ops.real_div(y, x), reverse_expected_val, expected_dtype
)
run_test_real_div(a=124, b=123)
run_test_real_div(a=41, b=20)
run_test_real_div(a=2, b=6)
def test_weak_tensor_truncate_div(self, a_dtype, b_dtype, expected_dtype):
def run_test_truncate_div(a, b):
# Skip if provided dtype is not a valid input dtype for the op.
if not output_dtype_supported_in_op("truncate_div", expected_dtype[0]):
return
a, b = maybe_to_positive_input(a, b, a_dtype, b_dtype, expected_dtype)
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = math_ops.truncatediv(a_tensor, b_tensor)
reverse_expected_val = math_ops.truncatediv(b_tensor, a_tensor)
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
for x, y in zip(a_list, b_list):
self.match_expected(
math_ops.truncatediv(x, y), expected_val, expected_dtype
)
self.match_expected(
math_ops.truncatediv(y, x), reverse_expected_val, expected_dtype
)
# math_ops.truncatediv and gen_math_ops.truncate_div are used
# interchangeably.
self.match_expected(
gen_math_ops.truncate_div(x, y), expected_val, expected_dtype
)
self.match_expected(
gen_math_ops.truncate_div(y, x),
reverse_expected_val,
expected_dtype,
)
run_test_truncate_div(a=124, b=123)
run_test_truncate_div(a=41, b=20)
run_test_truncate_div(a=2, b=6)
run_test_truncate_div(a=-7, b=5)
run_test_truncate_div(a=1, b=-2)
run_test_truncate_div(a=-100, b=-50)
def test_weak_tensor_truncate_mod(self, a_dtype, b_dtype, expected_dtype):
def run_test_truncate_mod(a, b):
# Skip if provided dtype is not a valid input dtype for the op.
if not output_dtype_supported_in_op("truncate_mod", expected_dtype[0]):
return
a, b = maybe_to_positive_input(a, b, a_dtype, b_dtype, expected_dtype)
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = math_ops.truncatemod(a_tensor, b_tensor)
reverse_expected_val = math_ops.truncatemod(b_tensor, a_tensor)
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
for x, y in zip(a_list, b_list):
self.match_expected(
math_ops.truncatemod(x, y), expected_val, expected_dtype
)
self.match_expected(
math_ops.truncatemod(y, x), reverse_expected_val, expected_dtype
)
# math_ops.truncatemod and gen_math_ops.truncate_mod are used
# interchangeably.
self.match_expected(
gen_math_ops.truncate_mod(x, y), expected_val, expected_dtype
)
self.match_expected(
gen_math_ops.truncate_mod(y, x),
reverse_expected_val,
expected_dtype,
)
run_test_truncate_mod(a=124, b=123)
run_test_truncate_mod(a=41, b=20)
run_test_truncate_mod(a=2, b=6)
run_test_truncate_mod(a=-7, b=5)
run_test_truncate_mod(a=1, b=-1)
run_test_truncate_mod(a=-100, b=-50)
def test_weak_tensor_scalar_mul(self, a_dtype, b_dtype, expected_dtype):
def run_test_scalar_mul(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
# Expected dtype = second arg's dtype.
_ = expected_dtype
if not a_dtype[0].is_compatible_with(b_dtype[0]):
return
expected_val = np.multiply(a, b)
for x, y in zip(a_list, b_list):
self.match_expected(math_ops.scalar_mul(x, y), expected_val, b_dtype)
self.match_expected(math_ops.scalar_mul(y, x), expected_val, a_dtype)
run_test_scalar_mul(a=4, b=1)
run_test_scalar_mul(a=41, b=2)
run_test_scalar_mul(a=2, b=0)
def test_weak_tensor_mat_mul(self, a_dtype, b_dtype, expected_dtype):
def run_test_mat_mul(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
# Skip if provided dtype is not a valid input dtype for the op.
if not output_dtype_supported_in_op("matmul", expected_dtype[0]):
return
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = math_ops.matmul(a_tensor, b_tensor)
expected_val_reverse = math_ops.matmul(b_tensor, a_tensor)
for x, y in zip(a_list, b_list):
self.match_expected(math_ops.matmul(x, y), expected_val, expected_dtype)
self.match_expected(
math_ops.matmul(y, x), expected_val_reverse, expected_dtype
)
run_test_mat_mul(a=[[2, 1], [3, 4]], b=[[1, 2], [3, 4]])
run_test_mat_mul(a=[[[3]]], b=[[[2]]])
def test_weak_tensor_truediv(self, a_dtype, b_dtype, expected_dtype):
def run_test_truediv(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = a_tensor / b_tensor
reverse_expected_val = b_tensor / a_tensor
for x, y in zip(a_list, b_list):
# Truediv has a dtype conversion orthogonal to our change. Therefore,
# we compare our result dtype to Tensor truediv.
expected_result_dtype = expected_val.dtype
self.match_expected(
math_ops.truediv(x, y),
expected_val,
(expected_result_dtype, expected_dtype[1]),
)
self.match_expected(
math_ops.truediv(y, x),
reverse_expected_val,
(expected_result_dtype, expected_dtype[1]),
)
# truediv, divide, and divide dunder method all use Python 3 division
# semantics.
self.match_expected(
math_ops.divide(x, y),
expected_val,
(expected_result_dtype, expected_dtype[1]),
)
self.match_expected(
math_ops.divide(y, x),
reverse_expected_val,
(expected_result_dtype, expected_dtype[1]),
)
if at_least_one_tensor_type(x, y):
self.match_expected(
x / y, expected_val, (expected_result_dtype, expected_dtype[1])
)
self.match_expected(
y / x,
reverse_expected_val,
(expected_result_dtype, expected_dtype[1]),
)
run_test_truediv(a=4, b=2)
run_test_truediv(a=41, b=3)
run_test_truediv(a=2, b=6)
def test_weak_tensor_div_no_nan(self, a_dtype, b_dtype, expected_dtype):
def run_test_div_no_nan(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = math_ops.div_no_nan(a_tensor, b_tensor)
reverse_expected_val = math_ops.div_no_nan(b_tensor, a_tensor)
# The behavior of div_no_nan is same as truediv in most cases, except
# for when it divides by nan or 0.
expected_result_dtype = expected_val.dtype
for x, y in zip(a_list, b_list):
self.match_expected(
math_ops.div_no_nan(x, y),
expected_val,
(expected_result_dtype, expected_dtype[1]),
)
self.match_expected(
math_ops.div_no_nan(y, x),
reverse_expected_val,
(expected_result_dtype, expected_dtype[1]),
)
run_test_div_no_nan(a=4, b=2)
run_test_div_no_nan(a=41, b=40)
run_test_div_no_nan(a=2, b=6)
# Test div_no_nan(x, 0) = 0 even if x is NaN or Inf.
x = np.nan
y = 0
self.match_expected(math_ops.div_no_nan(x, y), 0, (dtypes.float32, True))
x = np.inf
self.match_expected(math_ops.div_no_nan(x, y), 0, (dtypes.float32, True))
def test_weak_tensor_multiply_no_nan(self, a_dtype, b_dtype, expected_dtype):
def run_test_multiply_no_nan(a, b):
a_list = _get_test_input_for_binary_op(a, a_dtype)
b_list = _get_test_input_for_binary_op(b, b_dtype)
# Skip if provided dtype is not a valid input dtype for the op.
if not output_dtype_supported_in_op("multiply_no_nan", expected_dtype[0]):
return
a_tensor = constant_op.constant(a, expected_dtype[0])
b_tensor = constant_op.constant(b, expected_dtype[0])
expected_val = math_ops.multiply_no_nan(a_tensor, b_tensor)
for x, y in zip(a_list, b_list):
self.match_expected(
math_ops.multiply_no_nan(x, y), expected_val, expected_dtype
)
self.match_expected(
math_ops.multiply_no_nan(y, x), expected_val, expected_dtype
)
run_test_multiply_no_nan(a=4, b=2)
run_test_multiply_no_nan(a=41, b=10)
run_test_multiply_no_nan(a=2, b=6)
# Test multiply_no_nan(x, 0) = 0 even if x is NaN or Inf.
x = np.nan
y = 0
self.match_expected(
math_ops.multiply_no_nan(x, y), 0, (dtypes.float32, True)
)
x = np.inf
self.match_expected(
math_ops.multiply_no_nan(x, y), 0, (dtypes.float32, True)
)
@parameterized.parameters(safe_mode_unallowed_promos_list)
| WeakTensorBinaryOpsTest |
python | nedbat__coveragepy | tests/test_parser.py | {
"start": 34846,
"end": 37517
} | class ____(PythonParserTestBase):
"""Missing arc descriptions for match/case."""
def test_match_case(self) -> None:
parser = self.parse_text("""\
match command.split():
case ["go", direction] if direction in "nesw": # 2
match = f"go: {direction}"
case ["go", _]: # 4
match = "no go"
print(match) # 6
""")
assert parser.missing_arc_description(2, 3) == (
"line 2 didn't jump to line 3 because the pattern on line 2 never matched"
)
assert parser.missing_arc_description(2, 4) == (
"line 2 didn't jump to line 4 because the pattern on line 2 always matched"
)
assert parser.missing_arc_description(4, 6) == (
"line 4 didn't jump to line 6 because the pattern on line 4 always matched"
)
def test_final_wildcard(self) -> None:
parser = self.parse_text("""\
match command.split():
case ["go", direction] if direction in "nesw": # 2
match = f"go: {direction}"
case _: # 4
match = "no go"
print(match) # 6
""")
assert parser.missing_arc_description(2, 3) == (
"line 2 didn't jump to line 3 because the pattern on line 2 never matched"
)
assert parser.missing_arc_description(2, 4) == (
"line 2 didn't jump to line 4 because the pattern on line 2 always matched"
)
# 4-6 isn't a possible arc, so the description is generic.
assert parser.missing_arc_description(4, 6) == "line 4 didn't jump to line 6"
def test_missing_arc_descriptions_bug1775(self) -> None:
# Bug: the `if x == 2:` line was marked partial with a message of:
# line 6 didn't return from function 'func', because the return on line 4 wasn't executed
# At some point it changed to "didn't jump to the function exit," which
# is close enough. These situations are hard to describe precisely.
parser = self.parse_text("""\
def func():
x = 2
try:
return 4
finally:
if x == 2: # line 6
print("x is 2")
func()
""")
assert parser.missing_arc_description(6, -1) == "line 6 didn't jump to the function exit"
| MatchCaseMissingArcDescriptionTest |
python | django__django | django/db/models/expressions.py | {
"start": 29375,
"end": 29895
} | class ____(CombinedExpression):
output_field = fields.DurationField()
def __init__(self, lhs, rhs):
super().__init__(lhs, self.SUB, rhs)
def as_sql(self, compiler, connection):
connection.ops.check_expression_support(self)
lhs = compiler.compile(self.lhs)
rhs = compiler.compile(self.rhs)
return connection.ops.subtract_temporals(
self.lhs.output_field.get_internal_type(), lhs, rhs
)
@deconstructible(path="django.db.models.F")
| TemporalSubtraction |
python | FactoryBoy__factory_boy | factory/declarations.py | {
"start": 20684,
"end": 20801
} | class ____(T.NamedTuple):
value_provided: bool
value: T.Any
extra: T.Dict[str, T.Any]
| PostGenerationContext |
python | urllib3__urllib3 | test/__init__.py | {
"start": 9022,
"end": 10011
} | class ____(MetaPathFinder):
"""
Stashes away previously imported modules
If we reimport a module the data from coverage is lost, so we reuse the old
modules
"""
def __init__(
self, namespace: str, modules: dict[str, ModuleType] = sys.modules
) -> None:
self.namespace = namespace
self.modules = modules
self._data: dict[str, ModuleType] = {}
def stash(self) -> None:
if self.namespace in self.modules:
self._data[self.namespace] = self.modules.pop(self.namespace)
for module in list(self.modules.keys()):
if module.startswith(self.namespace + "."):
self._data[module] = self.modules.pop(module)
def pop(self) -> None:
self.modules.pop(self.namespace, None)
for module in list(self.modules.keys()):
if module.startswith(self.namespace + "."):
self.modules.pop(module)
self.modules.update(self._data)
| ModuleStash |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_gradient10.py | {
"start": 315,
"end": 1467
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_gradient10.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [56159232, 61364096]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"values": "=Sheet1!$A$1:$A$5",
"gradient": {"colors": ["#DDEBCF", "#156B13"]},
}
)
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_pools.py | {
"start": 18792,
"end": 40237
} | class ____(TestPoolsEndpoint):
@pytest.mark.enable_redact
@pytest.mark.parametrize(
("actions", "expected_results"),
[
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [
{"name": "pool3", "slots": 10, "description": "New Description"},
{"name": "pool4", "slots": 20, "description": "New Description"},
],
"action_on_existence": "fail",
}
]
},
{"create": {"success": ["pool3", "pool4"], "errors": []}},
id="test_successful_create",
),
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [
{"name": "pool3", "slots": 10, "description": "New Description"},
{"name": "pool1", "slots": 20, "description": "New Description"},
],
"action_on_existence": "skip",
}
]
},
{"create": {"success": ["pool3"], "errors": []}},
id="test_successful_create_with_skip",
),
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [
{"name": "pool3", "slots": 10, "description": "New Description"},
{"name": "pool2", "slots": 20, "description": "New Description"},
],
"action_on_existence": "overwrite",
}
]
},
{"create": {"success": ["pool3", "pool2"], "errors": []}},
id="test_successful_create_with_overwrite",
),
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [{"name": "pool2", "slots": 20, "description": "New Description"}],
"action_on_existence": "fail",
}
]
},
{
"create": {
"success": [],
"errors": [
{
"error": "The pools with these pool names: {'pool2'} already exist.",
"status_code": 409,
}
],
}
},
id="test_create_conflict",
),
pytest.param(
{
"actions": [
{
"action": "update",
"entities": [
{
"name": "pool2",
"slots": 10,
"description": "New Description",
"include_deferred": False,
}
],
"action_on_non_existence": "fail",
}
]
},
{"update": {"success": ["pool2"], "errors": []}},
id="test_successful_update",
),
pytest.param(
{
"actions": [
{
"action": "update",
"entities": [
{
"name": "pool4",
"slots": 20,
"description": "New Description",
"include_deferred": False,
}
],
"action_on_non_existence": "skip",
}
]
},
{"update": {"success": [], "errors": []}},
id="test_update_with_skip",
),
pytest.param(
{
"actions": [
{
"action": "update",
"entities": [
{
"name": "pool4",
"slots": 10,
"description": "New Description",
"include_deferred": False,
}
],
"action_on_non_existence": "fail",
}
]
},
{
"update": {
"success": [],
"errors": [
{
"error": "The pools with these pool names: {'pool4'} were not found.",
"status_code": 404,
}
],
}
},
id="test_update_not_found",
),
pytest.param(
{
"actions": [
{
"action": "update",
"entities": [
{
"name": "pool1",
"slots": 50,
"description": "Updated description",
"include_deferred": False,
}
],
"update_mask": ["slots", "description"],
"action_on_non_existence": "fail",
}
]
},
{
"update": {"success": ["pool1"], "errors": []},
},
id="test_update_with_valid_update_mask",
),
pytest.param(
{"actions": [{"action": "delete", "entities": ["pool1"], "action_on_non_existence": "skip"}]},
{"delete": {"success": ["pool1"], "errors": []}},
id="test_successful_delete",
),
pytest.param(
{"actions": [{"action": "delete", "entities": ["pool3"], "action_on_non_existence": "skip"}]},
{"delete": {"success": [], "errors": []}},
id="test_delete_with_skip",
),
pytest.param(
{"actions": [{"action": "delete", "entities": ["pool4"], "action_on_non_existence": "fail"}]},
{
"delete": {
"success": [],
"errors": [
{
"error": "The pools with these pool names: {'pool4'} were not found.",
"status_code": 404,
}
],
}
},
id="test_delete_not_found",
),
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [{"name": "pool6", "slots": 10, "description": "New Description"}],
"action_on_existence": "skip",
},
{
"action": "update",
"entities": [
{
"name": "pool1",
"slots": 10,
"description": "New Description",
"include_deferred": False,
}
],
"action_on_non_existence": "fail",
},
{"action": "delete", "entities": ["pool2"], "action_on_non_existence": "skip"},
]
},
{
"create": {"success": ["pool6"], "errors": []},
"update": {"success": ["pool1"], "errors": []},
"delete": {"success": ["pool2"], "errors": []},
},
id="test_create_update_delete",
),
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [{"name": "pool1", "slots": 10, "description": "New Description"}],
"action_on_existence": "fail",
},
{
"action": "update",
"entities": [
{
"name": "pool1",
"slots": 100,
"description": "New Description",
"include_deferred": False,
}
],
"action_on_non_existence": "fail",
},
{"action": "delete", "entities": ["pool4"], "action_on_non_existence": "skip"},
]
},
{
"create": {
"success": [],
"errors": [
{
"error": "The pools with these pool names: {'pool1'} already exist.",
"status_code": 409,
}
],
},
"update": {"success": ["pool1"], "errors": []},
"delete": {"success": [], "errors": []},
},
id="test_create_update_delete_with_fail",
),
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [{"name": "pool1", "slots": 10, "description": "New Description"}],
"action_on_existence": "skip",
},
{
"action": "update",
"entities": [
{
"name": "pool5",
"slots": 10,
"description": "New Description",
"include_deferred": False,
}
],
"action_on_non_existence": "skip",
},
{"action": "delete", "entities": ["pool5"], "action_on_non_existence": "skip"},
]
},
{
"create": {"success": [], "errors": []},
"update": {"success": [], "errors": []},
"delete": {"success": [], "errors": []},
},
id="test_create_update_delete_with_skip",
),
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [{"name": "pool5", "slots": 10, "description": "New Description"}],
"action_on_existence": "fail",
},
{
"action": "update",
"entities": [
{
"name": "pool5",
"slots": 100,
"description": "New test Description",
"include_deferred": False,
}
],
"action_on_non_existence": "fail",
},
{"action": "delete", "entities": ["pool5"], "action_on_non_existence": "fail"},
]
},
{
"create": {"success": ["pool5"], "errors": []},
"update": {"success": ["pool5"], "errors": []},
"delete": {"success": ["pool5"], "errors": []},
},
id="test_dependent_actions",
),
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [
{"name": "pool1", "slots": 100, "description": "New test Description"}
],
"action_on_existence": "fail",
},
{
"action": "update",
"entities": [
{
"name": "pool1",
"slots": 100,
"description": "New test Description",
"include_deferred": False,
}
],
"action_on_non_existence": "fail",
},
{
"action": "create",
"entities": [
{"name": "pool5", "slots": 100, "description": "New test Description"}
],
"action_on_existence": "fail",
},
{
"action": "update",
"entities": [
{
"name": "pool8",
"slots": 100,
"description": "New test Description",
"include_deferred": False,
}
],
"action_on_non_existence": "fail",
},
{"action": "delete", "entities": ["pool2"], "action_on_non_existence": "fail"},
{
"action": "create",
"entities": [
{"name": "pool6", "slots": 100, "description": "New test Description"}
],
"action_on_existence": "fail",
},
{
"action": "update",
"entities": [
{
"name": "pool9",
"slots": 100,
"description": "New test Description",
"include_deferred": False,
}
],
"action_on_non_existence": "fail",
},
]
},
{
"create": {
"success": ["pool5", "pool6"],
"errors": [
{
"error": "The pools with these pool names: {'pool1'} already exist.",
"status_code": 409,
}
],
},
"update": {
"success": ["pool1"],
"errors": [
{
"error": "The pools with these pool names: {'pool8'} were not found.",
"status_code": 404,
},
{
"error": "The pools with these pool names: {'pool9'} were not found.",
"status_code": 404,
},
],
},
"delete": {"success": ["pool2"], "errors": []},
},
id="test_repeated_actions",
),
pytest.param(
{
"actions": [
{
"action": "create",
"entities": [{"name": "pool6", "slots": 5, "description": "Initial Description"}],
"action_on_existence": "fail",
},
{
"action": "update",
"entities": [
{
"name": "pool6",
"slots": 50,
"description": "Masked Update Description",
"include_deferred": False,
}
],
"update_mask": ["slots"],
"action_on_non_existence": "fail",
},
{
"action": "delete",
"entities": ["pool6"],
"action_on_non_existence": "fail",
},
]
},
{
"create": {"success": ["pool6"], "errors": []},
"update": {"success": ["pool6"], "errors": []},
"delete": {"success": ["pool6"], "errors": []},
},
id="test_dependent_actions_with_update_mask",
),
],
)
def test_bulk_pools(self, test_client, actions, expected_results, session):
self.create_pools()
response = test_client.patch("/pools", json=actions)
response_data = response.json()
for key, value in expected_results.items():
assert response_data[key] == value
check_last_log(session, dag_id=None, event="bulk_pools", logical_date=None)
def test_update_mask_preserves_other_fields(self, test_client, session):
# Arrange: create a pool with initial values
self.create_pools()
# Act: update only the "slots" field via update_mask
response = test_client.patch(
"/pools",
json={
"actions": [
{
"action": "update",
"entities": [
{
"name": "pool1",
"slots": 50,
"description": "Should not be updated",
"include_deferred": False,
}
],
"update_mask": ["slots"], # only slots should update
"action_on_non_existence": "fail",
}
]
},
)
assert response.status_code == 200
response_data = response.json()
assert response_data["update"]["success"] == ["pool1"]
# Assert: fetch from DB and check only masked field changed
updated_pool = session.query(Pool).filter_by(pool="pool1").one()
assert updated_pool.slots == 50 # updated
assert updated_pool.description is None # unchanged
assert updated_pool.include_deferred is True # unchanged
def test_should_respond_401(self, unauthenticated_test_client):
response = unauthenticated_test_client.patch("/pools", json={})
assert response.status_code == 401
def test_should_respond_403(self, unauthorized_test_client):
response = unauthorized_test_client.patch(
"/pools",
json={
"actions": [
{
"action": "create",
"entities": [
{"pool": "pool1", "slots": 1},
],
},
]
},
)
assert response.status_code == 403
| TestBulkPools |
python | matplotlib__matplotlib | lib/matplotlib/dates.py | {
"start": 19226,
"end": 28386
} | class ____(ticker.Formatter):
"""
A `.Formatter` which attempts to figure out the best format to use for the
date, and to make it as compact as possible, but still be complete. This is
most useful when used with the `AutoDateLocator`::
>>> locator = AutoDateLocator()
>>> formatter = ConciseDateFormatter(locator)
Parameters
----------
locator : `.ticker.Locator`
Locator that this axis is using.
tz : str or `~datetime.tzinfo`, default: :rc:`timezone`
Ticks timezone, passed to `.dates.num2date`.
formats : list of 6 strings, optional
Format strings for 6 levels of tick labelling: mostly years,
months, days, hours, minutes, and seconds. Strings use
the same format codes as `~datetime.datetime.strftime`. Default is
``['%Y', '%b', '%d', '%H:%M', '%H:%M', '%S.%f']``
zero_formats : list of 6 strings, optional
Format strings for tick labels that are "zeros" for a given tick
level. For instance, if most ticks are months, ticks around 1 Jan 2005
will be labeled "Dec", "2005", "Feb". The default is
``['', '%Y', '%b', '%b-%d', '%H:%M', '%H:%M']``
offset_formats : list of 6 strings, optional
Format strings for the 6 levels that is applied to the "offset"
string found on the right side of an x-axis, or top of a y-axis.
Combined with the tick labels this should completely specify the
date. The default is::
['', '%Y', '%Y-%b', '%Y-%b-%d', '%Y-%b-%d', '%Y-%b-%d %H:%M']
show_offset : bool, default: True
Whether to show the offset or not.
usetex : bool, default: :rc:`text.usetex`
To enable/disable the use of TeX's math mode for rendering the results
of the formatter.
Examples
--------
See :doc:`/gallery/ticks/date_concise_formatter`
.. plot::
import datetime
import matplotlib.dates as mdates
base = datetime.datetime(2005, 2, 1)
dates = np.array([base + datetime.timedelta(hours=(2 * i))
for i in range(732)])
N = len(dates)
np.random.seed(19680801)
y = np.cumsum(np.random.randn(N))
fig, ax = plt.subplots(constrained_layout=True)
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.plot(dates, y)
ax.set_title('Concise Date Formatter')
"""
def __init__(self, locator, tz=None, formats=None, offset_formats=None,
zero_formats=None, show_offset=True, *, usetex=None):
"""
Autoformat the date labels. The default format is used to form an
initial string, and then redundant elements are removed.
"""
self._locator = locator
self._tz = tz
self.defaultfmt = '%Y'
# there are 6 levels with each level getting a specific format
# 0: mostly years, 1: months, 2: days,
# 3: hours, 4: minutes, 5: seconds
if formats:
if len(formats) != 6:
raise ValueError('formats argument must be a list of '
'6 format strings (or None)')
self.formats = formats
else:
self.formats = ['%Y', # ticks are mostly years
'%b', # ticks are mostly months
'%d', # ticks are mostly days
'%H:%M', # hrs
'%H:%M', # min
'%S.%f', # secs
]
# fmt for zeros ticks at this level. These are
# ticks that should be labeled w/ info the level above.
# like 1 Jan can just be labelled "Jan". 02:02:00 can
# just be labeled 02:02.
if zero_formats:
if len(zero_formats) != 6:
raise ValueError('zero_formats argument must be a list of '
'6 format strings (or None)')
self.zero_formats = zero_formats
elif formats:
# use the users formats for the zero tick formats
self.zero_formats = [''] + self.formats[:-1]
else:
# make the defaults a bit nicer:
self.zero_formats = [''] + self.formats[:-1]
self.zero_formats[3] = '%b-%d'
if offset_formats:
if len(offset_formats) != 6:
raise ValueError('offset_formats argument must be a list of '
'6 format strings (or None)')
self.offset_formats = offset_formats
else:
self.offset_formats = ['',
'%Y',
'%Y-%b',
'%Y-%b-%d',
'%Y-%b-%d',
'%Y-%b-%d %H:%M']
self.offset_string = ''
self.show_offset = show_offset
self._usetex = mpl._val_or_rc(usetex, 'text.usetex')
def __call__(self, x, pos=None):
formatter = DateFormatter(self.defaultfmt, self._tz,
usetex=self._usetex)
return formatter(x, pos=pos)
def format_ticks(self, values):
tickdatetime = [num2date(value, tz=self._tz) for value in values]
tickdate = np.array([tdt.timetuple()[:6] for tdt in tickdatetime])
# basic algorithm:
# 1) only display a part of the date if it changes over the ticks.
# 2) don't display the smaller part of the date if:
# it is always the same or if it is the start of the
# year, month, day etc.
# fmt for most ticks at this level
fmts = self.formats
# format beginnings of days, months, years, etc.
zerofmts = self.zero_formats
# offset fmt are for the offset in the upper left of the
# or lower right of the axis.
offsetfmts = self.offset_formats
show_offset = self.show_offset
# determine the level we will label at:
# mostly 0: years, 1: months, 2: days,
# 3: hours, 4: minutes, 5: seconds, 6: microseconds
for level in range(5, -1, -1):
unique = np.unique(tickdate[:, level])
if len(unique) > 1:
# if 1 is included in unique, the year is shown in ticks
if level < 2 and np.any(unique == 1):
show_offset = False
break
elif level == 0:
# all tickdate are the same, so only micros might be different
# set to the most precise (6: microseconds doesn't exist...)
level = 5
# level is the basic level we will label at.
# now loop through and decide the actual ticklabels
zerovals = [0, 1, 1, 0, 0, 0, 0]
labels = [''] * len(tickdate)
for nn in range(len(tickdate)):
if level < 5:
if tickdate[nn][level] == zerovals[level]:
fmt = zerofmts[level]
else:
fmt = fmts[level]
else:
# special handling for seconds + microseconds
if (tickdatetime[nn].second == tickdatetime[nn].microsecond
== 0):
fmt = zerofmts[level]
else:
fmt = fmts[level]
labels[nn] = tickdatetime[nn].strftime(fmt)
# special handling of seconds and microseconds:
# strip extra zeros and decimal if possible.
# this is complicated by two factors. 1) we have some level-4 strings
# here (i.e. 03:00, '0.50000', '1.000') 2) we would like to have the
# same number of decimals for each string (i.e. 0.5 and 1.0).
if level >= 5:
trailing_zeros = min(
(len(s) - len(s.rstrip('0')) for s in labels if '.' in s),
default=None)
if trailing_zeros:
for nn in range(len(labels)):
if '.' in labels[nn]:
labels[nn] = labels[nn][:-trailing_zeros].rstrip('.')
if show_offset:
# set the offset string:
if (self._locator.axis and
self._locator.axis.__name__ in ('xaxis', 'yaxis')
and self._locator.axis.get_inverted()):
self.offset_string = tickdatetime[0].strftime(offsetfmts[level])
else:
self.offset_string = tickdatetime[-1].strftime(offsetfmts[level])
if self._usetex:
self.offset_string = _wrap_in_tex(self.offset_string)
else:
self.offset_string = ''
if self._usetex:
return [_wrap_in_tex(l) for l in labels]
else:
return labels
def get_offset(self):
return self.offset_string
def format_data_short(self, value):
return num2date(value, tz=self._tz).strftime('%Y-%m-%d %H:%M:%S')
| ConciseDateFormatter |
python | davidhalter__parso | parso/python/errors.py | {
"start": 46347,
"end": 49112
} | class ____(_CheckAssignmentRule):
# namedexpr_test: test [':=' test]
def is_issue(self, namedexpr_test):
# assigned name
first = namedexpr_test.children[0]
def search_namedexpr_in_comp_for(node):
while True:
parent = node.parent
if parent is None:
return parent
if parent.type == 'sync_comp_for' and parent.children[3] == node:
return parent
node = parent
if search_namedexpr_in_comp_for(namedexpr_test):
# [i+1 for i in (i := range(5))]
# [i+1 for i in (j := range(5))]
# [i+1 for i in (lambda: (j := range(5)))()]
message = 'assignment expression cannot be used in a comprehension iterable expression'
self.add_issue(namedexpr_test, message=message)
# defined names
exprlist = list()
def process_comp_for(comp_for):
if comp_for.type == 'sync_comp_for':
comp = comp_for
elif comp_for.type == 'comp_for':
comp = comp_for.children[1]
exprlist.extend(_get_for_stmt_definition_exprs(comp))
def search_all_comp_ancestors(node):
has_ancestors = False
while True:
node = node.search_ancestor('testlist_comp', 'dictorsetmaker')
if node is None:
break
for child in node.children:
if child.type in _COMP_FOR_TYPES:
process_comp_for(child)
has_ancestors = True
break
return has_ancestors
# check assignment expressions in comprehensions
search_all = search_all_comp_ancestors(namedexpr_test)
if search_all:
if self._normalizer.context.node.type == 'classdef':
message = 'assignment expression within a comprehension ' \
'cannot be used in a class body'
self.add_issue(namedexpr_test, message=message)
namelist = [expr.value for expr in exprlist if expr.type == 'name']
if first.type == 'name' and first.value in namelist:
# [i := 0 for i, j in range(5)]
# [[(i := i) for j in range(5)] for i in range(5)]
# [i for i, j in range(5) if True or (i := 1)]
# [False and (i := 0) for i, j in range(5)]
message = 'assignment expression cannot rebind ' \
'comprehension iteration variable %r' % first.value
self.add_issue(namedexpr_test, message=message)
self._check_assignment(first, is_namedexpr=True)
| _NamedExprRule |
python | scipy__scipy | scipy/stats/_qmc.py | {
"start": 91832,
"end": 107805
} | class ____:
r"""QMC sampling from a multinomial distribution.
Parameters
----------
pvals : array_like (k,)
Vector of probabilities of size ``k``, where ``k`` is the number
of categories. Elements must be non-negative and sum to 1.
n_trials : int
Number of trials.
engine : QMCEngine, optional
Quasi-Monte Carlo engine sampler. If None, `Sobol` is used.
rng : `numpy.random.Generator`, optional
Pseudorandom number generator state. When `rng` is None, a new
`numpy.random.Generator` is created using entropy from the
operating system. Types other than `numpy.random.Generator` are
passed to `numpy.random.default_rng` to instantiate a ``Generator``.
.. versionchanged:: 1.15.0
As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
transition from use of `numpy.random.RandomState` to
`numpy.random.Generator`, this keyword was changed from `seed` to
`rng`. For an interim period, both keywords will continue to work, although
only one may be specified at a time. After the interim period, function
calls using the `seed` keyword will emit warnings. Following a
deprecation period, the `seed` keyword will be removed.
Examples
--------
Let's define 3 categories and for a given sample, the sum of the trials
of each category is 8. The number of trials per category is determined
by the `pvals` associated to each category.
Then, we sample this distribution 64 times.
>>> import matplotlib.pyplot as plt
>>> from scipy.stats import qmc
>>> dist = qmc.MultinomialQMC(
... pvals=[0.2, 0.4, 0.4], n_trials=10, engine=qmc.Halton(d=1)
... )
>>> sample = dist.random(64)
We can plot the sample and verify that the median of number of trials
for each category is following the `pvals`. That would be
``pvals * n_trials = [2, 4, 4]``.
>>> fig, ax = plt.subplots()
>>> ax.yaxis.get_major_locator().set_params(integer=True)
>>> _ = ax.boxplot(sample)
>>> ax.set(xlabel="Categories", ylabel="Trials")
>>> plt.show()
"""
@_transition_to_rng('seed', replace_doc=False)
def __init__(
self,
pvals: "npt.ArrayLike",
n_trials: IntNumber,
*,
engine: QMCEngine | None = None,
rng: SeedType = None,
) -> None:
self.pvals = np.atleast_1d(np.asarray(pvals))
if np.min(pvals) < 0:
raise ValueError('Elements of pvals must be non-negative.')
if not np.isclose(np.sum(pvals), 1):
raise ValueError('Elements of pvals must sum to 1.')
self.n_trials = n_trials
if engine is None:
# Need this during SPEC 7 transition to prevent `RandomState`
# from being passed via `rng`.
kwarg = "seed" if isinstance(rng, np.random.RandomState) else "rng"
kwargs = {kwarg: rng}
self.engine = Sobol(
d=1, scramble=True, bits=30, **kwargs
) # type: QMCEngine
elif isinstance(engine, QMCEngine):
if engine.d != 1:
raise ValueError("Dimension of `engine` must be 1.")
self.engine = engine
else:
raise ValueError("`engine` must be an instance of "
"`scipy.stats.qmc.QMCEngine` or `None`.")
def random(self, n: IntNumber = 1) -> np.ndarray:
"""Draw `n` QMC samples from the multinomial distribution.
Parameters
----------
n : int, optional
Number of samples to generate in the parameter space. Default is 1.
Returns
-------
samples : array_like (n, pvals)
Sample.
"""
sample = np.empty((n, len(self.pvals)))
for i in range(n):
base_draws = self.engine.random(self.n_trials).ravel()
p_cumulative = np.empty_like(self.pvals, dtype=float)
_fill_p_cumulative(np.array(self.pvals, dtype=float), p_cumulative)
sample_ = np.zeros_like(self.pvals, dtype=np.intp)
_categorize(base_draws, p_cumulative, sample_)
sample[i] = sample_
return sample
def _select_optimizer(
optimization: Literal["random-cd", "lloyd"] | None, config: dict
) -> Callable | None:
"""A factory for optimization methods."""
optimization_method: dict[str, Callable] = {
"random-cd": _random_cd,
"lloyd": _lloyd_centroidal_voronoi_tessellation
}
optimizer: partial | None
if optimization is not None:
try:
optimization = optimization.lower() # type: ignore[assignment]
optimizer_ = optimization_method[optimization]
except KeyError as exc:
message = (f"{optimization!r} is not a valid optimization"
f" method. It must be one of"
f" {set(optimization_method)!r}")
raise ValueError(message) from exc
# config
optimizer = partial(optimizer_, **config)
else:
optimizer = None
return optimizer
def _random_cd(
best_sample: np.ndarray, n_iters: int, n_nochange: int, rng: GeneratorType,
**kwargs: dict
) -> np.ndarray:
"""Optimal LHS on CD.
Create a base LHS and do random permutations of coordinates to
lower the centered discrepancy.
Because it starts with a normal LHS, it also works with the
`scramble` keyword argument.
Two stopping criterion are used to stop the algorithm: at most,
`n_iters` iterations are performed; or if there is no improvement
for `n_nochange` consecutive iterations.
"""
del kwargs # only use keywords which are defined, needed by factory
n, d = best_sample.shape
if d == 0 or n == 0:
return np.empty((n, d))
if d == 1 or n == 1:
# discrepancy measures are invariant under permuting factors and runs
return best_sample
best_disc = discrepancy(best_sample)
bounds = ([0, d - 1],
[0, n - 1],
[0, n - 1])
n_nochange_ = 0
n_iters_ = 0
while n_nochange_ < n_nochange and n_iters_ < n_iters:
n_iters_ += 1
col = rng_integers(rng, *bounds[0], endpoint=True) # type: ignore[misc]
row_1 = rng_integers(rng, *bounds[1], endpoint=True) # type: ignore[misc]
row_2 = rng_integers(rng, *bounds[2], endpoint=True) # type: ignore[misc]
disc = _perturb_discrepancy(best_sample,
row_1, row_2, col,
best_disc)
if disc < best_disc:
best_sample[row_1, col], best_sample[row_2, col] = (
best_sample[row_2, col], best_sample[row_1, col])
best_disc = disc
n_nochange_ = 0
else:
n_nochange_ += 1
return best_sample
def _l1_norm(sample: np.ndarray) -> float:
return distance.pdist(sample, 'cityblock').min()
def _lloyd_iteration(
sample: np.ndarray,
decay: float,
qhull_options: str
) -> np.ndarray:
"""Lloyd-Max algorithm iteration.
Based on the implementation of Stéfan van der Walt:
https://github.com/stefanv/lloyd
which is:
Copyright (c) 2021-04-21 Stéfan van der Walt
https://github.com/stefanv/lloyd
MIT License
Parameters
----------
sample : array_like (n, d)
The sample to iterate on.
decay : float
Relaxation decay. A positive value would move the samples toward
their centroid, and negative value would move them away.
1 would move the samples to their centroid.
qhull_options : str
Additional options to pass to Qhull. See Qhull manual
for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and
"Qbb Qc Qz Qj" otherwise.)
Returns
-------
sample : array_like (n, d)
The sample after an iteration of Lloyd's algorithm.
"""
new_sample = np.empty_like(sample)
voronoi = Voronoi(sample, qhull_options=qhull_options)
for ii, idx in enumerate(voronoi.point_region):
# the region is a series of indices into self.voronoi.vertices
# remove samples at infinity, designated by index -1
region = [i for i in voronoi.regions[idx] if i != -1]
# get the vertices for this region
verts = voronoi.vertices[region]
# clipping would be wrong, we need to intersect
# verts = np.clip(verts, 0, 1)
# move samples towards centroids:
# Centroid in n-D is the mean for uniformly distributed nodes
# of a geometry.
centroid = np.mean(verts, axis=0)
new_sample[ii] = sample[ii] + (centroid - sample[ii]) * decay
# only update sample to centroid within the region
is_valid = np.all(np.logical_and(new_sample >= 0, new_sample <= 1), axis=1)
sample[is_valid] = new_sample[is_valid]
return sample
def _lloyd_centroidal_voronoi_tessellation(
sample: "npt.ArrayLike",
*,
tol: DecimalNumber = 1e-5,
maxiter: IntNumber = 10,
qhull_options: str | None = None,
**kwargs: dict
) -> np.ndarray:
"""Approximate Centroidal Voronoi Tessellation.
Perturb samples in N-dimensions using Lloyd-Max algorithm.
Parameters
----------
sample : array_like (n, d)
The sample to iterate on. With ``n`` the number of samples and ``d``
the dimension. Samples must be in :math:`[0, 1]^d`, with ``d>=2``.
tol : float, optional
Tolerance for termination. If the min of the L1-norm over the samples
changes less than `tol`, it stops the algorithm. Default is 1e-5.
maxiter : int, optional
Maximum number of iterations. It will stop the algorithm even if
`tol` is above the threshold.
Too many iterations tend to cluster the samples as a hypersphere.
Default is 10.
qhull_options : str, optional
Additional options to pass to Qhull. See Qhull manual
for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and
"Qbb Qc Qz Qj" otherwise.)
Returns
-------
sample : array_like (n, d)
The sample after being processed by Lloyd-Max algorithm.
Notes
-----
Lloyd-Max algorithm is an iterative process with the purpose of improving
the dispersion of samples. For given sample: (i) compute a Voronoi
Tessellation; (ii) find the centroid of each Voronoi cell; (iii) move the
samples toward the centroid of their respective cell. See [1]_, [2]_.
A relaxation factor is used to control how fast samples can move at each
iteration. This factor is starting at 2 and ending at 1 after `maxiter`
following an exponential decay.
The process converges to equally spaced samples. It implies that measures
like the discrepancy could suffer from too many iterations. On the other
hand, L1 and L2 distances should improve. This is especially true with
QMC methods which tend to favor the discrepancy over other criteria.
.. note::
The current implementation does not intersect the Voronoi Tessellation
with the boundaries. This implies that for a low number of samples,
empirically below 20, no Voronoi cell is touching the boundaries.
Hence, samples cannot be moved close to the boundaries.
Further improvements could consider the samples at infinity so that
all boundaries are segments of some Voronoi cells. This would fix
the computation of the centroid position.
.. warning::
The Voronoi Tessellation step is expensive and quickly becomes
intractable with dimensions as low as 10 even for a sample
of size as low as 1000.
.. versionadded:: 1.9.0
References
----------
.. [1] Lloyd. "Least Squares Quantization in PCM".
IEEE Transactions on Information Theory, 1982.
.. [2] Max J. "Quantizing for minimum distortion".
IEEE Transactions on Information Theory, 1960.
Examples
--------
>>> import numpy as np
>>> from scipy.spatial import distance
>>> from scipy.stats._qmc import _lloyd_centroidal_voronoi_tessellation
>>> rng = np.random.default_rng()
>>> sample = rng.random((128, 2))
.. note::
The samples need to be in :math:`[0, 1]^d`. `scipy.stats.qmc.scale`
can be used to scale the samples from their
original bounds to :math:`[0, 1]^d`. And back to their original bounds.
Compute the quality of the sample using the L1 criterion.
>>> def l1_norm(sample):
... return distance.pdist(sample, 'cityblock').min()
>>> l1_norm(sample)
0.00161... # random
Now process the sample using Lloyd's algorithm and check the improvement
on the L1. The value should increase.
>>> sample = _lloyd_centroidal_voronoi_tessellation(sample)
>>> l1_norm(sample)
0.0278... # random
"""
del kwargs # only use keywords which are defined, needed by factory
sample = np.asarray(sample).copy()
if not sample.ndim == 2:
raise ValueError('`sample` is not a 2D array')
if not sample.shape[1] >= 2:
raise ValueError('`sample` dimension is not >= 2')
# Checking that sample is within the hypercube
if (sample.max() > 1.) or (sample.min() < 0.):
raise ValueError('`sample` is not in unit hypercube')
if qhull_options is None:
qhull_options = 'Qbb Qc Qz QJ'
if sample.shape[1] >= 5:
qhull_options += ' Qx'
# Fit an exponential to be 2 at 0 and 1 at `maxiter`.
# The decay is used for relaxation.
# analytical solution for y=exp(-maxiter/x) - 0.1
root = -maxiter / np.log(0.1)
decay = [np.exp(-x / root)+0.9 for x in range(maxiter)]
l1_old = _l1_norm(sample=sample)
for i in range(maxiter):
sample = _lloyd_iteration(
sample=sample, decay=decay[i],
qhull_options=qhull_options,
)
l1_new = _l1_norm(sample=sample)
if abs(l1_new - l1_old) < tol:
break
else:
l1_old = l1_new
return sample
def _validate_workers(workers: IntNumber = 1) -> IntNumber:
"""Validate `workers` based on platform and value.
Parameters
----------
workers : int, optional
Number of workers to use for parallel processing. If -1 is
given all CPU threads are used. Default is 1.
Returns
-------
Workers : int
Number of CPU used by the algorithm
"""
workers = int(workers)
if workers == -1:
workers = os.cpu_count() # type: ignore[assignment]
if workers is None:
raise NotImplementedError(
"Cannot determine the number of cpus using os.cpu_count(), "
"cannot use -1 for the number of workers"
)
elif workers <= 0:
raise ValueError(f"Invalid number of workers: {workers}, must be -1 "
"or > 0")
return workers
def _validate_bounds(
l_bounds: "npt.ArrayLike", u_bounds: "npt.ArrayLike", d: int
) -> "tuple[npt.NDArray[np.generic], npt.NDArray[np.generic]]":
"""Bounds input validation.
Parameters
----------
l_bounds, u_bounds : array_like (d,)
Lower and upper bounds.
d : int
Dimension to use for broadcasting.
Returns
-------
l_bounds, u_bounds : array_like (d,)
Lower and upper bounds.
"""
try:
lower = np.broadcast_to(l_bounds, d)
upper = np.broadcast_to(u_bounds, d)
except ValueError as exc:
msg = ("'l_bounds' and 'u_bounds' must be broadcastable and respect"
" the sample dimension")
raise ValueError(msg) from exc
if not np.all(lower < upper):
raise ValueError("Bounds are not consistent 'l_bounds' < 'u_bounds'")
return lower, upper
| MultinomialQMC |
python | gevent__gevent | src/gevent/libev/watcher.py | {
"start": 6809,
"end": 7085
} | class ____(object):
__slots__ = ('pid', 'rpid', 'rstatus')
def __init__(self, other):
self.pid = other.pid
self.rpid = other.rpid
self.rstatus = other.rstatus
def __bool__(self):
return False
__nonzero__ = __bool__
| _ClosedWatcher |
python | pypa__warehouse | warehouse/cli/__init__.py | {
"start": 87,
"end": 1156
} | class ____:
# This is defined here instead of anywhere else because we want to limit
# the modules that this imports from Warehouse. Anything imported in
# warehouse/__init__.py or warehouse/cli/__init__.py will not be able to
# be reloaded by ``warehouse serve --reload``.
def __init__(self, *args, **kwargs):
self.__args = args
self.__kwargs = kwargs
self.__config = None
def __getattr__(self, name):
if self.__config is None:
from warehouse.config import configure
self.__config = configure(*self.__args, **self.__kwargs)
return getattr(self.__config, name)
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@click.pass_context
def warehouse(ctx):
ctx.obj = LazyConfig()
# We want to automatically import all of the warehouse.cli.* modules so that
# any commands registered in any of them will be discovered.
for _, name, _ in pkgutil.walk_packages(__path__, prefix=__name__ + "."): # type: ignore # noqa
importlib.import_module(name)
| LazyConfig |
python | simonw__datasette | datasette/events.py | {
"start": 4611,
"end": 5332
} | class ____(Event):
"""
Event name: ``delete-row``
A row was deleted from a table.
:ivar database: The name of the database where the row was deleted.
:type database: str
:ivar table: The name of the table where the row was deleted.
:type table: str
:ivar pks: The primary key values of the deleted row.
"""
name = "delete-row"
database: str
table: str
pks: list
@hookimpl
def register_events():
return [
LoginEvent,
LogoutEvent,
CreateTableEvent,
CreateTokenEvent,
AlterTableEvent,
DropTableEvent,
InsertRowsEvent,
UpsertRowsEvent,
UpdateRowEvent,
DeleteRowEvent,
]
| DeleteRowEvent |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 184019,
"end": 184376
} | class ____:
_col_type = INT4RANGE
_col_str = "INT4RANGE"
_col_str_arr = "INT8RANGE"
def _data_str(self):
return "[1,4)"
def _data_obj(self):
return Range(1, 4)
_epsilon = 1
def _step_value_up(self, value):
return value + 1
def _step_value_down(self, value):
return value - 1
| _Int4RangeTests |
python | pytorch__pytorch | torch/nn/utils/weight_norm.py | {
"start": 384,
"end": 5882
} | class ____:
name: str
dim: int
def __init__(self, name: str, dim: int) -> None:
if dim is None:
dim = -1
self.name = name
self.dim = dim
# TODO Make return type more specific
def compute_weight(self, module: Module) -> Any:
g = getattr(module, self.name + "_g")
v = getattr(module, self.name + "_v")
return _weight_norm(v, g, self.dim)
@staticmethod
@deprecated(
"`torch.nn.utils.weight_norm` is deprecated "
"in favor of `torch.nn.utils.parametrizations.weight_norm`.",
category=FutureWarning,
)
def apply(module, name: str, dim: int) -> "WeightNorm":
for hook in module._forward_pre_hooks.values():
if isinstance(hook, WeightNorm) and hook.name == name:
raise RuntimeError(
f"Cannot register two weight_norm hooks on the same parameter {name}"
)
if dim is None:
dim = -1
fn = WeightNorm(name, dim)
weight = getattr(module, name)
if isinstance(weight, UninitializedParameter):
raise ValueError(
"The module passed to `WeightNorm` can't have uninitialized parameters. "
"Make sure to run the dummy forward before applying weight normalization"
)
# remove w from parameter list
del module._parameters[name]
# add g and v as new parameters and express w as g/||v|| * v
module.register_parameter(
name + "_g", Parameter(norm_except_dim(weight, 2, dim).data)
)
module.register_parameter(name + "_v", Parameter(weight.data))
setattr(module, name, fn.compute_weight(module))
# recompute weight before every forward()
module.register_forward_pre_hook(fn)
return fn
def remove(self, module: Module) -> None:
weight = self.compute_weight(module)
delattr(module, self.name)
del module._parameters[self.name + "_g"]
del module._parameters[self.name + "_v"]
setattr(module, self.name, Parameter(weight.data))
def __call__(self, module: Module, inputs: Any) -> None:
setattr(module, self.name, self.compute_weight(module))
T_module = TypeVar("T_module", bound=Module)
def weight_norm(module: T_module, name: str = "weight", dim: int = 0) -> T_module:
r"""Apply weight normalization to a parameter in the given module.
.. math::
\mathbf{w} = g \dfrac{\mathbf{v}}{\|\mathbf{v}\|}
Weight normalization is a reparameterization that decouples the magnitude
of a weight tensor from its direction. This replaces the parameter specified
by :attr:`name` (e.g. ``'weight'``) with two parameters: one specifying the magnitude
(e.g. ``'weight_g'``) and one specifying the direction (e.g. ``'weight_v'``).
Weight normalization is implemented via a hook that recomputes the weight
tensor from the magnitude and direction before every :meth:`~Module.forward`
call.
By default, with ``dim=0``, the norm is computed independently per output
channel/plane. To compute a norm over the entire weight tensor, use
``dim=None``.
See https://arxiv.org/abs/1602.07868
.. warning::
This function is deprecated. Use :func:`torch.nn.utils.parametrizations.weight_norm`
which uses the modern parametrization API. The new ``weight_norm`` is compatible
with ``state_dict`` generated from old ``weight_norm``.
Migration guide:
* The magnitude (``weight_g``) and direction (``weight_v``) are now expressed
as ``parametrizations.weight.original0`` and ``parametrizations.weight.original1``
respectively. If this is bothering you, please comment on
https://github.com/pytorch/pytorch/issues/102999
* To remove the weight normalization reparametrization, use
:func:`torch.nn.utils.parametrize.remove_parametrizations`.
* The weight is no longer recomputed once at module forward; instead, it will
be recomputed on every access. To restore the old behavior, use
:func:`torch.nn.utils.parametrize.cached` before invoking the module
in question.
Args:
module (Module): containing module
name (str, optional): name of weight parameter
dim (int, optional): dimension over which to compute the norm
Returns:
The original module with the weight norm hook
Example::
>>> m = weight_norm(nn.Linear(20, 40), name='weight')
>>> m
Linear(in_features=20, out_features=40, bias=True)
>>> m.weight_g.size()
torch.Size([40, 1])
>>> m.weight_v.size()
torch.Size([40, 20])
"""
WeightNorm.apply(module, name, dim)
return module
def remove_weight_norm(module: T_module, name: str = "weight") -> T_module:
r"""Remove the weight normalization reparameterization from a module.
Args:
module (Module): containing module
name (str, optional): name of weight parameter
Example:
>>> m = weight_norm(nn.Linear(20, 40))
>>> remove_weight_norm(m)
"""
for k, hook in module._forward_pre_hooks.items():
if isinstance(hook, WeightNorm) and hook.name == name:
hook.remove(module)
del module._forward_pre_hooks[k]
return module
raise ValueError(f"weight_norm of '{name}' not found in {module}")
| WeightNorm |
python | dask__dask | dask/graph_manipulation.py | {
"start": 19257,
"end": 19771
} | class ____:
"""Callables to be inserted in the Dask graph"""
@staticmethod
def bind(node: T, *args, **kwargs) -> T:
"""Dummy graph node of :func:`bind` and :func:`wait_on`.
Wait for both node and all variadic args to complete; then return node.
"""
return node
@staticmethod
def checkpoint(*args, **kwargs) -> None:
"""Dummy graph node of :func:`checkpoint`.
Wait for all variadic args to complete; then return None.
"""
pass
| chunks |
python | sqlalchemy__sqlalchemy | test/orm/test_pickled.py | {
"start": 24769,
"end": 27973
} | class ____(_fixtures.FixtureTest):
@classmethod
def setup_classes(cls):
pass
@classmethod
def setup_mappers(cls):
users, addresses, orders = (
cls.tables.users,
cls.tables.addresses,
cls.tables.orders,
)
cls.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(
Address, backref="user", order_by=addresses.c.id
),
# o2m, m2o
"orders": relationship(
Order, backref="user", order_by=orders.c.id
),
},
)
cls.mapper_registry.map_imperatively(Address, addresses)
cls.mapper_registry.map_imperatively(
Order, orders, properties={"address": relationship(Address)}
) # m2o
def test_tuple_labeling(self):
sess = fixture_session()
# test pickle + all the protocols !
for pickled in False, -1, 0, 1, 2:
for row in sess.query(User, Address).join(User.addresses).all():
if pickled is not False:
row = pickle.loads(pickle.dumps(row, pickled))
eq_(list(row._fields), ["User", "Address"])
eq_(row.User, row[0])
eq_(row.Address, row[1])
for row in sess.query(User.name, User.id.label("foobar")):
if pickled is not False:
row = pickle.loads(pickle.dumps(row, pickled))
eq_(list(row._fields), ["name", "foobar"])
eq_(row.name, row[0])
eq_(row.foobar, row[1])
for row in sess.query(User).with_entities(
User.name, User.id.label("foobar")
):
if pickled is not False:
row = pickle.loads(pickle.dumps(row, pickled))
eq_(list(row._fields), ["name", "foobar"])
eq_(row.name, row[0])
eq_(row.foobar, row[1])
oalias = aliased(Order)
for row in (
sess.query(User, oalias)
.join(User.orders.of_type(oalias))
.all()
):
if pickled is not False:
row = pickle.loads(pickle.dumps(row, pickled))
eq_(list(row._fields), ["User"])
eq_(row.User, row[0])
oalias = aliased(Order, name="orders")
for row in (
sess.query(User, oalias).join(oalias, User.orders).all()
):
if pickled is not False:
row = pickle.loads(pickle.dumps(row, pickled))
eq_(list(row._fields), ["User", "orders"])
eq_(row.User, row[0])
eq_(row.orders, row[1])
for row in sess.query(User.name + "hoho", User.name):
eq_(list(row._fields), ["name"])
eq_(row[0], row.name + "hoho")
if pickled is not False:
ret = sess.query(User, Address).join(User.addresses).all()
pickle.loads(pickle.dumps(ret, pickled))
| TupleLabelTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_comprehend.py | {
"start": 4365,
"end": 8313
} | class ____:
JOB_ID = "random-job-id-1234567"
MODE = "ONLY_REDACTION"
JOB_NAME = "TEST_START_PII_ENTITIES_DETECTION_JOB-1"
DEFAULT_JOB_NAME_STARTS_WITH = "start_pii_entities_detection_job"
REDACTION_CONFIG = {"PiiEntityTypes": ["NAME", "ADDRESS"], "MaskMode": "REPLACE_WITH_PII_ENTITY_TYPE"}
@pytest.fixture
def mock_conn(self) -> Generator[BaseAwsConnection, None, None]:
with mock.patch.object(ComprehendHook, "conn") as _conn:
_conn.start_pii_entities_detection_job.return_value = {"JobId": self.JOB_ID}
yield _conn
@pytest.fixture
def comprehend_hook(self) -> Generator[ComprehendHook, None, None]:
with mock_aws():
hook = ComprehendHook(aws_conn_id="aws_default")
yield hook
def setup_method(self):
self.operator = ComprehendStartPiiEntitiesDetectionJobOperator(
task_id="start_pii_entities_detection_job",
input_data_config=INPUT_DATA_CONFIG,
output_data_config=OUTPUT_DATA_CONFIG,
data_access_role_arn=ROLE_ARN,
mode=self.MODE,
language_code=LANGUAGE_CODE,
start_pii_entities_kwargs={"JobName": self.JOB_NAME, "RedactionConfig": self.REDACTION_CONFIG},
)
self.operator.defer = mock.MagicMock()
def test_init(self):
assert self.operator.input_data_config == INPUT_DATA_CONFIG
assert self.operator.output_data_config == OUTPUT_DATA_CONFIG
assert self.operator.data_access_role_arn == ROLE_ARN
assert self.operator.mode == self.MODE
assert self.operator.language_code == LANGUAGE_CODE
assert self.operator.start_pii_entities_kwargs.get("JobName") == self.JOB_NAME
assert self.operator.start_pii_entities_kwargs.get("RedactionConfig") == self.REDACTION_CONFIG
@mock.patch.object(ComprehendHook, "conn")
def test_start_pii_entities_detection_job_name_starts_with_service_name(self, comprehend_mock_conn):
self.op = ComprehendStartPiiEntitiesDetectionJobOperator(
task_id="start_pii_entities_detection_job",
input_data_config=INPUT_DATA_CONFIG,
output_data_config=OUTPUT_DATA_CONFIG,
data_access_role_arn=ROLE_ARN,
mode=self.MODE,
language_code=LANGUAGE_CODE,
start_pii_entities_kwargs={"RedactionConfig": self.REDACTION_CONFIG},
)
self.op.wait_for_completion = False
self.op.execute({})
assert self.op.start_pii_entities_kwargs.get("JobName").startswith(self.DEFAULT_JOB_NAME_STARTS_WITH)
comprehend_mock_conn.start_pii_entities_detection_job.assert_called_once_with(
InputDataConfig=INPUT_DATA_CONFIG,
OutputDataConfig=OUTPUT_DATA_CONFIG,
Mode=self.MODE,
DataAccessRoleArn=ROLE_ARN,
LanguageCode=LANGUAGE_CODE,
RedactionConfig=self.REDACTION_CONFIG,
JobName=self.op.start_pii_entities_kwargs.get("JobName"),
)
@pytest.mark.parametrize(
("wait_for_completion", "deferrable"),
[
pytest.param(False, False, id="no_wait"),
pytest.param(True, False, id="wait"),
pytest.param(False, True, id="defer"),
],
)
@mock.patch.object(ComprehendHook, "get_waiter")
def test_start_pii_entities_detection_job_wait_combinations(
self, _, wait_for_completion, deferrable, mock_conn, comprehend_hook
):
self.operator.wait_for_completion = wait_for_completion
self.operator.deferrable = deferrable
response = self.operator.execute({})
assert response == self.JOB_ID
assert comprehend_hook.get_waiter.call_count == wait_for_completion
assert self.operator.defer.call_count == deferrable
def test_template_fields(self):
validate_template_fields(self.operator)
| TestComprehendStartPiiEntitiesDetectionJobOperator |
python | rapidsai__cudf | python/cudf/cudf/tests/dataframe/indexing/test_loc.py | {
"start": 29052,
"end": 41622
} | class ____:
# https://github.com/rapidsai/cudf/issues/12833
@pytest.fixture(params=["increasing", "decreasing", "neither"])
def order(self, request):
return request.param
@pytest.fixture(params=[-1, 1], ids=["reverse", "forward"])
def take_order(self, request):
return request.param
@pytest.fixture(params=["float", "int", "string", "range"])
def dtype(self, request):
return request.param
@pytest.fixture
def index(self, order, dtype):
if dtype == "string":
index = ["a", "h", "f", "z"]
elif dtype == "int":
index = [-1, 10, 7, 14]
elif dtype == "float":
index = [-1.5, 7.10, 2.4, 11.2]
elif dtype == "range":
if order == "increasing":
return cudf.RangeIndex(2, 10, 3)
elif order == "decreasing":
return cudf.RangeIndex(10, 1, -3)
else:
return cudf.RangeIndex(10, 20, 3)
else:
raise ValueError(f"Unhandled index dtype {dtype}")
if order == "decreasing":
return sorted(index, reverse=True)
elif order == "increasing":
return sorted(index)
elif order == "neither":
return index
else:
raise ValueError(f"Unhandled index order {order}")
@pytest.fixture
def df(self, index):
return cudf.DataFrame({"a": range(len(index))}, index=index)
def test_loc_index_inindex_slice(self, df, take_order):
pdf = df.to_pandas()
lo = pdf.index[1]
hi = pdf.index[-2]
expect = pdf.loc[lo:hi:take_order]
actual = df.loc[lo:hi:take_order]
assert_eq(expect, actual)
def test_loc_index_inindex_subset(self, df, take_order):
pdf = df.to_pandas()
vals = [pdf.index[0], pdf.index[2]][::take_order]
expect = pdf.loc[vals]
actual = df.loc[vals]
assert_eq(expect, actual)
def test_loc_index_notinindex_slice(self, df, order, dtype, take_order):
pdf = df.to_pandas()
lo = pdf.index[1]
hi = pdf.index[-2]
if isinstance(lo, str):
lo = chr(ord(lo) - 1)
hi = chr(ord(hi) + 1)
else:
lo -= 1
hi += 1
if order == "neither" and dtype != "range":
with pytest.raises(KeyError):
pdf.loc[lo:hi:take_order]
with pytest.raises(KeyError):
df.loc[lo:hi:take_order]
else:
expect = pdf.loc[lo:hi:take_order]
actual = df.loc[lo:hi:take_order]
assert_eq(expect, actual)
def test_loc_single_row_from_slice():
# see https://github.com/rapidsai/cudf/issues/11930
pdf = pd.DataFrame({"a": [10, 20, 30], "b": [1, 2, 3]}).set_index("a")
df = cudf.from_pandas(pdf)
assert_eq(pdf.loc[5:10], df.loc[5:10])
@pytest.mark.parametrize("indexer", ["loc", "iloc"])
def test_boolean_mask_columns(indexer):
df = pd.DataFrame(np.zeros((3, 3)))
cdf = cudf.from_pandas(df)
mask = [True, False, True]
expect = getattr(df, indexer)[:, mask]
got = getattr(cdf, indexer)[:, mask]
assert_eq(expect, got)
@pytest.mark.parametrize("indexer", ["loc", "iloc"])
@pytest.mark.parametrize(
"mask",
[[False, True], [False, False, True, True, True]],
ids=["too-short", "too-long"],
)
def test_boolean_mask_columns_wrong_length(indexer, mask):
df = pd.DataFrame(np.zeros((3, 3)))
cdf = cudf.from_pandas(df)
with pytest.raises(IndexError):
getattr(df, indexer)[:, mask]
with pytest.raises(IndexError):
getattr(cdf, indexer)[:, mask]
@pytest.mark.parametrize("index_type", ["single", "slice"])
def test_loc_timestamp_issue_8585(index_type):
rng = np.random.default_rng(seed=0)
# https://github.com/rapidsai/cudf/issues/8585
start = pd.Timestamp("2021-03-12 00:00")
end = pd.Timestamp("2021-03-12 11:00")
timestamps = pd.date_range(start, end, periods=12)
value = rng.normal(size=12)
df = pd.DataFrame(value, index=timestamps, columns=["value"])
cdf = cudf.from_pandas(df)
if index_type == "single":
index = pd.Timestamp("2021-03-12 03:00")
elif index_type == "slice":
index = slice(start, end, None)
else:
raise ValueError("Invalid index type")
expect = df.loc[index]
actual = cdf.loc[index]
assert_eq(expect, actual)
@pytest.mark.parametrize(
"index_type",
[
"single",
pytest.param(
"slice",
marks=pytest.mark.xfail(
reason="https://github.com/rapidsai/cudf/issues/8585"
),
),
pytest.param(
"date_range",
marks=pytest.mark.xfail(
reason="https://github.com/rapidsai/cudf/issues/8585"
),
),
],
)
def test_loc_multiindex_timestamp_issue_8585(index_type):
rng = np.random.default_rng(seed=0)
# https://github.com/rapidsai/cudf/issues/8585
start = pd.Timestamp("2021-03-12 00:00")
end = pd.Timestamp("2021-03-12 03:00")
timestamps = pd.date_range(start, end, periods=4)
labels = ["A", "B", "C"]
index = pd.MultiIndex.from_product(
[timestamps, labels], names=["timestamp", "label"]
)
value = rng.normal(size=12)
df = pd.DataFrame(value, index=index, columns=["value"])
cdf = cudf.from_pandas(df)
start = pd.Timestamp("2021-03-12 01:00")
end = pd.Timestamp("2021-03-12 02:00")
if index_type == "single":
index = pd.Timestamp("2021-03-12 03:00")
elif index_type == "slice":
index = slice(start, end, None)
elif index_type == "date_range":
index = pd.date_range(start, end, periods=2)
else:
raise ValueError("Invalid index type")
expect = df.loc[index]
actual = cdf.loc[index]
assert_eq(expect, actual)
@pytest.mark.parametrize(
"indexer", [(..., 0), (0, ...)], ids=["row_ellipsis", "column_ellipsis"]
)
def test_loc_ellipsis_as_slice_issue_13268(indexer):
# https://github.com/rapidsai/cudf/issues/13268
df = pd.DataFrame(np.arange(4).reshape(2, 2))
cdf = cudf.from_pandas(df)
expect = df.loc[indexer]
actual = cdf.loc[indexer]
assert_eq(expect, actual)
@pytest.mark.xfail(
reason="https://github.com/rapidsai/cudf/issues/13269 "
"and https://github.com/rapidsai/cudf/issues/13273"
)
def test_loc_repeated_column_label_issue_13269():
# https://github.com/rapidsai/cudf/issues/13269
# https://github.com/rapidsai/cudf/issues/13273
df = pd.DataFrame(np.arange(4).reshape(2, 2))
cdf = cudf.from_pandas(df)
expect = df.loc[:, [0, 1, 0]]
actual = cdf.loc[:, [0, 1, 0]]
assert_eq(expect, actual)
def test_loc_column_boolean_mask_issue_13270():
# https://github.com/rapidsai/cudf/issues/13270
df = pd.DataFrame(np.arange(4).reshape(2, 2))
cdf = cudf.from_pandas(df)
expect = df.loc[:, [True, True]]
actual = cdf.loc[:, [True, True]]
assert_eq(expect, actual)
def test_loc_unsorted_index_slice_lookup_keyerror_issue_12833():
# https://github.com/rapidsai/cudf/issues/12833
df = pd.DataFrame({"a": [1, 2, 3]}, index=[7, 0, 4])
cdf = cudf.from_pandas(df)
# Check that pandas don't change their mind
with pytest.raises(KeyError):
df.loc[1:5]
with pytest.raises(KeyError):
cdf.loc[1:5]
@pytest.mark.parametrize("index", [range(5), list(range(5))])
def test_loc_missing_label_keyerror_issue_13379(index):
# https://github.com/rapidsai/cudf/issues/13379
df = pd.DataFrame({"a": index}, index=index)
cdf = cudf.from_pandas(df)
# Check that pandas don't change their mind
with pytest.raises(KeyError):
df.loc[[0, 5]]
with pytest.raises(KeyError):
cdf.loc[[0, 5]]
@pytest.mark.parametrize("series", [True, False], ids=["Series", "DataFrame"])
def test_loc_repeated_label_ordering_issue_13658(series):
# https://github.com/rapidsai/cudf/issues/13658
values = range(2048)
index = [1 for _ in values]
if series:
frame = cudf.Series(values, index=index)
else:
frame = cudf.DataFrame({"a": values}, index=index)
expect = frame.to_pandas().loc[[1]]
actual = frame.loc[[1]]
assert_eq(actual, expect)
@pytest.mark.parametrize(
"arg",
[
(2, ("one", "second")),
(slice(None, None, None), ("two", "first")),
(1, ("one", "first")),
(slice(None, None, None), ("two", "second")),
(slice(None, None, None), ("two", "first", "three")),
(3, ("two", "first", "three")),
(slice(None, None, None), ("two",)),
(0, ("two",)),
],
)
def test_loc_dataframe_column_multiindex(arg):
gdf = cudf.DataFrame(
[list("abcd"), list("efgh"), list("ijkl"), list("mnop")],
columns=cudf.MultiIndex.from_product(
[["one", "two"], ["first", "second"], ["three"]]
),
)
pdf = gdf.to_pandas()
assert_eq(gdf.loc[arg], pdf.loc[arg])
def test_loc_setitem_categorical_integer_not_position_based():
gdf = cudf.DataFrame(range(3), index=cudf.CategoricalIndex([1, 2, 3]))
pdf = gdf.to_pandas()
gdf.loc[1] = 10
pdf.loc[1] = 10
assert_eq(gdf, pdf)
def test_scalar_loc_row_categoricalindex():
df = cudf.DataFrame(
range(4), index=cudf.CategoricalIndex(["a", "a", "b", "c"])
)
result = df.loc["a"]
expected = df.to_pandas().loc["a"]
assert_eq(result, expected)
@pytest.mark.parametrize("klass", [cudf.DataFrame, cudf.Series])
@pytest.mark.parametrize("indexer", ["iloc", "loc"])
def test_iloc_loc_no_circular_reference(klass, indexer):
obj = klass([0])
ref = weakref.ref(obj)
getattr(obj, indexer)[0]
del obj
assert ref() is None
def test_loc_setitem_empty_dataframe():
pdf = pd.DataFrame(index=["index_1", "index_2", "index_3"])
gdf = cudf.from_pandas(pdf)
pdf.loc[["index_1"], "new_col"] = "A"
gdf.loc[["index_1"], "new_col"] = "A"
assert_eq(pdf, gdf)
@pytest.mark.parametrize(
"data",
[
[15, 14, 12, 10, 1],
[1, 10, 12, 14, 15],
],
)
@pytest.mark.parametrize(
"scalar",
[
1,
10,
15,
14,
0,
2,
],
)
def test_loc_datetime_monotonic_with_ts(data, scalar):
gdf = cudf.DataFrame(
{"a": [1, 1, 1, 2, 2], "b": [1, 2, 3, 4, 5]},
index=cudf.Index(data, dtype="datetime64[ns]"),
)
pdf = gdf.to_pandas()
i = pd.Timestamp(scalar)
actual = gdf.loc[i:]
expected = pdf.loc[i:]
assert_eq(actual, expected)
actual = gdf.loc[:i]
expected = pdf.loc[:i]
assert_eq(actual, expected)
@pytest.mark.parametrize("scalar", [1, 0])
def test_loc_datetime_random_with_ts(scalar):
gdf = cudf.DataFrame(
{"a": [1, 1, 1, 2, 2], "b": [1, 2, 3, 4, 5]},
index=cudf.Index([15, 14, 3, 10, 1], dtype="datetime64[ns]"),
)
pdf = gdf.to_pandas()
i = pd.Timestamp(scalar)
if i not in pdf.index:
assert_exceptions_equal(
lambda: pdf.loc[i:],
lambda: gdf.loc[i:],
lfunc_args_and_kwargs=([],),
rfunc_args_and_kwargs=([],),
)
assert_exceptions_equal(
lambda: pdf.loc[:i],
lambda: gdf.loc[:i],
lfunc_args_and_kwargs=([],),
rfunc_args_and_kwargs=([],),
)
else:
actual = gdf.loc[i:]
expected = pdf.loc[i:]
assert_eq(actual, expected)
actual = gdf.loc[:i]
expected = pdf.loc[:i]
assert_eq(actual, expected)
@pytest.mark.parametrize("indexer", ["iloc", "loc"])
@pytest.mark.parametrize("dtype", ["category", "timedelta64[ns]"])
def test_loc_iloc_setitem_col_slice_non_cupy_types(indexer, dtype):
df_pd = pd.DataFrame(range(2), dtype=dtype)
df_cudf = cudf.DataFrame(df_pd)
getattr(df_pd, indexer)[:, 0] = getattr(df_pd, indexer)[:, 0]
getattr(df_cudf, indexer)[:, 0] = getattr(df_cudf, indexer)[:, 0]
assert_eq(df_pd, df_cudf)
@pytest.mark.parametrize("indexer", ["iloc", "loc"])
@pytest.mark.parametrize(
"column_slice",
[
slice(None),
slice(0, 0),
slice(0, 1),
slice(1, 0),
slice(0, 2, 2),
],
)
def test_slice_empty_columns(indexer, column_slice):
df_pd = pd.DataFrame(index=[0, 1, 2])
df_cudf = cudf.from_pandas(df_pd)
result = getattr(df_cudf, indexer)[:, column_slice]
expected = getattr(df_pd, indexer)[:, column_slice]
assert_eq(result, expected)
| TestLocIndexWithOrder |
python | PyCQA__pylint | tests/functional/u/unused/unused_import.py | {
"start": 647,
"end": 1389
} | class ____:
SomeName = SomeName # https://bitbucket.org/logilab/pylint/issue/475
SomeOtherName = 1
SomeOtherName = SomeOtherName
from never import __all__
# pylint: disable=wrong-import-order,ungrouped-imports,reimported
import typing
from typing import TYPE_CHECKING
import typing as t
if typing.TYPE_CHECKING:
import collections
if TYPE_CHECKING:
import itertools
if t.TYPE_CHECKING:
import xml
EXAMPLE: t.Annotated[str, "Path"] = "/foo/bar"
def get_ordered_dict() -> "collections.OrderedDict":
return []
def get_itertools_obj() -> "itertools.count":
return []
def use_html_parser() -> "html.parser.HTMLParser":
return html.parser.HTMLParser
import os # [unused-import]
import sys
| SomeClass |
python | lepture__authlib | authlib/oauth1/rfc5849/errors.py | {
"start": 1166,
"end": 1263
} | class ____(OAuth1Error):
error = "unsupported_signature_method"
| UnsupportedSignatureMethodError |
python | python-openxml__python-docx | src/docx/image/png.py | {
"start": 962,
"end": 2713
} | class ____:
"""Parses a PNG image stream to extract the image properties found in its chunks."""
def __init__(self, chunks):
super(_PngParser, self).__init__()
self._chunks = chunks
@classmethod
def parse(cls, stream):
"""Return a |_PngParser| instance containing the header properties parsed from
the PNG image in `stream`."""
chunks = _Chunks.from_stream(stream)
return cls(chunks)
@property
def px_width(self):
"""The number of pixels in each row of the image."""
IHDR = self._chunks.IHDR
return IHDR.px_width
@property
def px_height(self):
"""The number of stacked rows of pixels in the image."""
IHDR = self._chunks.IHDR
return IHDR.px_height
@property
def horz_dpi(self):
"""Integer dots per inch for the width of this image.
Defaults to 72 when not present in the file, as is often the case.
"""
pHYs = self._chunks.pHYs
if pHYs is None:
return 72
return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit)
@property
def vert_dpi(self):
"""Integer dots per inch for the height of this image.
Defaults to 72 when not present in the file, as is often the case.
"""
pHYs = self._chunks.pHYs
if pHYs is None:
return 72
return self._dpi(pHYs.units_specifier, pHYs.vert_px_per_unit)
@staticmethod
def _dpi(units_specifier, px_per_unit):
"""Return dots per inch value calculated from `units_specifier` and
`px_per_unit`."""
if units_specifier == 1 and px_per_unit:
return int(round(px_per_unit * 0.0254))
return 72
| _PngParser |
python | encode__django-rest-framework | tests/test_metadata.py | {
"start": 431,
"end": 11149
} | class ____:
def test_determine_metadata_abstract_method_raises_proper_error(self):
with pytest.raises(NotImplementedError):
metadata.BaseMetadata().determine_metadata(None, None)
def test_metadata(self):
"""
OPTIONS requests to views should return a valid 200 response.
"""
class ExampleView(views.APIView):
"""Example view."""
pass
view = ExampleView.as_view()
response = view(request=request)
expected = {
'name': 'Example',
'description': 'Example view.',
'renders': [
'application/json',
'text/html'
],
'parses': [
'application/json',
'application/x-www-form-urlencoded',
'multipart/form-data'
]
}
assert response.status_code == status.HTTP_200_OK
assert response.data == expected
def test_none_metadata(self):
"""
OPTIONS requests to views where `metadata_class = None` should raise
a MethodNotAllowed exception, which will result in an HTTP 405 response.
"""
class ExampleView(views.APIView):
metadata_class = None
view = ExampleView.as_view()
response = view(request=request)
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
assert response.data == {'detail': 'Method "OPTIONS" not allowed.'}
def test_actions(self):
"""
On generic views OPTIONS should return an 'actions' key with metadata
on the fields that may be supplied to PUT and POST requests.
"""
class NestedField(serializers.Serializer):
a = serializers.IntegerField()
b = serializers.IntegerField()
class ExampleSerializer(serializers.Serializer):
choice_field = serializers.ChoiceField(['red', 'green', 'blue'])
integer_field = serializers.IntegerField(
min_value=1, max_value=1000
)
char_field = serializers.CharField(
required=False, min_length=3, max_length=40
)
list_field = serializers.ListField(
child=serializers.ListField(
child=serializers.IntegerField()
)
)
nested_field = NestedField()
uuid_field = serializers.UUIDField(label="UUID field")
class ExampleView(views.APIView):
"""Example view."""
def post(self, request):
pass
def get_serializer(self):
return ExampleSerializer()
view = ExampleView.as_view()
response = view(request=request)
expected = {
'name': 'Example',
'description': 'Example view.',
'renders': [
'application/json',
'text/html'
],
'parses': [
'application/json',
'application/x-www-form-urlencoded',
'multipart/form-data'
],
'actions': {
'POST': {
'choice_field': {
'type': 'choice',
'required': True,
'read_only': False,
'label': 'Choice field',
'choices': [
{'display_name': 'red', 'value': 'red'},
{'display_name': 'green', 'value': 'green'},
{'display_name': 'blue', 'value': 'blue'}
]
},
'integer_field': {
'type': 'integer',
'required': True,
'read_only': False,
'label': 'Integer field',
'min_value': 1,
'max_value': 1000,
},
'char_field': {
'type': 'string',
'required': False,
'read_only': False,
'label': 'Char field',
'min_length': 3,
'max_length': 40
},
'list_field': {
'type': 'list',
'required': True,
'read_only': False,
'label': 'List field',
'child': {
'type': 'list',
'required': True,
'read_only': False,
'child': {
'type': 'integer',
'required': True,
'read_only': False
}
}
},
'nested_field': {
'type': 'nested object',
'required': True,
'read_only': False,
'label': 'Nested field',
'children': {
'a': {
'type': 'integer',
'required': True,
'read_only': False,
'label': 'A'
},
'b': {
'type': 'integer',
'required': True,
'read_only': False,
'label': 'B'
}
}
},
'uuid_field': {
"type": "string",
"required": True,
"read_only": False,
"label": "UUID field",
},
}
}
}
assert response.status_code == status.HTTP_200_OK
assert response.data == expected
def test_global_permissions(self):
"""
If a user does not have global permissions on an action, then any
metadata associated with it should not be included in OPTION responses.
"""
class ExampleSerializer(serializers.Serializer):
choice_field = serializers.ChoiceField(['red', 'green', 'blue'])
integer_field = serializers.IntegerField(max_value=10)
char_field = serializers.CharField(required=False)
class ExampleView(views.APIView):
"""Example view."""
def post(self, request):
pass
def put(self, request):
pass
def get_serializer(self):
return ExampleSerializer()
def check_permissions(self, request):
if request.method == 'POST':
raise exceptions.PermissionDenied()
view = ExampleView.as_view()
response = view(request=request)
assert response.status_code == status.HTTP_200_OK
assert list(response.data['actions']) == ['PUT']
def test_object_permissions(self):
"""
If a user does not have object permissions on an action, then any
metadata associated with it should not be included in OPTION responses.
"""
class ExampleSerializer(serializers.Serializer):
choice_field = serializers.ChoiceField(['red', 'green', 'blue'])
integer_field = serializers.IntegerField(max_value=10)
char_field = serializers.CharField(required=False)
class ExampleView(views.APIView):
"""Example view."""
def post(self, request):
pass
def put(self, request):
pass
def get_serializer(self):
return ExampleSerializer()
def get_object(self):
if self.request.method == 'PUT':
raise exceptions.PermissionDenied()
view = ExampleView.as_view()
response = view(request=request)
assert response.status_code == status.HTTP_200_OK
assert list(response.data['actions'].keys()) == ['POST']
def test_bug_2455_clone_request(self):
class ExampleView(views.APIView):
renderer_classes = (BrowsableAPIRenderer,)
def post(self, request):
pass
def get_serializer(self):
assert hasattr(self.request, 'version')
return serializers.Serializer()
view = ExampleView.as_view()
view(request=request)
def test_bug_2477_clone_request(self):
class ExampleView(views.APIView):
renderer_classes = (BrowsableAPIRenderer,)
def post(self, request):
pass
def get_serializer(self):
assert hasattr(self.request, 'versioning_scheme')
return serializers.Serializer()
scheme = versioning.QueryParameterVersioning
view = ExampleView.as_view(versioning_class=scheme)
view(request=request)
def test_dont_show_hidden_fields(self):
"""
HiddenField shouldn't show up in SimpleMetadata at all.
"""
class ExampleSerializer(serializers.Serializer):
integer_field = serializers.IntegerField(max_value=10)
hidden_field = serializers.HiddenField(default=1)
class ExampleView(views.APIView):
"""Example view."""
def post(self, request):
pass
def get_serializer(self):
return ExampleSerializer()
view = ExampleView.as_view()
response = view(request=request)
assert response.status_code == status.HTTP_200_OK
assert set(response.data['actions']['POST'].keys()) == {'integer_field'}
def test_list_serializer_metadata_returns_info_about_fields_of_child_serializer(self):
class ExampleSerializer(serializers.Serializer):
integer_field = serializers.IntegerField(max_value=10)
char_field = serializers.CharField(required=False)
class ExampleListSerializer(serializers.ListSerializer):
pass
options = metadata.SimpleMetadata()
child_serializer = ExampleSerializer()
list_serializer = ExampleListSerializer(child=child_serializer)
assert options.get_serializer_info(list_serializer) == options.get_serializer_info(child_serializer)
| TestMetadata |
python | networkx__networkx | networkx/algorithms/tree/tests/test_mst.py | {
"start": 14416,
"end": 17454
} | class ____:
"""
Tests the spanning tree iterator on the example graph in the 2005 Sörensen
and Janssens paper An Algorithm to Generate all Spanning Trees of a Graph in
Order of Increasing Cost
"""
def setup_method(self):
# Original Graph
edges = [(0, 1, 5), (1, 2, 4), (1, 4, 6), (2, 3, 5), (2, 4, 7), (3, 4, 3)]
self.G = nx.Graph()
self.G.add_weighted_edges_from(edges)
# List of lists of spanning trees in increasing order
self.spanning_trees = [
# 1, MST, cost = 17
[
(0, 1, {"weight": 5}),
(1, 2, {"weight": 4}),
(2, 3, {"weight": 5}),
(3, 4, {"weight": 3}),
],
# 2, cost = 18
[
(0, 1, {"weight": 5}),
(1, 2, {"weight": 4}),
(1, 4, {"weight": 6}),
(3, 4, {"weight": 3}),
],
# 3, cost = 19
[
(0, 1, {"weight": 5}),
(1, 4, {"weight": 6}),
(2, 3, {"weight": 5}),
(3, 4, {"weight": 3}),
],
# 4, cost = 19
[
(0, 1, {"weight": 5}),
(1, 2, {"weight": 4}),
(2, 4, {"weight": 7}),
(3, 4, {"weight": 3}),
],
# 5, cost = 20
[
(0, 1, {"weight": 5}),
(1, 2, {"weight": 4}),
(1, 4, {"weight": 6}),
(2, 3, {"weight": 5}),
],
# 6, cost = 21
[
(0, 1, {"weight": 5}),
(1, 4, {"weight": 6}),
(2, 4, {"weight": 7}),
(3, 4, {"weight": 3}),
],
# 7, cost = 21
[
(0, 1, {"weight": 5}),
(1, 2, {"weight": 4}),
(2, 3, {"weight": 5}),
(2, 4, {"weight": 7}),
],
# 8, cost = 23
[
(0, 1, {"weight": 5}),
(1, 4, {"weight": 6}),
(2, 3, {"weight": 5}),
(2, 4, {"weight": 7}),
],
]
def test_minimum_spanning_tree_iterator(self):
"""
Tests that the spanning trees are correctly returned in increasing order
"""
tree_index = 0
for tree in nx.SpanningTreeIterator(self.G):
actual = sorted(tree.edges(data=True))
assert edges_equal(actual, self.spanning_trees[tree_index])
tree_index += 1
def test_maximum_spanning_tree_iterator(self):
"""
Tests that the spanning trees are correctly returned in decreasing order
"""
tree_index = 7
for tree in nx.SpanningTreeIterator(self.G, minimum=False):
actual = sorted(tree.edges(data=True))
assert edges_equal(actual, self.spanning_trees[tree_index])
tree_index -= 1
| TestSpanningTreeIterator |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_run_launcher.py | {
"start": 8496,
"end": 9676
} | class ____(LaunchFailTestSuite):
def test_multiple_launch_failure(self, graphql_context: WorkspaceRequestContext):
executionParamsList = [
{"selector": infer_job_selector(graphql_context, "no_config_job"), "mode": "default"},
{"selector": infer_job_selector(graphql_context, "no_config_job"), "mode": "default"},
]
result = execute_dagster_graphql(
context=graphql_context,
query=LAUNCH_MULTIPLE_RUNS_MUTATION,
variables={"executionParamsList": executionParamsList},
)
assert "launchMultipleRuns" in result.data
result_data = result.data["launchMultipleRuns"]
assert result_data["__typename"] == "LaunchMultipleRunsResult"
results = result_data["launchMultipleRunsResult"]
assert len(results) == 2
for run_result in results:
assert run_result["__typename"] == "PythonError"
assert run_result["message"].startswith(
"NotImplementedError: The entire purpose of this is to throw on launch"
)
assert run_result["className"] == "NotImplementedError"
| TestFailedMultipleLaunch |
python | scrapy__scrapy | tests/test_spidermiddleware_output_chain.py | {
"start": 2033,
"end": 2246
} | class ____(_BaseSpiderMiddleware):
def process_spider_input(self, response):
self.crawler.spider.logger.info("Middleware: will raise IndexError")
raise IndexError
| FailProcessSpiderInputMiddleware |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 10404,
"end": 10502
} | class ____(VyperException):
"""Invalid action for the active EVM ruleset."""
| EvmVersionException |
python | doocs__leetcode | solution/2100-2199/2114.Maximum Number of Words Found in Sentences/Solution.py | {
"start": 0,
"end": 131
} | class ____:
def mostWordsFound(self, sentences: List[str]) -> int:
return 1 + max(s.count(' ') for s in sentences)
| Solution |
python | sqlalchemy__sqlalchemy | test/sql/test_compiler.py | {
"start": 255882,
"end": 269839
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
def test_dont_overcorrelate(self):
self.assert_compile(
select(table1)
.select_from(table1)
.select_from(table1.select().subquery()),
"SELECT mytable.myid, mytable.name, "
"mytable.description FROM mytable, (SELECT "
"mytable.myid AS myid, mytable.name AS "
"name, mytable.description AS description "
"FROM mytable) AS anon_1",
)
def _fixture(self):
t1 = table("t1", column("a"))
t2 = table("t2", column("a"))
return t1, t2, select(t1).where(t1.c.a == t2.c.a)
def _assert_where_correlated(self, stmt):
self.assert_compile(
stmt,
"SELECT t2.a FROM t2 WHERE t2.a = "
"(SELECT t1.a FROM t1 WHERE t1.a = t2.a)",
)
def _assert_where_all_correlated(self, stmt):
self.assert_compile(
stmt,
"SELECT t1.a, t2.a AS a_1 FROM t1, t2 WHERE t2.a = "
"(SELECT t1.a WHERE t1.a = t2.a)",
)
# note there's no more "backwards" correlation after
# we've done #2746
# def _assert_where_backwards_correlated(self, stmt):
# self.assert_compile(
# stmt,
# "SELECT t2.a FROM t2 WHERE t2.a = "
# "(SELECT t1.a FROM t2 WHERE t1.a = t2.a)")
# def _assert_column_backwards_correlated(self, stmt):
# self.assert_compile(stmt,
# "SELECT t2.a, (SELECT t1.a FROM t2 WHERE t1.a = t2.a) "
# "AS anon_1 FROM t2")
def _assert_column_correlated(self, stmt):
self.assert_compile(
stmt,
"SELECT t2.a, (SELECT t1.a FROM t1 WHERE t1.a = t2.a) "
"AS anon_1 FROM t2",
)
def _assert_column_all_correlated(self, stmt):
self.assert_compile(
stmt,
"SELECT t1.a, t2.a AS a_1, "
"(SELECT t1.a WHERE t1.a = t2.a) AS anon_1 FROM t1, t2",
)
def _assert_having_correlated(self, stmt):
self.assert_compile(
stmt,
"SELECT t2.a FROM t2 HAVING t2.a = "
"(SELECT t1.a FROM t1 WHERE t1.a = t2.a)",
)
def _assert_from_uncorrelated(self, stmt):
self.assert_compile(
stmt,
"SELECT t2.a, anon_1.a AS a_1 FROM t2, "
"(SELECT t1.a AS a FROM t1, t2 WHERE t1.a = t2.a) AS anon_1",
)
def _assert_from_all_uncorrelated(self, stmt):
self.assert_compile(
stmt,
"SELECT t1.a, t2.a AS a_1, anon_1.a AS a_2 FROM t1, t2, "
"(SELECT t1.a AS a FROM t1, t2 WHERE t1.a = t2.a) AS anon_1",
)
def _assert_where_uncorrelated(self, stmt):
self.assert_compile(
stmt,
"SELECT t2.a FROM t2 WHERE t2.a = "
"(SELECT t1.a FROM t1, t2 WHERE t1.a = t2.a)",
)
def _assert_column_uncorrelated(self, stmt):
self.assert_compile(
stmt,
"SELECT t2.a, (SELECT t1.a FROM t1, t2 "
"WHERE t1.a = t2.a) AS anon_1 FROM t2",
)
def _assert_having_uncorrelated(self, stmt):
self.assert_compile(
stmt,
"SELECT t2.a FROM t2 HAVING t2.a = "
"(SELECT t1.a FROM t1, t2 WHERE t1.a = t2.a)",
)
def _assert_where_single_full_correlated(self, stmt):
self.assert_compile(
stmt, "SELECT t1.a FROM t1 WHERE t1.a = (SELECT t1.a)"
)
def test_correlate_semiauto_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_correlated(
select(t2).where(t2.c.a == s1.correlate(t2).scalar_subquery())
)
def test_correlate_semiauto_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_correlated(
select(t2, s1.correlate(t2).scalar_subquery())
)
def test_correlate_semiauto_column_correlate_from_subq(self):
t1, t2, s1 = self._fixture()
self._assert_column_correlated(
select(t2, s1.scalar_subquery().correlate(t2))
)
def test_correlate_semiauto_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(select(t2, s1.correlate(t2).alias()))
def test_correlate_semiauto_having(self):
t1, t2, s1 = self._fixture()
self._assert_having_correlated(
select(t2).having(t2.c.a == s1.correlate(t2).scalar_subquery())
)
def test_correlate_semiauto_having_from_subq(self):
t1, t2, s1 = self._fixture()
self._assert_having_correlated(
select(t2).having(t2.c.a == s1.scalar_subquery().correlate(t2))
)
def test_correlate_except_inclusion_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_correlated(
select(t2).where(
t2.c.a == s1.correlate_except(t1).scalar_subquery()
)
)
def test_correlate_except_exclusion_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_uncorrelated(
select(t2).where(
t2.c.a == s1.correlate_except(t2).scalar_subquery()
)
)
def test_correlate_except_inclusion_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_correlated(
select(t2, s1.correlate_except(t1).scalar_subquery())
)
def test_correlate_except_exclusion_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_uncorrelated(
select(t2, s1.correlate_except(t2).scalar_subquery())
)
def test_correlate_except_inclusion_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(
select(t2, s1.correlate_except(t1).alias())
)
def test_correlate_except_exclusion_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(
select(t2, s1.correlate_except(t2).alias())
)
@testing.combinations(False, None)
def test_correlate_except_none(self, value):
t1, t2, s1 = self._fixture()
self._assert_where_all_correlated(
select(t1, t2).where(
t2.c.a == s1.correlate_except(value).scalar_subquery()
)
)
def test_correlate_except_empty(self):
t1, t2, s1 = self._fixture()
self._assert_where_all_correlated(
select(t1, t2).where(
t2.c.a == s1.correlate_except().scalar_subquery()
)
)
def test_correlate_except_having(self):
t1, t2, s1 = self._fixture()
self._assert_having_correlated(
select(t2).having(
t2.c.a == s1.correlate_except(t1).scalar_subquery()
)
)
def test_correlate_auto_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_correlated(
select(t2).where(t2.c.a == s1.scalar_subquery())
)
def test_correlate_auto_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_correlated(select(t2, s1.scalar_subquery()))
def test_correlate_auto_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(select(t2, s1.alias()))
def test_correlate_auto_having(self):
t1, t2, s1 = self._fixture()
self._assert_having_correlated(
select(t2).having(t2.c.a == s1.scalar_subquery())
)
@testing.combinations(False, None)
def test_correlate_disabled_where(self, value):
t1, t2, s1 = self._fixture()
self._assert_where_uncorrelated(
select(t2).where(t2.c.a == s1.correlate(value).scalar_subquery())
)
def test_correlate_disabled_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_uncorrelated(
select(t2, s1.correlate(None).scalar_subquery())
)
def test_correlate_disabled_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(select(t2, s1.correlate(None).alias()))
def test_correlate_disabled_having(self):
t1, t2, s1 = self._fixture()
self._assert_having_uncorrelated(
select(t2).having(t2.c.a == s1.correlate(None).scalar_subquery())
)
def test_correlate_all_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_all_correlated(
select(t1, t2).where(
t2.c.a == s1.correlate(t1, t2).scalar_subquery()
)
)
def test_correlate_all_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_all_correlated(
select(t1, t2, s1.correlate(t1, t2).scalar_subquery())
)
def test_correlate_all_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_all_uncorrelated(
select(t1, t2, s1.correlate(t1, t2).alias())
)
def test_correlate_where_all_unintentional(self):
t1, t2, s1 = self._fixture()
assert_raises_message(
exc.InvalidRequestError,
"returned no FROM clauses due to auto-correlation",
select(t1, t2).where(t2.c.a == s1.scalar_subquery()).compile,
)
def test_correlate_from_all_ok(self):
t1, t2, s1 = self._fixture()
self.assert_compile(
select(t1, t2, s1.subquery()),
"SELECT t1.a, t2.a AS a_1, anon_1.a AS a_2 FROM t1, t2, "
"(SELECT t1.a AS a FROM t1, t2 WHERE t1.a = t2.a) AS anon_1",
)
def test_correlate_auto_where_singlefrom(self):
t1, t2, s1 = self._fixture()
s = select(t1.c.a)
s2 = select(t1).where(t1.c.a == s.scalar_subquery())
self.assert_compile(
s2, "SELECT t1.a FROM t1 WHERE t1.a = (SELECT t1.a FROM t1)"
)
def test_correlate_semiauto_where_singlefrom(self):
t1, t2, s1 = self._fixture()
s = select(t1.c.a)
s2 = select(t1).where(t1.c.a == s.correlate(t1).scalar_subquery())
self._assert_where_single_full_correlated(s2)
def test_correlate_except_semiauto_where_singlefrom(self):
t1, t2, s1 = self._fixture()
s = select(t1.c.a)
s2 = select(t1).where(
t1.c.a == s.correlate_except(t2).scalar_subquery()
)
self._assert_where_single_full_correlated(s2)
def test_correlate_alone_noeffect(self):
# new as of #2668
t1, t2, s1 = self._fixture()
self.assert_compile(
s1.correlate(t1, t2), "SELECT t1.a FROM t1, t2 WHERE t1.a = t2.a"
)
def test_correlate_except_froms(self):
# new as of #2748
t1 = table("t1", column("a"))
t2 = table("t2", column("a"), column("b"))
s = select(t2.c.b).where(t1.c.a == t2.c.a)
s = s.correlate_except(t2).alias("s")
s2 = select(func.foo(s.c.b)).scalar_subquery()
s3 = select(t1).order_by(s2)
self.assert_compile(
s3,
"SELECT t1.a FROM t1 ORDER BY "
"(SELECT foo(s.b) AS foo_1 FROM "
"(SELECT t2.b AS b FROM t2 WHERE t1.a = t2.a) AS s)",
)
def test_multilevel_froms_correlation(self):
# new as of #2748
p = table("parent", column("id"))
c = table("child", column("id"), column("parent_id"), column("pos"))
s = (
c.select()
.where(c.c.parent_id == p.c.id)
.order_by(c.c.pos)
.limit(1)
)
s = s.correlate(p).subquery()
s = exists().select_from(s).where(s.c.id == 1)
s = select(p).where(s)
self.assert_compile(
s,
"SELECT parent.id FROM parent WHERE EXISTS (SELECT * "
"FROM (SELECT child.id AS id, child.parent_id AS parent_id, "
"child.pos AS pos FROM child WHERE child.parent_id = parent.id "
"ORDER BY child.pos LIMIT :param_1) AS anon_1 "
"WHERE anon_1.id = :id_1)",
)
def test_no_contextless_correlate_except(self):
# new as of #2748
t1 = table("t1", column("x"))
t2 = table("t2", column("y"))
t3 = table("t3", column("z"))
s = (
select(t1)
.where(t1.c.x == t2.c.y)
.where(t2.c.y == t3.c.z)
.correlate_except(t1)
)
self.assert_compile(
s, "SELECT t1.x FROM t1, t2, t3 WHERE t1.x = t2.y AND t2.y = t3.z"
)
def test_multilevel_implicit_correlation_disabled(self):
# test that implicit correlation with multilevel WHERE correlation
# behaves like 0.8.1, 0.7 (i.e. doesn't happen)
t1 = table("t1", column("x"))
t2 = table("t2", column("y"))
t3 = table("t3", column("z"))
s = select(t1.c.x).where(t1.c.x == t2.c.y)
s2 = select(t3.c.z).where(t3.c.z == s.scalar_subquery())
s3 = select(t1).where(t1.c.x == s2.scalar_subquery())
self.assert_compile(
s3,
"SELECT t1.x FROM t1 "
"WHERE t1.x = (SELECT t3.z "
"FROM t3 "
"WHERE t3.z = (SELECT t1.x "
"FROM t1, t2 "
"WHERE t1.x = t2.y))",
)
def test_from_implicit_correlation_disabled(self):
# test that implicit correlation with immediate and
# multilevel FROM clauses behaves like 0.8.1 (i.e. doesn't happen)
t1 = table("t1", column("x"))
t2 = table("t2", column("y"))
s = select(t1.c.x).where(t1.c.x == t2.c.y)
s2 = select(t2, s.subquery())
s3 = select(t1, s2.subquery())
self.assert_compile(
s3,
"SELECT t1.x, anon_1.y, anon_1.x AS x_1 FROM t1, "
"(SELECT t2.y AS y, anon_2.x AS x FROM t2, "
"(SELECT t1.x AS x FROM t1, t2 WHERE t1.x = t2.y) "
"AS anon_2) AS anon_1",
)
| CorrelateTest |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/basic.py | {
"start": 5432,
"end": 6782
} | class ____(DefaultComponent):
type = "table"
def __init__(
self, title=None, subtitle=None, headers=[], data=[[]], vertical=False
):
super().__init__(title=title, subtitle=subtitle)
self._headers = []
self._data = [[]]
self._vertical = vertical
if self._validate_header_type(headers):
self._headers = headers
if self._validate_row_type(data):
self._data = data
@classmethod
def validate(cls, headers, data):
return (cls._validate_header_type(headers), cls._validate_row_type(data))
@staticmethod
def _validate_header_type(data):
if type(data) != list:
return False
return True
@staticmethod
def _validate_row_type(data):
if type(data) != list:
return False
try:
if type(data[0]) != list:
return False
except IndexError:
return False
except TypeError:
return False
return True
def render(self):
datadict = super().render()
datadict["columns"] = self._headers
datadict["data"] = self._data
datadict["vertical"] = self._vertical
if self.component_id is not None:
datadict["id"] = self.component_id
return datadict
| TableComponent |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py | {
"start": 255,
"end": 334
} | class ____(Generic[T]):
# Comments in a class body are preserved
var: T
| A |
python | plotly__plotly.py | plotly/graph_objs/sunburst/marker/_line.py | {
"start": 233,
"end": 4740
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sunburst.marker"
_path_str = "sunburst.marker.line"
_valid_props = {"color", "colorsrc", "width", "widthsrc"}
@property
def color(self):
"""
Sets the color of the line enclosing each sector. Defaults to
the `paper_bgcolor` value.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def width(self):
"""
Sets the width (in px) of the line enclosing each sector.
The 'width' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def widthsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `width`.
The 'widthsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["widthsrc"]
@widthsrc.setter
def widthsrc(self, val):
self["widthsrc"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the color of the line enclosing each sector.
Defaults to the `paper_bgcolor` value.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
width
Sets the width (in px) of the line enclosing each
sector.
widthsrc
Sets the source reference on Chart Studio Cloud for
`width`.
"""
def __init__(
self, arg=None, color=None, colorsrc=None, width=None, widthsrc=None, **kwargs
):
"""
Construct a new Line object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.sunburst.marker.Line`
color
Sets the color of the line enclosing each sector.
Defaults to the `paper_bgcolor` value.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
width
Sets the width (in px) of the line enclosing each
sector.
widthsrc
Sets the source reference on Chart Studio Cloud for
`width`.
Returns
-------
Line
"""
super().__init__("line")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.sunburst.marker.Line
constructor must be a dict or
an instance of :class:`plotly.graph_objs.sunburst.marker.Line`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("width", arg, width)
self._set_property("widthsrc", arg, widthsrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Line |
python | django__django | tests/admin_views/customadmin.py | {
"start": 1922,
"end": 2094
} | class ____(UserAdmin):
change_user_password_template = [
"admin/auth/user/change_password.html"
] # a list, to test fix for #18697
| CustomPwdTemplateUserAdmin |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py | {
"start": 3346,
"end": 4400
} | class ____(Issues, GeneratorMixin):
"""
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issues/#api-rest-api-3-issue-post
"""
def path(self, **kwargs) -> str:
return "issue"
def generate(self):
projects = ["EX", "IT", "P2", "TESTKEY1"]
issue_types = ["10001", "10002", "10004"]
for index in range(1, 76):
payload = json.dumps(
{
"fields": {
"project": {"key": random.choice(projects)},
"issuetype": {"id": random.choice(issue_types)},
"summary": f"Test {index}",
"description": {
"type": "doc",
"version": 1,
"content": [{"type": "paragraph", "content": [{"type": "text", "text": f"Test description {index}"}]}],
},
}
}
)
self.generate_record(payload)
| IssuesGenerator |
python | ansible__ansible | test/units/playbook/test_base.py | {
"start": 8925,
"end": 8992
} | class ____(Exception):
pass
# naming fails me...
| ExampleException |
python | openai__openai-python | src/openai/resources/chat/completions/messages.py | {
"start": 7116,
"end": 7335
} | class ____:
def __init__(self, messages: Messages) -> None:
self._messages = messages
self.list = _legacy_response.to_raw_response_wrapper(
messages.list,
)
| MessagesWithRawResponse |
python | has2k1__plotnine | plotnine/_utils/context.py | {
"start": 890,
"end": 2389
} | class ____:
"""
Context within which the plot is built
Parameters
----------
plot :
ggplot object to be built within the context.
show :
Whether to show the plot.
"""
def __init__(self, plot: ggplot, show: bool = False):
import matplotlib as mpl
self.plot = plot
self.show = show
# Contexts
self.rc_context = mpl.rc_context(plot.theme.rcParams)
# TODO: Remove this context when copy-on-write is permanent, i.e.
# pandas >= 3.0
self.pd_option_context = pd.option_context(
"mode.copy_on_write",
True,
)
def __enter__(self) -> Self:
"""
Enclose in matplolib & pandas environments
"""
self.rc_context.__enter__()
self.pd_option_context.__enter__()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
"""
Exit matplotlib & pandas environments
"""
import matplotlib.pyplot as plt
if exc_type is None:
if self.show:
plt.show()
else:
plt.close(self.plot.figure)
else:
# There is an exception, close any figure
if hasattr(self.plot, "figure"):
plt.close(self.plot.figure)
self.rc_context.__exit__(exc_type, exc_value, exc_traceback)
self.pd_option_context.__exit__(exc_type, exc_value, exc_traceback)
@dataclass
| plot_context |
python | PrefectHQ__prefect | src/prefect/client/schemas/sorting.py | {
"start": 1042,
"end": 1182
} | class ____(AutoEnum):
"""Defines log sorting options."""
TIMESTAMP_ASC = AutoEnum.auto()
TIMESTAMP_DESC = AutoEnum.auto()
| LogSort |
python | walkccc__LeetCode | solutions/2737. Find the Closest Marked Node/2737.py | {
"start": 0,
"end": 801
} | class ____:
def minimumDistance(
self,
n: int,
edges: list[list[int]],
s: int,
marked: list[int],
) -> int:
graph = [[] for _ in range(n)]
for u, v, w in edges:
graph[u].append((v, w))
dist = self._dijkstra(graph, s)
ans = min(dist[u] for u in marked)
return -1 if ans == math.inf else ans
def _dijkstra(
self,
graph: list[list[tuple[int, int]]],
src: int,
) -> list[int]:
dist = [math.inf] * len(graph)
dist[src] = 0
minHeap = [(dist[src], src)] # (d, u)
while minHeap:
d, u = heapq.heappop(minHeap)
if d > dist[u]:
continue
for v, w in graph[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(minHeap, (dist[v], v))
return dist
| Solution |
python | huggingface__transformers | src/transformers/models/phi/configuration_phi.py | {
"start": 874,
"end": 8257
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
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 Phi
[microsoft/phi-1](https://huggingface.co/microsoft/phi-1).
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 51200):
Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`PhiModel`].
hidden_size (`int`, *optional*, defaults to 2048):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 8192):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 24):
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`.
resid_pdrop (`float`, *optional*, defaults to 0.0):
Dropout probability for mlp outputs.
embd_pdrop (`int`, *optional*, defaults to 0.0):
The dropout ratio for the embeddings.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio after computing the attention scores.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
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. Phi-1 and Phi-1.5 supports up to 2048
tokens.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the rms normalization layers.
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`. Whether to tie weight embeddings or not.
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`.
qk_layernorm (`bool`, *optional*, defaults to `False`):
Whether or not to normalize the Queries and Keys after projecting the hidden states.
bos_token_id (`int`, *optional*, defaults to 1):
Denotes beginning of sequences token id.
eos_token_id (`int`, *optional*, defaults to 2):
Denotes end of sequences token id.
Example:
```python
>>> from transformers import PhiModel, PhiConfig
>>> # Initializing a Phi-1 style configuration
>>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
>>> # Initializing a model from the configuration
>>> model = PhiModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "phi"
keys_to_ignore_at_inference = ["past_key_values"]
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.dense": "rowwise",
"layers.*.mlp.fc1": "colwise",
"layers.*.mlp.fc2": "rowwise",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"embed_dropout": (["inputs_embeds"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"final_layernorm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
vocab_size: Optional[int] = 51200,
hidden_size: Optional[int] = 2048,
intermediate_size: Optional[int] = 8192,
num_hidden_layers: Optional[int] = 24,
num_attention_heads: Optional[int] = 32,
num_key_value_heads: Optional[int] = None,
resid_pdrop: Optional[float] = 0.0,
embd_pdrop: Optional[float] = 0.0,
attention_dropout: Optional[float] = 0.0,
hidden_act: Optional[str] = "gelu_new",
max_position_embeddings: Optional[int] = 2048,
initializer_range: Optional[float] = 0.02,
layer_norm_eps: Optional[int] = 1e-5,
use_cache: Optional[bool] = True,
tie_word_embeddings: Optional[bool] = False,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
qk_layernorm: Optional[bool] = False,
bos_token_id: Optional[int] = 1,
eos_token_id: Optional[int] = 2,
**kwargs,
):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.resid_pdrop = resid_pdrop
self.embd_pdrop = embd_pdrop
self.attention_dropout = attention_dropout
self.hidden_act = hidden_act
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.use_cache = use_cache
self.qk_layernorm = qk_layernorm
self.rope_parameters = rope_parameters
kwargs.setdefault("partial_rotary_factor", 0.5) # assign default for BC
super().__init__(
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
__all__ = ["PhiConfig"]
| PhiConfig |
python | protocolbuffers__protobuf | python/google/protobuf/internal/text_format_test.py | {
"start": 111120,
"end": 112676
} | class ____(TextFormatBase):
def setUp(self):
self.out = text_format.TextWriter(False)
self.addCleanup(self.out.close)
self.message = unittest_pb2.NestedTestAllTypes()
self.message.child.payload.optional_string = 'value'
self.field = self.message.DESCRIPTOR.fields_by_name['child']
self.value = self.message.child
def testMessageToString(self):
self.CompareToGoldenText(
text_format.MessageToString(self.message),
textwrap.dedent("""\
child {
payload {
optional_string: "value"
}
}
"""))
def testPrintMessage(self):
text_format.PrintMessage(self.message, self.out)
self.CompareToGoldenText(
self.out.getvalue(),
textwrap.dedent("""\
child {
payload {
optional_string: "value"
}
}
"""))
def testPrintField(self):
text_format.PrintField(self.field, self.value, self.out)
self.CompareToGoldenText(
self.out.getvalue(),
textwrap.dedent("""\
child {
payload {
optional_string: "value"
}
}
"""))
def testPrintFieldValue(self):
text_format.PrintFieldValue(
self.field, self.value, self.out)
self.CompareToGoldenText(
self.out.getvalue(),
textwrap.dedent("""\
{
payload {
optional_string: "value"
}
}"""))
| WhitespaceTest |
python | pandas-dev__pandas | pandas/tests/indexes/interval/test_interval_range.py | {
"start": 430,
"end": 14507
} | class ____:
@pytest.mark.parametrize("freq, periods", [(1, 100), (2.5, 40), (5, 20), (25, 4)])
def test_constructor_numeric(self, closed, name, freq, periods):
start, end = 0, 100
breaks = np.arange(101, step=freq)
expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
# defined from start/end/freq
result = interval_range(
start=start, end=end, freq=freq, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
# defined from start/periods/freq
result = interval_range(
start=start, periods=periods, freq=freq, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
# defined from end/periods/freq
result = interval_range(
end=end, periods=periods, freq=freq, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
# GH 20976: linspace behavior defined from start/end/periods
result = interval_range(
start=start, end=end, periods=periods, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("tz", [None, "US/Eastern"])
@pytest.mark.parametrize(
"freq, periods", [("D", 364), ("2D", 182), ("22D18h", 16), ("ME", 11)]
)
def test_constructor_timestamp(self, closed, name, freq, periods, tz):
start, end = Timestamp("20180101", tz=tz), Timestamp("20181231", tz=tz)
breaks = date_range(start=start, end=end, freq=freq)
expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
# defined from start/end/freq
result = interval_range(
start=start, end=end, freq=freq, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
# defined from start/periods/freq
result = interval_range(
start=start, periods=periods, freq=freq, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
# defined from end/periods/freq
result = interval_range(
end=end, periods=periods, freq=freq, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
# GH 20976: linspace behavior defined from start/end/periods
if not breaks.freq.n == 1 and tz is None:
result = interval_range(
start=start, end=end, periods=periods, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
"freq, periods", [("D", 100), ("2D12h", 40), ("5D", 20), ("25D", 4)]
)
def test_constructor_timedelta(self, closed, name, freq, periods):
start, end = Timedelta("0 days"), Timedelta("100 days")
breaks = timedelta_range(start=start, end=end, freq=freq)
expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed)
# defined from start/end/freq
result = interval_range(
start=start, end=end, freq=freq, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
# defined from start/periods/freq
result = interval_range(
start=start, periods=periods, freq=freq, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
# defined from end/periods/freq
result = interval_range(
end=end, periods=periods, freq=freq, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
# GH 20976: linspace behavior defined from start/end/periods
result = interval_range(
start=start, end=end, periods=periods, name=name, closed=closed
)
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
"start, end, freq, expected_endpoint",
[
(0, 10, 3, 9),
(0, 10, 1.5, 9),
(0.5, 10, 3, 9.5),
(Timedelta("0D"), Timedelta("10D"), "2D4h", Timedelta("8D16h")),
(
Timestamp("2018-01-01"),
Timestamp("2018-02-09"),
"MS",
Timestamp("2018-02-01"),
),
(
Timestamp("2018-01-01", tz="US/Eastern"),
Timestamp("2018-01-20", tz="US/Eastern"),
"5D12h",
Timestamp("2018-01-17 12:00:00", tz="US/Eastern"),
),
],
)
def test_early_truncation(self, start, end, freq, expected_endpoint):
# index truncates early if freq causes end to be skipped
result = interval_range(start=start, end=end, freq=freq)
result_endpoint = result.right[-1]
assert result_endpoint == expected_endpoint
@pytest.mark.parametrize(
"start, end, freq",
[(0.5, None, None), (None, 4.5, None), (0.5, None, 1.5), (None, 6.5, 1.5)],
)
def test_no_invalid_float_truncation(self, start, end, freq):
# GH 21161
if freq is None:
breaks = [0.5, 1.5, 2.5, 3.5, 4.5]
else:
breaks = [0.5, 2.0, 3.5, 5.0, 6.5]
expected = IntervalIndex.from_breaks(breaks)
result = interval_range(start=start, end=end, periods=4, freq=freq)
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
"start, mid, end",
[
(
Timestamp("2018-03-10", tz="US/Eastern"),
Timestamp("2018-03-10 23:30:00", tz="US/Eastern"),
Timestamp("2018-03-12", tz="US/Eastern"),
),
(
Timestamp("2018-11-03", tz="US/Eastern"),
Timestamp("2018-11-04 00:30:00", tz="US/Eastern"),
Timestamp("2018-11-05", tz="US/Eastern"),
),
],
)
def test_linspace_dst_transition(self, start, mid, end):
# GH 20976: linspace behavior defined from start/end/periods
# accounts for the hour gained/lost during DST transition
start = start.as_unit("ns")
mid = mid.as_unit("ns")
end = end.as_unit("ns")
result = interval_range(start=start, end=end, periods=2)
expected = IntervalIndex.from_breaks([start, mid, end])
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize("freq", [2, 2.0])
@pytest.mark.parametrize("end", [10, 10.0])
@pytest.mark.parametrize("start", [0, 0.0])
def test_float_subtype(self, start, end, freq):
# Has float subtype if any of start/end/freq are float, even if all
# resulting endpoints can safely be upcast to integers
# defined from start/end/freq
index = interval_range(start=start, end=end, freq=freq)
result = index.dtype.subtype
expected = "int64" if is_integer(start + end + freq) else "float64"
assert result == expected
# defined from start/periods/freq
index = interval_range(start=start, periods=5, freq=freq)
result = index.dtype.subtype
expected = "int64" if is_integer(start + freq) else "float64"
assert result == expected
# defined from end/periods/freq
index = interval_range(end=end, periods=5, freq=freq)
result = index.dtype.subtype
expected = "int64" if is_integer(end + freq) else "float64"
assert result == expected
# GH 20976: linspace behavior defined from start/end/periods
index = interval_range(start=start, end=end, periods=5)
result = index.dtype.subtype
expected = "int64" if is_integer(start + end) else "float64"
assert result == expected
@pytest.mark.parametrize(
"start, end, expected",
[
(np.int8(1), np.int8(10), np.dtype("int8")),
(np.int8(1), np.float16(10), np.dtype("float64")),
(np.float32(1), np.float32(10), np.dtype("float32")),
(1, 10, np.dtype("int64")),
(1, 10.0, np.dtype("float64")),
],
)
def test_interval_dtype(self, start, end, expected):
result = interval_range(start=start, end=end).dtype.subtype
assert result == expected
def test_interval_range_fractional_period(self):
# float value for periods
msg = "periods must be an integer, got 10.5"
ts = Timestamp("2024-03-25")
with pytest.raises(TypeError, match=msg):
interval_range(ts, periods=10.5)
def test_constructor_coverage(self):
# equivalent timestamp-like start/end
start, end = Timestamp("2017-01-01"), Timestamp("2017-01-15")
expected = interval_range(start=start, end=end)
result = interval_range(start=start.to_pydatetime(), end=end.to_pydatetime())
tm.assert_index_equal(result, expected)
result = interval_range(start=start.asm8, end=end.asm8)
tm.assert_index_equal(result, expected)
# equivalent freq with timestamp
equiv_freq = [
"D",
Day(),
Timedelta(days=1),
timedelta(days=1),
DateOffset(days=1),
]
for freq in equiv_freq:
result = interval_range(start=start, end=end, freq=freq)
tm.assert_index_equal(result, expected)
# equivalent timedelta-like start/end
start, end = Timedelta(days=1).as_unit("us"), Timedelta(days=10).as_unit("us")
expected = interval_range(start=start, end=end)
result = interval_range(start=start.to_pytimedelta(), end=end.to_pytimedelta())
tm.assert_index_equal(result, expected)
result = interval_range(start=start.asm8, end=end.asm8)
tm.assert_index_equal(result, expected)
# equivalent freq with timedelta
equiv_freq = ["D", Day(), Timedelta(days=1), timedelta(days=1)]
for freq in equiv_freq:
result = interval_range(start=start, end=end, freq=freq)
tm.assert_index_equal(result, expected)
def test_errors(self):
# not enough params
msg = (
"Of the four parameters: start, end, periods, and freq, "
"exactly three must be specified"
)
with pytest.raises(ValueError, match=msg):
interval_range(start=0)
with pytest.raises(ValueError, match=msg):
interval_range(end=5)
with pytest.raises(ValueError, match=msg):
interval_range(periods=2)
with pytest.raises(ValueError, match=msg):
interval_range()
# too many params
with pytest.raises(ValueError, match=msg):
interval_range(start=0, end=5, periods=6, freq=1.5)
# mixed units
msg = "start, end, freq need to be type compatible"
with pytest.raises(TypeError, match=msg):
interval_range(start=0, end=Timestamp("20130101"), freq=2)
with pytest.raises(TypeError, match=msg):
interval_range(start=0, end=Timedelta("1 day"), freq=2)
with pytest.raises(TypeError, match=msg):
interval_range(start=0, end=10, freq="D")
with pytest.raises(TypeError, match=msg):
interval_range(start=Timestamp("20130101"), end=10, freq="D")
with pytest.raises(TypeError, match=msg):
interval_range(
start=Timestamp("20130101"), end=Timedelta("1 day"), freq="D"
)
with pytest.raises(TypeError, match=msg):
interval_range(
start=Timestamp("20130101"), end=Timestamp("20130110"), freq=2
)
with pytest.raises(TypeError, match=msg):
interval_range(start=Timedelta("1 day"), end=10, freq="D")
with pytest.raises(TypeError, match=msg):
interval_range(
start=Timedelta("1 day"), end=Timestamp("20130110"), freq="D"
)
with pytest.raises(TypeError, match=msg):
interval_range(start=Timedelta("1 day"), end=Timedelta("10 days"), freq=2)
# invalid periods
msg = "periods must be an integer, got foo"
with pytest.raises(TypeError, match=msg):
interval_range(start=0, periods="foo")
# invalid start
msg = "start must be numeric or datetime-like, got foo"
with pytest.raises(ValueError, match=msg):
interval_range(start="foo", periods=10)
# invalid end
msg = r"end must be numeric or datetime-like, got \(0, 1\]"
with pytest.raises(ValueError, match=msg):
interval_range(end=Interval(0, 1), periods=10)
# invalid freq for datetime-like
msg = "freq must be numeric or convertible to DateOffset, got foo"
with pytest.raises(ValueError, match=msg):
interval_range(start=0, end=10, freq="foo")
with pytest.raises(ValueError, match=msg):
interval_range(start=Timestamp("20130101"), periods=10, freq="foo")
with pytest.raises(ValueError, match=msg):
interval_range(end=Timedelta("1 day"), periods=10, freq="foo")
# mixed tz
start = Timestamp("2017-01-01", tz="US/Eastern")
end = Timestamp("2017-01-07", tz="US/Pacific")
msg = "Start and end cannot both be tz-aware with different timezones"
with pytest.raises(TypeError, match=msg):
interval_range(start=start, end=end)
def test_float_freq(self):
# GH 54477
result = interval_range(0, 1, freq=0.1)
expected = IntervalIndex.from_breaks([0 + 0.1 * n for n in range(11)])
tm.assert_index_equal(result, expected)
result = interval_range(0, 1, freq=0.6)
expected = IntervalIndex.from_breaks([0, 0.6])
tm.assert_index_equal(result, expected)
def test_interval_range_float32_start_int_freq(self):
# GH 58964
result = interval_range(start=np.float32(0), end=2, freq=1)
expected = IntervalIndex.from_tuples(
[(0.0, 1.0), (1.0, 2.0)], dtype="interval[float64, right]"
)
tm.assert_index_equal(result, expected)
| TestIntervalRange |
python | ApeWorX__ape | src/ape/api/compiler.py | {
"start": 826,
"end": 10605
} | class ____(BaseInterfaceModel):
"""
Compiler plugins, such as for languages like
`Solidity <https://docs.soliditylang.org/en/v0.8.11/>`__ or
`Vyper <https://vyper.readthedocs.io/en/stable/>`__, implement this API.
See the repository for the `ape-solidity <https://github.com/ApeWorX/ape-solidity>`__ plugin or
the `ape-vyper <https://github.com/ApeWorX/ape-vyper>`__ plugin as example implementations of
this API.
"""
compiler_settings: dict = {}
"""
Adhoc compiler settings.
"""
@property
@abstractmethod
def name(self) -> str:
"""
The name of the compiler.
"""
def get_config(self, project: Optional["ProjectManager"] = None) -> "PluginConfig":
"""
The combination of settings from ``ape-config.yaml`` and ``.compiler_settings``.
Args:
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
Returns:
:class:`~ape.api.config.PluginConfig`
"""
pm = project or self.local_project
config = pm.config.get_config(self.name)
data = {**config.model_dump(mode="json", by_alias=True), **self.compiler_settings}
return config.model_validate(data)
@raises_not_implemented
def get_versions(self, all_paths: Iterable[Path]) -> set[str]: # type: ignore[empty-body]
"""
Retrieve the set of available compiler versions for this plugin to compile ``all_paths``.
Args:
all_paths (Iterable[pathlib.Path]): The list of paths.
Returns:
set[str]: A set of available compiler versions.
"""
@raises_not_implemented
def get_compiler_settings( # type: ignore[empty-body]
self,
contract_filepaths: Iterable[Path],
project: Optional["ProjectManager"] = None,
**overrides,
) -> dict["Version", dict]:
"""
Get a mapping of the settings that would be used to compile each of the sources
by the compiler version number.
Args:
contract_filepaths (Iterable[pathlib.Path]): The list of paths.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
**overrides: Settings overrides.
Returns:
dict[Version, dict]: A dict of compiler settings by compiler version.
"""
@abstractmethod
def compile(
self,
contract_filepaths: Iterable[Path],
project: Optional["ProjectManager"],
settings: Optional[dict] = None,
) -> Iterator["ContractType"]:
"""
Compile the given source files. All compiler plugins must implement this function.
Args:
contract_filepaths (Iterable[pathlib.Path]): A list of source file paths to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
settings (Optional[dict]): Adhoc compiler settings.
Returns:
list[:class:`~ape.type.contract.ContractType`]
"""
@raises_not_implemented
def compile_code( # type: ignore[empty-body]
self,
code: str,
project: Optional["ProjectManager"],
settings: Optional[dict] = None,
**kwargs,
) -> "ContractType":
"""
Compile a program.
Args:
code (str): The code to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
settings (Optional[Dict]): Adhoc compiler settings.
**kwargs: Additional overrides for the ``ethpm_types.ContractType`` model.
Returns:
``ContractType``: A compiled contract artifact.
"""
@raises_not_implemented
def get_imports( # type: ignore[empty-body]
self, contract_filepaths: Iterable[Path], project: Optional["ProjectManager"]
) -> dict[str, list[str]]:
"""
Returns a list of imports as source_ids for each contract's source_id in a given
compiler.
Args:
contract_filepaths (Iterable[pathlib.Path]): A list of source file paths to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
Returns:
dict[str, list[str]]: A dictionary like ``{source_id: [import_source_id, ...], ...}``
"""
@raises_not_implemented
def get_version_map( # type: ignore[empty-body]
self,
contract_filepaths: Iterable[Path],
project: Optional["ProjectManager"] = None,
) -> dict["Version", set[Path]]:
"""
Get a map of versions to source paths.
Args:
contract_filepaths (Iterable[Path]): Input source paths. Defaults to all source paths
per compiler.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
Returns:
dict[Version, set[Path]]
"""
@log_instead_of_fail(default="<CompilerAPI>")
def __repr__(self) -> str:
cls_name = getattr(type(self), "__name__", CompilerAPI.__name__)
return f"<{cls_name} {self.name}>"
def __str__(self) -> str:
return self.name
@cached_property
def supports_source_tracing(self) -> bool:
"""
Returns ``True`` if this compiler is able to provider a source
traceback for a given trace.
"""
try:
self.trace_source(None, None, None) # type: ignore
except APINotImplementedError:
return False
except Exception:
# Task failed successfully.
return True
return True
def enrich_error(self, err: ContractLogicError) -> ContractLogicError:
"""
Enrich a contract logic error using compiler information, such as
known PC locations for compiler runtime errors.
Args:
err (:class:`~ape.exceptions.ContractLogicError`): The exception
to enrich.
Returns:
:class:`~ape.exceptions.ContractLogicError`: The enriched exception.
"""
return err
@raises_not_implemented
def trace_source( # type: ignore[empty-body]
self, contract_source: "ContractSource", trace: "TraceAPI", calldata: "HexBytes"
) -> "SourceTraceback":
"""
Get a source-traceback for the given contract type.
The source traceback object contains all the control paths taken in the transaction.
When available, source-code location information is accessible from the object.
Args:
contract_source (``ContractSource``): A contract type with a local-source that was
compiled by this compiler.
trace (:class:`~ape.api.trace.TraceAPI`]): The resulting trace from executing a
function defined in the given contract type.
calldata (``HexBytes``): Calldata passed to the top-level call.
Returns:
:class:`~ape.types.trace.SourceTraceback`
"""
@raises_not_implemented
def flatten_contract( # type: ignore[empty-body]
self, path: Path, project: Optional["ProjectManager"] = None, **kwargs
) -> "Content":
"""
Get the content of a flattened contract via its source path.
Plugin implementations handle import resolution, SPDX de-duplication,
and anything else needed.
Args:
path (``pathlib.Path``): The source path of the contract.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project containing the base paths and full source set. Defaults to the local
project. Dependencies will change this value to their respective projects.
**kwargs (Any): Additional compiler-specific settings. See specific
compiler plugins when applicable.
Returns:
``ethpm_types.source.Content``: The flattened contract content.
"""
@raises_not_implemented
def init_coverage_profile(
self, source_coverage: "ContractSourceCoverage", contract_source: "ContractSource"
): # type: ignore[empty-body]
"""
Initialize an empty report for the given source ID. Modifies the given source
coverage in-place.
Args:
source_coverage (:class:`~ape.types.coverage.SourceCoverage`): The source
to generate an empty coverage profile for.
contract_source (``ethpm_types.source.ContractSource``): The contract with
source content.
"""
| CompilerAPI |
python | wandb__wandb | landfill/functional_tests/lightning_fabric/pl_base.py | {
"start": 3237,
"end": 3918
} | class ____(Dataset):
def __init__(self, num_samples, root_folder):
self.num_samples = num_samples
self.data = torch.randn(num_samples, 3, 32, 32)
self.targets = torch.randint(0, 10, (num_samples,))
self.root_folder = root_folder
def __getitem__(self, index):
img, target = self.data[index], int(self.targets[index])
return img, target
def __len__(self):
return self.num_samples
def save(self):
os.makedirs(self.root_folder, exist_ok=True)
torch.save(self.data, os.path.join(self.root_folder, "data.pt"))
torch.save(self.targets, os.path.join(self.root_folder, "targets.pt"))
| FakeCIFAR10 |
python | ray-project__ray | rllib/core/models/configs.py | {
"start": 42807,
"end": 44201
} | class ____(ModelConfig):
"""Configuration for an ActorCriticEncoder.
The base encoder functions like other encoders in RLlib. It is wrapped by the
ActorCriticEncoder to provides a shared encoder Model to use in RLModules that
provides twofold outputs: one for the actor and one for the critic. See
ModelConfig for usage details.
Attributes:
base_encoder_config: The configuration for the wrapped encoder(s).
shared: Whether the base encoder is shared between the actor and critic.
inference_only: Whether the configured encoder will only ever be used as an
actor-encoder, never as a value-function encoder. Thus, if True and `shared`
is False, will only build the actor-related components.
"""
base_encoder_config: ModelConfig = None
shared: bool = True
inference_only: bool = False
@_framework_implemented()
def build(self, framework: str = "torch") -> "Encoder":
if framework == "torch":
from ray.rllib.core.models.torch.encoder import (
TorchActorCriticEncoder,
TorchStatefulActorCriticEncoder,
)
if isinstance(self.base_encoder_config, RecurrentEncoderConfig):
return TorchStatefulActorCriticEncoder(self)
else:
return TorchActorCriticEncoder(self)
| ActorCriticEncoderConfig |
python | numpy__numpy | numpy/typing/tests/data/pass/ufunclike.py | {
"start": 81,
"end": 1351
} | class ____:
def __ceil__(self) -> Object:
return self
def __floor__(self) -> Object:
return self
def __trunc__(self) -> Object:
return self
def __ge__(self, value: object) -> bool:
return True
def __array__(self, dtype: np.typing.DTypeLike | None = None,
copy: bool | None = None) -> np.ndarray[Any, np.dtype[np.object_]]:
ret = np.empty((), dtype=object)
ret[()] = self
return ret
AR_LIKE_b = [True, True, False]
AR_LIKE_u = [np.uint32(1), np.uint32(2), np.uint32(3)]
AR_LIKE_i = [1, 2, 3]
AR_LIKE_f = [1.0, 2.0, 3.0]
AR_LIKE_O = [Object(), Object(), Object()]
AR_U: np.ndarray[Any, np.dtype[np.str_]] = np.zeros(3, dtype="U5")
np.fix(AR_LIKE_b) # type: ignore[deprecated]
np.fix(AR_LIKE_u) # type: ignore[deprecated]
np.fix(AR_LIKE_i) # type: ignore[deprecated]
np.fix(AR_LIKE_f) # type: ignore[deprecated]
np.fix(AR_LIKE_O) # type: ignore[deprecated]
np.fix(AR_LIKE_f, out=AR_U) # type: ignore[deprecated]
np.isposinf(AR_LIKE_b)
np.isposinf(AR_LIKE_u)
np.isposinf(AR_LIKE_i)
np.isposinf(AR_LIKE_f)
np.isposinf(AR_LIKE_f, out=AR_U)
np.isneginf(AR_LIKE_b)
np.isneginf(AR_LIKE_u)
np.isneginf(AR_LIKE_i)
np.isneginf(AR_LIKE_f)
np.isneginf(AR_LIKE_f, out=AR_U)
| Object |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table08.py | {
"start": 315,
"end": 1522
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table08.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels",
]
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.set_column("C:F", 10.288)
worksheet.write_string("A1", "Column1")
worksheet.write_string("B1", "Column2")
worksheet.write_string("C1", "Column3")
worksheet.write_string("D1", "Column4")
worksheet.write_string("E1", "Total")
worksheet.add_table(
"C3:F14",
{
"total_row": 1,
"columns": [
{"total_string": "Total"},
{},
{},
{"total_function": "count"},
],
},
)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 66856,
"end": 76760
} | class ____(roles.InElementRole, KeyedColumnElement[_T]):
r"""Represent a "bound expression".
:class:`.BindParameter` is invoked explicitly using the
:func:`.bindparam` function, as in::
from sqlalchemy import bindparam
stmt = select(users_table).where(
users_table.c.name == bindparam("username")
)
Detailed discussion of how :class:`.BindParameter` is used is
at :func:`.bindparam`.
.. seealso::
:func:`.bindparam`
"""
__visit_name__ = "bindparam"
_traverse_internals: _TraverseInternalsType = [
("key", InternalTraversal.dp_anon_name),
("type", InternalTraversal.dp_type),
("callable", InternalTraversal.dp_plain_dict),
("value", InternalTraversal.dp_plain_obj),
("literal_execute", InternalTraversal.dp_boolean),
]
key: str
_anon_map_key: Optional[str] = None
type: TypeEngine[_T]
value: Optional[_T]
_is_crud = False
_is_bind_parameter = True
# bindparam implements its own _gen_cache_key() method however
# we check subclasses for this flag, else no cache key is generated
inherit_cache = True
def __init__(
self,
key: Optional[str],
value: Any = _NoArg.NO_ARG,
type_: Optional[_TypeEngineArgument[_T]] = None,
unique: bool = False,
required: Union[bool, Literal[_NoArg.NO_ARG]] = _NoArg.NO_ARG,
quote: Optional[bool] = None,
callable_: Optional[Callable[[], Any]] = None,
expanding: bool = False,
isoutparam: bool = False,
literal_execute: bool = False,
_compared_to_operator: Optional[OperatorType] = None,
_compared_to_type: Optional[TypeEngine[Any]] = None,
_is_crud: bool = False,
):
if required is _NoArg.NO_ARG:
required = value is _NoArg.NO_ARG and callable_ is None
if value is _NoArg.NO_ARG:
value = None
if quote is not None:
key = quoted_name.construct(key, quote)
if unique:
self.key, self._anon_map_key = (
_anonymous_label.safe_construct_with_key(
id(self),
(
key
if key is not None
and not isinstance(key, _anonymous_label)
else "param"
),
sanitize_key=True,
)
)
elif key:
self.key = key
else:
self.key, self._anon_map_key = (
_anonymous_label.safe_construct_with_key(id(self), "param")
)
# identifying key that won't change across
# clones, used to identify the bind's logical
# identity
self._identifying_key = self.key
# key that was passed in the first place, used to
# generate new keys
self._orig_key = key or "param"
self.unique = unique
self.value = value
self.callable = callable_
self.isoutparam = isoutparam
self.required = required
# indicate an "expanding" parameter; the compiler sets this
# automatically in the compiler _render_in_expr_w_bindparam method
# for an IN expression
self.expanding = expanding
# this is another hint to help w/ expanding and is typically
# set in the compiler _render_in_expr_w_bindparam method for an
# IN expression
self.expand_op = None
self.literal_execute = literal_execute
if _is_crud:
self._is_crud = True
if type_ is None:
if expanding:
if value:
check_value = value[0]
else:
check_value = type_api._NO_VALUE_IN_LIST
else:
check_value = value
if _compared_to_type is not None:
self.type = _compared_to_type.coerce_compared_value(
_compared_to_operator, check_value
)
else:
self.type = type_api._resolve_value_to_type(check_value)
elif isinstance(type_, type):
self.type = type_()
elif is_tuple_type(type_):
if value:
if expanding:
check_value = value[0]
else:
check_value = value
cast("BindParameter[TupleAny]", self).type = (
type_._resolve_values_to_types(check_value)
)
else:
cast("BindParameter[TupleAny]", self).type = type_
else:
self.type = type_
def _with_value(self, value, maintain_key=False, required=NO_ARG):
"""Return a copy of this :class:`.BindParameter` with the given value
set.
"""
cloned = self._clone(maintain_key=maintain_key)
cloned.value = value
cloned.callable = None
cloned.required = required if required is not NO_ARG else self.required
if cloned.type is type_api.NULLTYPE:
cloned.type = type_api._resolve_value_to_type(value)
return cloned
@property
def effective_value(self) -> Optional[_T]:
"""Return the value of this bound parameter,
taking into account if the ``callable`` parameter
was set.
The ``callable`` value will be evaluated
and returned if present, else ``value``.
"""
if self.callable:
# TODO: set up protocol for bind parameter callable
return self.callable() # type: ignore
else:
return self.value
def render_literal_execute(self) -> Self:
"""Produce a copy of this bound parameter that will enable the
:paramref:`_sql.BindParameter.literal_execute` flag.
The :paramref:`_sql.BindParameter.literal_execute` flag will
have the effect of the parameter rendered in the compiled SQL
string using ``[POSTCOMPILE]`` form, which is a special form that
is converted to be a rendering of the literal value of the parameter
at SQL execution time. The rationale is to support caching
of SQL statement strings that can embed per-statement literal values,
such as LIMIT and OFFSET parameters, in the final SQL string that
is passed to the DBAPI. Dialects in particular may want to use
this method within custom compilation schemes.
.. versionadded:: 1.4.5
.. seealso::
:ref:`engine_thirdparty_caching`
"""
c: Self = ClauseElement._clone(self)
c.literal_execute = True
return c
def _negate_in_binary(self, negated_op, original_op):
if self.expand_op is original_op:
bind = self._clone()
bind.expand_op = negated_op
return bind
else:
return self
def _with_binary_element_type(self, type_: TypeEngine[Any]) -> Self:
c: Self = ClauseElement._clone(self)
c.type = type_
return c
def _clone(self, maintain_key: bool = False, **kw: Any) -> Self:
c: Self = ClauseElement._clone(self, **kw)
# ensure all the BindParameter objects stay in cloned set.
# in #7823, we changed "clone" so that a clone only keeps a reference
# to the "original" element, since for column correspondence, that's
# all we need. However, for BindParam, _cloned_set is used by
# the "cache key bind match" lookup, which means if any of those
# interim BindParameter objects became part of a cache key in the
# cache, we need it. So here, make sure all clones keep carrying
# forward.
c._cloned_set.update(self._cloned_set)
if not maintain_key and self.unique:
c.key, c._anon_map_key = _anonymous_label.safe_construct_with_key(
id(c), c._orig_key or "param", sanitize_key=True
)
return c
def _gen_cache_key(self, anon_map, bindparams):
_gen_cache_ok = self.__class__.__dict__.get("inherit_cache", False)
if not _gen_cache_ok:
if anon_map is not None:
anon_map[NO_CACHE] = True
return None
id_, found = anon_map.get_anon(self)
if found:
return (id_, self.__class__)
if bindparams is not None:
bindparams.append(self)
return (
id_,
self.__class__,
self.type._static_cache_key,
(
anon_map[self._anon_map_key]
if self._anon_map_key is not None
else self.key
),
self.literal_execute,
)
def _convert_to_unique(self):
if not self.unique:
self.unique = True
self.key, self._anon_map_key = (
_anonymous_label.safe_construct_with_key(
id(self), self._orig_key or "param", sanitize_key=True
)
)
def __getstate__(self):
"""execute a deferred value for serialization purposes."""
d = self.__dict__.copy()
v = self.value
if self.callable:
v = self.callable()
d["callable"] = None
d["value"] = v
return d
def __setstate__(self, state):
if state.get("unique", False):
anon_and_key = _anonymous_label.safe_construct_with_key(
id(self), state.get("_orig_key", "param"), sanitize_key=True
)
state["key"], state["_anon_map_key"] = anon_and_key
self.__dict__.update(state)
def __repr__(self):
return "%s(%r, %r, type_=%r)" % (
self.__class__.__name__,
self.key,
self.value,
self.type,
)
| BindParameter |
python | openai__openai-python | src/openai/types/realtime/realtime_audio_input_turn_detection.py | {
"start": 2381,
"end": 3449
} | class ____(BaseModel):
type: Literal["semantic_vad"]
"""Type of turn detection, `semantic_vad` to turn on Semantic VAD."""
create_response: Optional[bool] = None
"""
Whether or not to automatically generate a response when a VAD stop event
occurs.
"""
eagerness: Optional[Literal["low", "medium", "high", "auto"]] = None
"""Used only for `semantic_vad` mode.
The eagerness of the model to respond. `low` will wait longer for the user to
continue speaking, `high` will respond more quickly. `auto` is the default and
is equivalent to `medium`. `low`, `medium`, and `high` have max timeouts of 8s,
4s, and 2s respectively.
"""
interrupt_response: Optional[bool] = None
"""
Whether or not to automatically interrupt any ongoing response with output to
the default conversation (i.e. `conversation` of `auto`) when a VAD start event
occurs.
"""
RealtimeAudioInputTurnDetection: TypeAlias = Annotated[
Union[ServerVad, SemanticVad, None], PropertyInfo(discriminator="type")
]
| SemanticVad |
python | walkccc__LeetCode | solutions/2290. Minimum Obstacle Removal to Reach Corner/2290.py | {
"start": 0,
"end": 704
} | class ____:
def minimumObstacles(self, grid: list[list[int]]) -> int:
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
m = len(grid)
n = len(grid[0])
minHeap = [(grid[0][0], 0, 0)] # (d, i, j)
dist = [[math.inf] * n for _ in range(m)]
dist[0][0] = grid[0][0]
while minHeap:
d, i, j = heapq.heappop(minHeap)
if i == m - 1 and j == n - 1:
return d
for dx, dy in DIRS:
x = i + dx
y = j + dy
if x < 0 or x == m or y < 0 or y == n:
continue
newDist = d + grid[i][j]
if newDist < dist[x][y]:
dist[x][y] = newDist
heapq.heappush(minHeap, (newDist, x, y))
return dist[m - 1][n - 1]
| Solution |
python | celery__celery | t/unit/utils/test_platforms.py | {
"start": 10442,
"end": 12022
} | class ____:
@patch('celery.platforms.parse_uid')
@patch('os.setuid')
def test_setuid(self, _setuid, parse_uid):
parse_uid.return_value = 5001
setuid('user')
parse_uid.assert_called_with('user')
_setuid.assert_called_with(5001)
@patch('celery.platforms.parse_gid')
@patch('os.setgid')
def test_setgid(self, _setgid, parse_gid):
parse_gid.return_value = 50001
setgid('group')
parse_gid.assert_called_with('group')
_setgid.assert_called_with(50001)
def test_parse_uid_when_int(self):
assert parse_uid(5001) == 5001
@patch('pwd.getpwnam')
def test_parse_uid_when_existing_name(self, getpwnam):
class pwent:
pw_uid = 5001
getpwnam.return_value = pwent()
assert parse_uid('user') == 5001
@patch('pwd.getpwnam')
def test_parse_uid_when_nonexisting_name(self, getpwnam):
getpwnam.side_effect = KeyError('user')
with pytest.raises(KeyError):
parse_uid('user')
def test_parse_gid_when_int(self):
assert parse_gid(50001) == 50001
@patch('grp.getgrnam')
def test_parse_gid_when_existing_name(self, getgrnam):
class grent:
gr_gid = 50001
getgrnam.return_value = grent()
assert parse_gid('group') == 50001
@patch('grp.getgrnam')
def test_parse_gid_when_nonexisting_name(self, getgrnam):
getgrnam.side_effect = KeyError('group')
with pytest.raises(KeyError):
parse_gid('group')
@t.skip.if_win32
| test_setget_uid_gid |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 32502,
"end": 32575
} | class ____(set):
__slots__ = ('x', 'y', '__dict__')
| SetSubclassWithSlots |
python | marshmallow-code__marshmallow | src/marshmallow/orderedset.py | {
"start": 1194,
"end": 2953
} | class ____(MutableSet): # noqa: PLW1641
def __init__(self, iterable=None):
self.end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.map = {} # key --> [key, prev, next]
if iterable is not None:
self |= iterable
def __len__(self):
return len(self.map)
def __contains__(self, key):
return key in self.map
def add(self, key):
if key not in self.map:
end = self.end
curr = end[1]
curr[2] = end[1] = self.map[key] = [key, curr, end]
def discard(self, key):
if key in self.map:
key, prev, next = self.map.pop(key) # noqa: A001
prev[2] = next
next[1] = prev
def __iter__(self):
end = self.end
curr = end[2]
while curr is not end:
yield curr[0]
curr = curr[2]
def __reversed__(self):
end = self.end
curr = end[1]
while curr is not end:
yield curr[0]
curr = curr[1]
def pop(self, last=True):
if not self:
raise KeyError("set is empty")
key = self.end[1][0] if last else self.end[2][0]
self.discard(key)
return key
def __repr__(self):
if not self:
return f"{self.__class__.__name__}()"
return f"{self.__class__.__name__}({list(self)!r})"
def __eq__(self, other):
if isinstance(other, OrderedSet):
return len(self) == len(other) and list(self) == list(other)
return set(self) == set(other)
if __name__ == "__main__":
s = OrderedSet("abracadaba")
t = OrderedSet("simsalabim")
print(s | t)
print(s & t)
print(s - t)
| OrderedSet |
python | jmcnamara__XlsxWriter | xlsxwriter/exceptions.py | {
"start": 241,
"end": 322
} | class ____(Exception):
"""Base exception for XlsxWriter."""
| XlsxWriterException |
python | django__django | tests/model_inheritance/models.py | {
"start": 2613,
"end": 3251
} | class ____(Place):
# An explicit link to the parent (we can control the attribute name).
parent = models.OneToOneField(
Place, models.CASCADE, primary_key=True, parent_link=True
)
main_site = models.ForeignKey(Place, models.CASCADE, related_name="lot")
#
# Abstract base classes with related models where the sub-class has the
# same name in a different app and inherits from the same abstract base
# class.
# NOTE: The actual API tests for the following classes are in
# model_inheritance_same_model_name/models.py - They are defined
# here in order to have the name conflict between apps
#
| ParkingLot |
python | kubernetes-client__python | kubernetes/client/models/v1_load_balancer_ingress.py | {
"start": 383,
"end": 7117
} | 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 = {
'hostname': 'str',
'ip': 'str',
'ip_mode': 'str',
'ports': 'list[V1PortStatus]'
}
attribute_map = {
'hostname': 'hostname',
'ip': 'ip',
'ip_mode': 'ipMode',
'ports': 'ports'
}
def __init__(self, hostname=None, ip=None, ip_mode=None, ports=None, local_vars_configuration=None): # noqa: E501
"""V1LoadBalancerIngress - 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._hostname = None
self._ip = None
self._ip_mode = None
self._ports = None
self.discriminator = None
if hostname is not None:
self.hostname = hostname
if ip is not None:
self.ip = ip
if ip_mode is not None:
self.ip_mode = ip_mode
if ports is not None:
self.ports = ports
@property
def hostname(self):
"""Gets the hostname of this V1LoadBalancerIngress. # noqa: E501
Hostname is set for load-balancer ingress points that are DNS based (typically AWS load-balancers) # noqa: E501
:return: The hostname of this V1LoadBalancerIngress. # noqa: E501
:rtype: str
"""
return self._hostname
@hostname.setter
def hostname(self, hostname):
"""Sets the hostname of this V1LoadBalancerIngress.
Hostname is set for load-balancer ingress points that are DNS based (typically AWS load-balancers) # noqa: E501
:param hostname: The hostname of this V1LoadBalancerIngress. # noqa: E501
:type: str
"""
self._hostname = hostname
@property
def ip(self):
"""Gets the ip of this V1LoadBalancerIngress. # noqa: E501
IP is set for load-balancer ingress points that are IP based (typically GCE or OpenStack load-balancers) # noqa: E501
:return: The ip of this V1LoadBalancerIngress. # noqa: E501
:rtype: str
"""
return self._ip
@ip.setter
def ip(self, ip):
"""Sets the ip of this V1LoadBalancerIngress.
IP is set for load-balancer ingress points that are IP based (typically GCE or OpenStack load-balancers) # noqa: E501
:param ip: The ip of this V1LoadBalancerIngress. # noqa: E501
:type: str
"""
self._ip = ip
@property
def ip_mode(self):
"""Gets the ip_mode of this V1LoadBalancerIngress. # noqa: E501
IPMode specifies how the load-balancer IP behaves, and may only be specified when the ip field is specified. Setting this to \"VIP\" indicates that traffic is delivered to the node with the destination set to the load-balancer's IP and port. Setting this to \"Proxy\" indicates that traffic is delivered to the node or pod with the destination set to the node's IP and node port or the pod's IP and port. Service implementations may use this information to adjust traffic routing. # noqa: E501
:return: The ip_mode of this V1LoadBalancerIngress. # noqa: E501
:rtype: str
"""
return self._ip_mode
@ip_mode.setter
def ip_mode(self, ip_mode):
"""Sets the ip_mode of this V1LoadBalancerIngress.
IPMode specifies how the load-balancer IP behaves, and may only be specified when the ip field is specified. Setting this to \"VIP\" indicates that traffic is delivered to the node with the destination set to the load-balancer's IP and port. Setting this to \"Proxy\" indicates that traffic is delivered to the node or pod with the destination set to the node's IP and node port or the pod's IP and port. Service implementations may use this information to adjust traffic routing. # noqa: E501
:param ip_mode: The ip_mode of this V1LoadBalancerIngress. # noqa: E501
:type: str
"""
self._ip_mode = ip_mode
@property
def ports(self):
"""Gets the ports of this V1LoadBalancerIngress. # noqa: E501
Ports is a list of records of service ports If used, every port defined in the service should have an entry in it # noqa: E501
:return: The ports of this V1LoadBalancerIngress. # noqa: E501
:rtype: list[V1PortStatus]
"""
return self._ports
@ports.setter
def ports(self, ports):
"""Sets the ports of this V1LoadBalancerIngress.
Ports is a list of records of service ports If used, every port defined in the service should have an entry in it # noqa: E501
:param ports: The ports of this V1LoadBalancerIngress. # noqa: E501
:type: list[V1PortStatus]
"""
self._ports = ports
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, V1LoadBalancerIngress):
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, V1LoadBalancerIngress):
return True
return self.to_dict() != other.to_dict()
| V1LoadBalancerIngress |
python | astropy__astropy | astropy/io/votable/converters.py | {
"start": 20581,
"end": 21441
} | class ____(Converter):
"""
The base class for all numeric data types.
"""
array_type = NumericArray
vararray_type = ScalarVarArray
null = None
def __init__(self, field, config=None, pos=None):
Converter.__init__(self, field, config, pos)
self._memsize = np.dtype(self.format).itemsize
self._bigendian_format = ">" + self.format
if field.values.null is not None:
self.null = np.asarray(field.values.null, dtype=self.format)
self.default = self.null
self.is_null = self._is_null
else:
self.is_null = np.isnan
def binparse(self, read):
result = np.frombuffer(read(self._memsize), dtype=self._bigendian_format)
return result[0], self.is_null(result[0])
def _is_null(self, value):
return value == self.null
| Numeric |
python | huggingface__transformers | src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py | {
"start": 4232,
"end": 5660
} | class ____(ModelOutput):
r"""
waveform (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
The final audio waveform predicted by the model.
waveform_lengths (`torch.IntTensor` of shape `(batch_size,)`, *optional*):
The length in samples of each element in the `waveform` batch.
sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
The generated translated sequences. This is the output of the text-to-text or the speech-to-text models.
The second dimension (sequence_length) is either equal to `max_length` or shorter if all batches finished
early due to the `eos_token_id`.
unit_sequences (`torch.LongTensor` of shape `(batch_size, unit_sequence_length)`, *optional*):
The generated translated unit sequences. This is the output of the text-to-units model. The second
dimension (unit_sequence_length) is either equal to `t2u_max_length` or shorter if all batches finished
early due to the `t2u_eos_token_id`.
"""
waveform: Optional[torch.FloatTensor] = None
waveform_lengths: Optional[torch.IntTensor] = None
sequences: Optional[tuple[torch.FloatTensor]] = None
unit_sequences: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring(
custom_intro="""
Class defining the outputs from [`SeamlessM4Tv2TextToUnitDecoder`].
"""
)
| SeamlessM4Tv2GenerationOutput |
python | Farama-Foundation__Gymnasium | tests/wrappers/test_jax_to_numpy.py | {
"start": 459,
"end": 4741
} | class ____(NamedTuple):
a: jax.Array
b: jax.Array
@pytest.mark.parametrize(
"value, expected_value",
[
(1.0, np.array(1.0, dtype=np.float32)),
(2, np.array(2, dtype=np.int32)),
((3.0, 4), (np.array(3.0, dtype=np.float32), np.array(4, dtype=np.int32))),
([3.0, 4], [np.array(3.0, dtype=np.float32), np.array(4, dtype=np.int32)]),
(
{
"a": 6.0,
"b": 7,
},
{"a": np.array(6.0, dtype=np.float32), "b": np.array(7, dtype=np.int32)},
),
(np.array(1.0, dtype=np.float32), np.array(1.0, dtype=np.float32)),
(np.array(1.0, dtype=np.uint8), np.array(1.0, dtype=np.uint8)),
(np.array([1, 2], dtype=np.int32), np.array([1, 2], dtype=np.int32)),
(
np.array([[1.0], [2.0]], dtype=np.int32),
np.array([[1.0], [2.0]], dtype=np.int32),
),
(
{
"a": (
1,
np.array(2.0, dtype=np.float32),
np.array([3, 4], dtype=np.int32),
),
"b": {"c": 5},
},
{
"a": (
np.array(1, dtype=np.int32),
np.array(2.0, dtype=np.float32),
np.array([3, 4], dtype=np.int32),
),
"b": {"c": np.array(5, dtype=np.int32)},
},
),
(
ExampleNamedTuple(
a=np.array([1, 2], dtype=np.int32),
b=np.array([1.0, 2.0], dtype=np.float32),
),
ExampleNamedTuple(
a=np.array([1, 2], dtype=np.int32),
b=np.array([1.0, 2.0], dtype=np.float32),
),
),
(None, None),
],
)
def test_roundtripping(value, expected_value):
"""We test numpy -> jax -> numpy as this is direction in the NumpyToJax wrapper.
Warning: Jax doesn't support float64 out of the box, therefore, we only test float32 in this test.
"""
roundtripped_value = jax_to_numpy(numpy_to_jax(value))
assert data_equivalence(roundtripped_value, expected_value)
def jax_reset_func(self, seed=None, options=None):
"""A jax-based reset function."""
return jnp.array([1.0, 2.0, 3.0]), {"data": jnp.array([1, 2, 3])}
def jax_step_func(self, action):
"""A jax-based step function."""
assert isinstance(action, jax.Array), type(action)
return (
jnp.array([1, 2, 3]),
jnp.array(5.0),
jnp.array(True),
jnp.array(False),
{"data": jnp.array([1.0, 2.0])},
)
def test_jax_to_numpy_wrapper():
"""Tests the ``JaxToNumpyV0`` wrapper."""
jax_env = GenericTestEnv(reset_func=jax_reset_func, step_func=jax_step_func)
# Check that the reset and step for jax environment are as expected
obs, info = jax_env.reset()
assert isinstance(obs, jax.Array)
assert isinstance(info, dict) and isinstance(info["data"], jax.Array)
obs, reward, terminated, truncated, info = jax_env.step(jnp.array([1, 2]))
assert isinstance(obs, jax.Array)
assert isinstance(reward, jax.Array)
assert isinstance(terminated, jax.Array) and isinstance(truncated, jax.Array)
assert isinstance(info, dict) and isinstance(info["data"], jax.Array)
# Check that the wrapped version is correct.
numpy_env = JaxToNumpy(jax_env)
obs, info = numpy_env.reset()
assert isinstance(obs, np.ndarray)
assert isinstance(info, dict) and isinstance(info["data"], np.ndarray)
obs, reward, terminated, truncated, info = numpy_env.step(
np.array([1, 2], dtype=np.int32)
)
assert isinstance(obs, np.ndarray)
assert isinstance(reward, float)
assert isinstance(terminated, bool) and isinstance(truncated, bool)
assert isinstance(info, dict) and isinstance(info["data"], np.ndarray)
# Check that the wrapped environment can render. This implicitly returns None and requires a
# None -> None conversion
numpy_env.render()
# Test that the wrapped environment can be pickled
env = gymnasium.make("CartPole-v1", disable_env_checker=True)
wrapped_env = JaxToNumpy(env)
pkl = pickle.dumps(wrapped_env)
pickle.loads(pkl)
| ExampleNamedTuple |
python | davidhalter__jedi | jedi/inference/signature.py | {
"start": 124,
"end": 1101
} | class ____:
def to_string(self):
def param_strings():
is_positional = False
is_kw_only = False
for n in self.get_param_names(resolve_stars=True):
kind = n.get_kind()
is_positional |= kind == Parameter.POSITIONAL_ONLY
if is_positional and kind != Parameter.POSITIONAL_ONLY:
yield '/'
is_positional = False
if kind == Parameter.VAR_POSITIONAL:
is_kw_only = True
elif kind == Parameter.KEYWORD_ONLY and not is_kw_only:
yield '*'
is_kw_only = True
yield n.to_string()
if is_positional:
yield '/'
s = self.name.string_name + '(' + ', '.join(param_strings()) + ')'
annotation = self.annotation_string
if annotation:
s += ' -> ' + annotation
return s
| _SignatureMixin |
python | scipy__scipy | scipy/optimize/_trustregion_constr/tests/test_projections.py | {
"start": 7170,
"end": 8869
} | class ____(TestCase):
def test_dense_matrix(self):
A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
[0, 8, 7, 0, 1, 5, 9, 0],
[1, 0, 0, 0, 0, 1, 2, 3]])
test_vectors = ([-1.98931144, -1.56363389,
-0.84115584, 2.2864762,
5.599141, 0.09286976,
1.37040802, -0.28145812],
[697.92794044, -4091.65114008,
-3327.42316335, 836.86906951,
99434.98929065, -1285.37653682,
-4109.21503806, 2935.29289083])
test_expected_orth = (0, 0)
for i in range(len(test_vectors)):
x = test_vectors[i]
orth = test_expected_orth[i]
assert_array_almost_equal(orthogonality(A, x), orth)
def test_sparse_matrix(self):
A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
[0, 8, 7, 0, 1, 5, 9, 0],
[1, 0, 0, 0, 0, 1, 2, 3]])
A = csc_array(A)
test_vectors = ([-1.98931144, -1.56363389,
-0.84115584, 2.2864762,
5.599141, 0.09286976,
1.37040802, -0.28145812],
[697.92794044, -4091.65114008,
-3327.42316335, 836.86906951,
99434.98929065, -1285.37653682,
-4109.21503806, 2935.29289083])
test_expected_orth = (0, 0)
for i in range(len(test_vectors)):
x = test_vectors[i]
orth = test_expected_orth[i]
assert_array_almost_equal(orthogonality(A, x), orth)
| TestOrthogonality |
python | doocs__leetcode | lcof/面试题65. 不用加减乘除做加法/Solution.py | {
"start": 0,
"end": 251
} | class ____:
def add(self, a: int, b: int) -> int:
a, b = a & 0xFFFFFFFF, b & 0xFFFFFFFF
while b:
c = ((a & b) << 1) & 0xFFFFFFFF
a, b = a ^ b, c
return a if a < 0x80000000 else ~(a ^ 0xFFFFFFFF)
| Solution |
python | spyder-ide__spyder | spyder/plugins/onlinehelp/widgets.py | {
"start": 994,
"end": 1088
} | class ____:
# Triggers
Home = 'home_action'
Find = 'find_action'
| PydocBrowserActions |
python | PyCQA__pylint | tests/functional/t/too/too_few_public_methods_37.py | {
"start": 992,
"end": 1062
} | class ____:
x: float
y: float
@attrs.define
| AttrsBareFrozenPoint |
python | ansible__ansible | lib/ansible/module_utils/_internal/_datatag/__init__.py | {
"start": 33737,
"end": 34307
} | class ____(dict, AnsibleTaggedObject):
__slots__ = _ANSIBLE_TAGGED_OBJECT_SLOTS
_item_source: t.ClassVar[t.Optional[t.Callable]] = dict.items
def __copy__(self):
return super()._copy_collection()
def copy(self) -> _AnsibleTaggedDict:
return copy.copy(self)
# NB: Tags are intentionally not preserved for operator methods that return a new instance. In-place operators ignore tags from the `other` instance.
# Propagation of tags in these cases is left to the caller, based on needs specific to their use case.
| _AnsibleTaggedDict |
python | numpy__numpy | numpy/_core/tests/test_item_selection.py | {
"start": 4885,
"end": 6631
} | class ____:
@pytest.mark.parametrize("dtype", list(np.typecodes["All"])[1:] + ["i,O"])
@pytest.mark.parametrize("mode", ["raise", "wrap", "clip"])
def test_simple(self, dtype, mode):
if dtype.lower() == "m":
dtype += "8[ns]"
# put is weird and doesn't care about value length (even shorter)
vals = np.arange(1001).astype(dtype=dtype)
# Use vals.dtype in case of flexible dtype (i.e. string)
arr = np.zeros(1000, dtype=vals.dtype)
zeros = arr.copy()
if mode == "clip":
# Special because 0 and -1 value are "reserved" for clip test
indx = np.random.permutation(len(arr) - 2)[:-500] + 1
indx[-1] = 0
indx[-2] = len(arr) - 1
indx_put = indx.copy()
indx_put[-1] = -1389
indx_put[-2] = 1321
else:
# Avoid duplicates (for simplicity) and fill half only
indx = np.random.permutation(len(arr) - 3)[:-500]
indx_put = indx
if mode == "wrap":
indx_put = indx_put + len(arr)
np.put(arr, indx_put, vals, mode=mode)
assert_array_equal(arr[indx], vals[:len(indx)])
untouched = np.ones(len(arr), dtype=bool)
untouched[indx] = False
assert_array_equal(arr[untouched], zeros[:untouched.sum()])
@pytest.mark.parametrize("dtype", list(np.typecodes["All"])[1:] + ["i,O"])
@pytest.mark.parametrize("mode", ["raise", "wrap", "clip"])
def test_empty(self, dtype, mode):
arr = np.zeros(1000, dtype=dtype)
arr_copy = arr.copy()
# Allowing empty values like this is weird...
np.put(arr, [1, 2, 3], [])
assert_array_equal(arr, arr_copy)
| TestPut |
python | run-llama__llama_index | llama-index-integrations/question_gen/llama-index-question-gen-guidance/llama_index/question_gen/guidance/base.py | {
"start": 777,
"end": 2350
} | class ____(BaseQuestionGenerator):
def __init__(
self,
program: GuidancePydanticProgram,
verbose: bool = False,
) -> None:
self._program = program
self._verbose = verbose
@classmethod
def from_defaults(
cls,
prompt_template_str: str = DEFAULT_GUIDANCE_SUB_QUESTION_PROMPT_TMPL,
guidance_llm: Optional["GuidanceLLM"] = None,
verbose: bool = False,
) -> "GuidanceQuestionGenerator":
program = GuidancePydanticProgram(
output_cls=SubQuestionList,
guidance_llm=guidance_llm,
prompt_template_str=prompt_template_str,
verbose=verbose,
)
return cls(program, verbose)
def _get_prompts(self) -> PromptDictType:
"""Get prompts."""
return {}
def _update_prompts(self, prompts: PromptDictType) -> None:
"""Update prompts."""
def generate(
self, tools: Sequence[ToolMetadata], query: QueryBundle
) -> List[SubQuestion]:
tools_str = build_tools_text(tools)
query_str = query.query_str
question_list = self._program(
tools_str=tools_str,
query_str=query_str,
)
question_list = cast(SubQuestionList, question_list)
return question_list.items
async def agenerate(
self, tools: Sequence[ToolMetadata], query: QueryBundle
) -> List[SubQuestion]:
# TODO: currently guidance does not support async calls
return self.generate(tools=tools, query=query)
| GuidanceQuestionGenerator |
python | PrefectHQ__prefect | src/integrations/prefect-aws/prefect_aws/observers/ecs.py | {
"start": 2066,
"end": 2161
} | class ____(TypedDict):
tags: TagsFilter
last_status: LastStatusFilter
| EventHandlerFilters |
python | PyCQA__pylint | doc/data/messages/i/invalid-repr-returned/bad.py | {
"start": 0,
"end": 127
} | class ____:
"""__repr__ returns <type 'int'>"""
def __repr__(self): # [invalid-repr-returned]
return 1
| CustomRepr |
python | docker__docker-py | tests/unit/dockertypes_test.py | {
"start": 8957,
"end": 10877
} | class ____(unittest.TestCase):
def test_create_host_config_dict_ulimit(self):
ulimit_dct = {'name': 'nofile', 'soft': 8096}
config = create_host_config(
ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
)
assert 'Ulimits' in config
assert len(config['Ulimits']) == 1
ulimit_obj = config['Ulimits'][0]
assert isinstance(ulimit_obj, Ulimit)
assert ulimit_obj.name == ulimit_dct['name']
assert ulimit_obj.soft == ulimit_dct['soft']
assert ulimit_obj['Soft'] == ulimit_obj.soft
def test_create_host_config_dict_ulimit_capitals(self):
ulimit_dct = {'Name': 'nofile', 'Soft': 8096, 'Hard': 8096 * 4}
config = create_host_config(
ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
)
assert 'Ulimits' in config
assert len(config['Ulimits']) == 1
ulimit_obj = config['Ulimits'][0]
assert isinstance(ulimit_obj, Ulimit)
assert ulimit_obj.name == ulimit_dct['Name']
assert ulimit_obj.soft == ulimit_dct['Soft']
assert ulimit_obj.hard == ulimit_dct['Hard']
assert ulimit_obj['Soft'] == ulimit_obj.soft
def test_create_host_config_obj_ulimit(self):
ulimit_dct = Ulimit(name='nofile', soft=8096)
config = create_host_config(
ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION
)
assert 'Ulimits' in config
assert len(config['Ulimits']) == 1
ulimit_obj = config['Ulimits'][0]
assert isinstance(ulimit_obj, Ulimit)
assert ulimit_obj == ulimit_dct
def test_ulimit_invalid_type(self):
with pytest.raises(ValueError):
Ulimit(name=None)
with pytest.raises(ValueError):
Ulimit(name='hello', soft='123')
with pytest.raises(ValueError):
Ulimit(name='hello', hard='456')
| UlimitTest |
python | getsentry__sentry | src/sentry/replays/post_process.py | {
"start": 417,
"end": 511
} | class ____(TypedDict, total=False):
name: str | None
version: str | None
| SDKResponseType |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_univariate.py | {
"start": 287,
"end": 1199
} | class ____(Benchmark):
"""
Univariate Problem02 objective function.
This class defines the Univariate Problem02 global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\\text{Problem02}}(x) = \\sin(x) + \\sin \\left(\\frac{10}{3}x \\right)
Bound constraints: :math:`x \\in [2.7, 7.5]`
.. figure:: figures/Problem02.png
:alt: Univariate Problem02 function
:align: center
**Univariate Problem02 function**
*Global optimum*: :math:`f(x)=-1.899599` for :math:`x = 5.145735`
"""
def __init__(self, dimensions=1):
Benchmark.__init__(self, dimensions)
self._bounds = [(2.7, 7.5)]
self.global_optimum = 5.145735
self.fglob = -1.899599
def fun(self, x, *args):
self.nfev += 1
x = x[0]
return sin(x) + sin(10.0 / 3.0 * x)
| Problem02 |
python | streamlit__streamlit | e2e_playwright/st_help.py | {
"start": 3659,
"end": 4755
} | class ____:
"""Class with very long documentation to demonstrate width differences.
This documentation is intentionally long to show how different width settings affect
the display of help text. The content should be long enough to wrap and show the
difference between stretch and fixed width settings.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
"""
def __init__(self):
self.some_attribute = "This is a sample attribute"
self.another_attribute = "This is another attribute"
self.third_attribute = "This is a third attribute"
self.fourth_attribute = "This is a fourth attribute"
self.fifth_attribute = "This is a fifth attribute"
# Create instances for testing
long_doc_instance = LongDocumentationClass()
# Test different width configurations
st.help(long_doc_instance, width=300)
st.help(long_doc_instance, width="stretch")
| LongDocumentationClass |
python | huggingface__transformers | tests/models/fastspeech2_conformer/test_modeling_fastspeech2_conformer.py | {
"start": 13961,
"end": 20974
} | class ____(unittest.TestCase):
def test_inference_integration(self):
model = FastSpeech2ConformerModel.from_pretrained("espnet/fastspeech2_conformer")
model.to(torch_device)
model.eval()
tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
text = "Test that this generates speech"
input_ids = tokenizer(text, return_tensors="pt").to(torch_device)["input_ids"]
outputs_dict = model(input_ids)
spectrogram = outputs_dict["spectrogram"]
# mel-spectrogram is too large (1, 205, 80), so only check top-left 100 elements
# fmt: off
expectations = Expectations(
{
(None, None): [
[-1.2426, -1.7286, -1.6754, -1.7451, -1.6402, -1.5219, -1.4480, -1.3345, -1.4031, -1.4497],
[-0.7858, -1.4966, -1.3602, -1.4876, -1.2949, -1.0723, -1.0021, -0.7553, -0.6521, -0.6929],
[-0.7298, -1.3908, -1.0369, -1.2656, -1.0342, -0.7883, -0.7420, -0.5249, -0.3734, -0.3977],
[-0.4784, -1.3508, -1.1558, -1.4678, -1.2820, -1.0252, -1.0868, -0.9006, -0.8947, -0.8448],
[-0.3963, -1.2895, -1.2813, -1.6147, -1.4658, -1.2560, -1.4134, -1.2650, -1.3255, -1.1715],
[-1.4914, -1.3097, -0.3821, -0.3898, -0.5748, -0.9040, -1.0755, -1.0575, -1.2205, -1.0572],
[0.0197, -0.0582, 0.9147, 1.1512, 1.1651, 0.6628, -0.1010, -0.3085, -0.2285, 0.2650],
[1.1780, 0.1803, 0.7251, 1.5728, 1.6678, 0.4542, -0.1572, -0.1787, 0.0744, 0.8168],
[-0.2078, -0.3211, 1.1096, 1.5085, 1.4632, 0.6299, -0.0515, 0.0589, 0.8609, 1.4429],
[0.7831, -0.2663, 1.0352, 1.4489, 0.9088, 0.0247, -0.3995, 0.0078, 1.2446, 1.6998],
],
("cuda", 8): [
[-1.2426, -1.7286, -1.6754, -1.7451, -1.6402, -1.5219, -1.4480, -1.3345, -1.4030, -1.4497],
[-0.7858, -1.4966, -1.3601, -1.4876, -1.2949, -1.0723, -1.0021, -0.7553, -0.6521, -0.6929],
[-0.7298, -1.3908, -1.0369, -1.2656, -1.0342, -0.7883, -0.7420, -0.5249, -0.3734, -0.3977],
[-0.4784, -1.3508, -1.1558, -1.4678, -1.2820, -1.0252, -1.0868, -0.9006, -0.8947, -0.8448],
[-0.3963, -1.2895, -1.2813, -1.6147, -1.4658, -1.2560, -1.4134, -1.2650, -1.3255, -1.1715],
[-1.4913, -1.3097, -0.3820, -0.3897, -0.5747, -0.9040, -1.0755, -1.0575, -1.2205, -1.0571],
[ 0.0197, -0.0582, 0.9148, 1.1512, 1.1651, 0.6628, -0.1009, -0.3085, -0.2285, 0.2651],
[ 1.1780, 0.1803, 0.7251, 1.5728, 1.6677, 0.4542, -0.1572, -0.1787, 0.0744, 0.8168],
[-0.2078, -0.3211, 1.1096, 1.5085, 1.4631, 0.6299, -0.0515, 0.0589, 0.8609, 1.4429],
[ 0.7831, -0.2663, 1.0352, 1.4488, 0.9087, 0.0247, -0.3995, 0.0079, 1.2447, 1.6998],
],
}
)
expected_mel_spectrogram = torch.tensor(expectations.get_expectation()).to(torch_device)
# fmt: on
torch.testing.assert_close(spectrogram[0, :10, :10], expected_mel_spectrogram, rtol=2e-4, atol=2e-4)
self.assertEqual(spectrogram.shape, (1, 205, model.config.num_mel_bins))
def test_training_integration(self):
model = FastSpeech2ConformerModel.from_pretrained("espnet/fastspeech2_conformer")
model.to(torch_device)
# Set self.training manually to keep deterministic but run the training path
model.training = True
set_seed(0)
tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
text = "Test that this generates speech"
input_ids = tokenizer(text, return_tensors="pt").to(torch_device)["input_ids"]
# NOTE: Dummy numbers since FastSpeech2Conformer does not have a feature extractor due to the package deps required (librosa, MFA)
batch_size, max_text_len = input_ids.shape
pitch_labels = torch.rand((batch_size, max_text_len, 1), dtype=torch.float, device=torch_device)
energy_labels = torch.rand((batch_size, max_text_len, 1), dtype=torch.float, device=torch_device)
duration_labels = torch.normal(10, 2, size=(batch_size, max_text_len), device=torch_device).clamp(1, 20).int()
max_target_len, _ = duration_labels.sum(dim=1).max(dim=0)
max_target_len = max_target_len.item()
spectrogram_labels = torch.rand(
(batch_size, max_target_len, model.num_mel_bins), dtype=torch.float, device=torch_device
)
outputs_dict = model(
input_ids,
spectrogram_labels=spectrogram_labels,
duration_labels=duration_labels,
pitch_labels=pitch_labels,
energy_labels=energy_labels,
return_dict=True,
)
spectrogram = outputs_dict["spectrogram"]
loss = outputs_dict["loss"]
# # mel-spectrogram is too large (1, 224, 80), so only check top-left 100 elements
# fmt: off
expected_mel_spectrogram = torch.tensor(
[
[-5.1726e-01, -2.1546e-01, -6.2949e-01, -4.9966e-01, -6.2329e-01,-1.0024e+00, -5.0756e-01, -4.3783e-01, -7.7909e-01, -7.1529e-01],
[3.1639e-01, 4.6567e-01, 2.3859e-01, 6.1324e-01, 6.6993e-01,2.7852e-01, 3.4084e-01, 2.6045e-01, 3.1769e-01, 6.8664e-01],
[1.0904e+00, 8.2760e-01, 5.4471e-01, 1.3948e+00, 1.2052e+00,1.3914e-01, 3.0311e-01, 2.9209e-01, 6.6969e-01, 1.4900e+00],
[8.7539e-01, 7.7813e-01, 8.5193e-01, 1.7797e+00, 1.5827e+00,2.1765e-01, 9.5736e-02, 1.5207e-01, 9.2984e-01, 1.9718e+00],
[1.0156e+00, 7.4948e-01, 8.5781e-01, 2.0302e+00, 1.8718e+00,-4.6816e-02, -8.4771e-02, 1.5288e-01, 9.6214e-01, 2.1747e+00],
[9.5446e-01, 7.2816e-01, 8.5703e-01, 2.1049e+00, 2.1529e+00,9.1168e-02, -1.8864e-01, 4.7460e-02, 9.1671e-01, 2.2506e+00],
[1.0980e+00, 6.5521e-01, 8.2278e-01, 2.1420e+00, 2.2990e+00,1.1589e-01, -2.2167e-01, 1.1425e-03, 8.5591e-01, 2.2267e+00],
[9.2134e-01, 6.2354e-01, 8.9153e-01, 2.1447e+00, 2.2947e+00,9.8064e-02, -1.3171e-01, 1.2306e-01, 9.6330e-01, 2.2747e+00],
[1.0625e+00, 6.4575e-01, 1.0348e+00, 2.0821e+00, 2.1834e+00,2.3807e-01, -1.3262e-01, 1.5632e-01, 1.1988e+00, 2.3948e+00],
[1.4111e+00, 7.5421e-01, 1.0703e+00, 2.0512e+00, 1.9331e+00,4.0482e-03, -4.2486e-02, 4.6495e-01, 1.4404e+00, 2.3599e+00],
],
device=torch_device,
)
# fmt: on
expected_loss = torch.tensor(74.127174, device=torch_device)
torch.testing.assert_close(spectrogram[0, :10, :10], expected_mel_spectrogram, rtol=1e-3, atol=1e-3)
torch.testing.assert_close(loss, expected_loss, rtol=1e-4, atol=1e-4)
self.assertEqual(tuple(spectrogram.shape), (1, 219, model.config.num_mel_bins))
| FastSpeech2ConformerModelIntegrationTest |
python | openai__openai-python | src/openai/types/realtime/realtime_response_create_audio_output_param.py | {
"start": 332,
"end": 910
} | class ____(TypedDict, total=False):
format: RealtimeAudioFormatsParam
"""The format of the output audio."""
voice: Union[str, Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse", "marin", "cedar"]]
"""The voice the model uses to respond.
Voice cannot be changed during the session once the model has responded with
audio at least once. Current voice options are `alloy`, `ash`, `ballad`,
`coral`, `echo`, `sage`, `shimmer`, `verse`, `marin`, and `cedar`. We recommend
`marin` and `cedar` for best quality.
"""
| Output |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 11237,
"end": 11664
} | class ____(SocketTCPTest, ThreadableTest):
def __init__(self, methodName='runTest'):
SocketTCPTest.__init__(self, methodName=methodName)
ThreadableTest.__init__(self)
def clientSetUp(self):
self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def clientTearDown(self):
self.cli.close()
self.cli = None
ThreadableTest.clientTearDown(self)
| ThreadedTCPSocketTest |
python | ansible__ansible | test/integration/targets/connection_remote_is_local/connection_plugins/remote_is_local.py | {
"start": 583,
"end": 646
} | class ____(LocalConnection):
_remote_is_local = True
| Connection |
python | getsentry__sentry | src/sentry/grouping/parameterization.py | {
"start": 234,
"end": 9148
} | class ____:
name: str # name of the pattern (also used as group name in combined regex)
raw_pattern: str # regex pattern w/o matching group name
raw_pattern_experimental: str | None = None
lookbehind: str | None = None # positive lookbehind prefix if needed
lookahead: str | None = None # positive lookahead postfix if needed
counter: int = 0
# These need to be used with `(?x)`, to tell the regex compiler to ignore comments
# and unescaped whitespace, so we can use newlines and indentation for better legibility.
@property
def pattern(self) -> str:
return self._pattern(False)
@property
def experimental_pattern(self) -> str:
return self._pattern(self.raw_pattern_experimental is not None)
def _pattern(self, experimental: bool = False) -> str:
"""
Returns the regex pattern with a named matching group and lookbehind/lookahead if needed.
"""
pattern = self.raw_pattern_experimental if experimental else self.raw_pattern
prefix = rf"(?<={self.lookbehind})" if self.lookbehind else ""
postfix = rf"(?={self.lookahead})" if self.lookahead else ""
return rf"{prefix}(?P<{self.name}>{pattern}){postfix}"
DEFAULT_PARAMETERIZATION_REGEXES = [
ParameterizationRegex(
name="email",
raw_pattern=r"""[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*""",
),
ParameterizationRegex(name="url", raw_pattern=r"""\b(wss?|https?|ftp)://[^\s/$.?#].[^\s]*"""),
ParameterizationRegex(
name="hostname",
raw_pattern=r"""
# Top 100 TLDs. The complete list is 1000s long.
\b
([a-zA-Z0-9\-]{1,63}\.)+?
(
(COM|NET|ORG|JP|DE|UK|FR|BR|IT|RU|ES|ME|GOV|PL|CA|AU|CN|CO|IN|NL|EDU|INFO|EU|CH|ID|AT|KR|CZ|MX|BE|TV|SE|TR|TW|AL|UA|IR|VN|CL|SK|LY|CC|TO|NO|FI|US|PT|DK|AR|HU|TK|GR|IL|NEWS|RO|MY|BIZ|IE|ZA|NZ|SG|EE|TH|IO|XYZ|PE|BG|HK|RS|LT|LINK|PH|CLUB|SI|SITE|MOBI|BY|CAT|WIKI|LA|GA|XXX|CF|HR|NG|JOBS|ONLINE|KZ|UG|GQ|AE|IS|LV|PRO|FM|TIPS|MS|SA|APP)|
(com|net|org|jp|de|uk|fr|br|it|ru|es|me|gov|pl|ca|au|cn|co|in|nl|edu|info|eu|ch|id|at|kr|cz|mx|be|tv|se|tr|tw|al|ua|ir|vn|cl|sk|ly|cc|to|no|fi|us|pt|dk|ar|hu|tk|gr|il|news|ro|my|biz|ie|za|nz|sg|ee|th|io|xyz|pe|bg|hk|rs|lt|link|ph|club|si|site|mobi|by|cat|wiki|la|ga|xxx|cf|hr|ng|jobs|online|kz|ug|gq|ae|is|lv|pro|fm|tips|ms|sa|app)
)
\b
""",
),
ParameterizationRegex(
name="ip",
raw_pattern=r"""
(
([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|
([0-9a-fA-F]{1,4}:){1,7}:|
([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|
([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|
([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|
([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|
([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|
[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|
:((:[0-9a-fA-F]{1,4}){1,7}|:)|
fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|
::(ffff(:0{1,4}){0,1}:){0,1}
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|
([0-9a-fA-F]{1,4}:){1,4}:
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\b
) |
(
\b((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\b
)
""",
),
ParameterizationRegex(
name="traceparent",
raw_pattern=r"""
# https://www.w3.org/TR/trace-context/#traceparent-header
(\b00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]\b) |
# https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-request-tracing.html#request-tracing-syntax
(\b1-[0-9a-f]{8}-[0-9a-f]{24}\b)
""",
),
ParameterizationRegex(
name="uuid",
raw_pattern=r"""\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b""",
),
ParameterizationRegex(name="sha1", raw_pattern=r"""\b[0-9a-fA-F]{40}\b"""),
ParameterizationRegex(name="md5", raw_pattern=r"""\b[0-9a-fA-F]{32}\b"""),
ParameterizationRegex(
name="date",
raw_pattern=r"""
# No word boundaries required around dates. Should there be?
# RFC822, RFC1123, RFC1123Z
((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat),\s\d{1,2}\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2,4}\s\d{1,2}:\d{1,2}(:\d{1,2})?\s([-\+][\d]{2}[0-5][\d]|(?:UT|GMT|(?:E|C|M|P)(?:ST|DT)|[A-IK-Z])))
|
# Similar to RFC822, but "Mon Jan 02, 1999", "Jan 02, 1999"
(((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s)?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s[0-3]\d,\s\d{2,4})
|
# RFC850
((?:Sun|Sunday|Mon|Monday|Tue|Tuesday|Wed|Wednesday|Thu|Thursday|Fri|Friday|Sat|Saturday),\s\d{2}-(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2}\s\d{2}:\d{2}:\d{2}\s(?:UT|GMT|(?:E|C|M|P)(?:ST|DT)|[A-IK-Z]))
|
# RFC3339, RFC3339Nano
(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z?([+-]?\d{2}:\d{2})?)
|
# JavaScript
((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT[+-]\d{4}(?:\s\([^)]+\))?)
|
# Datetime:
(\d{4}-?[01]\d-?[0-3]\d\s[0-2]\d:[0-5]\d:[0-5]\d)(\.\d+)?
|
# Kitchen
([1-9]\d?:\d{2}(:\d{2})?(?: [aApP][Mm])?)
|
# Date
(\d{4}-[01]\d-[0-3]\d)
|
# Time
([0-2]\d:[0-5]\d:[0-5]\d)
|
# Old Date Formats, TODO: possibly safe to remove?
(
(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|
(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|
(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))
) |
(
\b(?:(Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s+)?
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
([\d]{1,2})\s+
([\d]{2}:[\d]{2}:[\d]{2})\s+
[\d]{4}
) |
(
\b(?:(Sun|Mon|Tue|Wed|Thu|Fri|Sat),\s+)?
(0[1-9]|[1-2]?[\d]|3[01])\s+
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
(19[\d]{2}|[2-9][\d]{3})\s+
(2[0-3]|[0-1][\d]):([0-5][\d])
(?::(60|[0-5][\d]))?\s+
([-\+][\d]{2}[0-5][\d]|(?:UT|GMT|(?:E|C|M|P)(?:ST|DT)|[A-IK-Z]))
) |
(datetime.datetime\(.*?\))
""",
),
ParameterizationRegex(name="duration", raw_pattern=r"""\b(\d+ms) | (\d+(\.\d+)?s)\b"""),
ParameterizationRegex(
name="hex",
raw_pattern=r"""
# Hex value with 0x or 0X prefix
(\b0[xX][0-9a-fA-F]+\b) |
# Hex value without 0x or 0X prefix exactly 4 or 8 bytes long.
#
# We don't need to lookahead for a-f since we if it contains at
# least one number it must contain at least one a-f otherwise it
# would have matched "int".
#
# (?=.*[0-9]): At least one 0-9 is in the match.
# [0-9a-f]{8/16}: Exactly 8 or 16 hex characters (0-9, a-f).
(\b(?=.*[0-9])[0-9a-f]{8}\b) |
(\b(?=.*[0-9])[0-9a-f]{16}\b)
""",
),
ParameterizationRegex(name="float", raw_pattern=r"""-\d+\.\d+\b | \b\d+\.\d+\b"""),
ParameterizationRegex(name="int", raw_pattern=r"""-\d+\b | \b\d+\b"""),
ParameterizationRegex(
name="quoted_str",
raw_pattern=r"""# Using `=`lookbehind which guarantees we'll only match the value half of key-value pairs,
# rather than all quoted strings
'([^']+)' | "([^"]+)"
""",
lookbehind="=",
),
ParameterizationRegex(
name="bool",
raw_pattern=r"""# Using `=`lookbehind which guarantees we'll only match the value half of key-value pairs,
# rather than all instances of the words 'true' and 'false'.
True |
true |
False |
false
""",
lookbehind="=",
),
]
DEFAULT_PARAMETERIZATION_REGEXES_MAP = {r.name: r.pattern for r in DEFAULT_PARAMETERIZATION_REGEXES}
EXPERIMENTAL_PARAMETERIZATION_REGEXES_MAP = {
r.name: r.experimental_pattern for r in DEFAULT_PARAMETERIZATION_REGEXES
}
@dataclasses.dataclass
| ParameterizationRegex |
python | Textualize__textual | docs/examples/widgets/button.py | {
"start": 146,
"end": 2008
} | class ____(App[str]):
CSS_PATH = "button.tcss"
def compose(self) -> ComposeResult:
yield Horizontal(
VerticalScroll(
Static("Standard Buttons", classes="header"),
Button("Default"),
Button("Primary!", variant="primary"),
Button.success("Success!"),
Button.warning("Warning!"),
Button.error("Error!"),
),
VerticalScroll(
Static("Disabled Buttons", classes="header"),
Button("Default", disabled=True),
Button("Primary!", variant="primary", disabled=True),
Button.success("Success!", disabled=True),
Button.warning("Warning!", disabled=True),
Button.error("Error!", disabled=True),
),
VerticalScroll(
Static("Flat Buttons", classes="header"),
Button("Default", flat=True),
Button("Primary!", variant="primary", flat=True),
Button.success("Success!", flat=True),
Button.warning("Warning!", flat=True),
Button.error("Error!", flat=True),
),
VerticalScroll(
Static("Disabled Flat Buttons", classes="header"),
Button("Default", disabled=True, flat=True),
Button("Primary!", variant="primary", disabled=True, flat=True),
Button.success("Success!", disabled=True, flat=True),
Button.warning("Warning!", disabled=True, flat=True),
Button.error("Error!", disabled=True, flat=True),
),
)
def on_button_pressed(self, event: Button.Pressed) -> None:
self.exit(str(event.button))
if __name__ == "__main__":
app = ButtonsApp()
print(app.run())
| ButtonsApp |
python | ansible__ansible | lib/ansible/_internal/_templating/_jinja_common.py | {
"start": 855,
"end": 956
} | class ____(enum.Enum):
DEFAULT = enum.auto()
ALLOW_UNSAFE_ATTRIBUTES = enum.auto()
| _SandboxMode |
python | astropy__astropy | astropy/wcs/wcsapi/conftest.py | {
"start": 1913,
"end": 3207
} | class ____(BaseLowLevelWCS):
@property
def pixel_n_dim(self):
return 1
@property
def world_n_dim(self):
return 1
@property
def world_axis_physical_types(self):
return ("em.freq",)
@property
def world_axis_units(self):
return ("Hz",)
@property
def world_axis_names(self):
return ("Frequency",)
_pixel_shape = None
@property
def pixel_shape(self):
return self._pixel_shape
@pixel_shape.setter
def pixel_shape(self, value):
self._pixel_shape = value
_pixel_bounds = None
@property
def pixel_bounds(self):
return self._pixel_bounds
@pixel_bounds.setter
def pixel_bounds(self, value):
self._pixel_bounds = value
def pixel_to_world_values(self, pixel_array):
return np.asarray(pixel_array - 10) * 3e9 + 4e9
def world_to_pixel_values(self, world_array):
return np.asarray(world_array - 4e9) / 3e9 + 10
@property
def world_axis_object_components(self):
return (("test", 0, "value"),)
@property
def world_axis_object_classes(self):
return {"test": (Quantity, (), {"unit": "Hz"})}
@pytest.fixture
def spectral_1d_ape14_wcs():
return Spectral1DLowLevelWCS()
| Spectral1DLowLevelWCS |
python | kamyu104__LeetCode-Solutions | Python/partition-array-into-k-distinct-groups.py | {
"start": 69,
"end": 463
} | class ____(object):
def partitionArray(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if len(nums)%k:
return False
group_cnt = len(nums)//k
cnt = collections.defaultdict(int)
for x in nums:
cnt[x] += 1
return all(x <= group_cnt for x in cnt.itervalues())
| Solution |
python | astropy__astropy | astropy/extern/ply/yacc.py | {
"start": 8727,
"end": 10276
} | class ____:
def __init__(self, s, stack=None):
self.slice = s
self.stack = stack
self.lexer = None
self.parser = None
def __getitem__(self, n):
if isinstance(n, slice):
return [s.value for s in self.slice[n]]
elif n >= 0:
return self.slice[n].value
else:
return self.stack[n].value
def __setitem__(self, n, v):
self.slice[n].value = v
def __getslice__(self, i, j):
return [s.value for s in self.slice[i:j]]
def __len__(self):
return len(self.slice)
def lineno(self, n):
return getattr(self.slice[n], 'lineno', 0)
def set_lineno(self, n, lineno):
self.slice[n].lineno = lineno
def linespan(self, n):
startline = getattr(self.slice[n], 'lineno', 0)
endline = getattr(self.slice[n], 'endlineno', startline)
return startline, endline
def lexpos(self, n):
return getattr(self.slice[n], 'lexpos', 0)
def set_lexpos(self, n, lexpos):
self.slice[n].lexpos = lexpos
def lexspan(self, n):
startpos = getattr(self.slice[n], 'lexpos', 0)
endpos = getattr(self.slice[n], 'endlexpos', startpos)
return startpos, endpos
def error(self):
raise SyntaxError
# -----------------------------------------------------------------------------
# == LRParser ==
#
# The LR Parsing engine.
# -----------------------------------------------------------------------------
| YaccProduction |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 24440,
"end": 24557
} | class ____(MixinOrigin, TestRefererMiddleware):
req_meta = {"referrer_policy": POLICY_ORIGIN}
| TestRequestMetaOrigin |
python | coleifer__peewee | tests/pwiz_integration.py | {
"start": 348,
"end": 449
} | class ____(TestModel):
username = CharField(primary_key=True)
id = IntegerField(default=0)
| User |
python | scipy__scipy | scipy/io/tests/test_idl.py | {
"start": 4434,
"end": 5821
} | class ____:
# Test that multi-dimensional arrays are read in with the correct dimensions
def test_1d(self):
s = readsav(path.join(DATA_PATH, 'array_float32_1d.sav'), verbose=False)
assert_equal(s.array1d.shape, (123, ))
def test_2d(self):
s = readsav(path.join(DATA_PATH, 'array_float32_2d.sav'), verbose=False)
assert_equal(s.array2d.shape, (22, 12))
def test_3d(self):
s = readsav(path.join(DATA_PATH, 'array_float32_3d.sav'), verbose=False)
assert_equal(s.array3d.shape, (11, 22, 12))
def test_4d(self):
s = readsav(path.join(DATA_PATH, 'array_float32_4d.sav'), verbose=False)
assert_equal(s.array4d.shape, (4, 5, 8, 7))
def test_5d(self):
s = readsav(path.join(DATA_PATH, 'array_float32_5d.sav'), verbose=False)
assert_equal(s.array5d.shape, (4, 3, 4, 6, 5))
def test_6d(self):
s = readsav(path.join(DATA_PATH, 'array_float32_6d.sav'), verbose=False)
assert_equal(s.array6d.shape, (3, 6, 4, 5, 3, 4))
def test_7d(self):
s = readsav(path.join(DATA_PATH, 'array_float32_7d.sav'), verbose=False)
assert_equal(s.array7d.shape, (2, 1, 2, 3, 4, 3, 2))
def test_8d(self):
s = readsav(path.join(DATA_PATH, 'array_float32_8d.sav'), verbose=False)
assert_equal(s.array8d.shape, (4, 3, 2, 1, 2, 3, 5, 4))
| TestArrayDimensions |
python | numba__numba | numba/tests/test_random.py | {
"start": 55403,
"end": 58051
} | class ____(BaseTest):
alpha = np.array([1, 1, 1, 2], dtype=np.float64)
def _check_sample(self, alpha, size, sample):
"""Check output structure"""
self.assertIsInstance(sample, np.ndarray)
self.assertEqual(sample.dtype, np.float64)
if size is None:
self.assertEqual(sample.size, len(alpha))
elif type(size) is int:
self.assertEqual(sample.shape, (size, len(alpha)))
else:
self.assertEqual(sample.shape, size + (len(alpha),))
"""Check statistical properties"""
for val in np.nditer(sample):
self.assertGreaterEqual(val, 0)
self.assertLessEqual(val, 1)
if size is None:
self.assertAlmostEqual(sample.sum(), 1, places=5)
else:
for totals in np.nditer(sample.sum(axis=-1)):
self.assertAlmostEqual(totals, 1, places=5)
def test_dirichlet_default(self):
"""
Test dirichlet(alpha, size=None)
"""
cfunc = jit(nopython=True)(numpy_dirichlet_default)
alphas = (
self.alpha,
tuple(self.alpha),
np.array([1, 1, 10000, 1], dtype=np.float64),
np.array([1, 1, 1.5, 1], dtype=np.float64),
)
for alpha in alphas:
res = cfunc(alpha)
self._check_sample(alpha, None, res)
def test_dirichlet(self):
"""
Test dirichlet(alpha, size=None)
"""
cfunc = jit(nopython=True)(numpy_dirichlet)
sizes = (None, (10,), (10, 10))
alphas = (
self.alpha,
tuple(self.alpha),
np.array([1, 1, 10000, 1], dtype=np.float64),
np.array([1, 1, 1.5, 1], dtype=np.float64),
)
for alpha, size in itertools.product(alphas, sizes):
res = cfunc(alpha, size)
self._check_sample(alpha, size, res)
def test_dirichlet_exceptions(self):
cfunc = jit(nopython=True)(numpy_dirichlet)
alpha = tuple((0, 1, 1))
with self.assertRaises(ValueError) as raises:
cfunc(alpha, 1)
self.assertIn("dirichlet: alpha must be > 0.0", str(raises.exception))
alpha = self.alpha
sizes = (True, 3j, 1.5, (1.5, 1), (3j, 1), (3j, 3j), (np.int8(3), np.int64(7)))
for size in sizes:
with self.assertRaises(TypingError) as raises:
cfunc(alpha, size)
self.assertIn(
"np.random.dirichlet(): size should be int or "
"tuple of ints or None, got",
str(raises.exception),
)
| TestRandomDirichlet |
python | plotly__plotly.py | plotly/graph_objs/_deprecations.py | {
"start": 19267,
"end": 20276
} | class ____(dict):
"""
plotly.graph_objs.Trace is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.Scatter
- plotly.graph_objs.Bar
- plotly.graph_objs.Area
- plotly.graph_objs.Histogram
- etc.
"""
def __init__(self, *args, **kwargs):
"""
plotly.graph_objs.Trace is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.Scatter
- plotly.graph_objs.Bar
- plotly.graph_objs.Area
- plotly.graph_objs.Histogram
- etc.
"""
warnings.warn(
"""plotly.graph_objs.Trace is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.Scatter
- plotly.graph_objs.Bar
- plotly.graph_objs.Area
- plotly.graph_objs.Histogram
- etc.
""",
DeprecationWarning,
)
super().__init__(*args, **kwargs)
| Trace |
python | mitsuhiko__rye | rye-devtools/src/rye_devtools/find_uv_downloads.py | {
"start": 480,
"end": 4593
} | class ____:
client: httpx.Client
RELEASE_URL = "https://api.github.com/repos/astral-sh/uv/releases"
ARCH = {
"x86_64": "x86_64",
"i686": "i686",
"aarch64": "aarch64",
}
GLIBC = {
"x86_64": "gnu",
"i686": "gnu",
"aarch64": "musl",
}
PLATFORM_ENV = {
"unknown-linux-gnu": ("linux", "gnu"),
"unknown-linux-musl": ("linux", "musl"),
"apple-darwin": ("macos", None),
"pc-windows-msvc": ("windows", None),
}
RE = re.compile(r"uv-(?P<arch>[^-]+)-(?P<plat_env>.+)(\.tar\.gz|\.zip)$")
def __init__(self, client: httpx.Client) -> None:
self.client = client
async def most_recent_downloads(
self, pages: int = 100
) -> AsyncIterator[UvDownload]:
highest_version = None
for page in range(1, pages):
log(f"fetching page {page}")
resp = await fetch(self.client, "%s?page=%d" % (self.RELEASE_URL, page))
rows = resp.json()
if not rows:
break
for row in rows:
version = Version.from_str(row["tag_name"])
if highest_version is None or highest_version < version:
for asset in row["assets"]:
url = asset["browser_download_url"]
if (triple := self.parse_triple(url)) is not None:
sha_resp = await fetch(self.client, url + ".sha256")
sha256 = sha_resp.text.split(" ")[0].strip()
yield UvDownload(
triple=triple,
version=version,
url=url,
sha256=sha256,
)
highest_version = version
@classmethod
def parse_triple(cls, url: str) -> PlatformTriple | None:
if (m := re.search(cls.RE, url)) is not None:
arch_str = m.group("arch")
plat_env_str = m.group("plat_env")
if arch_str in cls.ARCH and plat_env_str in cls.PLATFORM_ENV:
arch = cls.ARCH[arch_str]
plat, env = cls.PLATFORM_ENV[plat_env_str]
if env is None or env == cls.GLIBC[arch_str]:
return PlatformTriple(
arch=arch, platform=plat, environment=env, flavor=None
)
return None
def render(downloads: list[UvDownload]):
print("// Generated by rye-devtools. DO NOT EDIT.")
print(
"// To regenerate, run `rye run uv-downloads > rye/src/sources/generated/uv_downloads.inc` from the root of the repository."
)
print("use std::borrow::Cow;")
print("pub const UV_DOWNLOADS: &[UvDownload] = &[")
for download in downloads:
triple = download.triple
version = download.version
sha = download.sha256
url = download.url
print(
f' UvDownload {{arch: Cow::Borrowed("{triple.arch}"), os: Cow::Borrowed("{triple.platform}"), major: {version.major}, minor: {version.minor}, patch: {version.patch}, suffix: None, url: Cow::Borrowed("{url}"), sha256: Cow::Borrowed("{sha}") }},'
)
print("];")
async def async_main():
token = os.environ.get("GITHUB_TOKEN")
if not token:
try:
token = open("token.txt").read().strip()
except Exception:
pass
if not token:
log("Please set GITHUB_TOKEN environment variable or create a token.txt file.")
sys.exit(1)
headers = {
"X-GitHub-Api-Version": "2022-11-28",
"Authorization": "Bearer " + token,
}
log("Fetching all uv downloads.")
async with httpx.AsyncClient(follow_redirects=True, headers=headers) as client:
finder = UvDownloads(client)
downloads = [download async for download in finder.most_recent_downloads()]
log("Generating code.")
render(downloads)
def main():
asyncio.run(async_main())
if __name__ == "__main__":
main()
| UvDownloads |
python | Netflix__metaflow | metaflow/plugins/project_decorator.py | {
"start": 340,
"end": 7592
} | class ____(FlowDecorator):
"""
Specifies what flows belong to the same project.
A project-specific namespace is created for all flows that
use the same `@project(name)`.
Parameters
----------
name : str
Project name. Make sure that the name is unique amongst all
projects that use the same production scheduler. The name may
contain only lowercase alphanumeric characters and underscores.
branch : Optional[str], default None
The branch to use. If not specified, the branch is set to
`user.<username>` unless `production` is set to `True`. This can
also be set on the command line using `--branch` as a top-level option.
It is an error to specify `branch` in the decorator and on the command line.
production : bool, default False
Whether or not the branch is the production branch. This can also be set on the
command line using `--production` as a top-level option. It is an error to specify
`production` in the decorator and on the command line.
The project branch name will be:
- if `branch` is specified:
- if `production` is True: `prod.<branch>`
- if `production` is False: `test.<branch>`
- if `branch` is not specified:
- if `production` is True: `prod`
- if `production` is False: `user.<username>`
MF Add To Current
-----------------
project_name -> str
The name of the project assigned to this flow, i.e. `X` in `@project(name=X)`.
@@ Returns
-------
str
Project name.
project_flow_name -> str
The flow name prefixed with the current project and branch. This name identifies
the deployment on a production scheduler.
@@ Returns
-------
str
Flow name prefixed with project information.
branch_name -> str
The current branch, i.e. `X` in `--branch=X` set during deployment or run.
@@ Returns
-------
str
Branch name.
is_user_branch -> bool
True if the flow is deployed without a specific `--branch` or a `--production`
flag.
@@ Returns
-------
bool
True if the deployment does not correspond to a specific branch.
is_production -> bool
True if the flow is deployed with the `--production` flag
@@ Returns
-------
bool
True if the flow is deployed with `--production`.
"""
name = "project"
options = {
"production": dict(
is_flag=True,
default=False,
show_default=True,
help="Use the @project's production branch. To "
"use a custom branch, use --branch.",
),
"branch": dict(
default=None,
show_default=False,
help="Use the given branch name under @project. "
"The default is the user name if --production is "
"not specified.",
),
}
defaults = {"name": None, **{k: v["default"] for k, v in options.items()}}
def flow_init(
self, flow, graph, environment, flow_datastore, metadata, logger, echo, options
):
self._option_values = options
project_name = self.attributes.get("name")
for op in options:
if (
op in self._user_defined_attributes
and options[op] != self.defaults[op]
and self.attributes[op] != options[op]
):
# Exception if:
# - the user provides a value in the attributes field
# - AND the user provided a value in the command line (non default)
# - AND the values are different
# Note that this won't raise an error if the user provided the default
# value in the command line and provided one in attribute but although
# slightly inconsistent, it is not incorrect.
raise MetaflowException(
"You cannot pass %s as both a command-line argument and an attribute "
"of the @project decorator." % op
)
if "branch" in self._user_defined_attributes:
project_branch = self.attributes["branch"]
else:
project_branch = options["branch"]
if "production" in self._user_defined_attributes:
project_production = self.attributes["production"]
else:
project_production = options["production"]
project_flow_name, branch_name = format_name(
flow.name,
project_name,
project_production,
project_branch,
get_username(),
)
is_user_branch = project_branch is None and not project_production
echo(
"Project: *%s*, Branch: *%s*" % (project_name, branch_name),
fg="magenta",
highlight="green",
)
current._update_env(
{
"project_name": project_name,
"branch_name": branch_name,
"is_user_branch": is_user_branch,
"is_production": project_production,
"project_flow_name": project_flow_name,
}
)
metadata.add_sticky_tags(
sys_tags=["project:%s" % project_name, "project_branch:%s" % branch_name]
)
def get_top_level_options(self):
return list(self._option_values.items())
def format_name(flow_name, project_name, deploy_prod, given_branch, user_name):
if not project_name:
# an empty string is not a valid project name
raise MetaflowException(
"@project needs a name. " "Try @project(name='some_name')"
)
elif re.search(VALID_NAME_RE, project_name):
raise MetaflowException(
"The @project name must contain only "
"lowercase alphanumeric characters "
"and underscores."
)
elif len(project_name) > VALID_NAME_LEN:
raise MetaflowException(
"The @project name must be shorter than " "%d characters." % VALID_NAME_LEN
)
if given_branch:
if re.search(VALID_NAME_RE, given_branch):
raise MetaflowException(
"The branch name must contain only "
"lowercase alphanumeric characters "
"and underscores."
)
elif len(given_branch) > VALID_NAME_LEN:
raise MetaflowException(
"Branch name is too long. "
"The maximum is %d characters." % VALID_NAME_LEN
)
if deploy_prod:
branch = "prod.%s" % given_branch
else:
branch = "test.%s" % given_branch
elif deploy_prod:
branch = "prod"
else:
# For AWS Step Functions, we set the branch to the value of
# environment variable `METAFLOW_OWNER`, since AWS Step Functions
# has no notion of user name.
branch = "user.%s" % os.environ.get("METAFLOW_OWNER", user_name)
return ".".join((project_name, branch, flow_name)), branch
| ProjectDecorator |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_selection.py | {
"start": 42128,
"end": 42746
} | class ____(AssetSelection):
"""Used to represent a UI asset selection by column. This should not be resolved against
an in-process asset graph.
"""
selected_column: Optional[str]
def resolve_inner(
self, asset_graph: BaseAssetGraph, allow_missing: bool
) -> AbstractSet[AssetKey]:
"""This should not be invoked in user code."""
raise NotImplementedError
def to_selection_str(self) -> str:
if self.selected_column is None:
return "column:<null>"
return f'column:"{self.selected_column}"'
@whitelist_for_serdes
@record
| ColumnAssetSelection |
python | matplotlib__matplotlib | galleries/examples/event_handling/viewlims.py | {
"start": 795,
"end": 3249
} | class ____:
def __init__(self, h=500, w=500, niter=50, radius=2., power=2):
self.height = h
self.width = w
self.niter = niter
self.radius = radius
self.power = power
def compute_image(self, xlim, ylim):
self.x = np.linspace(*xlim, self.width)
self.y = np.linspace(*ylim, self.height).reshape(-1, 1)
c = self.x + 1.0j * self.y
threshold_time = np.zeros((self.height, self.width))
z = np.zeros(threshold_time.shape, dtype=complex)
mask = np.ones(threshold_time.shape, dtype=bool)
for i in range(self.niter):
z[mask] = z[mask]**self.power + c[mask]
mask = (np.abs(z) < self.radius)
threshold_time += mask
return threshold_time
def ax_update(self, ax):
ax.set_autoscale_on(False) # Otherwise, infinite loop
# Get the number of points from the number of pixels in the window
self.width, self.height = ax.patch.get_window_extent().size.round().astype(int)
# Update the image object with our new data and extent
ax.images[-1].set(data=self.compute_image(ax.get_xlim(), ax.get_ylim()),
extent=(*ax.get_xlim(), *ax.get_ylim()))
ax.figure.canvas.draw_idle()
md = MandelbrotDisplay()
fig1, (ax_full, ax_zoom) = plt.subplots(1, 2)
ax_zoom.imshow([[0]], origin="lower") # Empty initial image.
ax_zoom.set_title("Zoom here")
rect = Rectangle(
[0, 0], 0, 0, facecolor="none", edgecolor="black", linewidth=1.0)
ax_full.add_patch(rect)
def update_rect(rect, ax): # Let the rectangle track the bounds of the zoom axes.
xlo, xhi = ax.get_xlim()
ylo, yhi = ax.get_ylim()
rect.set_bounds((xlo, ylo, xhi - xlo, yhi - ylo))
ax.figure.canvas.draw_idle()
# Connect for changing the view limits.
ax_zoom.callbacks.connect("xlim_changed", functools.partial(update_rect, rect))
ax_zoom.callbacks.connect("ylim_changed", functools.partial(update_rect, rect))
ax_zoom.callbacks.connect("xlim_changed", md.ax_update)
ax_zoom.callbacks.connect("ylim_changed", md.ax_update)
# Initialize: trigger image computation by setting view limits; set colormap limits;
# copy image to full view.
ax_zoom.set(xlim=(-2, .5), ylim=(-1.25, 1.25))
im = ax_zoom.images[0]
ax_zoom.images[0].set(clim=(im.get_array().min(), im.get_array().max()))
ax_full.imshow(im.get_array(), extent=im.get_extent(), origin="lower")
plt.show()
| MandelbrotDisplay |
python | kamyu104__LeetCode-Solutions | Python/checking-existence-of-edge-length-limited-paths.py | {
"start": 876,
"end": 1659
} | class ____(object):
def distanceLimitedPathsExist(self, n, edgeList, queries):
"""
:type n: int
:type edgeList: List[List[int]]
:type queries: List[List[int]]
:rtype: List[bool]
"""
for i, q in enumerate(queries):
q.append(i)
edgeList.sort(key=lambda x: x[2])
queries.sort(key=lambda x: x[2])
union_find = UnionFind(n)
result = [False]*len(queries)
curr = 0
for u, v, w, i in queries:
while curr < len(edgeList) and edgeList[curr][2] < w:
union_find.union_set(edgeList[curr][0], edgeList[curr][1])
curr += 1
result[i] = union_find.find_set(u) == union_find.find_set(v)
return result
| Solution |
python | kamyu104__LeetCode-Solutions | Python/average-waiting-time.py | {
"start": 29,
"end": 338
} | class ____(object):
def averageWaitingTime(self, customers):
"""
:type customers: List[List[int]]
:rtype: float
"""
avai = wait = 0.0
for a, t in customers:
avai = max(avai, a)+t
wait += avai-a
return wait/len(customers)
| Solution |
python | crytic__slither | slither/tools/mutator/mutators/MVIE.py | {
"start": 269,
"end": 2699
} | class ____(AbstractMutator): # pylint: disable=too-few-public-methods
NAME = "MVIE"
HELP = "variable initialization using an expression"
def _mutate(self) -> Dict:
result: Dict = {}
variable: Variable
# Create fault for state variables declaration
for variable in self.contract.state_variables_declared:
if variable.initialized:
# Cannot remove the initialization of constant variables
if variable.is_constant:
continue
if not isinstance(variable.expression, Literal):
# Get the string
start = variable.source_mapping.start
stop = variable.expression.source_mapping.start
old_str = variable.source_mapping.content
new_str = old_str[: old_str.find("=")]
line_no = variable.node_initialization.source_mapping.lines
if not line_no[0] in self.dont_mutate_line:
create_patch_with_line(
result,
self.in_file,
start,
stop + variable.expression.source_mapping.length,
old_str,
new_str,
line_no[0],
)
for function in self.contract.functions_and_modifiers_declared:
for variable in function.local_variables:
if variable.initialized and not isinstance(variable.expression, Literal):
# Get the string
start = variable.source_mapping.start
stop = variable.expression.source_mapping.start
old_str = variable.source_mapping.content
new_str = old_str[: old_str.find("=")]
line_no = variable.source_mapping.lines
if not line_no[0] in self.dont_mutate_line:
create_patch_with_line(
result,
self.in_file,
start,
stop + variable.expression.source_mapping.length,
old_str,
new_str,
line_no[0],
)
return result
| MVIE |
python | cython__cython | Cython/Compiler/Tests/TestStringEncoding.py | {
"start": 75,
"end": 1068
} | class ____(unittest.TestCase):
"""
Test the StringEncoding module.
"""
def test_string_contains_lone_surrogates(self):
self.assertFalse(StringEncoding.string_contains_lone_surrogates("abc"))
self.assertFalse(StringEncoding.string_contains_lone_surrogates("\uABCD"))
self.assertFalse(StringEncoding.string_contains_lone_surrogates("\N{SNOWMAN}"))
self.assertTrue(StringEncoding.string_contains_lone_surrogates("\uD800\uDFFF"))
obfuscated_surrogate_pair = ("\uDFFF" + "\uD800")[::-1]
self.assertTrue(StringEncoding.string_contains_lone_surrogates(obfuscated_surrogate_pair))
self.assertTrue(StringEncoding.string_contains_lone_surrogates("\uD800"))
self.assertTrue(StringEncoding.string_contains_lone_surrogates("\uDFFF"))
self.assertTrue(StringEncoding.string_contains_lone_surrogates("\uDFFF\uD800"))
self.assertTrue(StringEncoding.string_contains_lone_surrogates("\uD800x\uDFFF"))
| StringEncodingTest |
python | realpython__materials | python-protocol/animals_v1.py | {
"start": 0,
"end": 197
} | class ____:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
def drink(self):
print(f"{self.name} is drinking.")
| Animal |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 7029,
"end": 7402
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layer1 = torch.nn.Linear(10, 10)
self.layer2 = None
self.train(True)
def forward(self, x):
if self.layer1 is not None:
x = self.layer1(x)
if self.layer2 is not None:
x = self.layer2(x)
return x
| IsNoneLayer |
python | pandas-dev__pandas | pandas/tests/base/test_constructors.py | {
"start": 2551,
"end": 3037
} | class ____:
def test_mixin(self):
class T(NoNewAttributesMixin):
pass
t = T()
assert not hasattr(t, "__frozen")
t.a = "test"
assert t.a == "test"
t._freeze()
assert "__frozen" in dir(t)
assert getattr(t, "__frozen")
msg = "You cannot add any new attribute"
with pytest.raises(AttributeError, match=msg):
t.b = "test"
assert not hasattr(t, "b")
| TestNoNewAttributesMixin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.