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 | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/reduction_ops_test.py | {
"start": 29503,
"end": 33892
} | class ____(test.TestCase):
def _compare(self, x, reduction_axes, keepdims, use_gpu=False):
np_ans = x
if reduction_axes is None:
np_ans = np.amin(np_ans, keepdims=keepdims)
else:
for ra in reduction_axes[::-1]:
np_ans = np.amin(np_ans, axis=ra, keepdims=keepdims)
with self.cached_session(use_gpu=use_gpu):
if reduction_axes is not None:
reduction_axes = np.array(reduction_axes).astype(np.int32)
tf_ans = math_ops.reduce_min(x, reduction_axes, keepdims)
out = self.evaluate(tf_ans)
self.assertAllClose(np_ans, out)
self.assertShapeEqual(np_ans, tf_ans)
def _compareAll(self, x, reduction_axes):
self._compare(x, reduction_axes, False, use_gpu=True)
self._compare(x, reduction_axes, True, use_gpu=True)
def testAxesType(self):
for dtype in [dtypes.int64, dtypes.int32]:
with self.cached_session():
v = math_ops.reduce_min([0, 0], constant_op.constant(0, dtype=dtype))
tf_v = self.evaluate(v)
self.assertAllEqual(tf_v, 0)
@test_util.disable_xla("b/168718272") # XLA handling of NaN is inconsistent
def testSpecialValues(self):
for dtype in [np.float32, np.float64]:
for size in range(1, 4):
for arr in itertools.product([-np.inf, 1., np.nan, np.inf],
repeat=size):
self._compareAll(np.array(arr, dtype=dtype), None)
def testFloatReduce3D(self):
# Create a 3D array of floats and reduce across all possible
# dimensions
np_arr = np.arange(1, 31).reshape([2, 3, 5]).astype(np.float32)
self._compareAll(np_arr, None)
self._compareAll(np_arr, [])
self._compareAll(np_arr, [0])
self._compareAll(np_arr, [1])
self._compareAll(np_arr, [2])
self._compareAll(np_arr, [0, 1])
self._compareAll(np_arr, [1, 2])
self._compareAll(np_arr, [0, 2])
self._compareAll(np_arr, [0, 1, 2])
def testDoubleReduce3D(self):
# Create a 3D array of doubles and reduce across all possible
# dimensions
np_arr = np.arange(1, 31).reshape([2, 3, 5]).astype(np.float64)
self._compareAll(np_arr, None)
self._compareAll(np_arr, [])
self._compareAll(np_arr, [0])
self._compareAll(np_arr, [1])
self._compareAll(np_arr, [2])
self._compareAll(np_arr, [0, 1])
self._compareAll(np_arr, [1, 2])
self._compareAll(np_arr, [0, 2])
self._compareAll(np_arr, [0, 1, 2])
@test_util.run_deprecated_v1
def testGradient(self):
s = [2, 3, 4, 2]
x = np.arange(1.0, 49.0).reshape(s).astype(np.float64)
with self.cached_session():
t = ops.convert_to_tensor(x)
su = math_ops.reduce_min(t, [1, 2])
jacob_t, jacob_n = gradient_checker.compute_gradient(
t, s, su, [2, 2], x_init_value=x, delta=1)
self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8)
@test_util.run_deprecated_v1
def testGradient2(self):
s = [2, 3, 4, 2]
x = np.arange(1.0, 49.0).reshape(s).astype(np.float64)
with self.cached_session():
t = ops.convert_to_tensor(x)
su = math_ops.reduce_min(t, [1])
jacob_t, jacob_n = gradient_checker.compute_gradient(
t, s, su, [2, 4, 2], x_init_value=x, delta=1)
self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8)
@test_util.run_deprecated_v1
def testGradient3(self):
s = [2, 3, 4, 2]
x = np.arange(1.0, 49.0).reshape(s).astype(np.float64)
with self.cached_session():
t = ops.convert_to_tensor(x)
su = math_ops.reduce_min(t, [2])
jacob_t, jacob_n = gradient_checker.compute_gradient(
t, s, su, [2, 3, 2], x_init_value=x, delta=1)
self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8)
@test_util.run_deprecated_v1
def testGradient4(self):
s = [2, 3, 4, 2]
x = np.arange(1.0, 49.0).reshape(s).astype(np.float64)
with self.cached_session():
t = ops.convert_to_tensor(x)
su = math_ops.reduce_min(t)
jacob_t, jacob_n = gradient_checker.compute_gradient(
t, s, su, [1], x_init_value=x, delta=1)
self.assertAllClose(jacob_t, jacob_n, rtol=1e-8, atol=1e-8)
@test_util.run_deprecated_v1
def testEmptyGradients(self):
with self.cached_session():
x = array_ops.zeros([0, 3])
y = math_ops.reduce_min(x, [1])
error = gradient_checker.compute_gradient_error(x, [0, 3], y, [0])
self.assertEqual(error, 0)
| MinReductionTest |
python | dask__dask | dask/array/tests/test_dispatch.py | {
"start": 7200,
"end": 8283
} | class ____(np.lib.mixins.NDArrayOperatorsMixin):
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
outputs = kwargs.get("out", ())
for item in inputs + outputs:
if hasattr(item, "__array_ufunc__") and not isinstance(
item, (np.ndarray, Array, UnknownScalarThatUnderstandsArrayOps)
):
return NotImplemented
# This is a dummy scalar that just returns a new object for every op
return UnknownScalarThatUnderstandsArrayOps()
@pytest.mark.parametrize("arr", [da.from_array([1, 2]), np.asarray([1, 2])])
def test_delegation_unknown_scalar_that_understands_arr_ops(arr):
s = UnknownScalarThatUnderstandsArrayOps()
assert type(arr * s) == UnknownScalarThatUnderstandsArrayOps
assert type(s * arr) == UnknownScalarThatUnderstandsArrayOps
# Explicit tests of numpy NEP-13 dispatching
assert type(np.multiply(s, arr)) == UnknownScalarThatUnderstandsArrayOps
assert type(np.multiply(arr, s)) == UnknownScalarThatUnderstandsArrayOps
| UnknownScalarThatUnderstandsArrayOps |
python | realpython__materials | python-312/typing/quiz.py | {
"start": 145,
"end": 502
} | class ____:
question: str
answer: str
@classmethod
def from_file(cls, path: pathlib.Path) -> Self:
question, answer, *_ = path.read_text(encoding="utf-8").split("\n")
return cls(question, answer)
def ask(self) -> bool:
answer = input(f"\n{self.question} ")
return answer == self.answer
@dataclass
| Question |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/plus/config.py | {
"start": 454,
"end": 1660
} | class ____(NamedTuple):
path: Path
raw_config: Mapping[str, Any]
plus_config: Mapping[str, Any]
is_dg_config: bool
DAGSTER_CLOUD_BASE_URL = "https://dagster.cloud"
def _get_dagster_plus_config_path_and_raw_config() -> Optional[DagsterPlusConfigInfo]:
cloud_config_path = get_dagster_cloud_cli_config_path()
dg_config_path = get_dg_config_path()
dg_config = load_config(dg_config_path) if dg_config_path.exists() else None
dg_plus_config = dg_config.get("cli", {}).get("plus", {}) if dg_config else None
cloud_config = load_config(cloud_config_path) if cloud_config_path.exists() else None
if dg_plus_config and cloud_config:
raise Exception(
f"Found Dagster Plus config in both {dg_config_path} and {cloud_config_path}. Please consolidate your config files."
)
if cloud_config is not None:
return DagsterPlusConfigInfo(
cloud_config_path, cloud_config, cloud_config, is_dg_config=False
)
elif dg_config is not None and dg_plus_config is not None:
return DagsterPlusConfigInfo(dg_config_path, dg_config, dg_plus_config, is_dg_config=True)
return None
@dataclass()
| DagsterPlusConfigInfo |
python | hynek__structlog | tests/test_stdlib.py | {
"start": 31046,
"end": 44837
} | class ____:
"""
These are all integration tests because they're all about integration.
"""
def test_foreign_delegate(self, capsys):
"""
If foreign_pre_chain is None, non-structlog log entries are delegated
to logging. The processor chain's event dict is invoked with
`_from_structlog=False`
"""
calls = configure_logging(None)
logging.getLogger().warning("foo")
assert ("", "foo [in test_foreign_delegate]\n") == capsys.readouterr()
assert calls[0]["_from_structlog"] is False
assert isinstance(calls[0]["_record"], logging.LogRecord)
def test_clears_args(self, capsys):
"""
We render our log records before sending it back to logging. Therefore
we must clear `LogRecord.args` otherwise the user gets an
`TypeError: not all arguments converted during string formatting.` if
they use positional formatting in stdlib logging.
"""
configure_logging(None)
logging.getLogger().warning("hello %s.", "world")
assert (
"",
"hello world. [in test_clears_args]\n",
) == capsys.readouterr()
def test_pass_foreign_args_true_sets_positional_args_key(self):
"""
If `pass_foreign_args` is `True` we set the `positional_args` key in
the `event_dict` before clearing args.
"""
test_processor = call_recorder(lambda _, __, event_dict: event_dict)
configure_logging((test_processor,), pass_foreign_args=True)
positional_args = {"foo": "bar"}
logging.getLogger().info("okay %(foo)s", positional_args)
event_dict = test_processor.call_args_list[0].args[2]
assert "positional_args" in event_dict
assert positional_args == event_dict["positional_args"]
def test_log_dict(self, capsys):
"""
dicts can be logged with std library loggers.
"""
configure_logging(None)
logging.getLogger().warning({"foo": "bar"})
assert (
"",
"{'foo': 'bar'} [in test_log_dict]\n",
) == capsys.readouterr()
def test_foreign_pre_chain(self, capsys):
"""
If foreign_pre_chain is an iterable, it's used to pre-process
non-structlog log entries.
"""
configure_logging([add_log_level])
logging.getLogger().warning("foo")
assert (
"",
"[warning ] foo [in test_foreign_pre_chain]\n",
) == capsys.readouterr()
def test_foreign_pre_chain_add_logger_name(self, capsys):
"""
foreign_pre_chain works with add_logger_name processor.
"""
configure_logging((add_logger_name,))
logging.getLogger("sample-name").warning("foo")
assert (
"",
"foo [sample-name] [in test_foreign_pr"
"e_chain_add_logger_name]\n",
) == capsys.readouterr()
def test_foreign_chain_can_pass_dictionaries_without_excepting(
self, capsys
):
"""
If a foreign logger passes a dictionary to a logging function,
check we correctly identify that it did not come from structlog.
"""
configure_logging(None)
configure(
processors=[ProcessorFormatter.wrap_for_formatter],
logger_factory=LoggerFactory(),
wrapper_class=BoundLogger,
)
logging.getLogger().warning({"foo": "bar"})
assert (
"",
"{'foo': 'bar'} [in "
"test_foreign_chain_can_pass_dictionaries_without_excepting]\n",
) == capsys.readouterr()
def test_foreign_pre_chain_gets_exc_info(self):
"""
If non-structlog record contains exc_info, foreign_pre_chain functions
have access to it.
"""
test_processor = call_recorder(lambda _, __, event_dict: event_dict)
configure_logging((test_processor,), renderer=KeyValueRenderer())
try:
raise RuntimeError("oh no")
except Exception:
logging.getLogger().exception("okay")
event_dict = test_processor.call_args_list[0].args[2]
assert "exc_info" in event_dict
assert isinstance(event_dict["exc_info"], tuple)
def test_foreign_pre_chain_sys_exc_info(self):
"""
If a foreign_pre_chain function accesses sys.exc_info(),
ProcessorFormatter should not have changed it.
"""
class MyError(Exception):
pass
def add_excinfo(logger, log_method, event_dict):
event_dict["exc_info"] = sys.exc_info()
return event_dict
test_processor = call_recorder(lambda _, __, event_dict: event_dict)
configure_logging(
(add_excinfo, test_processor), renderer=KeyValueRenderer()
)
try:
raise MyError("oh no")
except Exception:
logging.getLogger().error("okay")
event_dict = test_processor.call_args_list[0].args[2]
assert MyError is event_dict["exc_info"][0]
def test_other_handlers_get_original_record(self):
"""
Logging handlers that come after the handler with ProcessorFormatter
should receive original, unmodified record.
"""
configure_logging(None)
handler1 = logging.StreamHandler()
handler1.setFormatter(ProcessorFormatter(JSONRenderer()))
handler2 = stub(
handle=call_recorder(lambda record: None),
level=logging.INFO,
)
logger = logging.getLogger()
logger.addHandler(handler1)
logger.addHandler(handler2)
logger.info("meh")
assert 1 == len(handler2.handle.call_args_list)
handler2_record = handler2.handle.call_args_list[0].args[0]
assert "meh" == handler2_record.msg
@pytest.mark.parametrize("keep", [True, False])
def test_formatter_unsets_exc_info(self, capsys, keep):
"""
Stack traces doesn't get printed outside of the json document when
keep_exc_info are set to False but preserved if set to True.
"""
configure_logging(None)
logger = logging.getLogger()
def format_exc_info_fake(logger, name, event_dict):
del event_dict["exc_info"]
event_dict["exception"] = "Exception!"
return event_dict
formatter = ProcessorFormatter(
processor=JSONRenderer(),
keep_stack_info=keep,
keep_exc_info=keep,
foreign_pre_chain=[format_exc_info_fake],
)
logger.handlers[0].setFormatter(formatter)
try:
raise RuntimeError("oh no")
except Exception:
logging.getLogger().exception("seen worse")
out, err = capsys.readouterr()
assert "" == out
if keep is False:
assert (
'{"event": "seen worse", "exception": "Exception!"}\n'
) == err
else:
assert "Traceback (most recent call last):" in err
@pytest.mark.parametrize("keep", [True, False])
def test_formatter_unsets_stack_info(self, capsys, keep):
"""
Stack traces doesn't get printed outside of the json document when
keep_stack_info are set to False but preserved if set to True.
"""
configure_logging(None)
logger = logging.getLogger()
formatter = ProcessorFormatter(
processor=JSONRenderer(),
keep_stack_info=keep,
keep_exc_info=keep,
foreign_pre_chain=[],
)
logger.handlers[0].setFormatter(formatter)
logging.getLogger().warning("have a stack trace", stack_info=True)
out, err = capsys.readouterr()
assert "" == out
if keep is False:
assert 1 == err.count("Stack (most recent call last):")
else:
assert 2 == err.count("Stack (most recent call last):")
def test_native(self, capsys):
"""
If the log entry comes from structlog, it's unpackaged and processed.
"""
eds = configure_logging(None)
get_logger().warning("foo")
assert (
"",
"[warning ] foo [in test_native]\n",
) == capsys.readouterr()
assert eds[0]["_from_structlog"] is True
assert isinstance(eds[0]["_record"], logging.LogRecord)
def test_native_logger(self, capsys):
"""
If the log entry comes from structlog, it's unpackaged and processed.
"""
logger = logging.getLogger()
eds = configure_logging(None, logger=logger)
get_logger().warning("foo")
assert (
"",
"[warning ] foo [in test_native_logger]\n",
) == capsys.readouterr()
assert eds[0]["_from_structlog"] is True
assert isinstance(eds[0]["_record"], logging.LogRecord)
def test_foreign_pre_chain_filter_by_level(self, capsys):
"""
foreign_pre_chain works with filter_by_level processor.
"""
logger = logging.getLogger()
configure_logging([filter_by_level], logger=logger)
configure(
processors=[ProcessorFormatter.wrap_for_formatter],
logger_factory=LoggerFactory(),
wrapper_class=BoundLogger,
)
logger.warning("foo")
assert (
"",
"foo [in test_foreign_pre_chain_filter_by_level]\n",
) == capsys.readouterr()
def test_processor_and_processors(self):
"""
Passing both processor and processors raises a TypeError.
"""
with pytest.raises(TypeError, match="mutually exclusive"):
ProcessorFormatter(processor=1, processors=[1])
def test_no_renderer(self):
"""
Passing neither processor nor processors raises a TypeError.
"""
with pytest.raises(TypeError, match="must be passed"):
ProcessorFormatter()
def test_remove_processors_meta(self):
"""
remove_processors_meta removes _record and _from_structlog. And only
them.
"""
assert {"foo": "bar"} == ProcessorFormatter.remove_processors_meta(
None,
None,
{"foo": "bar", "_record": "foo", "_from_structlog": True},
)
def test_non_string_message_warning(self):
"""
A warning is raised if the last processor in
ProcessorFormatter.processors doesn't return a string.
"""
configure_logging(None)
logger = logging.getLogger()
formatter = ProcessorFormatter(
processors=[lambda *args, **kwargs: {"foo": "bar"}],
)
logger.handlers[0].setFormatter(formatter)
with pytest.warns(
RuntimeWarning,
match="The last processor in ProcessorFormatter.processors must return a string",
):
logger.info("baz")
def test_logrecord_exc_info(self):
"""
LogRecord.exc_info is set consistently for structlog and non-structlog
log records.
"""
configure_logging(None)
# This doesn't test ProcessorFormatter itself directly, but it's
# relevant to setups where ProcessorFormatter is used, i.e. where
# handlers will receive LogRecord objects that come from both structlog
# and non-structlog loggers.
records: dict[str, logging.LogRecord] = {}
class DummyHandler(logging.Handler):
def emit(self, record):
# Don't do anything; just store the record in the records dict
# by its message, so we can assert things about it.
if isinstance(record.msg, dict):
records[record.msg["event"]] = record
else:
records[record.msg] = record
stdlib_logger = logging.getLogger()
structlog_logger = get_logger()
# It doesn't matter which logger we add the handler to here.
stdlib_logger.addHandler(DummyHandler())
try:
raise Exception("foo")
except Exception:
stdlib_logger.exception("bar")
structlog_logger.exception("baz")
stdlib_record = records.pop("bar")
assert "bar" == stdlib_record.msg
assert stdlib_record.exc_info
assert Exception is stdlib_record.exc_info[0]
assert ("foo",) == stdlib_record.exc_info[1].args
structlog_record = records.pop("baz")
assert "baz" == structlog_record.msg["event"]
assert True is structlog_record.msg["exc_info"]
assert structlog_record.exc_info
assert Exception is structlog_record.exc_info[0]
assert ("foo",) == structlog_record.exc_info[1].args
assert not records
def test_use_get_message_false(self):
"""
If use_get_message_is False, the event is obtained using
str(record.msg) instead of calling record.getMessage. That means
positional formatting is not performed.
"""
event_dicts = []
def capture(_, __, ed):
event_dicts.append(ed.copy())
return str(ed)
proc = ProcessorFormatter(processors=[capture], use_get_message=False)
record = logging.LogRecord(
"foo",
logging.INFO,
"path.py",
42,
"le msg: %s",
("keep separate",),
None,
)
assert proc.format(record)
assert "le msg: %s" == event_dicts[0]["event"]
@pytest_asyncio.fixture(name="abl")
async def _abl(cl):
return AsyncBoundLogger(cl, context={}, processors=[])
| TestProcessorFormatter |
python | qdrant__qdrant-client | qdrant_client/local/multi_distances.py | {
"start": 1917,
"end": 8014
} | class ____:
def __init__(self, context_pairs: list[MultiContextPair]):
self.context_pairs = context_pairs
MultiQueryVector = Union[
MultiDiscoveryQuery,
MultiContextQuery,
MultiRecoQuery,
]
def calculate_multi_distance(
query_matrix: types.NumpyArray,
matrices: list[types.NumpyArray],
distance_type: models.Distance,
) -> types.NumpyArray:
assert not np.isnan(query_matrix).any(), "Query matrix must not contain NaN"
assert len(query_matrix.shape) == 2, "Query must be a matrix"
distances = calculate_multi_distance_core(query_matrix, matrices, distance_type)
if distance_type == models.Distance.EUCLID:
distances = np.sqrt(np.abs(distances))
elif distance_type == models.Distance.MANHATTAN:
distances = np.abs(distances)
return distances
def calculate_multi_distance_core(
query_matrix: types.NumpyArray,
matrices: list[types.NumpyArray],
distance_type: models.Distance,
) -> types.NumpyArray:
def euclidean(q: types.NumpyArray, m: types.NumpyArray, *_: Any) -> types.NumpyArray:
return -np.square(m - q, dtype=np.float32).sum(axis=-1, dtype=np.float32)
def manhattan(q: types.NumpyArray, m: types.NumpyArray, *_: Any) -> types.NumpyArray:
return -np.abs(m - q, dtype=np.float32).sum(axis=-1, dtype=np.float32)
assert not np.isnan(query_matrix).any(), "Query vector must not contain NaN"
similarities: list[float] = []
# Euclid and Manhattan are the only ones which are calculated differently during candidate selection
# in core, here we make sure to use the same internal similarity function as in core.
if distance_type in [models.Distance.EUCLID, models.Distance.MANHATTAN]:
query_matrix = query_matrix[:, np.newaxis]
dist_func = euclidean if distance_type == models.Distance.EUCLID else manhattan
else:
dist_func = calculate_distance # type: ignore
for matrix in matrices:
sim_matrix = dist_func(query_matrix, matrix, distance_type)
similarity = float(np.sum(np.max(sim_matrix, axis=-1)))
similarities.append(similarity)
return np.array(similarities)
def calculate_multi_recommend_best_scores(
query: MultiRecoQuery, matrices: list[types.NumpyArray], distance_type: models.Distance
) -> types.NumpyArray:
def get_best_scores(examples: list[types.NumpyArray]) -> types.NumpyArray:
matrix_count = len(matrices)
# Get scores to all examples
scores: list[types.NumpyArray] = []
for example in examples:
score = calculate_multi_distance_core(example, matrices, distance_type)
scores.append(score)
# Keep only max for each vector
if len(scores) == 0:
scores.append(np.full(matrix_count, -np.inf))
best_scores = np.array(scores, dtype=np.float32).max(axis=0)
return best_scores
pos = get_best_scores(query.positive)
neg = get_best_scores(query.negative)
# Choose from the best positive or the best negative,
# in both cases we apply sigmoid and then negate depending on the order
return np.where(
pos > neg,
np.fromiter((scaled_fast_sigmoid(xi) for xi in pos), pos.dtype),
np.fromiter((-scaled_fast_sigmoid(xi) for xi in neg), neg.dtype),
)
def calculate_multi_recommend_sum_scores(
query: MultiRecoQuery, matrices: list[types.NumpyArray], distance_type: models.Distance
) -> types.NumpyArray:
def get_sum_scores(examples: list[types.NumpyArray]) -> types.NumpyArray:
matrix_count = len(matrices)
scores: list[types.NumpyArray] = []
for example in examples:
score = calculate_multi_distance_core(example, matrices, distance_type)
scores.append(score)
if len(scores) == 0:
scores.append(np.zeros(matrix_count))
sum_scores = np.array(scores, dtype=np.float32).sum(axis=0)
return sum_scores
pos = get_sum_scores(query.positive)
neg = get_sum_scores(query.negative)
return pos - neg
def calculate_multi_discovery_ranks(
context: list[MultiContextPair],
matrices: list[types.NumpyArray],
distance_type: models.Distance,
) -> types.NumpyArray:
overall_ranks: types.NumpyArray = np.zeros(len(matrices), dtype=np.int32)
for pair in context:
# Get distances to positive and negative vectors
pos = calculate_multi_distance_core(pair.positive, matrices, distance_type)
neg = calculate_multi_distance_core(pair.negative, matrices, distance_type)
pair_ranks = np.array(
[
1 if is_bigger else 0 if is_equal else -1
for is_bigger, is_equal in zip(pos > neg, pos == neg)
]
)
overall_ranks += pair_ranks
return overall_ranks
def calculate_multi_discovery_scores(
query: MultiDiscoveryQuery, matrices: list[types.NumpyArray], distance_type: models.Distance
) -> types.NumpyArray:
ranks = calculate_multi_discovery_ranks(query.context, matrices, distance_type)
# Get distances to target
distances_to_target = calculate_multi_distance_core(query.target, matrices, distance_type)
sigmoided_distances = np.fromiter(
(scaled_fast_sigmoid(xi) for xi in distances_to_target), np.float32
)
return ranks + sigmoided_distances
def calculate_multi_context_scores(
query: MultiContextQuery, matrices: list[types.NumpyArray], distance_type: models.Distance
) -> types.NumpyArray:
overall_scores: types.NumpyArray = np.zeros(len(matrices), dtype=np.float32)
for pair in query.context_pairs:
# Get distances to positive and negative vectors
pos = calculate_multi_distance_core(pair.positive, matrices, distance_type)
neg = calculate_multi_distance_core(pair.negative, matrices, distance_type)
difference = pos - neg - EPSILON
pair_scores = np.fromiter(
(fast_sigmoid(xi) for xi in np.minimum(difference, 0.0)), np.float32
)
overall_scores += pair_scores
return overall_scores
| MultiContextQuery |
python | pytorch__pytorch | torch/_dynamo/variables/ctx_manager.py | {
"start": 1935,
"end": 5376
} | class ____(VariableTracker):
_nonvar_fields = {
"cm_obj",
"target_values",
"initial_values",
"state",
*VariableTracker._nonvar_fields,
}
def __init__(
self, target_values: Any, initial_values: Optional[Any] = None, **kwargs: Any
) -> None:
super().__init__(**kwargs)
self.target_values = target_values
self.initial_values = initial_values
def enter(self, tx: "InstructionTranslator") -> VariableTracker:
if hasattr(self, "_call_func"):
self._call_func(tx, self.target_values)
self.set_cleanup_hook(tx)
return variables.ConstantVariable.create(None)
def set_cleanup_hook(
self, tx: "InstructionTranslator", fn: Optional[Callable[..., Any]] = None
) -> None:
if fn is None:
def fn() -> None:
if hasattr(self, "_call_func"):
self._call_func(tx, self.initial_values)
self.cleanup_fn: Optional[Callable[..., Any]] = fn
tx.output.add_cleanup_hook(self.cleanup)
def exit(
self, tx: "InstructionTranslator", *args: VariableTracker
) -> VariableTracker:
self.cleanup_assert()
return variables.ConstantVariable.create(None)
def reconstruct_type(self, codegen: "PyCodegen") -> None:
codegen(
AttrSource(codegen.tx.import_source(self.module_name()), self.fn_name())
)
def reconstruct(self, codegen: "PyCodegen") -> None:
codegen.add_push_null(lambda: self.reconstruct_type(codegen))
target_values = self.target_values
if not target_values:
target_values = ()
codegen.extend_output([codegen.create_load_const(val) for val in target_values])
codegen.extend_output(create_call_function(len(target_values), False))
def module_name(self) -> str:
raise NotImplementedError("module_name called on base")
def fn_name(self) -> str:
raise NotImplementedError("fn_name called on base")
def call_function(
self,
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
assert len(args) == 1
assert isinstance(
args[0],
(
NestedUserFunctionVariable,
SkipFunctionVariable,
UserMethodVariable,
UserFunctionVariable,
),
)
if isinstance(args[0], NestedUserFunctionVariable):
return WrappedNestedUserFunctionVariable(args[0], self)
elif isinstance(args[0], SkipFunctionVariable):
return WrappedSkipFunctionVariable(args[0], self)
elif isinstance(args[0], UserMethodVariable):
return WrappedUserMethodVariable(args[0], self)
elif isinstance(args[0], UserFunctionVariable):
return WrappedUserFunctionVariable(args[0], self)
else:
raise AssertionError("Unexpected arg type")
def supports_graph_breaks(self) -> bool:
return True
def exit_on_graph_break(self) -> bool:
return True
def cleanup(self) -> None:
if self.cleanup_fn is not None:
self.cleanup_fn()
self.cleanup_fn = None
def cleanup_assert(self) -> None:
assert self.cleanup_fn, "multiple exits?"
self.cleanup()
| ContextWrappingVariable |
python | django__django | django/core/serializers/base.py | {
"start": 1074,
"end": 1786
} | class ____:
progress_width = 75
def __init__(self, output, total_count):
self.output = output
self.total_count = total_count
self.prev_done = 0
def update(self, count):
if not self.output:
return
perc = count * 100 // self.total_count
done = perc * self.progress_width // 100
if self.prev_done >= done:
return
self.prev_done = done
cr = "" if self.total_count == 1 else "\r"
self.output.write(
cr + "[" + "." * done + " " * (self.progress_width - done) + "]"
)
if done == self.progress_width:
self.output.write("\n")
self.output.flush()
| ProgressBar |
python | django__django | tests/auth_tests/test_models.py | {
"start": 8391,
"end": 9757
} | class ____(SimpleTestCase):
def test_has_usable_password(self):
"""
Passwords are usable even if they don't correspond to a hasher in
settings.PASSWORD_HASHERS.
"""
self.assertIs(User(password="some-gibbberish").has_usable_password(), True)
def test_normalize_username(self):
self.assertEqual(IntegerUsernameUser().normalize_username(123), 123)
def test_clean_normalize_username(self):
# The normalization happens in AbstractBaseUser.clean()
ohm_username = "iamtheΩ" # U+2126 OHM SIGN
for model in ("auth.User", "auth_tests.CustomUser"):
with self.subTest(model=model), self.settings(AUTH_USER_MODEL=model):
User = get_user_model()
user = User(**{User.USERNAME_FIELD: ohm_username, "password": "foo"})
user.clean()
username = user.get_username()
self.assertNotEqual(username, ohm_username)
self.assertEqual(
username, "iamtheΩ"
) # U+03A9 GREEK CAPITAL LETTER OMEGA
def test_default_email(self):
self.assertEqual(AbstractBaseUser.get_email_field_name(), "email")
def test_custom_email(self):
user = CustomEmailField()
self.assertEqual(user.get_email_field_name(), "email_address")
| AbstractBaseUserTests |
python | ipython__ipython | tests/test_formatters.py | {
"start": 455,
"end": 514
} | class ____(A):
def __repr__(self):
return "B()"
| B |
python | pytorch__pytorch | torch/onnx/_internal/exporter/_schemas.py | {
"start": 436,
"end": 2045
} | class ____:
def __repr__(self) -> str:
return "_EMPTY_DEFAULT"
_EMPTY_DEFAULT = _Empty()
# Map from python type to corresponding ONNX AttributeProto type
_PY_TYPE_TO_ATTR_TYPE = {
float: ir.AttributeType.FLOAT,
int: ir.AttributeType.INT,
str: ir.AttributeType.STRING,
bool: ir.AttributeType.INT,
ir.Tensor: ir.AttributeType.TENSOR,
ir.TensorProtocol: ir.AttributeType.TENSOR,
ir.Graph: ir.AttributeType.GRAPH,
ir.GraphProtocol: ir.AttributeType.GRAPH,
}
# Map from python type to corresponding ONNX AttributeProto type,
# for repeated (i.e., list of) values
_LIST_TYPE_TO_ATTR_TYPE = {
float: ir.AttributeType.FLOATS,
int: ir.AttributeType.INTS,
str: ir.AttributeType.STRINGS,
bool: ir.AttributeType.INTS,
ir.Tensor: ir.AttributeType.TENSORS,
ir.TensorProtocol: ir.AttributeType.TENSORS,
ir.Graph: ir.AttributeType.GRAPHS,
ir.GraphProtocol: ir.AttributeType.GRAPHS,
}
_ALL_VALUE_TYPES = (
{ir.TensorType(dtype) for dtype in ir.DataType}
| {ir.SequenceType(ir.TensorType(dtype)) for dtype in ir.DataType}
| {ir.OptionalType(ir.TensorType(dtype)) for dtype in ir.DataType}
)
# TypeAnnotationValue represents the (value of) valid type-annotations recognized
# by ONNX Script. Currently, it supports
# - float, int, str (primitive attribute types)
# - Sequence[float], Sequence[int], Sequence[str] (attribute types)
# - Tensor types
# - Sequence[Tensor] types
# - Union of above 2
# - TypeVars with above bounds
# - Above types with annotation attached
TypeAnnotationValue = Any
@dataclasses.dataclass(frozen=True)
| _Empty |
python | walkccc__LeetCode | solutions/311. Sparse Matrix Multiplication/311.py | {
"start": 0,
"end": 352
} | class ____:
def multiply(self, mat1: list[list[int]],
mat2: list[list[int]]) -> list[list[int]]:
m = len(mat1)
n = len(mat2)
l = len(mat2[0])
ans = [[0] * l for _ in range(m)]
for i in range(m):
for j in range(l):
for k in range(n):
ans[i][j] += mat1[i][k] * mat2[k][j]
return ans
| Solution |
python | dask__distributed | distributed/shuffle/_rechunk.py | {
"start": 5919,
"end": 6204
} | class ____(NamedTuple):
"""Information used to perform a partial rechunk along a single axis"""
#: Slice of the old chunks along this axis that belong to the partial
old: slice
#: Slice of the new chunks along this axis that belong to the partial
new: slice
| _Partial |
python | HIPS__autograd | examples/convnet.py | {
"start": 2027,
"end": 3202
} | class ____:
def __init__(self, kernel_shape, num_filters):
self.kernel_shape = kernel_shape
self.num_filters = num_filters
def forward_pass(self, inputs, param_vector):
# Input dimensions: [data, color_in, y, x]
# Params dimensions: [color_in, color_out, y, x]
# Output dimensions: [data, color_out, y, x]
params = self.parser.get(param_vector, "params")
biases = self.parser.get(param_vector, "biases")
conv = convolve(inputs, params, axes=([2, 3], [2, 3]), dot_axes=([1], [0]), mode="valid")
return conv + biases
def build_weights_dict(self, input_shape):
# Input shape : [color, y, x] (don't need to know number of data yet)
self.parser = WeightsParser()
self.parser.add_weights("params", (input_shape[0], self.num_filters) + self.kernel_shape)
self.parser.add_weights("biases", (1, self.num_filters, 1, 1))
output_shape = (self.num_filters,) + self.conv_output_shape(input_shape[1:], self.kernel_shape)
return self.parser.N, output_shape
def conv_output_shape(self, A, B):
return (A[0] - B[0] + 1, A[1] - B[1] + 1)
| conv_layer |
python | prabhupant__python-ds | data_structures/graphs/cycle_in_directed_graph.py | {
"start": 38,
"end": 935
} | class ____:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def is_cyclic_util(self, v, visited, rec_stack):
visited[v] = True
rec_stack[v] = True
for neighbour in self.graph[v]:
if visited[neighbour] == False:
if self.is_cyclic_util(neighbour, visited, rec_stack):
return True
elif rec_stack[neighbour] == True:
return True
rec_stack[v] = False
return False
def is_cyclic(self):
visited = [False] * self.V
rec_stack = [False] * self.V
for i in range(self.V):
if visited[i] == False:
if self.is_cyclic_util(node, visited, rec_stack) == True:
return True
return False
| Graph |
python | getsentry__sentry | src/sentry/users/services/user/model.py | {
"start": 853,
"end": 1510
} | class ____(RpcModel):
"""Minimal set of user attributes that can be fetched efficiently."""
id: int = -1
pk: int = -1
name: str = ""
email: str = ""
username: str = ""
actor_id: int | None = None
display_name: str = ""
label: str = ""
is_superuser: bool = False
is_authenticated: bool = False
is_anonymous: bool = False
is_active: bool = False
is_staff: bool = False
is_unclaimed: bool = False
last_active: datetime.datetime | None = None
is_sentry_app: bool = False
password_usable: bool = False
is_password_expired: bool = False
session_nonce: str | None = None
| RpcUserProfile |
python | scikit-learn__scikit-learn | sklearn/base.py | {
"start": 20722,
"end": 24177
} | class ____:
"""Mixin class for all regression estimators in scikit-learn.
This mixin defines the following functionality:
- set estimator type to `"regressor"` through the `estimator_type` tag;
- `score` method that default to :func:`~sklearn.metrics.r2_score`.
- enforce that `fit` requires `y` to be passed through the `requires_y` tag,
which is done by setting the regressor type tag.
Read more in the :ref:`User Guide <rolling_your_own_estimator>`.
Examples
--------
>>> import numpy as np
>>> from sklearn.base import BaseEstimator, RegressorMixin
>>> # Mixin classes should always be on the left-hand side for a correct MRO
>>> class MyEstimator(RegressorMixin, BaseEstimator):
... def __init__(self, *, param=1):
... self.param = param
... def fit(self, X, y=None):
... self.is_fitted_ = True
... return self
... def predict(self, X):
... return np.full(shape=X.shape[0], fill_value=self.param)
>>> estimator = MyEstimator(param=0)
>>> X = np.array([[1, 2], [2, 3], [3, 4]])
>>> y = np.array([-1, 0, 1])
>>> estimator.fit(X, y).predict(X)
array([0, 0, 0])
>>> estimator.score(X, y)
0.0
"""
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.estimator_type = "regressor"
tags.regressor_tags = RegressorTags()
tags.target_tags.required = True
return tags
def score(self, X, y, sample_weight=None):
"""Return :ref:`coefficient of determination <r2_score>` on test data.
The coefficient of determination, :math:`R^2`, is defined as
:math:`(1 - \\frac{u}{v})`, where :math:`u` is the residual
sum of squares ``((y_true - y_pred)** 2).sum()`` and :math:`v`
is the total sum of squares ``((y_true - y_true.mean()) ** 2).sum()``.
The best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). A constant model that always predicts
the expected value of `y`, disregarding the input features, would get
a :math:`R^2` score of 0.0.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed
kernel matrix or a list of generic objects instead with shape
``(n_samples, n_samples_fitted)``, where ``n_samples_fitted``
is the number of samples used in the fitting for the estimator.
y : array-like of shape (n_samples,) or (n_samples, n_outputs)
True values for `X`.
sample_weight : array-like of shape (n_samples,), default=None
Sample weights.
Returns
-------
score : float
:math:`R^2` of ``self.predict(X)`` w.r.t. `y`.
Notes
-----
The :math:`R^2` score used when calling ``score`` on a regressor uses
``multioutput='uniform_average'`` from version 0.23 to keep consistent
with default value of :func:`~sklearn.metrics.r2_score`.
This influences the ``score`` method of all the multioutput
regressors (except for
:class:`~sklearn.multioutput.MultiOutputRegressor`).
"""
from sklearn.metrics import r2_score
y_pred = self.predict(X)
return r2_score(y, y_pred, sample_weight=sample_weight)
| RegressorMixin |
python | dask__distributed | distributed/scheduler.py | {
"start": 5355,
"end": 7414
} | class ____:
"""A simple object holding information about a client."""
#: A unique identifier for this client. This is generally an opaque
#: string generated by the client itself.
client_key: str
#: Cached hash of :attr:`~ClientState.client_key`
_hash: int
#: A set of tasks this client wants to be kept in memory, so that it can download
#: its result when desired. This is the reverse mapping of
#: :class:`TaskState.who_wants`. Tasks are typically removed from this set when the
#: corresponding object in the client's space (for example a ``Future`` or a Dask
#: collection) gets garbage-collected.
wants_what: set[TaskState]
#: The last time we received a heartbeat from this client, in local scheduler time.
last_seen: float
#: Output of :func:`distributed.versions.get_versions` on the client
versions: dict[str, Any]
__slots__ = tuple(__annotations__)
def __init__(self, client: str, *, versions: dict[str, Any] | None = None):
self.client_key = client
self._hash = hash(client)
self.wants_what = set()
self.last_seen = time()
self.versions = versions or {}
def __hash__(self) -> int:
return self._hash
def __eq__(self, other: object) -> bool:
if not isinstance(other, ClientState):
return False
return self.client_key == other.client_key
def __repr__(self) -> str:
return f"<Client {self.client_key!r}>"
def __str__(self) -> str:
return self.client_key
def _to_dict_no_nest(self, *, exclude: Container[str] = ()) -> dict:
"""Dictionary representation for debugging purposes.
Not type stable and not intended for roundtrips.
See also
--------
Client.dump_cluster_state
distributed.utils.recursive_to_dict
TaskState._to_dict
"""
return recursive_to_dict(
self,
exclude=set(exclude) | {"versions"}, # type: ignore
members=True,
)
| ClientState |
python | google__pytype | pytype/config_test.py | {
"start": 120,
"end": 3131
} | class ____(unittest.TestCase):
def test_basic(self):
version = sys.version_info[:2]
argv = [
"-V",
utils.format_version(version),
"--use-pickled-files",
"-o",
"out.pyi",
"--pythonpath",
f"foo{os.pathsep}bar",
"test.py",
]
opts = config.Options(argv, command_line=True)
self.assertEqual(opts.python_version, version)
self.assertEqual(opts.use_pickled_files, True)
self.assertEqual(opts.pythonpath, ["foo", "bar"])
self.assertEqual(opts.output, "out.pyi")
self.assertEqual(opts.input, "test.py")
def test_create(self):
version = sys.version_info[:2]
opts = config.Options.create(
input_filename="foo.py",
python_version=utils.format_version(version),
use_pickled_files=True,
)
self.assertEqual(opts.input, "foo.py")
self.assertEqual(opts.use_pickled_files, True)
self.assertEqual(opts.python_version, version)
self.assertIsNone(opts.python_exe)
def test_analyze_annotated_check(self):
argv = ["--check", "test.py"]
opts = config.Options(argv, command_line=True)
self.assertTrue(opts.analyze_annotated) # default
argv.append("--analyze-annotated")
opts = config.Options(argv, command_line=True)
self.assertTrue(opts.analyze_annotated)
def test_analyze_annotated_output(self):
argv = ["--output=out.pyi", "test.py"]
opts = config.Options(argv, command_line=True)
self.assertFalse(opts.analyze_annotated) # default
argv.append("--analyze-annotated")
opts = config.Options(argv, command_line=True)
self.assertTrue(opts.analyze_annotated)
def test_verbosity(self):
level = logging.getLogger().getEffectiveLevel()
# make sure we properly exercise verbosity_from by changing the log level
assert level != logging.ERROR
with config.verbosity_from(config.Options.create(verbosity=1)):
self.assertEqual(logging.getLogger().getEffectiveLevel(), logging.ERROR)
self.assertEqual(logging.getLogger().getEffectiveLevel(), level)
def test_bad_verbosity(self):
argv = ["--verbosity", "5", "test.py"]
with self.assertRaises(SystemExit):
config.Options(argv, command_line=True)
def test_bad_verbosity_create(self):
with self.assertRaises(config.PostprocessingError):
config.Options.create("test.py", verbosity=5)
def _test_arg_conflict(self, arg1, arg2):
argv = [arg1, arg2, "test.py"]
with self.assertRaises(SystemExit):
config.Options(argv, command_line=True)
def test_arg_conflicts(self):
for arg1, arg2 in [
("--check", "--output=foo"),
("--output-errors-csv=foo", "--no-report-errors"),
("--pythonpath=foo", "--imports_info=bar"),
]:
self._test_arg_conflict(arg1, arg2)
def test_bad_construction(self):
with self.assertRaises(TypeError):
# To prevent accidental misuse, command_line must be explicitly set when
# directly constructing Options.
config.Options([])
| ConfigTest |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/hooks/search_ads.py | {
"start": 7905,
"end": 8798
} | class ____(GoogleBaseHook):
"""Hook for Google Search Ads 360."""
_conn: build | None = None
def __init__(
self,
api_version: str = "v2",
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(
gcp_conn_id=gcp_conn_id,
impersonation_chain=impersonation_chain,
**kwargs,
)
self.api_version = api_version
def get_conn(self):
"""Retrieve connection to Google SearchAds."""
if not self._conn:
http_authorized = self._authorize()
self._conn = build(
"doubleclicksearch",
self.api_version,
http=http_authorized,
cache_discovery=False,
)
return self._conn
| GoogleSearchAdsHook |
python | ipython__ipython | IPython/lib/display.py | {
"start": 14771,
"end": 22833
} | class ____(FileLink):
"""Class for embedding local file links in an IPython session, based on path
e.g. to embed links to files that were generated in the IPython notebook
under ``my/data``, you would do::
local_files = FileLinks("my/data")
display(local_files)
or in the HTML notebook, just::
FileLinks("my/data")
"""
def __init__(self,
path,
url_prefix='',
included_suffixes=None,
result_html_prefix='',
result_html_suffix='<br>',
notebook_display_formatter=None,
terminal_display_formatter=None,
recursive=True):
"""
See :class:`FileLink` for the ``path``, ``url_prefix``,
``result_html_prefix`` and ``result_html_suffix`` parameters.
included_suffixes : list
Filename suffixes to include when formatting output [default: include
all files]
notebook_display_formatter : function
Used to format links for display in the notebook. See discussion of
formatter functions below.
terminal_display_formatter : function
Used to format links for display in the terminal. See discussion of
formatter functions below.
Formatter functions must be of the form::
f(dirname, fnames, included_suffixes)
dirname : str
The name of a directory
fnames : list
The files in that directory
included_suffixes : list
The file suffixes that should be included in the output (passing None
meansto include all suffixes in the output in the built-in formatters)
recursive : boolean
Whether to recurse into subdirectories. Default is True.
The function should return a list of lines that will be printed in the
notebook (if passing notebook_display_formatter) or the terminal (if
passing terminal_display_formatter). This function is iterated over for
each directory in self.path. Default formatters are in place, can be
passed here to support alternative formatting.
"""
if isfile(path):
raise ValueError("Cannot display a file using FileLinks. "
"Use FileLink to display '%s'." % path)
self.included_suffixes = included_suffixes
# remove trailing slashes for more consistent output formatting
path = path.rstrip('/')
self.path = path
self.url_prefix = url_prefix
self.result_html_prefix = result_html_prefix
self.result_html_suffix = result_html_suffix
self.notebook_display_formatter = \
notebook_display_formatter or self._get_notebook_display_formatter()
self.terminal_display_formatter = \
terminal_display_formatter or self._get_terminal_display_formatter()
self.recursive = recursive
def _get_display_formatter(
self, dirname_output_format, fname_output_format, fp_format, fp_cleaner=None
):
"""generate built-in formatter function
this is used to define both the notebook and terminal built-in
formatters as they only differ by some wrapper text for each entry
dirname_output_format: string to use for formatting directory
names, dirname will be substituted for a single "%s" which
must appear in this string
fname_output_format: string to use for formatting file names,
if a single "%s" appears in the string, fname will be substituted
if two "%s" appear in the string, the path to fname will be
substituted for the first and fname will be substituted for the
second
fp_format: string to use for formatting filepaths, must contain
exactly two "%s" and the dirname will be substituted for the first
and fname will be substituted for the second
"""
def f(dirname, fnames, included_suffixes=None):
result = []
# begin by figuring out which filenames, if any,
# are going to be displayed
display_fnames = []
for fname in fnames:
if (isfile(join(dirname,fname)) and
(included_suffixes is None or
splitext(fname)[1] in included_suffixes)):
display_fnames.append(fname)
if len(display_fnames) == 0:
# if there are no filenames to display, don't print anything
# (not even the directory name)
pass
else:
# otherwise print the formatted directory name followed by
# the formatted filenames
dirname_output_line = dirname_output_format % dirname
result.append(dirname_output_line)
for fname in display_fnames:
fp = fp_format % (dirname,fname)
if fp_cleaner is not None:
fp = fp_cleaner(fp)
try:
# output can include both a filepath and a filename...
fname_output_line = fname_output_format % (fp, fname)
except TypeError:
# ... or just a single filepath
fname_output_line = fname_output_format % fname
result.append(fname_output_line)
return result
return f
def _get_notebook_display_formatter(self,
spacer=" "):
""" generate function to use for notebook formatting
"""
dirname_output_format = \
self.result_html_prefix + "%s/" + self.result_html_suffix
fname_output_format = \
self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
fp_format = self.url_prefix + '%s/%s'
if sep == "\\":
# Working on a platform where the path separator is "\", so
# must convert these to "/" for generating a URI
def fp_cleaner(fp):
# Replace all occurrences of backslash ("\") with a forward
# slash ("/") - this is necessary on windows when a path is
# provided as input, but we must link to a URI
return fp.replace('\\','/')
else:
fp_cleaner = None
return self._get_display_formatter(dirname_output_format,
fname_output_format,
fp_format,
fp_cleaner)
def _get_terminal_display_formatter(self,
spacer=" "):
""" generate function to use for terminal formatting
"""
dirname_output_format = "%s/"
fname_output_format = spacer + "%s"
fp_format = '%s/%s'
return self._get_display_formatter(dirname_output_format,
fname_output_format,
fp_format)
def _format_path(self):
result_lines = []
if self.recursive:
walked_dir = list(walk(self.path))
else:
walked_dir = [next(walk(self.path))]
walked_dir.sort()
for dirname, subdirs, fnames in walked_dir:
result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
return '\n'.join(result_lines)
def __repr__(self):
"""return newline-separated absolute paths
"""
result_lines = []
if self.recursive:
walked_dir = list(walk(self.path))
else:
walked_dir = [next(walk(self.path))]
walked_dir.sort()
for dirname, subdirs, fnames in walked_dir:
result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
return '\n'.join(result_lines)
| FileLinks |
python | run-llama__llama_index | llama-index-core/llama_index/core/storage/index_store/types.py | {
"start": 322,
"end": 1406
} | class ____(ABC):
@abstractmethod
def index_structs(self) -> List[IndexStruct]:
pass
@abstractmethod
async def async_index_structs(self) -> List[IndexStruct]:
pass
@abstractmethod
def add_index_struct(self, index_struct: IndexStruct) -> None:
pass
@abstractmethod
async def async_add_index_struct(self, index_struct: IndexStruct) -> None:
pass
@abstractmethod
def delete_index_struct(self, key: str) -> None:
pass
@abstractmethod
async def adelete_index_struct(self, key: str) -> None:
pass
@abstractmethod
def get_index_struct(
self, struct_id: Optional[str] = None
) -> Optional[IndexStruct]:
pass
@abstractmethod
async def aget_index_struct(
self, struct_id: Optional[str] = None
) -> Optional[IndexStruct]:
pass
def persist(
self,
persist_path: str = DEFAULT_PERSIST_PATH,
fs: Optional[fsspec.AbstractFileSystem] = None,
) -> None:
"""Persist the index store to disk."""
| BaseIndexStore |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 22513,
"end": 24336
} | class ____(graphene.Mutation):
"""Reloads a code location server."""
Output = graphene.NonNull(GrapheneReloadRepositoryLocationMutationResult)
class Arguments:
repositoryLocationName = graphene.NonNull(graphene.String)
class Meta:
name = "ReloadRepositoryLocationMutation"
@capture_error
@require_permission_check(Permissions.RELOAD_REPOSITORY_LOCATION)
def mutate(
self, graphene_info: ResolveInfo, repositoryLocationName: str
) -> Union[
GrapheneWorkspaceLocationEntry,
GrapheneReloadNotSupported,
GrapheneRepositoryLocationNotFound,
]:
assert_permission_for_location(
graphene_info, Permissions.RELOAD_REPOSITORY_LOCATION, repositoryLocationName
)
if not graphene_info.context.has_code_location_name(repositoryLocationName):
return GrapheneRepositoryLocationNotFound(repositoryLocationName)
if not graphene_info.context.is_reload_supported(repositoryLocationName):
return GrapheneReloadNotSupported(repositoryLocationName)
# The current workspace context is a WorkspaceRequestContext, which contains a reference to the
# repository locations that were present in the root IWorkspaceProcessContext the start of the
# request. Reloading a repository location modifies the IWorkspaceProcessContext, rendeirng
# our current WorkspaceRequestContext outdated. Therefore, `reload_repository_location` returns
# an updated WorkspaceRequestContext for us to use.
new_context = graphene_info.context.reload_code_location(repositoryLocationName)
return GrapheneWorkspaceLocationEntry(
check.not_none(new_context.get_location_entry(repositoryLocationName))
)
| GrapheneReloadRepositoryLocationMutation |
python | facelessuser__pymdown-extensions | pymdownx/blocks/definition.py | {
"start": 120,
"end": 1407
} | class ____(Block):
"""
Definition.
Converts non `ul`, `ol` blocks (ideally `p` tags) into `dt`
and will convert first level `li` elements of `ul` and `ol`
elements to `dd` tags. When done, the `ul`, and `ol` elements
will be removed.
"""
NAME = 'define'
def on_create(self, parent):
"""Create the element."""
return etree.SubElement(parent, 'dl')
def on_end(self, block):
"""Convert non list items to details."""
remove = []
offset = 0
for i, child in enumerate(list(block)):
if child.tag.lower() in ('dt', 'dd'):
continue
elif child.tag.lower() not in ('ul', 'ol'):
if child.tag.lower() == 'p':
child.tag = 'dt'
else:
dt = etree.Element('dt')
dt.append(child)
block.insert(i + offset, dt)
block.remove(child)
else:
for li in list(child):
offset += 1
li.tag = 'dd'
block.insert(i + offset, li)
child.remove(li)
remove.append(child)
for el in remove:
block.remove(el)
| Definition |
python | ray-project__ray | release/llm_tests/benchmark/configs.py | {
"start": 112,
"end": 253
} | class ____(str, Enum):
CONSTANT = "constant"
UNIFORM = "uniform"
EXPONENTIAL = "exponential"
NORMAL = "normal"
| DistributionType |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-pgvector/destination_pgvector/common/state/state_writers.py | {
"start": 524,
"end": 977
} | class ____(StateWriterBase):
"""A state writer that writes state artifacts to stdout.
This is required when we are functioning as a "Destination" in the Airbyte protocol, and
an orchestrator is responsible for saving those state artifacts.
"""
def write_state(
self,
state_message: AirbyteStateMessage,
) -> None:
"""Save or 'write' a state artifact."""
print(state_message.json())
| StdOutStateWriter |
python | fluentpython__example-code-2e | 22-dyn-attr-prop/blackknight.py | {
"start": 733,
"end": 1292
} | class ____:
def __init__(self):
self.phrases = [
('an arm', "'Tis but a scratch."),
('another arm', "It's just a flesh wound."),
('a leg', "I'm invincible!"),
('another leg', "All right, we'll call it a draw.")
]
@property
def member(self):
print('next member is:')
return self.phrases[0][0]
@member.deleter
def member(self):
member, text = self.phrases.pop(0)
print(f'BLACK KNIGHT (loses {member}) -- {text}')
# end::BLACK_KNIGHT[]
| BlackKnight |
python | chroma-core__chroma | chromadb/test/test_config.py | {
"start": 984,
"end": 1289
} | class ____(Component):
def __init__(self, system: System):
data.inits += "C"
super().__init__(system)
self.require(ComponentD)
@overrides
def start(self) -> None:
data.starts += "C"
@overrides
def stop(self) -> None:
data.stops += "C"
| ComponentC |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass5.py | {
"start": 158,
"end": 1393
} | class ____(ABC):
@overload
def func1(self, a: int) -> int:
pass
@overload
@abstractmethod
# This should generate an error because this overload is
# missing an abstractmethod overload.
def func1(self, a: float) -> float:
pass
@overload
def func1(self, a: str) -> str: ...
def func1(self, a: Union[int, float, str]) -> Union[int, float, str]:
raise NotImplementedError()
@overload
def func2(self, a: str) -> str: ...
@overload
@abstractmethod
def func2(self, a: int) -> int:
pass
@abstractmethod
def func2(self, a: Union[int, str]) -> Union[int, str]:
raise NotImplementedError()
@overload
def func3(self, a: str) -> str: # pyright: ignore[reportNoOverloadImplementation]
...
@overload
@abstractmethod
# This should generate an error because the abstract status is inconsistent.
def func3(self, a: int) -> int: ...
@overload
@abstractmethod
def func4(self, a: str) -> str: # pyright: ignore[reportNoOverloadImplementation]
...
@overload
# This should generate an error because the abstract status is inconsistent.
def func4(self, a: int) -> int: ...
| ClassA |
python | sanic-org__sanic | sanic/http/constants.py | {
"start": 33,
"end": 669
} | class ____(Enum):
"""Enum for representing the stage of the request/response cycle
| ``IDLE`` Waiting for request
| ``REQUEST`` Request headers being received
| ``HANDLER`` Headers done, handler running
| ``RESPONSE`` Response headers sent, body in progress
| ``FAILED`` Unrecoverable state (error while sending response)
|
"""
IDLE = 0 # Waiting for request
REQUEST = 1 # Request headers being received
HANDLER = 3 # Headers done, handler running
RESPONSE = 4 # Response headers sent, body in progress
FAILED = 100 # Unrecoverable state (error while sending response)
| Stage |
python | walkccc__LeetCode | solutions/2366. Minimum Replacements to Sort the Array/2366.py | {
"start": 0,
"end": 243
} | class ____:
def minimumReplacement(self, nums: list[int]) -> int:
ans = 0
mx = nums[-1]
for i in range(len(nums) - 2, -1, -1):
ops = (nums[i] - 1) // mx
ans += ops
mx = nums[i] // (ops + 1)
return ans
| Solution |
python | dask__dask | dask/array/tests/test_array_core.py | {
"start": 68474,
"end": 68813
} | class ____:
def __init__(self):
self.concurrent_uses = 0
self.max_concurrent_uses = 0
def __setitem__(self, key, value):
self.concurrent_uses += 1
self.max_concurrent_uses = max(self.concurrent_uses, self.max_concurrent_uses)
time.sleep(0.01)
self.concurrent_uses -= 1
| ThreadSafeStore |
python | getsentry__sentry | tests/sentry/releases/endpoints/test_project_release_details.py | {
"start": 806,
"end": 1818
} | class ____(APITestCase):
def test_simple(self) -> None:
self.login_as(user=self.user)
project = self.create_project(name="foo")
project2 = self.create_project(name="bar", organization=project.organization)
release = Release.objects.create(organization_id=project.organization_id, version="1")
release.add_project(project)
release.add_project(project2)
ReleaseProject.objects.filter(project=project, release=release).update(new_groups=5)
url = reverse(
"sentry-api-0-project-release-details",
kwargs={
"organization_id_or_slug": project.organization.slug,
"project_id_or_slug": project.slug,
"version": release.version,
},
)
response = self.client.get(url)
assert response.status_code == 200, response.content
assert response.data["version"] == release.version
assert response.data["newGroups"] == 5
| ReleaseDetailsTest |
python | doocs__leetcode | solution/0900-0999/0924.Minimize Malware Spread/Solution.py | {
"start": 0,
"end": 701
} | class ____:
__slots__ = "p", "size"
def __init__(self, n: int):
self.p = list(range(n))
self.size = [1] * n
def find(self, x: int) -> int:
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a: int, b: int) -> bool:
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
def get_size(self, root: int) -> int:
return self.size[root]
| UnionFind |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassFrozen1.py | {
"start": 367,
"end": 427
} | class ____(DC1):
val3: int = 4
@dataclass(frozen=True)
| DC3 |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_glacier.py | {
"start": 3337,
"end": 3564
} | class ____:
def test_job_status_success(self):
assert JobStatus.SUCCEEDED.value == SUCCEEDED
def test_job_status_in_progress(self):
assert JobStatus.IN_PROGRESS.value == IN_PROGRESS
| TestSensorJobDescription |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran_tests/deprecated/test_managed_elements.py | {
"start": 872,
"end": 14896
} | class ____(AbstractContextManager):
def __init__(
self, connectors: dict[str, FivetranConnector], destinations: dict[str, FivetranDestination]
):
self.rsps = responses.RequestsMock(assert_all_requests_are_fired=False)
self.connectors = connectors
self.destinations = destinations
self.created_groups: dict[str, str] = {}
self.group_id = 1
self.connectors_by_destination = {
dest_id: [
conn_id
for conn_id, conn in connectors.items()
if cast("FivetranDestination", conn.destination).name == dest.name
]
for dest_id, dest in destinations.items()
}
self.operations_log: list[tuple[str, str]] = []
def __enter__(self):
self.rsps.__enter__()
self.rsps.add_callback(
responses.GET,
"https://api.fivetran.com/v1/groups",
callback=format_callback(self.mock_groups),
)
self.rsps.add_callback(
responses.GET,
re.compile(r"https://api\.fivetran\.com/v1/destinations/.*"),
callback=format_callback(self.mock_destination),
)
self.rsps.add_callback(
responses.GET,
re.compile(r"https://api\.fivetran\.com/v1/groups/.*/connectors"),
callback=format_callback(self.mock_connectors),
)
self.rsps.add_callback(
responses.GET,
re.compile(r"https://api\.fivetran\.com/v1/connectors/.*"),
callback=format_callback(self.mock_connector),
)
self.rsps.add_callback(
responses.PATCH,
re.compile(r"https://api\.fivetran\.com/v1/destinations/.*"),
callback=format_callback(self.mock_patch_destination),
)
self.rsps.add_callback(
responses.PATCH,
re.compile(r"https://api\.fivetran\.com/v1/connectors/.*"),
callback=format_callback(self.mock_patch_connector),
)
self.rsps.add_callback(
responses.POST,
"https://api.fivetran.com/v1/groups",
callback=format_callback(self.mock_post_groups),
)
self.rsps.add_callback(
responses.POST,
"https://api.fivetran.com/v1/destinations",
callback=format_callback(self.mock_post_destinations),
)
self.rsps.add_callback(
responses.POST,
"https://api.fivetran.com/v1/connectors",
callback=format_callback(self.mock_post_connectors),
)
return self
def mock_post_groups(self, _method, _url, contents):
self.operations_log.append(("post_groups", contents["name"]))
new_group_id = str(self.group_id)
self.created_groups[new_group_id] = contents["name"]
self.group_id += 1
return {"code": "Success", "data": {"id": new_group_id}}
def mock_post_destinations(self, _method, _url, contents):
group_id = contents["group_id"]
self.operations_log.append(("post_destinations", group_id))
self.destinations[group_id] = InitializedFivetranDestination.from_api_json(
name=self.created_groups[group_id], api_json={**contents, "id": "my_new_dest_id"}
).destination
self.connectors_by_destination[group_id] = []
return {"code": "Success"}
def mock_post_connectors(self, _method, _url, contents):
group_id = contents["group_id"]
self.operations_log.append(("post_connectors", group_id))
conn = InitializedFivetranConnector.from_api_json(
api_json={**contents, "id": "my_new_conn_id", "schema": contents["config"]["schema"]}
).connector
conn.destination = self.destinations[group_id]
self.connectors["my_new_conn_id"] = conn
self.connectors_by_destination[group_id].append("my_new_conn_id")
return {"code": "Success"}
def mock_patch_destination(self, _method, url, contents):
destination_id = url.split("/")[-1]
destination = self.destinations[destination_id]
destination.destination_configuration = contents["config"]
self.operations_log.append(("patch_destination", destination_id))
return {"code": "Success"}
def mock_patch_connector(self, _method, url, contents):
connector_id = url.split("/")[-1]
connector = self.connectors[connector_id]
connector.source_configuration = contents["config"]
self.operations_log.append(("patch_connector", connector_id))
return {"code": "Success"}
def mock_connector(self, _method, url, _contents):
connector_id = url.split("/")[-1]
connector = self.connectors[connector_id]
return {
"code": "Success",
"data": {
"id": connector_id,
"group_id": connector.destination.name, # pyright: ignore[reportOptionalMemberAccess]
"service": connector.source_type,
"service_version": 1,
"schema": connector.schema_name,
"connected_by": "concerning_batch",
"created_at": "2018-07-21T22:55:21.724201Z",
"succeeded_at": "2018-12-26T17:58:18.245Z",
"failed_at": "2018-08-24T15:24:58.872491Z",
"sync_frequency": 60,
"status": {
"setup_state": "connected",
"sync_state": "paused",
"update_state": "delayed",
"is_historical_sync": False,
"tasks": [],
"warnings": [],
},
"config": connector.source_configuration,
},
}
def mock_connectors(self, _method, url, _contents):
destination_id = url.split("/")[-2]
connector_ids = self.connectors_by_destination[destination_id]
connectors = {conn_id: self.connectors[conn_id] for conn_id in connector_ids}
return {
"code": "Success",
"data": {
"items": [
{
"id": conn_id,
"group_id": destination_id,
"service": conn.source_type,
"service_version": 1,
"schema": conn.schema_name,
"connected_by": "concerning_batch",
"created_at": "2018-07-21T22:55:21.724201Z",
"succeeded_at": "2018-12-26T17:58:18.245Z",
"failed_at": "2018-08-24T15:24:58.872491Z",
"sync_frequency": 60,
"status": {
"setup_state": "connected",
"sync_state": "paused",
"update_state": "delayed",
"is_historical_sync": False,
"tasks": [],
"warnings": [],
},
}
for conn_id, conn in connectors.items()
],
"next_cursor": "eyJza2lwIjoxfQ",
},
}
def mock_destination(self, _method, url, _contents):
destination_id = url.split("/")[-1]
destination = self.destinations[destination_id]
return {
"code": "Success",
"data": {
"id": destination_id,
"group_id": destination_id,
"service": destination.destination_type,
"region": destination.region,
"time_zone_offset": destination.time_zone_offset,
"setup_status": "connected",
"config": destination.destination_configuration,
},
}
def mock_groups(self, _method, _url, _contents):
return {
"items": [
{
"id": dest_id,
"name": dest.name,
}
for dest_id, dest in self.destinations.items()
]
}
def __exit__(self, exc_type, exc_val, exc_tb):
self.rsps.__exit__(exc_type, exc_val, exc_tb)
def add_groups_response(res: responses.RequestsMock, groups: list[tuple[str, str]]):
res.add(
responses.GET,
"https://api.fivetran.com/v1/groups",
json={
"items": [
{
"id": group_id,
"name": group_name,
}
for group_id, group_name in groups
]
},
)
def add_groups_destinations(
res: responses.RequestsMock, dest_id: str, destination: FivetranDestination
):
res.add(
responses.GET,
f"https://api.fivetran.com/v1/destinations/{dest_id}",
json={
"code": "Success",
"data": {
"id": dest_id,
"group_id": dest_id,
"service": destination.destination_type,
"region": destination.region,
"time_zone_offset": destination.time_zone_offset,
"setup_status": "connected",
"config": destination.destination_configuration,
},
},
)
def add_groups_connectors(
res: responses.RequestsMock, group_id: str, connectors: dict[str, FivetranConnector]
):
res.add(
responses.GET,
f"https://api.fivetran.com/v1/groups/{group_id}/connectors",
json={
"code": "Success",
"data": {
"items": [
{
"id": conn_id,
"group_id": group_id,
"service": conn.source_type,
"service_version": 1,
"schema": conn.schema_name,
"connected_by": "concerning_batch",
"created_at": "2018-07-21T22:55:21.724201Z",
"succeeded_at": "2018-12-26T17:58:18.245Z",
"failed_at": "2018-08-24T15:24:58.872491Z",
"sync_frequency": 60,
"status": {
"setup_state": "connected",
"sync_state": "paused",
"update_state": "delayed",
"is_historical_sync": False,
"tasks": [],
"warnings": [],
},
}
for conn_id, conn in connectors.items()
],
"next_cursor": "eyJza2lwIjoxfQ",
},
},
)
for conn_id, conn in connectors.items():
res.add(
responses.GET,
f"https://api.fivetran.com/v1/connectors/{conn_id}",
json={
"code": "Success",
"data": {
"id": conn_id,
"group_id": group_id,
"service": conn.source_type,
"service_version": 1,
"schema": conn.schema_name,
"connected_by": "concerning_batch",
"created_at": "2018-07-21T22:55:21.724201Z",
"succeeded_at": "2018-12-26T17:58:18.245Z",
"failed_at": "2018-08-24T15:24:58.872491Z",
"sync_frequency": 60,
"status": {
"setup_state": "connected",
"sync_state": "paused",
"update_state": "delayed",
"is_historical_sync": False,
"tasks": [],
"warnings": [],
},
"config": conn.source_configuration,
},
},
)
@responses.activate
def test_basic_end_to_end():
ft_instance = fivetran_resource.configured(
{
"api_key": "some_key",
"api_secret": "some_secret",
}
)
snowflake_destination = FivetranDestination(
name="my_destination",
destination_type="Snowflake",
region="GCP_US_EAST4",
time_zone_offset=0,
destination_configuration={
"baz": "qux",
},
)
github_conn = FivetranConnector(
schema_name="my_connector",
source_type="GitHub",
source_configuration={
"foo": "bar",
},
destination=snowflake_destination,
)
reconciler = FivetranManagedElementReconciler(
fivetran=ft_instance,
connectors=[github_conn],
)
with MockFivetran(
connectors={"my_connector": github_conn},
destinations={"my_destination": snowflake_destination},
) as mock_ft:
assert reconciler.check() == ManagedElementDiff()
assert reconciler.apply() == ManagedElementDiff()
assert mock_ft.operations_log == [
("patch_destination", "my_destination"),
("patch_connector", "my_connector"),
]
with MockFivetran(
connectors={},
destinations={},
) as mock_ft:
expected_diff = diff_dicts(
{
"my_destination": {"baz": "qux"},
"my_connector": {"schema": "my_connector", "foo": "bar"},
},
{},
)
assert reconciler.check() == expected_diff
assert reconciler.apply() == expected_diff
assert mock_ft.operations_log == [
("post_groups", "my_destination"),
("post_destinations", "1"),
("post_connectors", "1"),
]
assert reconciler.check() == ManagedElementDiff()
assert reconciler.apply() == ManagedElementDiff()
assert mock_ft.operations_log[-2:] == [
("patch_destination", "1"),
("patch_connector", "my_new_conn_id"),
]
| MockFivetran |
python | pypa__installer | src/installer/records.py | {
"start": 745,
"end": 1973
} | class ____:
"""Represents the "hash" element of a RecordEntry.
Most consumers should use :py:meth:`Hash.parse` instead, since no
validation or parsing is performed by this constructor.
"""
name: str
"""Name of the hash function."""
value: str
"""Hashed value."""
def __str__(self) -> str:
return f"{self.name}={self.value}"
def validate(self, data: bytes) -> bool:
"""Validate that ``data`` matches this instance.
:param data: Contents of the file.
:return: Whether ``data`` matches the hashed value.
"""
digest = hashlib.new(self.name, data).digest()
value = base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=")
return self.value == value
@classmethod
def parse(cls, h: str) -> "Hash":
"""Build a Hash object, from a "name=value" string.
This accepts a string of the format for the second element in a record,
as described in :pep:`376`.
Typical usage::
Hash.parse("sha256=Y0sCextp4SQtQNU-MSs7SsdxD1W-gfKJtUlEbvZ3i-4")
:param h: a name=value string
"""
name, value = h.split("=", 1)
return cls(name, value)
@dataclass
| Hash |
python | PyCQA__pycodestyle | pycodestyle.py | {
"start": 84011,
"end": 86198
} | class ____(BaseReport):
"""Collect and print the results of the checks."""
def __init__(self, options):
super().__init__(options)
self._fmt = REPORT_FORMAT.get(options.format.lower(),
options.format)
self._repeat = options.repeat
self._show_source = options.show_source
self._show_pep8 = options.show_pep8
def init_file(self, filename, lines, expected, line_offset):
"""Signal a new file."""
self._deferred_print = []
return super().init_file(
filename, lines, expected, line_offset)
def error(self, line_number, offset, text, check):
"""Report an error, according to options."""
code = super().error(line_number, offset, text, check)
if code and (self.counters[code] == 1 or self._repeat):
self._deferred_print.append(
(line_number, offset, code, text[5:], check.__doc__))
return code
def get_file_results(self):
"""Print results and return the overall count for this file."""
self._deferred_print.sort()
for line_number, offset, code, text, doc in self._deferred_print:
print(self._fmt % {
'path': self.filename,
'row': self.line_offset + line_number, 'col': offset + 1,
'code': code, 'text': text,
})
if self._show_source:
if line_number > len(self.lines):
line = ''
else:
line = self.lines[line_number - 1]
print(line.rstrip())
print(re.sub(r'\S', ' ', line[:offset]) + '^')
if self._show_pep8 and doc:
print(' ' + doc.strip())
# stdout is block buffered when not stdout.isatty().
# line can be broken where buffer boundary since other
# processes write to same file.
# flush() after print() to avoid buffer boundary.
# Typical buffer size is 8192. line written safely when
# len(line) < 8192.
sys.stdout.flush()
return self.file_errors
| StandardReport |
python | pappasam__jedi-language-server | jedi_language_server/text_edit_utils.py | {
"start": 5045,
"end": 5739
} | class ____:
"""Data structure to convert byte offset file to line number and character."""
def __init__(self, code: str) -> None:
# Create a list saying at what offset in the file each line starts.
self.line_starts = []
offset = 0
for line in code.splitlines(keepends=True):
self.line_starts.append(offset)
offset += len(line)
def get(self, offset: int) -> Position:
"""Get the position in the file that corresponds to the given offset."""
line = bisect_right(self.line_starts, offset) - 1
character = offset - self.line_starts[line]
return Position(line=line, character=character)
| PositionLookup |
python | python__mypy | mypy/join.py | {
"start": 1142,
"end": 10295
} | class ____:
def __init__(self) -> None:
self.seen_instances: list[tuple[Instance, Instance]] = []
def join_instances(self, t: Instance, s: Instance) -> ProperType:
if (t, s) in self.seen_instances or (s, t) in self.seen_instances:
return object_from_instance(t)
self.seen_instances.append((t, s))
# Calculate the join of two instance types
if t.type == s.type:
# Simplest case: join two types with the same base type (but
# potentially different arguments).
# Combine type arguments.
args: list[Type] = []
# N.B: We use zip instead of indexing because the lengths might have
# mismatches during daemon reprocessing.
if t.type.has_type_var_tuple_type:
# We handle joins of variadic instances by simply creating correct mapping
# for type arguments and compute the individual joins same as for regular
# instances. All the heavy lifting is done in the join of tuple types.
assert s.type.type_var_tuple_prefix is not None
assert s.type.type_var_tuple_suffix is not None
prefix = s.type.type_var_tuple_prefix
suffix = s.type.type_var_tuple_suffix
tvt = s.type.defn.type_vars[prefix]
assert isinstance(tvt, TypeVarTupleType)
fallback = tvt.tuple_fallback
s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix(s.args, prefix, suffix)
t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(t.args, prefix, suffix)
s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix
t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix
else:
t_args = t.args
s_args = s.args
for ta, sa, type_var in zip(t_args, s_args, t.type.defn.type_vars):
ta_proper = get_proper_type(ta)
sa_proper = get_proper_type(sa)
new_type: Type | None = None
if isinstance(ta_proper, AnyType):
new_type = AnyType(TypeOfAny.from_another_any, ta_proper)
elif isinstance(sa_proper, AnyType):
new_type = AnyType(TypeOfAny.from_another_any, sa_proper)
elif isinstance(type_var, TypeVarType):
if type_var.variance in (COVARIANT, VARIANCE_NOT_READY):
new_type = join_types(ta, sa, self)
if len(type_var.values) != 0 and new_type not in type_var.values:
self.seen_instances.pop()
return object_from_instance(t)
if not is_subtype(new_type, type_var.upper_bound):
self.seen_instances.pop()
return object_from_instance(t)
# TODO: contravariant case should use meet but pass seen instances as
# an argument to keep track of recursive checks.
elif type_var.variance in (INVARIANT, CONTRAVARIANT):
if isinstance(ta_proper, UninhabitedType) and ta_proper.ambiguous:
new_type = sa
elif isinstance(sa_proper, UninhabitedType) and sa_proper.ambiguous:
new_type = ta
elif not is_equivalent(ta, sa):
self.seen_instances.pop()
return object_from_instance(t)
else:
# If the types are different but equivalent, then an Any is involved
# so using a join in the contravariant case is also OK.
new_type = join_types(ta, sa, self)
elif isinstance(type_var, TypeVarTupleType):
new_type = get_proper_type(join_types(ta, sa, self))
# Put the joined arguments back into instance in the normal form:
# a) Tuple[X, Y, Z] -> [X, Y, Z]
# b) tuple[X, ...] -> [*tuple[X, ...]]
if isinstance(new_type, Instance):
assert new_type.type.fullname == "builtins.tuple"
new_type = UnpackType(new_type)
else:
assert isinstance(new_type, TupleType)
args.extend(new_type.items)
continue
else:
# ParamSpec type variables behave the same, independent of variance
if not is_equivalent(ta, sa):
return get_proper_type(type_var.upper_bound)
new_type = join_types(ta, sa, self)
assert new_type is not None
args.append(new_type)
result: ProperType = Instance(t.type, args)
elif t.type.bases and is_proper_subtype(
t, s, subtype_context=SubtypeContext(ignore_type_params=True)
):
result = self.join_instances_via_supertype(t, s)
else:
# Now t is not a subtype of s, and t != s. Now s could be a subtype
# of t; alternatively, we need to find a common supertype. This works
# in of the both cases.
result = self.join_instances_via_supertype(s, t)
self.seen_instances.pop()
return result
def join_instances_via_supertype(self, t: Instance, s: Instance) -> ProperType:
# Give preference to joins via duck typing relationship, so that
# join(int, float) == float, for example.
for p in t.type._promote:
if is_subtype(p, s):
return join_types(p, s, self)
for p in s.type._promote:
if is_subtype(p, t):
return join_types(t, p, self)
# Compute the "best" supertype of t when joined with s.
# The definition of "best" may evolve; for now it is the one with
# the longest MRO. Ties are broken by using the earlier base.
# Go over both sets of bases in case there's an explicit Protocol base. This is important
# to ensure commutativity of join (although in cases where both classes have relevant
# Protocol bases this maybe might still not be commutative)
base_types: dict[TypeInfo, None] = {} # dict to deduplicate but preserve order
for base in t.type.bases:
base_types[base.type] = None
for base in s.type.bases:
if base.type.is_protocol and is_subtype(t, base):
base_types[base.type] = None
best: ProperType | None = None
for base_type in base_types:
mapped = map_instance_to_supertype(t, base_type)
res = self.join_instances(mapped, s)
if best is None or is_better(res, best):
best = res
assert best is not None
for promote in t.type._promote:
if isinstance(promote, Instance):
res = self.join_instances(promote, s)
if is_better(res, best):
best = res
return best
def trivial_join(s: Type, t: Type) -> Type:
"""Return one of types (expanded) if it is a supertype of other, otherwise top type."""
if is_subtype(s, t):
return t
elif is_subtype(t, s):
return s
else:
return object_or_any_from_type(get_proper_type(t))
@overload
def join_types(
s: ProperType, t: ProperType, instance_joiner: InstanceJoiner | None = None
) -> ProperType: ...
@overload
def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type: ...
def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type:
"""Return the least upper bound of s and t.
For example, the join of 'int' and 'object' is 'object'.
"""
if mypy.typeops.is_recursive_pair(s, t):
# This case can trigger an infinite recursion, general support for this will be
# tricky so we use a trivial join (like for protocols).
return trivial_join(s, t)
s = get_proper_type(s)
t = get_proper_type(t)
if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false):
# if types are restricted in different ways, use the more general versions
s = mypy.typeops.true_or_false(s)
t = mypy.typeops.true_or_false(t)
if isinstance(s, UnionType) and not isinstance(t, UnionType):
s, t = t, s
if isinstance(s, AnyType):
return s
if isinstance(s, ErasedType):
return t
if isinstance(s, NoneType) and not isinstance(t, NoneType):
s, t = t, s
if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType):
s, t = t, s
# Meets/joins require callable type normalization.
s, t = normalize_callables(s, t)
# Use a visitor to handle non-trivial cases.
return t.accept(TypeJoinVisitor(s, instance_joiner))
| InstanceJoiner |
python | sympy__sympy | sympy/geometry/parabola.py | {
"start": 523,
"end": 10716
} | class ____(GeometrySet):
"""A parabolic GeometryEntity.
A parabola is declared with a point, that is called 'focus', and
a line, that is called 'directrix'.
Only vertical or horizontal parabolas are currently supported.
Parameters
==========
focus : Point
Default value is Point(0, 0)
directrix : Line
Attributes
==========
focus
directrix
axis of symmetry
focal length
p parameter
vertex
eccentricity
Raises
======
ValueError
When `focus` is not a two dimensional point.
When `focus` is a point of directrix.
NotImplementedError
When `directrix` is neither horizontal nor vertical.
Examples
========
>>> from sympy import Parabola, Point, Line
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7,8)))
>>> p1.focus
Point2D(0, 0)
>>> p1.directrix
Line2D(Point2D(5, 8), Point2D(7, 8))
"""
def __new__(cls, focus=None, directrix=None, **kwargs):
if focus:
focus = Point(focus, dim=2)
else:
focus = Point(0, 0)
directrix = Line(directrix)
if directrix.contains(focus):
raise ValueError('The focus must not be a point of directrix')
return GeometryEntity.__new__(cls, focus, directrix, **kwargs)
@property
def ambient_dimension(self):
"""Returns the ambient dimension of parabola.
Returns
=======
ambient_dimension : integer
Examples
========
>>> from sympy import Parabola, Point, Line
>>> f1 = Point(0, 0)
>>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8)))
>>> p1.ambient_dimension
2
"""
return 2
@property
def axis_of_symmetry(self):
"""Return the axis of symmetry of the parabola: a line
perpendicular to the directrix passing through the focus.
Returns
=======
axis_of_symmetry : Line
See Also
========
sympy.geometry.line.Line
Examples
========
>>> from sympy import Parabola, Point, Line
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
>>> p1.axis_of_symmetry
Line2D(Point2D(0, 0), Point2D(0, 1))
"""
return self.directrix.perpendicular_line(self.focus)
@property
def directrix(self):
"""The directrix of the parabola.
Returns
=======
directrix : Line
See Also
========
sympy.geometry.line.Line
Examples
========
>>> from sympy import Parabola, Point, Line
>>> l1 = Line(Point(5, 8), Point(7, 8))
>>> p1 = Parabola(Point(0, 0), l1)
>>> p1.directrix
Line2D(Point2D(5, 8), Point2D(7, 8))
"""
return self.args[1]
@property
def eccentricity(self):
"""The eccentricity of the parabola.
Returns
=======
eccentricity : number
A parabola may also be characterized as a conic section with an
eccentricity of 1. As a consequence of this, all parabolas are
similar, meaning that while they can be different sizes,
they are all the same shape.
See Also
========
https://en.wikipedia.org/wiki/Parabola
Examples
========
>>> from sympy import Parabola, Point, Line
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
>>> p1.eccentricity
1
Notes
-----
The eccentricity for every Parabola is 1 by definition.
"""
return S.One
def equation(self, x='x', y='y'):
"""The equation of the parabola.
Parameters
==========
x : str, optional
Label for the x-axis. Default value is 'x'.
y : str, optional
Label for the y-axis. Default value is 'y'.
Returns
=======
equation : SymPy expression
Examples
========
>>> from sympy import Parabola, Point, Line
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
>>> p1.equation()
-x**2 - 16*y + 64
>>> p1.equation('f')
-f**2 - 16*y + 64
>>> p1.equation(y='z')
-x**2 - 16*z + 64
"""
x = _symbol(x, real=True)
y = _symbol(y, real=True)
m = self.directrix.slope
if m is S.Infinity:
t1 = 4 * (self.p_parameter) * (x - self.vertex.x)
t2 = (y - self.vertex.y)**2
elif m == 0:
t1 = 4 * (self.p_parameter) * (y - self.vertex.y)
t2 = (x - self.vertex.x)**2
else:
a, b = self.focus
c, d = self.directrix.coefficients[:2]
t1 = (x - a)**2 + (y - b)**2
t2 = self.directrix.equation(x, y)**2/(c**2 + d**2)
return t1 - t2
@property
def focal_length(self):
"""The focal length of the parabola.
Returns
=======
focal_lenght : number or symbolic expression
Notes
=====
The distance between the vertex and the focus
(or the vertex and directrix), measured along the axis
of symmetry, is the "focal length".
See Also
========
https://en.wikipedia.org/wiki/Parabola
Examples
========
>>> from sympy import Parabola, Point, Line
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
>>> p1.focal_length
4
"""
distance = self.directrix.distance(self.focus)
focal_length = distance/2
return focal_length
@property
def focus(self):
"""The focus of the parabola.
Returns
=======
focus : Point
See Also
========
sympy.geometry.point.Point
Examples
========
>>> from sympy import Parabola, Point, Line
>>> f1 = Point(0, 0)
>>> p1 = Parabola(f1, Line(Point(5, 8), Point(7, 8)))
>>> p1.focus
Point2D(0, 0)
"""
return self.args[0]
def intersection(self, o):
"""The intersection of the parabola and another geometrical entity `o`.
Parameters
==========
o : GeometryEntity, LinearEntity
Returns
=======
intersection : list of GeometryEntity objects
Examples
========
>>> from sympy import Parabola, Point, Ellipse, Line, Segment
>>> p1 = Point(0,0)
>>> l1 = Line(Point(1, -2), Point(-1,-2))
>>> parabola1 = Parabola(p1, l1)
>>> parabola1.intersection(Ellipse(Point(0, 0), 2, 5))
[Point2D(-2, 0), Point2D(2, 0)]
>>> parabola1.intersection(Line(Point(-7, 3), Point(12, 3)))
[Point2D(-4, 3), Point2D(4, 3)]
>>> parabola1.intersection(Segment((-12, -65), (14, -68)))
[]
"""
x, y = symbols('x y', real=True)
parabola_eq = self.equation()
if isinstance(o, Parabola):
if o in self:
return [o]
else:
return list(ordered([Point(i) for i in solve(
[parabola_eq, o.equation()], [x, y], set=True)[1]]))
elif isinstance(o, Point2D):
if simplify(parabola_eq.subs([(x, o._args[0]), (y, o._args[1])])) == 0:
return [o]
else:
return []
elif isinstance(o, (Segment2D, Ray2D)):
result = solve([parabola_eq,
Line2D(o.points[0], o.points[1]).equation()],
[x, y], set=True)[1]
return list(ordered([Point2D(i) for i in result if i in o]))
elif isinstance(o, (Line2D, Ellipse)):
return list(ordered([Point2D(i) for i in solve(
[parabola_eq, o.equation()], [x, y], set=True)[1]]))
elif isinstance(o, LinearEntity3D):
raise TypeError('Entity must be two dimensional, not three dimensional')
else:
raise TypeError('Wrong type of argument were put')
@property
def p_parameter(self):
"""P is a parameter of parabola.
Returns
=======
p : number or symbolic expression
Notes
=====
The absolute value of p is the focal length. The sign on p tells
which way the parabola faces. Vertical parabolas that open up
and horizontal that open right, give a positive value for p.
Vertical parabolas that open down and horizontal that open left,
give a negative value for p.
See Also
========
https://www.sparknotes.com/math/precalc/conicsections/section2/
Examples
========
>>> from sympy import Parabola, Point, Line
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
>>> p1.p_parameter
-4
"""
m = self.directrix.slope
if m is S.Infinity:
x = self.directrix.coefficients[2]
p = sign(self.focus.args[0] + x)
elif m == 0:
y = self.directrix.coefficients[2]
p = sign(self.focus.args[1] + y)
else:
d = self.directrix.projection(self.focus)
p = sign(self.focus.x - d.x)
return p * self.focal_length
@property
def vertex(self):
"""The vertex of the parabola.
Returns
=======
vertex : Point
See Also
========
sympy.geometry.point.Point
Examples
========
>>> from sympy import Parabola, Point, Line
>>> p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7, 8)))
>>> p1.vertex
Point2D(0, 4)
"""
focus = self.focus
m = self.directrix.slope
if m is S.Infinity:
vertex = Point(focus.args[0] - self.p_parameter, focus.args[1])
elif m == 0:
vertex = Point(focus.args[0], focus.args[1] - self.p_parameter)
else:
vertex = self.axis_of_symmetry.intersection(self)[0]
return vertex
| Parabola |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/dtrun2/package.py | {
"start": 217,
"end": 450
} | class ____(Package):
"""Simple package which acts as a run dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/dtrun2-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
| Dtrun2 |
python | getlogbook__logbook | src/logbook/queues.py | {
"start": 23036,
"end": 24409
} | class ____(SubscriberBase):
"""This is a subscriber which represents a group of subscribers.
This is helpful if you are writing a server-like application which has
"slaves". This way a user is easily able to view every log record which
happened somewhere in the entire system without having to check every
single slave::
subscribers = SubscriberGroup(
[MultiProcessingSubscriber(queue), ZeroMQSubscriber("tcp://127.0.0.1:5000")]
)
with target_handler:
subscribers.dispatch_forever()
"""
def __init__(self, subscribers=None, queue_limit=10):
self.members = []
self.queue = ThreadQueue(queue_limit)
for subscriber in subscribers or []:
self.add(subscriber)
def add(self, subscriber):
"""Adds the given `subscriber` to the group."""
member = GroupMember(subscriber, self.queue)
member.start()
self.members.append(member)
def recv(self, timeout=None):
try:
return self.queue.get(timeout=timeout)
except Empty:
return
def stop(self):
"""Stops the group from internally recieving any more messages, once the
internal queue is exhausted :meth:`recv` will always return `None`.
"""
for member in self.members:
member.stop()
| SubscriberGroup |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride6.py | {
"start": 4078,
"end": 4409
} | class ____(Generic[_T]):
@overload
def m1(self: "Parent4[int]", a: None) -> float: ...
@overload
def m1(self: "Parent4[int]", a: int) -> float: ...
@overload
def m1(self: "Parent4[float]", a: None) -> str: ...
def m1(self, a: int | None = None) -> float | str:
raise NotImplementedError
| Parent4 |
python | redis__redis-py | tests/test_maint_notifications.py | {
"start": 9353,
"end": 10926
} | class ____:
"""Test the NodeMigratingNotification class."""
def test_init(self):
"""Test NodeMigratingNotification initialization."""
with patch("time.monotonic", return_value=1000):
notification = NodeMigratingNotification(id=1, ttl=5)
assert notification.id == 1
assert notification.ttl == 5
assert notification.creation_time == 1000
def test_repr(self):
"""Test NodeMigratingNotification string representation."""
with patch("time.monotonic", return_value=1000):
notification = NodeMigratingNotification(id=1, ttl=5)
with patch("time.monotonic", return_value=1002): # 2 seconds later
repr_str = repr(notification)
assert "NodeMigratingNotification" in repr_str
assert "id=1" in repr_str
assert "ttl=5" in repr_str
assert "remaining=3.0s" in repr_str
assert "expired=False" in repr_str
def test_equality_and_hash(self):
"""Test equality and hash for NodeMigratingNotification."""
notification1 = NodeMigratingNotification(id=1, ttl=5)
notification2 = NodeMigratingNotification(
id=1, ttl=10
) # Same id, different ttl
notification3 = NodeMigratingNotification(id=2, ttl=5) # Different id
assert notification1 == notification2
assert notification1 != notification3
assert hash(notification1) == hash(notification2)
assert hash(notification1) != hash(notification3)
| TestNodeMigratingNotification |
python | charliermarsh__ruff | crates/ty_python_semantic/resources/corpus/73_class_generic_tuple.py | {
"start": 0,
"end": 24
} | class ____[*T]:
x: T
| Foo |
python | pytorch__pytorch | torch/_inductor/fx_passes/reinplace.py | {
"start": 1334,
"end": 2299
} | class ____:
inplace_op: Callable[..., Any]
mutated_arg: int
extra_check: Callable[[torch.fx.Node], bool] = lambda node: True
_SCATTER_OP_TO_VIEW = {
torch.ops.aten.diagonal_scatter.default: torch.ops.aten.diagonal.default,
torch.ops.aten.select_scatter.default: torch.ops.aten.select.int,
torch.ops.aten.slice_scatter.default: torch.ops.aten.slice.Tensor,
torch.ops.aten.as_strided_scatter.default: torch.ops.aten.as_strided.default,
}
_VIEW_OP_TO_SCATTER = {v: k for k, v in _SCATTER_OP_TO_VIEW.items()}
def graph_call_function(graph: torch.fx.Graph, fn, *args, **kwargs):
fake_args, fake_kwargs = pytree.tree_map(
lambda node: node.meta["val"] if isinstance(node, torch.fx.Node) else node,
(args, kwargs),
)
with V.fake_mode:
fake_result = fn(*fake_args, **fake_kwargs)
node = graph.call_function(fn, args, kwargs)
node.meta["val"] = fake_result
return node
@dataclass
| InplaceableOp |
python | ansible__ansible | lib/ansible/module_utils/facts/hardware/base.py | {
"start": 1768,
"end": 2003
} | class ____:
platform = 'Generic'
# FIXME: remove load_on_init when we can
def __init__(self, module, load_on_init=False):
self.module = module
def populate(self, collected_facts=None):
return {}
| Hardware |
python | facebookresearch__faiss | tests/test_contrib_with_scipy.py | {
"start": 388,
"end": 2019
} | class ____(unittest.TestCase):
def test_sparse_routines(self):
""" the sparse assignment routine """
ds = datasets.SyntheticDataset(1000, 2000, 0, 200)
xt = ds.get_train().copy()
faiss.normalize_L2(xt)
mask = np.abs(xt) > 0.045
xt[np.logical_not(mask)] = 0
centroids = ds.get_queries()
assert len(centroids) == 200
xsparse = scipy.sparse.csr_matrix(xt)
Dref, Iref = faiss.knn(xsparse.todense(), centroids, 1)
D, I = clustering.sparse_assign_to_dense(xsparse, centroids)
np.testing.assert_array_equal(Iref.ravel(), I)
np.testing.assert_array_almost_equal(Dref.ravel(), D, decimal=3)
D, I = clustering.sparse_assign_to_dense_blocks(
xsparse, centroids, qbs=123, bbs=33, nt=4)
np.testing.assert_array_equal(Iref.ravel(), I)
np.testing.assert_array_almost_equal(Dref.ravel(), D, decimal=3)
def test_sparse_kmeans(self):
""" demo on how to cluster sparse data into dense clusters """
ds = datasets.SyntheticDataset(1000, 1500, 0, 0)
xt = ds.get_train().copy()
faiss.normalize_L2(xt)
mask = np.abs(xt) > 0.045
xt[np.logical_not(mask)] = 0
km = faiss.Kmeans(ds.d, 50)
km.train(xt)
ref_err = km.iteration_stats[-1]["obj"]
xsparse = scipy.sparse.csr_matrix(xt)
centroids, iteration_stats = clustering.kmeans(
50, clustering.DatasetAssignSparse(xsparse), return_stats=True)
new_err = iteration_stats[-1]["obj"]
self.assertLess(new_err, ref_err * 1.1)
| TestClustering |
python | huggingface__transformers | src/transformers/models/edgetam/modular_edgetam.py | {
"start": 6357,
"end": 6427
} | class ____(Sam2FeedForward):
pass
@auto_docstring
| EdgeTamFeedForward |
python | numba__numba | numba/tests/test_operators.py | {
"start": 45552,
"end": 45637
} | class ____(TestMixedInts):
op = FunctionalOperatorImpl
| TestMixedIntsOperatorModule |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_project_forms.py | {
"start": 40599,
"end": 44688
} | class ____(TestCase):
def setUp(self):
self.project = get(Project)
def test_use_invalid_names(self):
data = {
"name": "VARIABLE WITH SPACES",
"value": "string here",
}
form = EnvironmentVariableForm(data, project=self.project)
self.assertFalse(form.is_valid())
self.assertIn(
"Variable name can't contain spaces",
form.errors["name"],
)
data = {
"name": "READTHEDOCS__INVALID",
"value": "string here",
}
form = EnvironmentVariableForm(data, project=self.project)
self.assertFalse(form.is_valid())
self.assertIn(
"Variable name can't start with READTHEDOCS",
form.errors["name"],
)
data = {
"name": "INVALID_CHAR*",
"value": "string here",
}
form = EnvironmentVariableForm(data, project=self.project)
self.assertFalse(form.is_valid())
self.assertIn(
"Only letters, numbers and underscore are allowed",
form.errors["name"],
)
data = {
"name": "__INVALID",
"value": "string here",
}
form = EnvironmentVariableForm(data, project=self.project)
self.assertFalse(form.is_valid())
self.assertIn(
"Variable name can't start with __ (double underscore)",
form.errors["name"],
)
get(EnvironmentVariable, name="EXISTENT_VAR", project=self.project)
data = {
"name": "EXISTENT_VAR",
"value": "string here",
}
form = EnvironmentVariableForm(data, project=self.project)
self.assertFalse(form.is_valid())
self.assertIn(
"There is already a variable with this name for this project",
form.errors["name"],
)
def test_create(self):
data = {
"name": "MYTOKEN",
"value": "string here",
}
form = EnvironmentVariableForm(data, project=self.project)
form.save()
self.assertEqual(EnvironmentVariable.objects.count(), 1)
self.assertEqual(EnvironmentVariable.objects.latest().name, "MYTOKEN")
self.assertEqual(EnvironmentVariable.objects.latest().value, "'string here'")
data = {
"name": "ESCAPED",
"value": r"string escaped here: #$\1[]{}\|",
}
form = EnvironmentVariableForm(data, project=self.project)
form.save()
self.assertEqual(EnvironmentVariable.objects.count(), 2)
self.assertEqual(EnvironmentVariable.objects.latest().name, "ESCAPED")
self.assertEqual(
EnvironmentVariable.objects.latest().value,
r"'string escaped here: #$\1[]{}\|'",
)
def test_create_env_variable_with_long_value(self):
data = {
"name": "MYTOKEN",
"value": "a" * (48000 + 1),
}
form = EnvironmentVariableForm(data, project=self.project)
assert not form.is_valid()
assert form.errors["value"] == [
"Ensure this value has at most 48000 characters (it has 48001)."
]
def test_create_env_variable_over_total_project_size(self):
size = 2000
for i in range((MAX_SIZE_ENV_VARS_PER_PROJECT - size) // size):
get(
EnvironmentVariable,
project=self.project,
name=f"ENVVAR{i}",
value="a" * size,
public=False,
)
form = EnvironmentVariableForm(
{"name": "A", "value": "a" * (size // 2)}, project=self.project
)
assert form.is_valid()
form.save()
form = EnvironmentVariableForm(
{"name": "B", "value": "a" * size}, project=self.project
)
assert not form.is_valid()
assert form.errors["__all__"] == [
"The total size of all environment variables in the project cannot exceed 256 KB."
]
| TestProjectEnvironmentVariablesForm |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/mlengine.py | {
"start": 2137,
"end": 2380
} | class ____(BaseGoogleLink):
"""Helper class for constructing ML Engine link."""
name = "MLEngine Version Details"
key = "ml_engine_version_details"
format_str = MLENGINE_MODEL_VERSION_DETAILS_LINK
| MLEngineModelVersionDetailsLink |
python | django__django | django/contrib/redirects/migrations/0001_initial.py | {
"start": 43,
"end": 2093
} | class ____(migrations.Migration):
dependencies = [
("sites", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="Redirect",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"site",
models.ForeignKey(
to="sites.Site",
on_delete=models.CASCADE,
verbose_name="site",
),
),
(
"old_path",
models.CharField(
help_text=(
"This should be an absolute path, excluding the domain "
"name. Example: “/events/search/”."
),
max_length=200,
verbose_name="redirect from",
db_index=True,
),
),
(
"new_path",
models.CharField(
help_text=(
"This can be either an absolute path (as above) or a full "
"URL starting with “http://”."
),
max_length=200,
verbose_name="redirect to",
blank=True,
),
),
],
options={
"ordering": ["old_path"],
"unique_together": {("site", "old_path")},
"db_table": "django_redirect",
"verbose_name": "redirect",
"verbose_name_plural": "redirects",
},
bases=(models.Model,),
),
]
| Migration |
python | numba__numba | numba/cuda/tests/cudapy/test_ufuncs.py | {
"start": 882,
"end": 9680
} | class ____(BasicUFuncTest, TestCase):
_numba_parallel_test_ = False
def setUp(self):
BasicUFuncTest.setUp(self)
# The basic ufunc test does not set up complex inputs, so we'll add
# some here for testing with CUDA.
self.inputs.extend([
(np.complex64(-0.5 - 0.5j), types.complex64),
(np.complex64(0.0), types.complex64),
(np.complex64(0.5 + 0.5j), types.complex64),
(np.complex128(-0.5 - 0.5j), types.complex128),
(np.complex128(0.0), types.complex128),
(np.complex128(0.5 + 0.5j), types.complex128),
(np.array([-0.5 - 0.5j, 0.0, 0.5 + 0.5j], dtype='c8'),
types.Array(types.complex64, 1, 'C')),
(np.array([-0.5 - 0.5j, 0.0, 0.5 + 0.5j], dtype='c16'),
types.Array(types.complex128, 1, 'C')),
])
# Test with multiple dimensions
self.inputs.extend([
# Basic 2D and 3D arrays
(np.linspace(0, 1).reshape((5, -1)),
types.Array(types.float64, 2, 'C')),
(np.linspace(0, 1).reshape((2, 5, -1)),
types.Array(types.float64, 3, 'C')),
# Complex data (i.e. interleaved)
(np.linspace(0, 1 + 1j).reshape(5, -1),
types.Array(types.complex128, 2, 'C')),
# F-ordered
(np.asfortranarray(np.linspace(0, 1).reshape((5, -1))),
types.Array(types.float64, 2, 'F')),
])
# Add tests for other integer types
self.inputs.extend([
(np.uint8(0), types.uint8),
(np.uint8(1), types.uint8),
(np.int8(-1), types.int8),
(np.int8(0), types.int8),
(np.uint16(0), types.uint16),
(np.uint16(1), types.uint16),
(np.int16(-1), types.int16),
(np.int16(0), types.int16),
(np.ulonglong(0), types.ulonglong),
(np.ulonglong(1), types.ulonglong),
(np.longlong(-1), types.longlong),
(np.longlong(0), types.longlong),
(np.array([0,1], dtype=np.ulonglong),
types.Array(types.ulonglong, 1, 'C')),
(np.array([0,1], dtype=np.longlong),
types.Array(types.longlong, 1, 'C')),
])
self._low_occupancy_warnings = config.CUDA_LOW_OCCUPANCY_WARNINGS
self._warn_on_implicit_copy = config.CUDA_WARN_ON_IMPLICIT_COPY
# Disable warnings about low gpu utilization in the test suite
config.CUDA_LOW_OCCUPANCY_WARNINGS = 0
# Disable warnings about host arrays in the test suite
config.CUDA_WARN_ON_IMPLICIT_COPY = 0
def tearDown(self):
# Restore original warning settings
config.CUDA_LOW_OCCUPANCY_WARNINGS = self._low_occupancy_warnings
config.CUDA_WARN_ON_IMPLICIT_COPY = self._warn_on_implicit_copy
def _make_ufunc_usecase(self, ufunc):
return _make_ufunc_usecase(ufunc)
@functools.lru_cache(maxsize=None)
def _compile(self, pyfunc, args):
# We return an already-configured kernel so that basic_ufunc_test can
# call it just like it does for a CPU function
return cuda.jit(args)(pyfunc)[1, 1]
def basic_int_ufunc_test(self, name=None):
skip_inputs = [
types.float32,
types.float64,
types.Array(types.float32, 1, 'C'),
types.Array(types.float32, 2, 'C'),
types.Array(types.float64, 1, 'C'),
types.Array(types.float64, 2, 'C'),
types.Array(types.float64, 3, 'C'),
types.Array(types.float64, 2, 'F'),
types.complex64,
types.complex128,
types.Array(types.complex64, 1, 'C'),
types.Array(types.complex64, 2, 'C'),
types.Array(types.complex128, 1, 'C'),
types.Array(types.complex128, 2, 'C'),
]
self.basic_ufunc_test(name, skip_inputs=skip_inputs)
############################################################################
# Trigonometric Functions
def test_sin_ufunc(self):
self.basic_ufunc_test(np.sin, kinds='cf')
def test_cos_ufunc(self):
self.basic_ufunc_test(np.cos, kinds='cf')
def test_tan_ufunc(self):
self.basic_ufunc_test(np.tan, kinds='cf')
def test_arcsin_ufunc(self):
self.basic_ufunc_test(np.arcsin, kinds='cf')
def test_arccos_ufunc(self):
self.basic_ufunc_test(np.arccos, kinds='cf')
def test_arctan_ufunc(self):
self.basic_ufunc_test(np.arctan, kinds='cf')
def test_arctan2_ufunc(self):
self.basic_ufunc_test(np.arctan2, kinds='f')
def test_hypot_ufunc(self):
self.basic_ufunc_test(np.hypot, kinds='f')
def test_sinh_ufunc(self):
self.basic_ufunc_test(np.sinh, kinds='cf')
def test_cosh_ufunc(self):
self.basic_ufunc_test(np.cosh, kinds='cf')
def test_tanh_ufunc(self):
self.basic_ufunc_test(np.tanh, kinds='cf')
def test_arcsinh_ufunc(self):
self.basic_ufunc_test(np.arcsinh, kinds='cf')
def test_arccosh_ufunc(self):
self.basic_ufunc_test(np.arccosh, kinds='cf')
def test_arctanh_ufunc(self):
# arctanh is only valid is only finite in the range ]-1, 1[
# This means that for any of the integer types it will produce
# conversion from infinity/-infinity to integer. That's undefined
# behavior in C, so the results may vary from implementation to
# implementation. This means that the result from the compiler
# used to compile NumPy may differ from the result generated by
# llvm. Skipping the integer types in this test avoids failed
# tests because of this.
to_skip = [types.Array(types.uint32, 1, 'C'), types.uint32,
types.Array(types.int32, 1, 'C'), types.int32,
types.Array(types.uint64, 1, 'C'), types.uint64,
types.Array(types.int64, 1, 'C'), types.int64]
self.basic_ufunc_test(np.arctanh, skip_inputs=to_skip, kinds='cf')
def test_deg2rad_ufunc(self):
self.basic_ufunc_test(np.deg2rad, kinds='f')
def test_rad2deg_ufunc(self):
self.basic_ufunc_test(np.rad2deg, kinds='f')
def test_degrees_ufunc(self):
self.basic_ufunc_test(np.degrees, kinds='f')
def test_radians_ufunc(self):
self.basic_ufunc_test(np.radians, kinds='f')
############################################################################
# Comparison functions
def test_greater_ufunc(self):
self.signed_unsigned_cmp_test(np.greater)
def test_greater_equal_ufunc(self):
self.signed_unsigned_cmp_test(np.greater_equal)
def test_less_ufunc(self):
self.signed_unsigned_cmp_test(np.less)
def test_less_equal_ufunc(self):
self.signed_unsigned_cmp_test(np.less_equal)
def test_not_equal_ufunc(self):
self.signed_unsigned_cmp_test(np.not_equal)
def test_equal_ufunc(self):
self.signed_unsigned_cmp_test(np.equal)
def test_logical_and_ufunc(self):
self.basic_ufunc_test(np.logical_and)
def test_logical_or_ufunc(self):
self.basic_ufunc_test(np.logical_or)
def test_logical_xor_ufunc(self):
self.basic_ufunc_test(np.logical_xor)
def test_logical_not_ufunc(self):
self.basic_ufunc_test(np.logical_not)
def test_maximum_ufunc(self):
self.basic_ufunc_test(np.maximum)
def test_minimum_ufunc(self):
self.basic_ufunc_test(np.minimum)
def test_fmax_ufunc(self):
self.basic_ufunc_test(np.fmax)
def test_fmin_ufunc(self):
self.basic_ufunc_test(np.fmin)
def test_bitwise_and_ufunc(self):
self.basic_int_ufunc_test(np.bitwise_and)
def test_bitwise_or_ufunc(self):
self.basic_int_ufunc_test(np.bitwise_or)
def test_bitwise_xor_ufunc(self):
self.basic_int_ufunc_test(np.bitwise_xor)
def test_invert_ufunc(self):
self.basic_int_ufunc_test(np.invert)
def test_bitwise_not_ufunc(self):
self.basic_int_ufunc_test(np.bitwise_not)
# Note: there is no entry for np.left_shift and np.right_shift
# because their implementations in NumPy have undefined behavior
# when the second argument is a negative. See the comment in
# numba/tests/test_ufuncs.py for more details.
############################################################################
# Mathematical Functions
def test_log_ufunc(self):
self.basic_ufunc_test(np.log, kinds='cf')
def test_log2_ufunc(self):
self.basic_ufunc_test(np.log2, kinds='cf')
def test_log10_ufunc(self):
self.basic_ufunc_test(np.log10, kinds='cf')
if __name__ == '__main__':
unittest.main()
| TestUFuncs |
python | openai__openai-python | src/openai/types/responses/response_reasoning_summary_part_added_event.py | {
"start": 400,
"end": 1006
} | class ____(BaseModel):
item_id: str
"""The ID of the item this summary part is associated with."""
output_index: int
"""The index of the output item this summary part is associated with."""
part: Part
"""The summary part that was added."""
sequence_number: int
"""The sequence number of this event."""
summary_index: int
"""The index of the summary part within the reasoning summary."""
type: Literal["response.reasoning_summary_part.added"]
"""The type of the event. Always `response.reasoning_summary_part.added`."""
| ResponseReasoningSummaryPartAddedEvent |
python | getsentry__sentry | src/sentry/rules/conditions/event_attribute.py | {
"start": 12901,
"end": 13357
} | class ____(AttributeHandler):
minimum_path_length = 2
@classmethod
def _handle(cls, path: list[str], event: GroupEvent) -> list[str]:
if path[1] == "crash_type":
contexts = event.data.get("contexts", {})
unreal = contexts.get("unreal")
if unreal is None:
unreal = {}
return [unreal.get(path[1])]
return []
@attribute_registry.register("app")
| UnrealAttributeHandler |
python | pytest-dev__pytest | testing/python/fixtures.py | {
"start": 74801,
"end": 107649
} | class ____:
def test_parametrize(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=["a", "b", "c"])
def arg(request):
return request.param
values = []
def test_param(arg):
values.append(arg)
def test_result():
assert values == list("abc")
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=4)
def test_multiple_parametrization_issue_736(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[1,2,3])
def foo(request):
return request.param
@pytest.mark.parametrize('foobar', [4,5,6])
def test_issue(foo, foobar):
assert foo in [1,2,3]
assert foobar in [4,5,6]
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=9)
@pytest.mark.parametrize(
"param_args",
["'fixt, val'", "'fixt,val'", "['fixt', 'val']", "('fixt', 'val')"],
)
def test_override_parametrized_fixture_issue_979(
self, pytester: Pytester, param_args
) -> None:
"""Make sure a parametrized argument can override a parametrized fixture.
This was a regression introduced in the fix for #736.
"""
pytester.makepyfile(
f"""
import pytest
@pytest.fixture(params=[1, 2])
def fixt(request):
return request.param
@pytest.mark.parametrize({param_args}, [(3, 'x'), (4, 'x')])
def test_foo(fixt, val):
pass
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_scope_session(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="module")
def arg():
values.append(1)
return 1
def test_1(arg):
assert arg == 1
def test_2(arg):
assert arg == 1
assert len(values) == 1
class TestClass(object):
def test3(self, arg):
assert arg == 1
assert len(values) == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=3)
def test_scope_session_exc(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="session")
def fix():
values.append(1)
pytest.skip('skipping')
def test_1(fix):
pass
def test_2(fix):
pass
def test_last():
assert values == [1]
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(skipped=2, passed=1)
def test_scope_session_exc_two_fix(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
m = []
@pytest.fixture(scope="session")
def a():
values.append(1)
pytest.skip('skipping')
@pytest.fixture(scope="session")
def b(a):
m.append(1)
def test_1(b):
pass
def test_2(b):
pass
def test_last():
assert values == [1]
assert m == []
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(skipped=2, passed=1)
def test_scope_exc(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_foo="""
def test_foo(fix):
pass
""",
test_bar="""
def test_bar(fix):
pass
""",
conftest="""
import pytest
reqs = []
@pytest.fixture(scope="session")
def fix(request):
reqs.append(1)
pytest.skip()
@pytest.fixture
def req_list():
return reqs
""",
test_real="""
def test_last(req_list):
assert req_list == [1]
""",
)
reprec = pytester.inline_run()
reprec.assertoutcome(skipped=2, passed=1)
def test_scope_module_uses_session(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="module")
def arg():
values.append(1)
return 1
def test_1(arg):
assert arg == 1
def test_2(arg):
assert arg == 1
assert len(values) == 1
class TestClass(object):
def test3(self, arg):
assert arg == 1
assert len(values) == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=3)
def test_scope_module_and_finalizer(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
finalized_list = []
created_list = []
@pytest.fixture(scope="module")
def arg(request):
created_list.append(1)
assert request.scope == "module"
request.addfinalizer(lambda: finalized_list.append(1))
@pytest.fixture
def created(request):
return len(created_list)
@pytest.fixture
def finalized(request):
return len(finalized_list)
"""
)
pytester.makepyfile(
test_mod1="""
def test_1(arg, created, finalized):
assert created == 1
assert finalized == 0
def test_2(arg, created, finalized):
assert created == 1
assert finalized == 0""",
test_mod2="""
def test_3(arg, created, finalized):
assert created == 2
assert finalized == 1""",
test_mode3="""
def test_4(arg, created, finalized):
assert created == 3
assert finalized == 2
""",
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=4)
def test_scope_mismatch_various(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
finalized = []
created = []
@pytest.fixture(scope="function")
def arg(request):
pass
"""
)
pytester.makepyfile(
test_mod1="""
import pytest
@pytest.fixture(scope="session")
def arg(request):
request.getfixturevalue("arg")
def test_1(arg):
pass
"""
)
result = pytester.runpytest()
assert result.ret != 0
result.stdout.fnmatch_lines(
["*ScopeMismatch*You tried*function*session*request*"]
)
def test_scope_mismatch_already_computed_dynamic(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_it="""
import pytest
@pytest.fixture(scope="function")
def fixfunc(): pass
@pytest.fixture(scope="module")
def fixmod(fixfunc): pass
def test_it(request, fixfunc):
request.getfixturevalue("fixmod")
""",
)
result = pytester.runpytest()
assert result.ret == ExitCode.TESTS_FAILED
result.stdout.fnmatch_lines(
[
"*ScopeMismatch*Requesting fixture stack*",
"test_it.py:6: def fixmod(fixfunc)",
"Requested fixture:",
"test_it.py:3: def fixfunc()",
]
)
def test_dynamic_scope(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
def pytest_addoption(parser):
parser.addoption("--extend-scope", action="store_true", default=False)
def dynamic_scope(fixture_name, config):
if config.getoption("--extend-scope"):
return "session"
return "function"
@pytest.fixture(scope=dynamic_scope)
def dynamic_fixture(calls=[]):
calls.append("call")
return len(calls)
"""
)
pytester.makepyfile(
"""
def test_first(dynamic_fixture):
assert dynamic_fixture == 1
def test_second(dynamic_fixture):
assert dynamic_fixture == 2
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
reprec = pytester.inline_run("--extend-scope")
reprec.assertoutcome(passed=1, failed=1)
def test_dynamic_scope_bad_return(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def dynamic_scope(**_):
return "wrong-scope"
@pytest.fixture(scope=dynamic_scope)
def fixture():
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
"Fixture 'fixture' from test_dynamic_scope_bad_return.py "
"got an unexpected scope value 'wrong-scope'"
)
def test_register_only_with_mark(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture()
def arg():
return 1
"""
)
pytester.makepyfile(
test_mod1="""
import pytest
@pytest.fixture()
def arg(arg):
return arg + 1
def test_1(arg):
assert arg == 2
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_parametrize_and_scope(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module", params=["a", "b", "c"])
def arg(request):
return request.param
values = []
def test_param(arg):
values.append(arg)
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=3)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
assert len(values) == 3
assert "a" in values
assert "b" in values
assert "c" in values
def test_scope_mismatch(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture(scope="function")
def arg(request):
pass
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="session")
def arg(arg):
pass
def test_mismatch(arg):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*ScopeMismatch*", "*1 error*"])
def test_parametrize_separated_order(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module", params=[1, 2])
def arg(request):
return request.param
values = []
def test_1(arg):
values.append(arg)
def test_2(arg):
values.append(arg)
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=4)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
assert values == [1, 1, 2, 2]
def test_module_parametrized_ordering(self, pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
console_output_style=classic
"""
)
pytester.makeconftest(
"""
import pytest
@pytest.fixture(scope="session", params="s1 s2".split())
def sarg():
pass
@pytest.fixture(scope="module", params="m1 m2".split())
def marg():
pass
"""
)
pytester.makepyfile(
test_mod1="""
def test_func(sarg):
pass
def test_func1(marg):
pass
""",
test_mod2="""
def test_func2(sarg):
pass
def test_func3(sarg, marg):
pass
def test_func3b(sarg, marg):
pass
def test_func4(marg):
pass
""",
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
"""
test_mod1.py::test_func[s1] PASSED
test_mod2.py::test_func2[s1] PASSED
test_mod2.py::test_func3[s1-m1] PASSED
test_mod2.py::test_func3b[s1-m1] PASSED
test_mod2.py::test_func3[s1-m2] PASSED
test_mod2.py::test_func3b[s1-m2] PASSED
test_mod1.py::test_func[s2] PASSED
test_mod2.py::test_func2[s2] PASSED
test_mod2.py::test_func3[s2-m1] PASSED
test_mod2.py::test_func3b[s2-m1] PASSED
test_mod2.py::test_func4[m1] PASSED
test_mod2.py::test_func3[s2-m2] PASSED
test_mod2.py::test_func3b[s2-m2] PASSED
test_mod2.py::test_func4[m2] PASSED
test_mod1.py::test_func1[m1] PASSED
test_mod1.py::test_func1[m2] PASSED
"""
)
def test_dynamic_parametrized_ordering(self, pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
console_output_style=classic
"""
)
pytester.makeconftest(
"""
import pytest
def pytest_configure(config):
class DynamicFixturePlugin(object):
@pytest.fixture(scope='session', params=['flavor1', 'flavor2'])
def flavor(self, request):
return request.param
config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture')
@pytest.fixture(scope='session', params=['vxlan', 'vlan'])
def encap(request):
return request.param
@pytest.fixture(scope='session', autouse='True')
def reprovision(request, flavor, encap):
pass
"""
)
pytester.makepyfile(
"""
def test(reprovision):
pass
def test2(reprovision):
pass
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
"""
test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED
test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED
test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED
test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED
test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED
test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED
test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED
test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED
"""
)
def test_class_ordering(self, pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
console_output_style=classic
"""
)
pytester.makeconftest(
"""
import pytest
values = []
@pytest.fixture(scope="function", params=[1,2])
def farg(request):
return request.param
@pytest.fixture(scope="class", params=list("ab"))
def carg(request):
return request.param
@pytest.fixture(scope="function", autouse=True)
def append(request, farg, carg):
def fin():
values.append("fin_%s%s" % (carg, farg))
request.addfinalizer(fin)
"""
)
pytester.makepyfile(
"""
import pytest
class TestClass2(object):
def test_1(self):
pass
def test_2(self):
pass
class TestClass(object):
def test_3(self):
pass
"""
)
result = pytester.runpytest("-vs")
result.stdout.re_match_lines(
r"""
test_class_ordering.py::TestClass2::test_1\[a-1\] PASSED
test_class_ordering.py::TestClass2::test_1\[a-2\] PASSED
test_class_ordering.py::TestClass2::test_2\[a-1\] PASSED
test_class_ordering.py::TestClass2::test_2\[a-2\] PASSED
test_class_ordering.py::TestClass2::test_1\[b-1\] PASSED
test_class_ordering.py::TestClass2::test_1\[b-2\] PASSED
test_class_ordering.py::TestClass2::test_2\[b-1\] PASSED
test_class_ordering.py::TestClass2::test_2\[b-2\] PASSED
test_class_ordering.py::TestClass::test_3\[a-1\] PASSED
test_class_ordering.py::TestClass::test_3\[a-2\] PASSED
test_class_ordering.py::TestClass::test_3\[b-1\] PASSED
test_class_ordering.py::TestClass::test_3\[b-2\] PASSED
"""
)
def test_parametrize_separated_order_higher_scope_first(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="function", params=[1, 2])
def arg(request):
param = request.param
request.addfinalizer(lambda: values.append("fin:%s" % param))
values.append("create:%s" % param)
return request.param
@pytest.fixture(scope="module", params=["mod1", "mod2"])
def modarg(request):
param = request.param
request.addfinalizer(lambda: values.append("fin:%s" % param))
values.append("create:%s" % param)
return request.param
values = []
def test_1(arg):
values.append("test1")
def test_2(modarg):
values.append("test2")
def test_3(arg, modarg):
values.append("test3")
def test_4(modarg, arg):
values.append("test4")
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=12)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
expected = [
"create:1",
"test1",
"fin:1",
"create:2",
"test1",
"fin:2",
"create:mod1",
"test2",
"create:1",
"test3",
"fin:1",
"create:2",
"test3",
"fin:2",
"create:1",
"test4",
"fin:1",
"create:2",
"test4",
"fin:2",
"fin:mod1",
"create:mod2",
"test2",
"create:1",
"test3",
"fin:1",
"create:2",
"test3",
"fin:2",
"create:1",
"test4",
"fin:1",
"create:2",
"test4",
"fin:2",
"fin:mod2",
]
import pprint
pprint.pprint(list(zip_longest(values, expected)))
assert values == expected
def test_parametrized_fixture_teardown_order(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[1,2], scope="class")
def param1(request):
return request.param
values = []
class TestClass(object):
@classmethod
@pytest.fixture(scope="class", autouse=True)
def setup1(self, request, param1):
values.append(1)
request.addfinalizer(self.teardown1)
@classmethod
def teardown1(self):
assert values.pop() == 1
@pytest.fixture(scope="class", autouse=True)
def setup2(self, request, param1):
values.append(2)
request.addfinalizer(self.teardown2)
@classmethod
def teardown2(self):
assert values.pop() == 2
def test(self):
pass
def test_finish():
assert not values
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
"""
*3 passed*
"""
)
assert result.ret == 0
def test_fixture_finalizer(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
import sys
@pytest.fixture
def browser(request):
def finalize():
sys.stdout.write_text('Finalized', encoding='utf-8')
request.addfinalizer(finalize)
return {}
"""
)
b = pytester.mkdir("subdir")
b.joinpath("test_overridden_fixture_finalizer.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def browser(browser):
browser['visited'] = True
return browser
def test_browser(browser):
assert browser['visited'] is True
"""
),
encoding="utf-8",
)
reprec = pytester.runpytest("-s")
for test in ["test_browser"]:
reprec.stdout.fnmatch_lines(["*Finalized*"])
def test_class_scope_with_normal_tests(self, pytester: Pytester) -> None:
testpath = pytester.makepyfile(
"""
import pytest
class Box(object):
value = 0
@pytest.fixture(scope='class')
def a(request):
Box.value += 1
return Box.value
def test_a(a):
assert a == 1
class Test1(object):
def test_b(self, a):
assert a == 2
class Test2(object):
def test_c(self, a):
assert a == 3"""
)
reprec = pytester.inline_run(testpath)
for test in ["test_a", "test_b", "test_c"]:
assert reprec.matchreport(test).passed
def test_request_is_clean(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(params=[1, 2])
def fix(request):
request.addfinalizer(lambda: values.append(request.param))
def test_fix(fix):
pass
"""
)
reprec = pytester.inline_run("-s")
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
assert values == [1, 2]
def test_parametrize_separated_lifecycle(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="module", params=[1, 2])
def arg(request):
x = request.param
request.addfinalizer(lambda: values.append("fin%s" % x))
return request.param
def test_1(arg):
values.append(arg)
def test_2(arg):
values.append(arg)
"""
)
reprec = pytester.inline_run("-vs")
reprec.assertoutcome(passed=4)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
import pprint
pprint.pprint(values)
# assert len(values) == 6
assert values[0] == values[1] == 1
assert values[2] == "fin1"
assert values[3] == values[4] == 2
assert values[5] == "fin2"
def test_parametrize_function_scoped_finalizers_called(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="function", params=[1, 2])
def arg(request):
x = request.param
request.addfinalizer(lambda: values.append("fin%s" % x))
return request.param
values = []
def test_1(arg):
values.append(arg)
def test_2(arg):
values.append(arg)
def test_3():
assert len(values) == 8
assert values == [1, "fin1", 2, "fin2", 1, "fin1", 2, "fin2"]
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=5)
@pytest.mark.parametrize("scope", ["session", "function", "module"])
def test_finalizer_order_on_parametrization(
self, scope, pytester: Pytester
) -> None:
"""#246"""
pytester.makepyfile(
f"""
import pytest
values = []
@pytest.fixture(scope={scope!r}, params=["1"])
def fix1(request):
return request.param
@pytest.fixture(scope={scope!r})
def fix2(request, base):
def cleanup_fix2():
assert not values, "base should not have been finalized"
request.addfinalizer(cleanup_fix2)
@pytest.fixture(scope={scope!r})
def base(request, fix1):
def cleanup_base():
values.append("fin_base")
print("finalizing base")
request.addfinalizer(cleanup_base)
def test_begin():
pass
def test_baz(base, fix2):
pass
def test_other():
pass
"""
)
reprec = pytester.inline_run("-lvs")
reprec.assertoutcome(passed=3)
def test_class_scope_parametrization_ordering(self, pytester: Pytester) -> None:
"""#396"""
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(params=["John", "Doe"], scope="class")
def human(request):
request.addfinalizer(lambda: values.append("fin %s" % request.param))
return request.param
class TestGreetings(object):
def test_hello(self, human):
values.append("test_hello")
class TestMetrics(object):
def test_name(self, human):
values.append("test_name")
def test_population(self, human):
values.append("test_population")
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=6)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
assert values == [
"test_hello",
"fin John",
"test_hello",
"fin Doe",
"test_name",
"test_population",
"fin John",
"test_name",
"test_population",
"fin Doe",
]
def test_parametrize_setup_function(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module", params=[1, 2])
def arg(request):
return request.param
@pytest.fixture(scope="module", autouse=True)
def mysetup(request, arg):
request.addfinalizer(lambda: values.append("fin%s" % arg))
values.append("setup%s" % arg)
values = []
def test_1(arg):
values.append(arg)
def test_2(arg):
values.append(arg)
def test_3():
import pprint
pprint.pprint(values)
if arg == 1:
assert values == ["setup1", 1, 1, ]
elif arg == 2:
assert values == ["setup1", 1, 1, "fin1",
"setup2", 2, 2, ]
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=6)
def test_fixture_marked_function_not_collected_as_test(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def test_app():
return 1
def test_something(test_app):
assert test_app == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_params_and_ids(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[object(), object()],
ids=['alpha', 'beta'])
def fix(request):
return request.param
def test_foo(fix):
assert 1
"""
)
res = pytester.runpytest("-v")
res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
def test_params_and_ids_yieldfixture(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[object(), object()], ids=['alpha', 'beta'])
def fix(request):
yield request.param
def test_foo(fix):
assert 1
"""
)
res = pytester.runpytest("-v")
res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
def test_deterministic_fixture_collection(
self, pytester: Pytester, monkeypatch
) -> None:
"""#920"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module",
params=["A",
"B",
"C"])
def A(request):
return request.param
@pytest.fixture(scope="module",
params=["DDDDDDDDD", "EEEEEEEEEEEE", "FFFFFFFFFFF", "banansda"])
def B(request, A):
return request.param
def test_foo(B):
# Something funky is going on here.
# Despite specified seeds, on what is collected,
# sometimes we get unexpected passes. hashing B seems
# to help?
assert hash(B) or True
"""
)
monkeypatch.setenv("PYTHONHASHSEED", "1")
out1 = pytester.runpytest_subprocess("-v")
monkeypatch.setenv("PYTHONHASHSEED", "2")
out2 = pytester.runpytest_subprocess("-v")
output1 = [
line
for line in out1.outlines
if line.startswith("test_deterministic_fixture_collection.py::test_foo")
]
output2 = [
line
for line in out2.outlines
if line.startswith("test_deterministic_fixture_collection.py::test_foo")
]
assert len(output1) == 12
assert output1 == output2
| TestFixtureMarker |
python | python-openxml__python-docx | src/docx/oxml/shape.py | {
"start": 6770,
"end": 6914
} | class ____(BaseOxmlElement):
"""``<a:prstGeom>`` element, specifies an preset autoshape geometry, such as
``rect``."""
| CT_PresetGeometry2D |
python | sympy__sympy | sympy/solvers/diophantine/diophantine.py | {
"start": 7591,
"end": 8551
} | class ____(DiophantineEquationType):
"""
Representation of a univariate diophantine equation.
A univariate diophantine equation is an equation of the form
`a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are
integer constants and `x` is an integer variable.
Examples
========
>>> from sympy.solvers.diophantine.diophantine import Univariate
>>> from sympy.abc import x
>>> Univariate((x - 2)*(x - 3)**2).solve() # solves equation (x - 2)*(x - 3)**2 == 0
{(2,), (3,)}
"""
name = 'univariate'
def matches(self):
return self.dimension == 1
def solve(self, parameters=None, limit=None):
self.pre_solve(parameters)
result = DiophantineSolutionSet(self.free_symbols, parameters=self.parameters)
for i in solveset_real(self.equation, self.free_symbols[0]).intersect(S.Integers):
result.add((i,))
return result
| Univariate |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 36633,
"end": 36788
} | class ____(str, Enum):
HEALTHY = "healthy"
DELAYED = "delayed"
UNAVAILABLE = "unavailable"
@PublicAPI(stability="alpha")
| AutoscalingMetricsHealth |
python | ansible__ansible | lib/ansible/modules/service.py | {
"start": 44576,
"end": 45321
} | class ____(FreeBsdService):
"""
This is the DragonFly BSD Service manipulation class - it uses the /etc/rc.conf
file for controlling services started at boot and the 'service' binary to
check status and perform direct service manipulation.
"""
platform = 'DragonFly'
distribution = None
def service_enable(self):
if self.enable:
self.rcconf_value = "YES"
else:
self.rcconf_value = "NO"
rcfiles = ['/etc/rc.conf'] # Overkill?
for rcfile in rcfiles:
if os.path.isfile(rcfile):
self.rcconf_file = rcfile
self.rcconf_key = "%s" % self.name.replace("-", "_")
return self.service_enable_rcconf()
| DragonFlyBsdService |
python | anthropics__anthropic-sdk-python | src/anthropic/types/web_search_tool_20250305_param.py | {
"start": 841,
"end": 1829
} | class ____(TypedDict, total=False):
name: Required[Literal["web_search"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["web_search_20250305"]]
allowed_domains: Optional[SequenceNotStr[str]]
"""If provided, only these domains will be included in results.
Cannot be used alongside `blocked_domains`.
"""
blocked_domains: Optional[SequenceNotStr[str]]
"""If provided, these domains will never appear in results.
Cannot be used alongside `allowed_domains`.
"""
cache_control: Optional[CacheControlEphemeralParam]
"""Create a cache control breakpoint at this content block."""
max_uses: Optional[int]
"""Maximum number of times the tool can be used in the API request."""
user_location: Optional[UserLocation]
"""Parameters for the user's location.
Used to provide more relevant search results.
"""
| WebSearchTool20250305Param |
python | davidhalter__jedi | test/completion/pep0526_variables.py | {
"start": 621,
"end": 752
} | class ____():
bar: int
baz: typing.ClassVar[str]
#? int()
Foo.bar
#? int()
Foo().bar
#? str()
Foo.baz
#? str()
Foo().baz
| Foo |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/models/__init__.py | {
"start": 10978,
"end": 12708
} | class ____(Model):
"""Represents a user registration."""
__tablename__ = "ab_register_user"
id = mapped_column(
Integer,
Sequence("ab_register_user_id_seq", start=1, increment=1, minvalue=1, cycle=False),
primary_key=True,
)
first_name: Mapped[str] = mapped_column(String(64), nullable=False)
last_name: Mapped[str] = mapped_column(String(64), nullable=False)
username: Mapped[str] = mapped_column(
String(512).with_variant(String(512, collation="NOCASE"), "sqlite"), unique=True, nullable=False
)
password: Mapped[str | None] = mapped_column(String(256))
email: Mapped[str] = mapped_column(String(320), unique=True, nullable=False)
registration_date: Mapped[datetime.datetime | None] = mapped_column(
DateTime, default=lambda: datetime.datetime.now(), nullable=True
)
registration_hash: Mapped[str | None] = mapped_column(String(256))
@event.listens_for(User.__table__, "before_create")
def add_index_on_ab_user_username_postgres(table, conn, **kw):
if conn.dialect.name != "postgresql":
return
index_name = "idx_ab_user_username"
if not any(table_index.name == index_name for table_index in table.indexes):
table.indexes.add(Index(index_name, func.lower(table.c.username), unique=True))
@event.listens_for(RegisterUser.__table__, "before_create")
def add_index_on_ab_register_user_username_postgres(table, conn, **kw):
if conn.dialect.name != "postgresql":
return
index_name = "idx_ab_register_user_username"
if not any(table_index.name == index_name for table_index in table.indexes):
table.indexes.add(Index(index_name, func.lower(table.c.username), unique=True))
| RegisterUser |
python | kamyu104__LeetCode-Solutions | Python/minimum-sideway-jumps.py | {
"start": 547,
"end": 970
} | class ____(object):
def minSideJumps(self, obstacles):
"""
:type obstacles: List[int]
:rtype: int
"""
dp = [1, 0, 1]
for i in obstacles:
if i:
dp[i-1] = float("inf")
for j in xrange(3):
if j+1 != i:
dp[j] = min(dp[0]+(j != 0), dp[1]+(j != 1), dp[2]+(j != 2))
return min(dp)
| Solution2 |
python | pennersr__django-allauth | allauth/headless/account/inputs.py | {
"start": 9038,
"end": 9114
} | class ____(ConfirmLoginCodeForm, inputs.Input):
pass
| ConfirmLoginCodeInput |
python | doocs__leetcode | lcof2/剑指 Offer II 027. 回文链表/Solution.py | {
"start": 151,
"end": 695
} | class ____:
def isPalindrome(self, head: ListNode) -> bool:
if head is None or head.next is None:
return True
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
pre, cur = None, slow.next
while cur:
t = cur.next
cur.next = pre
pre, cur = cur, t
while pre:
if pre.val != head.val:
return False
pre, head = pre.next, head.next
return True
| Solution |
python | crytic__slither | slither/core/declarations/function.py | {
"start": 3204,
"end": 3279
} | class ____(Enum):
Solidity = 0
Yul = 1
Vyper = 2
| FunctionLanguage |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 40361,
"end": 43051
} | class ____(_CompositeTestBase, fixtures.MappedTest):
@classmethod
def setup_mappers(cls):
foo = cls.tables.foo
cls.Point = cls._type_fixture()
cls.mapper_registry.map_imperatively(
Foo,
foo,
properties={"data": composite(cls.Point, foo.c.x, foo.c.y)},
)
def test_in_place_mutation(self):
sess = fixture_session()
d = self.Point(3, 4)
f1 = Foo(data=d)
sess.add(f1)
sess.commit()
f1.data.y = 5
sess.commit()
eq_(f1.data, self.Point(3, 5))
def test_pickle_of_parent(self):
sess = fixture_session()
d = self.Point(3, 4)
f1 = Foo(data=d)
sess.add(f1)
sess.commit()
f1.data
assert "data" in f1.__dict__
sess.close()
for loads, dumps in picklers():
sess = fixture_session()
f2 = loads(dumps(f1))
sess.add(f2)
f2.data.y = 12
assert f2 in sess.dirty
def test_set_none(self):
sess = fixture_session()
f1 = Foo(data=None)
sess.add(f1)
sess.commit()
eq_(f1.data, self.Point(None, None))
f1.data.y = 5
sess.commit()
eq_(f1.data, self.Point(None, 5))
def test_set_illegal(self):
f1 = Foo()
assert_raises_message(
ValueError,
"Attribute 'data' does not accept objects",
setattr,
f1,
"data",
"foo",
)
def test_unrelated_flush(self):
sess = fixture_session()
f1 = Foo(data=self.Point(3, 4), unrelated_data="unrelated")
sess.add(f1)
sess.flush()
f1.unrelated_data = "unrelated 2"
sess.flush()
f1.data.x = 5
sess.commit()
eq_(f1.data.x, 5)
def test_dont_reset_on_attr_refresh(self):
sess = fixture_session()
f1 = Foo(data=self.Point(3, 4), unrelated_data="unrelated")
sess.add(f1)
sess.flush()
f1.data.x = 5
# issue 6001, this would reload a new Point() that would be missed
# by the mutable composite, and tracking would be lost
sess.refresh(f1, ["unrelated_data"])
is_(list(f1.data._parents.keys())[0], f1._sa_instance_state)
f1.data.y = 9
sess.commit()
eq_(f1.data.x, 5)
eq_(f1.data.y, 9)
f1.data.x = 12
sess.refresh(f1, ["unrelated_data", "y"])
is_(list(f1.data._parents.keys())[0], f1._sa_instance_state)
f1.data.y = 15
sess.commit()
eq_(f1.data.x, 12)
eq_(f1.data.y, 15)
| MutableCompositesTest |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran/managed/types.py | {
"start": 2981,
"end": 3622
} | class ____:
def __init__(self, connector: FivetranConnector, connector_id: str):
self.connector = connector
self.connector_id = connector_id
@classmethod
def from_api_json(cls, api_json: dict[str, Any]):
return cls(
connector=FivetranConnector(
schema_name=api_json["schema"],
source_type=api_json["service"],
source_configuration=api_json["config"] or {},
auth_configuration=api_json.get("auth") or {},
destination=None,
),
connector_id=api_json["id"],
)
| InitializedFivetranConnector |
python | Pylons__pyramid | docs/tutorials/wiki2/src/basiclayout/tutorial/models/mymodel.py | {
"start": 132,
"end": 366
} | class ____(Base):
__tablename__ = 'models'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[Optional[str]]
value: Mapped[Optional[int]]
Index('my_index', MyModel.name, unique=True, mysql_length=255)
| MyModel |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar13.py | {
"start": 315,
"end": 1894
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar13.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet1 = workbook.add_worksheet()
chartsheet1 = workbook.add_chartsheet()
worksheet2 = workbook.add_worksheet()
worksheet3 = workbook.add_worksheet()
chartsheet2 = workbook.add_chartsheet()
worksheet4 = workbook.add_worksheet()
chart1 = workbook.add_chart({"type": "bar"})
chart2 = workbook.add_chart({"type": "bar"})
chart1.axis_ids = [40294272, 40295808]
chart2.axis_ids = [62356096, 62366080]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet1.write_column("A1", data[0])
worksheet1.write_column("B1", data[1])
worksheet1.write_column("C1", data[2])
chart1.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart1.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart1.add_series({"values": "=Sheet1!$C$1:$C$5"})
chart2.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart2.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart2.add_series({"values": "=Sheet1!$C$1:$C$5"})
chartsheet1.set_chart(chart1)
chartsheet2.set_chart(chart2)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | run-llama__llama_index | llama-index-core/llama_index/core/embeddings/mock_embed_model.py | {
"start": 248,
"end": 1211
} | class ____(BaseEmbedding):
"""
Mock embedding.
Used for token prediction.
Args:
embed_dim (int): embedding dimension
"""
embed_dim: int
def __init__(self, embed_dim: int, **kwargs: Any) -> None:
"""Init params."""
super().__init__(embed_dim=embed_dim, **kwargs)
@classmethod
def class_name(cls) -> str:
return "MockEmbedding"
def _get_vector(self) -> List[float]:
return [0.5] * self.embed_dim
async def _aget_text_embedding(self, text: str) -> List[float]:
return self._get_vector()
async def _aget_query_embedding(self, query: str) -> List[float]:
return self._get_vector()
def _get_query_embedding(self, query: str) -> List[float]:
"""Get query embedding."""
return self._get_vector()
def _get_text_embedding(self, text: str) -> List[float]:
"""Get text embedding."""
return self._get_vector()
| MockEmbedding |
python | Textualize__textual | src/textual/css/errors.py | {
"start": 544,
"end": 1261
} | class ____(ValueError):
"""Raised when the value of a style property is not valid
Attributes:
help_text: Optional HelpText to be rendered when this
error is raised.
"""
def __init__(self, *args: object, help_text: HelpText | None = None):
super().__init__(*args)
self.help_text: HelpText | None = help_text
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
from rich.traceback import Traceback
yield Traceback.from_exception(type(self), self, self.__traceback__)
if self.help_text is not None:
yield ""
yield self.help_text
yield ""
| StyleValueError |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 23016,
"end": 23300
} | class ____(Sky2PixProjection, Cylindrical):
r"""
Mercator - sky to pixel.
Corresponds to the ``MER`` projection in FITS WCS.
.. math::
x &= \phi \\
y &= \frac{180^{\circ}}{\pi}\ln \tan \left(\frac{90^{\circ} + \theta}{2}\right)
"""
| Sky2Pix_Mercator |
python | django__django | django/utils/log.py | {
"start": 4984,
"end": 5384
} | class ____(logging.Filter):
"""
A logging filter that checks the return value of a given callable (which
takes the record-to-be-logged as its only parameter) to decide whether to
log a record.
"""
def __init__(self, callback):
self.callback = callback
def filter(self, record):
if self.callback(record):
return 1
return 0
| CallbackFilter |
python | pypa__warehouse | tests/unit/admin/views/test_banners.py | {
"start": 6953,
"end": 7429
} | class ____:
def test_404_if_banner_does_not_exist(self, db_request):
db_request.matchdict["banner_id"] = str(uuid.uuid4())
with pytest.raises(HTTPNotFound):
views.preview_banner(db_request)
def test_preview_banner(self, db_request):
banner = BannerFactory.create()
db_request.matchdict["banner_id"] = str(banner.id)
resp = views.preview_banner(db_request)
assert {"banner": banner} == resp
| TestPreviewBanner |
python | tox-dev__tox | src/tox/config/loader/api.py | {
"start": 1680,
"end": 2432
} | class ____:
"""Arguments that help loading a configuration value."""
def __init__(self, chain: list[str] | None, name: str | None, env_name: str | None) -> None:
"""
:param chain: the configuration chain (useful to detect circular references)
:param name: the name of the configuration
:param env_name: the tox environment this load is for
"""
self.chain: list[str] = chain or []
self.name = name
self.env_name = env_name
def copy(self) -> ConfigLoadArgs:
""":return: create a copy of the object"""
return ConfigLoadArgs(self.chain.copy(), self.name, self.env_name)
OverrideMap = Mapping[str, list[Override]]
T = TypeVar("T")
V = TypeVar("V")
| ConfigLoadArgs |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/random/random_crop_test.py | {
"start": 885,
"end": 2724
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testNoOp(self):
# No random cropping is performed since the size is value.shape.
for shape in (2, 1, 1), (2, 1, 3), (4, 5, 3):
value = np.arange(0, np.prod(shape), dtype=np.int32).reshape(shape)
with self.cached_session():
crop = random_crop_ops.random_crop(value, shape).eval()
self.assertAllEqual(crop, value)
def testContains(self):
with self.cached_session():
shape = (3, 5, 7)
target = (2, 3, 4)
value = np.random.randint(1000000, size=shape)
value_set = set(
tuple(value[i:i + 2, j:j + 3, k:k + 4].ravel())
for i in range(2) for j in range(3) for k in range(4))
crop = random_crop_ops.random_crop(value, size=target)
for _ in range(20):
y = self.evaluate(crop)
self.assertAllEqual(y.shape, target)
self.assertTrue(tuple(y.ravel()) in value_set)
@test_util.run_deprecated_v1
def testRandomization(self):
# Run 1x1 crop num_samples times in an image and ensure that one finds each
# pixel 1/size of the time.
num_samples = 1000
shape = [5, 4, 1]
size = np.prod(shape)
single = [1, 1, 1]
value = np.arange(size).reshape(shape)
with self.cached_session():
crop = random_crop_ops.random_crop(value, single, seed=7)
counts = np.zeros(size, dtype=np.int32)
for _ in range(num_samples):
y = self.evaluate(crop)
self.assertAllEqual(y.shape, single)
counts[y] += 1
# Calculate the mean and 4 * standard deviation.
mean = np.repeat(num_samples / size, size)
four_stddev = 4.0 * np.sqrt(mean)
# Ensure that each entry is observed in 1/size of the samples
# within 4 standard deviations.
self.assertAllClose(counts, mean, atol=four_stddev)
| RandomCropTest |
python | getsentry__sentry | src/sudo/forms.py | {
"start": 402,
"end": 1106
} | class ____(forms.Form):
"""
A simple password input form used by the default :func:`~sudo.views.sudo` view.
"""
password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
def __init__(self, user: AnonymousUser | AbstractBaseUser, *args: Any, **kwargs: Any) -> None:
self.user = user
super().__init__(*args, **kwargs)
def clean_password(self) -> str:
username = self.user.get_username()
if auth.authenticate(
request=None,
username=username,
password=self.data["password"],
):
return self.data["password"]
raise forms.ValidationError(_("Incorrect password"))
| SudoForm |
python | ansible__ansible | lib/ansible/module_utils/urls.py | {
"start": 7072,
"end": 7248
} | class ____(ConnectionError):
"""Failure to connect due to SSL validation failing
No longer used, but kept for backwards compatibility
"""
pass
| SSLValidationError |
python | getsentry__sentry | tests/sentry/sentry_apps/test_sentry_app_installation_creator.py | {
"start": 1011,
"end": 6622
} | class ____(TestCase):
def setUp(self) -> None:
self.user = self.create_user()
self.org = self.create_organization()
self.project1 = self.create_project(organization=self.org)
self.project2 = self.create_project(organization=self.org)
self.sentry_app = self.create_sentry_app(
name="nulldb",
organization_id=self.org.id,
scopes=("project:read",),
events=("issue.created",),
)
def run_creator(self, **kwargs):
return SentryAppInstallationCreator(
organization_id=self.org.id, slug="nulldb", **kwargs
).run(user=self.user, request=kwargs.pop("request", None))
@responses.activate
@patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_creates_installation(self, mock_record: MagicMock) -> None:
responses.add(responses.POST, "https://example.com/webhook")
install = self.run_creator()
assert install.pk
# SLO assertions
assert_success_metric(mock_record=mock_record)
# INSTALLATION_CREATE (success)
assert_count_of_metric(
mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=1
)
assert_count_of_metric(
mock_record=mock_record, outcome=EventLifecycleOutcome.SUCCESS, outcome_count=1
)
@responses.activate
def test_creates_installation__multiple_runs(self) -> None:
responses.add(responses.POST, "https://example.com/webhook")
install = self.run_creator()
assert install.pk
install2 = self.run_creator()
assert install2.pk != install.pk
@responses.activate
def test_creates_api_grant(self) -> None:
responses.add(responses.POST, "https://example.com/webhook")
install = self.run_creator()
assert ApiGrant.objects.filter(id=install.api_grant_id).exists()
@responses.activate
def test_creates_service_hooks(self) -> None:
responses.add(responses.POST, "https://example.com/webhook")
install = self.run_creator()
with assume_test_silo_mode(SiloMode.REGION):
hook = ServiceHook.objects.get(organization_id=self.org.id)
assert hook.application_id == self.sentry_app.application.id
assert hook.actor_id == install.id
assert hook.organization_id == self.org.id
assert hook.events == self.sentry_app.events
assert hook.url == self.sentry_app.webhook_url
with assume_test_silo_mode(SiloMode.REGION):
assert not ServiceHookProject.objects.all()
@responses.activate
def test_creates_audit_log_entry(self) -> None:
responses.add(responses.POST, "https://example.com/webhook")
request = self.make_request(user=self.user, method="GET")
SentryAppInstallationCreator(organization_id=self.org.id, slug="nulldb").run(
user=self.user, request=request
)
assert AuditLogEntry.objects.filter(
event=audit_log.get_event_id("SENTRY_APP_INSTALL")
).exists()
@responses.activate
def test_notifies_service(self) -> None:
rpc_user = user_service.get_user(user_id=self.user.id)
with self.tasks():
responses.add(responses.POST, "https://example.com/webhook")
install = self.run_creator()
response_body = json.loads(responses.calls[0].request.body)
assert response_body.get("installation").get("uuid") == install.uuid
assert response_body.get("action") == "created"
assert rpc_user, "User should exist, unless explicitly noted in test"
assert response_body.get("actor").get("id") == rpc_user.id
@responses.activate
def test_associations(self) -> None:
responses.add(responses.POST, "https://example.com/webhook")
install = self.run_creator()
assert install.api_grant is not None
@responses.activate
def test_pending_status(self) -> None:
responses.add(responses.POST, "https://example.com/webhook")
install = self.run_creator()
assert install.status == SentryAppInstallationStatus.PENDING
@responses.activate
def test_installed_status(self) -> None:
responses.add(responses.POST, "https://example.com/webhook")
internal_app = self.create_internal_integration(name="internal", organization=self.org)
install = SentryAppInstallationCreator(
organization_id=self.org.id, slug=internal_app.slug
).run(user=self.user, request=None)
assert install.status == SentryAppInstallationStatus.INSTALLED
@responses.activate
@patch("sentry.analytics.record")
def test_records_analytics(self, record: MagicMock) -> None:
SentryAppInstallationCreator(
organization_id=self.org.id,
slug="nulldb",
).run(
user=self.user,
request=self.make_request(user=self.user, method="GET"),
)
assert_last_analytics_event(
record,
SentryAppInstalledEvent(
user_id=self.user.id,
organization_id=self.org.id,
sentry_app="nulldb",
),
)
@responses.activate
def test_placeholder_email(self) -> None:
responses.add(responses.POST, "https://example.com/webhook")
install = self.run_creator()
proxy_user = User.objects.get(id=install.sentry_app.proxy_user.id)
assert proxy_user.email == f"{proxy_user.username}@proxy-user.sentry.io"
| TestCreator |
python | keras-team__keras | keras/src/ops/function_test.py | {
"start": 334,
"end": 5838
} | class ____(testing.TestCase):
def test_define_and_call(self):
x1 = keras_tensor.KerasTensor((2, 3))
x2 = keras_tensor.KerasTensor((2, 3))
x = knp.add(x1, x2)
y1 = x * 3
y2 = x**2
fn = function.Function(
inputs=[x1, x2], outputs=[y1, y2], name="test_function"
)
self.assertEqual(fn.name, "test_function")
# Eager call
y_val = fn([np.ones((2, 3)), np.ones((2, 3))])
self.assertIsInstance(y_val, list)
self.assertAllClose(y_val[0], np.ones((2, 3)) * 6)
self.assertAllClose(y_val[1], np.ones((2, 3)) * 4)
# Symbolic call
x1_alt = keras_tensor.KerasTensor((2, 3))
x2_alt = keras_tensor.KerasTensor((2, 3))
y_val = fn([x1_alt, x2_alt])
self.assertIsInstance(y_val[0], keras_tensor.KerasTensor)
self.assertEqual(y_val[0].shape, (2, 3))
self.assertIsInstance(y_val[1], keras_tensor.KerasTensor)
self.assertEqual(y_val[1].shape, (2, 3))
# Recursion
fn = function.Function(inputs=[x1_alt, x2_alt], outputs=y_val)
y_val = fn([np.ones((2, 3)), np.ones((2, 3))])
self.assertIsInstance(y_val, list)
self.assertAllClose(y_val[0], np.ones((2, 3)) * 6)
self.assertAllClose(y_val[1], np.ones((2, 3)) * 4)
def test_dynamic_shape_inference(self):
x = keras_tensor.KerasTensor((None, 3))
y = x**2
fn = function.Function(x, y)
# Test with compute_output_spec
out = fn.compute_output_spec(keras_tensor.KerasTensor((4, 3)))
self.assertIsInstance(out, keras_tensor.KerasTensor)
self.assertEqual(out.shape, (4, 3))
# Test with compute_output_shape
out = fn.compute_output_shape((None, 3))
self.assertIsInstance(out, tuple)
self.assertEqual(out, (None, 3))
# Test with call
out = fn(keras_tensor.KerasTensor((4, 3)))
self.assertIsInstance(out, keras_tensor.KerasTensor)
self.assertEqual(out.shape, (4, 3))
def test_dict_io(self):
x1 = keras_tensor.KerasTensor((2, 3))
x2 = keras_tensor.KerasTensor((2, 3))
x = knp.add(x1, x2)
y1 = x * 3
y2 = x**2
fn = function.Function(
inputs={"x1": x1, "x2": x2}, outputs={"y1": y1, "y2": y2}
)
# Eager call
y_val = fn({"x1": np.ones((2, 3)), "x2": np.ones((2, 3))})
self.assertIsInstance(y_val, dict)
self.assertAllClose(y_val["y1"], np.ones((2, 3)) * 6)
self.assertAllClose(y_val["y2"], np.ones((2, 3)) * 4)
# Symbolic call
x1_alt = keras_tensor.KerasTensor((2, 3))
x2_alt = keras_tensor.KerasTensor((2, 3))
y_val = fn({"x1": x1_alt, "x2": x2_alt})
self.assertIsInstance(y_val["y1"], keras_tensor.KerasTensor)
self.assertEqual(y_val["y1"].shape, (2, 3))
self.assertIsInstance(y_val["y2"], keras_tensor.KerasTensor)
self.assertEqual(y_val["y2"].shape, (2, 3))
def test_invalid_inputs_error(self):
x1 = keras_tensor.KerasTensor((2, 3))
x2 = keras_tensor.KerasTensor((2, 3))
x = knp.add(x1, x2)
y1 = x * 3
y2 = x**2
fn = function.Function(
inputs=[x1, x2], outputs=[y1, y2], name="test_function"
)
self.assertEqual(fn.name, "test_function")
# Bad structure
with self.assertRaisesRegex(ValueError, "invalid input structure"):
_ = fn(np.ones((2, 3)))
# Bad rank
with self.assertRaisesRegex(ValueError, "incompatible inputs"):
_ = fn([np.ones((2, 3, 3)), np.ones((2, 3))])
# Bad shape
with self.assertRaisesRegex(ValueError, "incompatible inputs"):
_ = fn([np.ones((4, 3)), np.ones((2, 3))])
def test_graph_disconnected_error(self):
# TODO
pass
def test_serialization(self):
inputs = Input(shape=(10,))
outputs = Dense(1)(inputs)
model = Model(inputs=inputs, outputs=outputs)
config = model.get_config()
new_model = Model.from_config(config)
self.assertEqual(
json.dumps(model.get_config()), json.dumps(new_model.get_config())
)
def test_function_with_empty_outputs(self):
x = keras_tensor.KerasTensor((None, 3))
with self.assertRaisesRegex(
ValueError, "`outputs` argument cannot be empty"
):
_ = function.Function(inputs=x, outputs=[])
def test_function_with_empty_inputs(self):
x = keras_tensor.KerasTensor((None, 3))
with self.assertRaisesRegex(
ValueError, "`inputs` argument cannot be empty"
):
_ = function.Function(inputs=[], outputs=x)
def test_function_with_unconnected_inputs(self):
model_1 = Sequential(
[
Input(shape=(6,)),
Dense(3, activation="sigmoid"),
]
)
model_2 = Sequential(
[
Input(shape=(3,)),
Dense(2, activation="sigmoid"),
],
)
with self.assertRaisesRegex(
ValueError, "`inputs` not connected to `outputs`"
):
_ = Model(Input(shape=(6,)), model_2(model_1(Input(shape=(6,)))))
with self.assertRaisesRegex(
ValueError, "`inputs` not connected to `outputs`"
):
_ = Model(model_1(Input(shape=(6,))), model_2(Input(shape=(3,))))
| FunctionTest |
python | getsentry__sentry | src/social_auth/exceptions.py | {
"start": 138,
"end": 279
} | class ____(SocialAuthBaseException):
def __str__(self) -> str:
return gettext("Backend error: %s") % super().__str__()
| BackendError |
python | getsentry__sentry | tests/sentry_plugins/jira/test_plugin.py | {
"start": 10342,
"end": 17449
} | class ____(TestCase):
@cached_property
def plugin(self) -> JiraPlugin:
return JiraPlugin()
@cached_property
def request(self) -> RequestFactory:
return RequestFactory()
def test_conf_key(self) -> None:
assert self.plugin.conf_key == "jira"
def test_get_issue_label(self) -> None:
group = self.create_group(message="Hello world", culprit="foo.bar")
assert self.plugin.get_issue_label(group, "SEN-1") == "SEN-1"
def test_get_issue_url(self) -> None:
self.plugin.set_option("instance_url", "https://getsentry.atlassian.net", self.project)
group = self.create_group(message="Hello world", culprit="foo.bar")
assert (
self.plugin.get_issue_url(group, "SEN-1")
== "https://getsentry.atlassian.net/browse/SEN-1"
)
def test_is_configured(self) -> None:
assert self.plugin.is_configured(self.project) is False
self.plugin.set_option("default_project", "SEN", self.project)
assert self.plugin.is_configured(self.project) is True
@responses.activate
def test_create_issue(self) -> None:
responses.add(
responses.GET,
"https://getsentry.atlassian.net/rest/api/2/issue/createmeta",
json=create_meta_response,
)
responses.add(
responses.POST,
"https://getsentry.atlassian.net/rest/api/2/issue",
json={"key": "SEN-1"},
)
self.plugin.set_option("instance_url", "https://getsentry.atlassian.net", self.project)
group = self.create_group(message="Hello world", culprit="foo.bar")
request = drf_request_from_request(self.request.get("/"))
request.user = AnonymousUser()
form_data = {
"title": "Hello",
"description": "Fix this.",
"issuetype": "bug",
"project": "SEN",
}
assert self.plugin.create_issue(request, group, form_data) == "SEN-1"
@responses.activate
def test_link_issue(self) -> None:
responses.add(
responses.GET,
"https://getsentry.atlassian.net/rest/api/2/issue/SEN-19",
json=issue_response,
)
self.plugin.set_option("instance_url", "https://getsentry.atlassian.net", self.project)
group = self.create_group(message="Hello world", culprit="foo.bar")
request = drf_request_from_request(self.request.get("/"))
request.user = AnonymousUser()
form_data = {"issue_id": "SEN-19"}
assert (
self.plugin.link_issue(request, group, form_data)["title"]
== issue_response["fields"]["summary"]
)
def test_no_secrets(self) -> None:
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(owner=self.user, name="Rowdy Tiger")
self.team = self.create_team(organization=self.org, name="Mariachi Band")
self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal")
self.login_as(self.user)
self.plugin.set_option("password", "abcdef", self.project)
url = reverse(
"sentry-api-0-project-plugin-details", args=[self.org.slug, self.project.slug, "jira"]
)
res = self.client.get(url)
config = orjson.loads(res.content)["config"]
password_config = [item for item in config if item["name"] == "password"][0]
assert password_config.get("type") == "secret"
assert password_config.get("value") is None
assert password_config.get("hasSavedValue") is True
assert password_config.get("prefix") == ""
def test_get_formatted_user(self) -> None:
assert self.plugin._get_formatted_user(
{"displayName": "Foo Bar", "emailAddress": "foo@sentry.io", "name": "foobar"}
) == {"text": "Foo Bar - foo@sentry.io (foobar)", "id": "foobar"}
# test weird addon users that don't have email addresses
assert self.plugin._get_formatted_user(
{
"name": "robot",
"avatarUrls": {
"16x16": "https://avatar-cdn.atlassian.com/someid",
"24x24": "https://avatar-cdn.atlassian.com/someotherid",
},
"self": "https://something.atlassian.net/rest/api/2/user?username=someaddon",
}
) == {"id": "robot", "text": "robot (robot)"}
def _setup_autocomplete_jira(self) -> None:
self.plugin.set_option("instance_url", "https://getsentry.atlassian.net", self.project)
self.plugin.set_option("default_project", "SEN", self.project)
self.login_as(user=self.user)
self.group = self.create_group(message="Hello world", culprit="foo.bar")
@responses.activate
def test_autocomplete_issue_id(self) -> None:
self._setup_autocomplete_jira()
responses.add(
responses.GET,
"https://getsentry.atlassian.net/rest/api/2/search/",
json={"issues": [issue_response]},
)
url = f"/api/0/issues/{self.group.id}/plugins/jira/autocomplete/?autocomplete_query=SEN&autocomplete_field=issue_id"
response = self.client.get(url)
assert response.json() == {
"issue_id": [
{
"text": "(SEN-19) TypeError: 'set' object has no attribute '__getitem__'",
"id": "SEN-19",
}
]
}
@responses.activate
def test_autocomplete_jira_url_reporter(self) -> None:
self._setup_autocomplete_jira()
responses.add(
responses.GET,
"https://getsentry.atlassian.net/rest/api/2/user/search/?username=user&project=SEN",
json=user_search_response,
)
url = f"/api/0/issues/{self.group.id}/plugins/jira/autocomplete/?autocomplete_query=user&autocomplete_field=reporter&jira_url=https://getsentry.atlassian.net/rest/api/2/user/search/"
response = self.client.get(url)
assert response.json() == {
"reporter": [
{"id": "userexample", "text": "User Example - user@example.com (userexample)"}
]
}
def test_autocomplete_jira_url_missing(self) -> None:
self._setup_autocomplete_jira()
url = f"/api/0/issues/{self.group.id}/plugins/jira/autocomplete/?autocomplete_query=SEN&autocomplete_field=reporter"
response = self.client.get(url)
assert response.json() == {
"error_type": "validation",
"errors": [{"jira_url": "missing required parameter"}],
}
def test_autocomplete_jira_url_mismatch(self) -> None:
self._setup_autocomplete_jira()
url = f"/api/0/issues/{self.group.id}/plugins/jira/autocomplete/?autocomplete_query=SEN&autocomplete_field=reporter&jira_url=https://eviljira.com/"
response = self.client.get(url)
assert response.json() == {
"error_type": "validation",
"errors": [{"jira_url": "domain must match"}],
}
| JiraPluginTest |
python | boto__boto3 | boto3/dynamodb/conditions.py | {
"start": 5888,
"end": 6001
} | class ____(ConditionAttributeBase):
expression_operator = 'size'
expression_format = '{operator}({0})'
| Size |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/managed/types.py | {
"start": 52,
"end": 169
} | class ____(str, Enum):
"""Managed Index query mode."""
DEFAULT = "default"
MMR = "mmr"
| ManagedIndexQueryMode |
python | gevent__gevent | src/greentest/3.10/test_asyncore.py | {
"start": 739,
"end": 870
} | class ____:
def __init__(self):
self.socket = dummysocket()
def close(self):
self.socket.close()
| dummychannel |
python | run-llama__llama_index | llama-index-core/llama_index/core/ingestion/transformations.py | {
"start": 2873,
"end": 10583
} | class ____(Enum):
@classmethod
def from_component(cls, component: BaseComponent) -> "ConfigurableComponent":
component_class = type(component)
for component_type in cls:
if component_type.value.component_type == component_class:
return component_type
raise ValueError(
f"Component {component} is not a supported transformation component."
)
def build_configured_transformation(
self, component: BaseComponent
) -> "ConfiguredTransformation":
component_type = self.value.component_type
if not isinstance(component, component_type):
raise ValueError(
f"The enum value {self} is not compatible with component of "
f"type {type(component)}"
)
return ConfiguredTransformation[component_type]( # type: ignore
component=component, name=self.value.name
)
def build_configurable_transformation_enum() -> ConfigurableComponent:
"""
Build an enum of configurable transformations.
But conditional on if the corresponding component is available.
"""
enum_members = []
# Node parsers
enum_members.append(
(
"CODE_NODE_PARSER",
ConfigurableTransformation(
name="Code Splitter",
transformation_category=TransformationCategories.NODE_PARSER,
component_type=CodeSplitter,
),
)
)
enum_members.append(
(
"SENTENCE_AWARE_NODE_PARSER",
ConfigurableTransformation(
name="Sentence Splitter",
transformation_category=TransformationCategories.NODE_PARSER,
component_type=SentenceSplitter,
),
)
)
enum_members.append(
(
"TOKEN_AWARE_NODE_PARSER",
ConfigurableTransformation(
name="Token Text Splitter",
transformation_category=TransformationCategories.NODE_PARSER,
component_type=TokenTextSplitter,
),
)
)
enum_members.append(
(
"HTML_NODE_PARSER",
ConfigurableTransformation(
name="HTML Node Parser",
transformation_category=TransformationCategories.NODE_PARSER,
component_type=HTMLNodeParser,
),
)
)
enum_members.append(
(
"MARKDOWN_NODE_PARSER",
ConfigurableTransformation(
name="Markdown Node Parser",
transformation_category=TransformationCategories.NODE_PARSER,
component_type=MarkdownNodeParser,
),
)
)
enum_members.append(
(
"JSON_NODE_PARSER",
ConfigurableTransformation(
name="JSON Node Parser",
transformation_category=TransformationCategories.NODE_PARSER,
component_type=JSONNodeParser,
),
)
)
enum_members.append(
(
"SIMPLE_FILE_NODE_PARSER",
ConfigurableTransformation(
name="Simple File Node Parser",
transformation_category=TransformationCategories.NODE_PARSER,
component_type=SimpleFileNodeParser,
),
)
)
enum_members.append(
(
"MARKDOWN_ELEMENT_NODE_PARSER",
ConfigurableTransformation(
name="Markdown Element Node Parser",
transformation_category=TransformationCategories.NODE_PARSER,
component_type=MarkdownElementNodeParser,
),
)
)
# Embeddings
try:
from llama_index.embeddings.openai import OpenAIEmbedding # pants: no-infer-dep
enum_members.append(
(
"OPENAI_EMBEDDING",
ConfigurableTransformation(
name="OpenAI Embedding",
transformation_category=TransformationCategories.EMBEDDING,
component_type=OpenAIEmbedding,
),
)
)
except (ImportError, ValidationError):
pass
try:
from llama_index.embeddings.azure_openai import (
AzureOpenAIEmbedding,
) # pants: no-infer-dep
enum_members.append(
(
"AZURE_EMBEDDING",
ConfigurableTransformation(
name="Azure OpenAI Embedding",
transformation_category=TransformationCategories.EMBEDDING,
component_type=AzureOpenAIEmbedding,
),
)
)
except (ImportError, ValidationError):
pass
try:
from llama_index.embeddings.cohere import (
CohereEmbedding,
) # pants: no-infer-dep
enum_members.append(
(
"COHERE_EMBEDDING",
ConfigurableTransformation(
name="Cohere Embedding",
transformation_category=TransformationCategories.EMBEDDING,
component_type=CohereEmbedding,
),
)
)
except (ImportError, ValidationError):
pass
try:
from llama_index.embeddings.bedrock import (
BedrockEmbedding,
) # pants: no-infer-dep
enum_members.append(
(
"BEDROCK_EMBEDDING",
ConfigurableTransformation(
name="Bedrock Embedding",
transformation_category=TransformationCategories.EMBEDDING,
component_type=BedrockEmbedding,
),
)
)
except (ImportError, ValidationError):
pass
try:
from llama_index.embeddings.huggingface_api import (
HuggingFaceInferenceAPIEmbedding,
) # pants: no-infer-dep
enum_members.append(
(
"HUGGINGFACE_API_EMBEDDING",
ConfigurableTransformation(
name="HuggingFace API Embedding",
transformation_category=TransformationCategories.EMBEDDING,
component_type=HuggingFaceInferenceAPIEmbedding,
),
)
)
except (ImportError, ValidationError):
pass
try:
from llama_index.embeddings.gemini import (
GeminiEmbedding,
) # pants: no-infer-dep
enum_members.append(
(
"GEMINI_EMBEDDING",
ConfigurableTransformation(
name="Gemini Embedding",
transformation_category=TransformationCategories.EMBEDDING,
component_type=GeminiEmbedding,
),
)
)
except (ImportError, ValidationError):
pass
try:
from llama_index.embeddings.mistralai import (
MistralAIEmbedding,
) # pants: no-infer-dep
enum_members.append(
(
"MISTRALAI_EMBEDDING",
ConfigurableTransformation(
name="MistralAI Embedding",
transformation_category=TransformationCategories.EMBEDDING,
component_type=MistralAIEmbedding,
),
)
)
except (ImportError, ValidationError):
pass
return ConfigurableComponent("ConfigurableTransformations", enum_members) # type: ignore
ConfigurableTransformations = build_configurable_transformation_enum()
T = TypeVar("T", bound=BaseComponent)
| ConfigurableComponent |
python | astropy__astropy | astropy/modeling/tests/test_compound.py | {
"start": 13549,
"end": 13756
} | class ____(Model):
stddev = Parameter(default=0, min=0, max=0.3)
mean = Parameter(default=0, fixed=True)
@staticmethod
def evaluate(stddev, mean):
return stddev, mean
| _ConstraintsTestA |
python | encode__django-rest-framework | tests/test_validation_error.py | {
"start": 527,
"end": 774
} | class ____(APIView):
def get(self, request, *args, **kwargs):
ExampleSerializer(data={}).is_valid(raise_exception=True)
@api_view(['GET'])
def error_view(request):
ExampleSerializer(data={}).is_valid(raise_exception=True)
| ErrorView |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/vector/vectorize_observation.py | {
"start": 11925,
"end": 12761
} | class ____(VectorizeTransformObservation):
"""Observation wrapper that flattens the observation.
Example:
>>> import gymnasium as gym
>>> envs = gym.make_vec("CarRacing-v3", num_envs=3, vectorization_mode="sync")
>>> obs, info = envs.reset(seed=123)
>>> obs.shape
(3, 96, 96, 3)
>>> envs = FlattenObservation(envs)
>>> obs, info = envs.reset(seed=123)
>>> obs.shape
(3, 27648)
>>> envs.close()
"""
def __init__(self, env: VectorEnv):
"""Constructor for any environment's observation space that implements ``spaces.utils.flatten_space`` and ``spaces.utils.flatten``.
Args:
env: The vector environment to wrap
"""
super().__init__(env, transform_observation.FlattenObservation)
| FlattenObservation |
python | optuna__optuna | optuna/samplers/nsgaii/_crossovers/_vsbx.py | {
"start": 295,
"end": 5925
} | class ____(BaseCrossover):
"""Modified Simulated Binary Crossover operation used by
:class:`~optuna.samplers.NSGAIISampler`.
vSBX generates child individuals without excluding any region of the parameter space,
while maintaining the excellent properties of SBX.
In the paper, vSBX has only one argument, ``eta``,
and generate two child individuals.
However, Optuna can only return one child individual in one crossover operation,
so it uses the ``uniform_crossover_prob`` and ``use_child_gene_prob`` arguments
to make two individuals into one.
- `Pedro J. Ballester, Jonathan N. Carter.
Real-Parameter Genetic Algorithms for Finding Multiple Optimal Solutions
in Multi-modal Optimization. GECCO 2003: 706-717
<https://doi.org/10.1007/3-540-45105-6_86>`__
Args:
eta:
Distribution index. A small value of ``eta`` allows distant solutions
to be selected as children solutions. If not specified, takes default
value of ``2`` for single objective functions and ``20`` for multi objective.
uniform_crossover_prob:
``uniform_crossover_prob`` is the probability of uniform crossover
between two individuals selected as candidate child individuals.
This argument is whether or not two individuals are
crossover to make one child individual.
If the ``uniform_crossover_prob`` exceeds 0.5,
the result is equivalent to ``1-uniform_crossover_prob``,
because it returns one of the two individuals of the crossover result.
If not specified, takes default value of ``0.5``.
The range of values is ``[0.0, 1.0]``.
use_child_gene_prob:
``use_child_gene_prob`` is the probability of using the value of the generated
child variable rather than the value of the parent.
This probability is applied to each variable individually.
where ``1-use_chile_gene_prob`` is the probability of
using the parent's values as it is.
If not specified, takes default value of ``0.5``.
The range of values is ``(0.0, 1.0]``.
"""
n_parents = 2
def __init__(
self,
eta: float | None = None,
uniform_crossover_prob: float = 0.5,
use_child_gene_prob: float = 0.5,
) -> None:
if (eta is not None) and (eta < 0.0):
raise ValueError("The value of `eta` must be greater than or equal to 0.0.")
self._eta = eta
if uniform_crossover_prob < 0.0 or uniform_crossover_prob > 1.0:
raise ValueError(
"The value of `uniform_crossover_prob` must be in the range [0.0, 1.0]."
)
if use_child_gene_prob <= 0.0 or use_child_gene_prob > 1.0:
raise ValueError("The value of `use_child_gene_prob` must be in the range (0.0, 1.0].")
self._uniform_crossover_prob = uniform_crossover_prob
self._use_child_gene_prob = use_child_gene_prob
def crossover(
self,
parents_params: np.ndarray,
rng: np.random.RandomState,
study: Study,
search_space_bounds: np.ndarray,
) -> np.ndarray:
# https://doi.org/10.1007/3-540-45105-6_86
# Section 3.2 Crossover Schemes (vSBX)
if self._eta is None:
eta = 20.0 if study._is_multi_objective() else 2.0
else:
eta = self._eta
eps = 1e-10
us = rng.rand(len(search_space_bounds))
beta_1 = np.power(1 / np.maximum((2 * us), eps), 1 / (eta + 1))
beta_2 = np.power(1 / np.maximum((2 * (1 - us)), eps), 1 / (eta + 1))
u_1 = rng.rand()
if u_1 <= 0.5:
c1 = 0.5 * ((1 + beta_1) * parents_params[0] + (1 - beta_2) * parents_params[1])
else:
c1 = 0.5 * ((1 - beta_1) * parents_params[0] + (1 + beta_2) * parents_params[1])
u_2 = rng.rand()
if u_2 <= 0.5:
c2 = 0.5 * ((3 - beta_1) * parents_params[0] - (1 - beta_2) * parents_params[1])
else:
c2 = 0.5 * (-(1 - beta_1) * parents_params[0] + (3 - beta_2) * parents_params[1])
# vSBX applies crossover with use_child_gene_prob and uniform_crossover_prob.
# the gene of the parent individual is the gene of the child individual.
# The original vSBX creates two child individuals,
# but optuna's implementation creates only one child individual.
# Therefore, when there is no crossover,
# the gene is selected with equal probability from the parent individuals x1 and x2.
child1_params_list = []
child2_params_list = []
for c1_i, c2_i, x1_i, x2_i in zip(c1, c2, parents_params[0], parents_params[1]):
if rng.rand() < self._use_child_gene_prob:
if rng.rand() >= self._uniform_crossover_prob:
child1_params_list.append(c1_i)
child2_params_list.append(c2_i)
else:
child1_params_list.append(c2_i)
child2_params_list.append(c1_i)
else:
if rng.rand() >= self._uniform_crossover_prob:
child1_params_list.append(x1_i)
child2_params_list.append(x2_i)
else:
child1_params_list.append(x2_i)
child2_params_list.append(x1_i)
child_params_list = child1_params_list if rng.rand() < 0.5 else child2_params_list
child_params = np.array(child_params_list)
return child_params
| VSBXCrossover |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/required1.py | {
"start": 297,
"end": 1038
} | class ____(TypedDict):
a: Required[int]
b: NotRequired[int]
# This should generate an error because NotRequired can't be
# used in this context.
c: NotRequired[NotRequired[int]]
# This should generate an error because Required can't be
# used in this context.
d: Required[Required[int]]
e: NotRequired[Annotated[int, "hi"]]
# This should generate an error because it's missing type args.
f: Required
# This should generate an error because it's missing type args.
g: NotRequired
# This should generate an error because Required can't be
# used in this context.
x: Required[int]
# This should generate an error because NotRequired can't be
# used in this context.
y: Required[int]
| TD1 |
python | lxml__lxml | src/lxml/tests/test_unicode.py | {
"start": 5386,
"end": 7821
} | class ____(HelperTestCase):
def test_illegal_utf8(self):
data = b'<test>\x80\x80\x80</test>'
self.assertRaises(etree.XMLSyntaxError, etree.fromstring, data)
def test_illegal_utf8_recover(self):
data = b'<test>\x80\x80\x80</test>'
parser = etree.XMLParser(recover=True)
if etree.LIBXML_VERSION >= (2, 12, 0):
tree = etree.fromstring(data, parser)
self.assertEqual('\ufffd\ufffd\ufffd', tree.text)
else:
self.assertRaises(etree.XMLSyntaxError, etree.fromstring, data, parser)
def _test_encoding(self, encoding, xml_encoding_name=None):
self._test_encoded_input("<tag attrib='123'></tag>", 'tag', encoding, xml_encoding_name)
self._test_encoded_input("<älämänt öttrib='Атрибут'></älämänt>", 'älämänt', encoding, xml_encoding_name)
def _test_encoded_input(self, xml_input, tag_name, encoding, xml_encoding_name=None):
foo = """<?xml version='1.0' encoding='%s'?>\n""" % (
xml_encoding_name or encoding) + xml_input
root = etree.fromstring(foo.encode(encoding))
self.assertEqual(tag_name, root.tag)
doc_encoding = root.getroottree().docinfo.encoding
self.assertTrue(
doc_encoding.lower().rstrip('lbe'),
(xml_encoding_name or encoding).lower().rstrip('lbe'))
if 'sig' not in encoding:
xml = etree.tostring(root, encoding=encoding)
etree.fromstring(xml) # encoding
def test_utf8_fromstring(self):
self._test_encoding('utf-8')
def test_utf8sig_fromstring(self):
self._test_encoding('utf_8_sig', 'utf-8')
def test_utf16_fromstring(self):
self._test_encoding('utf-16')
def test_utf16LE_fromstring(self):
self._test_encoding('utf-16le', 'utf-16')
def test_utf16BE_fromstring(self):
self._test_encoding('utf-16be', 'utf-16')
def test_utf32_fromstring(self):
self._test_encoding('utf-32', 'utf-32')
def test_utf32LE_fromstring(self):
self._test_encoding('utf-32le', 'utf-32')
def test_utf32BE_fromstring(self):
self._test_encoding('utf-32be', 'utf-32')
def test_suite():
suite = unittest.TestSuite()
suite.addTests([unittest.defaultTestLoader.loadTestsFromTestCase(UnicodeTestCase)])
suite.addTests([unittest.defaultTestLoader.loadTestsFromTestCase(EncodingsTestCase)])
return suite
| EncodingsTestCase |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/images/api/main.py | {
"start": 963,
"end": 1782
} | class ____(webapp2.RequestHandler):
def get(self):
if self.request.get("id"):
photo = Photo.get_by_id(int(self.request.get("id")))
if photo:
img = images.Image(photo.full_size_image)
img.resize(width=80, height=100)
img.im_feeling_lucky()
thumbnail = img.execute_transforms(output_encoding=images.JPEG)
self.response.headers["Content-Type"] = "image/jpeg"
self.response.out.write(thumbnail)
return
# Either "id" wasn't provided, or there was no image with that ID
# in the datastore.
self.error(404)
# [END gae_images_api_ndb_thumbnailer]
app = webapp2.WSGIApplication([("/img", Thumbnailer)], debug=True)
# [END gae_images_api_ndb]
| Thumbnailer |
python | celery__celery | t/unit/app/test_beat.py | {
"start": 4243,
"end": 4392
} | class ____(mScheduler):
def send_task(self, *args, **kwargs):
raise beat.SchedulingError('Could not apply task')
| mSchedulerSchedulingError |
python | ray-project__ray | rllib/examples/rl_modules/classes/lstm_containing_rlm.py | {
"start": 422,
"end": 6039
} | class ____(TorchRLModule, ValueFunctionAPI):
"""An example TorchRLModule that contains an LSTM layer.
.. testcode::
import numpy as np
import gymnasium as gym
B = 10 # batch size
T = 5 # seq len
e = 25 # embedding dim
CELL = 32 # LSTM cell size
# Construct the RLModule.
my_net = LSTMContainingRLModule(
observation_space=gym.spaces.Box(-1.0, 1.0, (e,), np.float32),
action_space=gym.spaces.Discrete(4),
model_config={"lstm_cell_size": CELL}
)
# Create some dummy input.
obs = torch.from_numpy(
np.random.random_sample(size=(B, T, e)
).astype(np.float32))
state_in = my_net.get_initial_state()
# Repeat state_in across batch.
state_in = tree.map_structure(
lambda s: torch.from_numpy(s).unsqueeze(0).repeat(B, 1), state_in
)
input_dict = {
Columns.OBS: obs,
Columns.STATE_IN: state_in,
}
# Run through all 3 forward passes.
print(my_net.forward_inference(input_dict))
print(my_net.forward_exploration(input_dict))
print(my_net.forward_train(input_dict))
# Print out the number of parameters.
num_all_params = sum(int(np.prod(p.size())) for p in my_net.parameters())
print(f"num params = {num_all_params}")
"""
@override(TorchRLModule)
def setup(self):
"""Use this method to create all the model components that you require.
Feel free to access the following useful properties in this class:
- `self.model_config`: The config dict for this RLModule class,
which should contain flxeible settings, for example: {"hiddens": [256, 256]}.
- `self.observation|action_space`: The observation and action space that
this RLModule is subject to. Note that the observation space might not be the
exact space from your env, but that it might have already gone through
preprocessing through a connector pipeline (for example, flattening,
frame-stacking, mean/std-filtering, etc..).
"""
# Assume a simple Box(1D) tensor as input shape.
in_size = self.observation_space.shape[0]
# Get the LSTM cell size from the `model_config` attribute:
self._lstm_cell_size = self.model_config.get("lstm_cell_size", 256)
self._lstm = nn.LSTM(in_size, self._lstm_cell_size, batch_first=True)
in_size = self._lstm_cell_size
# Build a sequential stack.
layers = []
# Get the dense layer pre-stack configuration from the same config dict.
dense_layers = self.model_config.get("dense_layers", [128, 128])
for out_size in dense_layers:
# Dense layer.
layers.append(nn.Linear(in_size, out_size))
# ReLU activation.
layers.append(nn.ReLU())
in_size = out_size
self._fc_net = nn.Sequential(*layers)
# Logits layer (no bias, no activation).
self._pi_head = nn.Linear(in_size, self.action_space.n)
# Single-node value layer.
self._values = nn.Linear(in_size, 1)
@override(TorchRLModule)
def get_initial_state(self) -> Any:
return {
"h": np.zeros(shape=(self._lstm_cell_size,), dtype=np.float32),
"c": np.zeros(shape=(self._lstm_cell_size,), dtype=np.float32),
}
@override(TorchRLModule)
def _forward(self, batch, **kwargs):
# Compute the basic 1D embedding tensor (inputs to policy- and value-heads).
embeddings, state_outs = self._compute_embeddings_and_state_outs(batch)
logits = self._pi_head(embeddings)
# Return logits as ACTION_DIST_INPUTS (categorical distribution).
# Note that the default `GetActions` connector piece (in the EnvRunner) will
# take care of argmax-"sampling" from the logits to yield the inference (greedy)
# action.
return {
Columns.ACTION_DIST_INPUTS: logits,
Columns.STATE_OUT: state_outs,
}
@override(TorchRLModule)
def _forward_train(self, batch, **kwargs):
# Same logic as _forward, but also return embeddings to be used by value
# function branch during training.
embeddings, state_outs = self._compute_embeddings_and_state_outs(batch)
logits = self._pi_head(embeddings)
return {
Columns.ACTION_DIST_INPUTS: logits,
Columns.STATE_OUT: state_outs,
Columns.EMBEDDINGS: embeddings,
}
# We implement this RLModule as a ValueFunctionAPI RLModule, so it can be used
# by value-based methods like PPO or IMPALA.
@override(ValueFunctionAPI)
def compute_values(
self, batch: Dict[str, Any], embeddings: Optional[Any] = None
) -> TensorType:
if embeddings is None:
embeddings, _ = self._compute_embeddings_and_state_outs(batch)
values = self._values(embeddings).squeeze(-1)
return values
def _compute_embeddings_and_state_outs(self, batch):
obs = batch[Columns.OBS]
state_in = batch[Columns.STATE_IN]
h, c = state_in["h"], state_in["c"]
# Unsqueeze the layer dim (we only have 1 LSTM layer).
embeddings, (h, c) = self._lstm(obs, (h.unsqueeze(0), c.unsqueeze(0)))
# Push through our FC net.
embeddings = self._fc_net(embeddings)
# Squeeze the layer dim (we only have 1 LSTM layer).
return embeddings, {"h": h.squeeze(0), "c": c.squeeze(0)}
| LSTMContainingRLModule |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.