class LoadingError(Exception):      """Raised if an error occurs while loading the configuration file."""      class InconsistentEnvVariableError(Exception):      """Inconsistency value has been detected in an environment variable referenced by the configuration."""      class MissingEnvVariableError(Exception):      """Environment variable referenced in configuration is missing."""      class InvalidConfigurationId(Exception):      """Configuration id is not valid."""      class ConfigurationUpdateBlocked(Exception):      """The configuration is being blocked from update by other Taipy services."""


from ..common._repr_enum import _ReprEnum      class Frequency(_ReprEnum):      """Frequency of the recurrence of `Cycle^` and `Scenario^` objects.        The frequency must be provided in the `ScenarioConfig^`.        Each recurrent scenario is attached to the cycle corresponding to the creation date and the      frequency. In other words, each cycle represents an iteration and contains the various scenarios      created during this iteration.        For instance, when scenarios have a _MONTHLY_ frequency, one cycle will be created for each      month (January, February, March, etc.). A new scenario created on February 10th, gets      attached to the _February_ cycle.        The frequency is implemented as an enumeration with the following possible values:        - With a _DAILY_ frequency, a new cycle is created for each day.        - With a _WEEKLY_ frequency, a new cycle is created for each week (from Monday to Sunday).        - With a _MONTHLY_ frequency, a new cycle is created for each month.        - With a _QUARTERLY_ frequency, a new cycle is created for each quarter.        - With a _YEARLY_ frequency, a new cycle is created for each year.      """        DAILY = 1      WEEKLY = 2      MONTHLY = 3      QUARTERLY = 4      YEARLY = 5


class _Classproperty(object):      def __init__(self, f):          self.f = f        def __get__(self, obj, owner):          return self.f(owner)


#  # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with  # the License. You may obtain a copy of the License at  #  #        http://www.apache.org/licenses/LICENSE-2.0  #  # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on  # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the  # specific language governing permissions and limitations under the License.


import functools  from enum import Enum      class _ReprEnum(Enum):      @classmethod      @functools.lru_cache      def _from_repr(cls, repr_: str):          return next(filter(lambda e: repr(e) == repr_, cls))  # type: ignore


import keyword    from ..exceptions.exceptions import InvalidConfigurationId    __INVALID_TAIPY_ID_TERMS = ["CYCLE", "SCENARIO", "SEQUENCE", "TASK", "DATANODE"]      def _validate_id(name: str):      for invalid_taipy_id_term in __INVALID_TAIPY_ID_TERMS:          if invalid_taipy_id_term in name:              raise InvalidConfigurationId(f"{name} is not a valid identifier. {invalid_taipy_id_term} is restricted.")        if name.isidentifier() and not keyword.iskeyword(name):          return name        raise InvalidConfigurationId(f"{name} is not a valid identifier.")


import functools    from ...logger._taipy_logger import _TaipyLogger  from ..exceptions.exceptions import ConfigurationUpdateBlocked      class _ConfigBlocker:      """Configuration blocker singleton."""        __logger = _TaipyLogger._get_logger()      __block_config_update = False        @classmethod      def _block(cls):          cls.__block_config_update = True        @classmethod      def _unblock(cls):          cls.__block_config_update = False        @classmethod      def _check(cls):          def inner(f):              @functools.wraps(f)              def _check_if_is_blocking(*args, **kwargs):                  if cls.__block_config_update:                      error_message = (                          "The Core service should be stopped by running core.stop() before"                          " modifying the Configuration. For more information, please refer to:"                          " https://docs.taipy.io/en/latest/manuals/running_services/#running-core."                      )                      cls.__logger.error("ConfigurationUpdateBlocked: " + error_message)                      raise ConfigurationUpdateBlocked(error_message)                    return f(*args, **kwargs)                return _check_if_is_blocking            return inner


from ..common._repr_enum import _ReprEnum      class _OrderedEnum(_ReprEnum):      def __ge__(self, other):          if self.__class__ is other.__class__:              return self.value >= other.value          return NotImplemented        def __gt__(self, other):          if self.__class__ is other.__class__:              return self.value > other.value          return NotImplemented        def __le__(self, other):          if self.__class__ is other.__class__:              return self.value <= other.value          return NotImplemented        def __lt__(self, other):          if self.__class__ is other.__class__:              return self.value < other.value          return NotImplemented      class Scope(_OrderedEnum):      """Scope of a `DataNode^`.        This enumeration can have the following values:        - `GLOBAL`      - `CYCLE`      - `SCENARIO`      """        GLOBAL = 3      CYCLE = 2      SCENARIO = 1


import os  import re  from collections import UserDict  from datetime import datetime, timedelta  from importlib import import_module  from operator import attrgetter  from pydoc import locate    from ..exceptions.exceptions import InconsistentEnvVariableError, MissingEnvVariableError  from .frequency import Frequency  from .scope import Scope      class _TemplateHandler:      """Factory to handle actions related to config value templating."""        _PATTERN = r"^ENV\[([a-zA-Z_]\w*)\](:(\bbool\b|\bstr\b|\bfloat\b|\bint\b))?$"        @classmethod      def _replace_templates(cls, template, type=str, required=True, default=None):          if isinstance(template, tuple):              return tuple(cls._replace_template(item, type, required, default) for item in template)          if isinstance(template, list):              return [cls._replace_template(item, type, required, default) for item in template]          if isinstance(template, dict):              return {str(k): cls._replace_template(v, type, required, default) for k, v in template.items()}          if isinstance(template, UserDict):              return {str(k): cls._replace_template(v, type, required, default) for k, v in template.items()}          return cls._replace_template(template, type, required, default)        @classmethod      def _replace_template(cls, template, type, required, default):          if "ENV" not in str(template):              return template          match = re.fullmatch(cls._PATTERN, str(template))          if match:              var = match.group(1)              dynamic_type = match.group(3)              val = os.environ.get(var)              if val is None:                  if required:                      raise MissingEnvVariableError(f"Environment variable {var} is not set.")                  return default              if type == bool:                  return cls._to_bool(val)              elif type == int:                  return cls._to_int(val)              elif type == float:                  return cls._to_float(val)              elif type == Scope:                  return cls._to_scope(val)              elif type == Frequency:                  return cls._to_frequency(val)              else:                  if dynamic_type == "bool":                      return cls._to_bool(val)                  elif dynamic_type == "int":                      return cls._to_int(val)                  elif dynamic_type == "float":                      return cls._to_float(val)                  return val          return template        @staticmethod      def _to_bool(val: str) -> bool:          possible_values = ["true", "false"]          if str.lower(val) not in possible_values:              raise InconsistentEnvVariableError("{val} is not a Boolean.")          return str.lower(val) == "true" or not (str.lower(val) == "false")        @staticmethod      def _to_int(val: str) -> int:          try:              return int(val)          except ValueError:              raise InconsistentEnvVariableError(f"{val} is not an integer.")        @staticmethod      def _to_float(val: str) -> float:          try:              return float(val)          except ValueError:              raise InconsistentEnvVariableError(f"{val} is not a float.")        @staticmethod      def _to_datetime(val: str) -> datetime:          try:              return datetime.fromisoformat(val)          except ValueError:              raise InconsistentEnvVariableError(f"{val} is not a valid datetime.")        @staticmethod      def _to_timedelta(val: str) -> timedelta:          """          Parse a time string e.g. (2h13m) into a timedelta object.            :param timedelta_str: A string identifying a duration.  (eg. 2h13m)          :return datetime.timedelta: A datetime.timedelta object          """          regex = re.compile(              r"^((?P<days>[\.\d]+?)d)? *"              r"((?P<hours>[\.\d]+?)h)? *"              r"((?P<minutes>[\.\d]+?)m)? *"              r"((?P<seconds>[\.\d]+?)s)?$"          )          parts = regex.match(val)          if not parts:              raise InconsistentEnvVariableError(f"{val} is not a valid timedelta.")          time_params = {name: float(param) for name, param in parts.groupdict().items() if param}          return timedelta(**time_params)  # type: ignore        @staticmethod      def _to_scope(val: str) -> Scope:          try:              return Scope[str.upper(val)]          except Exception:              raise InconsistentEnvVariableError(f"{val} is not a valid scope.")        @staticmethod      def _to_frequency(val: str) -> Frequency:          try:              return Frequency[str.upper(val)]          except Exception:              raise InconsistentEnvVariableError(f"{val} is not a valid frequency.")        @staticmethod      def _to_function(val: str):          module_name, fct_name = val.rsplit(".", 1)          try:              module = import_module(module_name)              return attrgetter(fct_name)(module)          except Exception:              raise InconsistentEnvVariableError(f"{val} is not a valid function.")        @staticmethod      def _to_class(val: str):          try:              return locate(val)          except Exception:              raise InconsistentEnvVariableError(f"{val} is not a valid class.")


from __future__ import annotations    from typing import Any, Dict, Optional, Union    from ..common._config_blocker import _ConfigBlocker  from ..common._template_handler import _TemplateHandler as _tpl      class GlobalAppConfig:      """      Configuration fields related to the global application.        Attributes:          **properties (Dict[str, Any]): A dictionary of additional properties.      """        def __init__(self, **properties):          self._properties = properties        @property      def properties(self):          return {k: _tpl._replace_templates(v) for k, v in self._properties.items()}        @properties.setter  # type: ignore      @_ConfigBlocker._check()      def properties(self, val):          self._properties = val        def __getattr__(self, item: str) -> Optional[Any]:          return _tpl._replace_templates(self._properties.get(item))        @classmethod      def default_config(cls) -> GlobalAppConfig:          return GlobalAppConfig()        def _clean(self):          self._properties.clear()        def _to_dict(self):          as_dict = {}          as_dict.update(self._properties)          return as_dict        @classmethod      def _from_dict(cls, config_as_dict: Dict[str, Any]):          config = GlobalAppConfig()          config._properties = config_as_dict          return config        def _update(self, config_as_dict):          self._properties.update(config_as_dict)


import pathlib  import sys    from cookiecutter.main import cookiecutter    import taipy  from taipy._cli._base_cli import _CLI      class _ScaffoldCLI:      __TAIPY_PATH = pathlib.Path(taipy.__file__).parent.resolve() / "templates"        _TEMPLATE_MAP = {str(x.name): str(x) for x in __TAIPY_PATH.iterdir() if x.is_dir()}        @classmethod      def create_parser(cls):          create_parser = _CLI._add_subparser("create", help="Create a new Taipy application.")          create_parser.add_argument(              "--template",              choices=list(cls._TEMPLATE_MAP.keys()),              default="default",              help="The Taipy template to create new application.",          )        @classmethod      def parse_arguments(cls):          args = _CLI._parse()            if getattr(args, "which", None) == "create":              cookiecutter(cls._TEMPLATE_MAP[args.template])              sys.exit(0)


import subprocess  import sys    from taipy._cli._base_cli import _CLI      class _RunCLI:      @classmethod      def create_parser(cls):          run_parser = _CLI._add_subparser("run", help="Run a Taipy application.")          run_parser.add_argument(              "application_main_file",          )            sub_run_parser = run_parser.add_subparsers(title="subcommands")          sub_run_parser.add_parser(              "external-args",              help="""                  Arguments defined after this keyword will be considered as external arguments                  to be passed to the application              """,          )        @classmethod      def parse_arguments(cls):          args = _CLI._parse()            if getattr(args, "which", None) == "run":              all_args = sys.argv[3:]  # First 3 args are always (1) Python executable, (2) run, (3) Python file                external_args = []              try:                  external_args_index = all_args.index("external-args")              except ValueError:                  pass              else:                  external_args.extend(all_args[external_args_index + 1 :])                  all_args = all_args[:external_args_index]                taipy_args = [f"--taipy-{arg[2:]}" if arg.startswith("--") else arg for arg in all_args]                subprocess.run(                  [sys.executable, args.application_main_file, *(external_args + taipy_args)],                  stdout=sys.stdout,                  stderr=sys.stdout,              )                sys.exit(0)


import sys    from taipy._cli._base_cli import _CLI  from taipy.logger._taipy_logger import _TaipyLogger      class _HelpCLI:      __logger = _TaipyLogger._get_logger()        @classmethod      def create_parser(cls):          create_parser = _CLI._add_subparser("help", help="Show the Taipy help message.", add_help=False)          create_parser.add_argument(              "command", nargs="?", type=str, const="", default="", help="Show the help message of the command."          )        @classmethod      def parse_arguments(cls):          args = _CLI._parse()            if getattr(args, "which", None) == "help":              if args.command:                  if args.command in _CLI._sub_taipyparsers.keys():                      _CLI._sub_taipyparsers.get(args.command).print_help()                  else:                      cls.__logger.error(f"{args.command} is not a valid command.")              else:                  _CLI._parser.print_help()                sys.exit(0)


import argparse  from typing import Dict      class _CLI:      """Argument parser for Taipy application."""        # The conflict_handler is set to "resolve" to override conflict arguments      _subparser_action = None      _parser = argparse.ArgumentParser(conflict_handler="resolve")        _sub_taipyparsers: Dict[str, argparse.ArgumentParser] = {}      _arg_groups: Dict[str, argparse._ArgumentGroup] = {}        @classmethod      def _add_subparser(cls, name: str, **kwargs) -> argparse.ArgumentParser:          """Create a new subparser and return a argparse handler."""          if subparser := cls._sub_taipyparsers.get(name):              return subparser            if not cls._subparser_action:              cls._subparser_action = cls._parser.add_subparsers()            subparser = cls._subparser_action.add_parser(              name=name,              conflict_handler="resolve",              **kwargs,          )          cls._sub_taipyparsers[name] = subparser          subparser.set_defaults(which=name)          return subparser        @classmethod      def _add_groupparser(cls, title: str, description: str = "") -> argparse._ArgumentGroup:          """Create a new group for arguments and return a argparser handler."""          if groupparser := cls._arg_groups.get(title):              return groupparser            groupparser = cls._parser.add_argument_group(title=title, description=description)          cls._arg_groups[title] = groupparser          return groupparser        @classmethod      def _parse(cls):          """Parse and return only known arguments."""          args, _ = cls._parser.parse_known_args()          return args        @classmethod      def _remove_argument(cls, arg: str):          """Remove an argument from the parser. Note that the `arg` must be without --.            Source: https://stackoverflow.com/questions/32807319/disable-remove-argument-in-argparse          """          for action in cls._parser._actions:              opts = action.option_strings              if (opts and opts[0] == arg) or action.dest == arg:                  cls._parser._remove_action(action)                  break            for argument_group in cls._parser._action_groups:              for group_action in argument_group._group_actions:                  opts = group_action.option_strings                  if (opts and opts[0] == arg) or group_action.dest == arg:                      argument_group._group_actions.remove(group_action)                      return


from ._cli import _CLI


import typing as t      class Icon:      """Small image in the User Interface.        Icons are typically used in controls like [button](../gui/viselements/button.md)      or items in a [menu](../gui/viselements/menu.md).        Attributes:          path (str): The path to the image file.          text (Optional[str]): The text associated to the image or None if there is none.          svg (Optional[bool]): True if the image is svg.        If a text is associated to an icon, it is rendered by the visual elements that      uses this Icon.      """        @staticmethod      def get_dict_or(value: t.Union[str, t.Any]) -> t.Union[str, dict]:          return value._to_dict() if isinstance(value, Icon) else value        def __init__(          self,          path: str,          text: t.Optional[str] = None,          light_path: t.Optional[bool] = None,          dark_path: t.Optional[bool] = None,      ) -> None:          """Initialize a new Icon.            Arguments:              path (str): The path to an image file.
                  This path must be relative to and inside the root directory of the                  application (where the Python file that created the `Gui` instance                  is located).
                  In situations where the image file is located outside the application                  directory, a _path mapping_ must be used: the _path_mapping_ parameter                  of the `Gui^` constructor makes it possible to access a resource anywhere                  on the server filesystem, as if it were located in a subdirectory of                  the application directory.              text (Optional[str]): The text associated to the image. If *text* is None,                  there is no text associated to this image.              light_path (Optional[str]): The path to the light theme image (fallback to *path* if not defined).              dark_path (Optional[str]): The path to the dark theme image (fallback to *path* if not defined).          """          self.path = path          self.text = text          if light_path is not None:              self.light_path = light_path          if dark_path is not None:              self.dark_path = dark_path        def _to_dict(self, a_dict: t.Optional[dict] = None) -> dict:          if a_dict is None:              a_dict = {}          a_dict["path"] = self.path          if self.text is not None:              a_dict["text"] = self.text          if hasattr(self, "light_path") and self.light_path is not None:              a_dict["lightPath"] = self.light_path          if hasattr(self, "dark_path") and self.dark_path is not None:              a_dict["darkPath"] = self.dark_path          return a_dict


from .gui import Gui


import typing as t  from enum import Enum  from inspect import isclass    from .data import Decimator  from .utils import (      _TaipyBase,      _TaipyBool,      _TaipyContent,      _TaipyContentHtml,      _TaipyContentImage,      _TaipyData,      _TaipyDate,      _TaipyDateRange,      _TaipyDict,      _TaipyLoNumbers,      _TaipyLov,      _TaipyLovValue,      _TaipyNumber,  )      class _WsType(Enum):      ACTION = "A"      MULTIPLE_UPDATE = "MU"      REQUEST_UPDATE = "RU"      DATA_UPDATE = "DU"      UPDATE = "U"      ALERT = "AL"      BLOCK = "BL"      NAVIGATE = "NA"      CLIENT_ID = "ID"      MULTIPLE_MESSAGE = "MS"      DOWNLOAD_FILE = "DF"      PARTIAL = "PR"      ACKNOWLEDGEMENT = "ACK"      NumberTypes = {"int", "int64", "float", "float64"}      class PropertyType(Enum):      """      All the possible element property types.        This is used when creating custom visual elements, where you have      to indicate the type of each property.        Some types are 'dynamic', meaning that if the property value is modified, it      is automatically handled by Taipy and propagated to the entire application.        See `ElementProperty^` for more details.      """        boolean = "boolean"      """      The property holds a Boolean value.      """      toHtmlContent = _TaipyContentHtml      content = _TaipyContent      data = _TaipyData      date = _TaipyDate      date_range = _TaipyDateRange      dict = "dict"      """      The property holds a dictionary.      """      dynamic_dict = _TaipyDict      """      The property holds a dynamic dictionary.      """      dynamic_number = _TaipyNumber      """      The property holds a dynamic number.      """      dynamic_lo_numbers = _TaipyLoNumbers      """      The property holds a dynamic list of numbers.      """      dynamic_boolean = _TaipyBool      """      The property holds a dynamic Boolean value.      """      dynamic_list = "dynamiclist"      dynamic_string = "dynamicstring"      """      The property holds a dynamic string.      """      function = "function"      """      The property holds a reference to a function.      """      image = _TaipyContentImage      json = "json"      lov = _TaipyLov      """      The property holds a LoV (list of values).      """      lov_value = _TaipyLovValue      """      The property holds a value in a LoV (list of values).      """      number = "number"      """      The property holds a number.      """      react = "react"      broadcast = "broadcast"      string = "string"      """      The property holds a string.      """      string_or_number = "string|number"      """      The property holds a string or a number.        This is typically used to handle CSS dimension values, where a unit can be used.      """      boolean_or_list = "boolean|list"      slider_value = "number|number[]|lovValue"      string_list = "stringlist"      decimator = Decimator      """      The property holds an inner attributes that is defined by a library and cannot be overridden by the user.      """      inner = "inner"      @t.overload  # noqa: F811  def _get_taipy_type(a_type: None) -> None:      ...      @t.overload  def _get_taipy_type(a_type: t.Type[_TaipyBase]) -> t.Type[_TaipyBase]:  # noqa: F811      ...      @t.overload  def _get_taipy_type(a_type: PropertyType) -> t.Type[_TaipyBase]:  # noqa: F811      ...      @t.overload  def _get_taipy_type(  # noqa: F811      a_type: t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]  ) -> t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]:      ...      def _get_taipy_type(  # noqa: F811      a_type: t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]  ) -> t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]:      if a_type is None:          return None      if isinstance(a_type, PropertyType) and not isinstance(a_type.value, str):          return a_type.value      if isclass(a_type) and not isinstance(a_type, PropertyType) and issubclass(a_type, _TaipyBase):          return a_type      if a_type == PropertyType.boolean:          return _TaipyBool      elif a_type == PropertyType.number:          return _TaipyNumber      return None


"""# Taipy Graphical User Interface generator    The Taipy GUI package provides User Interface generation based on page templates. It can  run a web server that a web browser can connect to.    The pages are generated by a web server that allows web clients to connect, display and  interact with the page content through visual elements.    Each page can contain regular text and images, as well as Taipy controls that are  typically linked to some value that is managed by the whole Taipy application.    Here is how you can create your first Taipy User Interface:       - Create a Python source file.       Copy these two lines into a file called *taipy_app.py*.       ```py title="taipy_app.py"       from taipy import Gui       Gui("# Hello Taipy!").run()       ```     - Install Taipy:       ```       pip install taipy       ```     - Run your application:       ```       python taipy_app.py       ```    Your browser opens a new page, showing the content of your graphical  application.    !!! Note "Optional packages"        There are Python packages that you can install in your environment to      add functionality to Taipy GUI:        - [`python-magic`](https://pypi.org/project/python-magic/): identifies image format        from byte buffers so the [`image`](../../gui/viselements/image.md) control can        display them, and so that [`file_download`](../../gui/viselements/file_download.md)        can request the browser to display the image content when relevant.
        You can install that package with the regular `pip install python-magic` command        (then potentially `pip install python-magic` on Windows),        or install Taipy GUI using: `pip install taipy-gui[image]`.      - [`pyarrow`](https://pypi.org/project/pyarrow/): can improve the performance of your        application by reducing the volume of data transferred between the web server and the        clients. This is relevant if your application uses large tabular data.
        You can install that package with the regular `pip install pyarrow` command,        or install Taipy GUI using: `pip install taipy-gui[arrow]`.      - [`simple-websocket`](https://pypi.org/project/simple-websocket/): enables the        debugging of the WebSocket part of the server execution.
        You can install that package with the regular `pip install simple-websocket` command,        or install Taipy GUI using: `pip install taipy-gui[simple-websocket]`.      - [`pyngrok`](https://pypi.org/project/pyngrok/): enables use of [Ngrok](https://ngrok.com/)        to access Taipy GUI application from the internet.
        You can install that package with the regular `pip install pyngrok` command,        or install Taipy GUI using: `pip install taipy-gui[pyngrok]`.    """    from importlib.util import find_spec    from ._init import *  from ._renderers import Html, Markdown  from .gui_actions import (      broadcast_callback,      download,      get_module_context,      get_module_name_from_state,      get_state_id,      get_user_content_url,      hold_control,      invoke_callback,      invoke_long_callback,      navigate,      notify,      resume_control,  )  from .icon import Icon  from .page import Page  from .partial import Partial  from .state import State  from .utils import is_debugging    if find_spec("taipy") and find_spec("taipy.config"):      from taipy.config import _inject_section        from ._default_config import default_config      from ._gui_section import _GuiSection        _inject_section(          _GuiSection,          "gui_config",          _GuiSection(property_list=list(default_config)),          [("configure_gui", _GuiSection._configure)],          add_to_unconflicted_sections=True,      )


from __future__ import annotations    import inspect  import typing as t  from types import FrameType    from .utils import _filter_locals, _get_module_name_from_frame    if t.TYPE_CHECKING:      from ._renderers import _Element      class Page:      """Generic page generator.        The `Page` class transforms template text into actual pages that can be displayed      on a web browser.        When a page is requested to be displayed, it is converted into HTML      code that can be sent to the client. All control placeholders are      replaced by their respective graphical component so you can show      your application variables and interact with them.      """        def __init__(self, **kwargs) -> None:          self._class_module_name = ""          self._class_locals: t.Dict[str, t.Any] = {}          self._frame: t.Optional[FrameType] = None          self._renderer: t.Optional[Page] = self.create_page()          if "frame" in kwargs:              self._frame = kwargs.get("frame")          elif self._renderer:              self._frame = self._renderer._frame          elif len(inspect.stack()) < 4:              raise RuntimeError(f"Can't resolve module. Page '{type(self).__name__}' is not registered.")          else:              self._frame = t.cast(FrameType, t.cast(FrameType, inspect.stack()[3].frame))          if self._renderer:              # Extract the page module's attributes and methods              cls = type(self)              cls_locals = dict(vars(self))              funcs = [                  i[0]                  for i in inspect.getmembers(cls)                  if not i[0].startswith("_") and (inspect.ismethod(i[1]) or inspect.isfunction(i[1]))              ]              for f in funcs:                  func = getattr(self, f)                  if hasattr(func, "__func__") and func.__func__ is not None:                      cls_locals[f] = func.__func__              self._class_module_name = cls.__name__              self._class_locals = cls_locals        def create_page(self) -> t.Optional[Page]:          """Create the page content for page modules.            If this page is a page module, this method must be overloaded and return the page content.            This method should never be called directly: only the Taipy GUI internals will.            The default implementation returns None, indicating that this class does not implement          a page module.            Returns:              The page content for this Page subclass, making it a page module.          """          return None        def _get_locals(self) -> t.Optional[t.Dict[str, t.Any]]:          return (              self._class_locals              if self._is_class_module()              else None              if (frame := self._get_frame()) is None              else _filter_locals(frame.f_locals)          )        def _is_class_module(self):          return self._class_module_name != ""        def _get_frame(self):          if not hasattr(self, "_frame"):              raise RuntimeError(f"Page '{type(self).__name__}' was not registered correctly.")          return self._frame        def _get_module_name(self) -> t.Optional[str]:          return (              None              if (frame := self._get_frame()) is None              else f"{_get_module_name_from_frame(frame)}{'.' if self._class_module_name else ''}{self._class_module_name}"  # noqa: E501          )        def _get_content_detail(self, gui) -> str:          return f"in class {type(self).__name__}"        def render(self, gui) -> str:          if self._renderer is not None:              return self._renderer.render(gui)          return "
No renderer found for page
"


import sys  import traceback  import typing as t  import warnings      class TaipyGuiWarning(UserWarning):      """NOT DOCUMENTED        Warning category for Taipy warnings generated in user code.      """        _tp_debug_mode = False        @staticmethod      def set_debug_mode(debug_mode: bool):          TaipyGuiWarning._tp_debug_mode = (              debug_mode if debug_mode else hasattr(sys, "gettrace") and sys.gettrace() is not None          )      def _warn(message: str, e: t.Optional[BaseException] = None):      warnings.warn(          f"{message}:\n{''.join(traceback.format_exception(type(e), e, e.__traceback__))}"          if e and TaipyGuiWarning._tp_debug_mode          else f"{message}:\n{e}"          if e          else message,          TaipyGuiWarning,          stacklevel=2,      )


import typing as t  from copy import copy    from taipy.config import Config as TaipyConfig  from taipy.config import UniqueSection    from ._default_config import default_config      class _GuiSection(UniqueSection):      name = "gui"        def __init__(self, property_list: t.Optional[t.List] = None, **properties):          self._property_list = property_list          super().__init__(**properties)        def __copy__(self):          return _GuiSection(property_list=copy(self._property_list), **copy(self._properties))        def _clean(self):          self._properties.clear()        def _to_dict(self):          as_dict = {}          as_dict.update(self._properties)          return as_dict        @classmethod      def _from_dict(cls, as_dict: t.Dict[str, t.Any], *_):          return _GuiSection(property_list=list(default_config), **as_dict)        def _update(self, as_dict: t.Dict[str, t.Any]):          if self._property_list:              as_dict = {k: v for k, v in as_dict.items() if k in self._property_list}          self._properties.update(as_dict)        @staticmethod      def _configure(**properties) -> "_GuiSection":          """NOT DOCUMENTED          Configure the Graphical User Interface.            Parameters:              **properties (dict[str, any]): Keyword arguments that configure the behavior of the `Gui^` instances.<br/>                  Please refer to the                  [Configuration section](../gui/configuration.md#configuring-the-gui-instance)                  of the User Manual for more information on the accepted arguments.          Returns:              The GUI configuration.            """          section = _GuiSection(property_list=list(default_config), **properties)          TaipyConfig._register(section)          return TaipyConfig.unique_sections[_GuiSection.name]


# _Page for multipage support  from __future__ import annotations    import logging  import typing as t  import warnings    if t.TYPE_CHECKING:      from ._renderers import Page      from .gui import Gui      class _Page(object):      def __init__(self):          self._rendered_jsx: t.Optional[str] = None          self._renderer: t.Optional[Page] = None          self._style: t.Optional[str] = None          self._route: t.Optional[str] = None          self._head: t.Optional[list] = None        def render(self, gui: Gui):          if self._renderer is None:              raise RuntimeError(f"Can't render page {self._route}: no renderer found")          with warnings.catch_warnings(record=True) as w:              warnings.resetwarnings()              with gui._set_locals_context(self._renderer._get_module_name()):                  self._rendered_jsx = self._renderer.render(gui)              if w:                  s = "\033[1;31m\n"                  s += (                      message := f"--- {len(w)} warning(s) were found for page '{'/' if self._route == gui._get_root_page_name() else self._route}' {self._renderer._get_content_detail(gui)} ---\n"  # noqa: E501                  )                  for i, wm in enumerate(w):                      s += f" - Warning {i + 1}: {wm.message}\n"                  s += "-" * len(message)                  s += "\033[0m\n"                  logging.warn(s)          if hasattr(self._renderer, "head"):              self._head = list(self._renderer.head)  # type: ignore          # return renderer module_name from frame          return self._renderer._get_module_name()


#!/usr/bin/env python    """The setup script."""    import json  import os  from pathlib import Path    from setuptools import find_namespace_packages, find_packages, setup  from setuptools.command.build_py import build_py    readme = Path("README.md").read_text()    with open(f"src{os.sep}taipy{os.sep}gui{os.sep}version.json") as version_file:      version = json.load(version_file)      version_string = f'{version.get("major", 0)}.{version.get("minor", 0)}.{version.get("patch", 0)}'      if vext := version.get("ext"):          version_string = f"{version_string}.{vext}"    requirements = [      "flask>=3.0.0,<3.1",      "flask-cors>=4.0.0,<5.0",      "flask-socketio>=5.3.6,<6.0",      "markdown>=3.4.4,<4.0",      "pandas>=2.0.0,<3.0",      "python-dotenv>=1.0.0,<1.1",      "pytz>=2021.3,<2022.2",      "tzlocal>=3.0,<5.0",      "backports.zoneinfo>=0.2.1,<0.3;python_version<'3.9'",      "gevent>=23.7.0,<24.0",      "gevent-websocket>=0.10.1,<0.11",      "kthread>=0.2.3,<0.3",      "taipy-config@git+https://git@github.com/Avaiga/taipy-config.git@develop",      "gitignore-parser>=0.1,<0.2",      "simple-websocket>=0.10.1,<1.0",      "twisted>=23.8.0,<24.0",  ]    test_requirements = ["pytest>=3.8"]    extras_require = {      "ngrok": ["pyngrok>=5.1,<6.0"],      "image": [          "python-magic>=0.4.24,<0.5;platform_system!='Windows'",          "python-magic-bin>=0.4.14,<0.5;platform_system=='Windows'",      ],      "arrow": ["pyarrow>=10.0.1,<11.0"],  }      def _build_webapp():      already_exists = Path("./src/taipy/gui/webapp/index.html").exists()      if not already_exists:          os.system("cd ../../../frontend/taipy-gui/dom && npm ci")          os.system("cd ../../../frontend/taipy-gui && npm ci --omit=optional && npm run build")      class NPMInstall(build_py):      def run(self):          _build_webapp()          build_py.run(self)      setup(      author="Avaiga",      author_email="dev@taipy.io",      python_requires=">=3.8",      classifiers=[          "Intended Audience :: Developers",          "License :: OSI Approved :: Apache Software License",          "Natural Language :: English",          "Programming Language :: Python :: 3",          "Programming Language :: Python :: 3.8",          "Programming Language :: Python :: 3.9",          "Programming Language :: Python :: 3.10",          "Programming Language :: Python :: 3.11",      ],      description="Low-code library to create graphical user interfaces on the Web for your Python applications.",      long_description=readme,      long_description_content_type="text/markdown",      install_requires=requirements,      license="Apache License 2.0",      include_package_data=True,      keywords="taipy-gui",      name="taipy-gui",      package_dir={"": "src"},      packages=find_namespace_packages(where="src") + find_packages(include=["taipy", "taipy.gui", "taipy.gui.*"]),      test_suite="tests",      tests_require=test_requirements,      url="https://github.com/avaiga/taipy-gui",      version=version_string,      zip_safe=False,      extras_require=extras_require,      cmdclass={"build_py": NPMInstall},  )


from .config import Config, Stylekit    _default_stylekit: Stylekit = {      # Primary and secondary colors      "color_primary": "#ff6049",      "color_secondary": "#293ee7",      # Contextual color      "color_error": "#FF595E",      "color_warning": "#FAA916",      "color_success": "#96E6B3",      # Background and elevation color for LIGHT MODE      "color_background_light": "#f0f5f7",      "color_paper_light": "#ffffff",      # Background and elevation color for DARK MODE      "color_background_dark": "#152335",      "color_paper_dark": "#1f2f44",      # DEFINING FONTS      # Set main font family      "font_family": "Lato, Arial, sans-serif",      # DEFINING ROOT STYLES      # Set root margin      "root_margin": "1rem",      # DEFINING SHAPES      # Base border radius in px      "border_radius": 8,      # DEFINING MUI COMPONENTS STYLES      # Matching input and button height in css size unit      "input_button_height": "48px",  }    # Default config loaded by app.py  default_config: Config = {      "allow_unsafe_werkzeug": False,      "async_mode": "gevent",      "change_delay": None,      "chart_dark_template": None,      "base_url": "/",      "dark_mode": True,      "dark_theme": None,      "debug": False,      "extended_status": False,      "favicon": None,      "flask_log": False,      "host": "127.0.0.1",      "light_theme": None,      "margin": "1em",      "ngrok_token": "",      "notebook_proxy": True,      "notification_duration": 3000,      "propagate": True,      "run_browser": True,      "run_in_thread": False,      "run_server": True,      "server_config": None,      "single_client": False,      "system_notification": False,      "theme": None,      "time_zone": None,      "title": None,      "stylekit": _default_stylekit.copy(),      "upload_folder": None,      "use_arrow": False,      "use_reloader": False,      "watermark": "Taipy inside",      "webapp_path": None,      "port": 5000,  }


from __future__ import annotations    import typing as t    from ._page import _Page  from ._warnings import _warn  from .state import State    if t.TYPE_CHECKING:      from .page import Page      class Partial(_Page):      """Re-usable Page content.        Partials are used when you need to use a partial page content in different      and not related pages. This allows not to have to repeat yourself when      creating your page templates.        Visual elements such as [`part`](../gui/viselements/part.md),      [`dialog`](../gui/viselements/dialog.md) or      [`pane`](../gui/viselements/pane.md) can use Partials.        Note that `Partial` has no constructor (no `__init__()` method): to create a      `Partial`, you must call the `Gui.add_partial()^` function.        Partials can be really handy if you want to modify a section of a page:      the `update_content()` method dynamically update pages that make use      of this `Partial` therefore making it easy to change the content of      any page, at any moment.      """        _PARTIALS = "__partials"        __partials: t.Dict[str, Partial] = {}        def __init__(self, route: t.Optional[str] = None):          super().__init__()          if route is None:              self._route = f"TaiPy_partials_{len(Partial.__partials)}"              Partial.__partials[self._route] = self          else:              self._route = route        def update_content(self, state: State, content: str | "Page"):          """Update partial content.            Arguments:              state (State^): The current user state as received in any callback.              content (str): The new content to use and display.          """          if state and state._gui and callable(state._gui._update_partial):              state._gui._update_partial(self.__copy(content))          else:              _warn("'Partial.update_content()' must be called in the context of a callback.")        def __copy(self, content: str | "Page") -> Partial:          new_partial = Partial(self._route)          from .page import Page            if isinstance(content, Page):              new_partial._renderer = content          else:              new_partial._renderer = type(self._renderer)(content=content) if self._renderer is not None else None          return new_partial


from typing import Dict, Tuple    from taipy._cli._base_cli import _CLI      class _GuiCLI:      """Command-line interface of GUI."""        __GUI_ARGS: Dict[Tuple, Dict] = {          ("--port", "-P"): {              "dest": "taipy_port",              "metavar": "PORT",              "nargs": "?",              "default": "",              "const": "",              "help": "Specify server port",          },          ("--host", "-H"): {              "dest": "taipy_host",              "metavar": "HOST",              "nargs": "?",              "default": "",              "const": "",              "help": "Specify server host",          },          ("--ngrok-token",): {              "dest": "taipy_ngrok_token",              "metavar": "NGROK_TOKEN",              "nargs": "?",              "default": "",              "const": "",              "help": "Specify NGROK Authtoken",          },          ("--webapp-path",): {              "dest": "taipy_webapp_path",              "metavar": "WEBAPP_PATH",              "nargs": "?",              "default": "",              "const": "",              "help": "The path to the web app to be used. The default is the webapp directory under gui in the Taipy GUI package directory.",  # noqa: E501          },      }        __DEBUG_ARGS: Dict[str, Dict] = {          "--debug": {"dest": "taipy_debug", "help": "Turn on debug", "action": "store_true"},          "--no-debug": {"dest": "taipy_no_debug", "help": "Turn off debug", "action": "store_true"},      }        __RELOADER_ARGS: Dict[str, Dict] = {          "--use-reloader": {"dest": "taipy_use_reloader", "help": "Auto reload on code changes", "action": "store_true"},          "--no-reloader": {"dest": "taipy_no_reloader", "help": "No reload on code changes", "action": "store_true"},      }        @classmethod      def create_parser(cls):          gui_parser = _CLI._add_groupparser("Taipy GUI", "Optional arguments for Taipy GUI service")            for args, arg_dict in cls.__GUI_ARGS.items():              taipy_arg = (args[0], cls.__add_taipy_prefix(args[0]), *args[1:])              gui_parser.add_argument(*taipy_arg, **arg_dict)            debug_group = gui_parser.add_mutually_exclusive_group()          for debug_arg, debug_arg_dict in cls.__DEBUG_ARGS.items():              debug_group.add_argument(debug_arg, cls.__add_taipy_prefix(debug_arg), **debug_arg_dict)            reloader_group = gui_parser.add_mutually_exclusive_group()          for reloader_arg, reloader_arg_dict in cls.__RELOADER_ARGS.items():              reloader_group.add_argument(reloader_arg, cls.__add_taipy_prefix(reloader_arg), **reloader_arg_dict)        @classmethod      def create_run_parser(cls):          run_parser = _CLI._add_subparser("run", help="Run a Taipy application.")          for args, arg_dict in cls.__GUI_ARGS.items():              run_parser.add_argument(*args, **arg_dict)            debug_group = run_parser.add_mutually_exclusive_group()          for debug_arg, debug_arg_dict in cls.__DEBUG_ARGS.items():              debug_group.add_argument(debug_arg, **debug_arg_dict)            reloader_group = run_parser.add_mutually_exclusive_group()          for reloader_arg, reloader_arg_dict in cls.__RELOADER_ARGS.items():              reloader_group.add_argument(reloader_arg, **reloader_arg_dict)        @classmethod      def parse_arguments(cls):          return _CLI._parse()        @classmethod      def __add_taipy_prefix(cls, key: str):          if key.startswith("--no-"):              return key[:5] + "taipy-" + key[5:]            return key[:2] + "taipy-" + key[2:]


from ..gui_types import PropertyType  from .library import Element, ElementLibrary, ElementProperty


from __future__ import annotations    import typing as t      class _MapDict(object):      """      Provide class binding, can utilize getattr, setattr functionality      Also perform update operation      """        __local_vars = ("_dict", "_update_var")        def __init__(self, dict_import: dict, app_update_var=None):          self._dict = dict_import          # Bind app update var function          self._update_var = app_update_var        def __len__(self):          return self._dict.__len__()        def __length_hint__(self):          return self._dict.__length_hint__()        def __getitem__(self, key):          value = self._dict.__getitem__(key)          if isinstance(value, dict):              if self._update_var:                  return _MapDict(value, lambda s, v: self._update_var(f"{key}.{s}", v))              else:                  return _MapDict(value)          return value        def __setitem__(self, key, value):          if self._update_var:              self._update_var(key, value)          else:              self._dict.__setitem__(key, value)        def __delitem__(self, key):          self._dict.__delitem__(key)        def __missing__(self, key):          return self._dict.__missing__(key)        def __iter__(self):          return self._dict.__iter__()        def __reversed__(self):          return self._dict.__reversed__()        def __contains__(self, item):          return self._dict.__contains__(item)        # to be able to use getattr      def __getattr__(self, attr):          value = self._dict.__getitem__(attr)          if isinstance(value, dict):              if self._update_var:                  return _MapDict(value, lambda s, v: self._update_var(f"{attr}.{s}", v))              else:                  return _MapDict(value)          return value        def __setattr__(self, attr, value):          if attr in _MapDict.__local_vars:              super().__setattr__(attr, value)          else:              self.__setitem__(attr, value)        def keys(self):          return self._dict.keys()        def values(self):          return self._dict.values()        def items(self):          return self._dict.items()        def get(self, key: t.Any, default_value: t.Optional[str] = None) -> t.Optional[t.Any]:          return self._dict.get(key, default_value)        def clear(self) -> None:          self._dict.clear()        def setdefault(self, key, value=None) -> t.Optional[t.Any]:          return self._dict.setdefault(key, value)        def pop(self, key, default=None) -> t.Any:          return self._dict.pop(key, default)        def popitem(self) -> tuple:          return self._dict.popitem()        def copy(self) -> _MapDict:          return _MapDict(self._dict.copy(), self._update_var)        def update(self, d: dict) -> None:          current_keys = self.keys()          for k, v in d.items():              if k not in current_keys or self[k] != v:                  self.__setitem__(k, v)


import re  import typing as t    _RE_MODULE = re.compile(r"^__(.*?)__$")      def _filter_locals(locals_dict: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:      return {k: v for k, v in locals_dict.items() if (not _RE_MODULE.match(k) or k == "__name__")}


import typing as t    from .singleton import _Singleton    if t.TYPE_CHECKING:      from ..gui import Gui      class _RuntimeManager(object, metaclass=_Singleton):      def __init__(self):          self.__port_gui: t.Dict[int, "Gui"] = {}        def add_gui(self, gui: "Gui", port: int):          if port in self.__port_gui:              self.__port_gui[port].stop()          self.__port_gui[port] = gui        def get_used_port(self):          return list(self.__port_gui.keys())


import inspect  import sys  import typing as t  from types import FrameType, ModuleType      def _get_module_name_from_frame(frame: FrameType):      return frame.f_globals["__name__"] if "__name__" in frame.f_globals else None      def _get_module_name_from_imported_var(var_name: str, value: t.Any, sub_module_name: str) -> str:      module_list = sys.modules.copy()      # the provided sub_module_name are expected to contain only part of the full module_name provided by sys.modules      # --> we can find potential matched modules based on the sub_module_name      potential_matched_module = [m for m in module_list.keys() if m.endswith(sub_module_name)]      for m in potential_matched_module:          module = module_list[m]          if hasattr(module, var_name) and getattr(module, var_name) is value:              return m      # failed fetching any matched module with variable and value      return sub_module_name


import contextlib  import typing as t  import warnings  from threading import Thread  from urllib.parse import quote as urlquote  from urllib.parse import urlparse    from twisted.internet import reactor  from twisted.web.proxy import ProxyClient, ProxyClientFactory  from twisted.web.resource import Resource  from twisted.web.server import NOT_DONE_YET, Site    from .is_port_open import _is_port_open    # flake8: noqa: E402  from .singleton import _Singleton    warnings.filterwarnings(      "ignore",      category=UserWarning,      message="You do not have a working installation of the service_identity module: 'No module named 'service_identity''.*",  # noqa: E501  )      if t.TYPE_CHECKING:      from ..gui import Gui      def _modifiedHandleResponseEnd(self):      if self._finished:          return      self._finished = True      with contextlib.suppress(Exception):          self.father.finish()      self.transport.loseConnection()      setattr(ProxyClient, "handleResponseEnd", _modifiedHandleResponseEnd)      class _TaipyReverseProxyResource(Resource):      proxyClientFactoryClass = ProxyClientFactory        def __init__(self, host, path, gui: "Gui", reactor=reactor):          Resource.__init__(self)          self.host = host          self.path = path          self.reactor = reactor          self._gui = gui        def getChild(self, path, request):          return _TaipyReverseProxyResource(              self.host,              self.path + b"/" + urlquote(path, safe=b"").encode("utf-8"),              self._gui,              self.reactor,          )        def _get_port(self):          return self._gui._server._port        def render(self, request):          port = self._get_port()          host = self.host if port == 80 else "%s:%d" % (self.host, port)          request.requestHeaders.setRawHeaders(b"host", [host.encode("ascii")])          request.content.seek(0, 0)          rest = self.path + b"?" + qs if (qs := urlparse(request.uri)[4]) else self.path          clientFactory = self.proxyClientFactoryClass(              request.method,              rest,              request.clientproto,              request.getAllHeaders(),              request.content.read(),              request,          )          self.reactor.connectTCP(self.host, port, clientFactory)          return NOT_DONE_YET      class NotebookProxy(object, metaclass=_Singleton):      def __init__(self, gui: "Gui", listening_port: int) -> None:          self._listening_port = listening_port          self._gui = gui          self._is_running = False        def run(self):          if self._is_running:              return          host = self._gui._get_config("host", "127.0.0.1")          port = self._listening_port          if _is_port_open(host, port):              raise ConnectionError(                  f"Port {port} is already opened on {host}. You have another server application running on the same port."  # noqa: E501              )          site = Site(_TaipyReverseProxyResource(host, b"", self._gui))          reactor.listenTCP(port, site)          Thread(target=reactor.run, args=(False,)).start()          self._is_running = True        def stop(self):          if not self._is_running:              return          self._is_running = False          reactor.stop()


import typing as t  from operator import attrgetter    if t.TYPE_CHECKING:      from ..gui import Gui      def _getscopeattr(gui: "Gui", name: str, *more) -> t.Any:      if more:          return getattr(gui._get_data_scope(), name, more[0])      return getattr(gui._get_data_scope(), name)      def _getscopeattr_drill(gui: "Gui", name: str) -> t.Any:      return attrgetter(name)(gui._get_data_scope())      def _setscopeattr(gui: "Gui", name: str, value: t.Any):      if gui._is_broadcasting():          for scope in gui._get_all_data_scopes().values():              setattr(scope, name, value)      else:          setattr(gui._get_data_scope(), name, value)      def _setscopeattr_drill(gui: "Gui", name: str, value: t.Any):      if gui._is_broadcasting():          for scope in gui._get_all_data_scopes().values():              _attrsetter(scope, name, value)      else:          _attrsetter(gui._get_data_scope(), name, value)      def _hasscopeattr(gui: "Gui", name: str) -> bool:      return hasattr(gui._get_data_scope(), name)      def _delscopeattr(gui: "Gui", name: str):      delattr(gui._get_data_scope(), name)      def _attrsetter(obj: object, attr_str: str, value: object) -> None:      var_name_split = attr_str.split(sep=".")      for i in range(len(var_name_split) - 1):          sub_name = var_name_split[i]          obj = getattr(obj, sub_name)      setattr(obj, var_name_split[-1], value)


import typing as t      def _get_css_var_value(value: t.Any) -> str:      if isinstance(value, str):          if " " in value:              return f'"{value}"'          return value      if isinstance(value, int):          return f"{value}px"      return f"{value}"


import typing as t  from types import ModuleType    from ..page import Page      def _get_page_from_module(module: ModuleType) -> t.Optional[Page]:      return next((v for v in vars(module).values() if isinstance(v, Page)), None)


from __future__ import annotations    import typing as t    if t.TYPE_CHECKING:      from ..gui import Gui      def _varname_from_content(gui: Gui, content: str) -> t.Optional[str]:      return next((k for k, v in gui._get_locals_bind().items() if isinstance(v, str) and v == content), None)


from __future__ import annotations    import contextlib  import typing as t    from flask import g      class _LocalsContext:      __ctx_g_name = "locals_context"        def __init__(self) -> None:          self.__default_module: str = ""          self._lc_stack: t.List[str] = []          self._locals_map: t.Dict[str, t.Dict[str, t.Any]] = {}        def set_default(self, default: t.Dict[str, t.Any], default_module_name: str = "") -> None:          self.__default_module = default_module_name          self._locals_map[self.__default_module] = default        def get_default(self) -> t.Dict[str, t.Any]:          return self._locals_map[self.__default_module]        def get_all_keys(self) -> t.Set[str]:          keys = set()          for v in self._locals_map.values():              for i in v.keys():                  keys.add(i)          return keys        def get_all_context(self):          return self._locals_map.keys()        def add(self, context: t.Optional[str], locals_dict: t.Optional[t.Dict[str, t.Any]]):          if context is not None and locals_dict is not None and context not in self._locals_map:              self._locals_map[context] = locals_dict        @contextlib.contextmanager      def set_locals_context(self, context: t.Optional[str]) -> t.Iterator[None]:          try:              if context in self._locals_map:                  if hasattr(g, _LocalsContext.__ctx_g_name):                      self._lc_stack.append(getattr(g, _LocalsContext.__ctx_g_name))                  setattr(g, _LocalsContext.__ctx_g_name, context)              yield          finally:              if hasattr(g, _LocalsContext.__ctx_g_name):                  if len(self._lc_stack) > 0:                      setattr(g, _LocalsContext.__ctx_g_name, self._lc_stack.pop())                  else:                      delattr(g, _LocalsContext.__ctx_g_name)        def get_locals(self) -> t.Dict[str, t.Any]:          return self.get_default() if (context := self.get_context()) is None else self._locals_map[context]        def get_context(self) -> t.Optional[str]:          return getattr(g, _LocalsContext.__ctx_g_name) if hasattr(g, _LocalsContext.__ctx_g_name) else None        def is_default(self) -> bool:          return self.get_default() == self.get_locals()        def _get_locals_bind_from_context(self, context: t.Optional[str]):          if context is None:              context = self.__default_module          return self._locals_map[context]


from ._attributes import (      _delscopeattr,      _getscopeattr,      _getscopeattr_drill,      _hasscopeattr,      _setscopeattr,      _setscopeattr_drill,  )  from ._locals_context import _LocalsContext  from ._map_dict import _MapDict  from ._runtime_manager import _RuntimeManager  from ._variable_directory import _variable_decode, _variable_encode, _VariableDirectory  from .boolean import _is_boolean, _is_boolean_true  from .clientvarname import _get_broadcast_var_name, _get_client_var_name, _to_camel_case  from .datatype import _get_data_type  from .date import _date_to_string, _string_to_date  from .expr_var_name import _get_expr_var_name  from .filename import _get_non_existent_file_path  from .filter_locals import _filter_locals  from .get_imported_var import _get_imported_var  from .get_module_name import _get_module_name_from_frame, _get_module_name_from_imported_var  from .get_page_from_module import _get_page_from_module  from .getdatecolstrname import _RE_PD_TYPE, _get_date_col_str_name  from .html import _get_css_var_value  from .is_debugging import is_debugging  from .is_port_open import _is_port_open  from .isnotebook import _is_in_notebook  from .types import (      _TaipyBase,      _TaipyBool,      _TaipyContent,      _TaipyContentHtml,      _TaipyContentImage,      _TaipyData,      _TaipyDate,      _TaipyDateRange,      _TaipyDict,      _TaipyLoNumbers,      _TaipyLov,      _TaipyLovValue,      _TaipyNumber,  )  from .varnamefromcontent import _varname_from_content


import re  import typing as t    __expr_var_name_index: t.Dict[str, int] = {}  _RE_NOT_IN_VAR_NAME = r"[^A-Za-z0-9]+"      def _get_expr_var_name(expr: str) -> str:      var_name = re.sub(_RE_NOT_IN_VAR_NAME, "_", expr)      index = 0      if var_name in __expr_var_name_index.keys():          index = __expr_var_name_index[var_name]      __expr_var_name_index[var_name] = index + 1      return f"tp_{var_name}_{index}"      def _reset_expr_var_name():      __expr_var_name_index.clear()


import socket      def _is_port_open(host, port) -> bool:      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)      result = sock.connect_ex((host, port))      sock.close()      return result == 0


import json  import typing as t  from abc import ABC  from datetime import datetime    from .._warnings import _warn  from . import _date_to_string, _MapDict, _string_to_date, _variable_decode      class _TaipyBase(ABC):      __HOLDER_PREFIXES: t.Optional[t.List[str]] = None      _HOLDER_PREFIX = "_Tp"        def __init__(self, data: t.Any, hash_name: str) -> None:          self.__data = data          self.__hash_name = hash_name        def get(self):          return self.__data        def get_name(self):          return self.__hash_name        def set(self, data: t.Any):          self.__data = data        def cast_value(self, value: t.Any):          return value        def _get_readable_name(self):          try:              name, mod = _variable_decode(                  self.__hash_name[5:] if self.__hash_name.startswith("tpec_") else self.__hash_name              )              return name if mod is None or mod == "__main__" else f"{mod}.{name}"          except BaseException:              return self.__hash_name        @staticmethod      def get_hash():          return NotImplementedError        @staticmethod      def _get_holder_prefixes() -> t.List[str]:          if _TaipyBase.__HOLDER_PREFIXES is None:              _TaipyBase.__HOLDER_PREFIXES = [cls.get_hash() + "_" for cls in _TaipyBase.__subclasses__()]          return _TaipyBase.__HOLDER_PREFIXES      class _TaipyData(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "D"      class _TaipyBool(_TaipyBase):      def get(self):          return self.cast_value(super().get())        def cast_value(self, value: t.Any):          return bool(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "B"      class _TaipyNumber(_TaipyBase):      def get(self):          try:              return float(super().get())          except Exception as e:              raise TypeError(f"Variable '{self._get_readable_name()}' should hold a number: {e}")        def cast_value(self, value: t.Any):          if isinstance(value, str):              try:                  return float(value) if value else 0.0              except Exception as e:                  _warn(f"{self._get_readable_name()}: Parsing {value} as float", e)                  return 0.0          return super().cast_value(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "N"      class _TaipyLoNumbers(_TaipyBase):      def cast_value(self, value: t.Any):          if isinstance(value, str):              try:                  return list(map(lambda f: float(f), value[1:-1].split(",")))              except Exception as e:                  _warn(f"{self._get_readable_name()}: Parsing {value} as an array of numbers", e)                  return []          return super().cast_value(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Ln"      class _TaipyDate(_TaipyBase):      def get(self):          val = super().get()          if isinstance(val, datetime):              val = _date_to_string(val)          elif val is not None:              val = str(val)          return val        def cast_value(self, value: t.Any):          if isinstance(value, str):              return _string_to_date(value)          return super().cast_value(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Dt"      class _TaipyDateRange(_TaipyBase):      def get(self):          val = super().get()          if isinstance(val, list):              return [_date_to_string(v) if isinstance(v, datetime) else None if v is None else str(v) for v in val]          return val        def cast_value(self, value: t.Any):          if isinstance(value, list):              return [_string_to_date(v) if isinstance(v, str) else str(v) for v in value]          return super().cast_value(value)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Dr"      class _TaipyLovValue(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Lv"      class _TaipyLov(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "L"      class _TaipyContent(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "C"      class _TaipyContentImage(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Ci"      class _TaipyContentHtml(_TaipyBase):      @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Ch"      class _TaipyDict(_TaipyBase):      def get(self):          val = super().get()          return json.dumps(val._dict if isinstance(val, _MapDict) else val)        @staticmethod      def get_hash():          return _TaipyBase._HOLDER_PREFIX + "Di"


import sys      def is_debugging() -> bool:      """NOT DOCUMENTED"""      return hasattr(sys, "gettrace") and sys.gettrace() is not None


import typing as t      def _is_boolean_true(s: t.Union[bool, str]) -> bool:      return (          s          if isinstance(s, bool)          else s.lower() in ["true", "1", "t", "y", "yes", "yeah", "sure"]          if isinstance(s, str)          else False      )      def _is_boolean(s: t.Any) -> bool:      if isinstance(s, bool):          return True      elif isinstance(s, str):          return s.lower() in ["true", "1", "t", "y", "yes", "yeah", "sure", "false", "0", "f", "no"]      else:          return False


_replace_dict = {".": "__", "[": "_SqrOp_", "]": "_SqrCl_"}      def _get_client_var_name(var_name: str) -> str:      for k, v in _replace_dict.items():          var_name = var_name.replace(k, v)      return var_name      def _to_camel_case(value: str, upcase_first=False) -> str:      if not isinstance(value, str):          raise Exception("_to_camel_case allows only string parameter")        if len(value) <= 1:          return value.lower()      value = value.replace("_", " ").title().replace(" ", "").replace("[", "_").replace("]", "_")      return value[0].lower() + value[1:] if not upcase_first else value      def _get_broadcast_var_name(s: str) -> str:      return _get_client_var_name(f"_bc_{s}")


import re  import typing as t    from .._warnings import _warn  from .boolean import _is_boolean, _is_boolean_true  from .clientvarname import _to_camel_case      def _get_column_desc(columns: t.Dict[str, t.Any], key: str) -> t.Optional[t.Dict[str, t.Any]]:      return next((x for x in columns.values() if x.get("dfid") == key), None)      def _get_name_indexed_property(attributes: t.Dict[str, t.Any], name: str) -> t.Dict[str, t.Any]:      ret = {}      index_re = re.compile(name + r"\[(.*)\]$")      for key in attributes.keys():          if m := index_re.match(key):              ret[m.group(1)] = attributes.get(key)      return ret      def _update_col_desc_from_indexed(      attributes: t.Dict[str, t.Any], columns: t.Dict[str, t.Any], name: str, elt_name: str  ):      col_value = _get_name_indexed_property(attributes, name)      for k, v in col_value.items():          if col_desc := next((x for x in columns.values() if x.get("dfid") == k), None):              if col_desc.get(_to_camel_case(name)) is None:                  col_desc[_to_camel_case(name)] = str(v)          else:              _warn(f"{elt_name}: {name}[{k}] is not in the list of displayed columns.")      def _enhance_columns(  # noqa: C901      attributes: t.Dict[str, t.Any], hash_names: t.Dict[str, str], columns: t.Dict[str, t.Any], elt_name: str  ):      _update_col_desc_from_indexed(attributes, columns, "nan_value", elt_name)      _update_col_desc_from_indexed(attributes, columns, "width", elt_name)      filters = _get_name_indexed_property(attributes, "filter")      for k, v in filters.items():          if _is_boolean_true(v):              if col_desc := _get_column_desc(columns, k):                  col_desc["filter"] = True              else:                  _warn(f"{elt_name}: filter[{k}] is not in the list of displayed columns.")      editables = _get_name_indexed_property(attributes, "editable")      for k, v in editables.items():          if _is_boolean(v):              if col_desc := _get_column_desc(columns, k):                  col_desc["notEditable"] = not _is_boolean_true(v)              else:                  _warn(f"{elt_name}: editable[{k}] is not in the list of displayed columns.")      group_by = _get_name_indexed_property(attributes, "group_by")      for k, v in group_by.items():          if _is_boolean_true(v):              if col_desc := _get_column_desc(columns, k):                  col_desc["groupBy"] = True              else:                  _warn(f"{elt_name}: group_by[{k}] is not in the list of displayed columns.")      apply = _get_name_indexed_property(attributes, "apply")      for k, v in apply.items():  # pragma: no cover          if col_desc := _get_column_desc(columns, k):              if callable(v):                  value = hash_names.get(f"apply[{k}]")              elif isinstance(v, str):                  value = v.strip()              else:                  _warn(f"{elt_name}: apply[{k}] should be a user or predefined function.")                  value = None              if value:                  col_desc["apply"] = value          else:              _warn(f"{elt_name}: apply[{k}] is not in the list of displayed columns.")      styles = _get_name_indexed_property(attributes, "style")      for k, v in styles.items():  # pragma: no cover          if col_desc := _get_column_desc(columns, k):              if callable(v):                  value = hash_names.get(f"style[{k}]")              elif isinstance(v, str):                  value = v.strip()              else:                  value = None              if value in columns.keys():                  _warn(f"{elt_name}: style[{k}]={value} cannot be a column's name.")              elif value:                  col_desc["style"] = value          else:              _warn(f"{elt_name}: style[{k}] is not in the list of displayed columns.")      tooltips = _get_name_indexed_property(attributes, "tooltip")      for k, v in tooltips.items():  # pragma: no cover          if col_desc := _get_column_desc(columns, k):              if callable(v):                  value = hash_names.get(f"tooltip[{k}]")              elif isinstance(v, str):                  value = v.strip()              else:                  value = None              if value in columns.keys():                  _warn(f"{elt_name}: tooltip[{k}]={value} cannot be a column's name.")              elif value:                  col_desc["tooltip"] = value          else:              _warn(f"{elt_name}: tooltip[{k}] is not in the list of displayed columns.")      return columns


import typing as t  from datetime import datetime  from random import random    from ..data.data_scope import _DataScopes  from ._map_dict import _MapDict    if t.TYPE_CHECKING:      from ..gui import Gui      class _Bindings:      def __init__(self, gui: "Gui") -> None:          self.__gui = gui          self.__scopes = _DataScopes()        def _bind(self, name: str, value: t.Any) -> None:          if hasattr(self, name):              raise ValueError(f"Variable '{name}' is already bound")          if not name.isidentifier():              raise ValueError(f"Variable name '{name}' is invalid")          if isinstance(value, dict):              setattr(self._get_data_scope(), name, _MapDict(value))          else:              setattr(self._get_data_scope(), name, value)          # prop = property(self.__value_getter(name), self.__value_setter(name))          setattr(_Bindings, name, self.__get_property(name))        def __get_property(self, name):          def __setter(ud: _Bindings, value: t.Any):              if isinstance(value, dict):                  value = _MapDict(value, None)              ud.__gui._update_var(name, value)            def __getter(ud: _Bindings) -> t.Any:              value = getattr(ud._get_data_scope(), name)              if isinstance(value, _MapDict):                  return _MapDict(value._dict, lambda k, v: ud.__gui._update_var(f"{name}.{k}", v))              else:                  return value            return property(__getter, __setter)  # Getter, Setter        def _set_single_client(self, value: bool) -> None:          self.__scopes.set_single_client(value)        def _is_single_client(self) -> bool:          return self.__scopes.is_single_client()        def _get_or_create_scope(self, id: str):          create = not id          if create:              id = f"{datetime.now().strftime('%Y%m%d%H%M%S%f')}-{random()}"              self.__gui._send_ws_id(id)          self.__scopes.create_scope(id)          return id, create        def _new_scopes(self):          self.__scopes = _DataScopes()        def _get_data_scope(self):          return self.__scopes.get_scope(self.__gui._get_client_id())        def _get_all_scopes(self):          return self.__scopes.get_all_scopes()


import re  import typing as t  from types import FrameType    from ._locals_context import _LocalsContext  from .get_imported_var import _get_imported_var  from .get_module_name import _get_module_name_from_frame, _get_module_name_from_imported_var      class _VariableDirectory:      def __init__(self, locals_context: _LocalsContext):          self._locals_context = locals_context          self._default_module = ""          self._var_dir: t.Dict[str, t.Dict] = {}          self._var_head: t.Dict[str, t.List[t.Tuple[str, str]]] = {}          self._imported_var_dir: t.Dict[str, t.List[t.Tuple[str, str, str]]] = {}        def set_default(self, frame: FrameType) -> None:          self._default_module = _get_module_name_from_frame(frame)          self.add_frame(frame)        def add_frame(self, frame: t.Optional[FrameType]) -> None:          if frame is None:              return          module_name = _get_module_name_from_frame(frame)          if module_name not in self._imported_var_dir:              imported_var_list = _get_imported_var(frame)              self._imported_var_dir[module_name] = imported_var_list        def pre_process_module_import_all(self) -> None:          for imported_dir in self._imported_var_dir.values():              additional_var_list: t.List[t.Tuple[str, str, str]] = []              for name, asname, module in imported_dir:                  if name != "*" or asname != "*":                      continue                  if module not in self._locals_context._locals_map.keys():                      continue                  with self._locals_context.set_locals_context(module):                      additional_var_list.extend(                          (v, v, module) for v in self._locals_context.get_locals().keys() if not v.startswith("_")                      )              imported_dir.extend(additional_var_list)        def process_imported_var(self) -> None:          self.pre_process_module_import_all()          default_imported_dir = self._imported_var_dir[self._default_module]          with self._locals_context.set_locals_context(self._default_module):              for name, asname, module in default_imported_dir:                  if name == "*" and asname == "*":                      continue                  imported_module_name = _get_module_name_from_imported_var(                      name, self._locals_context.get_locals().get(asname, None), module                  )                  temp_var_name = self.add_var(asname, self._default_module)                  self.add_var(name, imported_module_name, temp_var_name)            for k, v in self._imported_var_dir.items():              with self._locals_context.set_locals_context(k):                  for name, asname, module in v:                      if name == "*" and asname == "*":                          continue                      imported_module_name = _get_module_name_from_imported_var(                          name, self._locals_context.get_locals().get(asname, None), module                      )                      var_name = self.get_var(name, imported_module_name)                      var_asname = self.get_var(asname, k)                      if var_name is None and var_asname is None:                          temp_var_name = self.add_var(asname, k)                          self.add_var(name, imported_module_name, temp_var_name)                      elif var_name is not None:                          self.add_var(asname, k, var_name)                      else:                          self.add_var(name, imported_module_name, var_asname)        def add_var(self, name: str, module: t.Optional[str], var_name: t.Optional[str] = None) -> str:          if module is None:              module = self._default_module          if gv := self.get_var(name, module):              return gv          var_encode = _variable_encode(name, module) if module != self._default_module else name          if var_name is None:              var_name = var_encode          self.__add_var_head(name, module, var_name)          if var_encode != var_name:              var_name_decode, module_decode = _variable_decode(var_name)              if module_decode is None:                  module_decode = self._default_module              self.__add_var_head(var_name_decode, module_decode, var_encode)          if name not in self._var_dir:              self._var_dir[name] = {module: var_name}          else:              self._var_dir[name][module] = var_name          return var_name        def __add_var_head(self, name: str, module: str, var_head: str) -> None:          if var_head not in self._var_head:              self._var_head[var_head] = [(name, module)]          else:              self._var_head[var_head].append((name, module))        def get_var(self, name: str, module: str) -> t.Optional[str]:          if name in self._var_dir and module in self._var_dir[name]:              return self._var_dir[name][module]          return None      _MODULE_NAME_MAP: t.List[str] = []  _MODULE_ID = "_TPMDL_"  _RE_TPMDL_DECODE = re.compile(r"(.*?)" + _MODULE_ID + r"(\d+)$")      def _variable_encode(var_name: str, module_name: t.Optional[str]):      if module_name is None:          return var_name      if module_name not in _MODULE_NAME_MAP:          _MODULE_NAME_MAP.append(module_name)      return f"{var_name}{_MODULE_ID}{_MODULE_NAME_MAP.index(module_name)}"      def _variable_decode(var_name: str):      from ._evaluator import _Evaluator        if result := _RE_TPMDL_DECODE.match(var_name):          return _Evaluator._expr_decode(str(result[1])), _MODULE_NAME_MAP[int(result[2])]      return _Evaluator._expr_decode(var_name), None      def _reset_name_map():      _MODULE_NAME_MAP.clear()


from typing import Dict      class _Singleton(type):      _instances: Dict = {}        def __call__(self, *args, **kwargs):          if self not in self._instances:              self._instances[self] = super(_Singleton, self).__call__(*args, **kwargs)          return self._instances[self]


import re    import pandas as pd      def _get_data_type(value):      if pd.api.types.is_bool_dtype(value):          return "bool"      elif pd.api.types.is_integer_dtype(value):          return "int"      elif pd.api.types.is_float_dtype(value):          return "float"      return re.match(r"^<class '(.*\.)?(.*?)(\d\d)?'>", str(type(value))).group(2)


import ast  import inspect  import typing as t  from types import FrameType      def _get_imported_var(frame: FrameType) -> t.List[t.Tuple[str, str, str]]:      st = ast.parse(inspect.getsource(frame))      var_list: t.List[t.Tuple[str, str, str]] = []      for node in ast.walk(st):          if isinstance(node, ast.ImportFrom):              # get the imported element as (name, asname, module)              # ex: from module1 import a as x --> ("a", "x", "module1")              var_list.extend(                  (                      child_node.name,                      child_node.asname if child_node.asname is not None else child_node.name,                      node.module or "",                  )                  for child_node in node.names              )      return var_list


import re  import typing as t  from datetime import date, datetime, time    from dateutil import parser  from pytz import utc    from .._warnings import _warn      def _date_to_string(date_val: t.Union[datetime, date, time]) -> str:      if isinstance(date_val, datetime):          # return date.isoformat() + 'Z', if possible          try:              return date_val.astimezone(utc).isoformat()          except Exception as e:              # astimezone() fails on Windows for pre-epoch times              # See https://bugs.python.org/issue36759              _warn("Exception raised converting date to ISO 8601", e)      return date_val.isoformat()      def _string_to_date(date_str: str) -> t.Union[datetime, date]:      # return datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ')      # return datetime.fromisoformat(date_str)      date = parser.parse(date_str)      date_regex = r"^[A-Z][a-z]{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{2} \d{4}$"      return date.date() if re.match(date_regex, date_str) else date


from importlib import util      def _is_in_notebook():  # pragma: no cover      try:          if not util.find_spec("IPython"):              return False            from IPython import get_ipython            ipython = get_ipython()            if ipython is None or "IPKernelApp" not in ipython.config:              return False      except (ImportError, AttributeError):          return False      return True


import typing as t  from pathlib import Path      def _get_non_existent_file_path(dir_path: Path, file_name: str) -> Path:      if not file_name:          file_name = "taipy_file.bin"      file_path = dir_path / file_name      index = 0      file_stem = file_path.stem      file_suffix = file_path.suffix      while file_path.exists():          file_path = dir_path / f"{file_stem}.{index}{file_suffix}"          index += 1      return file_path


import re  import typing as t    _RE_PD_TYPE = re.compile(r"^([^\s\d\[]+)(\d+)(\[(.*,\s(\S+))\])?")      def _get_date_col_str_name(columns: t.List[str], col: str) -> str:      suffix = "_str"      while col + suffix in columns:          suffix += "_"      return col + suffix


import typing as t    import numpy  import pandas as pd    from ..gui import Gui  from .data_format import _DataFormat  from .pandas_data_accessor import _PandasDataAccessor      class _NumpyDataAccessor(_PandasDataAccessor):      __types = (numpy.ndarray,)        @staticmethod      def get_supported_classes() -> t.List[str]:          return [t.__name__ for t in _NumpyDataAccessor.__types]  # type: ignore        def __get_dataframe(self, value: t.Any) -> pd.DataFrame:          return pd.DataFrame(value)        def get_col_types(self, var_name: str, value: t.Any) -> t.Union[None, t.Dict[str, str]]:  # type: ignore          if isinstance(value, _NumpyDataAccessor.__types):  # type: ignore              return super().get_col_types(var_name, self.__get_dataframe(value))          return None        def get_data(  # noqa: C901          self, guiApp: Gui, var_name: str, value: t.Any, payload: t.Dict[str, t.Any], data_format: _DataFormat      ) -> t.Dict[str, t.Any]:          if isinstance(value, _NumpyDataAccessor.__types):  # type: ignore              return super().get_data(guiApp, var_name, self.__get_dataframe(value), payload, data_format)          return {}


import typing as t    import pandas as pd    from ..gui import Gui  from ..utils import _MapDict  from .data_format import _DataFormat  from .pandas_data_accessor import _PandasDataAccessor      class _ArrayDictDataAccessor(_PandasDataAccessor):      __types = (dict, list, tuple, _MapDict)        @staticmethod      def get_supported_classes() -> t.List[str]:          return [t.__name__ for t in _ArrayDictDataAccessor.__types]  # type: ignore        def __get_dataframe(self, value: t.Any) -> t.Union[t.List[pd.DataFrame], pd.DataFrame]:          if isinstance(value, list):              if not value or isinstance(value[0], (str, int, float, bool)):                  return pd.DataFrame({"0": value})              types = {type(x) for x in value}              if len(types) == 1:                  type_elt = next(iter(types), None)                  if type_elt == list:                      lengths = {len(x) for x in value}                      return (                          pd.DataFrame(value)                          if len(lengths) == 1                          else [pd.DataFrame({f"{i}/0": v}) for i, v in enumerate(value)]                      )                  elif type_elt == dict:                      return [pd.DataFrame(v) for v in value]                  elif type_elt == _MapDict:                      return [pd.DataFrame(v._dict) for v in value]                  elif type_elt == pd.DataFrame:                      return value                elif len(types) == 2 and list in types and pd.DataFrame in types:                  return [v if isinstance(v, pd.DataFrame) else pd.DataFrame({f"{i}/0": v}) for i, v in enumerate(value)]          elif isinstance(value, _MapDict):              return pd.DataFrame(value._dict)          return pd.DataFrame(value)        def get_col_types(self, var_name: str, value: t.Any) -> t.Union[None, t.Dict[str, str]]:  # type: ignore          if isinstance(value, _ArrayDictDataAccessor.__types):  # type: ignore              return super().get_col_types(var_name, self.__get_dataframe(value))          return None        def get_data(  # noqa: C901          self, guiApp: Gui, var_name: str, value: t.Any, payload: t.Dict[str, t.Any], data_format: _DataFormat      ) -> t.Dict[str, t.Any]:          if isinstance(value, _ArrayDictDataAccessor.__types):  # type: ignore              return super().get_data(guiApp, var_name, self.__get_dataframe(value), payload, data_format)          return {}


from .data_accessor import _DataAccessor  from .decimator import LTTB, RDP, MinMaxDecimator, ScatterDecimator  from .utils import Decimator


import inspect  import typing as t  from abc import ABC, abstractmethod    from .._warnings import _warn  from ..utils import _TaipyData  from .data_format import _DataFormat      class _DataAccessor(ABC):      _WS_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"        @staticmethod      @abstractmethod      def get_supported_classes() -> t.List[str]:          pass        @abstractmethod      def get_data(          self, guiApp: t.Any, var_name: str, value: t.Any, payload: t.Dict[str, t.Any], data_format: _DataFormat      ) -> t.Dict[str, t.Any]:          pass        @abstractmethod      def get_col_types(self, var_name: str, value: t.Any) -> t.Dict[str, str]:          pass      class _InvalidDataAccessor(_DataAccessor):      @staticmethod      def get_supported_classes() -> t.List[str]:          return [type(None).__name__]        def get_data(          self, guiApp: t.Any, var_name: str, value: t.Any, payload: t.Dict[str, t.Any], data_format: _DataFormat      ) -> t.Dict[str, t.Any]:          return {}        def get_col_types(self, var_name: str, value: t.Any) -> t.Dict[str, str]:          return {}      class _DataAccessors(object):      def __init__(self) -> None:          self.__access_4_type: t.Dict[str, _DataAccessor] = {}            self.__invalid_data_accessor = _InvalidDataAccessor()            self.__data_format = _DataFormat.JSON            from .array_dict_data_accessor import _ArrayDictDataAccessor          from .numpy_data_accessor import _NumpyDataAccessor          from .pandas_data_accessor import _PandasDataAccessor            self._register(_PandasDataAccessor)          self._register(_ArrayDictDataAccessor)          self._register(_NumpyDataAccessor)        def _register(self, cls: t.Type[_DataAccessor]) -> None:          if not inspect.isclass(cls):              raise AttributeError("The argument of 'DataAccessors.register' should be a class")          if not issubclass(cls, _DataAccessor):              raise TypeError(f"Class {cls.__name__} is not a subclass of DataAccessor")          names = cls.get_supported_classes()          if not names:              raise TypeError(f"method {cls.__name__}.get_supported_classes returned an invalid value")          # check existence          inst: t.Optional[_DataAccessor] = None          for name in names:              inst = self.__access_4_type.get(name)              if inst:                  break          if inst is None:              try:                  inst = cls()              except Exception as e:                  raise TypeError(f"Class {cls.__name__} cannot be instanciated") from e              if inst:                  for name in names:                      self.__access_4_type[name] = inst  # type: ignore        def __get_instance(self, value: _TaipyData) -> _DataAccessor:  # type: ignore          value = value.get()          access = self.__access_4_type.get(type(value).__name__)          if access is None:              _warn(f"Can't find Data Accessor for type {type(value).__name__}.")              return self.__invalid_data_accessor          return access        def _get_data(          self, guiApp: t.Any, var_name: str, value: _TaipyData, payload: t.Dict[str, t.Any]      ) -> t.Dict[str, t.Any]:          return self.__get_instance(value).get_data(guiApp, var_name, value.get(), payload, self.__data_format)        def _get_col_types(self, var_name: str, value: _TaipyData) -> t.Dict[str, str]:          return self.__get_instance(value).get_col_types(var_name, value.get())        def _set_data_format(self, data_format: _DataFormat):          self.__data_format = data_format


from __future__ import annotations    import typing as t  from abc import ABC, abstractmethod    import numpy as np    from .._warnings import _warn    if t.TYPE_CHECKING:      import pandas as pd      class Decimator(ABC):      """Base class for decimating chart data.        *Decimating* is the term used to name the process of reducing the number of      data points displayed in charts while retaining the overall shape of the traces.      `Decimator` is a base class that does decimation on data sets.        Taipy GUI comes out-of-the-box with several implementation of this class for      different use cases.      """        _CHART_MODES: t.List[str] = []        def __init__(self, threshold: t.Optional[int], zoom: t.Optional[bool]) -> None:          """Initialize a new `Decimator`.            Arguments:              threshold (Optional[int]): The minimum amount of data points before the                  decimator class is applied.              zoom (Optional[bool]): set to True to reapply the decimation                  when zoom or re-layout events are triggered.          """          super().__init__()          self.threshold = threshold          self._zoom = zoom if zoom is not None else True        def _is_applicable(self, data: t.Any, nb_rows_max: int, chart_mode: str):          if chart_mode not in self._CHART_MODES:              _warn(f"{type(self).__name__} is only applicable for {' '.join(self._CHART_MODES)}.")              return False          if self.threshold is None:              if nb_rows_max < len(data):                  return True          elif self.threshold < len(data):              return True          return False        @abstractmethod      def decimate(self, data: np.ndarray, payload: t.Dict[str, t.Any]) -> np.ndarray:          """Decimate function.            This method is executed when the appropriate conditions specified in the          constructor are met. This function implements the algorithm that determines          which data points are kept or dropped.            Arguments:              data (numpy.array): An array containing all the data points represented as                  tuples.              payload (Dict[str, any]): additional information on charts that is provided                  at runtime.            Returns:              An array of Boolean mask values. The array should set True or False for each                  of its indexes where True indicates that the corresponding data point                  from *data* should be preserved, or False requires that this                  data point be dropped.          """          return NotImplementedError  # type: ignore      def _df_data_filter(      dataframe: pd.DataFrame,      x_column_name: t.Optional[str],      y_column_name: str,      z_column_name: str,      decimator: Decimator,      payload: t.Dict[str, t.Any],      is_copied: bool,  ):      df = dataframe.copy() if not is_copied else dataframe      if not x_column_name:          index = 0          while f"tAiPy_index_{index}" in df.columns:              index += 1          x_column_name = f"tAiPy_index_{index}"          df[x_column_name] = df.index      column_list = [x_column_name, y_column_name, z_column_name] if z_column_name else [x_column_name, y_column_name]      points = df[column_list].to_numpy()      mask = decimator.decimate(points, payload)      return df[mask], is_copied      def _df_relayout(      dataframe: pd.DataFrame,      x_column: t.Optional[str],      y_column: str,      chart_mode: str,      x0: t.Optional[float],      x1: t.Optional[float],      y0: t.Optional[float],      y1: t.Optional[float],      is_copied: bool,  ):      if chart_mode not in ["lines+markers", "markers"]:          return dataframe, is_copied      # if chart data is invalid      if x0 is None or x1 is None or y0 is None or y1 is None:          return dataframe, is_copied      df = dataframe.copy() if not is_copied else dataframe      is_copied = True      has_x_col = True        if not x_column:          index = 0          while f"tAiPy_index_{index}" in df.columns:              index += 1          x_column = f"tAiPy_index_{index}"          df[x_column] = df.index          has_x_col = False        # if chart_mode is empty      if chart_mode == "lines+markers":          # only filter by x column          df = df.loc[(df[x_column] > x0) & (df[x_column] < x1)]      else:          # filter by both x and y columns          df = df.loc[(df[x_column] > x0) & (df[x_column] < x1) & (df[y_column] > y0) & (df[y_column] < y1)]  # noqa      if not has_x_col:          df.drop(x_column, axis=1, inplace=True)      return df, is_copied


from enum import Enum      class _DataFormat(Enum):      JSON = "JSON"      APACHE_ARROW = "ARROW"