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 | huggingface__transformers | src/transformers/models/csm/modular_csm.py | {
"start": 1775,
"end": 5016
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
depth_decoder_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction) of the depth decoder model.
depth_decoder_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the depth decoder (scores for each vocabulary token before SoftMax).
depth_decoder_past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
depth_decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
depth_decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
backbone_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction) of the backbone model.
"""
loss: Optional[torch.FloatTensor] = None
logits: Optional[torch.FloatTensor] = None
past_key_values: Optional[Cache] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
depth_decoder_loss: Optional[torch.FloatTensor] = None
depth_decoder_logits: Optional[torch.FloatTensor] = None
depth_decoder_past_key_values: Optional[Cache] = None
depth_decoder_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
depth_decoder_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
backbone_loss: Optional[torch.FloatTensor] = None
# manually specify names for correct naming when converting from modular
| CsmOutputWithPast |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis17.py | {
"start": 315,
"end": 1389
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis17.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [43812736, 45705088]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
chart.set_y_axis({"log_base": 10})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | spyder-ide__spyder | spyder/plugins/run/models.py | {
"start": 728,
"end": 5850
} | class ____(QAbstractListModel):
sig_executor_widget_changed = Signal(object)
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.uuid: Optional[str] = None
self.current_input: Optional[Tuple[str, str]] = None
self.executor_names: Dict[str, str] = {}
self.executor_configurations: Dict[Tuple[str, str], Dict[
str, SupportedExecutionRunConfiguration]] = {}
self.executors_per_input: Dict[Tuple[str, str], Dict[str, int]] = {}
self.inverted_pos: Dict[Tuple[str, str], Dict[int, str]] = {}
self.executor_priority: Dict[Tuple[str, str], Dict[str, int]] = {}
def set_executor_name(self, executor_id: str, executor_name: str):
self.executor_names[executor_id] = executor_name
def add_input_executor_configuration(
self,
ext: str,
context_id: str,
executor_id: str,
config: SupportedExecutionRunConfiguration
):
executor_conf = self.executor_configurations.get((ext, context_id), {})
executor_conf[executor_id] = config
self.executor_configurations[(ext, context_id)] = executor_conf
input_executors = self.executors_per_input.get((ext, context_id), {})
all_exec_prio = self.executor_priority.get((ext, context_id), {})
priority = config['priority']
# Remove if existing
input_executors.pop(executor_id, None)
all_exec_prio.pop(executor_id, None)
all_exec_prio[executor_id] = priority
input_values = list(all_exec_prio.items())
input_values = sorted(input_values, key=lambda k: k[1])
input_values = [(x, i) for i, (x, _) in enumerate(input_values)]
self.executors_per_input[(ext, context_id)] = dict(input_values)
self.inverted_pos[(ext, context_id)] = {
v: k for (k, v) in input_values}
self.executor_priority[(ext, context_id)] = all_exec_prio
def remove_input_executor_configuration(
self,
ext: str,
context_id: str,
executor_id: str
):
input_executors = self.executors_per_input[(ext, context_id)]
pos = input_executors.pop(executor_id)
inverted_executors = self.inverted_pos[(ext, context_id)]
inverted_executors.pop(pos)
def switch_input(self, uuid: str, run_input: Tuple[str, str]):
if run_input in self.executors_per_input:
self.beginResetModel()
self.current_input = run_input
self.uuid = uuid
self.endResetModel()
else:
raise ValueError(
f'The requested run input combination {run_input} is not '
f'registered'
)
def get_selected_run_executor(
self,
index: int
) -> Tuple[str, SupportedExecutionRunConfiguration]:
executor_indices = self.inverted_pos[self.current_input]
executor_name = executor_indices[index]
executors = self.executor_configurations[self.current_input]
executor = executors[executor_name]
return executor_name, executor
def get_run_executor_index(self, executor_name: str) -> int:
ordered_executors = self.executors_per_input[self.current_input]
executor_index = ordered_executors[executor_name]
return executor_index
def get_initial_index(self) -> int:
last_executor = self.parent.get_last_used_executor_parameters(
self.uuid)
executor_id = last_executor['executor']
pos = 0
if executor_id is not None:
executors = self.executors_per_input[self.current_input]
pos = executors[executor_id]
return pos
def get_default_executor(self, input: Tuple[str, str]) -> str:
executors = self.inverted_pos[input]
return executors[0]
def executor_supports_configuration(
self,
executor: str,
exec_input: Tuple[str, str]
) -> bool:
input_executors = self.executor_configurations.get(exec_input, {})
return executor in input_executors
def data(self, index: QModelIndex, role: int = Qt.DisplayRole):
if role == Qt.DisplayRole or role == Qt.EditRole:
executor_indices = self.inverted_pos[self.current_input]
executor_id = executor_indices[index.row()]
return self.executor_names[executor_id]
def rowCount(self, parent: QModelIndex = None) -> int:
executors = self.executors_per_input.get(self.current_input, {})
return len(executors)
def __contains__(self, exec_input: Tuple[str, str]) -> bool:
return exec_input in self.executor_configurations
def __len__(self):
return len(self.executor_configurations)
def __iter__(self):
return iter(self.executor_configurations)
def __getitem__(
self, input_executor: tuple) -> SupportedExecutionRunConfiguration:
(input, executor) = input_executor
input_executors = self.executor_configurations[input]
return input_executors[executor]
| RunExecutorListModel |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/matmul_op_test.py | {
"start": 1376,
"end": 2408
} | class ____(test_lib.TestCase):
"""Simple test for tf.matmul where Tout is different from T."""
def testBatchMatMulV3OutputType(self):
# TODO(shivaniagrawal): uint8 is not supported for mixed matmul type in XLA.
for (a_dtype, b_dtype) in [(np.int8, np.int8), (np.uint8, np.uint8)]:
a = np.array([[1, 2], [3, 4]], dtype=a_dtype)
b = np.array([[1, 2], [3, 4]], dtype=b_dtype)
c = math_ops.batch_mat_mul_v3(a, b, adj_y=True, Tout=np.int32)
self.assertAllEqual((2, 2), c.shape)
self.assertAllEqual([[5, 11], [11, 25]], c)
def testBatchMatMulV3MixedPrec(self):
# TODO(shivaniagrawal): uint8 is not supported for mixed matmul type in XLA.
np_bf16 = dtypes.bfloat16.as_numpy_dtype
a = np.array([[1, 2], [3, 4]], dtype=np.int8)
b = np.array([[1, 2], [3, 4]], dtype=np_bf16)
c = math_ops.batch_mat_mul_v3(a, b, adj_y=True, Tout=np_bf16)
self.assertAllEqual((2, 2), c.shape)
self.assertAllEqual([[5, 11], [11, 25]], c)
@test_util.with_eager_op_as_function
| MatMulMixedType |
python | weaviate__weaviate-python-client | weaviate/collections/aggregate.py | {
"start": 668,
"end": 773
} | class ____(_Hybrid, _NearImage, _NearObject, _NearText, _NearVector, _OverAll):
pass
| _AggregateCollection |
python | django__django | tests/admin_inlines/admin.py | {
"start": 4276,
"end": 4634
} | class ____(forms.ModelForm):
title1 = forms.CharField(max_length=100)
def clean(self):
cleaned_data = self.cleaned_data
title1 = cleaned_data.get("title1")
title2 = cleaned_data.get("title2")
if title1 != title2:
raise ValidationError("The two titles must be the same")
return cleaned_data
| TitleForm |
python | ray-project__ray | python/ray/train/tests/test_session.py | {
"start": 9537,
"end": 10992
} | class ____(Accelerator):
pass
def test_set_and_get_accelerator(session):
accelerator = FakeAccelerator()
set_accelerator(accelerator)
assert get_accelerator(FakeAccelerator) is accelerator
def test_get_accelerator_constructs_default_accelerator(session):
assert isinstance(get_accelerator(FakeAccelerator), FakeAccelerator)
def test_get_accelerator_raises_error_outside_session():
with pytest.raises(SessionMisuseError):
get_accelerator(FakeAccelerator)
def test_set_accelerator_raises_error_if_accelerator_already_set(session):
accelerator1, accelerator2 = FakeAccelerator(), FakeAccelerator()
set_accelerator(accelerator1)
with pytest.raises(RuntimeError):
set_accelerator(accelerator2)
def test_set_accelerator_raises_error_outside_session():
accelerator = FakeAccelerator()
with pytest.raises(SessionMisuseError):
set_accelerator(accelerator)
def test_application_error_raised():
def f():
raise ValueError
init_session(
training_func=f,
world_rank=0,
local_rank=0,
node_rank=0,
local_world_size=1,
world_size=1,
storage=storage,
)
session = get_session()
session.start()
with pytest.raises(StartTraceback):
session.get_next()
shutdown_session()
if __name__ == "__main__":
import sys
import pytest
sys.exit(pytest.main(["-v", "-x", __file__]))
| FakeAccelerator |
python | PyCQA__pylint | tests/functional/c/consider/consider_using_in.py | {
"start": 2307,
"end": 2383
} | class ____:
value = 2
A.value == 1 or A.value == 2 # [consider-using-in]
| A |
python | realpython__materials | python-class/mixins.py | {
"start": 127,
"end": 285
} | class ____:
def to_json(self):
return json.dumps(self.__dict__)
def to_pickle(self):
return pickle.dumps(self.__dict__)
| SerializerMixin |
python | huggingface__transformers | src/transformers/models/clipseg/modeling_clipseg.py | {
"start": 29060,
"end": 30974
} | class ____(CLIPSegPreTrainedModel):
config: CLIPSegTextConfig
input_modalities = ("text",)
_no_split_modules = ["CLIPSegTextEmbeddings", "CLIPSegEncoderLayer"]
def __init__(self, config: CLIPSegTextConfig):
super().__init__(config)
self.text_model = CLIPSegTextTransformer(config)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> nn.Module:
return self.text_model.embeddings.token_embedding
def set_input_embeddings(self, value):
self.text_model.embeddings.token_embedding = value
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, BaseModelOutputWithPooling]:
r"""
Examples:
```python
>>> from transformers import AutoTokenizer, CLIPSegTextModel
>>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
>>> model = CLIPSegTextModel.from_pretrained("CIDAS/clipseg-rd64-refined")
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
```"""
return self.text_model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
| CLIPSegTextModel |
python | pypa__pip | src/pip/_vendor/pyproject_hooks/_impl.py | {
"start": 1774,
"end": 3746
} | class ____(Exception):
"""May be raised by build_sdist if the backend indicates that it can't."""
def __init__(self, traceback: str) -> None:
self.traceback = traceback
def default_subprocess_runner(
cmd: Sequence[str],
cwd: Optional[str] = None,
extra_environ: Optional[Mapping[str, str]] = None,
) -> None:
"""The default method of calling the wrapper subprocess.
This uses :func:`subprocess.check_call` under the hood.
"""
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
check_call(cmd, cwd=cwd, env=env)
def quiet_subprocess_runner(
cmd: Sequence[str],
cwd: Optional[str] = None,
extra_environ: Optional[Mapping[str, str]] = None,
) -> None:
"""Call the subprocess while suppressing output.
This uses :func:`subprocess.check_output` under the hood.
"""
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
check_output(cmd, cwd=cwd, env=env, stderr=STDOUT)
def norm_and_check(source_tree: str, requested: str) -> str:
"""Normalise and check a backend path.
Ensure that the requested backend path is specified as a relative path,
and resolves to a location under the given source tree.
Return an absolute version of the requested path.
"""
if os.path.isabs(requested):
raise ValueError("paths must be relative")
abs_source = os.path.abspath(source_tree)
abs_requested = os.path.normpath(os.path.join(abs_source, requested))
# We have to use commonprefix for Python 2.7 compatibility. So we
# normalise case to avoid problems because commonprefix is a character
# based comparison :-(
norm_source = os.path.normcase(abs_source)
norm_requested = os.path.normcase(abs_requested)
if os.path.commonprefix([norm_source, norm_requested]) != norm_source:
raise ValueError("paths must be inside source tree")
return abs_requested
| UnsupportedOperation |
python | tensorflow__tensorflow | tensorflow/python/distribute/multi_worker_test_base.py | {
"start": 15007,
"end": 19524
} | class ____(test.TestCase):
"""Base class for testing multi node strategy and dataset."""
@classmethod
def setUpClass(cls, num_workers=2, num_ps=1): # pylint: disable=g-missing-super-call
"""Create a local cluster with 2 workers."""
cls._cluster_spec = create_in_process_cluster(num_workers=num_workers,
num_ps=num_ps)
cls._default_target = 'grpc://' + cls._cluster_spec['worker'][0]
def setUp(self):
# We only cache the session in one test because another test may have a
# different session config or master target.
self._thread_local = threading.local()
self._thread_local.cached_session = None
self._coord = coordinator.Coordinator()
@contextlib.contextmanager
def session(self, graph=None, config=None, target=None):
"""Create a test session with master target set to the testing cluster.
Creates a test session that connects to the local testing cluster.
Args:
graph: Optional graph to use during the returned session.
config: An optional config_pb2.ConfigProto to use to configure the
session.
target: the target of session to connect to.
Yields:
A Session object that should be used as a context manager to surround
the graph building and execution code in a test case.
"""
config = self._create_config(config)
if target is None:
target = self._default_target
with session.Session(graph=graph, config=config, target=target) as sess:
yield sess
@contextlib.contextmanager
# TODO(b/117573461): Overwrite self.evaluate() to use this function.
def cached_session(self, graph=None, config=None, target=None):
"""Create a test session with master target set to the testing cluster.
Creates a test session that connects to the local testing cluster.
The session is only created once per test and then reused.
Args:
graph: Optional graph to use during the returned session.
config: An optional config_pb2.ConfigProto to use to configure the
session.
target: the target of session to connect to.
Yields:
A Session object that should be used as a context manager to surround
the graph building and execution code in a test case. Note that the
session will live until the end of the test.
"""
config = self._create_config(config)
if target is None:
target = self._default_target
if getattr(self._thread_local, 'cached_session', None) is None:
self._thread_local.cached_session = session.Session(
graph=None, config=config, target=target)
sess = self._thread_local.cached_session
with sess.graph.as_default(), sess.as_default():
yield sess
def _create_config(self, config):
if config is None:
config = config_pb2.ConfigProto(allow_soft_placement=True)
else:
config = copy.deepcopy(config)
# Don't perform optimizations for tests so we don't inadvertently run
# gpu ops on cpu
config.graph_options.optimizer_options.opt_level = -1
config.graph_options.rewrite_options.constant_folding = (
rewriter_config_pb2.RewriterConfig.OFF)
return config
def _run_client(self, client_fn, task_type, task_id, num_gpus, eager_mode,
*args, **kwargs):
def wrapped_client_fn():
with self._coord.stop_on_exception():
client_fn(task_type, task_id, num_gpus, *args, **kwargs)
if eager_mode:
with context.eager_mode():
wrapped_client_fn()
else:
with context.graph_mode():
wrapped_client_fn()
def _run_between_graph_clients(self, client_fn, cluster_spec, num_gpus, *args,
**kwargs):
"""Runs several clients for between-graph replication.
Args:
client_fn: a function that needs to accept `task_type`, `task_id`,
`num_gpus`.
cluster_spec: a dict specifying jobs in a cluster.
num_gpus: number of GPUs per worker.
*args: will be passed to `client_fn`.
**kwargs: will be passed to `client_fn`.
"""
threads = []
for task_type in ['chief', 'worker']:
for task_id in range(len(cluster_spec.get(task_type, []))):
t = threading.Thread(
target=self._run_client,
args=(client_fn, task_type, task_id, num_gpus,
context.executing_eagerly()) + args,
kwargs=kwargs)
t.start()
threads.append(t)
self._coord.join(threads)
| MultiWorkerTestBase |
python | apache__airflow | airflow-core/src/airflow/executors/workloads.py | {
"start": 1457,
"end": 1726
} | class ____(BaseModel):
token: str
"""The identity token for this workload"""
@staticmethod
def generate_token(sub_id: str, generator: JWTGenerator | None = None) -> str:
return generator.generate({"sub": sub_id}) if generator else ""
| BaseWorkload |
python | scipy__scipy | doc/source/array_api_capabilities_table.py | {
"start": 2233,
"end": 3392
} | class ____(SphinxDirective):
has_content = False
option_spec = {
module_name.replace("scipy.", ""): directives.unchanged
for module_name in PUBLIC_MODULES
}
option_spec["backend_type"] = directives.unchanged
def run(self):
backend_type = self.options.pop("backend_type")
flat_table, backends = _get_flat_table_and_backends(self.env, backend_type)
table_stats = calculate_table_statistics(flat_table)
modules = self.options.keys()
rows = []
headers = ["module"]
headers += backends
for module in modules:
label = self.options.get(module)
module_text = f":ref:`{module} <{label}>`" if label else module
info, accurate_count = table_stats[f"scipy.{module}"]
total = info.pop("total")
row = [f"{module_text} ({total})"]
for backend, count in info.items():
cell_text = f"{count/total:.0%}{'*' if not accurate_count else ''}"
row.append(cell_text)
rows.append(row)
return _make_reST_table(rows, headers, self.state)
| ArrayAPISupportPerModule |
python | astropy__astropy | astropy/visualization/wcsaxes/tests/test_transform_coord_meta.py | {
"start": 1386,
"end": 4721
} | class ____(BaseImageTests):
@figure_test
def test_coords_overlay(self):
# Set up a simple WCS that maps pixels to non-projected distances
wcs = WCS(naxis=2)
wcs.wcs.ctype = ["x", "y"]
wcs.wcs.cunit = ["km", "km"]
wcs.wcs.crpix = [614.5, 856.5]
wcs.wcs.cdelt = [6.25, 6.25]
wcs.wcs.crval = [0.0, 0.0]
fig = Figure(figsize=(4, 4))
ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=wcs)
fig.add_axes(ax)
s = DistanceToLonLat(R=6378.273)
ax.coords["x"].set_ticklabel_position("")
ax.coords["y"].set_ticklabel_position("")
coord_meta = {}
coord_meta["type"] = ("longitude", "latitude")
coord_meta["wrap"] = (360.0 * u.deg, None)
coord_meta["unit"] = (u.deg, u.deg)
coord_meta["name"] = "lon", "lat"
overlay = ax.get_coords_overlay(s, coord_meta=coord_meta)
overlay.grid(color="red")
overlay["lon"].grid(color="red", linestyle="solid", alpha=0.3)
overlay["lat"].grid(color="blue", linestyle="solid", alpha=0.3)
overlay["lon"].set_ticklabel(size=7, exclude_overlapping=True)
overlay["lat"].set_ticklabel(size=7, exclude_overlapping=True)
overlay["lon"].set_ticklabel_position("brtl")
overlay["lat"].set_ticklabel_position("brtl")
overlay["lon"].set_ticks(spacing=10.0 * u.deg)
overlay["lat"].set_ticks(spacing=10.0 * u.deg)
ax.set_xlim(-0.5, 1215.5)
ax.set_ylim(-0.5, 1791.5)
return fig
@figure_test
def test_coords_overlay_auto_coord_meta(self):
fig = Figure(figsize=(4, 4))
ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=WCS(self.msx_header))
fig.add_axes(ax)
ax.grid(color="red", alpha=0.5, linestyle="solid")
overlay = ax.get_coords_overlay("fk5") # automatically sets coord_meta
overlay.grid(color="black", alpha=0.5, linestyle="solid")
overlay["ra"].set_ticks(color="black")
overlay["dec"].set_ticks(color="black")
ax.set_xlim(-0.5, 148.5)
ax.set_ylim(-0.5, 148.5)
return fig
@figure_test
def test_direct_init(self):
s = DistanceToLonLat(R=6378.273)
coord_meta = {}
coord_meta["type"] = ("longitude", "latitude")
coord_meta["wrap"] = (360.0 * u.deg, None)
coord_meta["unit"] = (u.deg, u.deg)
coord_meta["name"] = "lon", "lat"
fig = Figure(figsize=(4, 4))
ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], transform=s, coord_meta=coord_meta)
fig.add_axes(ax)
ax.coords["lon"].grid(color="red", linestyle="solid", alpha=0.3)
ax.coords["lat"].grid(color="blue", linestyle="solid", alpha=0.3)
ax.coords["lon"].set_auto_axislabel(False)
ax.coords["lat"].set_auto_axislabel(False)
ax.coords["lon"].set_ticklabel(size=7, exclude_overlapping=True)
ax.coords["lat"].set_ticklabel(size=7, exclude_overlapping=True)
ax.coords["lon"].set_ticklabel_position("brtl")
ax.coords["lat"].set_ticklabel_position("brtl")
ax.coords["lon"].set_ticks(spacing=10.0 * u.deg)
ax.coords["lat"].set_ticks(spacing=10.0 * u.deg)
ax.set_xlim(-400.0, 500.0)
ax.set_ylim(-300.0, 400.0)
return fig
| TestTransformCoordMeta |
python | Textualize__textual | tests/tree/test_tree_expand_etc.py | {
"start": 114,
"end": 4824
} | class ____(App[None]):
"""Test tree app."""
def compose(self) -> ComposeResult:
yield Tree("Test")
def on_mount(self) -> None:
tree = self.query_one(Tree)
for n in range(10):
tree.root.add(f"Trunk {n}")
node = tree.root.children[0]
for n in range(10):
node = node.add(str(n))
async def test_tree_node_expand() -> None:
"""Expanding one node should not expand all nodes."""
async with TreeApp().run_test() as pilot:
pilot.app.query_one(Tree).root.expand()
assert pilot.app.query_one(Tree).root.is_expanded is True
check_node = pilot.app.query_one(Tree).root.children[0]
while check_node.children:
assert any(child.is_expanded for child in check_node.children) is False
check_node = check_node.children[0]
async def test_tree_node_expand_all() -> None:
"""Expanding all on a node should expand all child nodes too."""
async with TreeApp().run_test() as pilot:
pilot.app.query_one(Tree).root.expand_all()
assert pilot.app.query_one(Tree).root.is_expanded is True
check_node = pilot.app.query_one(Tree).root.children[0]
while check_node.children:
assert check_node.children[0].is_expanded is True
assert any(child.is_expanded for child in check_node.children[1:]) is False
check_node = check_node.children[0]
async def test_tree_node_collapse() -> None:
"""Collapsing one node should not collapse all nodes."""
async with TreeApp().run_test() as pilot:
pilot.app.query_one(Tree).root.expand_all()
pilot.app.query_one(Tree).root.children[0].collapse()
assert pilot.app.query_one(Tree).root.children[0].is_expanded is False
check_node = pilot.app.query_one(Tree).root.children[0].children[0]
while check_node.children:
assert all(child.is_expanded for child in check_node.children) is True
check_node = check_node.children[0]
async def test_tree_node_collapse_all() -> None:
"""Collapsing all on a node should collapse all child noes too."""
async with TreeApp().run_test() as pilot:
pilot.app.query_one(Tree).root.expand_all()
pilot.app.query_one(Tree).root.children[0].collapse_all()
assert pilot.app.query_one(Tree).root.children[0].is_expanded is False
check_node = pilot.app.query_one(Tree).root.children[0].children[0]
while check_node.children:
assert check_node.children[0].is_expanded is False
assert all(child.is_expanded for child in check_node.children[1:]) is True
check_node = check_node.children[0]
async def test_tree_node_toggle() -> None:
"""Toggling one node should not toggle all nodes."""
async with TreeApp().run_test() as pilot:
assert pilot.app.query_one(Tree).root.is_expanded is False
check_node = pilot.app.query_one(Tree).root.children[0]
while check_node.children:
assert any(child.is_expanded for child in check_node.children) is False
check_node = check_node.children[0]
pilot.app.query_one(Tree).root.toggle()
assert pilot.app.query_one(Tree).root.is_expanded is True
check_node = pilot.app.query_one(Tree).root.children[0]
while check_node.children:
assert any(child.is_expanded for child in check_node.children) is False
check_node = check_node.children[0]
async def test_tree_node_toggle_all() -> None:
"""Toggling all on a node should toggle all child nodes too."""
async with TreeApp().run_test() as pilot:
assert pilot.app.query_one(Tree).root.is_expanded is False
check_node = pilot.app.query_one(Tree).root.children[0]
while check_node.children:
assert any(child.is_expanded for child in check_node.children) is False
check_node = check_node.children[0]
pilot.app.query_one(Tree).root.toggle_all()
assert pilot.app.query_one(Tree).root.is_expanded is True
check_node = pilot.app.query_one(Tree).root.children[0]
while check_node.children:
assert check_node.children[0].is_expanded is True
assert any(child.is_expanded for child in check_node.children[1:]) is False
check_node = check_node.children[0]
pilot.app.query_one(Tree).root.toggle_all()
assert pilot.app.query_one(Tree).root.is_expanded is False
check_node = pilot.app.query_one(Tree).root.children[0]
while check_node.children:
assert any(child.is_expanded for child in check_node.children) is False
check_node = check_node.children[0]
| TreeApp |
python | pandas-dev__pandas | pandas/tests/indexes/period/test_tools.py | {
"start": 135,
"end": 1060
} | class ____:
"""
Wish to match NumPy units
"""
@pytest.mark.parametrize(
"freq, base_date",
[
("W-THU", "1970-01-01"),
("D", "1970-01-01"),
("B", "1970-01-01"),
("h", "1970-01-01"),
("min", "1970-01-01"),
("s", "1970-01-01"),
("ms", "1970-01-01"),
("us", "1970-01-01"),
("ns", "1970-01-01"),
("M", "1970-01"),
("Y", 1970),
],
)
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
@pytest.mark.filterwarnings(
"ignore:Period with BDay freq is deprecated:FutureWarning"
)
def test_freq(self, freq, base_date):
rng = period_range(start=base_date, periods=10, freq=freq)
exp = np.arange(10, dtype=np.int64)
tm.assert_numpy_array_equal(rng.asi8, exp)
| TestPeriodRepresentation |
python | scrapy__scrapy | tests/test_squeues.py | {
"start": 1133,
"end": 1453
} | class ____:
def test_serialize(self):
q = self.queue()
q.push("a")
q.push(123)
q.push({"a": "dict"})
assert q.pop() == "a"
assert q.pop() == 123
assert q.pop() == {"a": "dict"}
test_nonserializable_object = nonserializable_object_test
| FifoDiskQueueTestMixin |
python | pytorch__pytorch | test/distributed/checkpoint/test_file_system_checkpoint_cpu.py | {
"start": 3602,
"end": 4686
} | class ____(TestCase):
@parametrize("thread_count", _THREAD_COUNTS)
def test_read_write_only_tensor(self, thread_count) -> None:
with tempfile.TemporaryDirectory() as path:
state_dict_to_save = MyTestModule().state_dict()
fs_writer = FileSystemWriter(path=path, thread_count=thread_count)
save_state_dict(
state_dict=state_dict_to_save,
storage_writer=fs_writer,
no_dist=True,
)
state_dict_to_load_to = MyTestModule().state_dict()
with self.assertRaises(AssertionError):
assert_state_dict_equal(self, state_dict_to_load_to, state_dict_to_save)
# Load from file without any resharding
fs_reader = FileSystemReader(path=path)
load_state_dict(
state_dict=state_dict_to_load_to,
storage_reader=fs_reader,
no_dist=True,
)
assert_state_dict_equal(self, state_dict_to_load_to, state_dict_to_save)
| TestDistributedStateDictSaveLoad |
python | Netflix__metaflow | test/core/tests/merge_artifacts_include.py | {
"start": 67,
"end": 2313
} | class ____(MetaflowTest):
PRIORITY = 1
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"recursive_switch",
"recursive_switch_inside_foreach",
]
@steps(0, ["start"])
def start(self):
self.non_modified_passdown = "a"
self.modified_to_same_value = "b"
self.manual_merge_required = "c"
self.ignore_me = "d"
@steps(2, ["linear"])
def modify_things(self):
# Set to different things
from metaflow.metaflow_current import current
self.manual_merge_required = current.task_id
self.ignore_me = current.task_id
self.modified_to_same_value = "e"
assert_equals(self.non_modified_passdown, "a")
@steps(0, ["join"], required=True)
def merge_things(self, inputs):
from metaflow.metaflow_current import current
from metaflow.exception import MissingInMergeArtifactsException
self.manual_merge_required = current.task_id
# Test to see if we raise an exception if include specifies non-merged things
assert_exception(
lambda: self.merge_artifacts(
inputs, include=["manual_merge_required", "foobar"]
),
MissingInMergeArtifactsException,
)
# Test to make sure nothing is set if failed merge_artifacts
assert not hasattr(self, "non_modified_passdown")
# Merge include non_modified_passdown
self.merge_artifacts(inputs, include=["non_modified_passdown"])
# Ensure that everything we expect is passed down
assert_equals(self.non_modified_passdown, "a")
assert_equals(self.manual_merge_required, current.task_id)
assert not hasattr(self, "ignore_me")
assert not hasattr(self, "modified_to_same_value")
@steps(0, ["end"])
def end(self):
# Check that all values made it through
assert_equals(self.non_modified_passdown, "a")
assert hasattr(self, "manual_merge_required")
@steps(3, ["all"])
def step_all(self):
assert_equals(self.non_modified_passdown, "a")
| MergeArtifactsIncludeTest |
python | getsentry__sentry | tests/sentry/integrations/github/test_client.py | {
"start": 1647,
"end": 19493
} | class ____(TestCase):
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
def setUp(self, get_jwt):
ten_days = timezone.now() + timedelta(days=10)
self.integration = self.create_integration(
organization=self.organization,
provider="github",
name="Github Test Org",
external_id="1",
metadata={
"access_token": "12345token",
"expires_at": ten_days.strftime("%Y-%m-%dT%H:%M:%S"),
},
)
self.repo = Repository.objects.create(
organization_id=self.organization.id,
name="Test-Organization/foo",
url="https://github.com/Test-Organization/foo",
provider="integrations:github",
external_id=123,
integration_id=self.integration.id,
)
self.install = get_installation_of_type(
GitHubIntegration, self.integration, self.organization.id
)
self.github_client = self.install.get_client()
@responses.activate
def test_get_rate_limit(self) -> None:
responses.add(
method=responses.GET,
url="https://api.github.com/rate_limit",
json={
"resources": {
"core": {"limit": 5000, "remaining": 4999, "reset": 1372700873, "used": 1},
"search": {"limit": 30, "remaining": 18, "reset": 1372697452, "used": 12},
"graphql": {"limit": 5000, "remaining": 4993, "reset": 1372700389, "used": 7},
},
},
)
with mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1"):
gh_rate_limit = self.github_client.get_rate_limit()
assert gh_rate_limit.limit == 5000
assert gh_rate_limit.remaining == 4999
assert gh_rate_limit.used == 1
assert gh_rate_limit.next_window() == "17:47:53"
gh_rate_limit = self.github_client.get_rate_limit("search")
assert gh_rate_limit.limit == 30
assert gh_rate_limit.remaining == 18
assert gh_rate_limit.used == 12
assert gh_rate_limit.next_window() == "16:50:52"
gh_rate_limit = self.github_client.get_rate_limit("graphql")
assert gh_rate_limit.limit == 5000
assert gh_rate_limit.remaining == 4993
assert gh_rate_limit.used == 7
assert gh_rate_limit.next_window() == "17:39:49"
@responses.activate
def test_get_rate_limit_non_existent_resource(self) -> None:
with pytest.raises(AssertionError):
self.github_client.get_rate_limit("foo")
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_check_file(self, get_jwt) -> None:
path = "src/sentry/integrations/github/client.py"
version = "master"
url = f"https://api.github.com/repos/{self.repo.name}/contents/{path}?ref={version}"
responses.add(
method=responses.HEAD,
url=url,
json={"text": 200},
)
resp = self.github_client.check_file(self.repo, path, version)
assert isinstance(resp, BaseApiResponse)
assert resp.status_code == 200
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_check_no_file(self, get_jwt) -> None:
path = "src/santry/integrations/github/client.py"
version = "master"
url = f"https://api.github.com/repos/{self.repo.name}/contents/{path}?ref={version}"
responses.add(method=responses.HEAD, url=url, status=404)
with pytest.raises(ApiError):
self.github_client.check_file(self.repo, path, version)
assert responses.calls[0].response.status_code == 404
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
@responses.activate
def test_get_stacktrace_link(self, mock_record, get_jwt) -> None:
path = "/src/sentry/integrations/github/client.py"
version = "master"
url = "https://api.github.com/repos/{}/contents/{}?ref={}".format(
self.repo.name, path.lstrip("/"), version
)
responses.add(
method=responses.HEAD,
url=url,
json={"text": 200},
)
source_url = self.install.get_stacktrace_link(self.repo, path, "master", version)
assert (
source_url
== "https://github.com/Test-Organization/foo/blob/master/src/sentry/integrations/github/client.py"
)
assert (
len(mock_record.mock_calls) == 4
) # get_stacktrace_link calls check_file, which also has metrics
start1, start2, halt1, halt2 = mock_record.mock_calls
assert start1.args[0] == EventLifecycleOutcome.STARTED
assert start2.args[0] == EventLifecycleOutcome.STARTED # check_file
assert halt1.args[0] == EventLifecycleOutcome.SUCCESS # check_file
assert halt2.args[0] == EventLifecycleOutcome.SUCCESS
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_get_with_pagination(self, get_jwt) -> None:
url = f"https://api.github.com/repos/{self.repo.name}/assignees?per_page={self.github_client.page_size}"
responses.add(
method=responses.GET,
url=url,
json={"text": 200},
headers={"link": f'<{url}&page=2>; rel="next", <{url}&page=4>; rel="last"'},
)
# For simplicity, we're skipping the `first` and `prev` links from the following responses
responses.add(
method=responses.GET,
url=f"{url}&page=2",
json={"text": 200},
headers={"link": f'<{url}&page=3>; rel="next", <{url}&page=4>; rel="last"'},
)
responses.add(
method=responses.GET,
url=f"{url}&page=3",
json={"text": 200},
headers={"link": f'<{url}&page=4>; rel="next", <{url}&page=4>; rel="last"'},
)
responses.add(
method=responses.GET,
url=f"{url}&page=4",
json={"text": 200},
# To help understanding, the last page only contains the `first` and `prev` links
# The code only cares about the `next` value which is not included here
headers={"link": f'<{url}&page=1>; rel="first", <{url}&page=3>; rel="prev"'},
)
self.github_client._get_with_pagination(f"/repos/{self.repo.name}/assignees")
assert len(responses.calls) == 4
assert responses.calls[0].response.status_code == 200
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_get_with_pagination_only_one_page(self, get_jwt) -> None:
url = f"https://api.github.com/repos/{self.repo.name}/assignees?per_page={self.github_client.page_size}"
# No link in the headers because there are no more pages
responses.add(method=responses.GET, url=url, json={}, headers={})
self.github_client._get_with_pagination(f"/repos/{self.repo.name}/assignees")
assert len(responses.calls) == 1
assert responses.calls[0].response.status_code == 200
@mock.patch(
"sentry.integrations.github.integration.GitHubIntegration.check_file",
return_value=GITHUB_CODEOWNERS["html_url"],
)
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
@responses.activate
def test_get_codeowner_file(self, mock_record, mock_jwt, mock_check_file) -> None:
self.config = self.create_code_mapping(
repo=self.repo,
project=self.project,
)
responses.add(
method=responses.GET,
url=f"https://api.github.com/repos/{self.repo.name}/contents/CODEOWNERS?ref=master",
body="docs/* @NisanthanNanthakumar @getsentry/ecosystem\n* @NisanthanNanthakumar\n",
)
result = self.install.get_codeowner_file(
self.config.repository, ref=self.config.default_branch
)
assert (
responses.calls[0].request.headers["Content-Type"] == "application/raw; charset=utf-8"
)
assert result == GITHUB_CODEOWNERS
assert (
len(mock_record.mock_calls) == 2
) # check_file is mocked in this test, so there will be no metrics logged for it
assert mock_record.mock_calls[0].args[0] == EventLifecycleOutcome.STARTED
assert mock_record.mock_calls[1].args[0] == EventLifecycleOutcome.SUCCESS
@responses.activate
def test_get_cached_repo_files_caching_functionality(self) -> None:
"""Fetch files for repo. Test caching logic."""
responses.add(
method=responses.GET,
url=f"https://api.github.com/repos/{self.repo.name}/git/trees/master?recursive=1",
status=200,
json={"tree": [{"path": "src/foo.py", "type": "blob"}], "truncated": False},
)
repo_key = f"github:repo:{self.repo.name}:source-code"
assert cache.get(repo_key) is None
with mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1"):
files = self.install.get_cached_repo_files(self.repo.name, "master", 0)
assert cache.get(repo_key) == files
# Calling a second time should work
files = self.install.get_cached_repo_files(self.repo.name, "master", 0)
assert cache.get(repo_key) == files
# Calling again after the cache has been cleared should still work
cache.delete(repo_key)
files = self.install.get_cached_repo_files(self.repo.name, "master", 0)
assert cache.get(repo_key) == files
@responses.activate
def test_get_cached_repo_files_with_all_files(self) -> None:
"""Fetch files for repo. All files rather than just source code files"""
responses.add(
method=responses.GET,
url=f"https://api.github.com/repos/{self.repo.name}/git/trees/master?recursive=1",
status=200,
json={
"tree": [
{"type": "blob", "path": "src/foo.py"},
{"type": "blob", "path": "README"},
]
},
)
repo_key = f"github:repo:{self.repo.name}:all"
assert cache.get(repo_key) is None
with mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1"):
files = self.install.get_cached_repo_files(self.repo.name, "master", 0)
assert files == ["src/foo.py"]
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_update_comment(self, get_jwt) -> None:
responses.add(
method=responses.POST,
url=f"https://api.github.com/repos/{self.repo.name}/issues/1/comments",
status=201,
json={
"id": 1,
"node_id": "MDEyOklzc3VlQ29tbWVudDE=",
"url": f"https://api.github.com/repos/{self.repo.name}/issues/comments/1",
"html_url": f"https://github.com/{self.repo.name}/issues/1#issuecomment-1",
"body": "hello",
"created_at": "2023-05-23T17:00:00Z",
"updated_at": "2023-05-23T17:00:00Z",
"issue_url": f"https://api.github.com/repos/{self.repo.name}/issues/1",
"author_association": "COLLABORATOR",
},
)
self.github_client.create_comment(repo=self.repo.name, issue_id="1", data={"body": "hello"})
responses.add(
method=responses.PATCH,
url=f"https://api.github.com/repos/{self.repo.name}/issues/comments/1",
json={
"id": 1,
"node_id": "MDEyOklzc3VlQ29tbWVudDE=",
"url": f"https://api.github.com/repos/{self.repo.name}/issues/comments/1",
"html_url": f"https://github.com/{self.repo.name}/issues/1#issuecomment-1",
"body": "world",
"created_at": "2011-04-14T16:00:49Z",
"updated_at": "2011-04-14T16:00:49Z",
"issue_url": f"https://api.github.com/repos/{self.repo.name}/issues/1",
"author_association": "COLLABORATOR",
},
)
self.github_client.update_comment(
repo=self.repo.name, issue_id="1", comment_id="1", data={"body": "world"}
)
assert responses.calls[1].response.status_code == 200
assert responses.calls[1].request.body == b'{"body": "world"}'
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_update_pr_comment(self, get_jwt) -> None:
responses.add(
method=responses.POST,
url=f"https://api.github.com/repos/{self.repo.name}/issues/1/comments",
status=201,
json={
"id": 1,
"node_id": "MDEyOklzc3VlQ29tbWVudDE=",
"url": f"https://api.github.com/repos/{self.repo.name}/issues/comments/1",
"html_url": f"https://github.com/{self.repo.name}/issues/1#issuecomment-1",
"body": "hello",
"created_at": "2023-05-23T17:00:00Z",
"updated_at": "2023-05-23T17:00:00Z",
"issue_url": f"https://api.github.com/repos/{self.repo.name}/issues/1",
"author_association": "COLLABORATOR",
},
)
self.github_client.create_pr_comment(
repo=self.repo, pr=PullRequest(key="1"), data={"body": "hello"}
)
responses.add(
method=responses.PATCH,
url=f"https://api.github.com/repos/{self.repo.name}/issues/comments/1",
json={
"id": 1,
"node_id": "MDEyOklzc3VlQ29tbWVudDE=",
"url": f"https://api.github.com/repos/{self.repo.name}/issues/comments/1",
"html_url": f"https://github.com/{self.repo.name}/issues/1#issuecomment-1",
"body": "world",
"created_at": "2011-04-14T16:00:49Z",
"updated_at": "2011-04-14T16:00:49Z",
"issue_url": f"https://api.github.com/repos/{self.repo.name}/issues/1",
"author_association": "COLLABORATOR",
},
)
self.github_client.update_pr_comment(
repo=self.repo,
pr=PullRequest(key="1"),
pr_comment=PullRequestComment(external_id="1"),
data={"body": "world"},
)
assert responses.calls[1].response.status_code == 200
assert responses.calls[1].request.body == b'{"body": "world"}'
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_get_comment_reactions(self, get_jwt) -> None:
comment_reactions = {
"reactions": {
"url": "abcdef",
"hooray": 1,
"+1": 2,
"-1": 0,
}
}
responses.add(
responses.GET,
f"https://api.github.com/repos/{self.repo.name}/issues/comments/2",
json=comment_reactions,
)
reactions = self.github_client.get_comment_reactions(repo=self.repo.name, comment_id="2")
stored_reactions = comment_reactions["reactions"]
del stored_reactions["url"]
assert reactions == stored_reactions
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_get_comment_reactions_missing_reactions(self, get_jwt) -> None:
comment_reactions = {"other": "stuff"}
responses.add(
responses.GET,
f"https://api.github.com/repos/{self.repo.name}/issues/comments/2",
json=comment_reactions,
)
reactions = self.github_client.get_comment_reactions(repo=self.repo.name, comment_id="2")
assert reactions == {}
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_get_merge_commit_sha_from_commit(self, get_jwt) -> None:
merge_commit_sha = "jkl123"
pull_requests = [{"merge_commit_sha": merge_commit_sha, "state": "closed"}]
commit_sha = "asdf"
responses.add(
responses.GET,
f"https://api.github.com/repos/{self.repo.name}/commits/{commit_sha}/pulls",
json=pull_requests,
)
sha = self.github_client.get_merge_commit_sha_from_commit(repo=self.repo, sha=commit_sha)
assert sha == merge_commit_sha
@mock.patch("sentry.integrations.github.client.get_jwt", return_value="jwt_token_1")
@responses.activate
def test_get_merge_commit_sha_from_commit_open_pr(self, get_jwt) -> None:
merge_commit_sha = "jkl123"
pull_requests = [{"merge_commit_sha": merge_commit_sha, "state": "open"}]
commit_sha = "asdf"
responses.add(
responses.GET,
f"https://api.github.com/repos/{self.repo.name}/commits/{commit_sha}/pulls",
json=pull_requests,
)
sha = self.github_client.get_merge_commit_sha_from_commit(repo=self.repo, sha=commit_sha)
assert sha is None
@control_silo_test
| GitHubApiClientTest |
python | openai__openai-python | src/openai/types/beta/realtime/input_audio_buffer_committed_event.py | {
"start": 236,
"end": 733
} | class ____(BaseModel):
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the user message item that will be created."""
type: Literal["input_audio_buffer.committed"]
"""The event type, must be `input_audio_buffer.committed`."""
previous_item_id: Optional[str] = None
"""
The ID of the preceding item after which the new item will be inserted. Can be
`null` if the item has no predecessor.
"""
| InputAudioBufferCommittedEvent |
python | kamyu104__LeetCode-Solutions | Python/implement-stack-using-queues.py | {
"start": 77,
"end": 428
} | class ____(object):
def __init__(self):
self.data = collections.deque()
def push(self, x):
self.data.append(x)
def peek(self):
return self.data[0]
def pop(self):
return self.data.popleft()
def size(self):
return len(self.data)
def empty(self):
return len(self.data) == 0
| Queue |
python | celery__celery | t/unit/apps/test_multi.py | {
"start": 727,
"end": 1689
} | class ____:
def test_parse(self):
x = NamespacedOptionParser(['-c:1,3', '4'])
x.parse()
assert x.namespaces.get('1,3') == {'-c': '4'}
x = NamespacedOptionParser(['-c:jerry,elaine', '5',
'--loglevel:kramer=DEBUG',
'--flag',
'--logfile=foo', '-Q', 'bar', 'a', 'b',
'--', '.disable_rate_limits=1'])
x.parse()
assert x.options == {
'--logfile': 'foo',
'-Q': 'bar',
'--flag': None,
}
assert x.values, ['a' == 'b']
assert x.namespaces.get('jerry,elaine') == {'-c': '5'}
assert x.namespaces.get('kramer') == {'--loglevel': 'DEBUG'}
assert x.passthrough == '-- .disable_rate_limits=1'
def multi_args(p, *args, **kwargs):
return MultiParser(*args, **kwargs).parse(p)
| test_NamespacedOptionParser |
python | sympy__sympy | sympy/polys/agca/modules.py | {
"start": 33190,
"end": 33500
} | class ____(ProductOrder):
"""A product monomial order with a zeroth term as module index."""
def __init__(self, o1, o2, TOP):
if TOP:
ProductOrder.__init__(self, (o2, _subs1), (o1, _subs0))
else:
ProductOrder.__init__(self, (o1, _subs0), (o2, _subs1))
| ModuleOrder |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_B.py | {
"start": 13716,
"end": 15035
} | class ____(Benchmark):
r"""
Branin01 objective function.
The Branin01 global optimization problem is a multimodal minimization
problem defined as follows
.. math::
f_{\text{Branin01}}(x) = \left(- 1.275 \frac{x_1^{2}}{\pi^{2}} + 5
\frac{x_1}{\pi} + x_2 -6\right)^{2} + \left(10 -\frac{5}{4 \pi} \right)
\cos\left(x_1\right) + 10
with :math:`x_1 \in [-5, 10], x_2 \in [0, 15]`
*Global optimum*: :math:`f(x) = 0.39788735772973816` for :math:`x =
[-\pi, 12.275]` or :math:`x = [\pi, 2.275]` or :math:`x = [3\pi, 2.475]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO: Jamil#22, one of the solutions is different
"""
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = [(-5., 10.), (0., 15.)]
self.global_optimum = [[-pi, 12.275], [pi, 2.275], [3 * pi, 2.475]]
self.fglob = 0.39788735772973816
def fun(self, x, *args):
self.nfev += 1
return ((x[1] - (5.1 / (4 * pi ** 2)) * x[0] ** 2
+ 5 * x[0] / pi - 6) ** 2
+ 10 * (1 - 1 / (8 * pi)) * cos(x[0]) + 10)
| Branin01 |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_rotation_test.py | {
"start": 189,
"end": 2631
} | class ____(testing.TestCase):
@parameterized.named_parameters(
("random_rotate_neg4", -0.4),
("random_rotate_neg2", -0.2),
("random_rotate_4", 0.4),
("random_rotate_2", 0.2),
("random_rotate_tuple", (-0.2, 0.4)),
)
def test_random_rotation_shapes(self, factor):
self.run_layer_test(
layers.RandomRotation,
init_kwargs={
"factor": factor,
},
input_shape=(2, 3, 4),
expected_output_shape=(2, 3, 4),
supports_masking=False,
run_training_check=False,
)
def test_random_rotation_correctness(self):
if backend.config.image_data_format() == "channels_last":
input_shape = (1, 5, 5, 1)
else:
input_shape = (1, 1, 5, 5)
input_image = np.reshape(np.arange(0, 25), input_shape)
layer = layers.RandomRotation(factor=(0.5, 0.5))
actual_output = layer(input_image)
expected_output = np.asarray(
[
[24, 23, 22, 21, 20],
[19, 18, 17, 16, 15],
[14, 13, 12, 11, 10],
[9, 8, 7, 6, 5],
[4, 3, 2, 1, 0],
]
).reshape(input_shape)
self.assertAllClose(
backend.convert_to_tensor(expected_output), actual_output, atol=1e-5
)
def test_training_false(self):
input_image = np.reshape(np.arange(0, 25), (1, 5, 5, 1))
layer = layers.RandomRotation(factor=(0.5, 0.5))
actual_output = layer(input_image, training=False)
self.assertAllClose(actual_output, input_image)
def test_tf_data_compatibility(self):
if backend.config.image_data_format() == "channels_last":
input_shape = (1, 5, 5, 1)
else:
input_shape = (1, 1, 5, 5)
input_image = np.reshape(np.arange(0, 25), input_shape)
layer = layers.RandomRotation(factor=(0.5, 0.5))
ds = tf_data.Dataset.from_tensor_slices(input_image).map(layer)
expected_output = np.asarray(
[
[24, 23, 22, 21, 20],
[19, 18, 17, 16, 15],
[14, 13, 12, 11, 10],
[9, 8, 7, 6, 5],
[4, 3, 2, 1, 0],
]
).reshape(input_shape[1:])
output = next(iter(ds)).numpy()
self.assertAllClose(expected_output, output)
| RandomRotationTest |
python | xlwings__xlwings | xlwings/pro/_xlremote.py | {
"start": 7253,
"end": 8996
} | class ____(base_classes.Book):
def __init__(self, api, books):
self.books = books
self._api = api
self._json = {"actions": []}
if api["version"] != __version__ and api["client"] != "Office.js":
raise XlwingsError(
f"Your xlwings version is different on the client ({api['version']}) "
f"and server ({__version__})."
)
def append_json_action(self, **kwargs):
args = kwargs.get("args")
self._json["actions"].append(
{
"func": kwargs.get("func"),
"args": [args] if not isinstance(args, list) else args,
"values": kwargs.get("values"),
"sheet_position": kwargs.get("sheet_position"),
"start_row": kwargs.get("start_row"),
"start_column": kwargs.get("start_column"),
"row_count": kwargs.get("row_count"),
"column_count": kwargs.get("column_count"),
}
)
@property
def api(self):
return self._api
def json(self):
return self._json
@property
def name(self):
return self.api["book"]["name"]
@property
def fullname(self):
return self.name
@property
def names(self):
return Names(parent=self, api=self.api["names"])
@property
def sheets(self):
return Sheets(api=self.api["sheets"], book=self)
@property
def app(self):
return self.books.app
def close(self):
assert self.api is not None, "Seems this book was already closed."
self.books.books.remove(self)
self.books = None
self._api = None
def activate(self):
pass
| Book |
python | spack__spack | lib/spack/spack/oci/opener.py | {
"start": 7342,
"end": 15615
} | class ____(urllib.request.BaseHandler):
def __init__(self, credentials_provider: Callable[[str], Optional[UsernamePassword]]):
"""
Args:
credentials_provider: A function that takes a domain and may return a UsernamePassword.
"""
self.credentials_provider = credentials_provider
# Cached authorization headers for a given domain.
self.cached_auth_headers: Dict[str, str] = {}
def https_request(self, req: Request):
# Eagerly add the bearer token to the request if no
# auth header is set yet, to avoid 401s in multiple
# requests to the same registry.
# Use has_header, not .headers, since there are two
# types of headers (redirected and unredirected)
if req.has_header("Authorization"):
return req
parsed = urllib.parse.urlparse(req.full_url)
auth_header = self.cached_auth_headers.get(parsed.netloc)
if not auth_header:
return req
req.add_unredirected_header("Authorization", auth_header)
return req
def _try_bearer_challenge(
self,
challenges: List[Challenge],
credentials: Optional[UsernamePassword],
timeout: Optional[float],
) -> Optional[str]:
# Check whether a Bearer challenge is present in the WWW-Authenticate header
challenge = _get_bearer_challenge(challenges)
if not challenge:
return None
# Get the token from the auth handler
query = urllib.parse.urlencode(
{"service": challenge.service, "scope": challenge.scope, "client_id": "spack"}
)
parsed = urllib.parse.urlparse(challenge.realm)._replace(
query=query, fragment="", params=""
)
# Don't send credentials over insecure transport.
if parsed.scheme != "https":
raise ValueError(f"Cannot login over insecure {parsed.scheme} connection")
request = Request(urllib.parse.urlunparse(parsed), method="GET")
if credentials is not None:
request.add_unredirected_header("Authorization", credentials.basic_auth_header)
# Do a GET request.
response = self.parent.open(request, timeout=timeout)
try:
response_json = json.load(response)
token = response_json.get("token")
if token is None:
token = response_json.get("access_token")
assert type(token) is str
except Exception as e:
raise ValueError(f"Malformed token response from {challenge.realm}") from e
return f"Bearer {token}"
def _try_basic_challenge(
self, challenges: List[Challenge], credentials: UsernamePassword
) -> Optional[str]:
# Check whether a Basic challenge is present in the WWW-Authenticate header
# A realm is required for Basic auth, although we don't use it here. Leave this as a
# validation step.
realm = _get_basic_challenge(challenges)
if not realm:
return None
return credentials.basic_auth_header
def http_error_401(self, req: Request, fp, code, msg, headers):
# Login failed, avoid infinite recursion where we go back and
# forth between auth server and registry
if hasattr(req, "login_attempted"):
raise spack.util.web.DetailedHTTPError(
req, code, f"Failed to login: {msg}", headers, fp
)
# On 401 Unauthorized, parse the WWW-Authenticate header
# to determine what authentication is required
if "WWW-Authenticate" not in headers:
raise spack.util.web.DetailedHTTPError(
req, code, "Cannot login to registry, missing WWW-Authenticate header", headers, fp
)
www_auth_str = headers["WWW-Authenticate"]
try:
challenges = parse_www_authenticate(www_auth_str)
except ValueError as e:
raise spack.util.web.DetailedHTTPError(
req,
code,
f"Cannot login to registry, malformed WWW-Authenticate header: {www_auth_str}",
headers,
fp,
) from e
registry = urllib.parse.urlparse(req.get_full_url()).netloc
credentials = self.credentials_provider(registry)
# First try Bearer, then Basic
try:
auth_header = self._try_bearer_challenge(challenges, credentials, req.timeout)
if not auth_header and credentials:
auth_header = self._try_basic_challenge(challenges, credentials)
except Exception as e:
raise spack.util.web.DetailedHTTPError(
req, code, f"Cannot login to registry: {e}", headers, fp
) from e
if not auth_header:
raise spack.util.web.DetailedHTTPError(
req,
code,
f"Cannot login to registry, unsupported authentication scheme: {www_auth_str}",
headers,
fp,
)
self.cached_auth_headers[registry] = auth_header
# Add the authorization header to the request
req.add_unredirected_header("Authorization", auth_header)
setattr(req, "login_attempted", True)
return self.parent.open(req, timeout=req.timeout)
def credentials_from_mirrors(
domain: str, *, mirrors: Optional[Iterable[spack.mirrors.mirror.Mirror]] = None
) -> Optional[UsernamePassword]:
"""Filter out OCI registry credentials from a list of mirrors."""
mirrors = mirrors or spack.mirrors.mirror.MirrorCollection().values()
for mirror in mirrors:
# Prefer push credentials over fetch. Unlikely that those are different
# but our config format allows it.
for direction in ("push", "fetch"):
pair = mirror.get_credentials(direction).get("access_pair")
if not pair:
continue
url = mirror.get_url(direction)
try:
parsed = ImageReference.from_url(url)
except ValueError:
continue
if parsed.domain == domain:
return UsernamePassword(*pair)
return None
def create_opener():
"""Create an opener that can handle OCI authentication."""
opener = urllib.request.OpenerDirector()
for handler in [
urllib.request.ProxyHandler(),
urllib.request.UnknownHandler(),
urllib.request.HTTPHandler(),
spack.util.web.SpackHTTPSHandler(context=spack.util.web.ssl_create_default_context()),
spack.util.web.SpackHTTPDefaultErrorHandler(),
urllib.request.HTTPRedirectHandler(),
urllib.request.HTTPErrorProcessor(),
OCIAuthHandler(credentials_from_mirrors),
]:
opener.add_handler(handler)
return opener
def ensure_status(request: urllib.request.Request, response: HTTPResponse, status: int):
"""Raise an error if the response status is not the expected one."""
if response.status == status:
return
raise spack.util.web.DetailedHTTPError(
request, response.status, response.reason, response.info(), None
)
def default_retry(f, retries: int = 5, sleep=None):
sleep = sleep or time.sleep
def wrapper(*args, **kwargs):
for i in range(retries):
try:
return f(*args, **kwargs)
except OSError as e:
# Retry on internal server errors, and rate limit errors
# Potentially this could take into account the Retry-After header
# if registries support it
if i + 1 != retries and (
(
isinstance(e, urllib.error.HTTPError)
and (500 <= e.code < 600 or e.code == 429)
)
or (
isinstance(e, urllib.error.URLError)
and isinstance(e.reason, socket.timeout)
)
or isinstance(e, socket.timeout)
):
# Exponential backoff
sleep(2**i)
continue
raise
return wrapper
| OCIAuthHandler |
python | pypa__pipenv | pipenv/patched/pip/_internal/index/sources.py | {
"start": 2974,
"end": 4295
} | class ____(LinkSource):
"""Link source specified by ``--find-links=<path-to-dir>``.
This looks the content of the directory, and returns:
* ``page_candidates``: Links listed on each HTML file in the directory.
* ``file_candidates``: Archives in the directory.
"""
_paths_to_urls: Dict[str, _FlatDirectoryToUrls] = {}
def __init__(
self,
candidates_from_page: CandidatesFromPage,
path: str,
project_name: str,
) -> None:
self._candidates_from_page = candidates_from_page
self._project_name = canonicalize_name(project_name)
# Get existing instance of _FlatDirectoryToUrls if it exists
if path in self._paths_to_urls:
self._path_to_urls = self._paths_to_urls[path]
else:
self._path_to_urls = _FlatDirectoryToUrls(path=path)
self._paths_to_urls[path] = self._path_to_urls
@property
def link(self) -> Optional[Link]:
return None
def page_candidates(self) -> FoundCandidates:
for url in self._path_to_urls.page_candidates:
yield from self._candidates_from_page(Link(url))
def file_links(self) -> FoundLinks:
for url in self._path_to_urls.project_name_to_urls[self._project_name]:
yield Link(url)
| _FlatDirectorySource |
python | rapidsai__cudf | python/cudf/cudf/core/window/rolling.py | {
"start": 1729,
"end": 18178
} | class ____(GetAttrGetItemMixin, _RollingBase, Reducible):
"""
Rolling window calculations.
Parameters
----------
window : int, offset or a BaseIndexer subclass
Size of the window, i.e., the number of observations used
to calculate the statistic.
For datetime indexes, an offset can be provided instead
of an int. The offset must be convertible to a timedelta.
As opposed to a fixed window size, each window will be
sized to accommodate observations within the time period
specified by the offset.
If a BaseIndexer subclass is passed, calculates the window
boundaries based on the defined ``get_window_bounds`` method.
min_periods : int, optional
The minimum number of observations in the window that are
required to be non-null, so that the result is non-null.
If not provided or ``None``, ``min_periods`` is equal to
the window size.
center : bool, optional
If ``True``, the result is set at the center of the window.
If ``False`` (default), the result is set at the right edge
of the window.
Returns
-------
``Rolling`` object.
Examples
--------
>>> import cudf
>>> a = cudf.Series([1, 2, 3, None, 4])
Rolling sum with window size 2.
>>> print(a.rolling(2).sum())
0
1 3
2 5
3
4
dtype: int64
Rolling sum with window size 2 and min_periods 1.
>>> print(a.rolling(2, min_periods=1).sum())
0 1
1 3
2 5
3 3
4 4
dtype: int64
Rolling count with window size 3.
>>> print(a.rolling(3).count())
0 1
1 2
2 3
3 2
4 2
dtype: int64
Rolling count with window size 3, but with the result set at the
center of the window.
>>> print(a.rolling(3, center=True).count())
0 2
1 3
2 2
3 2
4 1 dtype: int64
Rolling max with variable window size specified by an offset;
only valid for datetime index.
>>> a = cudf.Series(
... [1, 9, 5, 4, np.nan, 1],
... index=[
... pd.Timestamp('20190101 09:00:00'),
... pd.Timestamp('20190101 09:00:01'),
... pd.Timestamp('20190101 09:00:02'),
... pd.Timestamp('20190101 09:00:04'),
... pd.Timestamp('20190101 09:00:07'),
... pd.Timestamp('20190101 09:00:08')
... ]
... )
>>> print(a.rolling('2s').max())
2019-01-01T09:00:00.000 1
2019-01-01T09:00:01.000 9
2019-01-01T09:00:02.000 9
2019-01-01T09:00:04.000 4
2019-01-01T09:00:07.000
2019-01-01T09:00:08.000 1
dtype: int64
Apply custom function on the window with the *apply* method
>>> import numpy as np
>>> import math
>>> b = cudf.Series([16, 25, 36, 49, 64, 81], dtype=np.float64)
>>> def some_func(A):
... b = 0
... for a in A:
... b = b + math.sqrt(a)
... return b
...
>>> print(b.rolling(3, min_periods=1).apply(some_func))
0 4.0
1 9.0
2 15.0
3 18.0
4 21.0
5 24.0
dtype: float64
And this also works for window rolling set by an offset
>>> import pandas as pd
>>> c = cudf.Series(
... [16, 25, 36, 49, 64, 81],
... index=[
... pd.Timestamp('20190101 09:00:00'),
... pd.Timestamp('20190101 09:00:01'),
... pd.Timestamp('20190101 09:00:02'),
... pd.Timestamp('20190101 09:00:04'),
... pd.Timestamp('20190101 09:00:07'),
... pd.Timestamp('20190101 09:00:08')
... ],
... dtype=np.float64
... )
>>> print(c.rolling('2s').apply(some_func))
2019-01-01T09:00:00.000 4.0
2019-01-01T09:00:01.000 9.0
2019-01-01T09:00:02.000 11.0
2019-01-01T09:00:04.000 7.0
2019-01-01T09:00:07.000 8.0
2019-01-01T09:00:08.000 17.0
dtype: float64
"""
_PROTECTED_KEYS = frozenset(("obj",))
_group_keys: Index | None = None
_VALID_REDUCTIONS = {
"sum",
"min",
"max",
"mean",
"var",
"std",
}
def __init__(
self,
obj: DataFrame | Series,
window,
min_periods=None,
center: bool = False,
win_type: str | None = None,
on=None,
axis=0,
closed: str | None = None,
step: int | None = None,
method: str = "single",
) -> None:
if not isinstance(center, bool):
raise ValueError("center must be a boolean")
self.center = center
if axis != 0:
warnings.warn(
"axis is deprecated with will be removed in a future version. "
"Transpose the DataFrame first instead."
)
raise NotImplementedError("axis != 0 is not supported yet.")
self.axis = axis
if win_type is not None:
if win_type != "boxcar":
raise NotImplementedError(
"Only the default win_type 'boxcar' is currently supported"
)
self.win_type = win_type
if on is not None:
raise NotImplementedError("on is currently not supported")
if closed not in (None, "right"):
raise NotImplementedError("closed is currently not supported")
if step is not None:
raise NotImplementedError("step is currently not supported")
if method != "single":
raise NotImplementedError("method is currently not supported")
if get_option("mode.pandas_compatible"):
obj = obj.nans_to_nulls()
self.obj = obj
self.window, self.min_periods = self._normalize_window_and_min_periods(
window, min_periods
)
def __getitem__(self, arg) -> Self:
if isinstance(arg, tuple):
arg = list(arg)
return self.obj[arg].rolling(
window=self.window,
min_periods=self.min_periods,
center=self.center,
)
@functools.cached_property
def _plc_windows(self) -> WindowTypePair:
"""
Return the preceding and following windows to pass into
pylibcudf.rolling.rolling_window
"""
if isinstance(self.window, (int, pd.Timedelta)):
if isinstance(self.window, pd.Timedelta):
if self.center:
raise NotImplementedError(
"center is not implemented for frequency-based windows"
)
pre = self.window.value
fwd = 0
orderby_obj = self.obj.index._column.astype(np.dtype(np.int64))
else:
if self.center:
pre = (self.window // 2) + 1
fwd = self.window - pre
else:
pre = self.window
fwd = 0
if self._group_keys is None:
# If we're doing ungrouped rolling window with
# integer offsets, no need to create
# preceding/following columns.
return pre, fwd
# TODO: Expose cudf::grouped_rolling_window and use
# that instead (perhaps), or implement an equivalent
# to make_range_windows that takes integer window
# bounds and group keys.
orderby_obj = as_column(range(len(self.obj)))
if self._group_keys is not None:
group_cols: list[plc.Column] = [
col.plc_column for col in self._group_keys._columns
]
else:
group_cols = []
group_keys = plc.Table(group_cols)
return plc.rolling.make_range_windows(
group_keys,
orderby_obj.plc_column,
plc.types.Order.ASCENDING,
plc.types.NullOrder.BEFORE,
plc.rolling.BoundedOpen(plc.Scalar.from_py(pre)),
plc.rolling.BoundedClosed(plc.Scalar.from_py(fwd)),
)
elif isinstance(self.window, BaseIndexer):
start, end = self.window.get_window_bounds(
num_values=len(self.obj),
min_periods=self.min_periods,
center=self.center,
closed=None,
step=None,
)
start = as_column(start, dtype=SIZE_TYPE_DTYPE)
end = as_column(end, dtype=SIZE_TYPE_DTYPE)
idx = as_column(range(len(start)))
preceding_window = (idx - start + np.int32(1)).astype(
SIZE_TYPE_DTYPE
)
following_window = (end - idx - np.int32(1)).astype(
SIZE_TYPE_DTYPE
)
return (
preceding_window.plc_column,
following_window.plc_column,
)
else:
raise ValueError(
"self.window should have been an int, BaseIndexer, or a pandas.Timedelta "
f"not {type(self.window).__name__}"
)
def _apply_agg_column(
self, source_column: ColumnBase, agg_name: str | Callable, **agg_kwargs
) -> ColumnBase:
pre, fwd = self._plc_windows
rolling_agg = aggregation.make_aggregation(
agg_name,
{
"dtype": np.dtype("float64")
if get_option("mode.pandas_compatible")
else source_column.dtype
}
if callable(agg_name)
else agg_kwargs,
).plc_obj
with acquire_spill_lock():
col = ColumnBase.from_pylibcudf(
plc.rolling.rolling_window(
source_column.plc_column,
pre,
fwd,
self.min_periods or 1,
rolling_agg,
)
)
if isinstance(agg_name, str) and get_option("mode.pandas_compatible"):
return col.astype(np.dtype("float64"))
return col
def _reduce(
self,
op: str,
*args,
**kwargs,
) -> DataFrame | Series:
"""Calculate the rolling {op}.
Returns
-------
Series or DataFrame
Return type is the same as the original object.
"""
return self._apply_agg(op)
def var(self, ddof: int = 1) -> DataFrame | Series:
"""Calculate the rolling variance.
Parameters
----------
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of
elements.
Returns
-------
Series or DataFrame
Return type is the same as the original object.
"""
return self._apply_agg("var", ddof=ddof)
def std(self, ddof: int = 1) -> DataFrame | Series:
"""Calculate the rolling standard deviation.
Parameters
----------
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of
elements.
Returns
-------
Series or DataFrame
Return type is the same as the original object.
"""
return self._apply_agg("std", ddof=ddof)
def count(self) -> DataFrame | Series:
"""Calculate the rolling count of non NaN observations.
Returns
-------
Series or DataFrame
Return type is the same as the original object.
"""
return self._apply_agg("count")
def median(self, **kwargs):
raise NotImplementedError(
"groupby().rolling().median() is not yet implemented"
)
def apply(self, func, *args, **kwargs) -> DataFrame | Series:
"""
Calculate the rolling custom aggregation function.
Parameters
----------
func : function
A user defined function that takes an 1D array as input
args : tuple
unsupported.
kwargs
unsupported
See Also
--------
cudf.Series.apply: Apply an elementwise function to
transform the values in the Column.
Notes
-----
The supported Python features are listed in
https://numba.readthedocs.io/en/stable/cuda/cudapysupported.html
with these exceptions:
* Math functions in `cmath` are not supported since `libcudf` does not
have complex number support and output of `cmath` functions are most
likely complex numbers.
* These five functions in `math` are not supported since numba
generates multiple PTX functions from them:
* math.sin()
* math.cos()
* math.tan()
* math.gamma()
* math.lgamma()
* Series with string dtypes are not supported.
* Global variables need to be re-defined explicitly inside
the udf, as numba considers them to be compile-time constants
and there is no known way to obtain value of the global variable.
Examples
--------
>>> import cudf
>>> def count_if_gt_3(window):
... count = 0
... for i in window:
... if i > 3:
... count += 1
... return count
...
>>> s = cudf.Series([0, 1.1, 5.8, 3.1, 6.2, 2.0, 1.5])
>>> s.rolling(3, min_periods=1).apply(count_if_gt_3)
0 0
1 0
2 1
3 2
4 3
5 2
6 1
dtype: int64
"""
if any(col.has_nulls() for col in self.obj._columns):
raise NotImplementedError(
"Handling UDF with null values is not yet supported"
)
return self._apply_agg(func)
def aggregate(self, func, *args, **kwargs) -> DataFrame | Series:
raise NotImplementedError("rolling.aggregate() is not yet implemented")
# agg is an alias for aggregate
agg = aggregate
def _normalize_window_and_min_periods(
self, window, min_periods
) -> tuple[int | pd.Timedelta | BaseIndexer, int | None]:
"""
Normalize the *window* and *min_periods* args
*window* can be:
* An integer, in which case it is the window size.
If *min_periods* is unspecified, it is set to be equal to
the window size.
* A timedelta offset, in which case it is used to generate
a column of window sizes to use for each element.
If *min_periods* is unspecified, it is set to 1.
Only valid for datetime index.
"""
if is_number(window):
# only allow integers
if not is_integer(window):
raise ValueError("window must be an integer")
if window <= 0:
raise ValueError("window cannot be zero or negative")
if min_periods is None:
return window, window
elif not is_integer(min_periods):
raise ValueError("min_periods must be an integer")
else:
return window, min_periods
elif isinstance(window, BaseIndexer):
return window, min_periods
elif is_scalar(window):
try:
window = pd.to_timedelta(window)
except ValueError as e:
raise ValueError(
"window must be integer, BaseIndexer, or convertible to a timedelta"
) from e
if self.obj.index.dtype.kind != "M":
raise ValueError(
"index must be a DatetimeIndex for a frequency-based window"
)
if min_periods is None:
return window, 1
else:
return window, min_periods
else:
raise ValueError(
"window must be integer, BaseIndexer, or convertible to a timedelta"
)
def __repr__(self) -> str:
return f"{type(self).__name__} [window={self.window},min_periods={self.min_periods},center={self.center}]"
| Rolling |
python | django__django | tests/get_earliest_or_latest/models.py | {
"start": 401,
"end": 628
} | class ____(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE)
likes_count = models.PositiveIntegerField()
# Ticket #23555 - model with an intentionally broken QuerySet.__iter__ method.
| Comment |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/stateful.py | {
"start": 37696,
"end": 40411
} | class ____:
name: str
# There are multiple alternatives for annotating the `precond` type, all of them
# have drawbacks. See https://github.com/HypothesisWorks/hypothesis/pull/3068#issuecomment-906642371
def precondition(precond: Callable[[Any], bool]) -> Callable[[TestFunc], TestFunc]:
"""Decorator to apply a precondition for rules in a RuleBasedStateMachine.
Specifies a precondition for a rule to be considered as a valid step in the
state machine, which is more efficient than using :func:`~hypothesis.assume`
within the rule. The ``precond`` function will be called with the instance of
RuleBasedStateMachine and should return True or False. Usually it will need
to look at attributes on that instance.
For example::
class MyTestMachine(RuleBasedStateMachine):
state = 1
@precondition(lambda self: self.state != 0)
@rule(numerator=integers())
def divide_with(self, numerator):
self.state = numerator / self.state
If multiple preconditions are applied to a single rule, it is only considered
a valid step when all of them return True. Preconditions may be applied to
invariants as well as rules.
"""
def decorator(f):
@proxies(f)
def precondition_wrapper(*args, **kwargs):
return f(*args, **kwargs)
existing_initialize_rule = getattr(f, INITIALIZE_RULE_MARKER, None)
if existing_initialize_rule is not None:
raise InvalidDefinition(
f"{_rule_qualname(f)} has been decorated with both @initialize and "
"@precondition, which is not allowed. An initialization rule "
"runs unconditionally and may not have a precondition."
)
rule = getattr(f, RULE_MARKER, None)
invariant = getattr(f, INVARIANT_MARKER, None)
if rule is not None:
assert invariant is None
new_rule = dataclasses.replace(
rule, preconditions=(*rule.preconditions, precond)
)
setattr(precondition_wrapper, RULE_MARKER, new_rule)
elif invariant is not None:
assert rule is None
new_invariant = dataclasses.replace(
invariant, preconditions=(*invariant.preconditions, precond)
)
setattr(precondition_wrapper, INVARIANT_MARKER, new_invariant)
else:
setattr(
precondition_wrapper,
PRECONDITIONS_MARKER,
(*getattr(f, PRECONDITIONS_MARKER, ()), precond),
)
return precondition_wrapper
return decorator
@dataclass(slots=True, frozen=True)
| VarReference |
python | encode__starlette | starlette/routing.py | {
"start": 7076,
"end": 11030
} | class ____(BaseRoute):
def __init__(
self,
path: str,
endpoint: Callable[..., Any],
*,
methods: Collection[str] | None = None,
name: str | None = None,
include_in_schema: bool = True,
middleware: Sequence[Middleware] | None = None,
) -> None:
assert path.startswith("/"), "Routed paths must start with '/'"
self.path = path
self.endpoint = endpoint
self.name = get_name(endpoint) if name is None else name
self.include_in_schema = include_in_schema
endpoint_handler = endpoint
while isinstance(endpoint_handler, functools.partial):
endpoint_handler = endpoint_handler.func
if inspect.isfunction(endpoint_handler) or inspect.ismethod(endpoint_handler):
# Endpoint is function or method. Treat it as `func(request) -> response`.
self.app = request_response(endpoint)
if methods is None:
methods = ["GET"]
else:
# Endpoint is a class. Treat it as ASGI.
self.app = endpoint
if middleware is not None:
for cls, args, kwargs in reversed(middleware):
self.app = cls(self.app, *args, **kwargs)
if methods is None:
self.methods = None
else:
self.methods = {method.upper() for method in methods}
if "GET" in self.methods:
self.methods.add("HEAD")
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
def matches(self, scope: Scope) -> tuple[Match, Scope]:
path_params: dict[str, Any]
if scope["type"] == "http":
route_path = get_route_path(scope)
match = self.path_regex.match(route_path)
if match:
matched_params = match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
path_params.update(matched_params)
child_scope = {"endpoint": self.endpoint, "path_params": path_params}
if self.methods and scope["method"] not in self.methods:
return Match.PARTIAL, child_scope
else:
return Match.FULL, child_scope
return Match.NONE, {}
def url_path_for(self, name: str, /, **path_params: Any) -> URLPath:
seen_params = set(path_params.keys())
expected_params = set(self.param_convertors.keys())
if name != self.name or seen_params != expected_params:
raise NoMatchFound(name, path_params)
path, remaining_params = replace_params(self.path_format, self.param_convertors, path_params)
assert not remaining_params
return URLPath(path=path, protocol="http")
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
if self.methods and scope["method"] not in self.methods:
headers = {"Allow": ", ".join(self.methods)}
if "app" in scope:
raise HTTPException(status_code=405, headers=headers)
else:
response = PlainTextResponse("Method Not Allowed", status_code=405, headers=headers)
await response(scope, receive, send)
else:
await self.app(scope, receive, send)
def __eq__(self, other: Any) -> bool:
return (
isinstance(other, Route)
and self.path == other.path
and self.endpoint == other.endpoint
and self.methods == other.methods
)
def __repr__(self) -> str:
class_name = self.__class__.__name__
methods = sorted(self.methods or [])
path, name = self.path, self.name
return f"{class_name}(path={path!r}, name={name!r}, methods={methods!r})"
| Route |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/schema.py | {
"start": 204933,
"end": 205645
} | class ____(TypedDict, total=False):
fk: _NamingSchemaDirective
pk: _NamingSchemaDirective
ix: _NamingSchemaDirective
ck: _NamingSchemaDirective
uq: _NamingSchemaDirective
_NamingSchemaParameter = Union[
# it seems like the TypedDict here is useful for pylance typeahead,
# and not much else
_NamingSchemaTD,
# there is no form that allows Union[Type[Any], str] to work in all
# cases, including breaking out Mapping[] entries for each combination
# even, therefore keys must be `Any` (see #10264)
Mapping[Any, _NamingSchemaDirective],
]
DEFAULT_NAMING_CONVENTION: _NamingSchemaParameter = util.immutabledict(
{"ix": "ix_%(column_0_label)s"}
)
| _NamingSchemaTD |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 3446,
"end": 4479
} | class ____(ActionBaseModel):
active: Optional[bool] = Field(
default=None, description="Whether or not the schedule is active."
)
schedule: Optional[schemas.schedules.SCHEDULE_TYPES] = Field(
default=None, description="The schedule for the deployment."
)
max_scheduled_runs: Optional[PositiveInteger] = Field(
default=None,
description="The maximum number of scheduled runs for the schedule.",
)
parameters: dict[str, Any] = Field(
default_factory=dict, description="A dictionary of parameter value overrides."
)
slug: Optional[str] = Field(
default=None,
description="A unique identifier for the schedule.",
)
@field_validator("max_scheduled_runs")
@classmethod
def validate_max_scheduled_runs(
cls, v: PositiveInteger | None
) -> PositiveInteger | None:
return validate_schedule_max_scheduled_runs(
v, PREFECT_DEPLOYMENT_SCHEDULE_MAX_SCHEDULED_RUNS.value()
)
| DeploymentScheduleUpdate |
python | pypa__pip | src/pip/_vendor/rich/live_render.py | {
"start": 340,
"end": 3521
} | class ____:
"""Creates a renderable that may be updated.
Args:
renderable (RenderableType): Any renderable object.
style (StyleType, optional): An optional style to apply to the renderable. Defaults to "".
"""
def __init__(
self,
renderable: RenderableType,
style: StyleType = "",
vertical_overflow: VerticalOverflowMethod = "ellipsis",
) -> None:
self.renderable = renderable
self.style = style
self.vertical_overflow = vertical_overflow
self._shape: Optional[Tuple[int, int]] = None
def set_renderable(self, renderable: RenderableType) -> None:
"""Set a new renderable.
Args:
renderable (RenderableType): Any renderable object, including str.
"""
self.renderable = renderable
def position_cursor(self) -> Control:
"""Get control codes to move cursor to beginning of live render.
Returns:
Control: A control instance that may be printed.
"""
if self._shape is not None:
_, height = self._shape
return Control(
ControlType.CARRIAGE_RETURN,
(ControlType.ERASE_IN_LINE, 2),
*(
(
(ControlType.CURSOR_UP, 1),
(ControlType.ERASE_IN_LINE, 2),
)
* (height - 1)
)
)
return Control()
def restore_cursor(self) -> Control:
"""Get control codes to clear the render and restore the cursor to its previous position.
Returns:
Control: A Control instance that may be printed.
"""
if self._shape is not None:
_, height = self._shape
return Control(
ControlType.CARRIAGE_RETURN,
*((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height
)
return Control()
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
renderable = self.renderable
style = console.get_style(self.style)
lines = console.render_lines(renderable, options, style=style, pad=False)
shape = Segment.get_shape(lines)
_, height = shape
if height > options.size.height:
if self.vertical_overflow == "crop":
lines = lines[: options.size.height]
shape = Segment.get_shape(lines)
elif self.vertical_overflow == "ellipsis":
lines = lines[: (options.size.height - 1)]
overflow_text = Text(
"...",
overflow="crop",
justify="center",
end="",
style="live.ellipsis",
)
lines.append(list(console.render(overflow_text)))
shape = Segment.get_shape(lines)
self._shape = shape
new_line = Segment.line()
for last, line in loop_last(lines):
yield from line
if not last:
yield new_line
| LiveRender |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_vectors.py | {
"start": 732,
"end": 2554
} | class ____(ColumnMapMetricProvider):
VECTOR_REGEX = r"\[\d+\.*\d*,\s*\d+\.*\d*(,\s*\d+\.*\d*)*]"
# This is the id string that will be used to reference your metric.
# Please see https://docs.greatexpectations.io/en/latest/reference/core_concepts/metrics.html#metrics
# for information on how to choose an id string for your Metric.
condition_metric_name = "column_values.is_vector"
# This method defines the business logic for evaluating your metric when using a PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
def matches_vector(x):
"""Checks if the row is a list containing only numbers with length
greater than 1. If a string uses regular expression to check
Returns true for such rows"""
if isinstance(x, str) and re.match(ColumnValuesIsVector.VECTOR_REGEX, str(x)):
return True
elif isinstance(x, list) and len(x) > 1:
return all(isinstance(listobject, (int, float)) for listobject in x)
else:
return False
return column.apply(lambda x: matches_vector(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# return column.in_([3])
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# return column.isin([3])
# This class defines the Expectation itself
# The main business logic for calculation lives here.
| ColumnValuesIsVector |
python | pandas-dev__pandas | pandas/tests/window/test_numba.py | {
"start": 9731,
"end": 13805
} | class ____:
@pytest.mark.parametrize(
"grouper", [lambda x: x, lambda x: x.groupby("A")], ids=["None", "groupby"]
)
@pytest.mark.parametrize("method", ["mean", "sum"])
def test_invalid_engine(self, grouper, method):
df = DataFrame({"A": ["a", "b", "a", "b"], "B": range(4)})
with pytest.raises(ValueError, match="engine must be either"):
getattr(grouper(df).ewm(com=1.0), method)(engine="foo")
@pytest.mark.parametrize(
"grouper", [lambda x: x, lambda x: x.groupby("A")], ids=["None", "groupby"]
)
@pytest.mark.parametrize("method", ["mean", "sum"])
def test_invalid_engine_kwargs(self, grouper, method):
df = DataFrame({"A": ["a", "b", "a", "b"], "B": range(4)})
with pytest.raises(ValueError, match="cython engine does not"):
getattr(grouper(df).ewm(com=1.0), method)(
engine="cython", engine_kwargs={"nopython": True}
)
@pytest.mark.parametrize("grouper", ["None", "groupby"])
@pytest.mark.parametrize("method", ["mean", "sum"])
def test_cython_vs_numba(
self, grouper, method, nogil, parallel, nopython, ignore_na, adjust
):
df = DataFrame({"B": range(4)})
if grouper == "None":
grouper = lambda x: x
else:
df["A"] = ["a", "b", "a", "b"]
grouper = lambda x: x.groupby("A")
if method == "sum":
adjust = True
ewm = grouper(df).ewm(com=1.0, adjust=adjust, ignore_na=ignore_na)
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
result = getattr(ewm, method)(engine="numba", engine_kwargs=engine_kwargs)
expected = getattr(ewm, method)(engine="cython")
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("grouper", ["None", "groupby"])
def test_cython_vs_numba_times(self, grouper, nogil, parallel, nopython, ignore_na):
# GH 40951
df = DataFrame({"B": [0, 0, 1, 1, 2, 2]})
if grouper == "None":
grouper = lambda x: x
else:
grouper = lambda x: x.groupby("A")
df["A"] = ["a", "b", "a", "b", "b", "a"]
halflife = "23 days"
times = to_datetime(
[
"2020-01-01",
"2020-01-01",
"2020-01-02",
"2020-01-10",
"2020-02-23",
"2020-01-03",
]
)
ewm = grouper(df).ewm(
halflife=halflife, adjust=True, ignore_na=ignore_na, times=times
)
engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
result = ewm.mean(engine="numba", engine_kwargs=engine_kwargs)
expected = ewm.mean(engine="cython")
tm.assert_frame_equal(result, expected)
@td.skip_if_no("numba")
def test_use_global_config():
def f(x):
return np.mean(x) + 2
s = Series(range(10))
with option_context("compute.use_numba", True):
result = s.rolling(2).apply(f, engine=None, raw=True)
expected = s.rolling(2).apply(f, engine="numba", raw=True)
tm.assert_series_equal(expected, result)
@td.skip_if_no("numba")
def test_invalid_kwargs_nopython():
with pytest.raises(TypeError, match="got an unexpected keyword argument 'a'"):
Series(range(1)).rolling(1).apply(
lambda x: x, kwargs={"a": 1}, engine="numba", raw=True
)
with pytest.raises(
NumbaUtilError, match="numba does not support keyword-only arguments"
):
Series(range(1)).rolling(1).apply(
lambda x, *, a: x, kwargs={"a": 1}, engine="numba", raw=True
)
tm.assert_series_equal(
Series(range(1), dtype=float) + 1,
Series(range(1))
.rolling(1)
.apply(lambda x, a: (x + a).sum(), kwargs={"a": 1}, engine="numba", raw=True),
)
@td.skip_if_no("numba")
@pytest.mark.slow
@pytest.mark.filterwarnings("ignore")
# Filter warnings when parallel=True and the function can't be parallelized by Numba
| TestEWM |
python | langchain-ai__langchain | libs/core/langchain_core/language_models/fake.py | {
"start": 2057,
"end": 2137
} | class ____(Exception):
"""Fake error for testing purposes."""
| FakeListLLMError |
python | facebook__pyre-check | client/commands/tests/statistics_test.py | {
"start": 18721,
"end": 22630
} | class ____(testslide.TestCase):
def test_collect_statistics(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root)
setup.ensure_files_exist(root_path, ["foo.py", "bar.py"])
foo_path = root_path / "foo.py"
bar_path = root_path / "bar.py"
data = statistics.collect_statistics(
[foo_path, bar_path], strict_default=False
)
self.assertIn(str(foo_path), data)
self.assertIn(str(bar_path), data)
def test_aggregate_statistics__single_file(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root)
a_path = root_path / "a.py"
a_path.write_text(
textwrap.dedent(
"""
# pyre-unsafe
def foo():
return 1
""".rstrip()
)
)
self.assertEqual(
statistics.aggregate_statistics(
statistics.collect_statistics([a_path], strict_default=False)
),
statistics.AggregatedStatisticsData(
annotations={
"return_count": 1,
"annotated_return_count": 0,
"globals_count": 0,
"annotated_globals_count": 0,
"parameter_count": 0,
"annotated_parameter_count": 0,
"attribute_count": 0,
"annotated_attribute_count": 0,
"function_count": 1,
"partially_annotated_function_count": 0,
"fully_annotated_function_count": 0,
"line_count": 5,
},
fixmes=0,
ignores=0,
strict=0,
unsafe=1,
),
)
def test_aggregate_statistics__multiple_files(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root)
a_path = root_path / "a.py"
b_path = root_path / "b.py"
a_path.write_text(
textwrap.dedent(
"""
# pyre-unsafe
def foo():
return 1
""".rstrip()
)
)
b_path.write_text(
textwrap.dedent(
"""
# pyre-strict
def foo(x: int) -> int:
return 1
""".rstrip()
)
)
self.assertEqual(
statistics.aggregate_statistics(
statistics.collect_statistics(
[a_path, b_path], strict_default=False
)
),
statistics.AggregatedStatisticsData(
annotations={
"return_count": 2,
"annotated_return_count": 1,
"globals_count": 0,
"annotated_globals_count": 0,
"parameter_count": 1,
"annotated_parameter_count": 1,
"attribute_count": 0,
"annotated_attribute_count": 0,
"function_count": 2,
"partially_annotated_function_count": 0,
"fully_annotated_function_count": 1,
"line_count": 10,
},
fixmes=0,
ignores=0,
strict=1,
unsafe=1,
),
)
| StatisticsTest |
python | pypa__pipenv | pipenv/patched/pip/_internal/utils/logging.py | {
"start": 1090,
"end": 2129
} | class ____(Exception):
"""
Raised if BrokenPipeError occurs for the stdout stream while logging.
"""
def _is_broken_pipe_error(exc_class: Type[BaseException], exc: BaseException) -> bool:
if exc_class is BrokenPipeError:
return True
# On Windows, a broken pipe can show up as EINVAL rather than EPIPE:
# https://bugs.python.org/issue19612
# https://bugs.python.org/issue30418
if not WINDOWS:
return False
return isinstance(exc, OSError) and exc.errno in (errno.EINVAL, errno.EPIPE)
@contextlib.contextmanager
def indent_log(num: int = 2) -> Generator[None, None, None]:
"""
A context manager which will cause the log output to be indented for any
log messages emitted inside it.
"""
# For thread-safety
_log_state.indentation = get_indentation()
_log_state.indentation += num
try:
yield
finally:
_log_state.indentation -= num
def get_indentation() -> int:
return getattr(_log_state, "indentation", 0)
| BrokenStdoutLoggingError |
python | ray-project__ray | doc/source/serve/doc_code/http_guide/disconnects.py | {
"start": 196,
"end": 1615
} | class ____:
def __init__(self):
self.print_storage: List[str] = []
def add(self, s: str):
self.print_storage.append(s)
def clear(self):
self.print_storage.clear()
def get(self) -> List[str]:
return self.print_storage
print_storage_handle = PrintStorage.remote()
def print(string: str):
ray.get(print_storage_handle.add.remote(string))
sys.stdout.write(f"{string}\n")
# __start_basic_disconnect__
import asyncio
from ray import serve
@serve.deployment
async def startled():
try:
print("Replica received request!")
await asyncio.sleep(10000)
except asyncio.CancelledError:
# Add custom behavior that should run
# upon cancellation here.
print("Request got cancelled!")
# __end_basic_disconnect__
serve.run(startled.bind())
import requests
from requests.exceptions import Timeout
# Intentionally time out request to test cancellation behavior
try:
requests.get("http://localhost:8000", timeout=0.5)
except Timeout:
pass
wait_for_condition(
lambda: {"Replica received request!", "Request got cancelled!"}
== set(ray.get(print_storage_handle.get.remote())),
timeout=5,
)
sys.stdout.write(f"{ray.get(print_storage_handle.get.remote())}\n")
ray.get(print_storage_handle.clear.remote())
# __start_shielded_disconnect__
import asyncio
from ray import serve
@serve.deployment
| PrintStorage |
python | doocs__leetcode | lcof/面试题61. 扑克牌中的顺子/Solution.py | {
"start": 0,
"end": 346
} | class ____:
def isStraight(self, nums: List[int]) -> bool:
vis = set()
mi, mx = inf, -inf
for x in nums:
if x == 0:
continue
if x in vis:
return False
vis.add(x)
mi = min(mi, x)
mx = max(mx, x)
return mx - mi <= 4
| Solution |
python | pydata__xarray | xarray/backends/pydap_.py | {
"start": 840,
"end": 1954
} | class ____(BackendArray):
def __init__(self, array, checksums=True):
self.array = array
@property
def shape(self) -> tuple[int, ...]:
return self.array.shape
@property
def dtype(self):
return self.array.dtype
def __getitem__(self, key):
return indexing.explicit_indexing_adapter(
key, self.shape, indexing.IndexingSupport.BASIC, self._getitem
)
def _getitem(self, key):
result = robust_getitem(self.array, key, catch=ValueError)
result = np.asarray(result.data)
axis = tuple(n for n, k in enumerate(key) if isinstance(k, integer_types))
if result.ndim + len(axis) != self.array.ndim and axis:
result = np.squeeze(result, axis)
return result
def get_group(ds, group):
if group in {None, "", "/"}:
# use the root group
return ds
else:
try:
return ds[group]
except KeyError as e:
# wrap error to provide slightly more helpful message
raise KeyError(f"group not found: {group}", e) from e
| PydapArrayWrapper |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 152878,
"end": 153971
} | class ____(Operation):
def call(self, x1, x2):
return backend.numpy.minimum(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape", [])
output_shape = broadcast_shapes(x1_shape, x2_shape)
output_dtype = dtypes.result_type(
getattr(x1, "dtype", type(x1)),
getattr(x2, "dtype", type(x2)),
)
x1_sparse = getattr(x1, "sparse", False)
x2_sparse = getattr(x2, "sparse", False)
output_sparse = x1_sparse and x2_sparse
return KerasTensor(
output_shape, dtype=output_dtype, sparse=output_sparse
)
@keras_export(["keras.ops.minimum", "keras.ops.numpy.minimum"])
def minimum(x1, x2):
"""Element-wise minimum of `x1` and `x2`.
Args:
x1: First tensor.
x2: Second tensor.
Returns:
Output tensor, element-wise minimum of `x1` and `x2`.
"""
if any_symbolic_tensors((x1, x2)):
return Minimum().symbolic_call(x1, x2)
return backend.numpy.minimum(x1, x2)
| Minimum |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/s3.py | {
"start": 25009,
"end": 32810
} | class ____(AwsBaseOperator[S3Hook]):
"""
Copies data from a source S3 location to a temporary location on the local filesystem.
Runs a transformation on this file as specified by the transformation
script and uploads the output to a destination S3 location.
The locations of the source and the destination files in the local
filesystem is provided as a first and second arguments to the
transformation script. The transformation script is expected to read the
data from source, transform it and write the output to the local
destination file. The operator then takes over control and uploads the
local destination file to S3.
S3 Select is also available to filter the source contents. Users can
omit the transformation script if S3 Select expression is specified.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:S3FileTransformOperator`
:param source_s3_key: The key to be retrieved from S3. (templated)
:param dest_s3_key: The key to be written from S3. (templated)
:param transform_script: location of the executable transformation script
:param select_expression: S3 Select expression
:param select_expr_serialization_config: A dictionary that contains input and output serialization configurations for S3 Select.
:param script_args: arguments for transformation script (templated)
:param source_aws_conn_id: source s3 connection
:param source_verify: Whether or not to verify SSL certificates for S3 connection.
By default SSL certificates are verified.
You can provide the following values:
- ``False``: do not validate SSL certificates. SSL will still be used
(unless use_ssl is False), but SSL certificates will not be
verified.
- ``path/to/cert/bundle.pem``: A filename of the CA cert bundle to uses.
You can specify this argument if you want to use a different
CA cert bundle than the one used by botocore.
This is also applicable to ``dest_verify``.
:param dest_aws_conn_id: destination s3 connection
:param dest_verify: Whether or not to verify SSL certificates for S3 connection.
See: ``source_verify``
:param replace: Replace dest S3 key if it already exists
"""
template_fields: Sequence[str] = aws_template_fields("source_s3_key", "dest_s3_key", "script_args")
template_ext: Sequence[str] = ()
ui_color = "#f9c915"
aws_hook_class = S3Hook
def __init__(
self,
*,
source_s3_key: str,
dest_s3_key: str,
transform_script: str | None = None,
select_expression=None,
select_expr_serialization_config: dict[str, dict[str, dict]] | None = None,
script_args: Sequence[str] | None = None,
source_aws_conn_id: str | None = "aws_default",
source_verify: bool | str | None = None,
dest_aws_conn_id: str | None = "aws_default",
dest_verify: bool | str | None = None,
replace: bool = False,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.source_s3_key = source_s3_key
self.source_aws_conn_id = source_aws_conn_id
self.source_verify = source_verify
self.dest_s3_key = dest_s3_key
self.dest_aws_conn_id = dest_aws_conn_id
self.dest_verify = dest_verify
self.replace = replace
self.transform_script = transform_script
self.select_expression = select_expression
self.select_expr_serialization_config = select_expr_serialization_config or {}
self.script_args = script_args or []
self.output_encoding = sys.getdefaultencoding()
def execute(self, context: Context):
if self.transform_script is None and self.select_expression is None:
raise AirflowException("Either transform_script or select_expression must be specified")
# Keep these hooks constructed here since we are using two unique conn_ids
source_s3 = S3Hook(aws_conn_id=self.source_aws_conn_id, verify=self.source_verify)
dest_s3 = S3Hook(aws_conn_id=self.dest_aws_conn_id, verify=self.dest_verify)
self.log.info("Downloading source S3 file %s", self.source_s3_key)
if not source_s3.check_for_key(self.source_s3_key):
raise AirflowException(f"The source key {self.source_s3_key} does not exist")
source_s3_key_object = source_s3.get_key(self.source_s3_key)
with NamedTemporaryFile("wb") as f_source, NamedTemporaryFile("wb") as f_dest:
self.log.info("Dumping S3 file %s contents to local file %s", self.source_s3_key, f_source.name)
if self.select_expression is not None:
input_serialization = self.select_expr_serialization_config.get("input_serialization")
output_serialization = self.select_expr_serialization_config.get("output_serialization")
content = source_s3.select_key(
key=self.source_s3_key,
expression=self.select_expression,
input_serialization=input_serialization,
output_serialization=output_serialization,
)
f_source.write(content.encode("utf-8"))
else:
source_s3_key_object.download_fileobj(Fileobj=f_source)
f_source.flush()
if self.transform_script is not None:
with subprocess.Popen(
[self.transform_script, f_source.name, f_dest.name, *self.script_args],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=True,
) as process:
self.log.info("Output:")
if process.stdout is not None:
for line in iter(process.stdout.readline, b""):
self.log.info(line.decode(self.output_encoding).rstrip())
process.wait()
if process.returncode:
raise AirflowException(f"Transform script failed: {process.returncode}")
self.log.info(
"Transform script successful. Output temporarily located at %s", f_dest.name
)
self.log.info("Uploading transformed file to S3")
f_dest.flush()
dest_s3.load_file(
filename=f_dest.name if self.transform_script else f_source.name,
key=self.dest_s3_key,
replace=self.replace,
)
self.log.info("Upload successful")
def get_openlineage_facets_on_start(self):
from airflow.providers.common.compat.openlineage.facet import Dataset
from airflow.providers.openlineage.extractors import OperatorLineage
dest_bucket_name, dest_bucket_key = S3Hook.get_s3_bucket_key(
bucket=None,
key=self.dest_s3_key,
bucket_param_name="dest_bucket_name",
key_param_name="dest_bucket_key",
)
source_bucket_name, source_bucket_key = S3Hook.get_s3_bucket_key(
bucket=None,
key=self.source_s3_key,
bucket_param_name="source_bucket_name",
key_param_name="source_bucket_key",
)
input_dataset = Dataset(
namespace=f"s3://{source_bucket_name}",
name=source_bucket_key,
)
output_dataset = Dataset(
namespace=f"s3://{dest_bucket_name}",
name=dest_bucket_key,
)
return OperatorLineage(
inputs=[input_dataset],
outputs=[output_dataset],
)
| S3FileTransformOperator |
python | ray-project__ray | python/ray/llm/tests/serve/gpu/integration/test_openai_compatibility.py | {
"start": 42,
"end": 4643
} | class ____:
"""Test that the rayllm are compatible with the OpenAI API"""
def test_models(self, testing_model): # noqa: F811
client, model = testing_model
models = client.models.list()
assert len(models.data) == 1, "Only the test model should be returned"
assert models.data[0].id == model, "The test model id should match"
assert models.data[0].metadata["input_modality"] == "text"
def test_completions(self, testing_model): # noqa: F811
client, model = testing_model
completion = client.completions.create(
model=model,
prompt="Hello world",
max_tokens=2,
)
assert completion.model == model
assert completion.model
assert completion.choices[0].text == "test_0 test_1"
def test_chat(self, testing_model): # noqa: F811
client, model = testing_model
# create a chat completion
chat_completion = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": "Hello world"}],
)
assert chat_completion
assert chat_completion.usage
assert chat_completion.id
assert isinstance(chat_completion.choices, list)
assert chat_completion.choices[0].message.content
def test_completions_missing_model(self, testing_model): # noqa: F811
client, _ = testing_model
with pytest.raises(openai.NotFoundError) as exc_info:
client.completions.create(
model="notarealmodel",
prompt="Hello world",
)
assert "Could not find" in str(exc_info.value)
def test_chat_missing_model(self, testing_model): # noqa: F811
client, _ = testing_model
with pytest.raises(openai.NotFoundError) as exc_info:
client.chat.completions.create(
model="notarealmodel",
messages=[{"role": "user", "content": "Hello world"}],
)
assert "Could not find" in str(exc_info.value)
def test_completions_stream(self, testing_model): # noqa: F811
client, model = testing_model
i = 0
for completion in client.completions.create(
model=model,
prompt="Hello world",
stream=True,
):
i += 1
assert completion
assert completion.id
assert isinstance(completion.choices, list)
assert isinstance(completion.choices[0].text, str)
assert i > 4
def test_chat_stream(self, testing_model): # noqa: F811
client, model = testing_model
i = 0
for chat_completion in client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": "Hello world"}],
stream=True,
stream_options=dict(
include_usage=True,
),
temperature=0.4,
frequency_penalty=0.02,
max_tokens=5,
):
if i == 0:
assert chat_completion
assert chat_completion.id
assert isinstance(chat_completion.choices, list)
assert chat_completion.choices[0].delta.role
else:
assert chat_completion
assert chat_completion.id
assert isinstance(chat_completion.choices, list)
assert chat_completion.choices[0].delta == {} or hasattr(
chat_completion.choices[0].delta, "content"
)
i += 1
def test_completions_stream_missing_model(self, testing_model): # noqa: F811
client, _ = testing_model
with pytest.raises(openai.NotFoundError) as exc_info:
for _chat_completion in client.completions.create(
model="notarealmodel",
prompt="Hello world",
stream=True,
):
pass
assert "Could not find" in str(exc_info.value)
def test_chat_stream_missing_model(self, testing_model): # noqa: F811
client, _ = testing_model
with pytest.raises(openai.NotFoundError) as exc_info:
for _chat_completion in client.chat.completions.create(
model="notarealmodel",
messages=[{"role": "user", "content": "Hello world"}],
stream=True,
):
pass
assert "Could not find" in str(exc_info.value)
if __name__ == "__main__":
sys.exit(pytest.main(["-v", __file__]))
| TestOpenAICompatibility |
python | huggingface__transformers | src/transformers/models/clvp/configuration_clvp.py | {
"start": 6999,
"end": 15038
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ClvpDecoder`]. It is used to instantiate a CLVP
Decoder Model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the Decoder part of the CLVP
[susnato/clvp_dev](https://huggingface.co/susnato/clvp_dev) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
The architecture is similar to GPT2.
Args:
vocab_size (`int`, *optional*, defaults to 8194):
Vocabulary size of the model.
max_position_embeddings (`int`, *optional*, defaults to 608):
The maximum sequence length of mel tokens that this model might ever be used with. Similar to `n_positions`
in `GPT2Config`.
max_text_tokens (`int`, *optional*, defaults to 404):
The maximum sequence length of text tokens that this model might ever be used with. Similar to
`n_positions` in `GPT2Config`.
hidden_size (`int`, *optional*, defaults to 1024):
Dimensionality of the embeddings and hidden states.
num_hidden_layers (`int`, *optional*, defaults to 30):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 16):
Number of attention heads for each attention layer in the Transformer encoder.
n_inner (`int`, *optional*):
Dimensionality of the inner feed-forward layers. `None` will set it to 4 times `hidden_size`.
num_mel_attn_blocks (`int`, *optional*, defaults to 6):
Denotes the number of self attention layers in [`ClvpConditioningEncoder`].
activation_function (`str`, *optional*, defaults to `"gelu_new"`):
Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
resid_pdrop (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
embd_pdrop (`float`, *optional*, defaults to 0.1):
The dropout ratio for the embeddings.
attention_dropout (`float`, *optional*, defaults to 0.1):
The dropout ratio for the attention.
layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
The epsilon to use in the layer normalization layers.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
summary_type (`string`, *optional*, defaults to `"cls_index"`):
Argument used when doing sequence summary.
Has to be one of the following options:
- `"last"`: Take the last token hidden state (like XLNet).
- `"first"`: Take the first token hidden state (like BERT).
- `"mean"`: Take the mean of all tokens hidden states.
- `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
- `"attn"`: Not implemented now, use multi-head attention.
summary_use_proj (`bool`, *optional*, defaults to `True`):
Whether or not to add a projection after the vector extraction.
summary_activation (`str`, *optional*):
Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
summary_first_dropout (`float`, *optional*, defaults to 0.1):
The dropout ratio to be used after the projection and activation.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models).
bos_token_id (`int`, *optional*, defaults to 8192):
Beginning of sequence token id, used at the start of the generation.
eos_token_id (`int`, *optional*, defaults to 8193):
End of sequence token id, used in the method
[`ClvpModelForConditionalGeneration.fix_speech_decoder_output()`] to correct decoder outputs.
feature_size (`int`, *optional*, defaults to 80):
The feature dimension of the extracted mel features. This value is used in [`ClvpConditioningEncoder`].
use_attention_bias (`bool`, *optional*, defaults to `True`):
Whether to use bias in Query, Key and Value layers during self attention.
initializer_factor (`float`, *optional*, defaults to 1.0):
A factor for initializing all weight matrices (should be kept to 1.0, used internally for initialization
testing).
decoder_fixing_codes (`list`, *optional*, defaults to `[83, 45, 45, 248]`):
These values are used in the method `fix_speech_decoder_output` to fix decoder generated outputs.
Example:
```python
>>> from transformers import ClvpDecoderConfig, ClvpDecoder
>>> # Initializing a ClvpDecoderConfig with susnato/clvp_dev style configuration
>>> decoder_configuration = ClvpDecoderConfig()
>>> # Initializing a ClvpDecoder (with random weights) from the susnato/clvp_dev style configuration
>>> model = ClvpDecoder(decoder_configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "clvp_decoder"
base_config_key = "decoder_config"
def __init__(
self,
vocab_size=8194,
max_position_embeddings=608,
max_text_tokens=404,
hidden_size=1024,
num_hidden_layers=30,
num_attention_heads=16,
n_inner=None,
num_mel_attn_blocks=6,
activation_function="gelu_new",
resid_pdrop=0.1,
embd_pdrop=0.1,
attention_dropout=0.1,
layer_norm_epsilon=1e-5,
initializer_range=0.02,
summary_type="cls_index",
summary_use_proj=True,
summary_activation=None,
summary_proj_to_labels=True,
summary_first_dropout=0.1,
use_cache=True,
bos_token_id=8192,
eos_token_id=8193,
feature_size=80,
use_attention_bias=True,
initializer_factor=1.0,
decoder_fixing_codes=[83, 45, 45, 248],
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.max_text_tokens = max_text_tokens
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.n_inner = n_inner
self.num_mel_attn_blocks = num_mel_attn_blocks
self.activation_function = activation_function
self.resid_pdrop = resid_pdrop
self.embd_pdrop = embd_pdrop
self.attention_dropout = attention_dropout
self.layer_norm_epsilon = layer_norm_epsilon
self.initializer_range = initializer_range
self.summary_type = summary_type
self.summary_use_proj = summary_use_proj
self.summary_activation = summary_activation
self.summary_first_dropout = summary_first_dropout
self.summary_proj_to_labels = summary_proj_to_labels
self.use_cache = use_cache
self.feature_size = feature_size
self.use_attention_bias = use_attention_bias
self.initializer_factor = initializer_factor
self.decoder_fixing_codes = decoder_fixing_codes
self.bos_token_id = bos_token_id
self.eos_token_id = eos_token_id
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
| ClvpDecoderConfig |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/autograd_cache.py | {
"start": 2396,
"end": 10470
} | class ____(BypassAOTAutogradCache):
pass
def should_use_remote_autograd_cache():
if torch.compiler.config.force_disable_caches:
return False
if config.enable_remote_autograd_cache is not None:
return config.enable_remote_autograd_cache
if not config.is_fbcode():
return False
if torch._utils_internal.is_fb_unit_test():
return False
try:
from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION
except ModuleNotFoundError:
return False
jk_name = "pytorch/remote_cache:aot_autograd_cache_version"
return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int(jk_name)
def should_use_local_autograd_cache():
if torch.compiler.config.force_disable_caches:
return False
return config.enable_autograd_cache
def should_bundle_autograd_cache():
return config.bundled_autograd_cache or torch._dynamo.config.caching_precompile
def check_node_safe(node: Node):
"""
Checks that the node only uses supported operators. We are starting with very
conservative cacheability constraints, and incrementally adding more support as we expand.
[Note: AOTAutograd Cacheability checks]
- Our cache key is computed from the FX graph produced by Dynamo and the input example values
- A node is "safe" if the same cache key results in a compiled artifact that has the same behavior
(i.e, the set of inputs that go into our cache key is sufficient to distinguish its behavior)
To accomplish this safety check, we consider the following functions to be safe:
- Public functions under modules torch, torch.functional, and torch.nn.functional: these are
allowed in the graph by dynamo, so we can assume they are safe to cache.
- method calls on base tensor types
- Any call_module that dynamo deemed safe to allow AOTAutograd to trace
- Non callable nodes, such as placeholder, output, get_attr
The test suite test_aot_autograd_cache.py::AOTAutogradCachePicklerTests tries its best to fully cover/specify this behavior.
"""
SAFE_TORCH_MODULES = ("torch.functional", "torch.nn.functional")
SAFE_TORCH_FUNCTIONS = (
"torch.Size",
"torch.Tensor",
"torch.sym_int",
"torch._sym_sqrt",
"torch.sym_float",
"torch.sym_sum",
)
SAFE_NON_TORCH_FUNCTIONS = (
"einops.einops.rearrange",
"einops.einops.repeat",
)
def is_public_torch_api(target):
# Don't blindly allow private functions in the torch namespace
is_private = target.__name__.startswith("_")
return (
getattr(target, "__module__", None) in SAFE_TORCH_MODULES and not is_private
)
def is_safe_torch_function(target):
"""Allowlisted torch functions"""
function_name = f"{target.__module__}.{target.__name__}"
# Allow torch.autograd.function.FunctionCtx if custom autograd functions are allowed
if function_name == "torch.autograd.function.FunctionCtx":
return (
torch._functorch.config.autograd_cache_allow_custom_autograd_functions
)
# Functions in torch_non_c_binding_in_graph_functions
# are guaranteed to be cache safe.
# See NOTE: [Cacheability of in-graph torch functions]
return (
function_name in torch_non_c_binding_in_graph_functions
or function_name in SAFE_TORCH_FUNCTIONS
or function_name in torch._inductor.config.unsafe_marked_cacheable_functions
)
def is_cacheable_function(target):
if isinstance(target, (torch._ops.OpOverload, torch._ops.OpOverloadPacket)):
return True
if is_public_torch_api(target):
return True
# Technically, FXGraphCache._check_for_hop already checks this,
# but better to error earlier anyway
if isinstance(target, torch._ops.HigherOrderOperator):
return target.cacheable()
is_builtin_fun_or_type = type(target).__name__ == "builtin_function_or_method"
if is_builtin_fun_or_type:
return True
if is_safe_torch_function(target):
return True
function_name = f"{target.__module__}.{target.__name__}"
if function_name in SAFE_NON_TORCH_FUNCTIONS:
return True
return False
def is_tensor(target):
# Tensors always have example values in meta field
return "example_value" in target.meta
# I'd love to use a match statement here, but it wasn't introduced until py3.10
if node.op == "call_function":
if node.meta and node.meta.get("is_wrapped", False):
# This is fx.wrap function
# By default we BypassAOTAutogradCache for unknown functions,
# But if user explicitly specified cache hash - allow to cache it.
if node.meta.get("user_cache_hash", None):
return
if not is_cacheable_function(node.target):
module = getattr(node.target, "__module__", None)
name = getattr(node.target, "__name__", None)
raise BypassAOTAutogradCache(
f"Unsupported call_function target {node.target}. \n Function module: {module}, \nFunction name: {name}"
)
elif node.op == "call_method":
method_name = node.target
method_target = node.args[0]
# Only support method calls on base tensors
if not is_tensor(method_target):
module = getattr(method_target, "__module__", None)
name = getattr(method_target, "__name__", None)
raise BypassAOTAutogradCache(
f"Unsupported call_method target {method_target}. \nMethod module: {module}, \nMethod name: {name}"
)
if (
type(method_name) is not str
and type(method_name).__name__ != "method_descriptor"
):
raise BypassAOTAutogradCache(
f"Unsupported call_method method {node.target}: {method_name}"
)
# Cache safe
elif node.op in ("placeholder", "get_attr", "call_module", "output"):
# Assumption today for call_module being a safe op:
# (1) today the only call_module ops that can show up in a graph come from "built-in-nn-modules"
# that dynamo assumes are safe to trace. If dynamo assumes they are safely to blindly trace, then
# they should be safe to cache as well.
# (2) in the steady-state (some time in H2?) we shouldn't see these anymore, once inline builtin nn modules by default
# (3) We do not allow user made nn modules in the graph today, only function calls.
pass
else:
raise BypassAOTAutogradCache(f"Unsupported node op {node.op}")
def check_cacheable(gm: torch.fx.GraphModule):
"""
Checks that the graph module only uses supported operators
"""
nodes = gm.graph.nodes
if torch._inductor.config.freezing:
raise BypassAOTAutogradCache("Cannot cache a graph with freezing enabled")
if not (
torch._inductor.config.fx_graph_cache or should_use_remote_fx_graph_cache()
):
raise BypassAOTAutogradCache("FX graph cache is not enabled")
tracing_context = torch._guards.TracingContext.try_get()
if tracing_context and tracing_context.fakify_first_call:
raise BypassAOTAutogradCache(
"Won't cache a graph with fakify_first_call enabled"
)
for node in nodes:
check_node_safe(node)
# Saved tensors hooks are globally set subgraphs,
# that are not used explicitly in the main graph.
# They are inlined in aot_autograd graphs.
# Subgraphs are only used for caching logic.
if hasattr(gm, "saved_tensors_hooks_pack_0"):
check_cacheable(gm.saved_tensors_hooks_pack_0) # type: ignore[arg-type]
# We have guarantee of unpack sugraph existence if pack subgraph exists
check_cacheable(gm.saved_tensors_hooks_unpack_0) # type: ignore[arg-type]
| FXGraphCacheMiss |
python | doocs__leetcode | solution/3100-3199/3183.The Number of Ways to Make the Sum/Solution2.py | {
"start": 154,
"end": 371
} | class ____:
def numberOfWays(self, n: int) -> int:
ans = f[n]
if n >= 4:
ans = (ans + f[n - 4]) % mod
if n >= 8:
ans = (ans + f[n - 8]) % mod
return ans
| Solution |
python | getsentry__sentry | src/sentry/monitors/serializers.py | {
"start": 5178,
"end": 5295
} | class ____(TypedDict, total=False):
alertRule: MonitorAlertRuleSerializerResponse
| MonitorSerializerResponseOptional |
python | anthropics__anthropic-sdk-python | tests/test_legacy_response.py | {
"start": 330,
"end": 1930
} | class ____(pydantic.BaseModel): ...
def test_response_parse_mismatched_basemodel(client: Anthropic) -> None:
response = LegacyAPIResponse(
raw=httpx.Response(200, content=b"foo"),
client=client,
stream=False,
stream_cls=None,
cast_to=str,
options=FinalRequestOptions.construct(method="get", url="/foo"),
)
with pytest.raises(
TypeError,
match="Pydantic models must subclass our base model type, e.g. `from anthropic import BaseModel`",
):
response.parse(to=PydanticModel)
@pytest.mark.parametrize(
"content, expected",
[
("false", False),
("true", True),
("False", False),
("True", True),
("TrUe", True),
("FalSe", False),
],
)
def test_response_parse_bool(client: Anthropic, content: str, expected: bool) -> None:
response = LegacyAPIResponse(
raw=httpx.Response(200, content=content),
client=client,
stream=False,
stream_cls=None,
cast_to=str,
options=FinalRequestOptions.construct(method="get", url="/foo"),
)
result = response.parse(to=bool)
assert result is expected
def test_response_parse_custom_stream(client: Anthropic) -> None:
response = LegacyAPIResponse(
raw=httpx.Response(200, content=b"foo"),
client=client,
stream=True,
stream_cls=None,
cast_to=str,
options=FinalRequestOptions.construct(method="get", url="/foo"),
)
stream = response.parse(to=Stream[int])
assert stream._cast_to == int
| PydanticModel |
python | kennethreitz__tablib | tests/test_tablib_dbfpy_packages_fields.py | {
"start": 122,
"end": 1208
} | class ____(unittest.TestCase):
"""dbfpy.fields.DbfFieldDef comparison test cases, via child classes."""
def setUp(self) -> None:
self.length = 10
self.a = fields.DbfCharacterFieldDef("abc", self.length)
self.z = fields.DbfCharacterFieldDef("xyz", self.length)
self.a2 = fields.DbfCharacterFieldDef("abc", self.length)
def test_compare__eq__(self):
# Act / Assert
self.assertEqual(self.a, self.a2)
def test_compare__ne__(self):
# Act / Assert
self.assertNotEqual(self.a, self.z)
def test_compare__lt__(self):
# Act / Assert
self.assertLess(self.a, self.z)
def test_compare__le__(self):
# Act / Assert
self.assertLessEqual(self.a, self.a2)
self.assertLessEqual(self.a, self.z)
def test_compare__gt__(self):
# Act / Assert
self.assertGreater(self.z, self.a)
def test_compare__ge__(self):
# Act / Assert
self.assertGreaterEqual(self.a2, self.a)
self.assertGreaterEqual(self.z, self.a)
| DbfFieldDefTestCompareCase |
python | pdm-project__pdm | src/pdm/models/repositories/base.py | {
"start": 836,
"end": 1485
} | class ____(NamedTuple):
dependencies: list[Requirement]
requires_python: str
summary: str
def cache_result(func: Callable[[T, Candidate], CandidateMetadata]) -> Callable[[T, Candidate], CandidateMetadata]:
@wraps(func)
def wrapper(self: T, candidate: Candidate) -> CandidateMetadata:
result = func(self, candidate)
prepared = candidate.prepared
info = ([r.as_line() for r in result.dependencies], result.requires_python, result.summary)
if prepared and prepared.should_cache():
self._candidate_info_cache.set(candidate, info)
return result
return wrapper
| CandidateMetadata |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 22288,
"end": 22873
} | class ____:
param_names = ["shape"]
params = [get_benchmark_shapes("TimeIndexing")]
def setup(self, shape):
self.df = generate_dataframe("int", *shape, RAND_LOW, RAND_HIGH)
self.numeric_indexer = [0, 1]
self.labels_indexer = self.df.columns[self.numeric_indexer].tolist()
def time_iloc(self, shape):
execute(self.df.iloc[:, self.numeric_indexer])
def time_loc(self, shape):
execute(self.df.loc[:, self.labels_indexer])
def time___getitem__(self, shape):
execute(self.df[self.labels_indexer])
| TimeIndexingColumns |
python | openai__openai-python | src/openai/_base_client.py | {
"start": 66840,
"end": 68237
} | class ____:
def __init__(self, name: str) -> None:
self.name = name
@override
def __str__(self) -> str:
return f"other:{self.name}"
Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]]
def get_python_runtime() -> str:
try:
return platform.python_implementation()
except Exception:
return "unknown"
def get_python_version() -> str:
try:
return platform.python_version()
except Exception:
return "unknown"
def get_architecture() -> Arch:
try:
machine = platform.machine().lower()
except Exception:
return "unknown"
if machine in ("arm64", "aarch64"):
return "arm64"
# TODO: untested
if machine == "arm":
return "arm"
if machine == "x86_64":
return "x64"
# TODO: untested
if sys.maxsize <= 2**32:
return "x32"
if machine:
return OtherArch(machine)
return "unknown"
def _merge_mappings(
obj1: Mapping[_T_co, Union[_T, Omit]],
obj2: Mapping[_T_co, Union[_T, Omit]],
) -> Dict[_T_co, _T]:
"""Merge two mappings of the same type, removing any values that are instances of `Omit`.
In cases with duplicate keys the second mapping takes precedence.
"""
merged = {**obj1, **obj2}
return {key: value for key, value in merged.items() if not isinstance(value, Omit)}
| OtherArch |
python | doocs__leetcode | solution/3100-3199/3104.Find Longest Self-Contained Substring/Solution.py | {
"start": 0,
"end": 576
} | class ____:
def maxSubstringLength(self, s: str) -> int:
first, last = {}, {}
for i, c in enumerate(s):
if c not in first:
first[c] = i
last[c] = i
ans, n = -1, len(s)
for c, i in first.items():
mx = last[c]
for j in range(i, n):
a, b = first[s[j]], last[s[j]]
if a < i:
break
mx = max(mx, b)
if mx == j and j - i + 1 < n:
ans = max(ans, j - i + 1)
return ans
| Solution |
python | scipy__scipy | scipy/special/_generate_pyx.py | {
"start": 13887,
"end": 16388
} | class ____:
"""
Base class for Ufunc.
"""
def __init__(self, name, signatures):
self.name = name
self.signatures = []
self.function_name_overrides = {}
for header in signatures.keys():
for name, sig in signatures[header].items():
inarg, outarg, ret = self._parse_signature(sig)
self.signatures.append((name, inarg, outarg, ret, header))
def _parse_signature(self, sig):
T = 'fdgFDGilp'
m = re.match(rf"\s*([{T}]*)\s*\*\s*([{T}]*)\s*->\s*([*{T}]*)\s*$",
sig)
if m:
inarg, outarg, ret = (x.strip() for x in m.groups())
if ret.count('*') > 1:
raise ValueError(f"{self.name}: Invalid signature: {sig}")
return inarg, outarg, ret
m = re.match(rf"\s*([{T}]*)\s*->\s*([{T}]?)\s*$", sig)
if m:
inarg, ret = (x.strip() for x in m.groups())
return inarg, "", ret
raise ValueError(f"{self.name}: Invalid signature: {sig}")
def get_prototypes(self, nptypes_for_h=False):
prototypes = []
for func_name, inarg, outarg, ret, header in self.signatures:
ret = ret.replace('*', '')
c_args = ([C_TYPES[x] for x in inarg]
+ [C_TYPES[x] + ' *' for x in outarg])
cy_args = ([CY_TYPES[x] for x in inarg]
+ [CY_TYPES[x] + ' *' for x in outarg])
c_proto = f"{C_TYPES[ret]} (*)({', '.join(c_args)})"
if header.endswith("h") and nptypes_for_h:
cy_proto = c_proto + "nogil"
else:
cy_proto = f"{CY_TYPES[ret]} (*)({', '.join(cy_args)}) noexcept nogil"
prototypes.append((func_name, c_proto, cy_proto, header))
return prototypes
def cython_func_name(self, c_name, specialized=False, prefix="_func_",
override=True):
# act on function name overrides
if override and c_name in self.function_name_overrides:
c_name = self.function_name_overrides[c_name]
prefix = ""
# support fused types
m = re.match(r'^(.*?)(\[.*\])$', c_name)
if m:
c_base_name, fused_part = m.groups()
else:
c_base_name, fused_part = c_name, ""
if specialized:
return f"{prefix}{c_base_name}{fused_part.replace(' ', '_')}"
else:
return f"{prefix}{c_base_name}"
| Func |
python | django__django | tests/forms_tests/tests/test_forms.py | {
"start": 208068,
"end": 208121
} | class ____(FormsTestCase):
pass
| Jinja2FormsTestCase |
python | astropy__astropy | astropy/utils/masked/tests/test_masked.py | {
"start": 59799,
"end": 60454
} | class ____(
TestMaskedArrayInteractionWithNumpyMA, QuantitySetup
):
pass
@pytest.mark.skipif(not HAS_PLT, reason="requires matplotlib.pyplot")
def test_plt_scatter_masked():
# check that plotting Masked data doesn't raise an exception
# see https://github.com/astropy/astropy/issues/12481
import matplotlib.pyplot as plt
_, ax = plt.subplots()
# no mask
x = Masked([1, 2, 3])
ax.scatter(x, x, c=x)
# all masked
x = Masked([1, 2, 3], mask=True)
ax.scatter(x, x, c=x)
# *some* masked
x = Masked([1, 2, 3], mask=[False, True, False])
ax.scatter(x, x, c=x)
| TestMaskedQuantityInteractionWithNumpyMA |
python | tensorflow__tensorflow | tensorflow/python/saved_model/nested_structure_coder_test.py | {
"start": 1725,
"end": 21542
} | class ____(test.TestCase):
def testEncodeDecodeList(self):
structure = [1.5, 2.5, 3.0]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected.list_value.values.add().float64_value = 1.5
expected.list_value.values.add().float64_value = 2.5
expected.list_value.values.add().float64_value = 3.0
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeTuple(self):
structure = ("hello", [3, (2, 1)])
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected.tuple_value.values.add().string_value = "hello"
list_value = expected.tuple_value.values.add().list_value
list_value.values.add().int64_value = 3
tuple_value = list_value.values.add().tuple_value
tuple_value.values.add().int64_value = 2
tuple_value.values.add().int64_value = 1
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeDict(self):
structure = dict(a=3, b=[7, 2.5])
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected.dict_value.fields["a"].int64_value = 3
list_value = expected.dict_value.fields["b"].list_value
list_value.values.add().int64_value = 7
list_value.values.add().float64_value = 2.5
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertIsInstance(decoded["a"], int)
self.assertEqual(structure, decoded)
def testEncodeDecodeImmutableDict(self):
structure = immutable_dict.ImmutableDict(dict(a=3, b=[7, 2.5]))
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected.dict_value.fields["a"].int64_value = 3
list_value = expected.dict_value.fields["b"].list_value
list_value.values.add().int64_value = 7
list_value.values.add().float64_value = 2.5
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertIsInstance(decoded["a"], int)
self.assertEqual(structure, decoded)
def testEncodeDecodeTensorShape(self):
structure = [tensor_shape.TensorShape([1, 2, 3]), "hello"]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected_list = expected.list_value
expected_tensor_shape = expected_list.values.add().tensor_shape_value
expected_tensor_shape.dim.add().size = 1
expected_tensor_shape.dim.add().size = 2
expected_tensor_shape.dim.add().size = 3
expected_tensor_shape = expected_list.values.add().string_value = "hello"
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeNamedTuple(self):
named_tuple_type = collections.namedtuple("NamedTuple", ["x", "y"])
named_tuple = named_tuple_type(x=[1, 2], y="hello")
self.assertTrue(nested_structure_coder.can_encode(named_tuple))
encoded = nested_structure_coder.encode_structure(named_tuple)
expected = struct_pb2.StructuredValue()
expected_named_tuple = expected.named_tuple_value
expected_named_tuple.name = "NamedTuple"
key_value_pair = expected_named_tuple.values.add()
key_value_pair.key = "x"
list_value = key_value_pair.value.list_value
list_value.values.add().int64_value = 1
list_value.values.add().int64_value = 2
key_value_pair = expected_named_tuple.values.add()
key_value_pair.key = "y"
key_value_pair.value.string_value = "hello"
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(named_tuple._asdict(), decoded._asdict())
self.assertEqual(named_tuple.__class__.__name__, decoded.__class__.__name__)
def testNone(self):
structure = [1.0, None]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected.list_value.values.add().float64_value = 1.0
expected.list_value.values.add().none_value.CopyFrom(struct_pb2.NoneValue())
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testBool(self):
structure = [False]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected.list_value.values.add().bool_value = False
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEmptyStructures(self):
structure = [list(), dict(), tuple()]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected.list_value.values.add().list_value.CopyFrom(struct_pb2.ListValue())
expected.list_value.values.add().dict_value.CopyFrom(struct_pb2.DictValue())
expected.list_value.values.add().tuple_value.CopyFrom(
struct_pb2.TupleValue())
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testDtype(self):
structure = [dtypes.int64]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
list_value = expected.list_value.values.add()
list_value.tensor_dtype_value = dtypes.int64.as_datatype_enum
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeTensorSpec(self):
structure = [tensor.TensorSpec([1, 2, 3], dtypes.int64, "hello")]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected_list = expected.list_value
expected_tensor_spec = expected_list.values.add().tensor_spec_value
expected_tensor_spec.shape.dim.add().size = 1
expected_tensor_spec.shape.dim.add().size = 2
expected_tensor_spec.shape.dim.add().size = 3
expected_tensor_spec.name = "hello"
expected_tensor_spec.dtype = dtypes.int64.as_datatype_enum
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeTensorSpecWithNoName(self):
structure = [tensor.TensorSpec([1, 2, 3], dtypes.int64)]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected_list = expected.list_value
expected_tensor_spec = expected_list.values.add().tensor_spec_value
expected_tensor_spec.shape.dim.add().size = 1
expected_tensor_spec.shape.dim.add().size = 2
expected_tensor_spec.shape.dim.add().size = 3
expected_tensor_spec.name = ""
expected_tensor_spec.dtype = dtypes.int64.as_datatype_enum
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeRaggedTensorSpec(self):
structure = [
ragged_tensor.RaggedTensorSpec([1, 2, 3], dtypes.int64, 2, dtypes.int32)
]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected_pbtxt = r"""
list_value {
values {
type_spec_value {
type_spec_class: RAGGED_TENSOR_SPEC
type_spec_class_name: 'RaggedTensorSpec'
num_flat_components: 3
type_state {
tuple_value {
# spec._shape
values {
tensor_shape_value {
dim { size: 1 }
dim { size: 2 }
dim { size: 3 }
}
}
# spec._dtype
values { tensor_dtype_value: DT_INT64 }
# spec._ragged_rank
values { int64_value: 2 }
# spec._row_splits_dtype
values { tensor_dtype_value: DT_INT32 }
}
}
}
}
}
"""
expected = struct_pb2.StructuredValue()
text_format.Parse(expected_pbtxt, expected)
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeSparseTensorSpec(self):
structure = [sparse_tensor.SparseTensorSpec([10, 20], dtypes.float32)]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected_pbtxt = r"""
list_value {
values {
type_spec_value {
type_spec_class: SPARSE_TENSOR_SPEC
type_spec_class_name: 'SparseTensorSpec'
num_flat_components: 3
type_state {
tuple_value {
# spec._shape
values {
tensor_shape_value {
dim { size: 10 }
dim { size: 20 }
}
}
# spec._dtype
values { tensor_dtype_value: DT_FLOAT }
}
}
}
}
}
"""
expected = struct_pb2.StructuredValue()
text_format.Parse(expected_pbtxt, expected)
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeExtensionTypeSpec(self):
class Zoo(extension_type.ExtensionType):
__name__ = "tf.nested_structure_coder_test.Zoo"
zookeepers: typing.Tuple[str, ...]
animals: typing.Mapping[str, tensor.Tensor]
structure = [
Zoo.Spec(
zookeepers=["Zoey", "Zack"],
animals={"tiger": tensor.TensorSpec([16])})
]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected_pbtxt = r"""
list_value {
values {
type_spec_value {
type_spec_class: EXTENSION_TYPE_SPEC
type_spec_class_name: "tf.nested_structure_coder_test.Zoo.Spec"
num_flat_components: 1
type_state {
tuple_value {
values {
tuple_value {
values { string_value: "zookeepers" }
values { tuple_value {
values { string_value: "Zoey" }
values { string_value: "Zack" } } } } }
values {
tuple_value {
values { string_value: "animals" }
values { dict_value {
fields {
key: "tiger"
value { tensor_spec_value {
shape { dim { size: 16 } }
dtype: DT_FLOAT } } } } } } } } } } } }
"""
expected = struct_pb2.StructuredValue()
text_format.Parse(expected_pbtxt, expected)
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testDecodeUnknownTensorSpec(self):
encoded = struct_pb2.StructuredValue()
encoded.type_spec_value.type_spec_class = 0
encoded.type_spec_value.type_spec_class_name = "FutureTensorSpec"
with self.assertRaisesRegex(ValueError,
"The type 'FutureTensorSpec' is not supported"):
nested_structure_coder.decode_proto(encoded)
def testEncodeDecodeBoundedTensorSpec(self):
structure = [
tensor.BoundedTensorSpec([1, 2, 3], dtypes.int64, 0, 10, "hello_0_10")
]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected_list = expected.list_value
expected_tensor_spec = expected_list.values.add().bounded_tensor_spec_value
expected_tensor_spec.shape.dim.add().size = 1
expected_tensor_spec.shape.dim.add().size = 2
expected_tensor_spec.shape.dim.add().size = 3
expected_tensor_spec.name = "hello_0_10"
expected_tensor_spec.dtype = dtypes.int64.as_datatype_enum
expected_tensor_spec.minimum.CopyFrom(
tensor_util.make_tensor_proto([0], dtype=dtypes.int64, shape=[]))
expected_tensor_spec.maximum.CopyFrom(
tensor_util.make_tensor_proto([10], dtype=dtypes.int64, shape=[]))
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeBoundedTensorSpecNoName(self):
structure = [
tensor.BoundedTensorSpec((28, 28, 3), dtypes.float64, -2, (1, 1, 20))
]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected_list = expected.list_value
expected_tensor_spec = expected_list.values.add().bounded_tensor_spec_value
expected_tensor_spec.shape.dim.add().size = 28
expected_tensor_spec.shape.dim.add().size = 28
expected_tensor_spec.shape.dim.add().size = 3
expected_tensor_spec.name = ""
expected_tensor_spec.dtype = dtypes.float64.as_datatype_enum
expected_tensor_spec.minimum.CopyFrom(
tensor_util.make_tensor_proto([-2], dtype=dtypes.float64, shape=[]))
expected_tensor_spec.maximum.CopyFrom(
tensor_util.make_tensor_proto([1, 1, 20],
dtype=dtypes.float64,
shape=[3]))
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDataSetSpec(self):
structure = [
dataset_ops.DatasetSpec({
"rt": ragged_tensor.RaggedTensorSpec([10, None], dtypes.int32),
"st": sparse_tensor.SparseTensorSpec([10, 20], dtypes.float32),
"t": tensor.TensorSpec([10, 8], dtypes.string)
})
]
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
@test_util.run_in_graph_and_eager_modes
def testEncodeDecodeTensor(self):
structure = constant_op.constant(1)
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected_pbtxt = r"""
tensor_value {
dtype: DT_INT32
tensor_shape {
}
int_val: 1
}
"""
expected = struct_pb2.StructuredValue()
text_format.Parse(expected_pbtxt, expected)
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertAllEqual(structure, decoded)
def testEncodeDecodeNumpy(self):
structure = np.array(1.0)
self.assertTrue(nested_structure_coder.can_encode(structure))
encoded = nested_structure_coder.encode_structure(structure)
expected_pbtxt = r"""
numpy_value {
dtype: DT_DOUBLE
tensor_shape {
}
double_val: 1.0
}
"""
expected = struct_pb2.StructuredValue()
text_format.Parse(expected_pbtxt, expected)
self.assertEqual(expected, encoded)
decoded = nested_structure_coder.decode_proto(encoded)
self.assertIsInstance(decoded, np.ndarray)
self.assertAllEqual(structure, decoded)
def testNotEncodable(self):
class NotEncodable(object):
pass
self.assertFalse(nested_structure_coder.can_encode([NotEncodable()]))
def testRegisterCustomCodec(self):
class MyObject(object):
pass
class MyObjectCodec(object):
"""Codec for MyObject."""
def can_encode(self, pyobj):
return isinstance(pyobj, MyObject)
def do_encode(self, array, encode_fn):
del array, encode_fn
return struct_pb2.StructuredValue()
def can_decode(self, value):
del value
return False
def do_decode(self, value, decode_fn):
raise NotImplementedError("Test only.")
nested_structure_coder.register_codec(MyObjectCodec())
my_object = MyObject()
self.assertTrue(nested_structure_coder.can_encode(my_object))
def testRegisteredTypeSpec(self):
expected_warning = ("Encoding a StructuredValue with type "
"NestedStructureTest.RegisteredTypeSpec; loading "
"this StructuredValue will require that this type "
"be imported and registered")
structure = {"x": RegisteredTypeSpec()}
self.assertTrue(nested_structure_coder.can_encode(structure))
with warnings.catch_warnings(record=True) as w:
encoded = nested_structure_coder.encode_structure(structure)
self.assertLen(w, 1)
self.assertIn(expected_warning, str(w[0].message))
decoded = nested_structure_coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testUnregisteredTypeSpec(self):
structure = {"x": UnregisteredTypeSpec()}
self.assertFalse(nested_structure_coder.can_encode(structure))
with self.assertRaises(nested_structure_coder.NotEncodableError):
nested_structure_coder.encode_structure(structure)
def testBuiltInTypeSpecCodecInvalidInputs(self):
class Foo:
pass
class Bar(internal.TypeSpec):
pass
with self.assertRaisesRegex(
ValueError, "The type '(.*?)' does not subclass tf.TypeSpec."):
nested_structure_coder.BuiltInTypeSpecCodec(Foo, 0)
with self.assertRaisesRegex(
ValueError, "The type '(.*?)' already has an instantiated codec."):
nested_structure_coder.BuiltInTypeSpecCodec(
dataset_ops.DatasetSpec, struct_pb2.TypeSpecProto.DATA_DATASET_SPEC)
with self.assertRaisesRegex(
ValueError, "The proto value '(.*?)' is already registered."):
nested_structure_coder.BuiltInTypeSpecCodec(
Bar, struct_pb2.TypeSpecProto.DATA_DATASET_SPEC)
with self.assertRaisesRegex(
ValueError, "The proto value '(.*?)' is invalid."):
nested_structure_coder.BuiltInTypeSpecCodec(Bar, 0)
with self.assertRaisesRegex(
ValueError, "The proto value '(.*?)' is invalid."):
nested_structure_coder.BuiltInTypeSpecCodec(Bar, 11)
with self.assertRaisesRegex(
ValueError, "The proto value '(.*?)' is invalid."):
nested_structure_coder.BuiltInTypeSpecCodec(Bar, 12)
with self.assertRaisesRegex(
ValueError, "The proto value '(.*?)' is invalid."):
nested_structure_coder.BuiltInTypeSpecCodec(Bar, 13)
# Trivial TypeSpec class for testing.
| NestedStructureCoderTest |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker/lkml/dagster_looker_lkml_translator.py | {
"start": 6698,
"end": 31242
} | class ____:
"""Holds a set of methods that derive Dagster asset definition metadata given a representation
of a LookML structure (dashboards, explores, views).
This class is exposed so that methods can be overridden to customize how Dagster asset metadata
is derived.
"""
@public
def get_asset_spec(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> AssetSpec:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster asset spec that represents the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
This method can be overridden to provide a custom asset spec for a LookML structure.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
AssetSpec: The Dagster asset spec that represents the LookML structure.
"""
return AssetSpec(
key=self._resolve_back_compat_method(
"get_asset_key", self._default_asset_key_fn, lookml_structure
),
deps=self._resolve_back_compat_method(
"get_deps", self._default_deps_fn, lookml_structure
),
description=self._resolve_back_compat_method(
"get_description", self._default_description_fn, lookml_structure
),
metadata=self._resolve_back_compat_method(
"get_metadata", self._default_metadata_fn, lookml_structure
),
group_name=self._resolve_back_compat_method(
"get_group_name", self._default_group_name_fn, lookml_structure
),
owners=self._resolve_back_compat_method(
"get_owners", self._default_owners_fn, lookml_structure
),
tags=self._resolve_back_compat_method(
"get_tags", self._default_tags_fn, lookml_structure
),
)
def _resolve_back_compat_method(
self,
method_name: str,
default_fn: Callable[[tuple[Path, LookMLStructureType, Mapping[str, Any]]], Any],
lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]],
):
method = getattr(type(self), method_name)
base_method = getattr(DagsterLookerLkmlTranslator, method_name)
if method is not base_method: # user defined this
supersession_warning(
subject=method_name,
additional_warn_text=(
f"Instead of overriding DagsterLookerLkmlTranslator.{method_name}(), "
f"override DagsterLookerLkmlTranslator.get_asset_spec()."
),
)
return method(self, lookml_structure)
else:
return default_fn(lookml_structure)
@superseded(
additional_warn_text="Use `DagsterLookerLkmlTranslator.get_asset_spec(...).key` instead.",
)
@public
def get_asset_key(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> AssetKey:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster asset key that represents the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
This method can be overridden to provide a custom asset key for a LookML structure.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
AssetKey: The Dagster asset key that represents the LookML structure.
"""
return self._default_asset_key_fn(lookml_structure)
def _default_asset_key_fn(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> AssetKey:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster asset key that represents the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
AssetKey: The Dagster asset key that represents the LookML structure.
"""
lookml_structure_path, lookml_structure_type, lookml_structure_props = lookml_structure
if lookml_structure_type == "dashboard":
return AssetKey(["dashboard", lookml_structure_props["dashboard"]])
if lookml_structure_type == "view":
return AssetKey(["view", lookml_structure_props["name"]])
if lookml_structure_type == "table":
sqlglot_table = lookml_structure_props["table"]
return AssetKey([part.name.replace("*", "_star") for part in sqlglot_table.parts])
if lookml_structure_type == "explore":
explore_name = lookml_structure_props.get("explore") or lookml_structure_props.get(
"name"
)
if not explore_name:
raise ValueError(
f"Could not find `name` or `explore` property in LookML structure type `{lookml_structure_type}`"
f" at path `{lookml_structure_path}` with properties {lookml_structure_props}"
)
return AssetKey(["explore", explore_name])
raise ValueError(
f"Unsupported LookML structure type `{lookml_structure_type}` at path `{lookml_structure_path}`"
)
@superseded(
additional_warn_text=(
"Iterate over `DagsterLookerLkmlTranslator.get_asset_spec(...).deps` "
"to access `AssetDep.asset_key` instead."
),
)
@public
def get_deps(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Sequence[AssetKey]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster dependencies of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
This method can be overridden to provide custom dependencies for a LookML structure.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Sequence[AssetKey]: The Dagster dependencies for the LookML structure.
"""
return self._default_deps_fn(lookml_structure)
def _default_deps_fn(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Sequence[AssetKey]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster dependencies of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Sequence[AssetKey]: The Dagster dependencies for the LookML structure.
"""
lookml_structure_path, lookml_structure_type, _ = lookml_structure
if lookml_structure_type == "dashboard":
return build_deps_for_looker_dashboard(
dagster_looker_translator=self, lookml_structure=lookml_structure
)
if lookml_structure_type == "explore":
return build_deps_for_looker_explore(
dagster_looker_translator=self, lookml_structure=lookml_structure
)
if lookml_structure_type == "view":
return build_deps_for_looker_view(
dagster_looker_translator=self, lookml_structure=lookml_structure
)
if lookml_structure_type == "table":
return []
raise ValueError(
f"Unsupported LookML structure type `{lookml_structure_type}` at path `{lookml_structure_path}`"
)
@superseded(
additional_warn_text="Use `DagsterLookerLkmlTranslator.get_asset_spec(...).description` instead.",
)
@public
def get_description(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[str]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster description of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
This method can be overridden to provide a custom description for a LookML structure.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[str]: The Dagster description for the LookML structure.
"""
return self._default_description_fn(lookml_structure)
def _default_description_fn(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[str]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster description of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[str]: The Dagster description for the LookML structure.
"""
_, _, lookml_structure_props = lookml_structure
return lookml_structure_props.get("description")
@superseded(
additional_warn_text="Use `DagsterLookerLkmlTranslator.get_asset_spec(...).metadata` instead.",
)
@public
def get_metadata(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[Mapping[str, Any]]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster metadata of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
This method can be overridden to provide custom metadata for a LookML structure.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[Mapping[str, Any]]: A dictionary representing the Dagster metadata for the
LookML structure.
"""
return self._default_metadata_fn(lookml_structure)
@public
def _default_metadata_fn(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[Mapping[str, Any]]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster metadata of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[Mapping[str, Any]]: A dictionary representing the Dagster metadata for the
LookML structure.
"""
return None
@superseded(
additional_warn_text="Use `DagsterLookerLkmlTranslator.get_asset_spec(...).group_name` instead.",
)
@public
def get_group_name(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[str]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster group name of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
This method can be overridden to provide a custom group name for a LookML structure.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[str]: A Dagster group name for the LookML structure.
"""
return self._default_group_name_fn(lookml_structure)
def _default_group_name_fn(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[str]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster group name of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[str]: A Dagster group name for the LookML structure.
"""
return None
@superseded(
additional_warn_text="Use `DagsterLookerLkmlTranslator.get_asset_spec(...).owners` instead.",
)
@public
def get_owners(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[Sequence[str]]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster owners of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
This method can be overridden to provide custom owners for a LookML structure.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[Sequence[str]]: A sequence of Dagster owners for the LookML structure.
"""
return self._default_owners_fn(lookml_structure)
def _default_owners_fn(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[Sequence[str]]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster owners of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[Sequence[str]]: A sequence of Dagster owners for the LookML structure.
"""
return None
@superseded(
additional_warn_text="Use `DagsterLookerLkmlTranslator.get_asset_spec(...).tags` instead.",
)
@public
def get_tags(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[Mapping[str, str]]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster tags of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
This method can be overridden to provide custom tags for a LookML structure.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[Mapping[str, str]]: A dictionary representing the Dagster tags for the
LookML structure.
"""
return self._default_tags_fn(lookml_structure)
def _default_tags_fn(
self, lookml_structure: tuple[Path, LookMLStructureType, Mapping[str, Any]]
) -> Optional[Mapping[str, str]]:
"""A method that takes in a LookML structure (dashboards, explores, views) and
returns the Dagster tags of the structure.
The LookML structure is parsed using ``lkml``. You can learn more about this here:
https://lkml.readthedocs.io/en/latest/simple.html.
You can learn more about LookML dashboards and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/param-lookml-dashboard.
You can learn more about LookML explores and views and the properties available in this
dictionary here: https://cloud.google.com/looker/docs/reference/lookml-quick-reference.
Args:
lookml_structure (Tuple[Path, str, Mapping[str, Any]]): A tuple with the path to file
defining a LookML structure, the LookML structure type, and a dictionary
representing a LookML structure.
Returns:
Optional[Mapping[str, str]]: A dictionary representing the Dagster tags for the
LookML structure.
"""
return None
| DagsterLookerLkmlTranslator |
python | celery__celery | t/unit/app/test_builtins.py | {
"start": 788,
"end": 1096
} | class ____(BuiltinsCase):
def setup_method(self):
self.accumulate = self.app.tasks['celery.accumulate']
def test_with_index(self):
assert self.accumulate(1, 2, 3, 4, index=0) == 1
def test_no_index(self):
assert self.accumulate(1, 2, 3, 4), (1, 2, 3 == 4)
| test_accumulate |
python | walkccc__LeetCode | solutions/2054. Two Best Non-Overlapping Events/2054.py | {
"start": 0,
"end": 497
} | class ____:
def maxTwoEvents(self, events: list[list[int]]) -> int:
ans = 0
maxValue = 0
evts = [] # (time, isStart, value)
for s, e, v in events:
evts.append((s, 1, v))
evts.append((e + 1, 0, v))
# When two events have the same time, the one is not start will be in the front
evts.sort()
for _, isStart, value in evts:
if isStart:
ans = max(ans, value + maxValue)
else:
maxValue = max(maxValue, value)
return ans
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias1.py | {
"start": 952,
"end": 1103
} | class ____:
TA1 = list
def __init__(self) -> None:
self.val = self.TA1
b = B()
reveal_type(b.val, expected_text="type[list[Unknown]]")
| B |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_code_interpreter.py | {
"start": 3236,
"end": 16704
} | class ____:
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.CodeInterpreter"
)
def test_init(self, mock_code_interpreter):
tool_spec = AgentCoreCodeInterpreterToolSpec(region="us-east-1")
assert tool_spec.region == "us-east-1"
assert tool_spec._code_interpreters == {}
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.get_aws_region"
)
def test_init_default_region(self, mock_get_aws_region):
mock_get_aws_region.return_value = "us-west-2"
tool_spec = AgentCoreCodeInterpreterToolSpec()
assert tool_spec.region == "us-west-2"
mock_get_aws_region.assert_called_once()
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.CodeInterpreter"
)
def test_get_or_create_interpreter_new(self, mock_code_interpreter):
mock_instance = MagicMock()
mock_code_interpreter.return_value = mock_instance
tool_spec = AgentCoreCodeInterpreterToolSpec(region="us-east-1")
interpreter = tool_spec._get_or_create_interpreter("test-thread")
assert interpreter == mock_instance
assert "test-thread" in tool_spec._code_interpreters
assert tool_spec._code_interpreters["test-thread"] == mock_instance
mock_code_interpreter.assert_called_once_with(region="us-east-1")
mock_instance.start.assert_called_once()
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.CodeInterpreter"
)
def test_get_or_create_interpreter_existing(self, mock_code_interpreter):
mock_instance = MagicMock()
tool_spec = AgentCoreCodeInterpreterToolSpec(region="us-east-1")
tool_spec._code_interpreters["test-thread"] = mock_instance
interpreter = tool_spec._get_or_create_interpreter("test-thread")
assert interpreter == mock_instance
mock_code_interpreter.assert_not_called()
mock_instance.start.assert_not_called()
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_execute_code(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_response = {
"stream": [
{"result": {"content": [{"type": "text", "text": "Hello World"}]}}
]
}
mock_code_interpreter.invoke.return_value = mock_response
mock_extract_output.return_value = "Hello World"
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
result = tool_spec.execute_code(
code="print('Hello World')",
language="python",
clear_context=True,
thread_id="test-thread",
)
tool_spec._get_or_create_interpreter.assert_called_once_with(
thread_id="test-thread"
)
mock_code_interpreter.invoke.assert_called_once_with(
method="executeCode",
params={
"code": "print('Hello World')",
"language": "python",
"clearContext": True,
},
)
mock_extract_output.assert_called_once_with(mock_response)
assert result == "Hello World"
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_execute_code_exception(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_code_interpreter.invoke.side_effect = Exception("Test error")
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
result = tool_spec.execute_code(
code="print('Hello World')", language="python", thread_id="test-thread"
)
assert "Error executing code: Test error" in result
mock_extract_output.assert_not_called()
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_execute_command(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_response = {
"stream": [
{"result": {"content": [{"type": "text", "text": "command output"}]}}
]
}
mock_code_interpreter.invoke.return_value = mock_response
mock_extract_output.return_value = "command output"
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
result = tool_spec.execute_command(command="ls -la", thread_id="test-thread")
tool_spec._get_or_create_interpreter.assert_called_once_with(
thread_id="test-thread"
)
mock_code_interpreter.invoke.assert_called_once_with(
method="executeCommand", params={"command": "ls -la"}
)
mock_extract_output.assert_called_once_with(mock_response)
assert result == "command output"
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_read_files(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_response = {
"stream": [
{"result": {"content": [{"type": "text", "text": "file content"}]}}
]
}
mock_code_interpreter.invoke.return_value = mock_response
mock_extract_output.return_value = "file content"
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
result = tool_spec.read_files(paths=["/tmp/test.txt"], thread_id="test-thread")
tool_spec._get_or_create_interpreter.assert_called_once_with(
thread_id="test-thread"
)
mock_code_interpreter.invoke.assert_called_once_with(
method="readFiles", params={"paths": ["/tmp/test.txt"]}
)
mock_extract_output.assert_called_once_with(mock_response)
assert result == "file content"
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_list_files(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_response = {
"stream": [
{
"result": {
"content": [{"type": "text", "text": "file1.txt\nfile2.txt"}]
}
}
]
}
mock_code_interpreter.invoke.return_value = mock_response
mock_extract_output.return_value = "file1.txt\nfile2.txt"
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
result = tool_spec.list_files(directory_path="/tmp", thread_id="test-thread")
tool_spec._get_or_create_interpreter.assert_called_once_with(
thread_id="test-thread"
)
mock_code_interpreter.invoke.assert_called_once_with(
method="listFiles", params={"directoryPath": "/tmp"}
)
mock_extract_output.assert_called_once_with(mock_response)
assert result == "file1.txt\nfile2.txt"
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_delete_files(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_response = {
"stream": [
{"result": {"content": [{"type": "text", "text": "Files deleted"}]}}
]
}
mock_code_interpreter.invoke.return_value = mock_response
mock_extract_output.return_value = "Files deleted"
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
result = tool_spec.delete_files(
paths=["/tmp/test.txt"], thread_id="test-thread"
)
tool_spec._get_or_create_interpreter.assert_called_once_with(
thread_id="test-thread"
)
mock_code_interpreter.invoke.assert_called_once_with(
method="removeFiles", params={"paths": ["/tmp/test.txt"]}
)
mock_extract_output.assert_called_once_with(mock_response)
assert result == "Files deleted"
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_write_files(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_response = {
"stream": [
{"result": {"content": [{"type": "text", "text": "Files written"}]}}
]
}
mock_code_interpreter.invoke.return_value = mock_response
mock_extract_output.return_value = "Files written"
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
files = [{"path": "/tmp/test.txt", "text": "Hello World"}]
result = tool_spec.write_files(files=files, thread_id="test-thread")
tool_spec._get_or_create_interpreter.assert_called_once_with(
thread_id="test-thread"
)
mock_code_interpreter.invoke.assert_called_once_with(
method="writeFiles", params={"content": files}
)
mock_extract_output.assert_called_once_with(mock_response)
assert result == "Files written"
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_start_command(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_response = {
"stream": [
{
"result": {
"content": [{"type": "text", "text": "Task started: task-123"}]
}
}
]
}
mock_code_interpreter.invoke.return_value = mock_response
mock_extract_output.return_value = "Task started: task-123"
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
result = tool_spec.start_command(command="sleep 10", thread_id="test-thread")
tool_spec._get_or_create_interpreter.assert_called_once_with(
thread_id="test-thread"
)
mock_code_interpreter.invoke.assert_called_once_with(
method="startCommandExecution", params={"command": "sleep 10"}
)
mock_extract_output.assert_called_once_with(mock_response)
assert result == "Task started: task-123"
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_get_task(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_response = {
"stream": [
{
"result": {
"content": [{"type": "text", "text": "Task status: running"}]
}
}
]
}
mock_code_interpreter.invoke.return_value = mock_response
mock_extract_output.return_value = "Task status: running"
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
result = tool_spec.get_task(task_id="task-123", thread_id="test-thread")
tool_spec._get_or_create_interpreter.assert_called_once_with(
thread_id="test-thread"
)
mock_code_interpreter.invoke.assert_called_once_with(
method="getTask", params={"taskId": "task-123"}
)
mock_extract_output.assert_called_once_with(mock_response)
assert result == "Task status: running"
@patch(
"llama_index.tools.aws_bedrock_agentcore.code_interpreter.base.extract_output_from_stream"
)
def test_stop_task(self, mock_extract_output):
mock_code_interpreter = MagicMock()
mock_response = {
"stream": [
{"result": {"content": [{"type": "text", "text": "Task stopped"}]}}
]
}
mock_code_interpreter.invoke.return_value = mock_response
mock_extract_output.return_value = "Task stopped"
tool_spec = AgentCoreCodeInterpreterToolSpec()
tool_spec._get_or_create_interpreter = MagicMock(
return_value=mock_code_interpreter
)
result = tool_spec.stop_task(task_id="task-123", thread_id="test-thread")
tool_spec._get_or_create_interpreter.assert_called_once_with(
thread_id="test-thread"
)
mock_code_interpreter.invoke.assert_called_once_with(
method="stopTask", params={"taskId": "task-123"}
)
mock_extract_output.assert_called_once_with(mock_response)
assert result == "Task stopped"
| TestAgentCoreCodeInterpreterToolSpec |
python | realpython__materials | nearbyshops/shops/migrations/0002_auto_20181020_0450.py | {
"start": 982,
"end": 1150
} | class ____(migrations.Migration):
dependencies = [
('shops', '0001_initial'),
]
operations = [
migrations.RunPython(load_data)
]
| Migration |
python | langchain-ai__langchain | libs/core/langchain_core/tracers/event_stream.py | {
"start": 2342,
"end": 34966
} | class ____(AsyncCallbackHandler, _StreamingCallbackHandler):
"""An implementation of an async callback handler for astream events."""
def __init__(
self,
*args: Any,
include_names: Sequence[str] | None = None,
include_types: Sequence[str] | None = None,
include_tags: Sequence[str] | None = None,
exclude_names: Sequence[str] | None = None,
exclude_types: Sequence[str] | None = None,
exclude_tags: Sequence[str] | None = None,
**kwargs: Any,
) -> None:
"""Initialize the tracer."""
super().__init__(*args, **kwargs)
# Map of run ID to run info.
# the entry corresponding to a given run id is cleaned
# up when each corresponding run ends.
self.run_map: dict[UUID, RunInfo] = {}
# The callback event that corresponds to the end of a parent run
# may be invoked BEFORE the callback event that corresponds to the end
# of a child run, which results in clean up of run_map.
# So we keep track of the mapping between children and parent run IDs
# in a separate container. This container is GCed when the tracer is GCed.
self.parent_map: dict[UUID, UUID | None] = {}
self.is_tapped: dict[UUID, Any] = {}
# Filter which events will be sent over the queue.
self.root_event_filter = _RootEventFilter(
include_names=include_names,
include_types=include_types,
include_tags=include_tags,
exclude_names=exclude_names,
exclude_types=exclude_types,
exclude_tags=exclude_tags,
)
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
memory_stream = _MemoryStream[StreamEvent](loop)
self.send_stream = memory_stream.get_send_stream()
self.receive_stream = memory_stream.get_receive_stream()
def _get_parent_ids(self, run_id: UUID) -> list[str]:
"""Get the parent IDs of a run (non-recursively) cast to strings."""
parent_ids = []
while parent_id := self.parent_map.get(run_id):
str_parent_id = str(parent_id)
if str_parent_id in parent_ids:
msg = (
f"Parent ID {parent_id} is already in the parent_ids list. "
f"This should never happen."
)
raise AssertionError(msg)
parent_ids.append(str_parent_id)
run_id = parent_id
# Return the parent IDs in reverse order, so that the first
# parent ID is the root and the last ID is the immediate parent.
return parent_ids[::-1]
def _send(self, event: StreamEvent, event_type: str) -> None:
"""Send an event to the stream."""
if self.root_event_filter.include_event(event, event_type):
self.send_stream.send_nowait(event)
def __aiter__(self) -> AsyncIterator[Any]:
"""Iterate over the receive stream.
Returns:
An async iterator over the receive stream.
"""
return self.receive_stream.__aiter__()
async def tap_output_aiter(
self, run_id: UUID, output: AsyncIterator[T]
) -> AsyncIterator[T]:
"""Tap the output aiter.
This method is used to tap the output of a Runnable that produces
an async iterator. It is used to generate stream events for the
output of the Runnable.
Args:
run_id: The ID of the run.
output: The output of the Runnable.
Yields:
The output of the Runnable.
"""
sentinel = object()
# atomic check and set
tap = self.is_tapped.setdefault(run_id, sentinel)
# wait for first chunk
first = await py_anext(output, default=sentinel)
if first is sentinel:
return
# get run info
run_info = self.run_map.get(run_id)
if run_info is None:
# run has finished, don't issue any stream events
yield cast("T", first)
return
if tap is sentinel:
# if we are the first to tap, issue stream events
event: StandardStreamEvent = {
"event": f"on_{run_info['run_type']}_stream",
"run_id": str(run_id),
"name": run_info["name"],
"tags": run_info["tags"],
"metadata": run_info["metadata"],
"data": {},
"parent_ids": self._get_parent_ids(run_id),
}
self._send({**event, "data": {"chunk": first}}, run_info["run_type"])
yield cast("T", first)
# consume the rest of the output
async for chunk in output:
self._send(
{**event, "data": {"chunk": chunk}},
run_info["run_type"],
)
yield chunk
else:
# otherwise just pass through
yield cast("T", first)
# consume the rest of the output
async for chunk in output:
yield chunk
def tap_output_iter(self, run_id: UUID, output: Iterator[T]) -> Iterator[T]:
"""Tap the output iter.
Args:
run_id: The ID of the run.
output: The output of the Runnable.
Yields:
The output of the Runnable.
"""
sentinel = object()
# atomic check and set
tap = self.is_tapped.setdefault(run_id, sentinel)
# wait for first chunk
first = next(output, sentinel)
if first is sentinel:
return
# get run info
run_info = self.run_map.get(run_id)
if run_info is None:
# run has finished, don't issue any stream events
yield cast("T", first)
return
if tap is sentinel:
# if we are the first to tap, issue stream events
event: StandardStreamEvent = {
"event": f"on_{run_info['run_type']}_stream",
"run_id": str(run_id),
"name": run_info["name"],
"tags": run_info["tags"],
"metadata": run_info["metadata"],
"data": {},
"parent_ids": self._get_parent_ids(run_id),
}
self._send({**event, "data": {"chunk": first}}, run_info["run_type"])
yield cast("T", first)
# consume the rest of the output
for chunk in output:
self._send(
{**event, "data": {"chunk": chunk}},
run_info["run_type"],
)
yield chunk
else:
# otherwise just pass through
yield cast("T", first)
# consume the rest of the output
for chunk in output:
yield chunk
def _write_run_start_info(
self,
run_id: UUID,
*,
tags: list[str] | None,
metadata: dict[str, Any] | None,
parent_run_id: UUID | None,
name_: str,
run_type: str,
**kwargs: Any,
) -> None:
"""Update the run info."""
info: RunInfo = {
"tags": tags or [],
"metadata": metadata or {},
"name": name_,
"run_type": run_type,
"parent_run_id": parent_run_id,
}
if "inputs" in kwargs:
# Handle inputs in a special case to allow inputs to be an
# optionally provided and distinguish between missing value
# vs. None value.
info["inputs"] = kwargs["inputs"]
self.run_map[run_id] = info
self.parent_map[run_id] = parent_run_id
@override
async def on_chat_model_start(
self,
serialized: dict[str, Any],
messages: list[list[BaseMessage]],
*,
run_id: UUID,
tags: list[str] | None = None,
parent_run_id: UUID | None = None,
metadata: dict[str, Any] | None = None,
name: str | None = None,
**kwargs: Any,
) -> None:
"""Start a trace for a chat model run."""
name_ = _assign_name(name, serialized)
run_type = "chat_model"
self._write_run_start_info(
run_id,
tags=tags,
metadata=metadata,
parent_run_id=parent_run_id,
name_=name_,
run_type=run_type,
inputs={"messages": messages},
)
self._send(
{
"event": "on_chat_model_start",
"data": {
"input": {"messages": messages},
},
"name": name_,
"tags": tags or [],
"run_id": str(run_id),
"metadata": metadata or {},
"parent_ids": self._get_parent_ids(run_id),
},
run_type,
)
@override
async def on_llm_start(
self,
serialized: dict[str, Any],
prompts: list[str],
*,
run_id: UUID,
tags: list[str] | None = None,
parent_run_id: UUID | None = None,
metadata: dict[str, Any] | None = None,
name: str | None = None,
**kwargs: Any,
) -> None:
"""Start a trace for a (non-chat model) LLM run."""
name_ = _assign_name(name, serialized)
run_type = "llm"
self._write_run_start_info(
run_id,
tags=tags,
metadata=metadata,
parent_run_id=parent_run_id,
name_=name_,
run_type=run_type,
inputs={"prompts": prompts},
)
self._send(
{
"event": "on_llm_start",
"data": {
"input": {
"prompts": prompts,
}
},
"name": name_,
"tags": tags or [],
"run_id": str(run_id),
"metadata": metadata or {},
"parent_ids": self._get_parent_ids(run_id),
},
run_type,
)
@override
async def on_custom_event(
self,
name: str,
data: Any,
*,
run_id: UUID,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
"""Generate a custom astream event."""
event = CustomStreamEvent(
event="on_custom_event",
run_id=str(run_id),
name=name,
tags=tags or [],
metadata=metadata or {},
data=data,
parent_ids=self._get_parent_ids(run_id),
)
self._send(event, name)
@override
async def on_llm_new_token(
self,
token: str,
*,
chunk: GenerationChunk | ChatGenerationChunk | None = None,
run_id: UUID,
parent_run_id: UUID | None = None,
**kwargs: Any,
) -> None:
"""Run on new output token. Only available when streaming is enabled.
For both chat models and non-chat models (legacy LLMs).
"""
run_info = self.run_map.get(run_id)
chunk_: GenerationChunk | BaseMessageChunk
if run_info is None:
msg = f"Run ID {run_id} not found in run map."
raise AssertionError(msg)
if self.is_tapped.get(run_id):
return
if run_info["run_type"] == "chat_model":
event = "on_chat_model_stream"
if chunk is None:
chunk_ = AIMessageChunk(content=token)
else:
chunk_ = cast("ChatGenerationChunk", chunk).message
elif run_info["run_type"] == "llm":
event = "on_llm_stream"
if chunk is None:
chunk_ = GenerationChunk(text=token)
else:
chunk_ = cast("GenerationChunk", chunk)
else:
msg = f"Unexpected run type: {run_info['run_type']}"
raise ValueError(msg)
self._send(
{
"event": event,
"data": {
"chunk": chunk_,
},
"run_id": str(run_id),
"name": run_info["name"],
"tags": run_info["tags"],
"metadata": run_info["metadata"],
"parent_ids": self._get_parent_ids(run_id),
},
run_info["run_type"],
)
@override
async def on_llm_end(
self, response: LLMResult, *, run_id: UUID, **kwargs: Any
) -> None:
"""End a trace for a model run.
For both chat models and non-chat models (legacy LLMs).
Raises:
ValueError: If the run type is not `'llm'` or `'chat_model'`.
"""
run_info = self.run_map.pop(run_id)
inputs_ = run_info.get("inputs")
generations: list[list[GenerationChunk]] | list[list[ChatGenerationChunk]]
output: dict | BaseMessage = {}
if run_info["run_type"] == "chat_model":
generations = cast("list[list[ChatGenerationChunk]]", response.generations)
for gen in generations:
if output != {}:
break
for chunk in gen:
output = chunk.message
break
event = "on_chat_model_end"
elif run_info["run_type"] == "llm":
generations = cast("list[list[GenerationChunk]]", response.generations)
output = {
"generations": [
[
{
"text": chunk.text,
"generation_info": chunk.generation_info,
"type": chunk.type,
}
for chunk in gen
]
for gen in generations
],
"llm_output": response.llm_output,
}
event = "on_llm_end"
else:
msg = f"Unexpected run type: {run_info['run_type']}"
raise ValueError(msg)
self._send(
{
"event": event,
"data": {"output": output, "input": inputs_},
"run_id": str(run_id),
"name": run_info["name"],
"tags": run_info["tags"],
"metadata": run_info["metadata"],
"parent_ids": self._get_parent_ids(run_id),
},
run_info["run_type"],
)
async def on_chain_start(
self,
serialized: dict[str, Any],
inputs: dict[str, Any],
*,
run_id: UUID,
tags: list[str] | None = None,
parent_run_id: UUID | None = None,
metadata: dict[str, Any] | None = None,
run_type: str | None = None,
name: str | None = None,
**kwargs: Any,
) -> None:
"""Start a trace for a chain run."""
name_ = _assign_name(name, serialized)
run_type_ = run_type or "chain"
data: EventData = {}
# Work-around Runnable core code not sending input in some
# cases.
if inputs != {"input": ""}:
data["input"] = inputs
kwargs["inputs"] = inputs
self._write_run_start_info(
run_id,
tags=tags,
metadata=metadata,
parent_run_id=parent_run_id,
name_=name_,
run_type=run_type_,
**kwargs,
)
self._send(
{
"event": f"on_{run_type_}_start",
"data": data,
"name": name_,
"tags": tags or [],
"run_id": str(run_id),
"metadata": metadata or {},
"parent_ids": self._get_parent_ids(run_id),
},
run_type_,
)
@override
async def on_chain_end(
self,
outputs: dict[str, Any],
*,
run_id: UUID,
inputs: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
"""End a trace for a chain run."""
run_info = self.run_map.pop(run_id)
run_type = run_info["run_type"]
event = f"on_{run_type}_end"
inputs = inputs or run_info.get("inputs") or {}
data: EventData = {
"output": outputs,
"input": inputs,
}
self._send(
{
"event": event,
"data": data,
"run_id": str(run_id),
"name": run_info["name"],
"tags": run_info["tags"],
"metadata": run_info["metadata"],
"parent_ids": self._get_parent_ids(run_id),
},
run_type,
)
def _get_tool_run_info_with_inputs(self, run_id: UUID) -> tuple[RunInfo, Any]:
"""Get run info for a tool and extract inputs, with validation.
Args:
run_id: The run ID of the tool.
Returns:
A tuple of (run_info, inputs).
Raises:
AssertionError: If the run ID is a tool call and does not have inputs.
"""
run_info = self.run_map.pop(run_id)
if "inputs" not in run_info:
msg = (
f"Run ID {run_id} is a tool call and is expected to have "
f"inputs associated with it."
)
raise AssertionError(msg)
inputs = run_info["inputs"]
return run_info, inputs
@override
async def on_tool_start(
self,
serialized: dict[str, Any],
input_str: str,
*,
run_id: UUID,
tags: list[str] | None = None,
parent_run_id: UUID | None = None,
metadata: dict[str, Any] | None = None,
name: str | None = None,
inputs: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
"""Start a trace for a tool run."""
name_ = _assign_name(name, serialized)
self._write_run_start_info(
run_id,
tags=tags,
metadata=metadata,
parent_run_id=parent_run_id,
name_=name_,
run_type="tool",
inputs=inputs,
)
self._send(
{
"event": "on_tool_start",
"data": {
"input": inputs or {},
},
"name": name_,
"tags": tags or [],
"run_id": str(run_id),
"metadata": metadata or {},
"parent_ids": self._get_parent_ids(run_id),
},
"tool",
)
@override
async def on_tool_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: UUID | None = None,
tags: list[str] | None = None,
**kwargs: Any,
) -> None:
"""Run when tool errors."""
run_info, inputs = self._get_tool_run_info_with_inputs(run_id)
self._send(
{
"event": "on_tool_error",
"data": {
"error": error,
"input": inputs,
},
"run_id": str(run_id),
"name": run_info["name"],
"tags": run_info["tags"],
"metadata": run_info["metadata"],
"parent_ids": self._get_parent_ids(run_id),
},
"tool",
)
@override
async def on_tool_end(self, output: Any, *, run_id: UUID, **kwargs: Any) -> None:
"""End a trace for a tool run.
Raises:
AssertionError: If the run ID is a tool call and does not have inputs
"""
run_info, inputs = self._get_tool_run_info_with_inputs(run_id)
self._send(
{
"event": "on_tool_end",
"data": {
"output": output,
"input": inputs,
},
"run_id": str(run_id),
"name": run_info["name"],
"tags": run_info["tags"],
"metadata": run_info["metadata"],
"parent_ids": self._get_parent_ids(run_id),
},
"tool",
)
@override
async def on_retriever_start(
self,
serialized: dict[str, Any],
query: str,
*,
run_id: UUID,
parent_run_id: UUID | None = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
name: str | None = None,
**kwargs: Any,
) -> None:
"""Run when Retriever starts running."""
name_ = _assign_name(name, serialized)
run_type = "retriever"
self._write_run_start_info(
run_id,
tags=tags,
metadata=metadata,
parent_run_id=parent_run_id,
name_=name_,
run_type=run_type,
inputs={"query": query},
)
self._send(
{
"event": "on_retriever_start",
"data": {
"input": {
"query": query,
}
},
"name": name_,
"tags": tags or [],
"run_id": str(run_id),
"metadata": metadata or {},
"parent_ids": self._get_parent_ids(run_id),
},
run_type,
)
@override
async def on_retriever_end(
self, documents: Sequence[Document], *, run_id: UUID, **kwargs: Any
) -> None:
"""Run when Retriever ends running."""
run_info = self.run_map.pop(run_id)
self._send(
{
"event": "on_retriever_end",
"data": {
"output": documents,
"input": run_info.get("inputs"),
},
"run_id": str(run_id),
"name": run_info["name"],
"tags": run_info["tags"],
"metadata": run_info["metadata"],
"parent_ids": self._get_parent_ids(run_id),
},
run_info["run_type"],
)
def __deepcopy__(self, memo: dict) -> _AstreamEventsCallbackHandler:
"""Return self."""
return self
def __copy__(self) -> _AstreamEventsCallbackHandler:
"""Return self."""
return self
async def _astream_events_implementation_v1(
runnable: Runnable[Input, Output],
value: Any,
config: RunnableConfig | None = None,
*,
include_names: Sequence[str] | None = None,
include_types: Sequence[str] | None = None,
include_tags: Sequence[str] | None = None,
exclude_names: Sequence[str] | None = None,
exclude_types: Sequence[str] | None = None,
exclude_tags: Sequence[str] | None = None,
**kwargs: Any,
) -> AsyncIterator[StandardStreamEvent]:
stream = LogStreamCallbackHandler(
auto_close=False,
include_names=include_names,
include_types=include_types,
include_tags=include_tags,
exclude_names=exclude_names,
exclude_types=exclude_types,
exclude_tags=exclude_tags,
_schema_format="streaming_events",
)
run_log = RunLog(state=None) # type: ignore[arg-type]
encountered_start_event = False
root_event_filter = _RootEventFilter(
include_names=include_names,
include_types=include_types,
include_tags=include_tags,
exclude_names=exclude_names,
exclude_types=exclude_types,
exclude_tags=exclude_tags,
)
config = ensure_config(config)
root_tags = config.get("tags", [])
root_metadata = config.get("metadata", {})
root_name = config.get("run_name", runnable.get_name())
async for log in _astream_log_implementation(
runnable,
value,
config=config,
stream=stream,
diff=True,
with_streamed_output_list=True,
**kwargs,
):
run_log += log
if not encountered_start_event:
# Yield the start event for the root runnable.
encountered_start_event = True
state = run_log.state.copy()
event = StandardStreamEvent(
event=f"on_{state['type']}_start",
run_id=state["id"],
name=root_name,
tags=root_tags,
metadata=root_metadata,
data={
"input": value,
},
parent_ids=[], # Not supported in v1
)
if root_event_filter.include_event(event, state["type"]):
yield event
paths = {
op["path"].split("/")[2]
for op in log.ops
if op["path"].startswith("/logs/")
}
# Elements in a set should be iterated in the same order
# as they were inserted in modern python versions.
for path in paths:
data: EventData = {}
log_entry: LogEntry = run_log.state["logs"][path]
if log_entry["end_time"] is None:
event_type = "stream" if log_entry["streamed_output"] else "start"
else:
event_type = "end"
if event_type == "start":
# Include the inputs with the start event if they are available.
# Usually they will NOT be available for components that operate
# on streams, since those components stream the input and
# don't know its final value until the end of the stream.
inputs = log_entry.get("inputs")
if inputs is not None:
data["input"] = inputs
if event_type == "end":
inputs = log_entry.get("inputs")
if inputs is not None:
data["input"] = inputs
# None is a VALID output for an end event
data["output"] = log_entry["final_output"]
if event_type == "stream":
num_chunks = len(log_entry["streamed_output"])
if num_chunks != 1:
msg = (
f"Expected exactly one chunk of streamed output, "
f"got {num_chunks} instead. This is impossible. "
f"Encountered in: {log_entry['name']}"
)
raise AssertionError(msg)
data = {"chunk": log_entry["streamed_output"][0]}
# Clean up the stream, we don't need it anymore.
# And this avoids duplicates as well!
log_entry["streamed_output"] = []
yield StandardStreamEvent(
event=f"on_{log_entry['type']}_{event_type}",
name=log_entry["name"],
run_id=log_entry["id"],
tags=log_entry["tags"],
metadata=log_entry["metadata"],
data=data,
parent_ids=[], # Not supported in v1
)
# Finally, we take care of the streaming output from the root chain
# if there is any.
state = run_log.state
if state["streamed_output"]:
num_chunks = len(state["streamed_output"])
if num_chunks != 1:
msg = (
f"Expected exactly one chunk of streamed output, "
f"got {num_chunks} instead. This is impossible. "
f"Encountered in: {state['name']}"
)
raise AssertionError(msg)
data = {"chunk": state["streamed_output"][0]}
# Clean up the stream, we don't need it anymore.
state["streamed_output"] = []
event = StandardStreamEvent(
event=f"on_{state['type']}_stream",
run_id=state["id"],
tags=root_tags,
metadata=root_metadata,
name=root_name,
data=data,
parent_ids=[], # Not supported in v1
)
if root_event_filter.include_event(event, state["type"]):
yield event
state = run_log.state
# Finally yield the end event for the root runnable.
event = StandardStreamEvent(
event=f"on_{state['type']}_end",
name=root_name,
run_id=state["id"],
tags=root_tags,
metadata=root_metadata,
data={
"output": state["final_output"],
},
parent_ids=[], # Not supported in v1
)
if root_event_filter.include_event(event, state["type"]):
yield event
async def _astream_events_implementation_v2(
runnable: Runnable[Input, Output],
value: Any,
config: RunnableConfig | None = None,
*,
include_names: Sequence[str] | None = None,
include_types: Sequence[str] | None = None,
include_tags: Sequence[str] | None = None,
exclude_names: Sequence[str] | None = None,
exclude_types: Sequence[str] | None = None,
exclude_tags: Sequence[str] | None = None,
**kwargs: Any,
) -> AsyncIterator[StandardStreamEvent]:
"""Implementation of the astream events API for V2 runnables."""
event_streamer = _AstreamEventsCallbackHandler(
include_names=include_names,
include_types=include_types,
include_tags=include_tags,
exclude_names=exclude_names,
exclude_types=exclude_types,
exclude_tags=exclude_tags,
)
# Assign the stream handler to the config
config = ensure_config(config)
run_id = cast("UUID", config.setdefault("run_id", uuid4()))
callbacks = config.get("callbacks")
if callbacks is None:
config["callbacks"] = [event_streamer]
elif isinstance(callbacks, list):
config["callbacks"] = [*callbacks, event_streamer]
elif isinstance(callbacks, BaseCallbackManager):
callbacks = callbacks.copy()
callbacks.add_handler(event_streamer, inherit=True)
config["callbacks"] = callbacks
else:
msg = (
f"Unexpected type for callbacks: {callbacks}."
"Expected None, list or AsyncCallbackManager."
)
raise ValueError(msg)
# Call the runnable in streaming mode,
# add each chunk to the output stream
async def consume_astream() -> None:
try:
# if astream also calls tap_output_aiter this will be a no-op
async with aclosing(runnable.astream(value, config, **kwargs)) as stream:
async for _ in event_streamer.tap_output_aiter(run_id, stream):
# All the content will be picked up
pass
finally:
await event_streamer.send_stream.aclose()
# Start the runnable in a task, so we can start consuming output
task = asyncio.create_task(consume_astream())
first_event_sent = False
first_event_run_id = None
try:
async for event in event_streamer:
if not first_event_sent:
first_event_sent = True
# This is a work-around an issue where the inputs into the
# chain are not available until the entire input is consumed.
# As a temporary solution, we'll modify the input to be the input
# that was passed into the chain.
event["data"]["input"] = value
first_event_run_id = event["run_id"]
yield event
continue
# If it's the end event corresponding to the root runnable
# we don't include the input in the event since it's guaranteed
# to be included in the first event.
if (
event["run_id"] == first_event_run_id
and event["event"].endswith("_end")
and "input" in event["data"]
):
del event["data"]["input"]
yield event
except asyncio.CancelledError as exc:
# Cancel the task if it's still running
task.cancel(exc.args[0] if exc.args else None)
raise
finally:
# Cancel the task if it's still running
task.cancel()
# Await it anyway, to run any cleanup code, and propagate any exceptions
with contextlib.suppress(asyncio.CancelledError):
await task
| _AstreamEventsCallbackHandler |
python | django-extensions__django-extensions | tests/management/commands/test_drop_test_database.py | {
"start": 1360,
"end": 2420
} | class ____(TestCase):
"""Test for drop_test_database command."""
def test_should_raise_CommandError_if_database_is_unknown(self):
with self.assertRaisesRegex(CommandError, "Unknown database unknown"):
call_command("drop_test_database", "--database=unknown")
@override_settings(DATABASES=UNKOWN_ENGINE)
@patch("django_extensions.management.commands.drop_test_database.input")
def test_should_raise_CommandError_if_unknown_database_engine(self, m_input):
m_input.return_value = "yes"
with self.assertRaisesRegex(
CommandError, "Unknown database engine django.db.backends.unknown"
):
call_command("drop_test_database")
@override_settings(DATABASES=NO_TEST_NAME)
def test_should_raise_CommandError_if_test_database_name_is_empty(self):
with self.assertRaisesRegex(
CommandError,
"You need to specify DATABASE_NAME in your Django settings file.",
):
call_command("drop_test_database")
| DropTestDatabaseExceptionsTests |
python | sphinx-doc__sphinx | sphinx/theming.py | {
"start": 1395,
"end": 4889
} | class ____:
"""A Theme is a set of HTML templates and configurations.
This class supports both theme directory and theme archive (zipped theme).
"""
def __init__(
self,
name: str,
*,
configs: dict[str, _ConfigFile],
paths: list[Path],
tmp_dirs: list[Path],
) -> None:
self.name = name
self._dirs = tuple(paths)
self._tmp_dirs = tmp_dirs
options: dict[str, Any] = {}
self.stylesheets: tuple[str, ...] = ()
self.sidebar_templates: tuple[str, ...] = ()
self.pygments_style_default: str | None = None
self.pygments_style_dark: str | None = None
for config in reversed(configs.values()):
options |= config.options
if config.stylesheets is not None:
self.stylesheets = config.stylesheets
if config.sidebar_templates is not None:
self.sidebar_templates = config.sidebar_templates
if config.pygments_style_default is not None:
self.pygments_style_default = config.pygments_style_default
if config.pygments_style_dark is not None:
self.pygments_style_dark = config.pygments_style_dark
self._options = options
def get_theme_dirs(self) -> list[_StrPath]:
"""Return a list of theme directories, beginning with this theme's,
then the base theme's, then that one's base theme's, etc.
"""
return list(map(_StrPath, self._dirs))
def get_config(self, section: str, name: str, default: Any = _NO_DEFAULT) -> Any:
"""Return the value for a theme configuration setting, searching the
base theme chain.
"""
if section == 'theme':
if name == 'stylesheet':
value = ', '.join(self.stylesheets) or default
elif name == 'sidebars':
value = ', '.join(self.sidebar_templates) or default
elif name == 'pygments_style':
value = self.pygments_style_default or default
elif name == 'pygments_dark_style':
value = self.pygments_style_dark or default
else:
value = default
elif section == 'options':
value = self._options.get(name, default)
else:
msg = __(
'Theme configuration sections other than [theme] and [options] '
'are not supported (tried to get a value from %r).'
)
raise ThemeError(msg)
if value is _NO_DEFAULT:
msg = __('setting %s.%s occurs in none of the searched theme configs') % (
section,
name,
)
raise ThemeError(msg)
return value
def get_options(self, overrides: dict[str, Any] | None = None) -> dict[str, Any]:
"""Return a dictionary of theme options and their values."""
if overrides is None:
overrides = {}
options = self._options.copy()
for option, value in overrides.items():
if option not in options:
logger.warning(__('unsupported theme option %r given'), option)
else:
options[option] = value
return options
def _cleanup(self) -> None:
"""Remove temporary directories."""
for tmp_dir in self._tmp_dirs:
with contextlib.suppress(Exception):
shutil.rmtree(tmp_dir)
| Theme |
python | kamyu104__LeetCode-Solutions | Python/count-almost-equal-pairs-ii.py | {
"start": 1536,
"end": 2879
} | class ____(object):
def countPairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
L = 7
K = 2
POW10 = [0]*L
POW10[0] = 1
for i in xrange(L-1):
POW10[i+1] = POW10[i]*10
def at_most(k, x):
lookup = {x}
result = [x]
u = 0
for _ in xrange(k):
for u in xrange(u, len(result)):
x = result[u]
for i in xrange(L):
a = x//POW10[i]%10
for j in xrange(i+1, L):
b = x//POW10[j]%10
if a == b:
continue
y = x-a*(POW10[i]-POW10[j])+b*(POW10[i]-POW10[j])
if y in lookup:
continue
lookup.add(y)
result.append(y)
return result
result = 0
cnt1 = collections.Counter(nums)
cnt2 = collections.Counter()
for x, v in cnt1.iteritems():
result += cnt2[x]*v+v*(v-1)//2
for x in at_most(K, x):
if x not in cnt1:
continue
cnt2[x] += v
return result
| Solution2 |
python | kamyu104__LeetCode-Solutions | Python/maximum-score-of-a-good-subarray.py | {
"start": 29,
"end": 744
} | class ____(object):
def maximumScore(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result = curr = nums[k]
left = right = k
while left-1 >= 0 or right+1 < len(nums):
# choosing larger one to expand is always better than or equal to choosing smaller one
if (nums[left-1] if left-1 >= 0 else 0) <= (nums[right+1] if right+1 < len(nums) else 0):
right += 1
else:
left -= 1
curr = min(curr, nums[left], nums[right])
result = max(result, curr*(right-left+1))
return result
# Time: O(nlogn)
# Space: O(n)
import bisect
| Solution |
python | astropy__astropy | astropy/units/tests/test_logarithmic.py | {
"start": 24678,
"end": 33261
} | class ____:
@pytest.mark.parametrize(
"other",
[
2.4 * u.mag(),
12.34 * u.ABmag,
u.Magnitude(3.45 * u.Jy),
u.Dex(3.0),
u.Dex(np.linspace(3000, 5000, 10) * u.Angstrom),
u.Magnitude(6.78, 2.0 * u.mag),
],
)
@pytest.mark.parametrize("fac", [1.0, 2, 0.4])
def test_multiplication_division(self, other, fac):
"""Check that multiplication and division work as expected"""
lq_sf = fac * other
assert lq_sf.unit.physical_unit == other.unit.physical_unit**fac
assert_allclose(lq_sf.physical, other.physical**fac)
lq_sf = other * fac
assert lq_sf.unit.physical_unit == other.unit.physical_unit**fac
assert_allclose(lq_sf.physical, other.physical**fac)
lq_sf = other / fac
assert lq_sf.unit.physical_unit**fac == other.unit.physical_unit
assert_allclose(lq_sf.physical**fac, other.physical)
lq_sf = other.copy()
lq_sf *= fac
assert lq_sf.unit.physical_unit == other.unit.physical_unit**fac
assert_allclose(lq_sf.physical, other.physical**fac)
lq_sf = other.copy()
lq_sf /= fac
assert lq_sf.unit.physical_unit**fac == other.unit.physical_unit
assert_allclose(lq_sf.physical**fac, other.physical)
def test_more_multiplication_division(self):
"""Check that multiplication/division with other quantities is only
possible when the physical unit is dimensionless, and that this keeps
the result as a LogQuantity if possible."""
lq = u.Magnitude(np.arange(1.0, 11.0) * u.Jy)
with pytest.raises(u.UnitsError):
lq * (1.0 * u.m)
with pytest.raises(u.UnitsError):
(1.0 * u.m) * lq
with pytest.raises(u.UnitsError):
lq / lq
for unit in (u.m, u.mag, u.dex):
with pytest.raises(u.UnitsError):
lq / unit
lq2 = u.Magnitude(np.arange(1, 11.0))
with pytest.raises(u.UnitsError):
lq2 * lq
with pytest.raises(u.UnitsError):
lq2 / lq
with pytest.raises(u.UnitsError):
lq / lq2
lq_sf = lq.copy()
with pytest.raises(u.UnitsError):
lq_sf *= lq2
# ensure that nothing changed inside
assert (lq_sf == lq).all()
with pytest.raises(u.UnitsError):
lq_sf /= lq2
# ensure that nothing changed inside
assert (lq_sf == lq).all()
# but dimensionless_unscaled can be cancelled
r = lq2 / u.Magnitude(2.0)
assert r.unit == u.dimensionless_unscaled
assert np.all(r.value == lq2.value / 2.0)
# And multiplying with a dimensionless array is also OK.
r2 = lq2 * np.arange(10.0)
assert isinstance(r2, u.Magnitude)
assert np.all(r2 == lq2._function_view * np.arange(10.0))
# with dimensionless, normal units OK, but return normal quantities
# if the unit no longer is consistent with the logarithmic unit.
tf = lq2 * u.m
tr = u.m * lq2
for t in (tf, tr):
assert not isinstance(t, type(lq2))
assert t.unit == lq2.unit.function_unit * u.m
with u.set_enabled_equivalencies(u.logarithmic()):
with pytest.raises(u.UnitsError):
t.to(lq2.unit.physical_unit)
t = tf / (50.0 * u.cm)
# now we essentially have the same quantity but with a prefactor of 2
assert t.unit.is_equivalent(lq2.unit.function_unit)
assert_allclose(t.to(lq2.unit.function_unit), lq2._function_view * 2)
@pytest.mark.parametrize("power", (2, 0.5, 1, 0))
def test_raise_to_power(self, power):
"""Check that raising LogQuantities to some power is only possible when
the physical unit is dimensionless, and that conversion is turned off
when the resulting logarithmic unit (say, mag**2) is incompatible."""
lq = u.Magnitude(np.arange(1.0, 4.0) * u.Jy)
if power == 0:
assert np.all(lq**power == 1.0)
elif power == 1:
assert np.all(lq**power == lq)
else:
with pytest.raises(u.UnitsError):
lq**power
# with dimensionless, it works, but falls back to normal quantity
# (except for power=1)
lq2 = u.Magnitude(np.arange(10.0))
t = lq2**power
if power == 0:
assert t.unit is u.dimensionless_unscaled
assert np.all(t.value == 1.0)
elif power == 1:
assert np.all(t == lq2)
else:
assert not isinstance(t, type(lq2))
assert t.unit == lq2.unit.function_unit**power
with u.set_enabled_equivalencies(u.logarithmic()):
with pytest.raises(u.UnitsError):
t.to(u.dimensionless_unscaled)
def test_error_on_lq_as_power(self):
lq = u.Magnitude(np.arange(1.0, 4.0) * u.Jy)
with pytest.raises(TypeError):
lq**lq
@pytest.mark.parametrize("other", pu_sample)
def test_addition_subtraction_to_normal_units_fails(self, other):
lq = u.Magnitude(np.arange(1.0, 10.0) * u.Jy)
q = 1.23 * other
with pytest.raises(u.UnitsError):
lq + q
with pytest.raises(u.UnitsError):
lq - q
with pytest.raises(u.UnitsError):
q - lq
@pytest.mark.parametrize(
"other",
(
1.23 * u.mag,
2.34 * u.mag(),
u.Magnitude(3.45 * u.Jy),
u.Magnitude(4.56 * u.m),
5.67 * u.Unit(2 * u.mag),
u.Magnitude(6.78, 2.0 * u.mag),
),
)
def test_addition_subtraction(self, other):
"""Check that addition/subtraction with quantities with magnitude or
MagUnit units works, and that it changes the physical units
appropriately."""
lq = u.Magnitude(np.arange(1.0, 10.0) * u.Jy)
other_physical = other.to(
getattr(other.unit, "physical_unit", u.dimensionless_unscaled),
equivalencies=u.logarithmic(),
)
lq_sf = lq + other
assert_allclose(lq_sf.physical, lq.physical * other_physical)
lq_sr = other + lq
assert_allclose(lq_sr.physical, lq.physical * other_physical)
lq_df = lq - other
assert_allclose(lq_df.physical, lq.physical / other_physical)
lq_dr = other - lq
assert_allclose(lq_dr.physical, other_physical / lq.physical)
@pytest.mark.parametrize("other", pu_sample)
def test_inplace_addition_subtraction_unit_checks(self, other):
lu1 = u.mag(u.Jy)
lq1 = u.Magnitude(np.arange(1.0, 10.0), lu1)
with pytest.raises(u.UnitsError):
lq1 += other
assert np.all(lq1.value == np.arange(1.0, 10.0))
assert lq1.unit == lu1
with pytest.raises(u.UnitsError):
lq1 -= other
assert np.all(lq1.value == np.arange(1.0, 10.0))
assert lq1.unit == lu1
@pytest.mark.parametrize(
"other",
(
1.23 * u.mag,
2.34 * u.mag(),
u.Magnitude(3.45 * u.Jy),
u.Magnitude(4.56 * u.m),
5.67 * u.Unit(2 * u.mag),
u.Magnitude(6.78, 2.0 * u.mag),
),
)
def test_inplace_addition_subtraction(self, other):
"""Check that inplace addition/subtraction with quantities with
magnitude or MagUnit units works, and that it changes the physical
units appropriately."""
lq = u.Magnitude(np.arange(1.0, 10.0) * u.Jy)
other_physical = other.to(
getattr(other.unit, "physical_unit", u.dimensionless_unscaled),
equivalencies=u.logarithmic(),
)
lq_sf = lq.copy()
lq_sf += other
assert_allclose(lq_sf.physical, lq.physical * other_physical)
lq_df = lq.copy()
lq_df -= other
assert_allclose(lq_df.physical, lq.physical / other_physical)
def test_complicated_addition_subtraction(self):
"""For fun, a more complicated example of addition and subtraction."""
dm0 = u.Unit("DM", 1.0 / (4.0 * np.pi * (10.0 * u.pc) ** 2))
DMmag = u.mag(dm0)
m_st = 10.0 * u.STmag
dm = 5.0 * DMmag
M_st = m_st - dm
assert M_st.unit.is_equivalent(u.erg / u.s / u.AA)
ratio = M_st.physical / (m_st.physical * 4.0 * np.pi * (100.0 * u.pc) ** 2)
assert np.abs(ratio - 1.0) < 1.0e-15
| TestLogQuantityArithmetic |
python | doocs__leetcode | solution/3100-3199/3196.Maximize Total Cost of Alternating Subarrays/Solution2.py | {
"start": 0,
"end": 183
} | class ____:
def maximumTotalCost(self, nums: List[int]) -> int:
f, g = -inf, 0
for x in nums:
f, g = max(f, g) + x, f - x
return max(f, g)
| Solution |
python | doocs__leetcode | solution/1800-1899/1827.Minimum Operations to Make the Array Increasing/Solution.py | {
"start": 0,
"end": 202
} | class ____:
def minOperations(self, nums: List[int]) -> int:
ans = mx = 0
for v in nums:
ans += max(0, mx + 1 - v)
mx = max(mx + 1, v)
return ans
| Solution |
python | scrapy__scrapy | tests/CrawlerProcess/reactor_default.py | {
"start": 148,
"end": 383
} | class ____(scrapy.Spider):
name = "no_request"
async def start(self):
return
yield
process = CrawlerProcess(settings={})
d = process.crawl(NoRequestsSpider)
d.addErrback(log.err)
process.start()
| NoRequestsSpider |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 14144,
"end": 15666
} | class ____(ranges.AbstractMultiRangeImpl):
def bind_processor(self, dialect):
asyncpg_Range = dialect.dbapi.asyncpg.Range
def to_range(value):
if isinstance(value, (str, NoneType)):
return value
def to_range(value):
if isinstance(value, ranges.Range):
value = asyncpg_Range(
value.lower,
value.upper,
lower_inc=value.bounds[0] == "[",
upper_inc=value.bounds[1] == "]",
empty=value.empty,
)
return value
return [to_range(element) for element in value]
return to_range
def result_processor(self, dialect, coltype):
def to_range_array(value):
def to_range(rvalue):
if rvalue is not None:
empty = rvalue.isempty
rvalue = ranges.Range(
rvalue.lower,
rvalue.upper,
bounds=f"{'[' if empty or rvalue.lower_inc else '('}" # type: ignore # noqa: E501
f"{']' if not empty and rvalue.upper_inc else ')'}",
empty=empty,
)
return rvalue
if value is not None:
value = ranges.MultiRange(to_range(elem) for elem in value)
return value
return to_range_array
| _AsyncpgMultiRange |
python | joke2k__faker | faker/providers/bank/fa_IR/__init__.py | {
"start": 42,
"end": 1327
} | class ____(BankProvider):
"""Implement bank provider for ``fa_IR`` locale."""
bban_format = "IR########################"
country_code = "IR"
swift_bank_codes = (
"BEGN",
"KESH",
"BKMN",
"BKBP",
"CIYB",
"BTOS",
"IVBB",
"KBID",
"KIBO",
"KHMI",
)
swift_location_codes = ("TH",)
swift_branch_codes = ("BSH", "BCQ", "tIR", "tTH", "ATM", "BIC", "TIR", "ASR", "FOR")
banks = (
"بانکهای قرض الحسنه",
"بانک ملّی ایران",
"بانک اقتصاد نوین",
"بانک قرضالحسنه مهر ایران",
"بانک سپه",
"بانک پارسیان",
"بانک قرضالحسنه رسالت",
"بانک صنعت و معدن",
"بانک کارآفرین",
"بانک کشاورزی",
"بانک سامان",
"بانک مسکن",
"بانک سینا",
"بانک توسعه صادرات ایران",
"بانک خاور میانه",
"بانک توسعه تعاون",
"بانک شهر",
"پست بانک ایران",
"بانک دی",
"بانک صادرات",
"بانک ملت",
"بانک تجارت",
"بانک رفاه",
"بانک حکمت ایرانیان",
"بانک گردشگری",
"بانک ایران زمین",
"بانک قوامین",
"بانک انصار",
"بانک سرمایه",
"بانک پاسارگاد",
"بانک مشترک ایران-ونزوئلا",
)
| Provider |
python | huggingface__transformers | tests/models/evolla/test_processing_evolla.py | {
"start": 1029,
"end": 8595
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = EvollaProcessor
model_id = "westlake-repl/Evolla-10B-hf"
input_keys = ["protein_input_ids", "protein_attention_mask", "input_ids", "attention_mask"]
@unittest.skip("EvollaProcessor requires `messages_list` and `proteins` inputs.")
def test_processor_with_multiple_inputs(self):
pass
def prepare_input_and_expected_output(self):
amino_acid_sequence = "AAAA"
foldseek_sequence = "dddd"
question = "What is the function of this protein?"
expected_output = {
"protein_input_ids": torch.tensor([[0, 13, 13, 13, 13, 2]]),
"protein_attention_mask": torch.tensor([[1, 1, 1, 1, 1, 1]]),
"input_ids": torch.tensor(
[
[
128000,
128006,
9125,
128007,
271,
2675,
527,
459,
15592,
6335,
430,
649,
4320,
904,
4860,
922,
13128,
13,
128009,
128006,
882,
128007,
271,
3923,
374,
279,
734,
315,
420,
13128,
30,
128009,
128006,
78191,
128007,
271,
]
]
),
"attention_mask": torch.tensor(
[
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
]
]
),
}
protein_dict = {"aa_seq": amino_acid_sequence, "foldseek": foldseek_sequence}
message = [
{"role": "system", "content": "You are an AI expert that can answer any questions about protein."},
{"role": "user", "content": question},
]
return protein_dict, message, expected_output
def get_protein_tokenizer(self, **kwargs):
if "fix_mistral_regex" not in kwargs:
kwargs["fix_mistral_regex"] = True
return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).protein_tokenizer
def prepare_inputs_single(self):
proteins = {
"aa_seq": "".join(random.choices(EVOLLA_VALID_AA, k=100)),
"foldseek": "".join(random.choices(EVOLLA_VALID_FS, k=100)),
}
return proteins
def prepare_inputs_pair(self):
proteins = [
{
"aa_seq": "".join(random.choices(EVOLLA_VALID_AA, k=100)),
"foldseek": "".join(random.choices(EVOLLA_VALID_FS, k=100)),
},
{
"aa_seq": "".join(random.choices(EVOLLA_VALID_AA, k=100)),
"foldseek": "".join(random.choices(EVOLLA_VALID_FS, k=100)),
},
]
return proteins
def prepare_inputs_long(self):
proteins = [
{
"aa_seq": "".join(random.choices(EVOLLA_VALID_AA, k=100)),
"foldseek": "".join(random.choices(EVOLLA_VALID_FS, k=100)),
},
{
"aa_seq": "".join(random.choices(EVOLLA_VALID_AA, k=2000)),
"foldseek": "".join(random.choices(EVOLLA_VALID_FS, k=2000)),
},
]
return proteins
def prepare_inputs_short(self):
proteins = [
{
"aa_seq": "".join(random.choices(EVOLLA_VALID_AA, k=1)),
"foldseek": "".join(random.choices(EVOLLA_VALID_FS, k=1)),
},
{
"aa_seq": "".join(random.choices(EVOLLA_VALID_AA, k=100)),
"foldseek": "".join(random.choices(EVOLLA_VALID_FS, k=100)),
},
]
return proteins
def prepare_inputs_empty(self):
proteins = [
{
"aa_seq": "",
"foldseek": "",
},
{
"aa_seq": "".join(random.choices(EVOLLA_VALID_AA, k=100)),
"foldseek": "".join(random.choices(EVOLLA_VALID_FS, k=100)),
},
]
return proteins
def prepare_inputs(self, protein_types="pair"):
r"""
Prepare inputs for the test.
Args:
protein_types (`str`): the types of proteins to prepare.
- "single": a single correct protein.
- "pair": a pair of correct proteins.
- "long": a long sequence of correct proteins and a correct protein.
- "short": a short sequence of correct proteins (only have 1 aa) and a correct protein.
- "empty": an empty sequence of proteins and a correct protein.
"""
if protein_types == "single":
proteins = self.prepare_inputs_single()
elif protein_types == "pair":
proteins = self.prepare_inputs_pair()
elif protein_types == "long":
proteins = self.prepare_inputs_long()
elif protein_types == "short":
proteins = self.prepare_inputs_short()
elif protein_types == "empty":
proteins = self.prepare_inputs_empty()
else:
raise ValueError(
f"protein_types should be one of 'single', 'pair', 'long','short', 'empty', but got {protein_types}"
)
questions = ["What is the function of the protein?"] * len(proteins)
messages_list = []
for question in questions:
messages = [
{"role": "system", "content": "You are an AI expert that can answer any questions about protein."},
{"role": "user", "content": question},
]
messages_list.append(messages)
return proteins, messages_list
def test_model_input_names(self):
processor = self.get_processor()
proteins, messages_list = self.prepare_inputs()
inputs = processor(messages_list=messages_list, proteins=proteins, padding="longest", return_tensors="pt")
self.assertSetEqual(set(inputs.keys()), set(self.input_keys))
| EvollaProcessorTest |
python | django__django | tests/apps/apps.py | {
"start": 36,
"end": 138
} | class ____(AppConfig):
name = "django.contrib.admin"
verbose_name = "Admin sweet admin."
| MyAdmin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF053.py | {
"start": 2074,
"end": 2119
} | class ____[T](Generic[Unpack[_As, _Bs]]): ...
| C |
python | streamlit__streamlit | e2e_playwright/st_altair_chart_basic_select_test.py | {
"start": 1108,
"end": 15502
} | class ____:
x: int
y: int
def _create_selection_rectangle(
app: Page,
chart: Locator,
canvas_start_pos: _MousePosition,
canvas_end_pos: _MousePosition,
) -> None:
expect(chart).to_be_visible()
chart.scroll_into_view_if_needed()
bounding_box = chart.bounding_box()
assert bounding_box is not None
canvas_start_x_px = bounding_box.get("x", 0)
canvas_start_y_px = bounding_box.get("y", 0)
app.mouse.move(
canvas_start_x_px + canvas_start_pos.x, canvas_start_y_px + canvas_start_pos.y
)
app.mouse.down()
app.mouse.move(
canvas_start_x_px + canvas_end_pos.x, canvas_start_y_px + canvas_end_pos.y
)
app.mouse.up()
wait_for_app_run(app)
def _click(app: Page, chart: Locator, click_position: _MousePosition) -> None:
expect(chart).to_be_visible()
chart.scroll_into_view_if_needed()
chart.click(position={"x": click_position.x, "y": click_position.y})
wait_for_app_run(app)
def _get_selection_point_scatter_chart(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(0)
)
def _get_selection_interval_scatter_chart(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(1)
)
def _get_selection_interval_scatter_chart_tooltip(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(2)
)
def _get_selection_point_bar_chart(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(3)
)
def _get_selection_interval_bar_chart(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(4)
)
def _get_selection_point_area_chart(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(5)
)
def _get_selection_interval_area_chart(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(6)
)
def _get_selection_point_histogram(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(7)
)
def _get_selection_interval_histogram(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(8)
)
def _get_in_form_chart(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(9)
)
def _get_callback_chart(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(10)
)
def _get_in_fragment_chart(app: Page) -> Locator:
return (
app.get_by_test_id("stVegaLiteChart")
.locator("[role='graphics-document']")
.nth(11)
)
def test_point_bar_chart_displays_selection_text(app: Page):
chart = _get_selection_point_bar_chart(app)
# click on E-bar
_click(app, chart, _MousePosition(150, 180))
expected_prefix = "Bar chart with selection_point:"
expected_selection = re.compile(
"\\{'selection': \\{'param_1': \\[\\{'a': 'B', 'b': 55\\}]\\}\\}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
def test_interval_bar_chart_displays_selection_text(app: Page):
chart = _get_selection_interval_bar_chart(app)
expect(chart).to_be_visible()
# change also height, because otherwise the selection is not triggered
_create_selection_rectangle(
app, chart, _MousePosition(90, 150), _MousePosition(175, 155)
)
expected_prefix = "Bar chart with selection_interval:"
expected_selection = re.compile(
"\\{'selection': \\{'param_1': \\{'a': \\['A', 'B'\\], 'b': \\[.+, .+\\]\\}\\}\\}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
def test_point_area_chart_displays_selection_text(app: Page):
chart = _get_selection_point_area_chart(app)
_click(app, chart, _MousePosition(150, 150))
expected_prefix = "Area chart with selection_point:"
expected_selection = re.compile(
"\\{'param_1': \\[\\{'source': 'Fossil Fuels', 'year': .+, 'net_generation': .+\\}\\]\\}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
def test_interval_area_chart_displays_selection_text(app: Page):
chart = _get_selection_interval_area_chart(app)
_create_selection_rectangle(
app, chart, _MousePosition(120, 110), _MousePosition(225, 195)
)
expected_prefix = "Area chart with selection_interval:"
expected_selection = re.compile(
"\\{'param_1': \\{'year': \\[.+, .+\\], 'net_generation': \\[.+, .+\\]\\}\\}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
def test_point_histogram_chart_displays_selection_text(app: Page):
chart = _get_selection_point_histogram(app)
_click(app, chart, _MousePosition(255, 238))
expected_prefix = "Histogram chart with selection_point:"
expected_selection = re.compile(
"{'selection': {'param_1': \\[{'IMDB_Rating': 4.6}\\]}}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
def test_interval_histogram_chart_displays_selection_text(app: Page):
chart = _get_selection_interval_histogram(app)
_create_selection_rectangle(
app, chart, _MousePosition(160, 210), _MousePosition(205, 200)
)
expected_prefix = "Histogram chart with selection_interval:"
expected_selection = re.compile(
"\\{'selection': \\{'param_1': \\{'IMDB_Rating': \\[.+, .+\\]\\}\\}\\}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
def test_double_click_interval_shows_no_selection_text(app: Page):
chart = _get_selection_interval_scatter_chart(app)
_create_selection_rectangle(
app, chart, _MousePosition(130, 100), _MousePosition(215, 160)
)
expected_prefix = "Scatter chart with selection_interval:"
expected_selection = re.compile(
"\\{'selection': \\{'param_1': \\{'Horsepower': \\[.+, .+\\], 'Miles_per_Gallon': \\[.+, .+\\]\\}\\}\\}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
chart.dblclick(position={"x": 130, "y": 100})
wait_for_app_run(app)
selection_text = app.get_by_test_id("stMarkdownContainer").filter(
has_text=expected_selection
)
expect(selection_text).to_have_count(0)
def test_point_selection_scatter_chart_displays_selection_text(app: Page):
chart = _get_selection_point_scatter_chart(app)
_click(app, chart, _MousePosition(264, 162))
expected_prefix = "Scatter chart with selection_point:"
expected_selection = re.compile(
"\\{'selection': \\{'param_1': \\[\\{'Origin': 'USA', 'Horsepower': .+, 'Miles_per_Gallon': .+\\}\\]\\}\\}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
def test_interval_selection_scatter_chart_displays_selection_snapshot(
app: Page, assert_snapshot: ImageCompareFunction
):
chart = _get_selection_interval_scatter_chart(app)
_create_selection_rectangle(
app, chart, _MousePosition(260, 110), _MousePosition(433, 220)
)
expected_prefix = "Scatter chart with selection_interval:"
expected_selection = re.compile(
"\\{'selection': \\{'param_1': \\{'Horsepower': \\[.+, .+\\], 'Miles_per_Gallon': \\[.+, .+\\]\\}\\}\\}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
assert_snapshot(chart, name="st_altair_chart-scatter_interval_selection")
def test_interval_selection_scatter_chart_no_tooltip_in_selection(app: Page):
chart = _get_selection_interval_scatter_chart_tooltip(app)
# create selection
_create_selection_rectangle(
app, chart, _MousePosition(260, 110), _MousePosition(433, 220)
)
# hover over a point in the selection
chart.hover(position={"x": 300, "y": 150})
# get the tooltip
tooltip = app.locator("#vg-tooltip-element")
# check tooltip empty - doesn't have "true" as content (Issue #10448)
expect(tooltip).to_have_text("")
def test_interval_selection_scatter_chart_tooltip_outside_selection(app: Page):
chart = _get_selection_interval_scatter_chart_tooltip(app)
# create selection
_create_selection_rectangle(
app, chart, _MousePosition(260, 110), _MousePosition(433, 220)
)
# hover over a point outside the selection
chart.hover(position={"x": 250, "y": 110})
# get the tooltip
tooltip = app.locator("#vg-tooltip-element")
# check the tooltip has expected content
expect(tooltip).to_contain_text("Horsepower")
expect(tooltip).to_contain_text("Miles_per_Gallon")
def _test_shift_click_point_selection_scatter_chart_displays_selection(
app: Page,
) -> Locator:
chart = _get_selection_point_scatter_chart(app)
expect(chart).to_be_visible()
chart.scroll_into_view_if_needed()
chart.click(position={"x": 264, "y": 162})
wait_for_app_run(app)
chart.click(position={"x": 310, "y": 175}, modifiers=["Shift"]) # ty: ignore[invalid-argument-type]
wait_for_app_run(app)
chart.click(position={"x": 402, "y": 194}, modifiers=["Shift"]) # ty: ignore[invalid-argument-type]
wait_for_app_run(app)
chart.click(position={"x": 181, "y": 94}, modifiers=["Shift"]) # ty: ignore[invalid-argument-type]
wait_for_app_run(app)
# move the mouse away so that we do not have any hover-menu effects on the chart when taking the screenshot.
# we re-use the screenshot for the unmounting test.
app.mouse.move(0, 0)
app.wait_for_timeout(250)
expected_prefix = "Scatter chart with selection_point:"
expected_selection = re.compile(
"\\{'selection': \\{'param_1': \\[\\{'Origin': 'USA', 'Horsepower': .+, 'Miles_per_Gallon': .+\\}, "
"\\{'Origin': 'USA', 'Horsepower': .+, 'Miles_per_Gallon': .+\\}, "
"\\{'Origin': 'USA', 'Horsepower': .+, 'Miles_per_Gallon': .+\\}, "
"\\{'Origin': 'Japan', 'Horsepower': .+, 'Miles_per_Gallon': .+\\}\\]\\}\\}"
)
expect_prefixed_markdown(app, expected_prefix, expected_selection)
return chart
def test_in_form_selection_and_session_state(app: Page):
chart = _get_in_form_chart(app)
expect(chart).to_be_visible()
_click(app, chart, _MousePosition(255, 238))
markdown_prefix = "Histogram-in-form selection:"
markdown_prefix_session_state = "Histogram-in-form selection in session state:"
empty_selection = re.compile("\\{'selection': \\{'param_1': \\{\\}\\}\\}")
# nothing should be shown yet because we did not submit the form
expect_prefixed_markdown(
app,
markdown_prefix,
empty_selection,
)
expect_prefixed_markdown(
app,
markdown_prefix_session_state,
empty_selection,
)
# submit the form. The selection uses a debounce of 200ms; if we click too early,
# the state is not updated correctly and we submit the old, unselected values
app.wait_for_timeout(210)
click_form_button(app, "Submit")
expected_selection = re.compile(
"{'selection': {'param_1': \\[{'IMDB_Rating': 4.6}\\]}}"
)
expect_prefixed_markdown(app, markdown_prefix, expected_selection)
expect_prefixed_markdown(app, markdown_prefix_session_state, expected_selection)
def test_selection_with_callback(app: Page):
chart = _get_callback_chart(app)
expect(chart).to_be_visible()
_click(app, chart, _MousePosition(255, 238))
markdown_prefix = "Histogram selection callback:"
expected_selection = re.compile(
"{'selection': {'param_1': \\[{'IMDB_Rating': 4.6}\\]}}"
)
expect_prefixed_markdown(app, markdown_prefix, expected_selection)
def test_selection_in_fragment(app: Page):
chart = _get_in_fragment_chart(app)
expect(chart).to_be_visible()
markdown_prefix = "Histogram-in-fragment selection:"
empty_selection = re.compile("\\{'selection': \\{'param_1': \\{\\}\\}\\}")
expect_prefixed_markdown(app, markdown_prefix, empty_selection)
_click(app, chart, _MousePosition(255, 238))
expected_selection = re.compile(
"{'selection': {'param_1': \\[{'IMDB_Rating': 4.6}\\]}}"
)
expect_prefixed_markdown(app, markdown_prefix, expected_selection)
# Check that the main script has run once (the initial run), but not after the selection:
expect(app.get_by_text("Runs: 1")).to_be_visible()
def test_shift_click_point_selection_scatter_chart_snapshot(
app: Page, assert_snapshot: ImageCompareFunction
):
chart = _test_shift_click_point_selection_scatter_chart_displays_selection(app)
chart.scroll_into_view_if_needed()
assert_snapshot(chart, name="st_altair_chart-scatter_shift_selection")
# Skip firefox since it takes a snapshot with a slightly different size
# compared to the one in the test_multi_row_and_multi_column_select_snapshot test
@pytest.mark.skip_browser("firefox")
def test_selection_state_remains_after_unmounting_snapshot(
app: Page, assert_snapshot: ImageCompareFunction
):
chart = _test_shift_click_point_selection_scatter_chart_displays_selection(app)
# click on button to trigger unmounting / mounting
app.get_by_test_id("stButton").filter(
has_text="Create some elements to unmount component"
).locator("button").click()
wait_for_app_run(app, wait_delay=4000)
chart.scroll_into_view_if_needed()
# Use the same snapshot name as the previous test to ensure visual consistency
# Increase the image_threshold slightly because the second image is a little bit moved for some reason
assert_snapshot(
chart,
name="st_altair_chart-scatter_shift_selection",
image_threshold=0.041,
)
def test_custom_css_class_via_key(app: Page):
"""Test that the element can have a custom css class via the key argument."""
expect(get_element_by_key(app, "scatter_point")).to_be_visible()
| _MousePosition |
python | django__django | tests/forms_tests/tests/test_renderers.py | {
"start": 1352,
"end": 1442
} | class ____(SharedTests, SimpleTestCase):
renderer = TemplatesSetting
| TemplatesSettingTests |
python | apache__airflow | helm-tests/tests/helm_tests/security/test_extra_configmaps_secrets.py | {
"start": 1055,
"end": 10260
} | class ____:
"""Tests extra configmaps and secrets."""
def test_extra_configmaps(self):
values_str = textwrap.dedent(
"""
extraConfigMaps:
"{{ .Release.Name }}-airflow-variables":
data: |
AIRFLOW_VAR_HELLO_MESSAGE: "Hi!"
AIRFLOW_VAR_KUBERNETES_NAMESPACE: "{{ .Release.Namespace }}"
"{{ .Release.Name }}-other-variables":
data: |
HELLO_WORLD: "Hi again!"
"""
)
values = yaml.safe_load(values_str)
k8s_objects = render_chart(
RELEASE_NAME, values=values, show_only=["templates/configmaps/extra-configmaps.yaml"]
)
k8s_objects_by_key = prepare_k8s_lookup_dict(k8s_objects)
all_expected_keys = [
("ConfigMap", f"{RELEASE_NAME}-airflow-variables"),
("ConfigMap", f"{RELEASE_NAME}-other-variables"),
]
assert set(k8s_objects_by_key.keys()) == set(all_expected_keys)
all_expected_data = [
{"AIRFLOW_VAR_HELLO_MESSAGE": "Hi!", "AIRFLOW_VAR_KUBERNETES_NAMESPACE": "default"},
{"HELLO_WORLD": "Hi again!"},
]
for expected_key, expected_data in zip(all_expected_keys, all_expected_data):
configmap_obj = k8s_objects_by_key[expected_key]
assert configmap_obj["data"] == expected_data
def test_extra_secrets(self):
values_str = textwrap.dedent(
"""
extraSecrets:
"{{ .Release.Name }}-airflow-connections":
data: |
AIRFLOW_CON_AWS: {{ printf "aws_connection_string" | b64enc }}
stringData: |
AIRFLOW_CON_GCP: "gcp_connection_string"
"{{ .Release.Name }}-other-secrets":
data: |
MY_SECRET_1: {{ printf "MY_SECRET_1" | b64enc }}
MY_SECRET_2: {{ printf "MY_SECRET_2" | b64enc }}
stringData: |
MY_SECRET_3: "MY_SECRET_3"
MY_SECRET_4: "MY_SECRET_4"
"{{ .Release.Name }}-other-secrets-with-type":
type: kubernetes.io/dockerconfigjson
data: |
MY_SECRET_5: {{ printf "MY_SECRET_5" | b64enc }}
MY_SECRET_6: {{ printf "MY_SECRET_6" | b64enc }}
stringData: |
MY_SECRET_7: "MY_SECRET_7"
MY_SECRET_8: "MY_SECRET_8"
"""
)
values = yaml.safe_load(values_str)
k8s_objects = render_chart(
RELEASE_NAME, values=values, show_only=["templates/secrets/extra-secrets.yaml"]
)
k8s_objects_by_key = prepare_k8s_lookup_dict(k8s_objects)
all_expected_keys = [
("Secret", f"{RELEASE_NAME}-airflow-connections"),
("Secret", f"{RELEASE_NAME}-other-secrets"),
("Secret", f"{RELEASE_NAME}-other-secrets-with-type"),
]
assert set(k8s_objects_by_key.keys()) == set(all_expected_keys)
all_expected_data = [
{"AIRFLOW_CON_AWS": b64encode(b"aws_connection_string").decode("utf-8")},
{
"MY_SECRET_1": b64encode(b"MY_SECRET_1").decode("utf-8"),
"MY_SECRET_2": b64encode(b"MY_SECRET_2").decode("utf-8"),
},
{
"MY_SECRET_5": b64encode(b"MY_SECRET_5").decode("utf-8"),
"MY_SECRET_6": b64encode(b"MY_SECRET_6").decode("utf-8"),
},
]
all_expected_string_data = [
{"AIRFLOW_CON_GCP": "gcp_connection_string"},
{"MY_SECRET_3": "MY_SECRET_3", "MY_SECRET_4": "MY_SECRET_4"},
{"MY_SECRET_7": "MY_SECRET_7", "MY_SECRET_8": "MY_SECRET_8"},
]
all_expected_types = [None, None, "kubernetes.io/dockerconfigjson"]
for expected_key, expected_data, expected_string_data, expected_type in zip(
all_expected_keys, all_expected_data, all_expected_string_data, all_expected_types
):
configmap_obj = k8s_objects_by_key[expected_key]
if expected_type:
assert configmap_obj["type"] == expected_type
else:
assert "type" not in configmap_obj
assert configmap_obj["data"] == expected_data
assert configmap_obj["stringData"] == expected_string_data
def test_extra_configmaps_secrets_labels(self):
k8s_objects = render_chart(
name=RELEASE_NAME,
values={
"labels": {"label1": "value1", "label2": "value2"},
"extraSecrets": {"{{ .Release.Name }}-extra-secret-1": {"stringData": "data: secretData"}},
"extraConfigMaps": {"{{ .Release.Name }}-extra-configmap-1": {"data": "data: configData"}},
},
show_only=["templates/configmaps/extra-configmaps.yaml", "templates/secrets/extra-secrets.yaml"],
)
expected_labels = {
"label1": "value1",
"label2": "value2",
"release": RELEASE_NAME,
"heritage": "Helm",
"chart": mock.ANY,
"tier": "airflow",
}
for k8s_object in k8s_objects:
assert k8s_object["metadata"]["labels"] == expected_labels
@pytest.mark.parametrize(
("chart_labels", "local_labels"),
[
({}, {"label3": "value3", "label4": "value4"}),
({"label1": "value1", "label2": "value2"}, {}),
({"label1": "value1", "label2": "value2"}, {"label3": "value3", "label4": "value4"}),
],
)
def test_extra_configmaps_secrets_additional_labels(self, chart_labels, local_labels):
k8s_objects = render_chart(
name=RELEASE_NAME,
values={
"labels": chart_labels,
"extraSecrets": {
"{{ .Release.Name }}-extra-secret-1": {
"labels": local_labels,
"stringData": "data: secretData",
}
},
"extraConfigMaps": {
"{{ .Release.Name }}-extra-configmap-1": {
"labels": local_labels,
"data": "data: configData",
}
},
},
show_only=["templates/configmaps/extra-configmaps.yaml", "templates/secrets/extra-secrets.yaml"],
)
common_labels = {
"release": RELEASE_NAME,
"heritage": "Helm",
"chart": mock.ANY,
"tier": "airflow",
}
for k8s_object in k8s_objects:
assert k8s_object["metadata"]["labels"] == {**common_labels, **chart_labels, **local_labels}
def test_extra_configmaps_secrets_additional_annotations(self):
k8s_objects = render_chart(
name=RELEASE_NAME,
values={
"extraSecrets": {
"{{ .Release.Name }}-extra-secret-1": {
"annotations": {"test_annotation": "test_annotation_value"},
"stringData": "data: secretData",
}
},
"extraConfigMaps": {
"{{ .Release.Name }}-extra-configmap-1": {
"annotations": {"test_annotation": "test_annotation_value"},
"data": "data: configData",
}
},
},
show_only=["templates/configmaps/extra-configmaps.yaml", "templates/secrets/extra-secrets.yaml"],
)
expected_annotations = {
"helm.sh/hook": "pre-install,pre-upgrade",
"helm.sh/hook-delete-policy": "before-hook-creation",
"helm.sh/hook-weight": "0",
"test_annotation": "test_annotation_value",
}
for k8s_object in k8s_objects:
assert k8s_object["metadata"]["annotations"] == expected_annotations
def test_extra_configmaps_secrets_disable_helm_hooks(self):
k8s_objects = render_chart(
name=RELEASE_NAME,
values={
"extraSecrets": {
"{{ .Release.Name }}-extra-secret-1": {
"useHelmHooks": False,
"annotations": {"test_annotation": "test_annotation_value"},
"stringData": "data: secretData",
}
},
"extraConfigMaps": {
"{{ .Release.Name }}-extra-configmap-1": {
"useHelmHooks": False,
"annotations": {"test_annotation": "test_annotation_value"},
"data": "data: configData",
}
},
},
show_only=["templates/configmaps/extra-configmaps.yaml", "templates/secrets/extra-secrets.yaml"],
)
expected_annotations = {
"test_annotation": "test_annotation_value",
}
for k8s_object in k8s_objects:
assert k8s_object["metadata"]["annotations"] == expected_annotations
| TestExtraConfigMapsSecrets |
python | pytorch__pytorch | benchmarks/dynamo/genai_layers/kernels.py | {
"start": 331,
"end": 4039
} | class ____(BenchmarkKernel):
def __init__(self, script_args):
super().__init__(script_args)
self.available_backends = ["eager", "compiled", "quack", "liger"]
def get_shapes(self) -> tuple[tuple[int, ...], ...]:
return (
(32768, 256),
(32768, 512),
(32768, 1024),
(32768, 2048),
(32768, 4096),
(32768, 8192),
(32768, 16384),
(32768, 32768),
(32768, 65536),
(16384, 131072),
(8192, 262144),
)
def get_memory_bytes(self, args, kwargs) -> int:
# Read x (M*N elements) + read target (M elements) + write loss (M elements)
x, target = args
M, N = x.shape
dtype = x.dtype
return (M * N + M + M) * dtype.itemsize
def eager(self, args, kwargs=None) -> Any:
assert kwargs is None
x, target = args
return lambda: F.cross_entropy(x, target, reduction="none")
def compiled(self, args, kwargs=None) -> Any:
assert kwargs is None
x, target = args
# Mark batch size as dynamic for realistic workload
torch._dynamo.mark_dynamic(x, 0)
torch._dynamo.mark_dynamic(target, 0)
# Need `lambda` otherwise torch.compile will not trace the function.
# More discussion: https://github.com/pytorch/pytorch/issues/158455
compiled_cross_entropy = torch.compile(
lambda x, target: F.cross_entropy(x, target, reduction="none"),
mode=self.compile_mode,
fullgraph=True,
)
return lambda: compiled_cross_entropy(x, target)
def quack(self, args, kwargs=None) -> Any:
assert kwargs is None
x, target = args
from quack.cross_entropy import _cross_entropy
return lambda: _cross_entropy(x, target)
def liger(self, args, kwargs=None) -> Any:
assert kwargs is None
from liger_kernel.transformers.cross_entropy import LigerCrossEntropyLoss
x, target = args
cross_entropy = LigerCrossEntropyLoss(reduction="none")
return lambda: cross_entropy(x, target)
def benchmark(self):
for M, N in self.get_shapes():
print(f"\n Tensor dimensions: [{M}, {N}]")
# quack requires cutlass dtype
torch_dtype = cutlass_torch.dtype(cutlass.BFloat16)
x = 0.1 * torch.randn(M, N, device="cuda", dtype=torch_dtype)
target = torch.randint(0, N, (M,), device="cuda", dtype=torch.int64)
self.benchmark_single_shape((x, target), setting=f"shape: [{M}, {N}]")
def check_accuracy(self, args, kwargs) -> None:
res = {}
for backend in self.available_backends:
args_ref, kwargs_ref = self.clone_inputs(args, kwargs)
res[backend] = getattr(self, backend)(args_ref, kwargs_ref)()
gold = res["eager"]
for backend in self.available_backends:
if backend == "eager":
continue
if backend == "quack":
# quack's cross_entropy only returns float32 loss output.
# Need to convert it to the same dtype as gold for comparison.
res[backend] = res[backend].to(gold.dtype)
try:
torch.testing.assert_close(res[backend], gold)
print(
f"Accuracy check \033[92m✓ succeed\033[0m for {backend} backend on {self.name} kernel"
)
except Exception as e:
print(
f"Accuracy check \033[91m✗ failed\033[0m for {backend} backend on {self.name} kernel. Error {e}"
)
| CrossEntropyForward |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0001_initial.py | {
"start": 163,
"end": 8886
} | class ____(migrations.Migration):
safe = Safe.always()
dependencies = [
("projects", "0001_initial"),
("taggit", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="Build",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"type",
models.CharField(
default=b"html",
max_length=55,
verbose_name="Type",
choices=[
(b"html", "HTML"),
(b"pdf", "PDF"),
(b"epub", "Epub"),
(b"man", "Manpage"),
(b"dash", "Dash"),
],
),
),
(
"state",
models.CharField(
default=b"finished",
max_length=55,
verbose_name="State",
choices=[
(b"triggered", "Triggered"),
(b"cloning", "Cloning"),
(b"installing", "Installing"),
(b"building", "Building"),
(b"finished", "Finished"),
],
),
),
("date", models.DateTimeField(auto_now_add=True, verbose_name="Date")),
("success", models.BooleanField(default=True, verbose_name="Success")),
(
"setup",
models.TextField(null=True, verbose_name="Setup", blank=True),
),
(
"setup_error",
models.TextField(null=True, verbose_name="Setup error", blank=True),
),
(
"output",
models.TextField(default=b"", verbose_name="Output", blank=True),
),
(
"error",
models.TextField(default=b"", verbose_name="Error", blank=True),
),
(
"exit_code",
models.IntegerField(null=True, verbose_name="Exit code", blank=True),
),
(
"commit",
models.CharField(max_length=255, null=True, verbose_name="Commit", blank=True),
),
(
"length",
models.IntegerField(null=True, verbose_name="Build Length", blank=True),
),
(
"builder",
models.CharField(max_length=255, null=True, verbose_name="Builder", blank=True),
),
(
"project",
models.ForeignKey(
related_name="builds",
verbose_name="Project",
to="projects.Project",
on_delete=models.CASCADE,
),
),
],
options={
"ordering": ["-date"],
"get_latest_by": "date",
},
),
migrations.CreateModel(
name="Version",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"type",
models.CharField(
default=b"unknown",
max_length=20,
verbose_name="Type",
choices=[
(b"branch", "Branch"),
(b"tag", "Tag"),
(b"unknown", "Unknown"),
],
),
),
(
"identifier",
models.CharField(max_length=255, verbose_name="Identifier"),
),
(
"verbose_name",
models.CharField(max_length=255, verbose_name="Verbose Name"),
),
(
"slug",
readthedocs.builds.version_slug.VersionSlugField(
max_length=255,
verbose_name="Slug",
db_index=True,
),
),
(
"supported",
models.BooleanField(default=True, verbose_name="Supported"),
),
("active", models.BooleanField(default=False, verbose_name="Active")),
("built", models.BooleanField(default=False, verbose_name="Built")),
(
"uploaded",
models.BooleanField(default=False, verbose_name="Uploaded"),
),
(
"privacy_level",
models.CharField(
default=b"public",
help_text="Level of privacy for this Version.",
max_length=20,
verbose_name="Privacy Level",
choices=[
(b"public", "Public"),
(b"protected", "Protected"),
(b"private", "Private"),
],
),
),
(
"machine",
models.BooleanField(default=False, verbose_name="Machine Created"),
),
(
"project",
models.ForeignKey(
related_name="versions",
verbose_name="Project",
to="projects.Project",
on_delete=models.CASCADE,
),
),
(
"tags",
taggit.managers.TaggableManager(
to="taggit.Tag",
through="taggit.TaggedItem",
blank=True,
help_text="A comma-separated list of tags.",
verbose_name="Tags",
),
),
],
options={
"ordering": ["-verbose_name"],
},
),
migrations.CreateModel(
name="VersionAlias",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"from_slug",
models.CharField(default=b"", max_length=255, verbose_name="From slug"),
),
(
"to_slug",
models.CharField(
default=b"", max_length=255, verbose_name="To slug", blank=True
),
),
("largest", models.BooleanField(default=False, verbose_name="Largest")),
(
"project",
models.ForeignKey(
related_name="aliases",
verbose_name="Project",
to="projects.Project",
on_delete=models.CASCADE,
),
),
],
),
migrations.AddField(
model_name="build",
name="version",
field=models.ForeignKey(
related_name="builds",
verbose_name="Version",
to="builds.Version",
null=True,
on_delete=models.CASCADE,
),
),
migrations.AlterUniqueTogether(
name="version",
unique_together={("project", "slug")},
),
]
| Migration |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/codeFlow2.py | {
"start": 180,
"end": 518
} | class ____(object):
# The symbol "stat" is a module even though
# it is redeclared below in this scope as
# a method.
_stat_mode: int = stat.S_IFDIR
def stat(self):
return None
def outer():
a = 1
def inner():
# This should generate an error
a += 1
inner()
return a
| FakeOsModule |
python | jazzband__pip-tools | tests/conftest.py | {
"start": 1801,
"end": 16360
} | class ____(BaseRepository):
def __init__(self, options: FakeOptions):
self._options = options
with open(os.path.join(TEST_DATA_PATH, "fake-index.json")) as f:
self.index = json.load(f)
with open(os.path.join(TEST_DATA_PATH, "fake-editables.json")) as f:
self.editables = json.load(f)
def get_hashes(self, ireq):
# Some fake hashes
return {
"test:123",
"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
}
def find_best_match(self, ireq, prereleases=False):
if ireq.editable:
return ireq
versions = list(
ireq.specifier.filter(
self.index[key_from_ireq(ireq)], prereleases=prereleases
)
)
if not versions:
tried_versions = [
InstallationCandidate(ireq.name, version, "https://fake.url.foo")
for version in self.index[key_from_ireq(ireq)]
]
raise NoCandidateFound(ireq, tried_versions, ["https://fake.url.foo"])
best_version = max(versions, key=Version)
return make_install_requirement(key_from_ireq(ireq), best_version, ireq)
def get_dependencies(self, ireq):
if ireq.editable or is_url_requirement(ireq):
return self.editables[str(ireq.link)]
name, version, extras = as_tuple(ireq)
# Store non-extra dependencies under the empty string
extras += ("",)
dependencies = [
dep for extra in extras for dep in self.index[name][version][extra]
]
return [
install_req_from_line(dep, constraint=ireq.constraint)
for dep in dependencies
]
@contextmanager
def allow_all_wheels(self):
# No need to do an actual pip.Wheel mock here.
yield
@property
def options(self):
return self._options
@property
def session(self) -> PipSession:
"""Not used"""
@property
def finder(self) -> PackageFinder:
"""Not used"""
@property
def command(self) -> InstallCommand:
"""Not used"""
def pytest_collection_modifyitems(config, items):
for item in items:
# Mark network tests as flaky
if item.get_closest_marker("network") and looks_like_ci():
item.add_marker(pytest.mark.flaky(reruns=3, reruns_delay=2))
@pytest.fixture
def fake_dist():
def _fake_dist(line, deps=None):
if deps is None:
deps = []
req = Requirement.parse(line)
key = req.name
if "==" in line:
version = line.split("==")[1]
else:
version = "0+unknown"
requires = [Requirement.parse(d) for d in deps]
direct_url = None
if req.url:
direct_url = direct_url_from_link(Link(req.url))
return Distribution(key, version, requires, direct_url)
return _fake_dist
@pytest.fixture
def repository():
return FakeRepository(
options=FakeOptions(deprecated_features_enabled=["legacy-resolver"])
)
@pytest.fixture
def pypi_repository(tmpdir):
return PyPIRepository(
[
"--index-url",
PyPIRepository.DEFAULT_INDEX_URL,
"--use-deprecated",
"legacy-resolver",
],
cache_dir=(tmpdir / "pypi-repo"),
)
@pytest.fixture
def depcache(tmpdir):
return DependencyCache(tmpdir / "dep-cache")
@pytest.fixture
def resolver(depcache, repository):
# TODO: It'd be nicer if Resolver instance could be set up and then
# use .resolve(...) on the specset, instead of passing it to
# the constructor like this (it's not reusable)
return partial(
LegacyResolver, repository=repository, cache=depcache, existing_constraints={}
)
@pytest.fixture
def backtracking_resolver(depcache):
# TODO: It'd be nicer if Resolver instance could be set up and then
# use .resolve(...) on the specset, instead of passing it to
# the constructor like this (it's not reusable)
return partial(
BacktrackingResolver,
repository=FakeRepository(options=FakeOptions()),
cache=depcache,
existing_constraints={},
)
@pytest.fixture
def base_resolver(depcache):
return partial(LegacyResolver, cache=depcache, existing_constraints={})
@pytest.fixture
def from_line():
def _from_line(*args, **kwargs):
if PIP_VERSION[:2] <= (23, 0):
hash_options = kwargs.pop("hash_options", {})
options = kwargs.pop("options", {})
options["hashes"] = hash_options
kwargs["options"] = options
return install_req_from_line(*args, **kwargs)
return _from_line
@pytest.fixture
def from_editable():
return install_req_from_editable
@pytest.fixture
def runner():
if Version(version_of("click")) < Version("8.2"):
cli_runner = CliRunner(mix_stderr=False)
else:
cli_runner = CliRunner()
with cli_runner.isolated_filesystem():
yield cli_runner
@pytest.fixture
def tmpdir_cwd(tmpdir):
with tmpdir.as_cwd():
yield Path(tmpdir)
@pytest.fixture
def make_pip_conf(tmpdir, monkeypatch):
created_paths = []
def _make_pip_conf(content):
pip_conf_file = "pip.conf" if os.name != "nt" else "pip.ini"
path = (tmpdir / pip_conf_file).strpath
with open(path, "w") as f:
f.write(content)
monkeypatch.setenv("PIP_CONFIG_FILE", path)
created_paths.append(path)
return path
try:
yield _make_pip_conf
finally:
for path in created_paths:
os.remove(path)
@pytest.fixture
def pip_conf(make_pip_conf, minimal_wheels_path):
return make_pip_conf(
dedent(
f"""\
[global]
no-index = true
find-links = {minimal_wheels_path.as_posix()}
"""
)
)
@pytest.fixture
def pip_with_index_conf(make_pip_conf, minimal_wheels_path):
return make_pip_conf(
dedent(
f"""\
[global]
index-url = http://example.com
find-links = {minimal_wheels_path.as_posix()}
"""
)
)
@pytest.fixture(scope="session")
def make_package(tmp_path_factory):
"""
Make a package from a given name, version and list of required packages.
"""
def _make_package(
name,
version="0.1",
install_requires=None,
extras_require=None,
build_system_requires=None,
):
if install_requires is None:
install_requires = []
if extras_require is None:
extras_require = dict()
install_requires_str = "[{}]".format(
",".join(f"{package!r}" for package in install_requires)
)
package_dir = tmp_path_factory.mktemp("packages") / name / version
package_dir.mkdir(parents=True)
with (package_dir / "setup.py").open("w") as fp:
fp.write(
dedent(
f"""\
from setuptools import setup
setup(
name={name!r},
version={version!r},
author="pip-tools",
author_email="pip-tools@localhost",
url="https://github.com/jazzband/pip-tools",
install_requires={install_requires_str},
extras_require={extras_require},
py_modules=[{name!r}],
)
"""
)
)
# Create a README to avoid setuptools warnings.
(package_dir / "README").touch()
# Create a module to make the package importable.
(package_dir / name).with_suffix(".py").touch()
if build_system_requires:
with (package_dir / "pyproject.toml").open("w") as fp:
fp.write(
dedent(
f"""\
[build-system]
requires = {json.dumps(build_system_requires)}
"""
)
)
return package_dir
return _make_package
@pytest.fixture(scope="session")
def run_setup_file():
"""
Run a setup.py file from a given package dir.
"""
def _run_setup_file(package_dir_path, *args):
setup_file = package_dir_path / "setup.py"
return subprocess.run(
[sys.executable, str(setup_file), *args],
cwd=str(package_dir_path),
stdout=subprocess.DEVNULL,
check=True,
) # nosec
return _run_setup_file
@pytest.fixture(scope="session")
def make_wheel(run_setup_file):
"""
Make a wheel distribution from a given package dir.
"""
def _make_wheel(package_dir, dist_dir, *args):
return run_setup_file(
package_dir, "bdist_wheel", "--dist-dir", str(dist_dir), *args
)
return _make_wheel
@pytest.fixture
def make_sdist(run_setup_file):
"""
Make a source distribution from a given package dir.
"""
def _make_sdist(package_dir, dist_dir, *args):
return run_setup_file(package_dir, "sdist", "--dist-dir", str(dist_dir), *args)
return _make_sdist
@pytest.fixture
def make_module(tmpdir):
"""
Make a metadata file with the given name and content and a fake module.
"""
def _make_module(fname, content):
path = os.path.join(tmpdir, "sample_lib")
os.mkdir(path)
path = os.path.join(tmpdir, "sample_lib", "__init__.py")
with open(path, "w") as stream:
stream.write("'example module'\n__version__ = '1.2.3'")
if fname == "setup.cfg":
path = os.path.join(tmpdir, "pyproject.toml")
with open(path, "w") as stream:
stream.write(
"\n".join(
(
"[build-system]",
'requires = ["setuptools"]',
'build-backend = "setuptools.build_meta"',
)
)
)
path = os.path.join(tmpdir, fname)
with open(path, "w") as stream:
stream.write(dedent(content))
return path
return _make_module
@pytest.fixture(scope="session")
def fake_dists(tmp_path_factory, make_package, make_wheel):
"""
Generate distribution packages `small-fake-*`
"""
dists_path = tmp_path_factory.mktemp("dists")
pkgs = [
make_package("small-fake-a", version="0.1"),
make_package("small-fake-b", version="0.2"),
make_package("small-fake-c", version="0.3"),
]
for pkg in pkgs:
make_wheel(pkg, dists_path)
return dists_path
@pytest.fixture(scope="session")
def fake_dists_with_build_deps(tmp_path_factory, make_package, make_wheel):
"""Generate distribution packages with names that make sense for testing build deps."""
dists_path = tmp_path_factory.mktemp("dists")
pkgs = [
make_package(
"fake_static_build_dep",
version="0.1",
install_requires=["fake_transient_run_dep"],
build_system_requires=["fake_transient_build_dep"],
),
make_package("fake_dynamic_build_dep_for_all", version="0.2"),
make_package("fake_dynamic_build_dep_for_sdist", version="0.3"),
make_package("fake_dynamic_build_dep_for_wheel", version="0.4"),
make_package("fake_dynamic_build_dep_for_editable", version="0.5"),
make_package("fake_direct_runtime_dep", version="0.1"),
make_package("fake_direct_extra_runtime_dep", version="0.2"),
make_package("fake_transient_build_dep", version="0.3"),
make_package("fake_transient_run_dep", version="0.3"),
]
for pkg in pkgs:
make_wheel(pkg, dists_path)
return dists_path
@pytest.fixture
def venv(tmp_path):
"""Create a temporary venv and get the path of its directory of executables."""
subprocess.run(
[sys.executable, "-m", "venv", os.fspath(tmp_path)],
check=True,
)
return tmp_path / ("Scripts" if platform.system() == "Windows" else "bin")
@pytest.fixture(autouse=True)
def _reset_log():
"""
Since piptools.logging.log is a global variable we have to restore its initial
state. Some tests can change logger verbosity which might cause a conflict
with other tests that depend on it.
"""
log.reset()
@pytest.fixture
def make_config_file(tmpdir_cwd):
"""
Make a config file for pip-tools with a given parameter set to a specific
value, returning a ``pathlib.Path`` to the config file.
"""
def _maker(
pyproject_param: str,
new_default: _t.Any,
config_file_name: str = DEFAULT_CONFIG_FILE_NAMES[0],
section: str = "pip-tools",
subsection: str | None = None,
) -> Path:
# Create a nested directory structure if config_file_name includes directories
config_dir = (tmpdir_cwd / config_file_name).parent
config_dir.mkdir(exist_ok=True, parents=True)
# Make a config file with this one config default override
config_file = tmpdir_cwd / config_file_name
nested_config = {pyproject_param: new_default}
if subsection:
nested_config = {subsection: nested_config}
config_to_dump = {"tool": {section: nested_config}}
config_file.write_text(tomli_w.dumps(config_to_dump))
return _t.cast(Path, config_file.relative_to(tmpdir_cwd))
return _maker
@pytest.fixture(scope="session")
def setuptools_wheel_path(tmp_path_factory):
"""
Ensure setuptools is downloaded and return the path to the download directory.
"""
tmp_wheels_path = tmp_path_factory.mktemp("tmp_wheels")
subprocess.check_call(
[
sys.executable,
"-Im",
"pip",
"download",
f"--dest={tmp_wheels_path.as_posix()}",
"--no-deps",
"setuptools",
],
)
return tmp_wheels_path
@pytest.fixture(scope="session")
def minimal_wheels_path(setuptools_wheel_path):
"""
Ensure minimal wheels and setuptools are downloaded and return the path.
"""
shutil.copytree(MINIMAL_WHEELS_PATH, setuptools_wheel_path, dirs_exist_ok=True)
return setuptools_wheel_path
| FakeRepository |
python | getsentry__sentry | src/sentry/monitors/validators.py | {
"start": 22384,
"end": 23138
} | class ____(serializers.Serializer):
status = serializers.ChoiceField(
choices=(
("ok", CheckInStatus.OK),
("error", CheckInStatus.ERROR),
("in_progress", CheckInStatus.IN_PROGRESS),
),
help_text="The status of the job run.",
)
duration = EmptyIntegerField(
required=False,
allow_null=True,
max_value=BoundedPositiveIntegerField.MAX_VALUE,
min_value=0,
help_text="Duration of the job run, in milliseconds.",
)
environment = serializers.CharField(
required=False,
allow_null=True,
help_text="Name of the environment.",
)
contexts = ContextsValidator(required=False, allow_null=True)
| MonitorCheckInValidator |
python | sympy__sympy | sympy/physics/control/lti.py | {
"start": 161725,
"end": 194030
} | class ____(MIMOLinearTimeInvariant):
r"""
A class for representing the MIMO (multiple-input and multiple-output)
generalization of the SISO (single-input and single-output) transfer function.
It is a matrix of transfer functions (``TransferFunction``, SISO-``Series`` or SISO-``Parallel``).
There is only one argument, ``arg`` which is also the compulsory argument.
``arg`` is expected to be strictly of the type list of lists
which holds the transfer functions or reducible to transfer functions.
Parameters
==========
arg : Nested ``List`` (strictly).
Users are expected to input a nested list of ``TransferFunction``, ``Series``
and/or ``Parallel`` objects.
Examples
========
.. note::
``pprint()`` can be used for better visualization of ``TransferFunctionMatrix`` objects.
>>> from sympy.abc import s, p, a
>>> from sympy import pprint
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> tf_1 = TransferFunction(s + a, s**2 + s + 1, s)
>>> tf_2 = TransferFunction(p**4 - 3*p + 2, s + p, s)
>>> tf_3 = TransferFunction(3, s + 2, s)
>>> tf_4 = TransferFunction(-a + p, 9*s - 9, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_3]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)))
>>> tfm_1.var
s
>>> tfm_1.num_inputs
1
>>> tfm_1.num_outputs
3
>>> tfm_1.shape
(3, 1)
>>> tfm_1.args
(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)),)
>>> tfm_2 = TransferFunctionMatrix([[tf_1, -tf_3], [tf_2, -tf_1], [tf_3, -tf_2]])
>>> tfm_2
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(tfm_2, use_unicode=False) # pretty-printing for better visualization
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
TransferFunctionMatrix can be transposed, if user wants to switch the input and output transfer functions
>>> tfm_2.transpose()
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(3, s + 2, s)), (TransferFunction(-3, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(_, use_unicode=False)
[ 4 ]
[ a + s p - 3*p + 2 3 ]
[---------- ------------ ----- ]
[ 2 p + s s + 2 ]
[s + s + 1 ]
[ ]
[ 4 ]
[ -3 -a - s - p + 3*p - 2]
[ ----- ---------- --------------]
[ s + 2 2 p + s ]
[ s + s + 1 ]{t}
>>> tf_5 = TransferFunction(5, s, s)
>>> tf_6 = TransferFunction(5*s, (2 + s**2), s)
>>> tf_7 = TransferFunction(5, (s*(2 + s**2)), s)
>>> tf_8 = TransferFunction(5, 1, s)
>>> tfm_3 = TransferFunctionMatrix([[tf_5, tf_6], [tf_7, tf_8]])
>>> tfm_3
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))))
>>> pprint(tfm_3, use_unicode=False)
[ 5 5*s ]
[ - ------]
[ s 2 ]
[ s + 2]
[ ]
[ 5 5 ]
[---------- - ]
[ / 2 \ 1 ]
[s*\s + 2/ ]{t}
>>> tfm_3.var
s
>>> tfm_3.shape
(2, 2)
>>> tfm_3.num_outputs
2
>>> tfm_3.num_inputs
2
>>> tfm_3.args
(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))),)
To access the ``TransferFunction`` at any index in the ``TransferFunctionMatrix``, use the index notation.
>>> tfm_3[1, 0] # gives the TransferFunction present at 2nd Row and 1st Col. Similar to that in Matrix classes
TransferFunction(5, s*(s**2 + 2), s)
>>> tfm_3[0, 0] # gives the TransferFunction present at 1st Row and 1st Col.
TransferFunction(5, s, s)
>>> tfm_3[:, 0] # gives the first column
TransferFunctionMatrix(((TransferFunction(5, s, s),), (TransferFunction(5, s*(s**2 + 2), s),)))
>>> pprint(_, use_unicode=False)
[ 5 ]
[ - ]
[ s ]
[ ]
[ 5 ]
[----------]
[ / 2 \]
[s*\s + 2/]{t}
>>> tfm_3[0, :] # gives the first row
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)),))
>>> pprint(_, use_unicode=False)
[5 5*s ]
[- ------]
[s 2 ]
[ s + 2]{t}
To negate a transfer function matrix, ``-`` operator can be prepended:
>>> tfm_4 = TransferFunctionMatrix([[tf_2], [-tf_1], [tf_3]])
>>> -tfm_4
TransferFunctionMatrix(((TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(-3, s + 2, s),)))
>>> tfm_5 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, -tf_1]])
>>> -tfm_5
TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s)), (TransferFunction(-3, s + 2, s), TransferFunction(a + s, s**2 + s + 1, s))))
``subs()`` returns the ``TransferFunctionMatrix`` object with the value substituted in the expression. This will not
mutate your original ``TransferFunctionMatrix``.
>>> tfm_2.subs(p, 2) # substituting p everywhere in tfm_2 with 2.
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ a + s -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -a - s ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
>>> pprint(tfm_2, use_unicode=False) # State of tfm_2 is unchanged after substitution
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
``subs()`` also supports multiple substitutions.
>>> tfm_2.subs({p: 2, a: 1}) # substituting p with 2 and a with 1
TransferFunctionMatrix(((TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-s - 1, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ s + 1 -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -s - 1 ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
Users can reduce the ``Series`` and ``Parallel`` elements of the matrix to ``TransferFunction`` by using
``doit()``.
>>> tfm_6 = TransferFunctionMatrix([[Series(tf_3, tf_4), Parallel(tf_3, tf_4)]])
>>> tfm_6
TransferFunctionMatrix(((Series(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s)), Parallel(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s))),))
>>> pprint(tfm_6, use_unicode=False)
[-a + p 3 -a + p 3 ]
[-------*----- ------- + -----]
[9*s - 9 s + 2 9*s - 9 s + 2]{t}
>>> tfm_6.doit()
TransferFunctionMatrix(((TransferFunction(-3*a + 3*p, (s + 2)*(9*s - 9), s), TransferFunction(27*s + (-a + p)*(s + 2) - 27, (s + 2)*(9*s - 9), s)),))
>>> pprint(_, use_unicode=False)
[ -3*a + 3*p 27*s + (-a + p)*(s + 2) - 27]
[----------------- ----------------------------]
[(s + 2)*(9*s - 9) (s + 2)*(9*s - 9) ]{t}
>>> tf_9 = TransferFunction(1, s, s)
>>> tf_10 = TransferFunction(1, s**2, s)
>>> tfm_7 = TransferFunctionMatrix([[Series(tf_9, tf_10), tf_9], [tf_10, Parallel(tf_9, tf_10)]])
>>> tfm_7
TransferFunctionMatrix(((Series(TransferFunction(1, s, s), TransferFunction(1, s**2, s)), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), Parallel(TransferFunction(1, s, s), TransferFunction(1, s**2, s)))))
>>> pprint(tfm_7, use_unicode=False)
[ 1 1 ]
[---- - ]
[ 2 s ]
[s*s ]
[ ]
[ 1 1 1]
[ -- -- + -]
[ 2 2 s]
[ s s ]{t}
>>> tfm_7.doit()
TransferFunctionMatrix(((TransferFunction(1, s**3, s), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), TransferFunction(s**2 + s, s**3, s))))
>>> pprint(_, use_unicode=False)
[1 1 ]
[-- - ]
[ 3 s ]
[s ]
[ ]
[ 2 ]
[1 s + s]
[-- ------]
[ 2 3 ]
[s s ]{t}
Addition, subtraction, and multiplication of transfer function matrices can form
unevaluated ``Series`` or ``Parallel`` objects.
- For addition and subtraction:
All the transfer function matrices must have the same shape.
- For multiplication (C = A * B):
The number of inputs of the first transfer function matrix (A) must be equal to the
number of outputs of the second transfer function matrix (B).
Also, use pretty-printing (``pprint``) to analyse better.
>>> tfm_8 = TransferFunctionMatrix([[tf_3], [tf_2], [-tf_1]])
>>> tfm_9 = TransferFunctionMatrix([[-tf_3]])
>>> tfm_10 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_4]])
>>> tfm_11 = TransferFunctionMatrix([[tf_4], [-tf_1]])
>>> tfm_12 = TransferFunctionMatrix([[tf_4, -tf_1, tf_3], [-tf_2, -tf_4, -tf_3]])
>>> tfm_8 + tfm_10
MIMOParallel(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))))
>>> pprint(_, use_unicode=False)
[ 3 ] [ a + s ]
[ ----- ] [ ---------- ]
[ s + 2 ] [ 2 ]
[ ] [ s + s + 1 ]
[ 4 ] [ ]
[p - 3*p + 2] [ 4 ]
[------------] + [p - 3*p + 2]
[ p + s ] [------------]
[ ] [ p + s ]
[ -a - s ] [ ]
[ ---------- ] [ -a + p ]
[ 2 ] [ ------- ]
[ s + s + 1 ]{t} [ 9*s - 9 ]{t}
>>> -tfm_10 - tfm_8
MIMOParallel(TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a - p, 9*s - 9, s),))), TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),))))
>>> pprint(_, use_unicode=False)
[ -a - s ] [ -3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [- p + 3*p - 2]
[- p + 3*p - 2] + [--------------]
[--------------] [ p + s ]
[ p + s ] [ ]
[ ] [ a + s ]
[ a - p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
>>> tfm_12 * tfm_8
MIMOSeries(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2]
[ ] *[------------]
[ 4 ] [ p + s ]
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_12 * tfm_8 * tfm_9
MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2] [ -3 ]
[ ] *[------------] *[-----]
[ 4 ] [ p + s ] [s + 2]{t}
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_10 + tfm_8*tfm_9
MIMOParallel(TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))), MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),)))))
>>> pprint(_, use_unicode=False)
[ a + s ] [ 3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [p - 3*p + 2] [ -3 ]
[p - 3*p + 2] + [------------] *[-----]
[------------] [ p + s ] [s + 2]{t}
[ p + s ] [ ]
[ ] [ -a - s ]
[ -a + p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
These unevaluated ``Series`` or ``Parallel`` objects can convert into the
resultant transfer function matrix using ``.doit()`` method or by
``.rewrite(TransferFunctionMatrix)``.
>>> (-tfm_8 + tfm_10 + tfm_8*tfm_9).doit()
TransferFunctionMatrix(((TransferFunction((a + s)*(s + 2)**3 - 3*(s + 2)**2*(s**2 + s + 1) - 9*(s + 2)*(s**2 + s + 1), (s + 2)**3*(s**2 + s + 1), s),), (TransferFunction((p + s)*(-3*p**4 + 9*p - 6), (p + s)**2*(s + 2), s),), (TransferFunction((-a + p)*(s + 2)*(s**2 + s + 1)**2 + (a + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + (3*a + 3*s)*(9*s - 9)*(s**2 + s + 1), (s + 2)*(9*s - 9)*(s**2 + s + 1)**2, s),)))
>>> (-tfm_12 * -tfm_8 * -tfm_9).rewrite(TransferFunctionMatrix)
TransferFunctionMatrix(((TransferFunction(3*(-3*a + 3*p)*(p + s)*(s + 2)*(s**2 + s + 1)**2 + 3*(-3*a - 3*s)*(p + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + 3*(a + s)*(s + 2)**2*(9*s - 9)*(-p**4 + 3*p - 2)*(s**2 + s + 1), (p + s)*(s + 2)**3*(9*s - 9)*(s**2 + s + 1)**2, s),), (TransferFunction(3*(-a + p)*(p + s)*(s + 2)**2*(-p**4 + 3*p - 2)*(s**2 + s + 1) + 3*(3*a + 3*s)*(p + s)**2*(s + 2)*(9*s - 9) + 3*(p + s)*(s + 2)*(9*s - 9)*(-3*p**4 + 9*p - 6)*(s**2 + s + 1), (p + s)**2*(s + 2)**3*(9*s - 9)*(s**2 + s + 1), s),)))
See Also
========
DiscreteTransferFunction, TransferFunction, MIMOSeries, MIMOParallel, Feedback
"""
def __new__(cls, arg):
expr_mat_arg = []
try:
var = arg[0][0].var
except TypeError:
raise ValueError(filldedent("""
`arg` param in TransferFunctionMatrix should
strictly be a nested list containing TransferFunctionBase
objects."""))
for row in arg:
temp = []
for element in row:
if not isinstance(element, SISOLinearTimeInvariant):
raise TypeError(filldedent("""
Each element is expected to be of
type `SISOLinearTimeInvariant`."""))
if var != element.var:
raise ValueError(filldedent("""
Conflicting value(s) found for `var`.
All TransferFunction instances in TransferFunctionMatrix
should use the same complex variable in Laplace domain
or z-domain."""))
temp.append(element.to_expr())
expr_mat_arg.append(temp)
_check_time_compatibility([sys for row in arg for sys in row])
if isinstance(arg, (tuple, list, Tuple)):
# Making nested Tuple (sympy.core.containers.Tuple) from nested list or nested Python tuple
arg = Tuple(*(Tuple(*r, sympify=False) for r in arg), sympify=False)
obj = super(TransferFunctionMatrix, cls).__new__(cls, arg)
obj._expr_mat = ImmutableMatrix(expr_mat_arg)
obj.is_StateSpace_object = False
obj._is_continuous = arg[0][0].is_continuous
return obj
@classmethod
def from_Matrix(cls, matrix, var, sampling_time=0):
"""
Creates a new ``TransferFunctionMatrix`` efficiently from a SymPy Matrix
of ``Expr`` objects.
Parameters
==========
matrix : ``ImmutableMatrix`` having ``Expr``/``Number`` elements.
var : Symbol
Complex variable of the Laplace transform or z-transform which will
be used by the all the transfer function objects in the
``TransferFunctionMatrix``.
sampling_time : Number, Symbol, optional
Sampling time for the discrete-time transfer function matrix.
Default is 0, which means that the transfer function matrix will be
treated as a continuous-time transfer function matrix.
Examples
========
>>> from sympy.abc import s, z
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix, pprint
>>> M = Matrix([[s, 1/s], [1/(s+1), s]])
>>> M_tf = TransferFunctionMatrix.from_Matrix(M, s)
>>> pprint(M_tf, use_unicode=False)
[ s 1]
[ - -]
[ 1 s]
[ ]
[ 1 s]
[----- -]
[s + 1 1]{t}
>>> M_tf.elem_poles()
[[[], [0]], [[-1], []]]
>>> M_tf.elem_zeros()
[[[0], []], [[], [0]]]
>>> M_2 = Matrix([[z/(z-1), z/(z-8)], [z**2/(z**2-2+1), z]])
>>> M2_tf = TransferFunctionMatrix.from_Matrix(M_2, z, 0.1)
>>> pprint(M2_tf, use_unicode=False)
[ z z ]
[----- -----]
[z - 1 z - 8]
[ ]
[ 2 ]
[ z z ]
[------ - ]
[ 2 1 ]
[z - 1 ]{k}
[st: 0.100000000000000]
"""
return _to_TFM(matrix, var, sampling_time)
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions or
``Series``/``Parallel`` objects in a transfer function matrix.
Examples
========
>>> from sympy.abc import p, s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> G4 = TransferFunction(s + 1, s**2 + s + 1, s)
>>> S1 = Series(G1, G2)
>>> S2 = Series(-G3, Parallel(G2, -G1))
>>> tfm1 = TransferFunctionMatrix([[G1], [G2], [G3]])
>>> tfm1.var
p
>>> tfm2 = TransferFunctionMatrix([[-S1, -S2], [S1, S2]])
>>> tfm2.var
p
>>> tfm3 = TransferFunctionMatrix([[G4]])
>>> tfm3.var
s
"""
return self.args[0][0][0].var
@property
def num_inputs(self):
"""
Returns the number of inputs of the system.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> G1 = TransferFunction(s + 3, s**2 - 3, s)
>>> G2 = TransferFunction(4, s**2, s)
>>> G3 = TransferFunction(p**2 + s**2, p - 3, s)
>>> tfm_1 = TransferFunctionMatrix([[G2, -G1, G3], [-G2, -G1, -G3]])
>>> tfm_1.num_inputs
3
See Also
========
num_outputs
"""
return self._expr_mat.shape[1]
@property
def num_outputs(self):
"""
Returns the number of outputs of the system.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix
>>> M_1 = Matrix([[s], [1/s]])
>>> TFM = TransferFunctionMatrix.from_Matrix(M_1, s)
>>> print(TFM)
TransferFunctionMatrix(((TransferFunction(s, 1, s),), (TransferFunction(1, s, s),)))
>>> TFM.num_outputs
2
See Also
========
num_inputs
"""
return self._expr_mat.shape[0]
@property
def shape(self):
"""
Returns the shape of the transfer function matrix, that is,
``(# of outputs, # of inputs)``.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf1 = TransferFunction(p**2 - 1, s**4 + s**3 - p, p)
>>> tf2 = TransferFunction(1 - p, p**2 - 3*p + 7, p)
>>> tf3 = TransferFunction(3, 4, p)
>>> tfm1 = TransferFunctionMatrix([[tf1, -tf2]])
>>> tfm1.shape
(1, 2)
>>> tfm2 = TransferFunctionMatrix([[-tf2, tf3], [tf1, -tf1]])
>>> tfm2.shape
(2, 2)
"""
return self._expr_mat.shape
def __neg__(self):
neg = -self._expr_mat
return _to_TFM(neg, self.var, self.sampling_time)
@_check_other_MIMO
def __add__(self, other):
if not isinstance(other, MIMOParallel):
return MIMOParallel(self, other)
other_arg_list = list(other.args)
return MIMOParallel(self, *other_arg_list)
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
@_check_other_MIMO
def __mul__(self, other):
if not isinstance(other, MIMOSeries):
return MIMOSeries(other, self)
other_arg_list = list(other.args)
return MIMOSeries(*other_arg_list, self)
def __getitem__(self, key):
trunc = self._expr_mat.__getitem__(key)
if isinstance(trunc, ImmutableMatrix):
return _to_TFM(trunc, self.var, self.sampling_time)
if self.sampling_time == 0:
to_tf = lambda expr: \
TransferFunction.from_rational_expression(expr, self.var)
else:
to_tf = lambda expr: \
DiscreteTransferFunction.from_rational_expression(expr, self.var,
self.sampling_time)
return to_tf(trunc)
def transpose(self):
"""
Returns the transpose of the ``TransferFunctionMatrix``
(switched input and output layers).
"""
transposed_mat = self._expr_mat.transpose()
return _to_TFM(transposed_mat, self.var, self.sampling_time)
def elem_poles(self):
"""
Returns the poles of each element of the ``TransferFunctionMatrix``.
.. note::
Actual poles of a MIMO system are NOT the poles of individual
elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s + 2, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s + 2, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_poles()
[[[-1], [-2, -1]], [[-2, -1], [-5/2 + sqrt(65)/2, -sqrt(65)/2 - 5/2]]]
See Also
========
elem_zeros
"""
return [[element.poles() for element in row] for row in \
self.doit().args[0]]
def elem_zeros(self):
"""
Returns the zeros of each element of the ``TransferFunctionMatrix``.
.. note::
Actual zeros of a MIMO system are NOT the zeros of individual
elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_zeros()
[[[], [-6]], [[-3], [4, 5]]]
See Also
========
elem_poles
"""
return [[element.zeros() for element in row] for row in \
self.doit().args[0]]
def eval_frequency(self, other):
"""
Evaluates system response of each transfer function in the
``TransferFunctionMatrix`` at any point in the real or complex plane.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> from sympy import I
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s))))
>>> tfm_1.eval_frequency(2)
Matrix([
[ 1, 2/3],
[5/12, 3/2]])
>>> tfm_1.eval_frequency(I*2)
Matrix([
[ 3/5 - 6*I/5, -I],
[3/20 - 11*I/20, -101/74 + 23*I/74]])
"""
mat = self._expr_mat.subs(self.var, other)
return mat.expand()
def _flat(self):
"""Returns flattened list of args in TransferFunctionMatrix"""
return [elem for tup in self.args[0] for elem in tup]
def _eval_evalf(self, prec):
"""
Calls evalf() on each transfer function in the transfer function
matrix
"""
dps = prec_to_dps(prec)
mat = self._expr_mat.applyfunc(lambda a: a.evalf(n=dps))
return _to_TFM(mat, self.var, self.sampling_time)
def _eval_simplify(self, **kwargs):
"""Simplifies the transfer function matrix"""
simp_mat = self._expr_mat.applyfunc(lambda a: cancel(a, expand=False))
return _to_TFM(simp_mat, self.var, self.sampling_time)
def expand(self, **hints):
"""Expands the transfer function matrix"""
expand_mat = self._expr_mat.expand(**hints)
return _to_TFM(expand_mat, self.var, self.sampling_time)
@property
def sampling_time(self):
return self.args[0][0][0].sampling_time
def create_state_space(A, B, C, D, sampling_time=0):
"""
Creates a new state space object.
sampling_time == 0 means continuous time state space.
sampling_time > 0 means discrete time state space.
Parameters
==========
sampling_time : Symbol, Number, optional
Default is 0.
Time interval between two consecutive sampling instants.
If sampling_time == 0, it is a continuous time state space,
else it is a discrete time state space.
Examples
========
>>> from sympy import Matrix
>>> from sympy.abc import t
>>> from sympy.physics.control.lti import create_state_space
>>> A = Matrix([[1,0],[0,1]])
>>> B = Matrix([1,0])
>>> C = Matrix([1,0]).T
>>> D = Matrix([0])
>>> create_state_space(A, B, C, D)
StateSpace(Matrix([
[1, 0],
[0, 1]]), Matrix([
[1],
[0]]), Matrix([[1, 0]]), Matrix([[0]]))
>>> create_state_space(A, B, C, D, t)
DiscreteStateSpace(Matrix([
[1, 0],
[0, 1]]), Matrix([
[1],
[0]]), Matrix([[1, 0]]), Matrix([[0]]), t)
See Also
========
StateSpace, DiscreteStateSpace
"""
if sampling_time == 0:
return StateSpace(A, B, C, D)
return DiscreteStateSpace(A, B, C, D, sampling_time)
| TransferFunctionMatrix |
python | huggingface__transformers | src/transformers/cli/chat.py | {
"start": 8088,
"end": 24709
} | class ____:
"""Chat with a model from the command line."""
# Defining a class to help with internal state but in practice it's just a method to call
# TODO: refactor into a proper module with helpers + 1 main method
def __init__(
self,
model_id: Annotated[str, typer.Argument(help="ID of the model to use (e.g. 'HuggingFaceTB/SmolLM3-3B').")],
base_url: Annotated[
Optional[str], typer.Argument(help="Base url to connect to (e.g. http://localhost:8000/v1).")
] = f"http://{DEFAULT_HTTP_ENDPOINT['hostname']}:{DEFAULT_HTTP_ENDPOINT['port']}",
generate_flags: Annotated[
list[str] | None,
typer.Argument(
help=(
"Flags to pass to `generate`, using a space as a separator between flags. Accepts booleans, numbers, "
"and lists of integers, more advanced parameterization should be set through --generation-config. "
"Example: `transformers chat <base_url> <model_id> max_new_tokens=100 do_sample=False eos_token_id=[1,2]`. "
"If you're a new user, check this basic flag guide: "
"https://huggingface.co/docs/transformers/llm_tutorial#common-options"
)
),
] = None,
# General settings
user: Annotated[
str | None,
typer.Option(help="Username to display in chat interface. Defaults to the current user's name."),
] = None,
system_prompt: Annotated[str | None, typer.Option(help="System prompt.")] = None,
save_folder: Annotated[str, typer.Option(help="Folder to save chat history.")] = "./chat_history/",
examples_path: Annotated[str | None, typer.Option(help="Path to a yaml file with examples.")] = None,
# Generation settings
generation_config: Annotated[
str | None,
typer.Option(
help="Path to a local generation config file or to a HuggingFace repo containing a `generation_config.json` file. Other generation settings passed as CLI arguments will be applied on top of this generation config."
),
] = None,
) -> None:
"""Chat with a model from the command line."""
self.base_url = base_url
parsed = urlparse(self.base_url)
if parsed.hostname == DEFAULT_HTTP_ENDPOINT["hostname"] and parsed.port == DEFAULT_HTTP_ENDPOINT["port"]:
self.check_health(self.base_url)
self.model_id = model_id
self.system_prompt = system_prompt
self.save_folder = save_folder
# Generation settings
config = load_generation_config(generation_config)
config.update(do_sample=True, max_new_tokens=256) # some default values
config.update(**parse_generate_flags(generate_flags))
self.config = config
self.settings = {"base_url": base_url, "model_id": model_id, "config": self.config.to_dict()}
# User settings
self.user = user if user is not None else get_username()
# Load examples
if examples_path:
with open(examples_path) as f:
self.examples = yaml.safe_load(f)
else:
self.examples = DEFAULT_EXAMPLES
# Check requirements
if not is_rich_available():
raise ImportError("You need to install rich to use the chat interface. (`pip install rich`)")
# Run chat session
asyncio.run(self._inner_run())
@staticmethod
def check_health(url):
health_url = urljoin(url + "/", "health")
try:
output = httpx.get(health_url)
if output.status_code != 200:
raise ValueError(
f"The server running on {url} returned status code {output.status_code} on health check (/health)."
)
except httpx.ConnectError:
raise ValueError(
f"No server currently running on {url}. To run a local server, please run `transformers serve` in a"
f"separate shell. Find more information here: https://huggingface.co/docs/transformers/serving"
)
return True
def handle_non_exit_user_commands(
self,
user_input: str,
interface: RichInterface,
examples: dict[str, dict[str, str]],
config: GenerationConfig,
chat: list[dict],
) -> tuple[list[dict], GenerationConfig]:
"""
Handles all user commands except for `!exit`. May update the chat history (e.g. reset it) or the
generation config (e.g. set a new flag).
"""
valid_command = True
if user_input == "!clear":
chat = new_chat_history(self.system_prompt)
interface.clear()
elif user_input == "!help":
interface.print_help()
elif user_input.startswith("!save") and len(user_input.split()) < 2:
split_input = user_input.split()
filename = (
split_input[1]
if len(split_input) == 2
else os.path.join(self.save_folder, self.model_id, f"chat_{time.strftime('%Y-%m-%d_%H-%M-%S')}.json")
)
save_chat(filename=filename, chat=chat, settings=self.settings)
interface.print_color(text=f"Chat saved to {filename}!", color="green")
elif user_input.startswith("!set"):
# splits the new args into a list of strings, each string being a `flag=value` pair (same format as
# `generate_flags`)
new_generate_flags = user_input[4:].strip()
new_generate_flags = new_generate_flags.split()
# sanity check: each member in the list must have an =
for flag in new_generate_flags:
if "=" not in flag:
interface.print_color(
text=(
f"Invalid flag format, missing `=` after `{flag}`. Please use the format "
"`arg_1=value_1 arg_2=value_2 ...`."
),
color="red",
)
break
else:
# Update config from user flags
config.update(**parse_generate_flags(new_generate_flags))
elif user_input.startswith("!example") and len(user_input.split()) == 2:
example_name = user_input.split()[1]
if example_name in examples:
interface.clear()
chat = []
interface.print_user_message(examples[example_name]["text"])
chat.append({"role": "user", "content": examples[example_name]["text"]})
else:
example_error = (
f"Example {example_name} not found in list of available examples: {list(examples.keys())}."
)
interface.print_color(text=example_error, color="red")
elif user_input == "!status":
interface.print_status(config=config)
else:
valid_command = False
interface.print_color(text=f"'{user_input}' is not a valid command. Showing help message.", color="red")
interface.print_help()
return chat, valid_command, config
async def _inner_run(self):
interface = RichInterface(model_id=self.model_id, user_id=self.user)
interface.clear()
chat = new_chat_history(self.system_prompt)
# Starts the session with a minimal help message at the top, so that a user doesn't get stuck
interface.print_help(minimal=True)
config = self.config
async with AsyncInferenceClient(base_url=self.base_url) as client:
pending_user_input: Optional[str] = None
while True:
try:
if pending_user_input is not None:
user_input = pending_user_input
pending_user_input = None
interface.print_user_message(user_input)
else:
user_input = interface.input()
# User commands
if user_input == "!exit":
break
elif user_input == "!clear":
chat = new_chat_history(self.system_prompt)
interface.clear()
continue
elif user_input == "!help":
interface.print_help()
continue
elif user_input.startswith("!save") and len(user_input.split()) < 2:
split_input = user_input.split()
filename = (
split_input[1]
if len(split_input) == 2
else os.path.join(
self.save_folder, self.model_id, f"chat_{time.strftime('%Y-%m-%d_%H-%M-%S')}.json"
)
)
save_chat(filename=filename, chat=chat, settings=self.settings)
interface.print_color(text=f"Chat saved to {filename}!", color="green")
continue
elif user_input.startswith("!set"):
# splits the new args into a list of strings, each string being a `flag=value` pair (same format as
# `generate_flags`)
new_generate_flags = user_input[4:].strip()
new_generate_flags = new_generate_flags.split()
# sanity check: each member in the list must have an =
for flag in new_generate_flags:
if "=" not in flag:
interface.print_color(
text=(
f"Invalid flag format, missing `=` after `{flag}`. Please use the format "
"`arg_1=value_1 arg_2=value_2 ...`."
),
color="red",
)
break
else:
# Update config from user flags
config.update(**parse_generate_flags(new_generate_flags))
continue
elif user_input.startswith("!example") and len(user_input.split()) == 2:
example_name = user_input.split()[1]
if example_name in self.examples:
interface.clear()
chat = []
interface.print_user_message(self.examples[example_name]["text"])
chat.append({"role": "user", "content": self.examples[example_name]["text"]})
else:
example_error = f"Example {example_name} not found in list of available examples: {list(self.examples.keys())}."
interface.print_color(text=example_error, color="red")
elif user_input == "!status":
interface.print_status(config=config)
continue
elif user_input.startswith("!"):
interface.print_color(
text=f"'{user_input}' is not a valid command. Showing help message.", color="red"
)
interface.print_help()
continue
else:
chat.append({"role": "user", "content": user_input})
stream = client.chat_completion(
chat,
stream=True,
model=self.model_id,
extra_body={
"generation_config": config.to_json_string(),
"model": self.model_id,
},
)
model_output, finish_reason = await interface.stream_output(stream)
chat.append({"role": "assistant", "content": model_output})
if finish_reason == "length":
interface.print_color("Generation stopped after reaching the token limit.", "yellow")
if interface.confirm("Continue generating?"):
pending_user_input = "Please continue. Do not repeat text.”"
continue
except KeyboardInterrupt:
break
def load_generation_config(generation_config: str | None) -> GenerationConfig:
if generation_config is None:
return GenerationConfig()
if ".json" in generation_config: # is a local file
dirname = os.path.dirname(generation_config)
filename = os.path.basename(generation_config)
return GenerationConfig.from_pretrained(dirname, filename)
else:
return GenerationConfig.from_pretrained(generation_config)
def parse_generate_flags(generate_flags: list[str] | None) -> dict:
"""Parses the generate flags from the user input into a dictionary of `generate` kwargs."""
if generate_flags is None or len(generate_flags) == 0:
return {}
# Assumption: `generate_flags` is a list of strings, each string being a `flag=value` pair, that can be parsed
# into a json string if we:
# 1. Add quotes around each flag name
generate_flags_as_dict = {'"' + flag.split("=")[0] + '"': flag.split("=")[1] for flag in generate_flags}
# 2. Handle types:
# 2. a. booleans should be lowercase, None should be null
generate_flags_as_dict = {
k: v.lower() if v.lower() in ["true", "false"] else v for k, v in generate_flags_as_dict.items()
}
generate_flags_as_dict = {k: "null" if v == "None" else v for k, v in generate_flags_as_dict.items()}
# 2. b. strings should be quoted
def is_number(s: str) -> bool:
# handle negative numbers
s = s.removeprefix("-")
return s.replace(".", "", 1).isdigit()
generate_flags_as_dict = {k: f'"{v}"' if not is_number(v) else v for k, v in generate_flags_as_dict.items()}
# 2. c. [no processing needed] lists are lists of ints because `generate` doesn't take lists of strings :)
# We also mention in the help message that we only accept lists of ints for now.
# 3. Join the result into a comma separated string
generate_flags_string = ", ".join([f"{k}: {v}" for k, v in generate_flags_as_dict.items()])
# 4. Add the opening/closing brackets
generate_flags_string = "{" + generate_flags_string + "}"
# 5. Remove quotes around boolean/null and around lists
generate_flags_string = generate_flags_string.replace('"null"', "null")
generate_flags_string = generate_flags_string.replace('"true"', "true")
generate_flags_string = generate_flags_string.replace('"false"', "false")
generate_flags_string = generate_flags_string.replace('"[', "[")
generate_flags_string = generate_flags_string.replace(']"', "]")
# 6. Replace the `=` with `:`
generate_flags_string = generate_flags_string.replace("=", ":")
try:
processed_generate_flags = json.loads(generate_flags_string)
except json.JSONDecodeError:
raise ValueError(
"Failed to convert `generate_flags` into a valid JSON object."
"\n`generate_flags` = {generate_flags}"
"\nConverted JSON string = {generate_flags_string}"
)
return processed_generate_flags
def new_chat_history(system_prompt: str | None = None) -> list[dict]:
"""Returns a new chat conversation."""
return [{"role": "system", "content": system_prompt}] if system_prompt else []
def save_chat(filename: str, chat: list[dict], settings: dict) -> str:
"""Saves the chat history to a file."""
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
json.dump({"settings": settings, "chat_history": chat}, f, indent=4)
return os.path.abspath(filename)
def get_username() -> str:
"""Returns the username of the current user."""
if platform.system() == "Windows":
return os.getlogin()
else:
return pwd.getpwuid(os.getuid()).pw_name
if __name__ == "__main__":
Chat(model_id="meta-llama/Llama-3.2-3b-Instruct")
| Chat |
python | huggingface__transformers | tests/models/dab_detr/test_modeling_dab_detr.py | {
"start": 31825,
"end": 35126
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return ConditionalDetrImageProcessor.from_pretrained(CHECKPOINT) if is_vision_available() else None
def test_inference_no_head(self):
model = DabDetrModel.from_pretrained(CHECKPOINT).to(torch_device)
image_processor = self.default_image_processor
image = prepare_img()
encoding = image_processor(images=image, return_tensors="pt").to(torch_device)
with torch.no_grad():
outputs = model(pixel_values=encoding.pixel_values)
expected_shape = torch.Size((1, 300, 256))
self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
expected_slice = torch.tensor(
[
[-0.4879, -0.2594, 0.4524],
[-0.4997, -0.4258, 0.4329],
[-0.8220, -0.4996, 0.0577],
]
).to(torch_device)
torch.testing.assert_close(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=2e-4, rtol=2e-4)
def test_inference_object_detection_head(self):
model = DabDetrForObjectDetection.from_pretrained(CHECKPOINT).to(torch_device)
image_processor = self.default_image_processor
image = prepare_img()
encoding = image_processor(images=image, return_tensors="pt").to(torch_device)
pixel_values = encoding["pixel_values"].to(torch_device)
with torch.no_grad():
outputs = model(pixel_values)
# verify logits + box predictions
expected_shape_logits = torch.Size((1, model.config.num_queries, model.config.num_labels))
self.assertEqual(outputs.logits.shape, expected_shape_logits)
expected_slice_logits = torch.tensor(
[
[-10.1764, -5.5247, -8.9324],
[-9.8137, -5.6730, -7.5163],
[-10.3056, -5.6075, -8.5935],
]
).to(torch_device)
torch.testing.assert_close(outputs.logits[0, :3, :3], expected_slice_logits, atol=3e-4, rtol=3e-4)
expected_shape_boxes = torch.Size((1, model.config.num_queries, 4))
self.assertEqual(outputs.pred_boxes.shape, expected_shape_boxes)
expected_slice_boxes = torch.tensor(
[
[0.3708, 0.3000, 0.2754],
[0.5211, 0.6126, 0.9494],
[0.2897, 0.6731, 0.5460],
]
).to(torch_device)
torch.testing.assert_close(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=3e-4, rtol=3e-4)
# verify postprocessing
results = image_processor.post_process_object_detection(
outputs, threshold=0.3, target_sizes=[image.size[::-1]]
)[0]
expected_scores = torch.tensor([0.8732, 0.8563, 0.8554, 0.6080, 0.5895]).to(torch_device)
expected_labels = [17, 75, 17, 75, 63]
expected_boxes = torch.tensor([14.6931, 49.3886, 320.5176, 469.2762]).to(torch_device)
self.assertEqual(len(results["scores"]), 5)
torch.testing.assert_close(results["scores"], expected_scores, atol=3e-4, rtol=3e-4)
self.assertSequenceEqual(results["labels"].tolist(), expected_labels)
torch.testing.assert_close(results["boxes"][0, :], expected_boxes, atol=3e-4, rtol=3e-4)
| DabDetrModelIntegrationTests |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 28089,
"end": 29487
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = AlignTextAttention(config)
self.intermediate = AlignTextIntermediate(config)
self.output = AlignTextOutput(config)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = False,
**kwargs,
) -> tuple[torch.Tensor]:
self_attention_outputs = self.attention(
hidden_states,
attention_mask=attention_mask,
output_attentions=output_attentions,
**kwargs,
)
attention_output = self_attention_outputs[0]
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
layer_output = apply_chunking_to_forward(
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
)
outputs = (layer_output,) + outputs
return outputs
def feed_forward_chunk(self, attention_output):
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output)
return layer_output
| AlignTextLayer |
python | cython__cython | Cython/Compiler/ParseTreeTransforms.py | {
"start": 71107,
"end": 75966
} | class ____(VisitorTransform, SkipDeclarations):
# used from within CreateClosureClasses
def __call__(self, node):
from . import Visitor
assert isinstance(node, ExprNodes.GeneratorExpressionNode)
self.gen_node = node
self.args = list(node.def_node.args)
self.call_parameters = list(node.call_parameters)
self.tag_count = 0
self.substitutions = {}
self.visitchildren(node)
for k, v in self.substitutions.items():
# doing another search for replacements here (at the end) allows us to sweep up
# CloneNodes too (which are often generated by the optimizer)
# (it could arguably be done more efficiently with a single traversal though)
Visitor.recursively_replace_node(node, k, v)
node.def_node.args = self.args
node.call_parameters = self.call_parameters
return node
def visit_GeneratorExpressionNode(self, node):
# a generator can also be substituted itself, so handle that case
new_node = self._handle_ExprNode(node, do_visit_children=False)
# However do not traverse into it. A new _HandleGeneratorArguments visitor will be used
# elsewhere to do that.
return node
def _handle_ExprNode(self, node, do_visit_children):
if (node.generator_arg_tag is not None and self.gen_node is not None and
self.gen_node == node.generator_arg_tag):
pos = node.pos
# The reason for using ".x" as the name is that this is how CPython
# tracks internal variables in loops (e.g.
# { locals() for v in range(10) }
# will produce "v" and ".0"). We don't replicate this behaviour completely
# but use it as a starting point
name_source = self.tag_count
self.tag_count += 1
name = EncodedString(".{}".format(name_source))
def_node = self.gen_node.def_node
if not def_node.local_scope.lookup_here(name):
from . import Symtab
cname = EncodedString(Naming.genexpr_arg_prefix + Symtab.punycodify_name(str(name_source)))
name_decl = Nodes.CNameDeclaratorNode(pos=pos, name=name)
type = node.type
# strip away cv types - they shouldn't be applied to the
# function argument or to the closure struct.
# It isn't obvious whether the right thing to do would be to capture by reference or by
# value (C++ itself doesn't know either for lambda functions and forces a choice).
# However, capture by reference involves converting to FakeReference which would require
# re-analysing AttributeNodes. Therefore I've picked capture-by-value out of convenience
# TODO - could probably be optimized by making the arg a reference but the closure not
# (see https://github.com/cython/cython/issues/2468)
type = PyrexTypes.remove_cv_ref(type, remove_fakeref=False)
name_decl.type = type
new_arg = Nodes.CArgDeclNode(pos=pos, declarator=name_decl,
base_type=None, default=None, annotation=None)
new_arg.name = name_decl.name
new_arg.type = type
self.args.append(new_arg)
node.generator_arg_tag = None # avoid the possibility of this being caught again
self.call_parameters.append(node)
new_arg.entry = def_node.declare_argument(def_node.local_scope, new_arg)
new_arg.entry.cname = cname
new_arg.entry.in_closure = True
if do_visit_children:
# now visit the Nodes's children (but remove self.gen_node to not to further
# argument substitution)
gen_node, self.gen_node = self.gen_node, None
self.visitchildren(node)
self.gen_node = gen_node
# replace the node inside the generator with a looked-up name
# (initialized_check can safely be False because the source variable will be checked
# before it is captured if the check is required)
name_node = ExprNodes.NameNode(pos, name=name, initialized_check=False)
name_node.entry = self.gen_node.def_node.gbody.local_scope.lookup(name_node.name)
name_node.type = name_node.entry.type
self.substitutions[node] = name_node
return name_node
if do_visit_children:
self.visitchildren(node)
return node
def visit_ExprNode(self, node):
return self._handle_ExprNode(node, True)
visit_Node = VisitorTransform.recurse_to_children
| _HandleGeneratorArguments |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_onetimes.py | {
"start": 1826,
"end": 3800
} | class ____(StreamTestCase):
_STREAM_NAME = "onetimes"
@HttpMocker()
def test_state_message_produced_while_read_and_state_match_latest_record(self, http_mocker: HttpMocker) -> None:
min_cursor_value = "2024-01-01T00:00:00+00:00"
max_cursor_value = "2024-02-01T00:00:00+00:00"
http_mocker.get(
self.stream_request().with_limit(250).with_updated_at_min(START_DATE).build(),
get_stream_response(_STREAM_NAME)
.with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD).with_cursor(min_cursor_value))
.with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD).with_cursor(max_cursor_value))
.build(),
)
output = read_incremental(self._config, _STREAM_NAME)
test_cursor_value = get_cursor_value_from_state_message(output, _CURSOR_FIELD)
assert test_cursor_value == max_cursor_value
@HttpMocker()
def test_given_multiple_pages_when_read_then_return_records_with_state(self, http_mocker: HttpMocker) -> None:
min_cursor_value = "2024-01-01T00:00:00+00:00"
max_cursor_value = "2024-02-01T00:00:00+00:00"
http_mocker.get(
self.stream_request().with_limit(250).with_next_page_token(NEXT_PAGE_TOKEN).build(),
get_stream_response(_STREAM_NAME).with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD)).build(),
)
http_mocker.get(
self.stream_request().with_limit(250).with_updated_at_min(START_DATE).build(),
get_stream_response(_STREAM_NAME)
.with_pagination()
.with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD).with_cursor(min_cursor_value))
.with_record(get_stream_record(_STREAM_NAME, "id", _CURSOR_FIELD).with_cursor(max_cursor_value))
.build(),
)
output = read_incremental(self._config, _STREAM_NAME)
assert len(output.records) == 3
| TestIncremental |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/operands.py | {
"start": 4642,
"end": 5100
} | class ____(SubsetAutomationCondition):
@property
def name(self) -> str:
return "backfill_in_progress"
async def compute_subset(self, context: AutomationContext) -> EntitySubset: # pyright: ignore[reportIncompatibleMethodOverride]
return await context.asset_graph_view.compute_backfill_in_progress_subset(key=context.key)
@whitelist_for_serdes(storage_name="FailedAutomationCondition")
@record
| BackfillInProgressAutomationCondition |
python | numpy__numpy | benchmarks/benchmarks/bench_trim_zeros.py | {
"start": 166,
"end": 607
} | class ____(Benchmark):
param_names = ["dtype", "size"]
params = [
[_INT, _FLOAT, _COMPLEX, _BOOL],
[3000, 30_000, 300_000]
]
def setup(self, dtype, size):
n = size // 3
self.array = np.hstack([
np.zeros(n),
np.random.uniform(size=n),
np.zeros(n),
]).astype(dtype)
def time_trim_zeros(self, dtype, size):
np.trim_zeros(self.array)
| TrimZeros |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_code_execution_result_block.py | {
"start": 304,
"end": 499
} | class ____(BaseModel):
content: List[BetaCodeExecutionOutputBlock]
return_code: int
stderr: str
stdout: str
type: Literal["code_execution_result"]
| BetaCodeExecutionResultBlock |
python | pandas-dev__pandas | pandas/core/indexing.py | {
"start": 21940,
"end": 40738
} | class ____(NDFrameIndexerBase):
_valid_types: str
axis: AxisInt | None = None
# sub-classes need to set _takeable
_takeable: bool
@final
def __call__(self, axis: Axis | None = None) -> Self:
# we need to return a copy of ourselves
new_self = type(self)(self.name, self.obj)
if axis is not None:
axis_int_none = self.obj._get_axis_number(axis)
else:
axis_int_none = axis
new_self.axis = axis_int_none
return new_self
def _get_setitem_indexer(self, key):
"""
Convert a potentially-label-based key into a positional indexer.
"""
if self.name == "loc":
# always holds here bc iloc overrides _get_setitem_indexer
self._ensure_listlike_indexer(key, axis=self.axis)
if isinstance(key, tuple):
for x in key:
check_dict_or_set_indexers(x)
if self.axis is not None:
key = _tupleize_axis_indexer(self.ndim, self.axis, key)
ax = self.obj._get_axis(0)
if (
isinstance(ax, MultiIndex)
and self.name != "iloc"
and is_hashable(key)
and not isinstance(key, slice)
):
with suppress(KeyError, InvalidIndexError):
# TypeError e.g. passed a bool
return ax.get_loc(key)
if isinstance(key, tuple):
with suppress(IndexingError):
# suppress "Too many indexers"
return self._convert_tuple(key)
if isinstance(key, range):
# GH#45479 test_loc_setitem_range_key
key = list(key)
return self._convert_to_indexer(key, axis=0)
@final
def _maybe_mask_setitem_value(self, indexer, value):
"""
If we have obj.iloc[mask] = series_or_frame and series_or_frame has the
same length as obj, we treat this as obj.iloc[mask] = series_or_frame[mask],
similar to Series.__setitem__.
Note this is only for loc, not iloc.
"""
if (
isinstance(indexer, tuple)
and len(indexer) == 2
and isinstance(value, (ABCSeries, ABCDataFrame))
):
pi, icols = indexer
ndim = value.ndim
if com.is_bool_indexer(pi) and len(value) == len(pi):
newkey = pi.nonzero()[0]
if is_scalar_indexer(icols, self.ndim - 1) and ndim == 1:
# e.g. test_loc_setitem_boolean_mask_allfalse
if len(newkey) == 0:
value = value.iloc[:0]
else:
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_series(indexer, value)
indexer = (newkey, icols)
elif (
isinstance(icols, np.ndarray)
and icols.dtype.kind == "i"
and len(icols) == 1
):
if ndim == 1:
# We implicitly broadcast, though numpy does not, see
# github.com/pandas-dev/pandas/pull/45501#discussion_r789071825
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_series(indexer, value)
indexer = (newkey, icols)
elif ndim == 2 and value.shape[1] == 1:
if len(newkey) == 0:
value = value.iloc[:0]
else:
# test_loc_setitem_ndframe_values_alignment
value = self.obj.iloc._align_frame(indexer, value)
indexer = (newkey, icols)
elif com.is_bool_indexer(indexer):
indexer = indexer.nonzero()[0]
return indexer, value
@final
def _ensure_listlike_indexer(self, key, axis=None, value=None) -> None:
"""
Ensure that a list-like of column labels are all present by adding them if
they do not already exist.
Parameters
----------
key : list-like of column labels
Target labels.
axis : key axis if known
"""
column_axis = 1
# column only exists in 2-dimensional DataFrame
if self.ndim != 2:
return
if isinstance(key, tuple) and len(key) > 1:
# key may be a tuple if we are .loc
# if length of key is > 1 set key to column part
# unless axis is already specified, then go with that
if axis is None:
axis = column_axis
key = key[axis]
if (
axis == column_axis
and not isinstance(self.obj.columns, MultiIndex)
and is_list_like_indexer(key)
and not com.is_bool_indexer(key)
and all(is_hashable(k) for k in key)
):
# GH#38148
keys = self.obj.columns.union(key, sort=False)
diff = Index(key).difference(self.obj.columns, sort=False)
if len(diff):
# e.g. if we are doing df.loc[:, ["A", "B"]] = 7 and "B"
# is a new column, add the new columns with dtype=np.void
# so that later when we go through setitem_single_column
# we will use isetitem. Without this, the reindex_axis
# below would create float64 columns in this example, which
# would successfully hold 7, so we would end up with the wrong
# dtype.
indexer = np.arange(len(keys), dtype=np.intp)
indexer[len(self.obj.columns) :] = -1
new_mgr = self.obj._mgr.reindex_indexer(
keys, indexer=indexer, axis=0, only_slice=True, use_na_proxy=True
)
self.obj._mgr = new_mgr
return
self.obj._mgr = self.obj._mgr.reindex_axis(keys, axis=0, only_slice=True)
@final
def __setitem__(self, key, value) -> None:
if not CHAINED_WARNING_DISABLED:
if sys.getrefcount(self.obj) <= REF_COUNT_IDX:
warnings.warn(
_chained_assignment_msg, ChainedAssignmentError, stacklevel=2
)
check_dict_or_set_indexers(key)
if isinstance(key, tuple):
key = (list(x) if is_iterator(x) else x for x in key)
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
else:
maybe_callable = com.apply_if_callable(key, self.obj)
key = self._raise_callable_usage(key, maybe_callable)
indexer = self._get_setitem_indexer(key)
self._has_valid_setitem_indexer(key)
iloc: _iLocIndexer = (
cast("_iLocIndexer", self) if self.name == "iloc" else self.obj.iloc
)
iloc._setitem_with_indexer(indexer, value, self.name)
def _validate_key(self, key, axis: AxisInt) -> None:
"""
Ensure that key is valid for current indexer.
Parameters
----------
key : scalar, slice or list-like
Key requested.
axis : int
Dimension on which the indexing is being made.
Raises
------
TypeError
If the key (or some element of it) has wrong type.
IndexError
If the key (or some element of it) is out of bounds.
KeyError
If the key was not found.
"""
raise AbstractMethodError(self)
@final
def _expand_ellipsis(self, tup: tuple) -> tuple:
"""
If a tuple key includes an Ellipsis, replace it with an appropriate
number of null slices.
"""
if any(x is Ellipsis for x in tup):
if tup.count(Ellipsis) > 1:
raise IndexingError(_one_ellipsis_message)
if len(tup) == self.ndim:
# It is unambiguous what axis this Ellipsis is indexing,
# treat as a single null slice.
i = tup.index(Ellipsis)
# FIXME: this assumes only one Ellipsis
new_key = tup[:i] + (_NS,) + tup[i + 1 :]
return new_key
# TODO: other cases? only one test gets here, and that is covered
# by _validate_key_length
return tup
@final
def _validate_tuple_indexer(self, key: tuple) -> tuple:
"""
Check the key for valid keys across my indexer.
"""
key = self._validate_key_length(key)
key = self._expand_ellipsis(key)
for i, k in enumerate(key):
try:
self._validate_key(k, i)
except ValueError as err:
raise ValueError(
f"Location based indexing can only have [{self._valid_types}] types"
) from err
return key
@final
def _is_nested_tuple_indexer(self, tup: tuple) -> bool:
"""
Returns
-------
bool
"""
if any(isinstance(ax, MultiIndex) for ax in self.obj.axes):
return any(is_nested_tuple(tup, ax) for ax in self.obj.axes)
return False
@final
def _convert_tuple(self, key: tuple) -> tuple:
# Note: we assume _tupleize_axis_indexer has been called, if necessary.
self._validate_key_length(key)
keyidx = [self._convert_to_indexer(k, axis=i) for i, k in enumerate(key)]
return tuple(keyidx)
@final
def _validate_key_length(self, key: tuple) -> tuple:
if len(key) > self.ndim:
if key[0] is Ellipsis:
# e.g. Series.iloc[..., 3] reduces to just Series.iloc[3]
key = key[1:]
if Ellipsis in key:
raise IndexingError(_one_ellipsis_message)
return self._validate_key_length(key)
raise IndexingError("Too many indexers")
return key
@final
def _getitem_tuple_same_dim(self, tup: tuple):
"""
Index with indexers that should return an object of the same dimension
as self.obj.
This is only called after a failed call to _getitem_lowerdim.
"""
retval = self.obj
# Selecting columns before rows is significantly faster
start_val = (self.ndim - len(tup)) + 1
for i, key in enumerate(reversed(tup)):
i = self.ndim - i - start_val
if com.is_null_slice(key):
continue
retval = getattr(retval, self.name)._getitem_axis(key, axis=i)
# We should never have retval.ndim < self.ndim, as that should
# be handled by the _getitem_lowerdim call above.
assert retval.ndim == self.ndim
if retval is self.obj:
# if all axes were a null slice (`df.loc[:, :]`), ensure we still
# return a new object (https://github.com/pandas-dev/pandas/pull/49469)
retval = retval.copy(deep=False)
return retval
@final
def _getitem_lowerdim(self, tup: tuple):
# we can directly get the axis result since the axis is specified
if self.axis is not None:
axis = self.obj._get_axis_number(self.axis)
return self._getitem_axis(tup, axis=axis)
# we may have a nested tuples indexer here
if self._is_nested_tuple_indexer(tup):
return self._getitem_nested_tuple(tup)
# we maybe be using a tuple to represent multiple dimensions here
ax0 = self.obj._get_axis(0)
# ...but iloc should handle the tuple as simple integer-location
# instead of checking it as multiindex representation (GH 13797)
if (
isinstance(ax0, MultiIndex)
and self.name != "iloc"
and not any(isinstance(x, slice) for x in tup)
):
# Note: in all extant test cases, replacing the slice condition with
# `all(is_hashable(x) or com.is_null_slice(x) for x in tup)`
# is equivalent.
# (see the other place where we call _handle_lowerdim_multi_index_axis0)
with suppress(IndexingError):
return cast(_LocIndexer, self)._handle_lowerdim_multi_index_axis0(tup)
tup = self._validate_key_length(tup)
# Reverse tuple so that we are indexing along columns before rows
# and avoid unintended dtype inference. # GH60600
for i, key in zip(range(len(tup) - 1, -1, -1), reversed(tup), strict=True):
if is_label_like(key) or is_list_like(key):
# We don't need to check for tuples here because those are
# caught by the _is_nested_tuple_indexer check above.
section = self._getitem_axis(key, axis=i)
# We should never have a scalar section here, because
# _getitem_lowerdim is only called after a check for
# is_scalar_access, which that would be.
if section.ndim == self.ndim:
# we're in the middle of slicing through a MultiIndex
# revise the key wrt to `section` by inserting an _NS
new_key = tup[:i] + (_NS,) + tup[i + 1 :]
else:
# Note: the section.ndim == self.ndim check above
# rules out having DataFrame here, so we dont need to worry
# about transposing.
new_key = tup[:i] + tup[i + 1 :]
if len(new_key) == 1:
new_key = new_key[0]
# Slices should return views, but calling iloc/loc with a null
# slice returns a new object.
if com.is_null_slice(new_key):
return section
# This is an elided recursive call to iloc/loc
return getattr(section, self.name)[new_key]
raise IndexingError("not applicable")
@final
def _getitem_nested_tuple(self, tup: tuple):
# we have a nested tuple so have at least 1 multi-index level
# we should be able to match up the dimensionality here
def _contains_slice(x: object) -> bool:
# Check if object is a slice or a tuple containing a slice
if isinstance(x, tuple):
return any(isinstance(v, slice) for v in x)
elif isinstance(x, slice):
return True
return False
for key in tup:
check_dict_or_set_indexers(key)
# we have too many indexers for our dim, but have at least 1
# multi-index dimension, try to see if we have something like
# a tuple passed to a series with a multi-index
if len(tup) > self.ndim:
if self.name != "loc":
# This should never be reached, but let's be explicit about it
raise ValueError("Too many indices") # pragma: no cover
if all(
(is_hashable(x) and not _contains_slice(x)) or com.is_null_slice(x)
for x in tup
):
# GH#10521 Series should reduce MultiIndex dimensions instead of
# DataFrame, IndexingError is not raised when slice(None,None,None)
# with one row.
with suppress(IndexingError):
return cast(_LocIndexer, self)._handle_lowerdim_multi_index_axis0(
tup
)
elif isinstance(self.obj, ABCSeries) and any(
isinstance(k, tuple) for k in tup
):
# GH#35349 Raise if tuple in tuple for series
# Do this after the all-hashable-or-null-slice check so that
# we are only getting non-hashable tuples, in particular ones
# that themselves contain a slice entry
# See test_loc_series_getitem_too_many_dimensions
raise IndexingError("Too many indexers")
# this is a series with a multi-index specified a tuple of
# selectors
axis = self.axis or 0
return self._getitem_axis(tup, axis=axis)
# handle the multi-axis by taking sections and reducing
# this is iterative
obj = self.obj
# GH#41369 Loop in reverse order ensures indexing along columns before rows
# which selects only necessary blocks which avoids dtype conversion if possible
axis = len(tup) - 1
for key in reversed(tup):
if com.is_null_slice(key):
axis -= 1
continue
obj = getattr(obj, self.name)._getitem_axis(key, axis=axis)
axis -= 1
# if we have a scalar, we are done
if is_scalar(obj) or not hasattr(obj, "ndim"):
break
return obj
def _convert_to_indexer(self, key, axis: AxisInt):
raise AbstractMethodError(self)
def _raise_callable_usage(self, key: Any, maybe_callable: T) -> T:
# GH53533
if self.name == "iloc" and callable(key) and isinstance(maybe_callable, tuple):
raise ValueError(
"Returning a tuple from a callable with iloc is not allowed.",
)
return maybe_callable
@final
def __getitem__(self, key):
check_dict_or_set_indexers(key)
if type(key) is tuple:
key = (list(x) if is_iterator(x) else x for x in key)
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
if self._is_scalar_access(key):
return self.obj._get_value(*key, takeable=self._takeable)
return self._getitem_tuple(key)
else:
# we by definition only have the 0th axis
axis = self.axis or 0
maybe_callable = com.apply_if_callable(key, self.obj)
maybe_callable = self._raise_callable_usage(key, maybe_callable)
return self._getitem_axis(maybe_callable, axis=axis)
def _is_scalar_access(self, key: tuple):
raise NotImplementedError
def _getitem_tuple(self, tup: tuple):
raise AbstractMethodError(self)
def _getitem_axis(self, key, axis: AxisInt):
raise NotImplementedError
def _has_valid_setitem_indexer(self, indexer) -> bool:
raise AbstractMethodError(self)
@final
def _getbool_axis(self, key, axis: AxisInt):
# caller is responsible for ensuring non-None axis
labels = self.obj._get_axis(axis)
key = check_bool_indexer(labels, key)
inds = key.nonzero()[0]
return self.obj.take(inds, axis=axis)
@doc(IndexingMixin.loc)
| _LocationIndexer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.