id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
178,430 | from __future__ import annotations
import hashlib
import json
from typing import TYPE_CHECKING, Final, cast
from streamlit.errors import StreamlitAPIException
from streamlit.proto.BokehChart_pb2 import BokehChart as BokehChartProto
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.util import HASHLIB_KWARGS
import json
The provided code snippet includes necessary dependencies for implementing the `marshall` function. Write a Python function `def marshall( proto: BokehChartProto, figure: Figure, use_container_width: bool, element_id: str, ) -> None` to solve the following problem:
Construct a Bokeh chart object. See DeltaGenerator.bokeh_chart for docs.
Here is the function:
def marshall(
proto: BokehChartProto,
figure: Figure,
use_container_width: bool,
element_id: str,
) -> None:
"""Construct a Bokeh chart object.
See DeltaGenerator.bokeh_chart for docs.
"""
from bokeh.embed import json_item
data = json_item(figure)
proto.figure = json.dumps(data)
proto.use_container_width = use_container_width
proto.element_id = element_id | Construct a Bokeh chart object. See DeltaGenerator.bokeh_chart for docs. |
178,431 | from __future__ import annotations
import math
from typing import TYPE_CHECKING, Union, cast
from typing_extensions import TypeAlias
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Progress_pb2 import Progress as ProgressProto
from streamlit.string_util import clean_text
def _check_float_between(value: float, low: float = 0.0, high: float = 1.0) -> bool:
"""
Checks given value is 'between' the bounds of [low, high],
considering close values around bounds are acceptable input
Notes
-----
This check is required for handling values that are slightly above or below the
acceptable range, for example -0.0000000000021, 1.0000000000000013.
These values are little off the conventional 0.0 <= x <= 1.0 condition
due to floating point operations, but should still be considered acceptable input.
Parameters
----------
value : float
low : float
high : float
"""
return (
(low <= value <= high)
or math.isclose(value, low, rel_tol=1e-9, abs_tol=1e-9)
or math.isclose(value, high, rel_tol=1e-9, abs_tol=1e-9)
)
class StreamlitAPIException(MarkdownFormattedException):
"""Base class for Streamlit API exceptions.
An API exception should be thrown when user code interacts with the
Streamlit API incorrectly. (That is, when we throw an exception as a
result of a user's malformed `st.foo` call, it should be a
StreamlitAPIException or subclass.)
When displaying these exceptions on the frontend, we strip Streamlit
entries from the stack trace so that the user doesn't see a bunch of
noise related to Streamlit internals.
"""
def __repr__(self) -> str:
return util.repr_(self)
def _get_value(value):
if isinstance(value, int):
if 0 <= value <= 100:
return value
else:
raise StreamlitAPIException(
"Progress Value has invalid value [0, 100]: %d" % value
)
elif isinstance(value, float):
if _check_float_between(value, low=0.0, high=1.0):
return int(value * 100)
else:
raise StreamlitAPIException(
"Progress Value has invalid value [0.0, 1.0]: %f" % value
)
else:
raise StreamlitAPIException(
"Progress Value has invalid type: %s" % type(value).__name__
) | null |
178,432 | from __future__ import annotations
import math
from typing import TYPE_CHECKING, Union, cast
from typing_extensions import TypeAlias
from streamlit.errors import StreamlitAPIException
from streamlit.proto.Progress_pb2 import Progress as ProgressProto
from streamlit.string_util import clean_text
class StreamlitAPIException(MarkdownFormattedException):
"""Base class for Streamlit API exceptions.
An API exception should be thrown when user code interacts with the
Streamlit API incorrectly. (That is, when we throw an exception as a
result of a user's malformed `st.foo` call, it should be a
StreamlitAPIException or subclass.)
When displaying these exceptions on the frontend, we strip Streamlit
entries from the stack trace so that the user doesn't see a bunch of
noise related to Streamlit internals.
"""
def __repr__(self) -> str:
return util.repr_(self)
def clean_text(text: SupportsStr) -> str:
"""Convert an object to text, dedent it, and strip whitespace."""
return textwrap.dedent(str(text)).strip()
def _get_text(text: str | None) -> str | None:
if text is None:
return None
if isinstance(text, str):
return clean_text(text)
raise StreamlitAPIException(
f"Progress Text is of type {str(type(text))}, which is not an accepted type."
"Text only accepts: str. Please convert the text to an accepted type."
) | null |
178,433 | from __future__ import annotations
import sys
from contextvars import ContextVar
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Any,
Callable,
Final,
Hashable,
Iterable,
Literal,
NoReturn,
TypeVar,
cast,
overload,
)
from streamlit import (
cli_util,
config,
cursor,
env_util,
logger,
runtime,
type_util,
util,
)
from streamlit.cursor import Cursor
from streamlit.elements.alert import AlertMixin
from streamlit.elements.altair_utils import AddRowsMetadata
from streamlit.elements.arrow import ArrowMixin
from streamlit.elements.arrow_altair import ArrowAltairMixin, prep_data
from streamlit.elements.arrow_vega_lite import ArrowVegaLiteMixin
from streamlit.elements.balloons import BalloonsMixin
from streamlit.elements.bokeh_chart import BokehMixin
from streamlit.elements.code import CodeMixin
from streamlit.elements.deck_gl_json_chart import PydeckMixin
from streamlit.elements.doc_string import HelpMixin
from streamlit.elements.empty import EmptyMixin
from streamlit.elements.exception import ExceptionMixin
from streamlit.elements.form import FormData, FormMixin, current_form_id
from streamlit.elements.graphviz_chart import GraphvizMixin
from streamlit.elements.heading import HeadingMixin
from streamlit.elements.iframe import IframeMixin
from streamlit.elements.image import ImageMixin
from streamlit.elements.json import JsonMixin
from streamlit.elements.layouts import LayoutsMixin
from streamlit.elements.map import MapMixin
from streamlit.elements.markdown import MarkdownMixin
from streamlit.elements.media import MediaMixin
from streamlit.elements.metric import MetricMixin
from streamlit.elements.plotly_chart import PlotlyMixin
from streamlit.elements.progress import ProgressMixin
from streamlit.elements.pyplot import PyplotMixin
from streamlit.elements.snow import SnowMixin
from streamlit.elements.text import TextMixin
from streamlit.elements.toast import ToastMixin
from streamlit.elements.widgets.button import ButtonMixin
from streamlit.elements.widgets.camera_input import CameraInputMixin
from streamlit.elements.widgets.chat import ChatMixin
from streamlit.elements.widgets.checkbox import CheckboxMixin
from streamlit.elements.widgets.color_picker import ColorPickerMixin
from streamlit.elements.widgets.data_editor import DataEditorMixin
from streamlit.elements.widgets.file_uploader import FileUploaderMixin
from streamlit.elements.widgets.multiselect import MultiSelectMixin
from streamlit.elements.widgets.number_input import NumberInputMixin
from streamlit.elements.widgets.radio import RadioMixin
from streamlit.elements.widgets.select_slider import SelectSliderMixin
from streamlit.elements.widgets.selectbox import SelectboxMixin
from streamlit.elements.widgets.slider import SliderMixin
from streamlit.elements.widgets.text_widgets import TextWidgetsMixin
from streamlit.elements.widgets.time_widgets import TimeWidgetsMixin
from streamlit.elements.write import WriteMixin
from streamlit.errors import NoSessionContext, StreamlitAPIException
from streamlit.proto import Block_pb2, ForwardMsg_pb2
from streamlit.proto.RootContainer_pb2 import RootContainer
from streamlit.runtime import caching, legacy_caching
from streamlit.runtime.scriptrunner import get_script_run_ctx
from streamlit.runtime.state import NoValue
_use_warning_has_been_displayed: bool = False
The provided code snippet includes necessary dependencies for implementing the `_maybe_print_use_warning` function. Write a Python function `def _maybe_print_use_warning() -> None` to solve the following problem:
Print a warning if Streamlit is imported but not being run with `streamlit run`. The warning is printed only once, and is printed using the root logger.
Here is the function:
def _maybe_print_use_warning() -> None:
"""Print a warning if Streamlit is imported but not being run with `streamlit run`.
The warning is printed only once, and is printed using the root logger.
"""
global _use_warning_has_been_displayed
if not _use_warning_has_been_displayed:
_use_warning_has_been_displayed = True
warning = cli_util.style_for_cli("Warning:", bold=True, fg="yellow")
if env_util.is_repl():
logger.get_logger("root").warning(
f"\n {warning} to view a Streamlit app on a browser, use Streamlit in a file and\n run it with the following command:\n\n streamlit run [FILE_NAME] [ARGUMENTS]"
)
elif not runtime.exists() and config.get_option(
"global.showWarningOnDirectExecution"
):
script_name = sys.argv[0]
logger.get_logger("root").warning(
f"\n {warning} to view this Streamlit app on a browser, run it with the following\n command:\n\n streamlit run {script_name} [ARGUMENTS]"
) | Print a warning if Streamlit is imported but not being run with `streamlit run`. The warning is printed only once, and is printed using the root logger. |
178,434 | from __future__ import annotations
import sys
from contextvars import ContextVar
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Any,
Callable,
Final,
Hashable,
Iterable,
Literal,
NoReturn,
TypeVar,
cast,
overload,
)
from streamlit import (
cli_util,
config,
cursor,
env_util,
logger,
runtime,
type_util,
util,
)
from streamlit.cursor import Cursor
from streamlit.elements.alert import AlertMixin
from streamlit.elements.altair_utils import AddRowsMetadata
from streamlit.elements.arrow import ArrowMixin
from streamlit.elements.arrow_altair import ArrowAltairMixin, prep_data
from streamlit.elements.arrow_vega_lite import ArrowVegaLiteMixin
from streamlit.elements.balloons import BalloonsMixin
from streamlit.elements.bokeh_chart import BokehMixin
from streamlit.elements.code import CodeMixin
from streamlit.elements.deck_gl_json_chart import PydeckMixin
from streamlit.elements.doc_string import HelpMixin
from streamlit.elements.empty import EmptyMixin
from streamlit.elements.exception import ExceptionMixin
from streamlit.elements.form import FormData, FormMixin, current_form_id
from streamlit.elements.graphviz_chart import GraphvizMixin
from streamlit.elements.heading import HeadingMixin
from streamlit.elements.iframe import IframeMixin
from streamlit.elements.image import ImageMixin
from streamlit.elements.json import JsonMixin
from streamlit.elements.layouts import LayoutsMixin
from streamlit.elements.map import MapMixin
from streamlit.elements.markdown import MarkdownMixin
from streamlit.elements.media import MediaMixin
from streamlit.elements.metric import MetricMixin
from streamlit.elements.plotly_chart import PlotlyMixin
from streamlit.elements.progress import ProgressMixin
from streamlit.elements.pyplot import PyplotMixin
from streamlit.elements.snow import SnowMixin
from streamlit.elements.text import TextMixin
from streamlit.elements.toast import ToastMixin
from streamlit.elements.widgets.button import ButtonMixin
from streamlit.elements.widgets.camera_input import CameraInputMixin
from streamlit.elements.widgets.chat import ChatMixin
from streamlit.elements.widgets.checkbox import CheckboxMixin
from streamlit.elements.widgets.color_picker import ColorPickerMixin
from streamlit.elements.widgets.data_editor import DataEditorMixin
from streamlit.elements.widgets.file_uploader import FileUploaderMixin
from streamlit.elements.widgets.multiselect import MultiSelectMixin
from streamlit.elements.widgets.number_input import NumberInputMixin
from streamlit.elements.widgets.radio import RadioMixin
from streamlit.elements.widgets.select_slider import SelectSliderMixin
from streamlit.elements.widgets.selectbox import SelectboxMixin
from streamlit.elements.widgets.slider import SliderMixin
from streamlit.elements.widgets.text_widgets import TextWidgetsMixin
from streamlit.elements.widgets.time_widgets import TimeWidgetsMixin
from streamlit.elements.write import WriteMixin
from streamlit.errors import NoSessionContext, StreamlitAPIException
from streamlit.proto import Block_pb2, ForwardMsg_pb2
from streamlit.proto.RootContainer_pb2 import RootContainer
from streamlit.runtime import caching, legacy_caching
from streamlit.runtime.scriptrunner import get_script_run_ctx
from streamlit.runtime.state import NoValue
ARROW_DELTA_TYPES_THAT_MELT_DATAFRAMES: Final = (
"arrow_line_chart",
"arrow_area_chart",
"arrow_bar_chart",
"arrow_scatter_chart",
)
def _get_pandas_index_attr(
data: DataFrame | Series,
attr: str,
) -> Any | None:
return getattr(data.index, attr, None)
class AddRowsMetadata:
"""Metadata needed by add_rows on native charts."""
last_index: Hashable | None
columns: PrepDataColumns
def prep_data(
df: pd.DataFrame,
x_column: str | None,
y_column_list: list[str],
color_column: str | None,
size_column: str | None,
) -> tuple[pd.DataFrame, str | None, str | None, str | None, str | None]:
"""Prepares the data for charting. This is also used in add_rows.
Returns the prepared dataframe and the new names of the x column (taking the index reset into
consideration) and y, color, and size columns.
"""
# If y is provided, but x is not, we'll use the index as x.
# So we need to pull the index into its own column.
x_column = _maybe_reset_index_in_place(df, x_column, y_column_list)
# Drop columns we're not using.
selected_data = _drop_unused_columns(
df, x_column, color_column, size_column, *y_column_list
)
# Maybe convert color to Vega colors.
_maybe_convert_color_column_in_place(selected_data, color_column)
# Make sure all columns have string names.
(
x_column,
y_column_list,
color_column,
size_column,
) = _convert_col_names_to_str_in_place(
selected_data, x_column, y_column_list, color_column, size_column
)
# Maybe melt data from wide format into long format.
melted_data, y_column, color_column = _maybe_melt(
selected_data, x_column, y_column_list, color_column, size_column
)
# Return the data, but also the new names to use for x, y, and color.
return melted_data, x_column, y_column, color_column, size_column
class StreamlitAPIException(MarkdownFormattedException):
"""Base class for Streamlit API exceptions.
An API exception should be thrown when user code interacts with the
Streamlit API incorrectly. (That is, when we throw an exception as a
result of a user's malformed `st.foo` call, it should be a
StreamlitAPIException or subclass.)
When displaying these exceptions on the frontend, we strip Streamlit
entries from the stack trace so that the user doesn't see a bunch of
noise related to Streamlit internals.
"""
def __repr__(self) -> str:
return util.repr_(self)
Data: TypeAlias = Union[
"DataFrame",
"Series",
"Styler",
"Index",
"pa.Table",
"ndarray",
Iterable,
Dict[str, List[Any]],
None,
]
def _prep_data_for_add_rows(
data: Data,
delta_type: str,
add_rows_metadata: AddRowsMetadata,
) -> tuple[Data, AddRowsMetadata]:
out_data: Data
# For some delta types we have to reshape the data structure
# otherwise the input data and the actual data used
# by vega_lite will be different, and it will throw an error.
if delta_type in ARROW_DELTA_TYPES_THAT_MELT_DATAFRAMES:
import pandas as pd
df = cast(pd.DataFrame, type_util.convert_anything_to_df(data))
# Make range indices start at last_index.
if isinstance(df.index, pd.RangeIndex):
old_step = _get_pandas_index_attr(df, "step")
# We have to drop the predefined index
df = df.reset_index(drop=True)
old_stop = _get_pandas_index_attr(df, "stop")
if old_step is None or old_stop is None:
raise StreamlitAPIException(
"'RangeIndex' object has no attribute 'step'"
)
start = add_rows_metadata.last_index + old_step
stop = add_rows_metadata.last_index + old_step + old_stop
df.index = pd.RangeIndex(start=start, stop=stop, step=old_step)
add_rows_metadata.last_index = stop - 1
out_data, *_ = prep_data(df, **add_rows_metadata.columns)
else:
# When calling add_rows on st.table or st.dataframe we want styles to pass through.
out_data = type_util.convert_anything_to_df(data, allow_styler=True)
return out_data, add_rows_metadata | null |
178,435 | from __future__ import annotations
import sys
from contextvars import ContextVar
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Any,
Callable,
Final,
Hashable,
Iterable,
Literal,
NoReturn,
TypeVar,
cast,
overload,
)
from streamlit import (
cli_util,
config,
cursor,
env_util,
logger,
runtime,
type_util,
util,
)
from streamlit.cursor import Cursor
from streamlit.elements.alert import AlertMixin
from streamlit.elements.altair_utils import AddRowsMetadata
from streamlit.elements.arrow import ArrowMixin
from streamlit.elements.arrow_altair import ArrowAltairMixin, prep_data
from streamlit.elements.arrow_vega_lite import ArrowVegaLiteMixin
from streamlit.elements.balloons import BalloonsMixin
from streamlit.elements.bokeh_chart import BokehMixin
from streamlit.elements.code import CodeMixin
from streamlit.elements.deck_gl_json_chart import PydeckMixin
from streamlit.elements.doc_string import HelpMixin
from streamlit.elements.empty import EmptyMixin
from streamlit.elements.exception import ExceptionMixin
from streamlit.elements.form import FormData, FormMixin, current_form_id
from streamlit.elements.graphviz_chart import GraphvizMixin
from streamlit.elements.heading import HeadingMixin
from streamlit.elements.iframe import IframeMixin
from streamlit.elements.image import ImageMixin
from streamlit.elements.json import JsonMixin
from streamlit.elements.layouts import LayoutsMixin
from streamlit.elements.map import MapMixin
from streamlit.elements.markdown import MarkdownMixin
from streamlit.elements.media import MediaMixin
from streamlit.elements.metric import MetricMixin
from streamlit.elements.plotly_chart import PlotlyMixin
from streamlit.elements.progress import ProgressMixin
from streamlit.elements.pyplot import PyplotMixin
from streamlit.elements.snow import SnowMixin
from streamlit.elements.text import TextMixin
from streamlit.elements.toast import ToastMixin
from streamlit.elements.widgets.button import ButtonMixin
from streamlit.elements.widgets.camera_input import CameraInputMixin
from streamlit.elements.widgets.chat import ChatMixin
from streamlit.elements.widgets.checkbox import CheckboxMixin
from streamlit.elements.widgets.color_picker import ColorPickerMixin
from streamlit.elements.widgets.data_editor import DataEditorMixin
from streamlit.elements.widgets.file_uploader import FileUploaderMixin
from streamlit.elements.widgets.multiselect import MultiSelectMixin
from streamlit.elements.widgets.number_input import NumberInputMixin
from streamlit.elements.widgets.radio import RadioMixin
from streamlit.elements.widgets.select_slider import SelectSliderMixin
from streamlit.elements.widgets.selectbox import SelectboxMixin
from streamlit.elements.widgets.slider import SliderMixin
from streamlit.elements.widgets.text_widgets import TextWidgetsMixin
from streamlit.elements.widgets.time_widgets import TimeWidgetsMixin
from streamlit.elements.write import WriteMixin
from streamlit.errors import NoSessionContext, StreamlitAPIException
from streamlit.proto import Block_pb2, ForwardMsg_pb2
from streamlit.proto.RootContainer_pb2 import RootContainer
from streamlit.runtime import caching, legacy_caching
from streamlit.runtime.scriptrunner import get_script_run_ctx
from streamlit.runtime.state import NoValue
DG = TypeVar("DG", bound="DeltaGenerator")
def _value_or_dg(value: None, dg: DG) -> DG:
... | null |
178,436 | from __future__ import annotations
import sys
from contextvars import ContextVar
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Any,
Callable,
Final,
Hashable,
Iterable,
Literal,
NoReturn,
TypeVar,
cast,
overload,
)
from streamlit import (
cli_util,
config,
cursor,
env_util,
logger,
runtime,
type_util,
util,
)
from streamlit.cursor import Cursor
from streamlit.elements.alert import AlertMixin
from streamlit.elements.altair_utils import AddRowsMetadata
from streamlit.elements.arrow import ArrowMixin
from streamlit.elements.arrow_altair import ArrowAltairMixin, prep_data
from streamlit.elements.arrow_vega_lite import ArrowVegaLiteMixin
from streamlit.elements.balloons import BalloonsMixin
from streamlit.elements.bokeh_chart import BokehMixin
from streamlit.elements.code import CodeMixin
from streamlit.elements.deck_gl_json_chart import PydeckMixin
from streamlit.elements.doc_string import HelpMixin
from streamlit.elements.empty import EmptyMixin
from streamlit.elements.exception import ExceptionMixin
from streamlit.elements.form import FormData, FormMixin, current_form_id
from streamlit.elements.graphviz_chart import GraphvizMixin
from streamlit.elements.heading import HeadingMixin
from streamlit.elements.iframe import IframeMixin
from streamlit.elements.image import ImageMixin
from streamlit.elements.json import JsonMixin
from streamlit.elements.layouts import LayoutsMixin
from streamlit.elements.map import MapMixin
from streamlit.elements.markdown import MarkdownMixin
from streamlit.elements.media import MediaMixin
from streamlit.elements.metric import MetricMixin
from streamlit.elements.plotly_chart import PlotlyMixin
from streamlit.elements.progress import ProgressMixin
from streamlit.elements.pyplot import PyplotMixin
from streamlit.elements.snow import SnowMixin
from streamlit.elements.text import TextMixin
from streamlit.elements.toast import ToastMixin
from streamlit.elements.widgets.button import ButtonMixin
from streamlit.elements.widgets.camera_input import CameraInputMixin
from streamlit.elements.widgets.chat import ChatMixin
from streamlit.elements.widgets.checkbox import CheckboxMixin
from streamlit.elements.widgets.color_picker import ColorPickerMixin
from streamlit.elements.widgets.data_editor import DataEditorMixin
from streamlit.elements.widgets.file_uploader import FileUploaderMixin
from streamlit.elements.widgets.multiselect import MultiSelectMixin
from streamlit.elements.widgets.number_input import NumberInputMixin
from streamlit.elements.widgets.radio import RadioMixin
from streamlit.elements.widgets.select_slider import SelectSliderMixin
from streamlit.elements.widgets.selectbox import SelectboxMixin
from streamlit.elements.widgets.slider import SliderMixin
from streamlit.elements.widgets.text_widgets import TextWidgetsMixin
from streamlit.elements.widgets.time_widgets import TimeWidgetsMixin
from streamlit.elements.write import WriteMixin
from streamlit.errors import NoSessionContext, StreamlitAPIException
from streamlit.proto import Block_pb2, ForwardMsg_pb2
from streamlit.proto.RootContainer_pb2 import RootContainer
from streamlit.runtime import caching, legacy_caching
from streamlit.runtime.scriptrunner import get_script_run_ctx
from streamlit.runtime.state import NoValue
DG = TypeVar("DG", bound="DeltaGenerator")
def _value_or_dg(value: type[NoValue], dg: DG) -> None: # type: ignore[misc]
... | null |
178,437 | from __future__ import annotations
import sys
from contextvars import ContextVar
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Any,
Callable,
Final,
Hashable,
Iterable,
Literal,
NoReturn,
TypeVar,
cast,
overload,
)
from streamlit import (
cli_util,
config,
cursor,
env_util,
logger,
runtime,
type_util,
util,
)
from streamlit.cursor import Cursor
from streamlit.elements.alert import AlertMixin
from streamlit.elements.altair_utils import AddRowsMetadata
from streamlit.elements.arrow import ArrowMixin
from streamlit.elements.arrow_altair import ArrowAltairMixin, prep_data
from streamlit.elements.arrow_vega_lite import ArrowVegaLiteMixin
from streamlit.elements.balloons import BalloonsMixin
from streamlit.elements.bokeh_chart import BokehMixin
from streamlit.elements.code import CodeMixin
from streamlit.elements.deck_gl_json_chart import PydeckMixin
from streamlit.elements.doc_string import HelpMixin
from streamlit.elements.empty import EmptyMixin
from streamlit.elements.exception import ExceptionMixin
from streamlit.elements.form import FormData, FormMixin, current_form_id
from streamlit.elements.graphviz_chart import GraphvizMixin
from streamlit.elements.heading import HeadingMixin
from streamlit.elements.iframe import IframeMixin
from streamlit.elements.image import ImageMixin
from streamlit.elements.json import JsonMixin
from streamlit.elements.layouts import LayoutsMixin
from streamlit.elements.map import MapMixin
from streamlit.elements.markdown import MarkdownMixin
from streamlit.elements.media import MediaMixin
from streamlit.elements.metric import MetricMixin
from streamlit.elements.plotly_chart import PlotlyMixin
from streamlit.elements.progress import ProgressMixin
from streamlit.elements.pyplot import PyplotMixin
from streamlit.elements.snow import SnowMixin
from streamlit.elements.text import TextMixin
from streamlit.elements.toast import ToastMixin
from streamlit.elements.widgets.button import ButtonMixin
from streamlit.elements.widgets.camera_input import CameraInputMixin
from streamlit.elements.widgets.chat import ChatMixin
from streamlit.elements.widgets.checkbox import CheckboxMixin
from streamlit.elements.widgets.color_picker import ColorPickerMixin
from streamlit.elements.widgets.data_editor import DataEditorMixin
from streamlit.elements.widgets.file_uploader import FileUploaderMixin
from streamlit.elements.widgets.multiselect import MultiSelectMixin
from streamlit.elements.widgets.number_input import NumberInputMixin
from streamlit.elements.widgets.radio import RadioMixin
from streamlit.elements.widgets.select_slider import SelectSliderMixin
from streamlit.elements.widgets.selectbox import SelectboxMixin
from streamlit.elements.widgets.slider import SliderMixin
from streamlit.elements.widgets.text_widgets import TextWidgetsMixin
from streamlit.elements.widgets.time_widgets import TimeWidgetsMixin
from streamlit.elements.write import WriteMixin
from streamlit.errors import NoSessionContext, StreamlitAPIException
from streamlit.proto import Block_pb2, ForwardMsg_pb2
from streamlit.proto.RootContainer_pb2 import RootContainer
from streamlit.runtime import caching, legacy_caching
from streamlit.runtime.scriptrunner import get_script_run_ctx
from streamlit.runtime.state import NoValue
Value = TypeVar("Value")
DG = TypeVar("DG", bound="DeltaGenerator")
def _value_or_dg(value: Value, dg: DG) -> Value:
# This overload definition technically overlaps with the one above (Value
# contains Type[NoValue]), and since the return types are conflicting,
# mypy complains. Hence, the ignore-comment above. But, in practice, since
# the overload above is more specific, and is matched first, there is no
# actual overlap. The `Value` type here is thus narrowed to the cases
# where value is neither None nor NoValue.
# The ignore-comment should thus be fine.
... | null |
178,438 | from __future__ import annotations
import sys
from contextvars import ContextVar
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Any,
Callable,
Final,
Hashable,
Iterable,
Literal,
NoReturn,
TypeVar,
cast,
overload,
)
from streamlit import (
cli_util,
config,
cursor,
env_util,
logger,
runtime,
type_util,
util,
)
from streamlit.cursor import Cursor
from streamlit.elements.alert import AlertMixin
from streamlit.elements.altair_utils import AddRowsMetadata
from streamlit.elements.arrow import ArrowMixin
from streamlit.elements.arrow_altair import ArrowAltairMixin, prep_data
from streamlit.elements.arrow_vega_lite import ArrowVegaLiteMixin
from streamlit.elements.balloons import BalloonsMixin
from streamlit.elements.bokeh_chart import BokehMixin
from streamlit.elements.code import CodeMixin
from streamlit.elements.deck_gl_json_chart import PydeckMixin
from streamlit.elements.doc_string import HelpMixin
from streamlit.elements.empty import EmptyMixin
from streamlit.elements.exception import ExceptionMixin
from streamlit.elements.form import FormData, FormMixin, current_form_id
from streamlit.elements.graphviz_chart import GraphvizMixin
from streamlit.elements.heading import HeadingMixin
from streamlit.elements.iframe import IframeMixin
from streamlit.elements.image import ImageMixin
from streamlit.elements.json import JsonMixin
from streamlit.elements.layouts import LayoutsMixin
from streamlit.elements.map import MapMixin
from streamlit.elements.markdown import MarkdownMixin
from streamlit.elements.media import MediaMixin
from streamlit.elements.metric import MetricMixin
from streamlit.elements.plotly_chart import PlotlyMixin
from streamlit.elements.progress import ProgressMixin
from streamlit.elements.pyplot import PyplotMixin
from streamlit.elements.snow import SnowMixin
from streamlit.elements.text import TextMixin
from streamlit.elements.toast import ToastMixin
from streamlit.elements.widgets.button import ButtonMixin
from streamlit.elements.widgets.camera_input import CameraInputMixin
from streamlit.elements.widgets.chat import ChatMixin
from streamlit.elements.widgets.checkbox import CheckboxMixin
from streamlit.elements.widgets.color_picker import ColorPickerMixin
from streamlit.elements.widgets.data_editor import DataEditorMixin
from streamlit.elements.widgets.file_uploader import FileUploaderMixin
from streamlit.elements.widgets.multiselect import MultiSelectMixin
from streamlit.elements.widgets.number_input import NumberInputMixin
from streamlit.elements.widgets.radio import RadioMixin
from streamlit.elements.widgets.select_slider import SelectSliderMixin
from streamlit.elements.widgets.selectbox import SelectboxMixin
from streamlit.elements.widgets.slider import SliderMixin
from streamlit.elements.widgets.text_widgets import TextWidgetsMixin
from streamlit.elements.widgets.time_widgets import TimeWidgetsMixin
from streamlit.elements.write import WriteMixin
from streamlit.errors import NoSessionContext, StreamlitAPIException
from streamlit.proto import Block_pb2, ForwardMsg_pb2
from streamlit.proto.RootContainer_pb2 import RootContainer
from streamlit.runtime import caching, legacy_caching
from streamlit.runtime.scriptrunner import get_script_run_ctx
from streamlit.runtime.state import NoValue
Value = TypeVar("Value")
DG = TypeVar("DG", bound="DeltaGenerator")
The provided code snippet includes necessary dependencies for implementing the `_value_or_dg` function. Write a Python function `def _value_or_dg( value: type[NoValue] | Value | None, dg: DG, ) -> DG | Value | None` to solve the following problem:
Return either value, or None, or dg. This is needed because Widgets have meaningful return values. This is unlike other elements, which always return None. Then we internally replace that None with a DeltaGenerator instance. However, sometimes a widget may want to return None, and in this case it should not be replaced by a DeltaGenerator. So we have a special NoValue object that gets replaced by None.
Here is the function:
def _value_or_dg(
value: type[NoValue] | Value | None,
dg: DG,
) -> DG | Value | None:
"""Return either value, or None, or dg.
This is needed because Widgets have meaningful return values. This is
unlike other elements, which always return None. Then we internally replace
that None with a DeltaGenerator instance.
However, sometimes a widget may want to return None, and in this case it
should not be replaced by a DeltaGenerator. So we have a special NoValue
object that gets replaced by None.
"""
if value is NoValue:
return None
if value is None:
return dg
return cast(Value, value) | Return either value, or None, or dg. This is needed because Widgets have meaningful return values. This is unlike other elements, which always return None. Then we internally replace that None with a DeltaGenerator instance. However, sometimes a widget may want to return None, and in this case it should not be replaced by a DeltaGenerator. So we have a special NoValue object that gets replaced by None. |
178,439 | from __future__ import annotations
import sys
from contextvars import ContextVar
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Any,
Callable,
Final,
Hashable,
Iterable,
Literal,
NoReturn,
TypeVar,
cast,
overload,
)
from streamlit import (
cli_util,
config,
cursor,
env_util,
logger,
runtime,
type_util,
util,
)
from streamlit.cursor import Cursor
from streamlit.elements.alert import AlertMixin
from streamlit.elements.altair_utils import AddRowsMetadata
from streamlit.elements.arrow import ArrowMixin
from streamlit.elements.arrow_altair import ArrowAltairMixin, prep_data
from streamlit.elements.arrow_vega_lite import ArrowVegaLiteMixin
from streamlit.elements.balloons import BalloonsMixin
from streamlit.elements.bokeh_chart import BokehMixin
from streamlit.elements.code import CodeMixin
from streamlit.elements.deck_gl_json_chart import PydeckMixin
from streamlit.elements.doc_string import HelpMixin
from streamlit.elements.empty import EmptyMixin
from streamlit.elements.exception import ExceptionMixin
from streamlit.elements.form import FormData, FormMixin, current_form_id
from streamlit.elements.graphviz_chart import GraphvizMixin
from streamlit.elements.heading import HeadingMixin
from streamlit.elements.iframe import IframeMixin
from streamlit.elements.image import ImageMixin
from streamlit.elements.json import JsonMixin
from streamlit.elements.layouts import LayoutsMixin
from streamlit.elements.map import MapMixin
from streamlit.elements.markdown import MarkdownMixin
from streamlit.elements.media import MediaMixin
from streamlit.elements.metric import MetricMixin
from streamlit.elements.plotly_chart import PlotlyMixin
from streamlit.elements.progress import ProgressMixin
from streamlit.elements.pyplot import PyplotMixin
from streamlit.elements.snow import SnowMixin
from streamlit.elements.text import TextMixin
from streamlit.elements.toast import ToastMixin
from streamlit.elements.widgets.button import ButtonMixin
from streamlit.elements.widgets.camera_input import CameraInputMixin
from streamlit.elements.widgets.chat import ChatMixin
from streamlit.elements.widgets.checkbox import CheckboxMixin
from streamlit.elements.widgets.color_picker import ColorPickerMixin
from streamlit.elements.widgets.data_editor import DataEditorMixin
from streamlit.elements.widgets.file_uploader import FileUploaderMixin
from streamlit.elements.widgets.multiselect import MultiSelectMixin
from streamlit.elements.widgets.number_input import NumberInputMixin
from streamlit.elements.widgets.radio import RadioMixin
from streamlit.elements.widgets.select_slider import SelectSliderMixin
from streamlit.elements.widgets.selectbox import SelectboxMixin
from streamlit.elements.widgets.slider import SliderMixin
from streamlit.elements.widgets.text_widgets import TextWidgetsMixin
from streamlit.elements.widgets.time_widgets import TimeWidgetsMixin
from streamlit.elements.write import WriteMixin
from streamlit.errors import NoSessionContext, StreamlitAPIException
from streamlit.proto import Block_pb2, ForwardMsg_pb2
from streamlit.proto.RootContainer_pb2 import RootContainer
from streamlit.runtime import caching, legacy_caching
from streamlit.runtime.scriptrunner import get_script_run_ctx
from streamlit.runtime.state import NoValue
class NoSessionContext(Error):
pass
The provided code snippet includes necessary dependencies for implementing the `_enqueue_message` function. Write a Python function `def _enqueue_message(msg: ForwardMsg_pb2.ForwardMsg) -> None` to solve the following problem:
Enqueues a ForwardMsg proto to send to the app.
Here is the function:
def _enqueue_message(msg: ForwardMsg_pb2.ForwardMsg) -> None:
"""Enqueues a ForwardMsg proto to send to the app."""
ctx = get_script_run_ctx()
if ctx is None:
raise NoSessionContext()
ctx.enqueue(msg) | Enqueues a ForwardMsg proto to send to the app. |
178,440 | from __future__ import annotations
from typing import Iterator, Mapping, NoReturn, Union
from streamlit.errors import StreamlitAPIException
from streamlit.runtime.scriptrunner import get_script_run_ctx as _get_script_run_ctx
from streamlit.runtime.scriptrunner.script_run_context import UserInfo
UserInfo: TypeAlias = Dict[str, Union[str, None]]
def _get_user_info() -> UserInfo:
ctx = _get_script_run_ctx()
if ctx is None:
# TODO: Add appropriate warnings when ctx is missing
return {}
return ctx.user_info | null |
178,441 | from __future__ import annotations
import re
import threading
from pathlib import Path
from typing import Any, Callable, Final, cast
from blinker import Signal
from streamlit.logger import get_logger
from streamlit.string_util import extract_leading_emoji
from streamlit.util import calc_md5
_on_pages_changed = Signal(doc="Emitted when the pages directory is changed")
def register_pages_changed_callback(
callback: Callable[[str], None],
) -> Callable[[], None]:
def disconnect():
_on_pages_changed.disconnect(callback)
# weak=False so that we have control of when the pages changed
# callback is deregistered.
_on_pages_changed.connect(callback, weak=False)
return disconnect | null |
178,442 | from __future__ import annotations
import ast
import contextlib
import re
import textwrap
import traceback
from typing import Any, Iterable
from streamlit.runtime.metrics_util import gather_metrics
code = _main.code
empty = _main.empty
warning = _main.warning
The provided code snippet includes necessary dependencies for implementing the `echo` function. Write a Python function `def echo(code_location="above")` to solve the following problem:
Use in a `with` block to draw some code on the app, then execute it. Parameters ---------- code_location : "above" or "below" Whether to show the echoed code before or after the results of the executed code block. Example ------- >>> import streamlit as st >>> >>> with st.echo(): >>> st.write('This code will be printed')
Here is the function:
def echo(code_location="above"):
"""Use in a `with` block to draw some code on the app, then execute it.
Parameters
----------
code_location : "above" or "below"
Whether to show the echoed code before or after the results of the
executed code block.
Example
-------
>>> import streamlit as st
>>>
>>> with st.echo():
>>> st.write('This code will be printed')
"""
from streamlit import code, empty, source_util, warning
if code_location == "below":
show_code = code
show_warning = warning
else:
placeholder = empty()
show_code = placeholder.code
show_warning = placeholder.warning
try:
# Get stack frame *before* running the echoed code. The frame's
# line number will point to the `st.echo` statement we're running.
frame = traceback.extract_stack()[-3]
filename, start_line = frame.filename, frame.lineno or 0
# Read the file containing the source code of the echoed statement.
with source_util.open_python_file(filename) as source_file:
source_lines = source_file.readlines()
# Use ast to parse the Python file and find the code block to display
root_node = ast.parse("".join(source_lines))
line_to_node_map: dict[int, Any] = {}
def collect_body_statements(node: ast.AST) -> None:
if not hasattr(node, "body"):
return
for child in ast.iter_child_nodes(node):
# If child doesn't have "lineno", it is not something we could display
if hasattr(child, "lineno"):
line_to_node_map[child.lineno] = child
collect_body_statements(child)
collect_body_statements(root_node)
# In AST module the lineno (line numbers) are 1-indexed,
# so we decrease it by 1 to lookup in source lines list
echo_block_start_line = line_to_node_map[start_line].body[0].lineno - 1
echo_block_end_line = line_to_node_map[start_line].end_lineno
lines_to_display = source_lines[echo_block_start_line:echo_block_end_line]
code_string = textwrap.dedent("".join(lines_to_display))
# Run the echoed code...
yield
# And draw the code string to the app!
show_code(code_string, "python")
except FileNotFoundError as err:
show_warning("Unable to display code. %s" % err) | Use in a `with` block to draw some code on the app, then execute it. Parameters ---------- code_location : "above" or "below" Whether to show the echoed code before or after the results of the executed code block. Example ------- >>> import streamlit as st >>> >>> with st.echo(): >>> st.write('This code will be printed') |
178,443 | from __future__ import annotations
import ast
import contextlib
import re
import textwrap
import traceback
from typing import Any, Iterable
from streamlit.runtime.metrics_util import gather_metrics
def _get_indent(line: str) -> int | None:
"""Get the number of whitespaces at the beginning of the given line.
If the line is empty, or if it contains just whitespace and a newline,
return None.
"""
if _EMPTY_LINE_RE.match(line) is not None:
return None
match = _SPACES_RE.match(line)
return match.end() if match is not None else 0
The provided code snippet includes necessary dependencies for implementing the `_get_initial_indent` function. Write a Python function `def _get_initial_indent(lines: Iterable[str]) -> int` to solve the following problem:
Return the indent of the first non-empty line in the list. If all lines are empty, return 0.
Here is the function:
def _get_initial_indent(lines: Iterable[str]) -> int:
"""Return the indent of the first non-empty line in the list.
If all lines are empty, return 0.
"""
for line in lines:
indent = _get_indent(line)
if indent is not None:
return indent
return 0 | Return the indent of the first non-empty line in the list. If all lines are empty, return 0. |
178,444 | from __future__ import annotations
import re
from typing import Any
def extract_args(line: str) -> list[str]:
"""Parse argument strings from all outer parentheses in a line of code.
Parameters
----------
line : str
A line of code
Returns
-------
list of strings
Contents of the outer parentheses
Example
-------
>>> line = 'foo(bar, baz), "a", my(func)'
>>> extract_args(line)
['bar, baz', 'func']
"""
stack = 0
startIndex = None
results = []
for i, c in enumerate(line):
if c == "(":
if stack == 0:
startIndex = i + 1
stack += 1
elif c == ")":
stack -= 1
if stack == 0:
results.append(line[startIndex:i])
return results
The provided code snippet includes necessary dependencies for implementing the `get_method_args_from_code` function. Write a Python function `def get_method_args_from_code(args: list[Any], line: str) -> list[str]` to solve the following problem:
Parse arguments from a stringified arguments list inside parentheses Parameters ---------- args : list A list where it's size matches the expected number of parsed arguments line : str Stringified line of code with method arguments inside parentheses Returns ------- list of strings Parsed arguments Example ------- >>> line = 'foo(bar, baz, my(func, tion))' >>> >>> get_method_args_from_code(range(0, 3), line) ['bar', 'baz', 'my(func, tion)']
Here is the function:
def get_method_args_from_code(args: list[Any], line: str) -> list[str]:
"""Parse arguments from a stringified arguments list inside parentheses
Parameters
----------
args : list
A list where it's size matches the expected number of parsed arguments
line : str
Stringified line of code with method arguments inside parentheses
Returns
-------
list of strings
Parsed arguments
Example
-------
>>> line = 'foo(bar, baz, my(func, tion))'
>>>
>>> get_method_args_from_code(range(0, 3), line)
['bar', 'baz', 'my(func, tion)']
"""
line_args = extract_args(line)[0]
# Split arguments, https://stackoverflow.com/a/26634150
if len(args) > 1:
inputs = re.split(r",\s*(?![^(){}[\]]*\))", line_args)
assert len(inputs) == len(args), "Could not split arguments"
else:
inputs = [line_args]
return inputs | Parse arguments from a stringified arguments list inside parentheses Parameters ---------- args : list A list where it's size matches the expected number of parsed arguments line : str Stringified line of code with method arguments inside parentheses Returns ------- list of strings Parsed arguments Example ------- >>> line = 'foo(bar, baz, my(func, tion))' >>> >>> get_method_args_from_code(range(0, 3), line) ['bar', 'baz', 'my(func, tion)'] |
178,445 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
_config_options_template: dict[str, ConfigOption] = OrderedDict()
def set_option(key: str, value: Any, where_defined: str = _USER_DEFINED) -> None:
"""Set config option.
Run `streamlit config show` in the terminal to see all available options.
This is an internal API. The public `st.set_option` API is implemented
in `set_user_option`.
Parameters
----------
key : str
The config option key of the form "section.optionName". To see all
available options, run `streamlit config show` on a terminal.
value
The new value to assign to this config option.
where_defined : str
Tells the config system where this was set.
"""
with _config_lock:
# Ensure that our config files have been parsed.
get_config_options()
_set_option(key, value, where_defined)
class StreamlitAPIException(MarkdownFormattedException):
"""Base class for Streamlit API exceptions.
An API exception should be thrown when user code interacts with the
Streamlit API incorrectly. (That is, when we throw an exception as a
result of a user's malformed `st.foo` call, it should be a
StreamlitAPIException or subclass.)
When displaying these exceptions on the frontend, we strip Streamlit
entries from the stack trace so that the user doesn't see a bunch of
noise related to Streamlit internals.
"""
def __repr__(self) -> str:
return util.repr_(self)
The provided code snippet includes necessary dependencies for implementing the `set_user_option` function. Write a Python function `def set_user_option(key: str, value: Any) -> None` to solve the following problem:
Set config option. Currently, only the following config options can be set within the script itself: * client.caching * client.displayEnabled * deprecation.* Calling with any other options will raise StreamlitAPIException. Run `streamlit config show` in the terminal to see all available options. Parameters ---------- key : str The config option key of the form "section.optionName". To see all available options, run `streamlit config show` on a terminal. value The new value to assign to this config option.
Here is the function:
def set_user_option(key: str, value: Any) -> None:
"""Set config option.
Currently, only the following config options can be set within the script itself:
* client.caching
* client.displayEnabled
* deprecation.*
Calling with any other options will raise StreamlitAPIException.
Run `streamlit config show` in the terminal to see all available options.
Parameters
----------
key : str
The config option key of the form "section.optionName". To see all
available options, run `streamlit config show` on a terminal.
value
The new value to assign to this config option.
"""
try:
opt = _config_options_template[key]
except KeyError as ke:
raise StreamlitAPIException(f"Unrecognized config option: {key}") from ke
if opt.scriptable:
set_option(key, value)
return
raise StreamlitAPIException(
"{key} cannot be set on the fly. Set as command line option, e.g. streamlit run script.py --{key}, or in config.toml instead.".format(
key=key
)
) | Set config option. Currently, only the following config options can be set within the script itself: * client.caching * client.displayEnabled * deprecation.* Calling with any other options will raise StreamlitAPIException. Run `streamlit config show` in the terminal to see all available options. Parameters ---------- key : str The config option key of the form "section.optionName". To see all available options, run `streamlit config show` on a terminal. value The new value to assign to this config option. |
178,446 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
_section_descriptions: dict[str, str] = OrderedDict(
_test="Special test section just used for unit tests."
)
The provided code snippet includes necessary dependencies for implementing the `_create_section` function. Write a Python function `def _create_section(section: str, description: str) -> None` to solve the following problem:
Create a config section and store it globally in this module.
Here is the function:
def _create_section(section: str, description: str) -> None:
"""Create a config section and store it globally in this module."""
assert section not in _section_descriptions, (
'Cannot define section "%s" twice.' % section
)
_section_descriptions[section] = description | Create a config section and store it globally in this module. |
178,447 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
_section_descriptions: dict[str, str] = OrderedDict(
_test="Special test section just used for unit tests."
)
_config_options_template: dict[str, ConfigOption] = OrderedDict()
class ConfigOption:
'''Stores a Streamlit configuration option.
A configuration option, like 'browser.serverPort', which indicates which port
to use when connecting to the proxy. There are two ways to create a
ConfigOption:
Simple ConfigOptions are created as follows:
ConfigOption('browser.serverPort',
description = 'Connect to the proxy at this port.',
default_val = 8501)
More complex config options resolve their values at runtime as follows:
def _proxy_port():
"""Connect to the proxy at this port.
Defaults to 8501.
"""
return 8501
NOTE: For complex config options, the function is called each time the
option.value is evaluated!
Attributes
----------
key : str
The fully qualified section.name
value : any
The value for this option. If this is a complex config option then
the callback is called EACH TIME value is evaluated.
section : str
The section of this option. Example: 'global'.
name : str
See __init__.
description : str
See __init__.
where_defined : str
Indicates which file set this config option.
ConfigOption.DEFAULT_DEFINITION means this file.
is_default: bool
True if the config value is equal to its default value.
visibility : {"visible", "hidden"}
See __init__.
scriptable : bool
See __init__.
deprecated: bool
See __init__.
deprecation_text : str or None
See __init__.
expiration_date : str or None
See __init__.
replaced_by : str or None
See __init__.
sensitive : bool
See __init__.
env_var: str
The name of the environment variable that can be used to set the option.
'''
# This is a special value for ConfigOption.where_defined which indicates
# that the option default was not overridden.
DEFAULT_DEFINITION = "<default>"
# This is a special value for ConfigOption.where_defined which indicates
# that the options was defined by Streamlit's own code.
STREAMLIT_DEFINITION = "<streamlit>"
def __init__(
self,
key: str,
description: str | None = None,
default_val: Any | None = None,
visibility: str = "visible",
scriptable: bool = False,
deprecated: bool = False,
deprecation_text: str | None = None,
expiration_date: str | None = None,
replaced_by: str | None = None,
type_: type = str,
sensitive: bool = False,
):
"""Create a ConfigOption with the given name.
Parameters
----------
key : str
Should be of the form "section.optionName"
Examples: server.name, deprecation.v1_0_featureName
description : str
Like a comment for the config option.
default_val : any
The value for this config option.
visibility : {"visible", "hidden"}
Whether this option should be shown to users.
scriptable : bool
Whether this config option can be set within a user script.
deprecated: bool
Whether this config option is deprecated.
deprecation_text : str or None
Required if deprecated == True. Set this to a string explaining
what to use instead.
expiration_date : str or None
Required if deprecated == True. set this to the date at which it
will no longer be accepted. Format: 'YYYY-MM-DD'.
replaced_by : str or None
If this is option has been deprecated in favor or another option,
set this to the path to the new option. Example:
'server.runOnSave'. If this is set, the 'deprecated' option
will automatically be set to True, and deprecation_text will have a
meaningful default (unless you override it).
type_ : one of str, int, float or bool
Useful to cast the config params sent by cmd option parameter.
sensitive: bool
Sensitive configuration options cannot be set by CLI parameter.
"""
# Parse out the section and name.
self.key = key
key_format = (
# Capture a group called "section"
r"(?P<section>"
# Matching text comprised of letters and numbers that begins
# with a lowercase letter with an optional "_" preceding it.
# Examples: "_section", "section1"
r"\_?[a-z][a-zA-Z0-9]*"
r")"
# Separator between groups
r"\."
# Capture a group called "name"
r"(?P<name>"
# Match text comprised of letters and numbers beginning with a
# lowercase letter.
# Examples: "name", "nameOfConfig", "config1"
r"[a-z][a-zA-Z0-9]*"
r")$"
)
match = re.match(key_format, self.key)
assert match, f'Key "{self.key}" has invalid format.'
self.section, self.name = match.group("section"), match.group("name")
self.description = description
self.visibility = visibility
self.scriptable = scriptable
self.default_val = default_val
self.deprecated = deprecated
self.replaced_by = replaced_by
self.is_default = True
self._get_val_func: Callable[[], Any] | None = None
self.where_defined = ConfigOption.DEFAULT_DEFINITION
self.type = type_
self.sensitive = sensitive
if self.replaced_by:
self.deprecated = True
if deprecation_text is None:
deprecation_text = "Replaced by %s." % self.replaced_by
if self.deprecated:
assert expiration_date, "expiration_date is required for deprecated items"
assert deprecation_text, "deprecation_text is required for deprecated items"
self.expiration_date = expiration_date
self.deprecation_text = textwrap.dedent(deprecation_text)
self.set_value(default_val)
def __repr__(self) -> str:
return util.repr_(self)
def __call__(self, get_val_func: Callable[[], Any]) -> ConfigOption:
"""Assign a function to compute the value for this option.
This method is called when ConfigOption is used as a decorator.
Parameters
----------
get_val_func : function
A function which will be called to get the value of this parameter.
We will use its docString as the description.
Returns
-------
ConfigOption
Returns self, which makes testing easier. See config_test.py.
"""
assert (
get_val_func.__doc__
), "Complex config options require doc strings for their description."
self.description = get_val_func.__doc__
self._get_val_func = get_val_func
return self
def value(self) -> Any:
"""Get the value of this config option."""
if self._get_val_func is None:
return None
return self._get_val_func()
def set_value(self, value: Any, where_defined: str | None = None) -> None:
"""Set the value of this option.
Parameters
----------
value
The new value for this parameter.
where_defined : str
New value to remember where this parameter was set.
"""
self._get_val_func = lambda: value
if where_defined is None:
self.where_defined = ConfigOption.DEFAULT_DEFINITION
else:
self.where_defined = where_defined
self.is_default = value == self.default_val
if self.deprecated and self.where_defined != ConfigOption.DEFAULT_DEFINITION:
details = {
"key": self.key,
"file": self.where_defined,
"explanation": self.deprecation_text,
"date": self.expiration_date,
}
if self.is_expired():
# Import here to avoid circular imports
from streamlit.logger import get_logger
LOGGER = get_logger(__name__)
LOGGER.error(
textwrap.dedent(
"""
════════════════════════════════════════════════
%(key)s IS NO LONGER SUPPORTED.
%(explanation)s
Please update %(file)s.
════════════════════════════════════════════════
"""
)
% details
)
else:
# Import here to avoid circular imports
from streamlit.logger import get_logger
LOGGER = get_logger(__name__)
LOGGER.warning(
textwrap.dedent(
"""
════════════════════════════════════════════════
%(key)s IS DEPRECATED.
%(explanation)s
This option will be removed on or after %(date)s.
Please update %(file)s.
════════════════════════════════════════════════
"""
)
% details
)
def is_expired(self) -> bool:
"""Returns true if expiration_date is in the past."""
if not self.deprecated:
return False
expiration_date = _parse_yyyymmdd_str(self.expiration_date)
now = datetime.datetime.now()
return now > expiration_date
def env_var(self):
"""
Get the name of the environment variable that can be used to set the option.
"""
name = self.key.replace(".", "_")
return f"STREAMLIT_{to_snake_case(name).upper()}"
The provided code snippet includes necessary dependencies for implementing the `_create_option` function. Write a Python function `def _create_option( key: str, description: str | None = None, default_val: Any | None = None, scriptable: bool = False, visibility: str = "visible", deprecated: bool = False, deprecation_text: str | None = None, expiration_date: str | None = None, replaced_by: str | None = None, type_: type = str, sensitive: bool = False, ) -> ConfigOption` to solve the following problem:
Create a ConfigOption and store it globally in this module. There are two ways to create a ConfigOption: (1) Simple, constant config options are created as follows: _create_option('section.optionName', description = 'Put the description here.', default_val = 12345) (2) More complex, programmable config options use decorator syntax to resolve their values at runtime: @_create_option('section.optionName') def _section_option_name(): """Put the description here.""" return 12345 To achieve this sugar, _create_option() returns a *callable object* of type ConfigObject, which then decorates the function. NOTE: ConfigObjects call their evaluation functions *every time* the option is requested. To prevent this, use the `streamlit.util.memoize` decorator as follows: @_create_option('section.memoizedOptionName') @util.memoize def _section_memoized_option_name(): """Put the description here.""" (This function is only called once.) """ return 12345
Here is the function:
def _create_option(
key: str,
description: str | None = None,
default_val: Any | None = None,
scriptable: bool = False,
visibility: str = "visible",
deprecated: bool = False,
deprecation_text: str | None = None,
expiration_date: str | None = None,
replaced_by: str | None = None,
type_: type = str,
sensitive: bool = False,
) -> ConfigOption:
'''Create a ConfigOption and store it globally in this module.
There are two ways to create a ConfigOption:
(1) Simple, constant config options are created as follows:
_create_option('section.optionName',
description = 'Put the description here.',
default_val = 12345)
(2) More complex, programmable config options use decorator syntax to
resolve their values at runtime:
@_create_option('section.optionName')
def _section_option_name():
"""Put the description here."""
return 12345
To achieve this sugar, _create_option() returns a *callable object* of type
ConfigObject, which then decorates the function.
NOTE: ConfigObjects call their evaluation functions *every time* the option
is requested. To prevent this, use the `streamlit.util.memoize` decorator as
follows:
@_create_option('section.memoizedOptionName')
@util.memoize
def _section_memoized_option_name():
"""Put the description here."""
(This function is only called once.)
"""
return 12345
'''
option = ConfigOption(
key,
description=description,
default_val=default_val,
scriptable=scriptable,
visibility=visibility,
deprecated=deprecated,
deprecation_text=deprecation_text,
expiration_date=expiration_date,
replaced_by=replaced_by,
type_=type_,
sensitive=sensitive,
)
assert (
option.section in _section_descriptions
), 'Section "{}" must be one of {}.'.format(
option.section,
", ".join(_section_descriptions.keys()),
)
assert key not in _config_options_template, 'Cannot define option "%s" twice.' % key
_config_options_template[key] = option
return option | Create a ConfigOption and store it globally in this module. There are two ways to create a ConfigOption: (1) Simple, constant config options are created as follows: _create_option('section.optionName', description = 'Put the description here.', default_val = 12345) (2) More complex, programmable config options use decorator syntax to resolve their values at runtime: @_create_option('section.optionName') def _section_option_name(): """Put the description here.""" return 12345 To achieve this sugar, _create_option() returns a *callable object* of type ConfigObject, which then decorates the function. NOTE: ConfigObjects call their evaluation functions *every time* the option is requested. To prevent this, use the `streamlit.util.memoize` decorator as follows: @_create_option('section.memoizedOptionName') @util.memoize def _section_memoized_option_name(): """Put the description here.""" (This function is only called once.) """ return 12345 |
178,448 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
_config_options_template: dict[str, ConfigOption] = OrderedDict()
_config_options: dict[str, ConfigOption] | None = None
The provided code snippet includes necessary dependencies for implementing the `_delete_option` function. Write a Python function `def _delete_option(key: str) -> None` to solve the following problem:
Remove a ConfigOption by key from the global store. Only for use in testing.
Here is the function:
def _delete_option(key: str) -> None:
"""Remove a ConfigOption by key from the global store.
Only for use in testing.
"""
try:
del _config_options_template[key]
assert (
_config_options is not None
), "_config_options should always be populated here."
del _config_options[key]
except Exception:
# We don't care if the option already doesn't exist.
pass | Remove a ConfigOption by key from the global store. Only for use in testing. |
178,449 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
The provided code snippet includes necessary dependencies for implementing the `_global_development_mode` function. Write a Python function `def _global_development_mode() -> bool` to solve the following problem:
Are we in development mode. This option defaults to True if and only if Streamlit wasn't installed normally.
Here is the function:
def _global_development_mode() -> bool:
"""Are we in development mode.
This option defaults to True if and only if Streamlit wasn't installed
normally.
"""
return (
not env_util.is_pex()
and "site-packages" not in __file__
and "dist-packages" not in __file__
and "__pypackages__" not in __file__
) | Are we in development mode. This option defaults to True if and only if Streamlit wasn't installed normally. |
178,450 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
def get_option(key: str) -> Any:
"""Return the current value of a given Streamlit config option.
Run `streamlit config show` in the terminal to see all available options.
Parameters
----------
key : str
The config option key of the form "section.optionName". To see all
available options, run `streamlit config show` on a terminal.
"""
with _config_lock:
config_options = get_config_options()
if key not in config_options:
raise RuntimeError('Config key "%s" not defined.' % key)
return config_options[key].value
The provided code snippet includes necessary dependencies for implementing the `_logger_log_level` function. Write a Python function `def _logger_log_level() -> str` to solve the following problem:
Level of logging: 'error', 'warning', 'info', or 'debug'. Default: 'info'
Here is the function:
def _logger_log_level() -> str:
"""Level of logging: 'error', 'warning', 'info', or 'debug'.
Default: 'info'
"""
if get_option("global.logLevel"):
return str(get_option("global.logLevel"))
elif get_option("global.developmentMode"):
return "debug"
else:
return "info" | Level of logging: 'error', 'warning', 'info', or 'debug'. Default: 'info' |
178,451 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
def get_option(key: str) -> Any:
"""Return the current value of a given Streamlit config option.
Run `streamlit config show` in the terminal to see all available options.
Parameters
----------
key : str
The config option key of the form "section.optionName". To see all
available options, run `streamlit config show` on a terminal.
"""
with _config_lock:
config_options = get_config_options()
if key not in config_options:
raise RuntimeError('Config key "%s" not defined.' % key)
return config_options[key].value
DEFAULT_LOG_MESSAGE: Final = "%(asctime)s %(levelname) -7s " "%(name)s: %(message)s"
The provided code snippet includes necessary dependencies for implementing the `_logger_message_format` function. Write a Python function `def _logger_message_format() -> str` to solve the following problem:
String format for logging messages. If logger.datetimeFormat is set, logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See [Python's documentation](https://docs.python.org/2.6/library/logging.html#formatter-objects) for available attributes. Default: "%(asctime)s %(message)s"
Here is the function:
def _logger_message_format() -> str:
"""String format for logging messages. If logger.datetimeFormat is set,
logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See
[Python's documentation](https://docs.python.org/2.6/library/logging.html#formatter-objects)
for available attributes.
Default: "%(asctime)s %(message)s"
"""
if get_option("global.developmentMode"):
from streamlit.logger import DEFAULT_LOG_MESSAGE
return DEFAULT_LOG_MESSAGE
else:
return "%(asctime)s %(message)s" | String format for logging messages. If logger.datetimeFormat is set, logger messages will default to `%(asctime)s.%(msecs)03d %(message)s`. See [Python's documentation](https://docs.python.org/2.6/library/logging.html#formatter-objects) for available attributes. Default: "%(asctime)s %(message)s" |
178,452 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
secrets = _secrets_singleton
The provided code snippet includes necessary dependencies for implementing the `_server_cookie_secret` function. Write a Python function `def _server_cookie_secret() -> str` to solve the following problem:
Symmetric key used to produce signed cookies. If deploying on multiple replicas, this should be set to the same value across all replicas to ensure they all share the same secret. Default: randomly generated secret key.
Here is the function:
def _server_cookie_secret() -> str:
"""Symmetric key used to produce signed cookies. If deploying on multiple replicas, this should
be set to the same value across all replicas to ensure they all share the same secret.
Default: randomly generated secret key.
"""
return secrets.token_hex() | Symmetric key used to produce signed cookies. If deploying on multiple replicas, this should be set to the same value across all replicas to ensure they all share the same secret. Default: randomly generated secret key. |
178,453 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
The provided code snippet includes necessary dependencies for implementing the `_server_headless` function. Write a Python function `def _server_headless() -> bool` to solve the following problem:
If false, will attempt to open a browser window on start. Default: false unless (1) we are on a Linux box where DISPLAY is unset, or (2) we are running in the Streamlit Atom plugin.
Here is the function:
def _server_headless() -> bool:
"""If false, will attempt to open a browser window on start.
Default: false unless (1) we are on a Linux box where DISPLAY is unset, or
(2) we are running in the Streamlit Atom plugin.
"""
if env_util.IS_LINUX_OR_BSD and not os.getenv("DISPLAY"):
# We're running in Linux and DISPLAY is unset
return True
if os.getenv("IS_RUNNING_IN_STREAMLIT_EDITOR_PLUGIN") is not None:
# We're running within the Streamlit Atom plugin
return True
return False | If false, will attempt to open a browser window on start. Default: false unless (1) we are on a Linux box where DISPLAY is unset, or (2) we are running in the Streamlit Atom plugin. |
178,454 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
The provided code snippet includes necessary dependencies for implementing the `_server_address` function. Write a Python function `def _server_address() -> str | None` to solve the following problem:
The address where the server will listen for client and browser connections. Use this if you want to bind the server to a specific address. If set, the server will only be accessible from this address, and not from any aliases (like localhost). Default: (unset)
Here is the function:
def _server_address() -> str | None:
"""The address where the server will listen for client and browser
connections. Use this if you want to bind the server to a specific address.
If set, the server will only be accessible from this address, and not from
any aliases (like localhost).
Default: (unset)
"""
return None | The address where the server will listen for client and browser connections. Use this if you want to bind the server to a specific address. If set, the server will only be accessible from this address, and not from any aliases (like localhost). Default: (unset) |
178,455 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
def get_option(key: str) -> Any:
"""Return the current value of a given Streamlit config option.
Run `streamlit config show` in the terminal to see all available options.
Parameters
----------
key : str
The config option key of the form "section.optionName". To see all
available options, run `streamlit config show` on a terminal.
"""
with _config_lock:
config_options = get_config_options()
if key not in config_options:
raise RuntimeError('Config key "%s" not defined.' % key)
return config_options[key].value
The provided code snippet includes necessary dependencies for implementing the `_browser_server_port` function. Write a Python function `def _browser_server_port() -> int` to solve the following problem:
Port where users should point their browsers in order to connect to the app. This is used to: - Set the correct URL for XSRF protection purposes. - Show the URL on the terminal (part of `streamlit run`). - Open the browser automatically (part of `streamlit run`). This option is for advanced use cases. To change the port of your app, use `server.Port` instead. Don't use port 3000 which is reserved for internal development. Default: whatever value is set in server.port.
Here is the function:
def _browser_server_port() -> int:
"""Port where users should point their browsers in order to connect to the
app.
This is used to:
- Set the correct URL for XSRF protection purposes.
- Show the URL on the terminal (part of `streamlit run`).
- Open the browser automatically (part of `streamlit run`).
This option is for advanced use cases. To change the port of your app, use
`server.Port` instead. Don't use port 3000 which is reserved for internal
development.
Default: whatever value is set in server.port.
"""
return int(get_option("server.port")) | Port where users should point their browsers in order to connect to the app. This is used to: - Set the correct URL for XSRF protection purposes. - Show the URL on the terminal (part of `streamlit run`). - Open the browser automatically (part of `streamlit run`). This option is for advanced use cases. To change the port of your app, use `server.Port` instead. Don't use port 3000 which is reserved for internal development. Default: whatever value is set in server.port. |
178,456 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
def get_option(key: str) -> Any:
"""Return the current value of a given Streamlit config option.
Run `streamlit config show` in the terminal to see all available options.
Parameters
----------
key : str
The config option key of the form "section.optionName". To see all
available options, run `streamlit config show` on a terminal.
"""
with _config_lock:
config_options = get_config_options()
if key not in config_options:
raise RuntimeError('Config key "%s" not defined.' % key)
return config_options[key].value
def _is_unset(option_name: str) -> bool:
"""Check if a given option has not been set by the user.
Parameters
----------
option_name : str
The option to check
Returns
-------
bool
True if the option has not been set by the user.
"""
return get_where_defined(option_name) == ConfigOption.DEFAULT_DEFINITION
def get_logger(name: str) -> logging.Logger:
"""Return a logger.
Parameters
----------
name : str
The name of the logger to use. You should just pass in __name__.
Returns
-------
Logger
"""
if name in _loggers.keys():
return _loggers[name]
if name == "root":
logger = logging.getLogger("streamlit")
else:
logger = logging.getLogger(name)
logger.setLevel(_global_log_level)
logger.propagate = False
setup_formatter(logger)
_loggers[name] = logger
return logger
def _check_conflicts() -> None:
# Node-related conflicts
# When using the Node server, we must always connect to 8501 (this is
# hard-coded in JS). Otherwise, the browser would decide what port to
# connect to based on window.location.port, which in dev is going to
# be (3000)
# Import logger locally to prevent circular references
from streamlit.logger import get_logger
LOGGER = get_logger(__name__)
if get_option("global.developmentMode"):
assert _is_unset(
"server.port"
), "server.port does not work when global.developmentMode is true."
assert _is_unset("browser.serverPort"), (
"browser.serverPort does not work when global.developmentMode is " "true."
)
# XSRF conflicts
if get_option("server.enableXsrfProtection"):
if not get_option("server.enableCORS") or get_option("global.developmentMode"):
LOGGER.warning(
"""
Warning: the config option 'server.enableCORS=false' is not compatible with 'server.enableXsrfProtection=true'.
As a result, 'server.enableCORS' is being overridden to 'true'.
More information:
In order to protect against CSRF attacks, we send a cookie with each request.
To do so, we must specify allowable origins, which places a restriction on
cross-origin resource sharing.
If cross origin resource sharing is required, please disable server.enableXsrfProtection.
"""
) | null |
178,457 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
def get_option(key: str) -> Any:
"""Return the current value of a given Streamlit config option.
Run `streamlit config show` in the terminal to see all available options.
Parameters
----------
key : str
The config option key of the form "section.optionName". To see all
available options, run `streamlit config show` on a terminal.
"""
with _config_lock:
config_options = get_config_options()
if key not in config_options:
raise RuntimeError('Config key "%s" not defined.' % key)
return config_options[key].value
def _set_development_mode() -> None:
development.is_development_mode = get_option("global.developmentMode") | null |
178,458 | from __future__ import annotations
import copy
import os
import secrets
import threading
from collections import OrderedDict
from typing import Any, Callable
from blinker import Signal
from streamlit import config_util, development, env_util, file_util, util
from streamlit.config_option import ConfigOption
from streamlit.errors import StreamlitAPIException
_config_lock = threading.RLock()
_config_options: dict[str, ConfigOption] | None = None
_on_config_parsed = Signal(doc="Emitted when the config file is parsed.")
The provided code snippet includes necessary dependencies for implementing the `on_config_parsed` function. Write a Python function `def on_config_parsed( func: Callable[[], None], force_connect=False, lock=False ) -> Callable[[], bool]` to solve the following problem:
Wait for the config file to be parsed then call func. If the config file has already been parsed, just calls func immediately unless force_connect is set. Parameters ---------- func : Callable[[], None] A function to run on config parse. force_connect : bool Wait until the next config file parse to run func, even if config files have already been parsed. lock : bool If set, grab _config_lock before running func. Returns ------- Callable[[], bool] A function that the caller can use to deregister func.
Here is the function:
def on_config_parsed(
func: Callable[[], None], force_connect=False, lock=False
) -> Callable[[], bool]:
"""Wait for the config file to be parsed then call func.
If the config file has already been parsed, just calls func immediately
unless force_connect is set.
Parameters
----------
func : Callable[[], None]
A function to run on config parse.
force_connect : bool
Wait until the next config file parse to run func, even if config files
have already been parsed.
lock : bool
If set, grab _config_lock before running func.
Returns
-------
Callable[[], bool]
A function that the caller can use to deregister func.
"""
# We need to use the same receiver when we connect or disconnect on the
# Signal. If we don't do this, then the registered receiver won't be released
# leading to a memory leak because the Signal will keep a reference of the
# callable argument. When the callable argument is an object method, then
# the reference to that object won't be released.
receiver = lambda _: func_with_lock()
def disconnect():
return _on_config_parsed.disconnect(receiver)
def func_with_lock():
if lock:
with _config_lock:
func()
else:
func()
if force_connect or not _config_options:
# weak=False so that we have control of when the on_config_parsed
# callback is deregistered.
_on_config_parsed.connect(receiver, weak=False)
else:
func_with_lock()
return disconnect | Wait for the config file to be parsed then call func. If the config file has already been parsed, just calls func immediately unless force_connect is set. Parameters ---------- func : Callable[[], None] A function to run on config parse. force_connect : bool Wait until the next config file parse to run func, even if config files have already been parsed. lock : bool If set, grab _config_lock before running func. Returns ------- Callable[[], bool] A function that the caller can use to deregister func. |
178,459 | import inspect
import textwrap
import streamlit as st
The provided code snippet includes necessary dependencies for implementing the `show_code` function. Write a Python function `def show_code(demo)` to solve the following problem:
Showing the code of the demo.
Here is the function:
def show_code(demo):
"""Showing the code of the demo."""
show_code = st.sidebar.checkbox("Show code", True)
if show_code:
# Showing the code of the demo.
st.markdown("## Code")
sourcelines, _ = inspect.getsourcelines(demo)
st.code(textwrap.dedent("".join(sourcelines[1:]))) | Showing the code of the demo. |
178,460 | from typing import Any
import numpy as np
import streamlit as st
from streamlit.hello.utils import show_code
st.set_page_config(page_title="Animation Demo", page_icon="📹")
st.markdown("# Animation Demo")
st.sidebar.header("Animation Demo")
st.write(
"""This app shows how you can use Streamlit to build cool animations.
It displays an animated fractal based on the the Julia Set. Use the slider
to tune different parameters."""
)
def animation_demo() -> None:
# Interactive Streamlit elements, like these sliders, return their value.
# This gives you an extremely simple interaction model.
iterations = st.sidebar.slider("Level of detail", 2, 20, 10, 1)
separation = st.sidebar.slider("Separation", 0.7, 2.0, 0.7885)
# Non-interactive elements return a placeholder to their location
# in the app. Here we're storing progress_bar to update it later.
progress_bar = st.sidebar.progress(0)
# These two elements will be filled in later, so we create a placeholder
# for them using st.empty()
frame_text = st.sidebar.empty()
image = st.empty()
m, n, s = 960, 640, 400
x = np.linspace(-m / s, m / s, num=m).reshape((1, m))
y = np.linspace(-n / s, n / s, num=n).reshape((n, 1))
for frame_num, a in enumerate(np.linspace(0.0, 4 * np.pi, 100)):
# Here were setting value for these two elements.
progress_bar.progress(frame_num)
frame_text.text("Frame %i/100" % (frame_num + 1))
# Performing some fractal wizardry.
c = separation * np.exp(1j * a)
Z = np.tile(x, (n, 1)) + 1j * np.tile(y, (1, m))
C = np.full((n, m), c)
M: Any = np.full((n, m), True, dtype=bool)
N = np.zeros((n, m))
for i in range(iterations):
Z[M] = Z[M] * Z[M] + C[M]
M[np.abs(Z) > 2] = False
N[M] = i
# Update the image placeholder by calling the image() function on it.
image.image(1.0 - (N / N.max()), use_column_width=True)
# We clear elements by calling empty on them.
progress_bar.empty()
frame_text.empty()
# Streamlit widgets automatically run the script from top to bottom. Since
# this button is not connected to any other logic, it just causes a plain
# rerun.
st.button("Re-run") | null |
178,461 | import time
import numpy as np
import streamlit as st
from streamlit.hello.utils import show_code
st.set_page_config(page_title="Plotting Demo", page_icon="📈")
st.markdown("# Plotting Demo")
st.sidebar.header("Plotting Demo")
st.write(
"""This demo illustrates a combination of plotting and animation with
Streamlit. We're generating a bunch of random numbers in a loop for around
5 seconds. Enjoy!"""
)
def plotting_demo():
progress_bar = st.sidebar.progress(0)
status_text = st.sidebar.empty()
last_rows = np.random.randn(1, 1)
chart = st.line_chart(last_rows)
for i in range(1, 101):
new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)
status_text.text("%i%% Complete" % i)
chart.add_rows(new_rows)
progress_bar.progress(i)
last_rows = new_rows
time.sleep(0.05)
progress_bar.empty()
# Streamlit widgets automatically run the script from top to bottom. Since
# this button is not connected to any other logic, it just causes a plain
# rerun.
st.button("Re-run") | null |
178,462 | from urllib.error import URLError
import pandas as pd
import pydeck as pdk
import streamlit as st
from streamlit.hello.utils import show_code
st.set_page_config(page_title="Mapping Demo", page_icon="🌍")
st.markdown("# Mapping Demo")
st.sidebar.header("Mapping Demo")
st.write(
"""This demo shows how to use
[`st.pydeck_chart`](https://docs.streamlit.io/library/api-reference/charts/st.pydeck_chart)
to display geospatial data."""
)
def mapping_demo():
@st.cache_data
def from_data_file(filename):
url = (
"https://raw.githubusercontent.com/streamlit/"
"example-data/master/hello/v1/%s" % filename
)
return pd.read_json(url)
try:
ALL_LAYERS = {
"Bike Rentals": pdk.Layer(
"HexagonLayer",
data=from_data_file("bike_rental_stats.json"),
get_position=["lon", "lat"],
radius=200,
elevation_scale=4,
elevation_range=[0, 1000],
extruded=True,
),
"Bart Stop Exits": pdk.Layer(
"ScatterplotLayer",
data=from_data_file("bart_stop_stats.json"),
get_position=["lon", "lat"],
get_color=[200, 30, 0, 160],
get_radius="[exits]",
radius_scale=0.05,
),
"Bart Stop Names": pdk.Layer(
"TextLayer",
data=from_data_file("bart_stop_stats.json"),
get_position=["lon", "lat"],
get_text="name",
get_color=[0, 0, 0, 200],
get_size=10,
get_alignment_baseline="'bottom'",
),
"Outbound Flow": pdk.Layer(
"ArcLayer",
data=from_data_file("bart_path_stats.json"),
get_source_position=["lon", "lat"],
get_target_position=["lon2", "lat2"],
get_source_color=[200, 30, 0, 160],
get_target_color=[200, 30, 0, 160],
auto_highlight=True,
width_scale=0.0001,
get_width="outbound",
width_min_pixels=3,
width_max_pixels=30,
),
}
st.sidebar.markdown("### Map Layers")
selected_layers = [
layer
for layer_name, layer in ALL_LAYERS.items()
if st.sidebar.checkbox(layer_name, True)
]
if selected_layers:
st.pydeck_chart(
pdk.Deck(
map_style=None,
initial_view_state={
"latitude": 37.76,
"longitude": -122.4,
"zoom": 11,
"pitch": 50,
},
layers=selected_layers,
)
)
else:
st.error("Please choose at least one layer above.")
except URLError as e:
st.error(
"""
**This demo requires internet access.**
Connection error: %s
"""
% e.reason
) | null |
178,463 | from urllib.error import URLError
import altair as alt
import pandas as pd
import streamlit as st
from streamlit.hello.utils import show_code
st.set_page_config(page_title="DataFrame Demo", page_icon="📊")
st.markdown("# DataFrame Demo")
st.sidebar.header("DataFrame Demo")
st.write(
"""This demo shows how to use `st.write` to visualize Pandas DataFrames.
(Data courtesy of the [UN Data Explorer](http://data.un.org/Explorer.aspx).)"""
)
def data_frame_demo():
@st.cache_data
def get_UN_data():
AWS_BUCKET_URL = "https://streamlit-demo-data.s3-us-west-2.amazonaws.com"
df = pd.read_csv(AWS_BUCKET_URL + "/agri.csv.gz")
return df.set_index("Region")
try:
df = get_UN_data()
countries = st.multiselect(
"Choose countries", list(df.index), ["China", "United States of America"]
)
if not countries:
st.error("Please select at least one country.")
else:
data = df.loc[countries]
data /= 1000000.0
st.write("### Gross Agricultural Production ($B)", data.sort_index())
data = data.T.reset_index()
data = pd.melt(data, id_vars=["index"]).rename(
columns={"index": "year", "value": "Gross Agricultural Product ($B)"}
)
chart = (
alt.Chart(data)
.mark_area(opacity=0.3)
.encode(
x="year:T",
y=alt.Y("Gross Agricultural Product ($B):Q", stack=None),
color="Region:N",
)
)
st.altair_chart(chart, use_container_width=True)
except URLError as e:
st.error(
"""
**This demo requires internet access.**
Connection error: %s
"""
% e.reason
) | null |
178,464 | from __future__ import annotations
import hashlib
import os
import time
from pathlib import Path
from streamlit.util import HASHLIB_KWARGS
def _get_file_content_with_blocking_retries(file_path: str) -> bytes:
content = b""
# There's a race condition where sometimes file_path no longer exists when
# we try to read it (since the file is in the process of being written).
# So here we retry a few times using this loop. See issue #186.
for i in range(_MAX_RETRIES):
try:
with open(file_path, "rb") as f:
content = f.read()
break
except FileNotFoundError as e:
if i >= _MAX_RETRIES - 1:
raise e
time.sleep(_RETRY_WAIT_SECS)
return content
def _stable_dir_identifier(dir_path: str, glob_pattern: str) -> str:
"""Wait for the files in a directory to look stable-ish before returning an id.
We do this to deal with problems that would otherwise arise from many tools
(e.g. git) and editors (e.g. vim) "editing" files (from the user's
perspective) by doing some combination of deleting, creating, and moving
various files under the hood.
Because of this, we're unable to rely on FileSystemEvents that we receive
from watchdog to determine when a file has been added to or removed from a
directory.
This is a bit of an unfortunate situation, but the approach we take here is
most likely fine as:
* The worst thing that can happen taking this approach is a false
positive page added/removed notification, which isn't too disastrous
and can just be ignored.
* It is impossible (that is, I'm fairly certain that the problem is
undecidable) to know whether a file created/deleted/moved event
corresponds to a legitimate file creation/deletion/move or is part of
some sequence of events that results in what the user sees as a file
"edit".
"""
dirfiles = _dirfiles(dir_path, glob_pattern)
for _ in range(_MAX_RETRIES):
time.sleep(_RETRY_WAIT_SECS)
new_dirfiles = _dirfiles(dir_path, glob_pattern)
if dirfiles == new_dirfiles:
break
dirfiles = new_dirfiles
return f"{dir_path}+{dirfiles}"
HASHLIB_KWARGS: dict[str, Any] = (
{"usedforsecurity": False} if sys.version_info >= (3, 9) else {}
)
The provided code snippet includes necessary dependencies for implementing the `calc_md5_with_blocking_retries` function. Write a Python function `def calc_md5_with_blocking_retries( path: str, *, # keyword-only arguments: glob_pattern: str | None = None, allow_nonexistent: bool = False, ) -> str` to solve the following problem:
Calculate the MD5 checksum of a given path. For a file, this means calculating the md5 of the file's contents. For a directory, we concatenate the directory's path with the names of all the files in it and calculate the md5 of that. IMPORTANT: This method calls time.sleep(), which blocks execution. So you should only use this outside the main thread.
Here is the function:
def calc_md5_with_blocking_retries(
path: str,
*, # keyword-only arguments:
glob_pattern: str | None = None,
allow_nonexistent: bool = False,
) -> str:
"""Calculate the MD5 checksum of a given path.
For a file, this means calculating the md5 of the file's contents. For a
directory, we concatenate the directory's path with the names of all the
files in it and calculate the md5 of that.
IMPORTANT: This method calls time.sleep(), which blocks execution. So you
should only use this outside the main thread.
"""
if allow_nonexistent and not os.path.exists(path):
content = path.encode("UTF-8")
elif os.path.isdir(path):
glob_pattern = glob_pattern or "*"
content = _stable_dir_identifier(path, glob_pattern).encode("UTF-8")
else:
content = _get_file_content_with_blocking_retries(path)
md5 = hashlib.md5(**HASHLIB_KWARGS)
md5.update(content)
# Use hexdigest() instead of digest(), so it's easier to debug.
return md5.hexdigest() | Calculate the MD5 checksum of a given path. For a file, this means calculating the md5 of the file's contents. For a directory, we concatenate the directory's path with the names of all the files in it and calculate the md5 of that. IMPORTANT: This method calls time.sleep(), which blocks execution. So you should only use this outside the main thread. |
178,465 | from __future__ import annotations
import hashlib
import os
import time
from pathlib import Path
from streamlit.util import HASHLIB_KWARGS
The provided code snippet includes necessary dependencies for implementing the `path_modification_time` function. Write a Python function `def path_modification_time(path: str, allow_nonexistent: bool = False) -> float` to solve the following problem:
Return the modification time of a path (file or directory). If allow_nonexistent is True and the path does not exist, we return 0.0 to guarantee that any file/dir later created at the path has a later modification time than the last time returned by this function for that path. If allow_nonexistent is False and no file/dir exists at the path, a FileNotFoundError is raised (by os.stat). For any path that does correspond to an existing file/dir, we return its modification time.
Here is the function:
def path_modification_time(path: str, allow_nonexistent: bool = False) -> float:
"""Return the modification time of a path (file or directory).
If allow_nonexistent is True and the path does not exist, we return 0.0 to
guarantee that any file/dir later created at the path has a later
modification time than the last time returned by this function for that
path.
If allow_nonexistent is False and no file/dir exists at the path, a
FileNotFoundError is raised (by os.stat).
For any path that does correspond to an existing file/dir, we return its
modification time.
"""
if allow_nonexistent and not os.path.exists(path):
return 0.0
return os.stat(path).st_mtime | Return the modification time of a path (file or directory). If allow_nonexistent is True and the path does not exist, we return 0.0 to guarantee that any file/dir later created at the path has a later modification time than the last time returned by this function for that path. If allow_nonexistent is False and no file/dir exists at the path, a FileNotFoundError is raised (by os.stat). For any path that does correspond to an existing file/dir, we return its modification time. |
178,466 | from __future__ import annotations
from typing import Callable, Type, Union
import streamlit.watcher
from streamlit import cli_util, config, env_util
from streamlit.watcher.polling_path_watcher import PollingPathWatcher
def _is_watchdog_available() -> bool:
"""Check if the watchdog module is installed."""
try:
import watchdog # noqa: F401
return True
except ImportError:
return False
def report_watchdog_availability():
if (
not config.get_option("global.disableWatchdogWarning")
and config.get_option("server.fileWatcherType") not in ["poll", "none"]
and not _is_watchdog_available()
):
msg = "\n $ xcode-select --install" if env_util.IS_DARWIN else ""
cli_util.print_to_cli(
" %s" % "For better performance, install the Watchdog module:",
fg="blue",
bold=True,
)
cli_util.print_to_cli(
"""%s
$ pip install watchdog
"""
% msg
) | null |
178,467 | from __future__ import annotations
from typing import Callable, Type, Union
import streamlit.watcher
from streamlit import cli_util, config, env_util
from streamlit.watcher.polling_path_watcher import PollingPathWatcher
def _watch_path(
path: str,
on_path_changed: Callable[[str], None],
watcher_type: str | None = None,
*, # keyword-only arguments:
glob_pattern: str | None = None,
allow_nonexistent: bool = False,
) -> bool:
"""Create a PathWatcher for the given path if we have a viable
PathWatcher class.
Parameters
----------
path
Path to watch.
on_path_changed
Function that's called when the path changes.
watcher_type
Optional watcher_type string. If None, it will default to the
'server.fileWatcherType` config option.
glob_pattern
Optional glob pattern to use when watching a directory. If set, only
files matching the pattern will be counted as being created/deleted
within the watched directory.
allow_nonexistent
If True, allow the file or directory at the given path to be
nonexistent.
Returns
-------
bool
True if the path is being watched, or False if we have no
PathWatcher class.
"""
if watcher_type is None:
watcher_type = config.get_option("server.fileWatcherType")
watcher_class = get_path_watcher_class(watcher_type)
if watcher_class is NoOpPathWatcher:
return False
watcher_class(
path,
on_path_changed,
glob_pattern=glob_pattern,
allow_nonexistent=allow_nonexistent,
)
return True
def watch_file(
path: str,
on_file_changed: Callable[[str], None],
watcher_type: str | None = None,
) -> bool:
return _watch_path(path, on_file_changed, watcher_type) | null |
178,468 | from __future__ import annotations
from typing import Callable, Type, Union
import streamlit.watcher
from streamlit import cli_util, config, env_util
from streamlit.watcher.polling_path_watcher import PollingPathWatcher
def _watch_path(
path: str,
on_path_changed: Callable[[str], None],
watcher_type: str | None = None,
*, # keyword-only arguments:
glob_pattern: str | None = None,
allow_nonexistent: bool = False,
) -> bool:
"""Create a PathWatcher for the given path if we have a viable
PathWatcher class.
Parameters
----------
path
Path to watch.
on_path_changed
Function that's called when the path changes.
watcher_type
Optional watcher_type string. If None, it will default to the
'server.fileWatcherType` config option.
glob_pattern
Optional glob pattern to use when watching a directory. If set, only
files matching the pattern will be counted as being created/deleted
within the watched directory.
allow_nonexistent
If True, allow the file or directory at the given path to be
nonexistent.
Returns
-------
bool
True if the path is being watched, or False if we have no
PathWatcher class.
"""
if watcher_type is None:
watcher_type = config.get_option("server.fileWatcherType")
watcher_class = get_path_watcher_class(watcher_type)
if watcher_class is NoOpPathWatcher:
return False
watcher_class(
path,
on_path_changed,
glob_pattern=glob_pattern,
allow_nonexistent=allow_nonexistent,
)
return True
def watch_dir(
path: str,
on_dir_changed: Callable[[str], None],
watcher_type: str | None = None,
*, # keyword-only arguments:
glob_pattern: str | None = None,
allow_nonexistent: bool = False,
) -> bool:
return _watch_path(
path,
on_dir_changed,
watcher_type,
glob_pattern=glob_pattern,
allow_nonexistent=allow_nonexistent,
) | null |
178,469 | from __future__ import annotations
from typing import Callable, Type, Union
import streamlit.watcher
from streamlit import cli_util, config, env_util
from streamlit.watcher.polling_path_watcher import PollingPathWatcher
PathWatcherType = Union[
Type["streamlit.watcher.event_based_path_watcher.EventBasedPathWatcher"],
Type[PollingPathWatcher],
Type[NoOpPathWatcher],
]
def get_path_watcher_class(watcher_type: str) -> PathWatcherType:
"""Return the PathWatcher class that corresponds to the given watcher_type
string. Acceptable values are 'auto', 'watchdog', 'poll' and 'none'.
"""
if watcher_type in {"watchdog", "auto"} and _is_watchdog_available():
# Lazy-import this module to prevent unnecessary imports of the watchdog package.
from streamlit.watcher.event_based_path_watcher import EventBasedPathWatcher
return EventBasedPathWatcher
elif watcher_type == "auto":
return PollingPathWatcher
elif watcher_type == "poll":
return PollingPathWatcher
else:
return NoOpPathWatcher
The provided code snippet includes necessary dependencies for implementing the `get_default_path_watcher_class` function. Write a Python function `def get_default_path_watcher_class() -> PathWatcherType` to solve the following problem:
Return the class to use for path changes notifications, based on the server.fileWatcherType config option.
Here is the function:
def get_default_path_watcher_class() -> PathWatcherType:
"""Return the class to use for path changes notifications, based on the
server.fileWatcherType config option.
"""
return get_path_watcher_class(config.get_option("server.fileWatcherType")) | Return the class to use for path changes notifications, based on the server.fileWatcherType config option. |
178,470 | from __future__ import annotations
import collections
import os
import sys
import types
from typing import Callable, Final
from streamlit import config, file_util
from streamlit.folder_black_list import FolderBlackList
from streamlit.logger import get_logger
from streamlit.source_util import get_pages
from streamlit.watcher.path_watcher import (
NoOpPathWatcher,
get_default_path_watcher_class,
)
_LOGGER: Final = get_logger(__name__)
def _is_valid_path(path: str | None) -> bool:
return isinstance(path, str) and (os.path.isfile(path) or os.path.isdir(path))
def get_module_paths(module: types.ModuleType) -> set[str]:
paths_extractors = [
# https://docs.python.org/3/reference/datamodel.html
# __file__ is the pathname of the file from which the module was loaded
# if it was loaded from a file.
# The __file__ attribute may be missing for certain types of modules
lambda m: [m.__file__],
# https://docs.python.org/3/reference/import.html#__spec__
# The __spec__ attribute is set to the module spec that was used
# when importing the module. one exception is __main__,
# where __spec__ is set to None in some cases.
# https://www.python.org/dev/peps/pep-0451/#id16
# "origin" in an import context means the system
# (or resource within a system) from which a module originates
# ... It is up to the loader to decide on how to interpret
# and use a module's origin, if at all.
lambda m: [m.__spec__.origin],
# https://www.python.org/dev/peps/pep-0420/
# Handling of "namespace packages" in which the __path__ attribute
# is a _NamespacePath object with a _path attribute containing
# the various paths of the package.
lambda m: [p for p in m.__path__._path],
]
all_paths = set()
for extract_paths in paths_extractors:
potential_paths = []
try:
potential_paths = extract_paths(module)
except AttributeError:
# Some modules might not have __file__ or __spec__ attributes.
pass
except Exception as e:
_LOGGER.warning(f"Examining the path of {module.__name__} raised: {e}")
all_paths.update(
[os.path.abspath(str(p)) for p in potential_paths if _is_valid_path(p)]
)
return all_paths | null |
178,471 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
def _convert_config_option_to_click_option(
config_option: ConfigOption,
) -> dict[str, Any]:
"""Composes given config option options as options for click lib."""
option = f"--{config_option.key}"
param = config_option.key.replace(".", "_")
description = config_option.description
if config_option.deprecated:
if description is None:
description = ""
description += (
f"\n {config_option.deprecation_text} - {config_option.expiration_date}"
)
return {
"param": param,
"description": description,
"type": config_option.type,
"option": option,
"envvar": config_option.env_var,
}
def _make_sensitive_option_callback(config_option: ConfigOption):
def callback(_ctx: click.Context, _param: click.Parameter, cli_value) -> None:
if cli_value is None:
return None
raise SystemExit(
f"Setting {config_option.key!r} option using the CLI flag is not allowed. "
f"Set this option in the configuration file or environment "
f"variable: {config_option.env_var!r}"
)
return callback
def help():
"""Print this help message."""
# We use _get_command_line_as_string to run some error checks but don't do
# anything with its return value.
_get_command_line_as_string()
assert len(sys.argv) == 2 # This is always true, but let's assert anyway.
# Pretend user typed 'streamlit --help' instead of 'streamlit help'.
sys.argv[1] = "--help"
main(prog_name="streamlit")
The provided code snippet includes necessary dependencies for implementing the `configurator_options` function. Write a Python function `def configurator_options(func)` to solve the following problem:
Decorator that adds config param keys to click dynamically.
Here is the function:
def configurator_options(func):
"""Decorator that adds config param keys to click dynamically."""
for _, value in reversed(_config._config_options_template.items()):
parsed_parameter = _convert_config_option_to_click_option(value)
if value.sensitive:
# Display a warning if the user tries to set sensitive
# options using the CLI and exit with non-zero code.
click_option_kwargs = {
"expose_value": False,
"hidden": True,
"is_eager": True,
"callback": _make_sensitive_option_callback(value),
}
else:
click_option_kwargs = {
"show_envvar": True,
"envvar": parsed_parameter["envvar"],
}
config_option = click.option(
parsed_parameter["option"],
parsed_parameter["param"],
help=parsed_parameter["description"],
type=parsed_parameter["type"],
**click_option_kwargs,
)
func = config_option(func)
return func | Decorator that adds config param keys to click dynamically. |
178,472 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
def main(log_level="info"):
"""Try out a demo with:
$ streamlit hello
Or use the line below to run your own script:
$ streamlit run your_script.py
"""
if log_level:
from streamlit.logger import get_logger
LOGGER = get_logger(__name__)
LOGGER.warning(
"Setting the log level using the --log_level flag is unsupported."
"\nUse the --logger.level flag (after your streamlit command) instead."
)
def _get_command_line_as_string() -> str | None:
import subprocess
parent = click.get_current_context().parent
if parent is None:
return None
if "streamlit.cli" in parent.command_path:
raise RuntimeError(
"Running streamlit via `python -m streamlit.cli <command>` is"
" unsupported. Please use `python -m streamlit <command>` instead."
)
cmd_line_as_list = [parent.command_path]
cmd_line_as_list.extend(sys.argv[1:])
return subprocess.list2cmdline(cmd_line_as_list)
The provided code snippet includes necessary dependencies for implementing the `main_version` function. Write a Python function `def main_version()` to solve the following problem:
Print Streamlit's version number.
Here is the function:
def main_version():
"""Print Streamlit's version number."""
# Pretend user typed 'streamlit --version' instead of 'streamlit version'
import sys
# We use _get_command_line_as_string to run some error checks but don't do
# anything with its return value.
_get_command_line_as_string()
assert len(sys.argv) == 2 # This is always true, but let's assert anyway.
sys.argv[1] = "--version"
main() | Print Streamlit's version number. |
178,473 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
The provided code snippet includes necessary dependencies for implementing the `main_docs` function. Write a Python function `def main_docs()` to solve the following problem:
Show help in browser.
Here is the function:
def main_docs():
"""Show help in browser."""
print("Showing help page in browser...")
from streamlit import util
util.open_browser("https://docs.streamlit.io") | Show help in browser. |
178,474 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
def _main_run(
file,
args: list[str] | None = None,
flag_options: dict[str, Any] | None = None,
) -> None:
if args is None:
args = []
if flag_options is None:
flag_options = {}
is_hello = _get_command_line_as_string() == "streamlit hello"
check_credentials()
bootstrap.run(file, is_hello, args, flag_options)
The provided code snippet includes necessary dependencies for implementing the `main_hello` function. Write a Python function `def main_hello(**kwargs)` to solve the following problem:
Runs the Hello World script.
Here is the function:
def main_hello(**kwargs):
"""Runs the Hello World script."""
from streamlit.hello import Hello
bootstrap.load_config_options(flag_options=kwargs)
filename = Hello.__file__
_main_run(filename, flag_options=kwargs) | Runs the Hello World script. |
178,475 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
ACCEPTED_FILE_EXTENSIONS = ("py", "py3")
def _download_remote(main_script_path: str, url_path: str) -> None:
"""Fetch remote file at url_path to main_script_path"""
import requests
with open(main_script_path, "wb") as fp:
try:
resp = requests.get(url_path)
resp.raise_for_status()
fp.write(resp.content)
except requests.exceptions.RequestException as e:
raise click.BadParameter(f"Unable to fetch {url_path}.\n{e}")
def _main_run(
file,
args: list[str] | None = None,
flag_options: dict[str, Any] | None = None,
) -> None:
if args is None:
args = []
if flag_options is None:
flag_options = {}
is_hello = _get_command_line_as_string() == "streamlit hello"
check_credentials()
bootstrap.run(file, is_hello, args, flag_options)
class TemporaryDirectory:
"""Temporary directory context manager.
Creates a temporary directory that exists within the context manager scope.
It returns the path to the created directory.
Wrapper on top of tempfile.mkdtemp.
Parameters
----------
suffix : str or None
Suffix to the filename.
prefix : str or None
Prefix to the filename.
dir : str or None
Enclosing directory.
"""
def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
def __repr__(self) -> str:
return util.repr_(self)
def __enter__(self):
self._path = tempfile.mkdtemp(*self._args, **self._kwargs)
return self._path
def __exit__(self, exc_type, exc_value, exc_traceback):
shutil.rmtree(self._path)
The provided code snippet includes necessary dependencies for implementing the `main_run` function. Write a Python function `def main_run(target: str, args=None, **kwargs)` to solve the following problem:
Run a Python script, piping stderr to Streamlit. The script can be local or it can be an url. In the latter case, Streamlit will download the script to a temporary file and runs this file.
Here is the function:
def main_run(target: str, args=None, **kwargs):
"""Run a Python script, piping stderr to Streamlit.
The script can be local or it can be an url. In the latter case, Streamlit
will download the script to a temporary file and runs this file.
"""
from streamlit import url_util
bootstrap.load_config_options(flag_options=kwargs)
_, extension = os.path.splitext(target)
if extension[1:] not in ACCEPTED_FILE_EXTENSIONS:
if extension[1:] == "":
raise click.BadArgumentUsage(
"Streamlit requires raw Python (.py) files, but the provided file has no extension.\nFor more information, please see https://docs.streamlit.io"
)
else:
raise click.BadArgumentUsage(
f"Streamlit requires raw Python (.py) files, not {extension}.\nFor more information, please see https://docs.streamlit.io"
)
if url_util.is_url(target):
from streamlit.temporary_directory import TemporaryDirectory
with TemporaryDirectory() as temp_dir:
from urllib.parse import urlparse
path = urlparse(target).path
main_script_path = os.path.join(
temp_dir, path.strip("/").rsplit("/", 1)[-1]
)
# if this is a GitHub/Gist blob url, convert to a raw URL first.
target = url_util.process_gitblob_url(target)
_download_remote(main_script_path, target)
_main_run(main_script_path, args, flag_options=kwargs)
else:
if not os.path.exists(target):
raise click.BadParameter(f"File does not exist: {target}")
_main_run(target, args, flag_options=kwargs) | Run a Python script, piping stderr to Streamlit. The script can be local or it can be an url. In the latter case, Streamlit will download the script to a temporary file and runs this file. |
178,476 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
The provided code snippet includes necessary dependencies for implementing the `cache` function. Write a Python function `def cache()` to solve the following problem:
Manage the Streamlit cache.
Here is the function:
def cache():
"""Manage the Streamlit cache."""
pass | Manage the Streamlit cache. |
178,477 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
def create_default_cache_storage_manager() -> CacheStorageManager:
"""
Get the cache storage manager.
It would be used both in server.py and in cli.py to have unified cache storage
Returns
-------
CacheStorageManager
The cache storage manager.
"""
return LocalDiskCacheStorageManager()
The provided code snippet includes necessary dependencies for implementing the `cache_clear` function. Write a Python function `def cache_clear()` to solve the following problem:
Clear st.cache, st.cache_data, and st.cache_resource caches.
Here is the function:
def cache_clear():
"""Clear st.cache, st.cache_data, and st.cache_resource caches."""
result = legacy_caching.clear_cache()
cache_path = legacy_caching.get_cache_path()
if result:
print(f"Cleared directory {cache_path}.")
else:
print(f"Nothing to clear at {cache_path}.")
# in this `streamlit cache clear` cli command we cannot use the
# `cache_storage_manager from runtime (since runtime is not initialized)
# so we create a new cache_storage_manager instance that used in runtime,
# and call clear_all() method for it.
# This will not remove the in-memory cache.
cache_storage_manager = create_default_cache_storage_manager()
cache_storage_manager.clear_all()
caching.cache_resource.clear() | Clear st.cache, st.cache_data, and st.cache_resource caches. |
178,478 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
The provided code snippet includes necessary dependencies for implementing the `config` function. Write a Python function `def config()` to solve the following problem:
Manage Streamlit's config settings.
Here is the function:
def config():
"""Manage Streamlit's config settings."""
pass | Manage Streamlit's config settings. |
178,479 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
The provided code snippet includes necessary dependencies for implementing the `config_show` function. Write a Python function `def config_show(**kwargs)` to solve the following problem:
Show all of Streamlit's config settings.
Here is the function:
def config_show(**kwargs):
"""Show all of Streamlit's config settings."""
bootstrap.load_config_options(flag_options=kwargs)
_config.show_config() | Show all of Streamlit's config settings. |
178,480 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
class Credentials(object):
"""Credentials class."""
_singleton: "Credentials" | None = None
def get_current(cls):
"""Return the singleton instance."""
if cls._singleton is None:
Credentials()
return Credentials._singleton
def __init__(self):
"""Initialize class."""
if Credentials._singleton is not None:
raise RuntimeError(
"Credentials already initialized. Use .get_current() instead"
)
self.activation = None
self._conf_file = _get_credential_file_path()
Credentials._singleton = self
def __repr__(self) -> str:
return util.repr_(self)
def load(self, auto_resolve: bool = False) -> None:
"""Load from toml file."""
if self.activation is not None:
_LOGGER.error("Credentials already loaded. Not rereading file.")
return
import toml
try:
with open(self._conf_file, "r") as f:
data = toml.load(f).get("general")
if data is None:
raise Exception
self.activation = _verify_email(data.get("email"))
except FileNotFoundError:
if auto_resolve:
self.activate(show_instructions=not auto_resolve)
return
raise RuntimeError(
'Credentials not found. Please run "streamlit activate".'
)
except Exception:
if auto_resolve:
self.reset()
self.activate(show_instructions=not auto_resolve)
return
raise Exception(
textwrap.dedent(
"""
Unable to load credentials from %s.
Run "streamlit reset" and try again.
"""
)
% (self._conf_file)
)
def _check_activated(self, auto_resolve: bool = True) -> None:
"""Check if streamlit is activated.
Used by `streamlit run script.py`
"""
try:
self.load(auto_resolve)
except (Exception, RuntimeError) as e:
_exit(str(e))
if self.activation is None or not self.activation.is_valid:
_exit("Activation email not valid.")
def reset(cls) -> None:
"""Reset credentials by removing file.
This is used by `streamlit activate reset` in case a user wants
to start over.
"""
c = Credentials.get_current()
c.activation = None
try:
os.remove(c._conf_file)
except OSError as e:
_LOGGER.error("Error removing credentials file: %s" % e)
def save(self) -> None:
"""Save to toml file and send email."""
from requests.exceptions import RequestException
if self.activation is None:
return
# Create intermediate directories if necessary
os.makedirs(os.path.dirname(self._conf_file), exist_ok=True)
# Write the file
data = {"email": self.activation.email}
import toml
with open(self._conf_file, "w") as f:
toml.dump({"general": data}, f)
try:
_send_email(self.activation.email)
except RequestException as e:
_LOGGER.error(f"Error saving email: {e}")
def activate(self, show_instructions: bool = True) -> None:
"""Activate Streamlit.
Used by `streamlit activate`.
"""
try:
self.load()
except RuntimeError:
# Runtime Error is raised if credentials file is not found. In that case,
# `self.activation` is None and we will show the activation prompt below.
pass
if self.activation:
if self.activation.is_valid:
_exit("Already activated")
else:
_exit(
"Activation not valid. Please run "
"`streamlit activate reset` then `streamlit activate`"
)
else:
activated = False
while not activated:
import click
email = click.prompt(
text=email_prompt(),
prompt_suffix="",
default="",
show_default=False,
)
self.activation = _verify_email(email)
if self.activation.is_valid:
self.save()
# IMPORTANT: Break the text below at 80 chars.
TELEMETRY_TEXT = """
You can find our privacy policy at %(link)s
Summary:
- This open source library collects usage statistics.
- We cannot see and do not store information contained inside Streamlit apps,
such as text, charts, images, etc.
- Telemetry data is stored in servers in the United States.
- If you'd like to opt out, add the following to %(config)s,
creating that file if necessary:
[browser]
gatherUsageStats = false
""" % {
"link": cli_util.style_for_cli(
"https://streamlit.io/privacy-policy", underline=True
),
"config": cli_util.style_for_cli(_CONFIG_FILE_PATH),
}
cli_util.print_to_cli(TELEMETRY_TEXT)
if show_instructions:
# IMPORTANT: Break the text below at 80 chars.
INSTRUCTIONS_TEXT = """
%(start)s
%(prompt)s %(hello)s
""" % {
"start": cli_util.style_for_cli(
"Get started by typing:", fg="blue", bold=True
),
"prompt": cli_util.style_for_cli("$", fg="blue"),
"hello": cli_util.style_for_cli(
"streamlit hello", bold=True
),
}
cli_util.print_to_cli(INSTRUCTIONS_TEXT)
activated = True
else: # pragma: nocover
_LOGGER.error("Please try again.")
The provided code snippet includes necessary dependencies for implementing the `activate` function. Write a Python function `def activate(ctx)` to solve the following problem:
Activate Streamlit by entering your email.
Here is the function:
def activate(ctx):
"""Activate Streamlit by entering your email."""
if not ctx.invoked_subcommand:
Credentials.get_current().activate() | Activate Streamlit by entering your email. |
178,481 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
class Credentials(object):
"""Credentials class."""
_singleton: "Credentials" | None = None
def get_current(cls):
"""Return the singleton instance."""
if cls._singleton is None:
Credentials()
return Credentials._singleton
def __init__(self):
"""Initialize class."""
if Credentials._singleton is not None:
raise RuntimeError(
"Credentials already initialized. Use .get_current() instead"
)
self.activation = None
self._conf_file = _get_credential_file_path()
Credentials._singleton = self
def __repr__(self) -> str:
return util.repr_(self)
def load(self, auto_resolve: bool = False) -> None:
"""Load from toml file."""
if self.activation is not None:
_LOGGER.error("Credentials already loaded. Not rereading file.")
return
import toml
try:
with open(self._conf_file, "r") as f:
data = toml.load(f).get("general")
if data is None:
raise Exception
self.activation = _verify_email(data.get("email"))
except FileNotFoundError:
if auto_resolve:
self.activate(show_instructions=not auto_resolve)
return
raise RuntimeError(
'Credentials not found. Please run "streamlit activate".'
)
except Exception:
if auto_resolve:
self.reset()
self.activate(show_instructions=not auto_resolve)
return
raise Exception(
textwrap.dedent(
"""
Unable to load credentials from %s.
Run "streamlit reset" and try again.
"""
)
% (self._conf_file)
)
def _check_activated(self, auto_resolve: bool = True) -> None:
"""Check if streamlit is activated.
Used by `streamlit run script.py`
"""
try:
self.load(auto_resolve)
except (Exception, RuntimeError) as e:
_exit(str(e))
if self.activation is None or not self.activation.is_valid:
_exit("Activation email not valid.")
def reset(cls) -> None:
"""Reset credentials by removing file.
This is used by `streamlit activate reset` in case a user wants
to start over.
"""
c = Credentials.get_current()
c.activation = None
try:
os.remove(c._conf_file)
except OSError as e:
_LOGGER.error("Error removing credentials file: %s" % e)
def save(self) -> None:
"""Save to toml file and send email."""
from requests.exceptions import RequestException
if self.activation is None:
return
# Create intermediate directories if necessary
os.makedirs(os.path.dirname(self._conf_file), exist_ok=True)
# Write the file
data = {"email": self.activation.email}
import toml
with open(self._conf_file, "w") as f:
toml.dump({"general": data}, f)
try:
_send_email(self.activation.email)
except RequestException as e:
_LOGGER.error(f"Error saving email: {e}")
def activate(self, show_instructions: bool = True) -> None:
"""Activate Streamlit.
Used by `streamlit activate`.
"""
try:
self.load()
except RuntimeError:
# Runtime Error is raised if credentials file is not found. In that case,
# `self.activation` is None and we will show the activation prompt below.
pass
if self.activation:
if self.activation.is_valid:
_exit("Already activated")
else:
_exit(
"Activation not valid. Please run "
"`streamlit activate reset` then `streamlit activate`"
)
else:
activated = False
while not activated:
import click
email = click.prompt(
text=email_prompt(),
prompt_suffix="",
default="",
show_default=False,
)
self.activation = _verify_email(email)
if self.activation.is_valid:
self.save()
# IMPORTANT: Break the text below at 80 chars.
TELEMETRY_TEXT = """
You can find our privacy policy at %(link)s
Summary:
- This open source library collects usage statistics.
- We cannot see and do not store information contained inside Streamlit apps,
such as text, charts, images, etc.
- Telemetry data is stored in servers in the United States.
- If you'd like to opt out, add the following to %(config)s,
creating that file if necessary:
[browser]
gatherUsageStats = false
""" % {
"link": cli_util.style_for_cli(
"https://streamlit.io/privacy-policy", underline=True
),
"config": cli_util.style_for_cli(_CONFIG_FILE_PATH),
}
cli_util.print_to_cli(TELEMETRY_TEXT)
if show_instructions:
# IMPORTANT: Break the text below at 80 chars.
INSTRUCTIONS_TEXT = """
%(start)s
%(prompt)s %(hello)s
""" % {
"start": cli_util.style_for_cli(
"Get started by typing:", fg="blue", bold=True
),
"prompt": cli_util.style_for_cli("$", fg="blue"),
"hello": cli_util.style_for_cli(
"streamlit hello", bold=True
),
}
cli_util.print_to_cli(INSTRUCTIONS_TEXT)
activated = True
else: # pragma: nocover
_LOGGER.error("Please try again.")
The provided code snippet includes necessary dependencies for implementing the `activate_reset` function. Write a Python function `def activate_reset()` to solve the following problem:
Reset Activation Credentials.
Here is the function:
def activate_reset():
"""Reset Activation Credentials."""
Credentials.get_current().reset() | Reset Activation Credentials. |
178,482 | from __future__ import annotations
import os
import sys
from typing import Any
import click
import streamlit.runtime.caching as caching
import streamlit.runtime.legacy_caching as legacy_caching
import streamlit.web.bootstrap as bootstrap
from streamlit import config as _config
from streamlit.config_option import ConfigOption
from streamlit.runtime.credentials import Credentials, check_credentials
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
def _get_command_line_as_string() -> str | None:
import subprocess
parent = click.get_current_context().parent
if parent is None:
return None
if "streamlit.cli" in parent.command_path:
raise RuntimeError(
"Running streamlit via `python -m streamlit.cli <command>` is"
" unsupported. Please use `python -m streamlit <command>` instead."
)
cmd_line_as_list = [parent.command_path]
cmd_line_as_list.extend(sys.argv[1:])
return subprocess.list2cmdline(cmd_line_as_list)
The provided code snippet includes necessary dependencies for implementing the `test_prog_name` function. Write a Python function `def test_prog_name()` to solve the following problem:
Assert that the program name is set to `streamlit test`. This is used by our cli-smoke-tests to verify that the program name is set to `streamlit ...` whether the streamlit binary is invoked directly or via `python -m streamlit ...`.
Here is the function:
def test_prog_name():
"""Assert that the program name is set to `streamlit test`.
This is used by our cli-smoke-tests to verify that the program name is set
to `streamlit ...` whether the streamlit binary is invoked directly or via
`python -m streamlit ...`.
"""
# We use _get_command_line_as_string to run some error checks but don't do
# anything with its return value.
_get_command_line_as_string()
parent = click.get_current_context().parent
assert parent is not None
assert parent.command_path == "streamlit test" | Assert that the program name is set to `streamlit test`. This is used by our cli-smoke-tests to verify that the program name is set to `streamlit ...` whether the streamlit binary is invoked directly or via `python -m streamlit ...`. |
178,483 | from __future__ import annotations
import os
from typing import Final
import tornado.web
from streamlit import config, file_util
from streamlit.logger import get_logger
from streamlit.runtime.runtime_util import serialize_forward_msg
from streamlit.web.server.server_util import emit_endpoint_deprecation_notice
The provided code snippet includes necessary dependencies for implementing the `allow_cross_origin_requests` function. Write a Python function `def allow_cross_origin_requests() -> bool` to solve the following problem:
True if cross-origin requests are allowed. We only allow cross-origin requests when CORS protection has been disabled with server.enableCORS=False or if using the Node server. When using the Node server, we have a dev and prod port, which count as two origins.
Here is the function:
def allow_cross_origin_requests() -> bool:
"""True if cross-origin requests are allowed.
We only allow cross-origin requests when CORS protection has been disabled
with server.enableCORS=False or if using the Node server. When using the
Node server, we have a dev and prod port, which count as two origins.
"""
return not config.get_option("server.enableCORS") or config.get_option(
"global.developmentMode"
) | True if cross-origin requests are allowed. We only allow cross-origin requests when CORS protection has been disabled with server.enableCORS=False or if using the Node server. When using the Node server, we have a dev and prod port, which count as two origins. |
178,484 | from __future__ import annotations
from typing import Final
from urllib.parse import urljoin
import tornado.web
from streamlit import config, net_util, url_util
def _get_server_address_if_manually_set() -> str | None:
if config.is_manually_set("browser.serverAddress"):
return url_util.get_hostname(config.get_option("browser.serverAddress"))
return None
The provided code snippet includes necessary dependencies for implementing the `is_url_from_allowed_origins` function. Write a Python function `def is_url_from_allowed_origins(url: str) -> bool` to solve the following problem:
Return True if URL is from allowed origins (for CORS purpose). Allowed origins: 1. localhost 2. The internal and external IP addresses of the machine where this function was called from. If `server.enableCORS` is False, this allows all origins.
Here is the function:
def is_url_from_allowed_origins(url: str) -> bool:
"""Return True if URL is from allowed origins (for CORS purpose).
Allowed origins:
1. localhost
2. The internal and external IP addresses of the machine where this
function was called from.
If `server.enableCORS` is False, this allows all origins.
"""
if not config.get_option("server.enableCORS"):
# Allow everything when CORS is disabled.
return True
hostname = url_util.get_hostname(url)
allowed_domains = [ # List[Union[str, Callable[[], Optional[str]]]]
# Check localhost first.
"localhost",
"0.0.0.0",
"127.0.0.1",
# Try to avoid making unnecessary HTTP requests by checking if the user
# manually specified a server address.
_get_server_address_if_manually_set,
# Then try the options that depend on HTTP requests or opening sockets.
net_util.get_internal_ip,
net_util.get_external_ip,
]
for allowed_domain in allowed_domains:
if callable(allowed_domain):
allowed_domain = allowed_domain()
if allowed_domain is None:
continue
if hostname == allowed_domain:
return True
return False | Return True if URL is from allowed origins (for CORS purpose). Allowed origins: 1. localhost 2. The internal and external IP addresses of the machine where this function was called from. If `server.enableCORS` is False, this allows all origins. |
178,485 | from __future__ import annotations
from typing import Final
from urllib.parse import urljoin
import tornado.web
from streamlit import config, net_util, url_util
The provided code snippet includes necessary dependencies for implementing the `make_url_path_regex` function. Write a Python function `def make_url_path_regex(*path, **kwargs) -> str` to solve the following problem:
Get a regex of the form ^/foo/bar/baz/?$ for a path (foo, bar, baz).
Here is the function:
def make_url_path_regex(*path, **kwargs) -> str:
"""Get a regex of the form ^/foo/bar/baz/?$ for a path (foo, bar, baz)."""
path = [x.strip("/") for x in path if x] # Filter out falsely components.
path_format = r"^/%s/?$" if kwargs.get("trailing_slash", True) else r"^/%s$"
return path_format % "/".join(path) | Get a regex of the form ^/foo/bar/baz/?$ for a path (foo, bar, baz). |
178,486 | from __future__ import annotations
from typing import Final
from urllib.parse import urljoin
import tornado.web
from streamlit import config, net_util, url_util
The provided code snippet includes necessary dependencies for implementing the `emit_endpoint_deprecation_notice` function. Write a Python function `def emit_endpoint_deprecation_notice( handler: tornado.web.RequestHandler, new_path: str ) -> None` to solve the following problem:
Emits the warning about deprecation of HTTP endpoint in the HTTP header.
Here is the function:
def emit_endpoint_deprecation_notice(
handler: tornado.web.RequestHandler, new_path: str
) -> None:
"""
Emits the warning about deprecation of HTTP endpoint in the HTTP header.
"""
handler.set_header("Deprecation", True)
new_url = urljoin(f"{handler.request.protocol}://{handler.request.host}", new_path)
handler.set_header("Link", f'<{new_url}>; rel="alternate"') | Emits the warning about deprecation of HTTP endpoint in the HTTP header. |
178,487 | from __future__ import annotations
import errno
import logging
import os
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any, Awaitable, Final
import tornado.concurrent
import tornado.locks
import tornado.netutil
import tornado.web
import tornado.websocket
from tornado.httpserver import HTTPServer
from streamlit import cli_util, config, file_util, source_util, util
from streamlit.config_option import ConfigOption
from streamlit.logger import get_logger
from streamlit.runtime import Runtime, RuntimeConfig, RuntimeState
from streamlit.runtime.memory_media_file_storage import MemoryMediaFileStorage
from streamlit.runtime.memory_uploaded_file_manager import MemoryUploadedFileManager
from streamlit.runtime.runtime_util import get_max_message_size_bytes
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
from streamlit.web.server.app_static_file_handler import AppStaticFileHandler
from streamlit.web.server.browser_websocket_handler import BrowserWebSocketHandler
from streamlit.web.server.component_request_handler import ComponentRequestHandler
from streamlit.web.server.media_file_handler import MediaFileHandler
from streamlit.web.server.routes import (
AddSlashHandler,
HealthHandler,
HostConfigHandler,
MessageCacheHandler,
StaticFileHandler,
)
from streamlit.web.server.server_util import DEVELOPMENT_PORT, make_url_path_regex
from streamlit.web.server.stats_request_handler import StatsRequestHandler
from streamlit.web.server.upload_file_request_handler import UploadFileRequestHandler
def server_address_is_unix_socket() -> bool:
address = config.get_option("server.address")
return address is not None and address.startswith(UNIX_SOCKET_PREFIX)
def _get_ssl_options(cert_file: str | None, key_file: str | None) -> SSLContext | None:
if bool(cert_file) != bool(key_file):
_LOGGER.error(
"Options 'server.sslCertFile' and 'server.sslKeyFile' must "
"be set together. Set missing options or delete existing options."
)
sys.exit(1)
if cert_file and key_file:
# ssl_ctx.load_cert_chain raise exception as below, but it is not
# sufficiently user-friendly
# FileNotFoundError: [Errno 2] No such file or directory
if not Path(cert_file).exists():
_LOGGER.error("Cert file '%s' does not exist.", cert_file)
sys.exit(1)
if not Path(key_file).exists():
_LOGGER.error("Key file '%s' does not exist.", key_file)
sys.exit(1)
import ssl
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
# When the SSL certificate fails to load, an exception is raised as below,
# but it is not sufficiently user-friendly.
# ssl.SSLError: [SSL] PEM lib (_ssl.c:4067)
try:
ssl_ctx.load_cert_chain(cert_file, key_file)
except ssl.SSLError:
_LOGGER.error(
"Failed to load SSL certificate. Make sure "
"cert file '%s' and key file '%s' are correct.",
cert_file,
key_file,
)
sys.exit(1)
return ssl_ctx
return None
def start_listening_unix_socket(http_server: HTTPServer) -> None:
address = config.get_option("server.address")
file_name = os.path.expanduser(address[len(UNIX_SOCKET_PREFIX) :])
unix_socket = tornado.netutil.bind_unix_socket(file_name)
http_server.add_socket(unix_socket)
def start_listening_tcp_socket(http_server: HTTPServer) -> None:
call_count = 0
port = None
while call_count < MAX_PORT_SEARCH_RETRIES:
address = config.get_option("server.address")
port = config.get_option("server.port")
if int(port) == DEVELOPMENT_PORT:
_LOGGER.warning(
"Port %s is reserved for internal development. "
"It is strongly recommended to select an alternative port "
"for `server.port`.",
DEVELOPMENT_PORT,
)
try:
http_server.listen(port, address)
break # It worked! So let's break out of the loop.
except OSError as e:
if e.errno == errno.EADDRINUSE:
if server_port_is_manually_set():
_LOGGER.error("Port %s is already in use", port)
sys.exit(1)
else:
_LOGGER.debug(
"Port %s already in use, trying to use the next one.", port
)
port += 1
# Don't use the development port here:
if port == DEVELOPMENT_PORT:
port += 1
config.set_option(
"server.port", port, ConfigOption.STREAMLIT_DEFINITION
)
call_count += 1
else:
raise
if call_count >= MAX_PORT_SEARCH_RETRIES:
raise RetriesExceeded(
f"Cannot start Streamlit server. Port {port} is already in use, and "
f"Streamlit was unable to find a free port after {MAX_PORT_SEARCH_RETRIES} attempts.",
)
The provided code snippet includes necessary dependencies for implementing the `start_listening` function. Write a Python function `def start_listening(app: tornado.web.Application) -> None` to solve the following problem:
Makes the server start listening at the configured port. In case the port is already taken it tries listening to the next available port. It will error after MAX_PORT_SEARCH_RETRIES attempts.
Here is the function:
def start_listening(app: tornado.web.Application) -> None:
"""Makes the server start listening at the configured port.
In case the port is already taken it tries listening to the next available
port. It will error after MAX_PORT_SEARCH_RETRIES attempts.
"""
cert_file = config.get_option("server.sslCertFile")
key_file = config.get_option("server.sslKeyFile")
ssl_options = _get_ssl_options(cert_file, key_file)
http_server = HTTPServer(
app,
max_buffer_size=config.get_option("server.maxUploadSize") * 1024 * 1024,
ssl_options=ssl_options,
)
if server_address_is_unix_socket():
start_listening_unix_socket(http_server)
else:
start_listening_tcp_socket(http_server) | Makes the server start listening at the configured port. In case the port is already taken it tries listening to the next available port. It will error after MAX_PORT_SEARCH_RETRIES attempts. |
178,488 | from __future__ import annotations
import errno
import logging
import os
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any, Awaitable, Final
import tornado.concurrent
import tornado.locks
import tornado.netutil
import tornado.web
import tornado.websocket
from tornado.httpserver import HTTPServer
from streamlit import cli_util, config, file_util, source_util, util
from streamlit.config_option import ConfigOption
from streamlit.logger import get_logger
from streamlit.runtime import Runtime, RuntimeConfig, RuntimeState
from streamlit.runtime.memory_media_file_storage import MemoryMediaFileStorage
from streamlit.runtime.memory_uploaded_file_manager import MemoryUploadedFileManager
from streamlit.runtime.runtime_util import get_max_message_size_bytes
from streamlit.web.cache_storage_manager_config import (
create_default_cache_storage_manager,
)
from streamlit.web.server.app_static_file_handler import AppStaticFileHandler
from streamlit.web.server.browser_websocket_handler import BrowserWebSocketHandler
from streamlit.web.server.component_request_handler import ComponentRequestHandler
from streamlit.web.server.media_file_handler import MediaFileHandler
from streamlit.web.server.routes import (
AddSlashHandler,
HealthHandler,
HostConfigHandler,
MessageCacheHandler,
StaticFileHandler,
)
from streamlit.web.server.server_util import DEVELOPMENT_PORT, make_url_path_regex
from streamlit.web.server.stats_request_handler import StatsRequestHandler
from streamlit.web.server.upload_file_request_handler import UploadFileRequestHandler
def _set_tornado_log_levels() -> None:
if not config.get_option("global.developmentMode"):
# Hide logs unless they're super important.
# Example of stuff we don't care about: 404 about .js.map files.
logging.getLogger("tornado.access").setLevel(logging.ERROR)
logging.getLogger("tornado.application").setLevel(logging.ERROR)
logging.getLogger("tornado.general").setLevel(logging.ERROR) | null |
178,489 | from __future__ import annotations
from streamlit import runtime
from streamlit.runtime.metrics_util import gather_metrics
from streamlit.runtime.scriptrunner import get_script_run_ctx
from streamlit.web.server.browser_websocket_handler import BrowserWebSocketHandler
class BrowserWebSocketHandler(WebSocketHandler, SessionClient):
"""Handles a WebSocket connection from the browser"""
def initialize(self, runtime: Runtime) -> None:
self._runtime = runtime
self._session_id: str | None = None
# The XSRF cookie is normally set when xsrf_form_html is used, but in a
# pure-Javascript application that does not use any regular forms we just
# need to read the self.xsrf_token manually to set the cookie as a side
# effect. See https://www.tornadoweb.org/en/stable/guide/security.html#cross-site-request-forgery-protection
# for more details.
if config.get_option("server.enableXsrfProtection"):
_ = self.xsrf_token
def check_origin(self, origin: str) -> bool:
"""Set up CORS."""
return super().check_origin(origin) or is_url_from_allowed_origins(origin)
def write_forward_msg(self, msg: ForwardMsg) -> None:
"""Send a ForwardMsg to the browser."""
try:
self.write_message(serialize_forward_msg(msg), binary=True)
except tornado.websocket.WebSocketClosedError as e:
raise SessionClientDisconnectedError from e
def select_subprotocol(self, subprotocols: list[str]) -> str | None:
"""Return the first subprotocol in the given list.
This method is used by Tornado to select a protocol when the
Sec-WebSocket-Protocol header is set in an HTTP Upgrade request.
NOTE: We repurpose the Sec-WebSocket-Protocol header here in a slightly
unfortunate (but necessary) way. The browser WebSocket API doesn't allow us to
set arbitrary HTTP headers, and this header is the only one where we have the
ability to set it to arbitrary values, so we use it to pass tokens (in this
case, the previous session ID to allow us to reconnect to it) from client to
server as the *third* value in the list.
The reason why the auth token is set as the third value is that:
* when Sec-WebSocket-Protocol is set, many clients expect the server to
respond with a selected subprotocol to use. We don't want that reply to be
the session token, so we by convention have the client always set the first
protocol to "streamlit" and select that.
* the second protocol in the list is reserved in some deployment environments
for an auth token that we currently don't use
"""
if subprotocols:
return subprotocols[0]
return None
def open(self, *args, **kwargs) -> Awaitable[None] | None:
# Extract user info from the X-Streamlit-User header
is_public_cloud_app = False
try:
header_content = self.request.headers["X-Streamlit-User"]
payload = base64.b64decode(header_content)
user_obj = json.loads(payload)
email = user_obj["email"]
is_public_cloud_app = user_obj["isPublicCloudApp"]
except (KeyError, binascii.Error, json.decoder.JSONDecodeError):
email = "test@example.com"
user_info: dict[str, str | None] = dict()
if is_public_cloud_app:
user_info["email"] = None
else:
user_info["email"] = email
existing_session_id = None
try:
ws_protocols = [
p.strip()
for p in self.request.headers["Sec-Websocket-Protocol"].split(",")
]
if len(ws_protocols) >= 3:
# See the NOTE in the docstring of the `select_subprotocol` method above
# for a detailed explanation of why this is done.
existing_session_id = ws_protocols[2]
except KeyError:
# Just let existing_session_id=None if we run into any error while trying to
# extract it from the Sec-Websocket-Protocol header.
pass
self._session_id = self._runtime.connect_session(
client=self,
user_info=user_info,
existing_session_id=existing_session_id,
)
return None
def on_close(self) -> None:
if not self._session_id:
return
self._runtime.disconnect_session(self._session_id)
self._session_id = None
def get_compression_options(self) -> dict[Any, Any] | None:
"""Enable WebSocket compression.
Returning an empty dict enables websocket compression. Returning
None disables it.
(See the docstring in the parent class.)
"""
if config.get_option("server.enableWebsocketCompression"):
return {}
return None
def on_message(self, payload: str | bytes) -> None:
if not self._session_id:
return
try:
if isinstance(payload, str):
# Sanity check. (The frontend should only be sending us bytes;
# Protobuf.ParseFromString does not accept str input.)
raise RuntimeError(
"WebSocket received an unexpected `str` message. "
"(We expect `bytes` only.)"
)
msg = BackMsg()
msg.ParseFromString(payload)
_LOGGER.debug("Received the following back message:\n%s", msg)
except Exception as ex:
_LOGGER.error(ex)
self._runtime.handle_backmsg_deserialization_exception(self._session_id, ex)
return
# "debug_disconnect_websocket" and "debug_shutdown_runtime" are special
# developmentMode-only messages used in e2e tests to test reconnect handling and
# disabling widgets.
if msg.WhichOneof("type") == "debug_disconnect_websocket":
if config.get_option("global.developmentMode"):
self.close()
else:
_LOGGER.warning(
"Client tried to disconnect websocket when not in development mode."
)
elif msg.WhichOneof("type") == "debug_shutdown_runtime":
if config.get_option("global.developmentMode"):
self._runtime.stop()
else:
_LOGGER.warning(
"Client tried to shut down runtime when not in development mode."
)
else:
# AppSession handles all other BackMsg types.
self._runtime.handle_backmsg(self._session_id, msg)
The provided code snippet includes necessary dependencies for implementing the `_get_websocket_headers` function. Write a Python function `def _get_websocket_headers() -> dict[str, str] | None` to solve the following problem:
Return a copy of the HTTP request headers for the current session's WebSocket connection. If there's no active session, return None instead. Raise an error if the server is not running. Note to the intrepid: this is an UNSUPPORTED, INTERNAL API. (We don't have plans to remove it without a replacement, but we don't consider this a production-ready function, and its signature may change without a deprecation warning.)
Here is the function:
def _get_websocket_headers() -> dict[str, str] | None:
"""Return a copy of the HTTP request headers for the current session's
WebSocket connection. If there's no active session, return None instead.
Raise an error if the server is not running.
Note to the intrepid: this is an UNSUPPORTED, INTERNAL API. (We don't have plans
to remove it without a replacement, but we don't consider this a production-ready
function, and its signature may change without a deprecation warning.)
"""
ctx = get_script_run_ctx()
if ctx is None:
return None
session_client = runtime.get_instance().get_client(ctx.session_id)
if session_client is None:
return None
if not isinstance(session_client, BrowserWebSocketHandler):
raise RuntimeError(
f"SessionClient is not a BrowserWebSocketHandler! ({session_client})"
)
return dict(session_client.request.headers) | Return a copy of the HTTP request headers for the current session's WebSocket connection. If there's no active session, return None instead. Raise an error if the server is not running. Note to the intrepid: this is an UNSUPPORTED, INTERNAL API. (We don't have plans to remove it without a replacement, but we don't consider this a production-ready function, and its signature may change without a deprecation warning.) |
178,490 | from __future__ import annotations
from typing import Any
from streamlit import util
from streamlit.runtime.scriptrunner import get_script_run_ctx
def make_delta_path(
root_container: int, parent_path: tuple[int, ...], index: int
) -> list[int]:
delta_path = [root_container]
delta_path.extend(parent_path)
delta_path.append(index)
return delta_path | null |
178,491 | from __future__ import annotations
from typing import Any
from streamlit import util
from streamlit.runtime.scriptrunner import get_script_run_ctx
class RunningCursor(Cursor):
def __init__(self, root_container: int, parent_path: tuple[int, ...] = ()):
"""A moving pointer to a delta location in the app.
RunningCursors auto-increment to the next available location when you
call get_locked_cursor() on them.
Parameters
----------
root_container: int
The root container this cursor lives in.
parent_path: tuple of ints
The full path of this cursor, consisting of the IDs of all ancestors.
The 0th item is the topmost ancestor.
"""
self._root_container = root_container
self._parent_path = parent_path
self._index = 0
def root_container(self) -> int:
return self._root_container
def parent_path(self) -> tuple[int, ...]:
return self._parent_path
def index(self) -> int:
return self._index
def is_locked(self) -> bool:
return False
def get_locked_cursor(self, **props) -> LockedCursor:
locked_cursor = LockedCursor(
root_container=self._root_container,
parent_path=self._parent_path,
index=self._index,
**props,
)
self._index += 1
return locked_cursor
The provided code snippet includes necessary dependencies for implementing the `get_container_cursor` function. Write a Python function `def get_container_cursor( root_container: int | None, ) -> RunningCursor | None` to solve the following problem:
Return the top-level RunningCursor for the given container. This is the cursor that is used when user code calls something like `st.foo` (which uses the main container) or `st.sidebar.foo` (which uses the sidebar container).
Here is the function:
def get_container_cursor(
root_container: int | None,
) -> RunningCursor | None:
"""Return the top-level RunningCursor for the given container.
This is the cursor that is used when user code calls something like
`st.foo` (which uses the main container) or `st.sidebar.foo` (which uses
the sidebar container).
"""
if root_container is None:
return None
ctx = get_script_run_ctx()
if ctx is None:
return None
if root_container in ctx.cursors:
return ctx.cursors[root_container]
cursor = RunningCursor(root_container=root_container)
ctx.cursors[root_container] = cursor
return cursor | Return the top-level RunningCursor for the given container. This is the cursor that is used when user code calls something like `st.foo` (which uses the main container) or `st.sidebar.foo` (which uses the sidebar container). |
178,492 | from __future__ import annotations
import os
from typing import Any, Collection, cast
The provided code snippet includes necessary dependencies for implementing the `extract_from_dict` function. Write a Python function `def extract_from_dict( keys: Collection[str], source_dict: dict[str, Any] ) -> dict[str, Any]` to solve the following problem:
Extract the specified keys from source_dict and return them in a new dict. Parameters ---------- keys : Collection[str] The keys to extract from source_dict. source_dict : Dict[str, Any] The dict to extract keys from. Note that this function mutates source_dict. Returns ------- Dict[str, Any] A new dict containing the keys/values extracted from source_dict.
Here is the function:
def extract_from_dict(
keys: Collection[str], source_dict: dict[str, Any]
) -> dict[str, Any]:
"""Extract the specified keys from source_dict and return them in a new dict.
Parameters
----------
keys : Collection[str]
The keys to extract from source_dict.
source_dict : Dict[str, Any]
The dict to extract keys from. Note that this function mutates source_dict.
Returns
-------
Dict[str, Any]
A new dict containing the keys/values extracted from source_dict.
"""
d = {}
for k in keys:
if k in source_dict:
d[k] = source_dict.pop(k)
return d | Extract the specified keys from source_dict and return them in a new dict. Parameters ---------- keys : Collection[str] The keys to extract from source_dict. source_dict : Dict[str, Any] The dict to extract keys from. Note that this function mutates source_dict. Returns ------- Dict[str, Any] A new dict containing the keys/values extracted from source_dict. |
178,493 | from __future__ import annotations
import os
from typing import Any, Collection, cast
SNOWSQL_CONNECTION_FILE = "~/.snowsql/config"
The provided code snippet includes necessary dependencies for implementing the `load_from_snowsql_config_file` function. Write a Python function `def load_from_snowsql_config_file(connection_name: str) -> dict[str, Any]` to solve the following problem:
Loads the dictionary from snowsql config file.
Here is the function:
def load_from_snowsql_config_file(connection_name: str) -> dict[str, Any]:
"""Loads the dictionary from snowsql config file."""
snowsql_config_file = os.path.expanduser(SNOWSQL_CONNECTION_FILE)
if not os.path.exists(snowsql_config_file):
return {}
# Lazy-load config parser for better import / startup performance
import configparser
config = configparser.ConfigParser(inline_comment_prefixes="#")
config.read(snowsql_config_file)
if f"connections.{connection_name}" in config:
raw_conn_params = config[f"connections.{connection_name}"]
elif "connections" in config:
raw_conn_params = config["connections"]
else:
return {}
conn_params = {
k.replace("name", ""): v.strip('"') for k, v in raw_conn_params.items()
}
if "db" in conn_params:
conn_params["database"] = conn_params["db"]
del conn_params["db"]
return conn_params | Loads the dictionary from snowsql config file. |
178,494 | from __future__ import annotations
import os
from typing import Any, Collection, cast
The provided code snippet includes necessary dependencies for implementing the `running_in_sis` function. Write a Python function `def running_in_sis() -> bool` to solve the following problem:
Return whether this app is running in SiS.
Here is the function:
def running_in_sis() -> bool:
"""Return whether this app is running in SiS."""
try:
from snowflake.snowpark._internal.utils import ( # type: ignore[import] # isort: skip
is_in_stored_procedure,
)
return cast(bool, is_in_stored_procedure())
except ModuleNotFoundError:
return False | Return whether this app is running in SiS. |
178,495 | from __future__ import annotations
import re
from streamlit import cli_util
from streamlit.config_option import ConfigOption
def _clean(txt: str) -> str:
"""Replace sequences of multiple spaces with a single space, excluding newlines.
Preserves leading and trailing spaces, and does not modify spaces in between lines.
"""
return re.sub(" +", " ", txt)
def _clean_paragraphs(txt: str) -> list[str]:
"""Split the text into paragraphs, preserve newlines within the paragraphs."""
# Strip both leading and trailing newlines.
txt = txt.strip("\n")
paragraphs = txt.split("\n\n")
cleaned_paragraphs = [
"\n".join(_clean(line) for line in paragraph.split("\n"))
for paragraph in paragraphs
]
return cleaned_paragraphs
class ConfigOption:
'''Stores a Streamlit configuration option.
A configuration option, like 'browser.serverPort', which indicates which port
to use when connecting to the proxy. There are two ways to create a
ConfigOption:
Simple ConfigOptions are created as follows:
ConfigOption('browser.serverPort',
description = 'Connect to the proxy at this port.',
default_val = 8501)
More complex config options resolve their values at runtime as follows:
def _proxy_port():
"""Connect to the proxy at this port.
Defaults to 8501.
"""
return 8501
NOTE: For complex config options, the function is called each time the
option.value is evaluated!
Attributes
----------
key : str
The fully qualified section.name
value : any
The value for this option. If this is a complex config option then
the callback is called EACH TIME value is evaluated.
section : str
The section of this option. Example: 'global'.
name : str
See __init__.
description : str
See __init__.
where_defined : str
Indicates which file set this config option.
ConfigOption.DEFAULT_DEFINITION means this file.
is_default: bool
True if the config value is equal to its default value.
visibility : {"visible", "hidden"}
See __init__.
scriptable : bool
See __init__.
deprecated: bool
See __init__.
deprecation_text : str or None
See __init__.
expiration_date : str or None
See __init__.
replaced_by : str or None
See __init__.
sensitive : bool
See __init__.
env_var: str
The name of the environment variable that can be used to set the option.
'''
# This is a special value for ConfigOption.where_defined which indicates
# that the option default was not overridden.
DEFAULT_DEFINITION = "<default>"
# This is a special value for ConfigOption.where_defined which indicates
# that the options was defined by Streamlit's own code.
STREAMLIT_DEFINITION = "<streamlit>"
def __init__(
self,
key: str,
description: str | None = None,
default_val: Any | None = None,
visibility: str = "visible",
scriptable: bool = False,
deprecated: bool = False,
deprecation_text: str | None = None,
expiration_date: str | None = None,
replaced_by: str | None = None,
type_: type = str,
sensitive: bool = False,
):
"""Create a ConfigOption with the given name.
Parameters
----------
key : str
Should be of the form "section.optionName"
Examples: server.name, deprecation.v1_0_featureName
description : str
Like a comment for the config option.
default_val : any
The value for this config option.
visibility : {"visible", "hidden"}
Whether this option should be shown to users.
scriptable : bool
Whether this config option can be set within a user script.
deprecated: bool
Whether this config option is deprecated.
deprecation_text : str or None
Required if deprecated == True. Set this to a string explaining
what to use instead.
expiration_date : str or None
Required if deprecated == True. set this to the date at which it
will no longer be accepted. Format: 'YYYY-MM-DD'.
replaced_by : str or None
If this is option has been deprecated in favor or another option,
set this to the path to the new option. Example:
'server.runOnSave'. If this is set, the 'deprecated' option
will automatically be set to True, and deprecation_text will have a
meaningful default (unless you override it).
type_ : one of str, int, float or bool
Useful to cast the config params sent by cmd option parameter.
sensitive: bool
Sensitive configuration options cannot be set by CLI parameter.
"""
# Parse out the section and name.
self.key = key
key_format = (
# Capture a group called "section"
r"(?P<section>"
# Matching text comprised of letters and numbers that begins
# with a lowercase letter with an optional "_" preceding it.
# Examples: "_section", "section1"
r"\_?[a-z][a-zA-Z0-9]*"
r")"
# Separator between groups
r"\."
# Capture a group called "name"
r"(?P<name>"
# Match text comprised of letters and numbers beginning with a
# lowercase letter.
# Examples: "name", "nameOfConfig", "config1"
r"[a-z][a-zA-Z0-9]*"
r")$"
)
match = re.match(key_format, self.key)
assert match, f'Key "{self.key}" has invalid format.'
self.section, self.name = match.group("section"), match.group("name")
self.description = description
self.visibility = visibility
self.scriptable = scriptable
self.default_val = default_val
self.deprecated = deprecated
self.replaced_by = replaced_by
self.is_default = True
self._get_val_func: Callable[[], Any] | None = None
self.where_defined = ConfigOption.DEFAULT_DEFINITION
self.type = type_
self.sensitive = sensitive
if self.replaced_by:
self.deprecated = True
if deprecation_text is None:
deprecation_text = "Replaced by %s." % self.replaced_by
if self.deprecated:
assert expiration_date, "expiration_date is required for deprecated items"
assert deprecation_text, "deprecation_text is required for deprecated items"
self.expiration_date = expiration_date
self.deprecation_text = textwrap.dedent(deprecation_text)
self.set_value(default_val)
def __repr__(self) -> str:
return util.repr_(self)
def __call__(self, get_val_func: Callable[[], Any]) -> ConfigOption:
"""Assign a function to compute the value for this option.
This method is called when ConfigOption is used as a decorator.
Parameters
----------
get_val_func : function
A function which will be called to get the value of this parameter.
We will use its docString as the description.
Returns
-------
ConfigOption
Returns self, which makes testing easier. See config_test.py.
"""
assert (
get_val_func.__doc__
), "Complex config options require doc strings for their description."
self.description = get_val_func.__doc__
self._get_val_func = get_val_func
return self
def value(self) -> Any:
"""Get the value of this config option."""
if self._get_val_func is None:
return None
return self._get_val_func()
def set_value(self, value: Any, where_defined: str | None = None) -> None:
"""Set the value of this option.
Parameters
----------
value
The new value for this parameter.
where_defined : str
New value to remember where this parameter was set.
"""
self._get_val_func = lambda: value
if where_defined is None:
self.where_defined = ConfigOption.DEFAULT_DEFINITION
else:
self.where_defined = where_defined
self.is_default = value == self.default_val
if self.deprecated and self.where_defined != ConfigOption.DEFAULT_DEFINITION:
details = {
"key": self.key,
"file": self.where_defined,
"explanation": self.deprecation_text,
"date": self.expiration_date,
}
if self.is_expired():
# Import here to avoid circular imports
from streamlit.logger import get_logger
LOGGER = get_logger(__name__)
LOGGER.error(
textwrap.dedent(
"""
════════════════════════════════════════════════
%(key)s IS NO LONGER SUPPORTED.
%(explanation)s
Please update %(file)s.
════════════════════════════════════════════════
"""
)
% details
)
else:
# Import here to avoid circular imports
from streamlit.logger import get_logger
LOGGER = get_logger(__name__)
LOGGER.warning(
textwrap.dedent(
"""
════════════════════════════════════════════════
%(key)s IS DEPRECATED.
%(explanation)s
This option will be removed on or after %(date)s.
Please update %(file)s.
════════════════════════════════════════════════
"""
)
% details
)
def is_expired(self) -> bool:
"""Returns true if expiration_date is in the past."""
if not self.deprecated:
return False
expiration_date = _parse_yyyymmdd_str(self.expiration_date)
now = datetime.datetime.now()
return now > expiration_date
def env_var(self):
"""
Get the name of the environment variable that can be used to set the option.
"""
name = self.key.replace(".", "_")
return f"STREAMLIT_{to_snake_case(name).upper()}"
The provided code snippet includes necessary dependencies for implementing the `show_config` function. Write a Python function `def show_config( section_descriptions: dict[str, str], config_options: dict[str, ConfigOption], ) -> None` to solve the following problem:
Print the given config sections/options to the terminal.
Here is the function:
def show_config(
section_descriptions: dict[str, str],
config_options: dict[str, ConfigOption],
) -> None:
"""Print the given config sections/options to the terminal."""
out = []
out.append(
_clean(
"""
# Below are all the sections and options you can have in
~/.streamlit/config.toml.
"""
)
)
def append_desc(text):
out.append("# " + cli_util.style_for_cli(text, bold=True))
def append_comment(text):
out.append("# " + cli_util.style_for_cli(text))
def append_section(text):
out.append(cli_util.style_for_cli(text, bold=True, fg="green"))
def append_setting(text):
out.append(cli_util.style_for_cli(text, fg="green"))
for section, _ in section_descriptions.items():
# We inject a fake config section used for unit tests that we exclude here as
# its options are often missing required properties, which confuses the code
# below.
if section == "_test":
continue
section_options = {
k: v
for k, v in config_options.items()
if v.section == section and v.visibility == "visible" and not v.is_expired()
}
# Only show config header if section is non-empty.
if len(section_options) == 0:
continue
out.append("")
append_section("[%s]" % section)
out.append("")
for key, option in section_options.items():
key = option.key.split(".")[1]
description_paragraphs = _clean_paragraphs(option.description or "")
last_paragraph_idx = len(description_paragraphs) - 1
for i, paragraph in enumerate(description_paragraphs):
# Split paragraph into lines
lines = paragraph.rstrip().split(
"\n"
) # Remove trailing newline characters
# If the first line is empty, remove it
if lines and not lines[0].strip():
lines = lines[1:]
# Choose function based on whether it's the first paragraph or not
append_func = append_desc if i == 0 else append_comment
# Add comment character to each line and add to out
for line in lines:
append_func(line.lstrip())
# # Add a line break after a paragraph only if it's not the last paragraph
if i != last_paragraph_idx:
out.append("")
import toml
toml_default = toml.dumps({"default": option.default_val})
toml_default = toml_default[10:].strip()
if len(toml_default) > 0:
# Ensure a line break before appending "Default" comment, if not already there
if out[-1] != "":
out.append("")
append_comment("Default: %s" % toml_default)
else:
# Don't say "Default: (unset)" here because this branch applies
# to complex config settings too.
pass
if option.deprecated:
append_comment(cli_util.style_for_cli("DEPRECATED.", fg="yellow"))
for line in _clean_paragraphs(option.deprecation_text):
append_comment(line)
append_comment(
"This option will be removed on or after %s."
% option.expiration_date
)
option_is_manually_set = (
option.where_defined != ConfigOption.DEFAULT_DEFINITION
)
if option_is_manually_set:
append_comment("The value below was set in %s" % option.where_defined)
toml_setting = toml.dumps({key: option.value})
if len(toml_setting) == 0:
toml_setting = f"# {key} =\n"
elif not option_is_manually_set:
toml_setting = f"# {toml_setting}"
append_setting(toml_setting)
cli_util.print_to_cli("\n".join(out)) | Print the given config sections/options to the terminal. |
178,496 | from __future__ import annotations
import datetime
import re
import textwrap
from typing import Any, Callable
from streamlit import util
from streamlit.case_converters import to_snake_case
def _parse_yyyymmdd_str(date_str: str) -> datetime.datetime:
year, month, day = (int(token) for token in date_str.split("-", 2))
return datetime.datetime(year, month, day) | null |
178,497 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
_z_P_L = "P" if _sizeof_Clong < _sizeof_Cvoidp else "L"
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_calcsize` function. Write a Python function `def _calcsize(fmt)` to solve the following problem:
Like struct.calcsize() but with 'z' for Py_ssize_t.
Here is the function:
def _calcsize(fmt):
"""Like struct.calcsize() but with 'z' for Py_ssize_t."""
return calcsize(fmt.replace("z", _z_P_L)) | Like struct.calcsize() but with 'z' for Py_ssize_t. |
178,498 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_keys` function. Write a Python function `def _keys(obj)` to solve the following problem:
Return iter-/generator, preferably.
Here is the function:
def _keys(obj): # dict only
"""Return iter-/generator, preferably."""
o = getattr(obj, "iterkeys", obj.keys)
return o() if callable(o) else (o or ()) | Return iter-/generator, preferably. |
178,499 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_isbuiltin2` function. Write a Python function `def _isbuiltin2(typ)` to solve the following problem:
Return True for built-in types as in Python 2.
Here is the function:
def _isbuiltin2(typ):
"""Return True for built-in types as in Python 2."""
# range is no longer a built-in in Python 3+
return isbuiltin(typ) or (typ is range) | Return True for built-in types as in Python 2. |
178,500 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
_NN = ""
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _len(obj):
"""Safe len()."""
try:
return len(obj)
except TypeError: # no len() nor __len__
return 0
from array import array as _array
def leng(obj, **opts):
"""Return the length of an object, in number of *items*.
See function **basicsize** for a description of the available options.
"""
n = t = _typedefof(obj, **opts)
if t:
n = t.leng
if n and callable(n):
i, v, n = t.item, t.vari, n(obj)
if v and i == _sizeof_Cbyte:
i = getattr(obj, v, i)
if i > _sizeof_Cbyte:
n = n // i
return n
The provided code snippet includes necessary dependencies for implementing the `_lengstr` function. Write a Python function `def _lengstr(obj)` to solve the following problem:
Object length as a string.
Here is the function:
def _lengstr(obj):
"""Object length as a string."""
n = leng(obj)
if n is None: # no len
r = _NN
else:
x = "!" if n > _len(obj) else _NN # extended
r = " leng %d%s" % (n, x)
return r | Object length as a string. |
178,501 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
t = hasattr(sys, "gettotalrefcount")
del t
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
t = (_kind_static, _kind_dynamic, _kind_derived, _kind_ignored, _kind_inferred) = (
i("static"),
i("dynamic"),
i("derived"),
i("ignored"),
i("inferred"),
)
from array import array as _array
for t in _values(_typedefs):
if t.type and t.leng:
try: # create an (empty) instance
s.append(t.type())
except TypeError:
pass
for t in s:
try:
i = iter(t)
_typedef_both(type(i), leng=_len_iter, refs=_iter_refs, item=0) # no itemsize!
except (KeyError, TypeError): # ignore non-iterables, duplicates, etc.
pass
The provided code snippet includes necessary dependencies for implementing the `_p100` function. Write a Python function `def _p100(part, total, prec=1)` to solve the following problem:
Return percentage as string.
Here is the function:
def _p100(part, total, prec=1):
"""Return percentage as string."""
t = float(total)
if t > 0:
p = part * 100.0 / t
r = "%.*f%%" % (prec, p)
else:
r = "n/a"
return r | Return percentage as string. |
178,502 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
_NN = ""
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _repr(obj, clip=80):
"""Clip long repr() string."""
try: # safe repr()
r = repr(obj).replace(linesep, "\\n")
except Exception:
r = "N/A"
if len(r) > clip > 0:
h = (clip // 2) - 2
if h > 0:
r = r[:h] + "...." + r[-h:]
return r
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_prepr` function. Write a Python function `def _prepr(obj, clip=0)` to solve the following problem:
Prettify and clip long repr() string.
Here is the function:
def _prepr(obj, clip=0):
"""Prettify and clip long repr() string."""
return _repr(obj, clip=clip).strip("<>").replace("'", _NN) # remove <''> | Prettify and clip long repr() string. |
178,503 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
if sys.platform == "ios": # Apple iOS
_gc_getobjects = _getobjects
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_printf` function. Write a Python function `def _printf(fmt, *args, **print3options)` to solve the following problem:
Formatted print to sys.stdout or given stream. *print3options* -- some keyword arguments, like Python 3+ print.
Here is the function:
def _printf(fmt, *args, **print3options):
"""Formatted print to sys.stdout or given stream.
*print3options* -- some keyword arguments, like Python 3+ print.
"""
if print3options: # like Python 3+
f = print3options.get("file", None) or sys.stdout
if args:
f.write(fmt % args)
else:
f.write(fmt)
f.write(print3options.get("end", linesep))
if print3options.get("flush", False):
f.flush()
elif args:
print(fmt % args)
else:
print(fmt) | Formatted print to sys.stdout or given stream. *print3options* -- some keyword arguments, like Python 3+ print. |
178,504 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _SI(size, K=1024, i="i"):
"""Return size as SI string."""
if 1 < K <= size:
f = float(size)
for si in iter("KMGPTE"):
f /= K
if f < K:
return " or %.1f %s%sB" % (f, si, i)
return _NN
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_SI2` function. Write a Python function `def _SI2(size, **kwds)` to solve the following problem:
Return size as regular plus SI string.
Here is the function:
def _SI2(size, **kwds):
"""Return size as regular plus SI string."""
return str(size) + _SI(size, **kwds) | Return size as regular plus SI string. |
178,505 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _refs(obj, named, *attrs, **kwds):
"""Return specific attribute objects of an object."""
if named:
_N = _NamedRef
else:
def _N(unused, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_enum_refs` function. Write a Python function `def _enum_refs(obj, named)` to solve the following problem:
Return specific referents of an enumerate object.
Here is the function:
def _enum_refs(obj, named):
"""Return specific referents of an enumerate object."""
return _refs(obj, named, "__doc__") | Return specific referents of an enumerate object. |
178,506 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _refs(obj, named, *attrs, **kwds):
"""Return specific attribute objects of an object."""
if named:
_N = _NamedRef
else:
def _N(unused, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_file_refs` function. Write a Python function `def _file_refs(obj, named)` to solve the following problem:
Return specific referents of a file object.
Here is the function:
def _file_refs(obj, named):
"""Return specific referents of a file object."""
return _refs(obj, named, "mode", "name") | Return specific referents of a file object. |
178,507 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _refs(obj, named, *attrs, **kwds):
"""Return specific attribute objects of an object."""
if named:
_N = _NamedRef
else:
def _N(unused, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_gen_refs` function. Write a Python function `def _gen_refs(obj, named)` to solve the following problem:
Return the referent(s) of a generator (expression) object.
Here is the function:
def _gen_refs(obj, named):
"""Return the referent(s) of a generator (expression) object."""
# only some gi_frame attrs, but none of
# the items to keep the generator intact
f = getattr(obj, "gi_frame", None)
return _refs(f, named, "f_locals", "f_code") | Return the referent(s) of a generator (expression) object. |
178,508 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _nameof(obj, dflt=_NN):
"""Return the name of an object."""
return getattr(obj, "__name__", dflt)
def _refs(obj, named, *attrs, **kwds):
"""Return specific attribute objects of an object."""
if named:
_N = _NamedRef
else:
def _N(unused, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_iter_refs` function. Write a Python function `def _iter_refs(obj, named)` to solve the following problem:
Return the referent(s) of an iterator object.
Here is the function:
def _iter_refs(obj, named):
"""Return the referent(s) of an iterator object."""
r = _getreferents(obj) # special case
return _refs(r, named, itor=_nameof(obj) or "iteref") | Return the referent(s) of an iterator object. |
178,509 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _refs(obj, named, *attrs, **kwds):
"""Return specific attribute objects of an object."""
if named:
_N = _NamedRef
else:
def _N(unused, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_prop_refs` function. Write a Python function `def _prop_refs(obj, named)` to solve the following problem:
Return specific referents of a property object.
Here is the function:
def _prop_refs(obj, named):
"""Return specific referents of a property object."""
return _refs(obj, named, "__doc__", pref="f") | Return specific referents of a property object. |
178,510 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_seq_refs` function. Write a Python function `def _seq_refs(obj, unused)` to solve the following problem:
Return specific referents of a frozen/set, list, tuple and xrange object.
Here is the function:
def _seq_refs(obj, unused): # named unused for PyChecker
"""Return specific referents of a frozen/set, list, tuple and xrange object."""
return obj # XXX for r in obj: yield r | Return specific referents of a frozen/set, list, tuple and xrange object. |
178,511 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _refs(obj, named, *attrs, **kwds):
"""Return specific attribute objects of an object."""
if named:
_N = _NamedRef
else:
def _N(unused, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_stat_refs` function. Write a Python function `def _stat_refs(obj, named)` to solve the following problem:
Return referents of a os.stat object.
Here is the function:
def _stat_refs(obj, named):
"""Return referents of a os.stat object."""
return _refs(obj, named, pref="st_") | Return referents of a os.stat object. |
178,512 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _refs(obj, named, *attrs, **kwds):
"""Return specific attribute objects of an object."""
if named:
_N = _NamedRef
else:
def _N(unused, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_statvfs_refs` function. Write a Python function `def _statvfs_refs(obj, named)` to solve the following problem:
Return referents of a os.statvfs object.
Here is the function:
def _statvfs_refs(obj, named):
"""Return referents of a os.statvfs object."""
return _refs(obj, named, pref="f_") | Return referents of a os.statvfs object. |
178,513 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _refs(obj, named, *attrs, **kwds):
"""Return specific attribute objects of an object."""
if named:
_N = _NamedRef
else:
def _N(unused, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_tb_refs` function. Write a Python function `def _tb_refs(obj, named)` to solve the following problem:
Return specific referents of a traceback object.
Here is the function:
def _tb_refs(obj, named):
"""Return specific referents of a traceback object."""
return _refs(obj, named, pref="tb_") | Return specific referents of a traceback object. |
178,514 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _refs(obj, named, *attrs, **kwds):
"""Return specific attribute objects of an object."""
if named:
_N = _NamedRef
else:
def _N(unused, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_type_refs` function. Write a Python function `def _type_refs(obj, named)` to solve the following problem:
Return specific referents of a type object.
Here is the function:
def _type_refs(obj, named):
"""Return specific referents of a type object."""
return _refs(
obj,
named,
"__doc__",
"__mro__",
"__name__",
"__slots__",
"__weakref__",
"__dict__",
) | Return specific referents of a type object. |
178,515 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_weak_refs` function. Write a Python function `def _weak_refs(obj, unused)` to solve the following problem:
Return weakly referent object.
Here is the function:
def _weak_refs(obj, unused): # unused for named
"""Return weakly referent object."""
try: # ignore 'key' of KeyedRef
return (obj(),)
except Exception: # XXX ReferenceError
return () | Return weakly referent object. |
178,516 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_len_bytearray` function. Write a Python function `def _len_bytearray(obj)` to solve the following problem:
Bytearray size.
Here is the function:
def _len_bytearray(obj):
"""Bytearray size."""
return obj.__alloc__() | Bytearray size. |
178,517 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _power_of_2(n):
"""Find the next power of 2."""
p2 = 2 ** int(log(n, 2))
while n > p2:
p2 += p2
return p2
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_len_dict` function. Write a Python function `def _len_dict(obj)` to solve the following problem:
Dict length in items (estimate).
Here is the function:
def _len_dict(obj):
"""Dict length in items (estimate)."""
n = len(obj) # active items
if n < 6: # ma_smalltable ...
n = 0 # ... in basicsize
else: # at least one unused
n = _power_of_2(n + 1)
return n | Dict length in items (estimate). |
178,518 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
_getsizeof = sys.getsizeof
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_len_int` function. Write a Python function `def _len_int(obj)` to solve the following problem:
Length of *int* (multi-precision, formerly long) in Cdigits.
Here is the function:
def _len_int(obj):
"""Length of *int* (multi-precision, formerly long) in Cdigits."""
n = _getsizeof(obj, 0) - int.__basicsize__
return (n // int.__itemsize__) if n > 0 else 0 | Length of *int* (multi-precision, formerly long) in Cdigits. |
178,519 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _len(obj):
"""Safe len()."""
try:
return len(obj)
except TypeError: # no len() nor __len__
return 0
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_len_iter` function. Write a Python function `def _len_iter(obj)` to solve the following problem:
Length (hint) of an iterator.
Here is the function:
def _len_iter(obj):
"""Length (hint) of an iterator."""
n = getattr(obj, "__length_hint__", None)
return n() if n and callable(n) else _len(obj) | Length (hint) of an iterator. |
178,520 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_len_list` function. Write a Python function `def _len_list(obj)` to solve the following problem:
Length of list (estimate).
Here is the function:
def _len_list(obj):
"""Length of list (estimate)."""
n = len(obj)
# estimate over-allocation
if n > 8:
n += 6 + (n >> 3)
elif n:
n += 4
return n | Length of list (estimate). |
178,521 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _power_of_2(n):
"""Find the next power of 2."""
p2 = 2 ** int(log(n, 2))
while n > p2:
p2 += p2
return p2
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_len_set` function. Write a Python function `def _len_set(obj)` to solve the following problem:
Length of frozen/set (estimate).
Here is the function:
def _len_set(obj):
"""Length of frozen/set (estimate)."""
n = len(obj)
if n > 8: # assume half filled
n = _power_of_2(n + n - 2)
elif n: # at least 8
n = 8
return n | Length of frozen/set (estimate). |
178,522 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_len_slice` function. Write a Python function `def _len_slice(obj)` to solve the following problem:
Slice length.
Here is the function:
def _len_slice(obj):
"""Slice length."""
try:
return (obj.stop - obj.start + 1) // obj.step
except (AttributeError, TypeError):
return 0 | Slice length. |
178,523 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_len_struct` function. Write a Python function `def _len_struct(obj)` to solve the following problem:
Struct length in bytes.
Here is the function:
def _len_struct(obj):
"""Struct length in bytes."""
try:
return obj.size
except AttributeError:
return 0 | Struct length in bytes. |
178,524 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
The provided code snippet includes necessary dependencies for implementing the `_len_unicode` function. Write a Python function `def _len_unicode(obj)` to solve the following problem:
Unicode size.
Here is the function:
def _len_unicode(obj):
"""Unicode size."""
return len(obj) + 1 | Unicode size. |
178,525 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
t = hasattr(sys, "gettotalrefcount")
del t
_Type_type = type(type)
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
_NoneNone = None, None
def _claskey(obj):
"""Wrap a class object."""
i = id(obj)
try:
k = _claskeys[i]
except KeyError:
_claskeys[i] = k = _Claskey(obj)
return k
t = (_kind_static, _kind_dynamic, _kind_derived, _kind_ignored, _kind_inferred) = (
i("static"),
i("dynamic"),
i("derived"),
i("ignored"),
i("inferred"),
)
from array import array as _array
try:
if type(bytes) is not type(str): # bytes is str in 2.6, bytes new in 2.6, 3.0
_typedef_both(bytes, item=_sizeof_Cbyte, leng=_len) # bytes new in 2.6, 3.0
except NameError: # missing
pass
for t in _values(_typedefs):
if t.type and t.leng:
try: # create an (empty) instance
s.append(t.type())
except TypeError:
pass
for t in s:
try:
i = iter(t)
_typedef_both(type(i), leng=_len_iter, refs=_iter_refs, item=0) # no itemsize!
except (KeyError, TypeError): # ignore non-iterables, duplicates, etc.
pass
The provided code snippet includes necessary dependencies for implementing the `_key2tuple` function. Write a Python function `def _key2tuple(obj)` to solve the following problem:
Return class and instance keys for a class.
Here is the function:
def _key2tuple(obj): # PYCHOK expected
"""Return class and instance keys for a class."""
t = type(obj) is _Type_type # isclass(obj):
return (_claskey(obj), obj) if t else _NoneNone | Return class and instance keys for a class. |
178,526 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
_Not_vari = _NN
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _basicsize(t, base=0, heap=False, obj=None):
"""Get non-zero basicsize of type,
including the header sizes.
"""
s = max(getattr(t, "__basicsize__", 0), base)
# include gc header size
if t != _Type_type:
h = getattr(t, "__flags__", 0) & _Py_TPFLAGS_HAVE_GC
elif heap: # type, allocated on heap
h = True
else: # None has no __flags__ attr
h = getattr(obj, "__flags__", 0) & _Py_TPFLAGS_HEAPTYPE
if h:
s += _sizeof_CPyGC_Head
# include reference counters
return s + _sizeof_Crefcounts
def _itemsize(t, item=0):
"""Get non-zero itemsize of type."""
# replace zero value with default
return getattr(t, "__itemsize__", 0) or item
class _Typedef(object):
"""Type definition class."""
base = 0 # basic size in bytes
both = None # both data and code if True, code only if False
item = 0 # item size in bytes
kind = None # _kind_... value
leng = None # _len_...() function or None
refs = None # _..._refs() function or None
type = None # original type
vari = None # item size attr name or _Not_vari
xtyp = None # if True, not _getsizeof'd
def __init__(self, **kwds):
self.reset(**kwds)
def __lt__(self, unused): # for Python 3+
return True
def __repr__(self):
return repr(self.args())
def __str__(self):
t = [str(self.base), str(self.item)]
for f in (self.leng, self.refs):
t.append(_nameof(f) or "n/a")
if not self.both:
t.append("(code only)")
return ", ".join(t)
def args(self): # as args tuple
"""Return all attributes as arguments tuple."""
return (
self.base,
self.item,
self.leng,
self.refs,
self.both,
self.kind,
self.type,
self.xtyp,
)
def dup(self, other=None, **kwds):
"""Duplicate attributes of dict or other typedef."""
t = other or _dict_typedef
d = t.kwds()
d.update(kwds)
self.reset(**d)
def flat(self, obj, mask=0):
"""Return the aligned flat size."""
s = self.base
if self.leng and self.item > 0: # include items
s += self.leng(obj) * self.item
# workaround sys.getsizeof bug for _array types
# (in some Python versions) and for other types
# with variable .itemsize like numpy.arrays, etc.
if not self.xtyp:
s = _getsizeof(obj, s)
if mask: # alignment mask
s = (s + mask) & ~mask
# if (mask + 1) & mask:
# raise _OptionError(self.flat, mask=mask)
return s
def format(self):
"""Return format dict."""
a = _nameof(self.leng)
return dict(
leng=((" (%s)" % (a,)) if a else _NN),
item="var" if self.vari else self.item,
code=_NN if self.both else " (code only)",
base=self.base,
kind=self.kind,
)
def kwds(self):
"""Return all attributes as keywords dict."""
return dict(
base=self.base,
both=self.both,
item=self.item,
kind=self.kind,
leng=self.leng,
refs=self.refs,
type=self.type,
vari=self.vari,
xtyp=self.xtyp,
)
def reset(
self,
base=0,
item=0,
leng=None,
refs=None,
both=True,
kind=None,
type=None,
vari=_Not_vari,
xtyp=False,
**extra,
):
"""Reset all specified typedef attributes."""
v = vari or _Not_vari
if v != str(v): # attr name
e = dict(vari=v)
elif base < 0:
e = dict(base=base)
elif both not in (False, True):
e = dict(both=both)
elif item < 0:
e = dict(item=item)
elif kind not in _all_kinds:
e = dict(kind=kind)
elif leng not in _all_lens: # XXX or not callable(leng)
e = dict(leng=leng)
elif refs not in _all_refs: # XXX or not callable(refs)
e = dict(refs=refs)
elif xtyp not in (False, True):
e = dict(xtyp=xtyp)
elif extra:
e = {}
else:
self.base = base
self.both = both
self.item = item
self.kind = kind
self.leng = leng
self.refs = refs
self.type = type # unchecked, as-is
self.vari = v
self.xtyp = xtyp
return
e.update(extra)
raise _OptionError(self.reset, **e)
def save(self, t, base=0, heap=False):
"""Save this typedef plus its class typedef."""
c, k = _key2tuple(t)
if k and k not in _typedefs: # instance key
_typedefs[k] = self
if c and c not in _typedefs: # class key
b = _basicsize(type(t), base=base, heap=heap)
k = _kind_ignored if _isignored(t) else self.kind
_typedefs[c] = _Typedef(
base=b, both=False, kind=k, type=t, refs=_type_refs
)
elif t not in _typedefs:
if not _isbuiltin2(t): # array, range, xrange in Python 2.x
s = " ".join((self.vari, _moduleof(t), _nameof(t)))
s = "%r %s %s" % ((c, k), self.both, s.strip())
raise KeyError("typedef %r bad: %s" % (self, s))
_typedefs[t] = _Typedef(
base=_basicsize(t, base=base), both=False, kind=_kind_ignored, type=t
)
def set(self, safe_len=False, **kwds):
"""Set one or more attributes."""
if kwds: # double check
d = self.kwds()
d.update(kwds)
self.reset(**d)
if safe_len and self.item:
self.leng = _len
from array import array as _array
try:
if type(bytes) is not type(str): # bytes is str in 2.6, bytes new in 2.6, 3.0
_typedef_both(bytes, item=_sizeof_Cbyte, leng=_len) # bytes new in 2.6, 3.0
except NameError: # missing
pass
The provided code snippet includes necessary dependencies for implementing the `_typedef_both` function. Write a Python function `def _typedef_both( t, base=0, item=0, leng=None, refs=None, kind=_kind_static, heap=False, vari=_Not_vari, )` to solve the following problem:
Add new typedef for both data and code.
Here is the function:
def _typedef_both(
t,
base=0,
item=0,
leng=None,
refs=None,
kind=_kind_static,
heap=False,
vari=_Not_vari,
):
"""Add new typedef for both data and code."""
v = _Typedef(
base=_basicsize(t, base=base),
item=_itemsize(t, item),
refs=refs,
leng=leng,
both=True,
kind=kind,
type=t,
vari=vari,
)
v.save(t, base=base, heap=heap)
return v # for _dict_typedef | Add new typedef for both data and code. |
178,527 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
def _basicsize(t, base=0, heap=False, obj=None):
"""Get non-zero basicsize of type,
including the header sizes.
"""
s = max(getattr(t, "__basicsize__", 0), base)
# include gc header size
if t != _Type_type:
h = getattr(t, "__flags__", 0) & _Py_TPFLAGS_HAVE_GC
elif heap: # type, allocated on heap
h = True
else: # None has no __flags__ attr
h = getattr(obj, "__flags__", 0) & _Py_TPFLAGS_HEAPTYPE
if h:
s += _sizeof_CPyGC_Head
# include reference counters
return s + _sizeof_Crefcounts
class _Typedef(object):
"""Type definition class."""
base = 0 # basic size in bytes
both = None # both data and code if True, code only if False
item = 0 # item size in bytes
kind = None # _kind_... value
leng = None # _len_...() function or None
refs = None # _..._refs() function or None
type = None # original type
vari = None # item size attr name or _Not_vari
xtyp = None # if True, not _getsizeof'd
def __init__(self, **kwds):
self.reset(**kwds)
def __lt__(self, unused): # for Python 3+
return True
def __repr__(self):
return repr(self.args())
def __str__(self):
t = [str(self.base), str(self.item)]
for f in (self.leng, self.refs):
t.append(_nameof(f) or "n/a")
if not self.both:
t.append("(code only)")
return ", ".join(t)
def args(self): # as args tuple
"""Return all attributes as arguments tuple."""
return (
self.base,
self.item,
self.leng,
self.refs,
self.both,
self.kind,
self.type,
self.xtyp,
)
def dup(self, other=None, **kwds):
"""Duplicate attributes of dict or other typedef."""
t = other or _dict_typedef
d = t.kwds()
d.update(kwds)
self.reset(**d)
def flat(self, obj, mask=0):
"""Return the aligned flat size."""
s = self.base
if self.leng and self.item > 0: # include items
s += self.leng(obj) * self.item
# workaround sys.getsizeof bug for _array types
# (in some Python versions) and for other types
# with variable .itemsize like numpy.arrays, etc.
if not self.xtyp:
s = _getsizeof(obj, s)
if mask: # alignment mask
s = (s + mask) & ~mask
# if (mask + 1) & mask:
# raise _OptionError(self.flat, mask=mask)
return s
def format(self):
"""Return format dict."""
a = _nameof(self.leng)
return dict(
leng=((" (%s)" % (a,)) if a else _NN),
item="var" if self.vari else self.item,
code=_NN if self.both else " (code only)",
base=self.base,
kind=self.kind,
)
def kwds(self):
"""Return all attributes as keywords dict."""
return dict(
base=self.base,
both=self.both,
item=self.item,
kind=self.kind,
leng=self.leng,
refs=self.refs,
type=self.type,
vari=self.vari,
xtyp=self.xtyp,
)
def reset(
self,
base=0,
item=0,
leng=None,
refs=None,
both=True,
kind=None,
type=None,
vari=_Not_vari,
xtyp=False,
**extra,
):
"""Reset all specified typedef attributes."""
v = vari or _Not_vari
if v != str(v): # attr name
e = dict(vari=v)
elif base < 0:
e = dict(base=base)
elif both not in (False, True):
e = dict(both=both)
elif item < 0:
e = dict(item=item)
elif kind not in _all_kinds:
e = dict(kind=kind)
elif leng not in _all_lens: # XXX or not callable(leng)
e = dict(leng=leng)
elif refs not in _all_refs: # XXX or not callable(refs)
e = dict(refs=refs)
elif xtyp not in (False, True):
e = dict(xtyp=xtyp)
elif extra:
e = {}
else:
self.base = base
self.both = both
self.item = item
self.kind = kind
self.leng = leng
self.refs = refs
self.type = type # unchecked, as-is
self.vari = v
self.xtyp = xtyp
return
e.update(extra)
raise _OptionError(self.reset, **e)
def save(self, t, base=0, heap=False):
"""Save this typedef plus its class typedef."""
c, k = _key2tuple(t)
if k and k not in _typedefs: # instance key
_typedefs[k] = self
if c and c not in _typedefs: # class key
b = _basicsize(type(t), base=base, heap=heap)
k = _kind_ignored if _isignored(t) else self.kind
_typedefs[c] = _Typedef(
base=b, both=False, kind=k, type=t, refs=_type_refs
)
elif t not in _typedefs:
if not _isbuiltin2(t): # array, range, xrange in Python 2.x
s = " ".join((self.vari, _moduleof(t), _nameof(t)))
s = "%r %s %s" % ((c, k), self.both, s.strip())
raise KeyError("typedef %r bad: %s" % (self, s))
_typedefs[t] = _Typedef(
base=_basicsize(t, base=base), both=False, kind=_kind_ignored, type=t
)
def set(self, safe_len=False, **kwds):
"""Set one or more attributes."""
if kwds: # double check
d = self.kwds()
d.update(kwds)
self.reset(**d)
if safe_len and self.item:
self.leng = _len
from array import array as _array
try:
if type(bytes) is not type(str): # bytes is str in 2.6, bytes new in 2.6, 3.0
_typedef_both(bytes, item=_sizeof_Cbyte, leng=_len) # bytes new in 2.6, 3.0
except NameError: # missing
pass
The provided code snippet includes necessary dependencies for implementing the `_typedef_code` function. Write a Python function `def _typedef_code(t, base=0, refs=None, kind=_kind_static, heap=False)` to solve the following problem:
Add new typedef for code only.
Here is the function:
def _typedef_code(t, base=0, refs=None, kind=_kind_static, heap=False):
"""Add new typedef for code only."""
v = _Typedef(
base=_basicsize(t, base=base), refs=refs, both=False, kind=kind, type=t
)
v.save(t, base=base, heap=heap)
return v # for _dict_typedef | Add new typedef for code only. |
178,528 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
from array import array as _array
_amapped = 0.01
The provided code snippet includes necessary dependencies for implementing the `amapped` function. Write a Python function `def amapped(percentage=None)` to solve the following problem:
Set/get approximate mapped memory usage as a percentage of the mapped file size. Sets the new percentage if not None and returns the previously set percentage. Applies only to *numpy.memmap* objects.
Here is the function:
def amapped(percentage=None):
"""Set/get approximate mapped memory usage as a percentage
of the mapped file size.
Sets the new percentage if not None and returns the
previously set percentage.
Applies only to *numpy.memmap* objects.
"""
global _amapped
p = _amapped * 100.0
if percentage is not None:
_amapped = max(0, min(1, percentage * 0.01))
return p | Set/get approximate mapped memory usage as a percentage of the mapped file size. Sets the new percentage if not None and returns the previously set percentage. Applies only to *numpy.memmap* objects. |
178,529 | import sys
import types as Types
import warnings
import weakref as Weakref
from inspect import isbuiltin, isclass, iscode, isframe, isfunction, ismethod, ismodule
from math import log
from os import curdir, linesep
from struct import calcsize
t = hasattr(sys, "gettotalrefcount")
del t
from gc import get_objects as _getobjects
from gc import get_referents as _getreferents
t = (_kind_static, _kind_dynamic, _kind_derived, _kind_ignored, _kind_inferred) = (
i("static"),
i("dynamic"),
i("derived"),
i("ignored"),
i("inferred"),
)
from array import array as _array
for t in _values(_typedefs):
if t.type and t.leng:
try: # create an (empty) instance
s.append(t.type())
except TypeError:
pass
for t in s:
try:
i = iter(t)
_typedef_both(type(i), leng=_len_iter, refs=_iter_refs, item=0) # no itemsize!
except (KeyError, TypeError): # ignore non-iterables, duplicates, etc.
pass
_asizer = Asizer()
The provided code snippet includes necessary dependencies for implementing the `asized` function. Write a Python function `def asized(*objs, **opts)` to solve the following problem:
Return a tuple containing an **Asized** instance for each object passed as positional argument. The available options and defaults are: *above=0* -- threshold for largest objects stats *align=8* -- size alignment *code=False* -- incl. (byte)code size *cutoff=10* -- limit large objects or profiles stats *derive=False* -- derive from super type *detail=0* -- Asized refs level *frames=False* -- ignore stack frame objects *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0* -- print statistics If only one object is given, the return value is the **Asized** instance for that object. Otherwise, the length of the returned tuple matches the number of given objects. The **Asized** size of duplicate and ignored objects will be zero. Set *detail* to the desired referents level and *limit* to the maximum recursion depth. See function **asizeof** for descriptions of the other options.
Here is the function:
def asized(*objs, **opts):
"""Return a tuple containing an **Asized** instance for each
object passed as positional argument.
The available options and defaults are:
*above=0* -- threshold for largest objects stats
*align=8* -- size alignment
*code=False* -- incl. (byte)code size
*cutoff=10* -- limit large objects or profiles stats
*derive=False* -- derive from super type
*detail=0* -- Asized refs level
*frames=False* -- ignore stack frame objects
*ignored=True* -- ignore certain types
*infer=False* -- try to infer types
*limit=100* -- recursion limit
*stats=0* -- print statistics
If only one object is given, the return value is the **Asized**
instance for that object. Otherwise, the length of the returned
tuple matches the number of given objects.
The **Asized** size of duplicate and ignored objects will be zero.
Set *detail* to the desired referents level and *limit* to the
maximum recursion depth.
See function **asizeof** for descriptions of the other options.
"""
_asizer.reset(**opts)
if objs:
t = _asizer.asized(*objs)
_asizer.print_stats(objs, opts=opts, sized=t) # show opts as _kwdstr
_asizer._clear()
else:
t = ()
return t | Return a tuple containing an **Asized** instance for each object passed as positional argument. The available options and defaults are: *above=0* -- threshold for largest objects stats *align=8* -- size alignment *code=False* -- incl. (byte)code size *cutoff=10* -- limit large objects or profiles stats *derive=False* -- derive from super type *detail=0* -- Asized refs level *frames=False* -- ignore stack frame objects *ignored=True* -- ignore certain types *infer=False* -- try to infer types *limit=100* -- recursion limit *stats=0* -- print statistics If only one object is given, the return value is the **Asized** instance for that object. Otherwise, the length of the returned tuple matches the number of given objects. The **Asized** size of duplicate and ignored objects will be zero. Set *detail* to the desired referents level and *limit* to the maximum recursion depth. See function **asizeof** for descriptions of the other options. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.