import inspect  import typing as t  from contextlib import nullcontext  from operator import attrgetter  from types import FrameType    from flask import has_app_context  from flask.ctx import AppContext    from .utils import _get_module_name_from_frame, _is_in_notebook  from .utils._attributes import _attrsetter    if t.TYPE_CHECKING:      from .gui import Gui      class State:      """Accessor to the bound variables from callbacks.        `State` is used when you need to access the value of variables      bound to visual elements (see [Binding](../gui/binding.md)).
      Because each browser connected to the application server may represent and      modify any variable at any moment as the result of user interaction, each      connection holds its own set of variables along with their values. We call      the set of these the application variables the application _state_, as seen      by a given client.        Each callback (see [Callbacks](../gui/callbacks.md)) receives a specific      instance of the `State` class, where you can find all the variables bound to      visual elements in your application.        Note that `State` also is a Python Context Manager: In situations where you      have several variables to update, it is more clear and more efficient to assign      the variable values in a `with` construct:      ```py      def my_callback(state, ...):        ...        with state as s:          s.var1 = value1          s.var2 = value2        ...      ```        You cannot set a variable in the context of a lambda function because Python      prevents any use of the assignment operator.
      You can, however, use the `assign()` method on the state that the lambda function      receives, so you can work around this limitation:        Here is how you could define a button that changes the value of a variable      directly in a page expressed using Markdown:      ```         <|Set variable|button|on_action={lambda s: s.assign("var_name", new_value)}|>      ```      This would be strictly similar to the Markdown line:      ```         <|Set variable|button|on_action=change_variable|>      ```      with the Python code:      ```py      def change_variable(state):          state.var_name = new_value      ```      """        __gui_attr = "_gui"      __attrs = (          __gui_attr,          "_user_var_list",          "_context_list",      )      __methods = (          "assign",          "broadcast",          "get_gui",          "refresh",          "_set_context",          "_notebook_context",          "_get_placeholder",          "_set_placeholder",          "_get_gui_attr",          "_get_placeholder_attrs",          "_add_attribute",      )      __placeholder_attrs = (          "_taipy_p1",          "_current_context",      )      __excluded_attrs = __attrs + __methods + __placeholder_attrs        def __init__(self, gui: "Gui", var_list: t.Iterable[str], context_list: t.Iterable[str]) -> None:          super().__setattr__(State.__attrs[1], list(State.__filter_var_list(var_list, State.__excluded_attrs)))          super().__setattr__(State.__attrs[2], list(context_list))          super().__setattr__(State.__attrs[0], gui)        def get_gui(self) -> "Gui":          """Return the Gui instance for this state object.            Returns:              Gui: The Gui instance for this state object.          """          return super().__getattribute__(State.__gui_attr)        @staticmethod      def __filter_var_list(var_list: t.Iterable[str], excluded_attrs: t.Iterable[str]) -> t.Iterable[str]:          return filter(lambda n: n not in excluded_attrs, var_list)        def __getattribute__(self, name: str) -> t.Any:          if name in State.__methods:              return super().__getattribute__(name)          gui: "Gui" = self.get_gui()          if name == State.__gui_attr:              return gui          if name in State.__excluded_attrs:              raise AttributeError(f"Variable '{name}' is protected and is not accessible.")          if gui._is_in_brdcst_callback() and (              name not in gui._get_shared_variables() and not gui._bindings()._is_single_client()          ):              raise AttributeError(f"Variable '{name}' is not available to be accessed in shared callback.")          if name not in super().__getattribute__(State.__attrs[1]):              raise AttributeError(f"Variable '{name}' is not defined.")          with self._notebook_context(gui), self._set_context(gui):              encoded_name = gui._bind_var(name)              return getattr(gui._bindings(), encoded_name)        def __setattr__(self, name: str, value: t.Any) -> None:          gui: "Gui" = super().__getattribute__(State.__gui_attr)          if gui._is_in_brdcst_callback() and (              name not in gui._get_shared_variables() and not gui._bindings()._is_single_client()          ):              raise AttributeError(f"Variable '{name}' is not available to be accessed in shared callback.")          if name not in super().__getattribute__(State.__attrs[1]):              raise AttributeError(f"Variable '{name}' is not accessible.")          with self._notebook_context(gui), self._set_context(gui):              encoded_name = gui._bind_var(name)              setattr(gui._bindings(), encoded_name, value)        def __getitem__(self, key: str):          context = key if key in super().__getattribute__(State.__attrs[2]) else None          if context is None:              gui: "Gui" = super().__getattribute__(State.__gui_attr)              page_ctx = gui._get_page_context(key)              context = page_ctx if page_ctx is not None else None          if context is None:              raise RuntimeError(f"Can't resolve context '{key}' from state object")          self._set_placeholder(State.__placeholder_attrs[1], context)          return self        def _set_context(self, gui: "Gui") -> t.ContextManager[None]:          if (pl_ctx := self._get_placeholder(State.__placeholder_attrs[1])) is not None:              self._set_placeholder(State.__placeholder_attrs[1], None)              if pl_ctx != gui._get_locals_context():                  return gui._set_locals_context(pl_ctx)          if len(inspect.stack()) > 1:              ctx = _get_module_name_from_frame(t.cast(FrameType, t.cast(FrameType, inspect.stack()[2].frame)))              current_context = gui._get_locals_context()              # ignore context if the current one starts with the new one (to resolve for class modules)              if ctx != current_context and not current_context.startswith(str(ctx)):                  return gui._set_locals_context(ctx)          return nullcontext()        def _notebook_context(self, gui: "Gui"):          return gui.get_flask_app().app_context() if not has_app_context() and _is_in_notebook() else nullcontext()        def _get_placeholder(self, name: str):          if name in State.__placeholder_attrs:              try:                  return super().__getattribute__(name)              except AttributeError:                  return None          return None        def _set_placeholder(self, name: str, value: t.Any):          if name in State.__placeholder_attrs:              super().__setattr__(name, value)        def _get_placeholder_attrs(self):          return State.__placeholder_attrs        def _add_attribute(self, name: str, default_value: t.Optional[t.Any] = None) -> bool:          attrs: t.List[str] = super().__getattribute__(State.__attrs[1])          if name not in attrs:              attrs.append(name)              gui = super().__getattribute__(State.__gui_attr)              return gui._bind_var_val(name, default_value)          return False        def assign(self, name: str, value: t.Any) -> t.Any:          """Assign a value to a state variable.            This should be used only from within a lambda function used          as a callback in a visual element.            Arguments:              name (str): The variable name to assign to.              value (Any): The new variable value.            Returns:              Any: The previous value of the variable.          """          val = attrgetter(name)(self)          _attrsetter(self, name, value)          return val        def refresh(self, name: str):          """Refresh a state variable.            This allows to re-sync the user interface with a variable value.            Arguments:              name (str): The variable name to refresh.          """          val = attrgetter(name)(self)          _attrsetter(self, name, val)        def broadcast(self, name: str, value: t.Any):          """Update a variable on all clients.            All connected clients will receive an update of the variable called *name* with the          provided value, even if it is not shared.            Arguments:              name (str): The variable name to update.              value (Any): The new variable value.          """          gui: "Gui" = super().__getattribute__(State.__gui_attr)          with self._set_context(gui):              encoded_name = gui._bind_var(name)              gui._broadcast_all_clients(encoded_name, value)        def __enter__(self):          super().__getattribute__(State.__attrs[0]).__enter__()          return self        def __exit__(self, exc_type, exc_value, traceback):          return super().__getattribute__(State.__attrs[0]).__exit__(exc_type, exc_value, traceback)


import re  import sys  import typing as t  import xml.etree.ElementTree as etree  from abc import ABC, abstractmethod  from inspect import isclass  from pathlib import Path  from urllib.parse import urlencode    from .._renderers.builder import _Builder  from .._warnings import _warn  from ..types import PropertyType  from ..utils import _get_broadcast_var_name, _TaipyBase, _to_camel_case    if t.TYPE_CHECKING:      from ..gui import Gui      from ..state import State      class ElementProperty:      """      The declaration of a property of a visual element.        Each visual element property is described by an instance of `ElementProperty`.      This class holds the information on the name, type and default value for the      element property.      """        def __init__(          self,          property_type: PropertyType,          default_value: t.Optional[t.Any] = None,          js_name: t.Optional[str] = None,      ) -> None:          """Initializes a new custom property declaration for an `Element^`.            Arguments:              property_type (PropertyType): The type of this property.              default_value (Optional[Any]): The default value for this property. Default is None.              js_name (Optional[str]): The name of this property, in the front-end JavaScript code.
                  If unspecified, a camel case version of `name` is generated: for example, if `name` is                  "my_property_name", then this property is referred to as "myPropertyName" in the                  JavaScript code.          """          self.default_value = default_value          if property_type == PropertyType.broadcast:              if isinstance(default_value, str):                  self.default_value = _get_broadcast_var_name(default_value)              else:                  _warn("Element property with type 'broadcast' must define a string default value.")              self.property_type = PropertyType.react          else:              self.property_type = property_type          self._js_name = js_name          super().__init__()        def check(self, element_name: str, prop_name: str):          if not isinstance(prop_name, str) or not prop_name or not prop_name.isidentifier():              _warn(f"Property name '{prop_name}' is invalid for element '{element_name}'.")          if not isinstance(self.property_type, PropertyType) and not (              isclass(self.property_type) and issubclass(self.property_type, _TaipyBase)          ):              _warn(f"Property type '{self.property_type}' is invalid for element property '{element_name}.{prop_name}'.")        def _get_tuple(self, name: str) -> tuple:          return (name, self.property_type, self.default_value)        def get_js_name(self, name: str) -> str:          return self._js_name or _to_camel_case(name)      class Element:      """      The definition of a custom visual element.        An element is defined by its properties (name, type and default value) and      what the default property name is.      """        __RE_PROP_VAR = re.compile(r"<tp:prop:(\w+)>")        def __init__(          self,          default_property: str,          properties: t.Dict[str, ElementProperty],          react_component: t.Optional[str] = None,          render_xhtml: t.Optional[t.Callable[[t.Dict[str, t.Any]], str]] = None,          inner_properties: t.Optional[t.Dict[str, ElementProperty]] = None,      ) -> None:          """Initializes a new custom element declaration.            If *render_xhtml* is specified, then this is a static element, and          *react_component* is ignored.            Arguments:              default_property (str): the name of the default property for this element.              properties (List[ElementProperty]): The list of properties for this element.              inner_properties (Optional[List[ElementProperty]]): The optional list of inner properties for this element.
                  Default values are set/binded automatically.              react_component (Optional[str]): The name of the component to be created on the front-end.
                  If not specified, it is set to a camel case version of the element's name                  ("one_name" is transformed to "OneName").              render_xhtml (Optional[callable[[dict[str, Any]], str]]): A function that receives a                  dictionary containing the element's properties and their values                  and that must return a valid XHTML string.          """          self.default_attribute = default_property          self.attributes = properties          self.inner_properties = inner_properties          self.js_name = react_component          if callable(render_xhtml):              self._render_xhtml = render_xhtml          super().__init__()        def _get_js_name(self, name: str) -> str:          return self.js_name or _to_camel_case(name, True)        def check(self, name: str):          if not isinstance(name, str) or not name or not name.isidentifier():              _warn(f"Invalid element name: '{name}'.")          default_found = False          if self.attributes:              for prop_name, property in self.attributes.items():                  if isinstance(property, ElementProperty):                      property.check(name, prop_name)                      if not default_found:                          default_found = self.default_attribute == prop_name                  else:                      _warn(f"Property must inherit from 'ElementProperty' '{name}.{prop_name}'.")          if not default_found:              _warn(f"Element {name} has no default property.")        def _is_server_only(self):          return hasattr(self, "_render_xhtml") and callable(self._render_xhtml)        def _call_builder(          self,          name,          gui: "Gui",          properties: t.Optional[t.Dict[str, t.Any]],          lib: "ElementLibrary",          is_html: t.Optional[bool] = False,      ) -> t.Union[t.Any, t.Tuple[str, str]]:          attributes = properties if isinstance(properties, dict) else {}          if self.inner_properties:              self.attributes.update(self.inner_properties)              for prop, attr in self.inner_properties.items():                  val = attr.default_value                  if val:                      # handling property replacement in inner properties <tp:prop:...>                      while m := Element.__RE_PROP_VAR.search(val):                          var = attributes.get(m.group(1))                          hash_value = "None" if var is None else gui._evaluate_expr(var)                          val = val[: m.start()] + hash_value + val[m.end() :]                  attributes[prop] = val          # this modifies attributes          hash_names = _Builder._get_variable_hash_names(gui, attributes)  # variable replacement          # call user render if any          if self._is_server_only():              xhtml = self._render_xhtml(attributes)              try:                  xml_root = etree.fromstring(xhtml)                  if is_html:                      return xhtml, name                  else:                      return xml_root                except Exception as e:                  _warn(f"{name}.render_xhtml() did not return a valid XHTML string", e)                  return f"{name}.render_xhtml() did not return a valid XHTML string. {e}"          else:              default_attr: t.Optional[ElementProperty] = None              default_value = None              default_name = None              attrs = []              if self.attributes:                  for prop_name, property in self.attributes.items():                      if isinstance(property, ElementProperty):                          if self.default_attribute == prop_name:                              default_name = prop_name                              default_attr = property                              default_value = property.default_value                          else:                              attrs.append(property._get_tuple(prop_name))              elt_built = _Builder(                  gui=gui,                  control_type=name,                  element_name=f"{lib.get_js_module_name()}_{self._get_js_name(name)}",                  attributes=properties,                  hash_names=hash_names,                  lib_name=lib.get_name(),                  default_value=default_value,              )              if default_attr is not None:                  elt_built.set_value_and_default(                      var_name=default_name,                      var_type=default_attr.property_type,                      default_val=default_attr.default_value,                      with_default=default_attr.property_type != PropertyType.data,                  )              elt_built.set_attributes(attrs)              return elt_built._build_to_string() if is_html else elt_built.el      class ElementLibrary(ABC):      """      A library of user-defined visual elements.        An element library can declare any number of custom visual elements.        In order to use those elements you must register the element library      using the function `Gui.add_library()^`.        An element library can mix *static* and *dynamic* elements.      """        @abstractmethod      def get_elements(self) -> t.Dict[str, Element]:          """          Return the dictionary holding all visual element declarations.            The key for each of this dictionary's entry is the name of the element,          and the value is an instance of `Element^`.            The default implementation returns an empty dictionary, indicating that this library          contains no custom visual elements.          """          return {}        @abstractmethod      def get_name(self) -> str:          """          Return the library name.            This string is used for different purposes:            - It allows for finding the definition of visual elements when parsing the            page content.
            Custom elements are defined with the fragment `<|<library_name>.<element_name>|>` in            Markdown pages, and with the tag `<<library_name>:<element_name>>` in HTML pages.            - In element libraries that hold elements with dynamic properties (where JavaScript)            is involved, the name of the JavaScript module that has the front-end code is            derived from this name, as described in `(ElementLibrary.)get_js_module_name()^`.            Returns:              The name of this element library. This must be a valid Python identifier.            !!! note "Element libraries with the same name"              You can add different libraries that have the same name.
              This is useful in large projects where you want to split a potentially large number              of custom visual elements into different groups but still access them from your pages              using the same library name prefix.
              In this situation, you will have to implement `(ElementLibrary.)get_js_module_name()^`              because each JavaScript module will have to have a unique name.            """          return NotImplementedError  # type: ignore        def get_js_module_name(self) -> str:          """          Return the name of the JavaScript module.            The JavaScript module is the JavaScript file that contains all the front-end          code for this element library. Typically, the name of JavaScript modules uses camel case.
          This module name must be unique on the browser window scope: if your application uses          several custom element libraries, they must define a unique name for their JavaScript module.            The default implementation transforms the return value of `(ElementLibrary.)get_name()^` in          the following manner:            - The JavaScript module name is a camel case version of the element library name            (see `(ElementLibrary.)get_name()^`):              - If the library name is "library", the JavaScript module name defaults to "Library".              - If the library name is "myLibrary", the JavaScript module name defaults to "Mylibrary".          - If the element library name has underscore characters, each underscore-separated fragment is            considered as a distinct word:              - If the library name is "my_library", the JavaScript module name defaults to "MyLibrary".            Returns:              The name of the JavaScript module for this element library.
              The default implementation returns a camel case version of `self.get_name()`,              as described above.          """          return _to_camel_case(self.get_name(), True)        def get_scripts(self) -> t.List[str]:          """          Return the list of the mandatory script file pathnames.            If a script file pathname is an absolute URL it will be used as is.
          If it's not it will be passed to `(ElementLibrary.)get_resource()^` to retrieve a local          path to the resource.            The default implementation returns an empty list, indicating that this library contains          no custom visual elements with dynamic properties.            Returns:              A list of paths (relative to the element library Python implementation file or              absolute) to all JavaScript module files to be loaded on the front-end.
              The default implementation returns an empty list.          """          return []        def get_styles(self) -> t.List[str]:          """          TODO          Returns the list of resources names for the css stylesheets.          Defaults to []            """          return []        def get_resource(self, name: str) -> Path:          """          TODO          Defaults to return None?          Returns a path for a resource name.          Resource URL should be formed as /taipy-extension/<library_name>/<resource virtual path> with(see get_resource_url)          - <resource virtual path> being the `name` parameter          - <library_name> the value returned by `get_name()`            Arguments:              name (str): The name of the resource for which a local Path should be returned.          """          module_obj = sys.modules.get(self.__class__.__module__)          base = (Path(".") if module_obj is None else Path(module_obj.__file__).parent).resolve()  # type: ignore          base = base if base.exists() else Path(".").resolve()          file = (base / name).resolve()          if str(file).startswith(str(base)) and file.exists():              return file          else:              raise FileNotFoundError(f"Cannot access resource {file}.")        def get_resource_url(self, resource: str) -> str:          """TODO"""          from ..gui import Gui            return f"/{Gui._EXTENSION_ROOT}/{self.get_name()}/{resource}{self.get_query(resource)}"        def get_data(self, library_name: str, payload: t.Dict, var_name: str, value: t.Any) -> t.Optional[t.Dict]:          """          TODO          Called if implemented (i.e returns a dict).            Arguments:              library_name (str): The name of this library.              payload (dict): The payload send by the `createRequestDataUpdateAction()` front-end function.              var_name (str): The name of the variable holding the data.              value (any): The current value of the variable identified by *var_name*.          """          return None        def on_init(self, gui: "Gui") -> t.Optional[t.Tuple[str, t.Any]]:          """          Initialize this element library.            This method is invoked by `Gui.run()^`.            It allows to define variables that are accessible from elements          defined in this element library.            Arguments              gui: The `Gui^` instance.            Returns:              An optional tuple composed of a variable name (that *must* be a valid Python              identifier), associated with its value.
              This name can be used as the name of a variable accessible by the elements defined              in this library.
              This name must be unique across the entire application, which is a problem since              different element libraries might use the same symbol. A good development practice              is to make this variable name unique by prefixing it with the name of the element              library itself.          """          return None        def on_user_init(self, state: "State"):          """          Initialize user state on first access.            Arguments              state: The `State^` instance.          """          pass        def get_query(self, name: str) -> str:          """          Return an URL query depending on the resource name.
          Default implementation returns the version if defined.            Arguments:              name (str): The name of the resource for which a query should be returned.            Returns:              A string that holds the query part of an URL (starting with ?).          """          if version := self.get_version():              return f"?{urlencode({'v': version})}"          return ""        def get_version(self) -> t.Optional[str]:          """          The optional library version            Returns:              An optional string representing the library version.
              This version will be appended to the resource URL as a query arg (?v=<version>)          """          return None


from ..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  from enum import Enum    from .._renderers.utils import _get_columns_dict  from .._warnings import _warn  from ..types import PropertyType  from ..utils import _MapDict    if t.TYPE_CHECKING:      from ..gui import Gui      class _Chart_iprops(Enum):      x = 0      y = 1      z = 2      label = 3      text = 4      mode = 5      type = 6      color = 7      xaxis = 8      yaxis = 9      selected_color = 10      marker = 11      selected_marker = 12      orientation = 13      _name = 14      line = 15      text_anchor = 16      options = 17      lon = 18      lat = 19      base = 20      r = 21      theta = 22      close = 23      open = 24      high = 25      low = 26      locations = 27      values = 28      labels = 29      decimator = 30      measure = 31      parents = 32      __CHART_AXIS: t.Dict[str, t.Tuple[_Chart_iprops, ...]] = {      "bar": (_Chart_iprops.x, _Chart_iprops.y, _Chart_iprops.base),      "candlestick": (          _Chart_iprops.x,          _Chart_iprops.close,          _Chart_iprops.open,          _Chart_iprops.high,          _Chart_iprops.low,      ),      "choropleth": (_Chart_iprops.locations, _Chart_iprops.z),      "densitymapbox": (_Chart_iprops.lon, _Chart_iprops.lat, _Chart_iprops.z),      "funnelarea": (_Chart_iprops.values,),      "pie": (_Chart_iprops.values, _Chart_iprops.labels),      "scattergeo": (_Chart_iprops.lon, _Chart_iprops.lat),      "scattermapbox": (_Chart_iprops.lon, _Chart_iprops.lat),      "scatterpolar": (_Chart_iprops.r, _Chart_iprops.theta),      "scatterpolargl": (_Chart_iprops.r, _Chart_iprops.theta),      "treemap": (_Chart_iprops.labels, _Chart_iprops.parents, _Chart_iprops.values),      "waterfall": (_Chart_iprops.x, _Chart_iprops.y, _Chart_iprops.measure),  }  __CHART_DEFAULT_AXIS: t.Tuple[_Chart_iprops, ...] = (_Chart_iprops.x, _Chart_iprops.y, _Chart_iprops.z)  __CHART_MARKER_TO_COLS: t.Tuple[str, ...] = ("color", "size", "symbol", "opacity")  __CHART_NO_INDEX: t.Tuple[str, ...] = ("pie", "histogram", "heatmap", "funnelarea")  _CHART_NAMES: t.Tuple[str, ...] = tuple(e.name[1:] if e.name[0] == "_" else e.name for e in _Chart_iprops)      def __check_dict(values: t.List[t.Any], properties: t.Iterable[_Chart_iprops]) -> None:      for prop in properties:          if values[prop.value] is not None and not isinstance(values[prop.value], (dict, _MapDict)):              _warn(f"Property {prop.name} of chart control should be a dict.")              values[prop.value] = None      def __get_multiple_indexed_attributes(      attributes: t.Dict[str, t.Any], names: t.Iterable[str], index: t.Optional[int] = None  ) -> t.List[t.Optional[str]]:      names = names if index is None else [f"{n}[{index}]" for n in names]  # type: ignore      return [attributes.get(name) for name in names]      __RE_INDEXED_DATA = re.compile(r"^(\d+)\/(.*)")      def __get_col_from_indexed(col_name: str, idx: int) -> t.Optional[str]:      if re_res := __RE_INDEXED_DATA.search(col_name):          return col_name if str(idx) == re_res.group(1) else None      return col_name      def _build_chart_config(gui: "Gui", attributes: t.Dict[str, t.Any], col_types: t.Dict[str, str]):  # noqa: C901      default_type = attributes.get("_default_type", "scatter")      default_mode = attributes.get("_default_mode", "lines+markers")      trace = __get_multiple_indexed_attributes(attributes, _CHART_NAMES)      if not trace[_Chart_iprops.mode.value]:          trace[_Chart_iprops.mode.value] = default_mode      # type      if not trace[_Chart_iprops.type.value]:          trace[_Chart_iprops.type.value] = default_type      if not trace[_Chart_iprops.xaxis.value]:          trace[_Chart_iprops.xaxis.value] = "x"      if not trace[_Chart_iprops.yaxis.value]:          trace[_Chart_iprops.yaxis.value] = "y"      # Indexed properties: Check for arrays      for prop in _Chart_iprops:          values = trace[prop.value]          if isinstance(values, (list, tuple)) and len(values):              prop_name = prop.name[1:] if prop.name[0] == "_" else prop.name              for idx, val in enumerate(values):                  if idx == 0:                      trace[prop.value] = val                  if val is not None:                      indexed_prop = f"{prop_name}[{idx + 1}]"                      if attributes.get(indexed_prop) is None:                          attributes[indexed_prop] = val      # marker selected_marker options      __check_dict(trace, (_Chart_iprops.marker, _Chart_iprops.selected_marker, _Chart_iprops.options))      axis = []      traces: t.List[t.List[t.Optional[str]]] = []      idx = 1      indexed_trace = __get_multiple_indexed_attributes(attributes, _CHART_NAMES, idx)      if len([x for x in indexed_trace if x]):          while len([x for x in indexed_trace if x]):              axis.append(                  __CHART_AXIS.get(                      indexed_trace[_Chart_iprops.type.value] or trace[_Chart_iprops.type.value] or "",                      __CHART_DEFAULT_AXIS,                  )              )              # marker selected_marker options              __check_dict(indexed_trace, (_Chart_iprops.marker, _Chart_iprops.selected_marker, _Chart_iprops.options))              if trace[_Chart_iprops.decimator.value] and not indexed_trace[_Chart_iprops.decimator.value]:                  # copy the decimator only once                  indexed_trace[_Chart_iprops.decimator.value] = trace[_Chart_iprops.decimator.value]                  trace[_Chart_iprops.decimator.value] = None              traces.append([x or trace[i] for i, x in enumerate(indexed_trace)])              idx += 1              indexed_trace = __get_multiple_indexed_attributes(attributes, _CHART_NAMES, idx)      else:          traces.append(trace)          # axis names          axis.append(__CHART_AXIS.get(trace[_Chart_iprops.type.value] or "", __CHART_DEFAULT_AXIS))        # list of data columns name indexes with label text      dt_idx = tuple(e.value for e in (axis[0] + (_Chart_iprops.label, _Chart_iprops.text)))        # configure columns      columns: t.Set[str] = set()      for j, trace in enumerate(traces):          dt_idx = tuple(              e.value for e in (axis[j] if j < len(axis) else axis[0]) + (_Chart_iprops.label, _Chart_iprops.text)          )          columns.update([trace[i] or "" for i in dt_idx if trace[i]])      # add optionnal column if any      markers = [          t[_Chart_iprops.marker.value]          or ({"color": t[_Chart_iprops.color.value]} if t[_Chart_iprops.color.value] else None)          for t in traces      ]      opt_cols = set()      for m in markers:          if isinstance(m, (dict, _MapDict)):              for prop1 in __CHART_MARKER_TO_COLS:                  val = m.get(prop1)                  if isinstance(val, str) and val not in columns:                      opt_cols.add(val)        # Validate the column names      col_dict = _get_columns_dict(attributes.get("data"), list(columns), col_types, opt_columns=opt_cols)        # Manage Decimator      decimators: t.List[t.Optional[str]] = []      for tr in traces:          if tr[_Chart_iprops.decimator.value]:              cls = gui._get_user_instance(                  class_name=str(tr[_Chart_iprops.decimator.value]), class_type=PropertyType.decimator.value              )              if isinstance(cls, PropertyType.decimator.value):                  decimators.append(str(tr[_Chart_iprops.decimator.value]))                  continue          decimators.append(None)        # set default columns if not defined      icols = [[c2 for c2 in [__get_col_from_indexed(c1, i) for c1 in col_dict.keys()] if c2] for i in range(len(traces))]        for i, tr in enumerate(traces):          if i < len(axis):              used_cols = {tr[ax.value] for ax in axis[i] if tr[ax.value]}              unused_cols = [c for c in icols[i] if c not in used_cols]              if unused_cols and not any(tr[ax.value] for ax in axis[i]):                  traces[i] = list(                      v or (unused_cols.pop(0) if unused_cols and _Chart_iprops(j) in axis[i] else v)                      for j, v in enumerate(tr)                  )        if col_dict is not None:          reverse_cols = {str(cd.get("dfid")): c for c, cd in col_dict.items()}            # List used axis          used_axis = [[e for e in (axis[j] if j < len(axis) else axis[0]) if tr[e.value]] for j, tr in enumerate(traces)]            ret_dict = {              "columns": col_dict,              "labels": [                  reverse_cols.get(tr[_Chart_iprops.label.value] or "", (tr[_Chart_iprops.label.value] or ""))                  for tr in traces              ],              "texts": [                  reverse_cols.get(tr[_Chart_iprops.text.value] or "", (tr[_Chart_iprops.text.value] or None))                  for tr in traces              ],              "modes": [tr[_Chart_iprops.mode.value] for tr in traces],              "types": [tr[_Chart_iprops.type.value] for tr in traces],              "xaxis": [tr[_Chart_iprops.xaxis.value] for tr in traces],              "yaxis": [tr[_Chart_iprops.yaxis.value] for tr in traces],              "markers": markers,              "selectedMarkers": [                  tr[_Chart_iprops.selected_marker.value]                  or (                      {"color": tr[_Chart_iprops.selected_color.value]}                      if tr[_Chart_iprops.selected_color.value]                      else None                  )                  for tr in traces              ],              "traces": [                  [reverse_cols.get(c or "", c) for c in [tr[e.value] for e in used_axis[j]]]                  for j, tr in enumerate(traces)              ],              "orientations": [tr[_Chart_iprops.orientation.value] for tr in traces],              "names": [tr[_Chart_iprops._name.value] for tr in traces],              "lines": [                  tr[_Chart_iprops.line.value]                  if isinstance(tr[_Chart_iprops.line.value], (dict, _MapDict))                  else {"dash": tr[_Chart_iprops.line.value]}                  if tr[_Chart_iprops.line.value]                  else None                  for tr in traces              ],              "textAnchors": [tr[_Chart_iprops.text_anchor.value] for tr in traces],              "options": [tr[_Chart_iprops.options.value] for tr in traces],              "axisNames": [[e.name for e in ax] for ax in used_axis],              "addIndex": [tr[_Chart_iprops.type.value] not in __CHART_NO_INDEX for tr in traces],          }          if len([d for d in decimators if d]):              ret_dict.update(decimators=decimators)          return ret_dict      return {}


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


# flake8: noqa: E402  import contextlib  import typing as t  import warnings  from threading import Thread  from urllib.parse import quote as urlquote  from urllib.parse import urlparse    warnings.filterwarnings(      "ignore",      category=UserWarning,      message="You do not have a working installation of the service_identity module: 'No module named 'service_identity''.*",  )  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  from .singleton import _Singleton    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."              )          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)


from __future__ import annotations    import typing as t    from .._warnings import _warn  from ..icon import Icon  from . import _MapDict      class _Adapter:      def __init__(self):          self.__adapter_for_type: t.Dict[str, t.Callable] = {}          self.__type_for_variable: t.Dict[str, str] = {}          self.__warning_by_type: t.Set[str] = set()        def _add_for_type(self, type_name: str, adapter: t.Callable) -> None:          self.__adapter_for_type[type_name] = adapter        def _add_type_for_var(self, var_name: str, type_name: str) -> None:          self.__type_for_variable[var_name] = type_name        def _get_for_type(self, type_name: str) -> t.Optional[t.Callable]:          return self.__adapter_for_type.get(type_name)        def _get_unique_type(self, type_name: str) -> str:          index = 0          while type_name in self.__adapter_for_type:              type_name = f"{type_name}{index}"              index += 1          return type_name        def _run_for_var(self, var_name: str, value: t.Any, id_only=False) -> t.Any:          ret = self._run(self.__get_for_var(var_name, value), value, var_name, id_only)          return ret if ret is not None else value        def __get_for_var(self, var_name: str, value: t.Any) -> t.Optional[t.Callable]:          adapter = None          type_name = self.__type_for_variable.get(var_name)          if not isinstance(type_name, str):              adapter = self.__adapter_for_type.get(var_name)              type_name = var_name if callable(adapter) else type(value).__name__          if adapter is None:              adapter = self.__adapter_for_type.get(type_name)          return adapter if callable(adapter) else None        def _get_elt_per_ids(self, var_name: str, lov: t.List[t.Any]) -> t.Dict[str, t.Any]:          dict_res = {}          adapter = self.__get_for_var(var_name, lov[0] if lov else None)          for value in lov:              try:                  result = adapter(value._dict if isinstance(value, _MapDict) else value) if adapter else value                  if result is not None:                      dict_res[self.__get_id(result)] = value                      children = self.__get_children(result)                      if children is not None:                          dict_res.update(self._get_elt_per_ids(var_name, children))              except Exception as e:                  _warn(f"Cannot run adapter for {var_name}", e)          return dict_res        def _run(          self, adapter: t.Optional[t.Callable], value: t.Any, var_name: str, id_only=False      ) -> t.Union[t.Tuple[str, ...], str, None]:          if value is None:              return None          try:              result = value._dict if isinstance(value, _MapDict) else value              if adapter:                  result = adapter(result)                  if result is None:                      return result              elif isinstance(result, str):                  return result              tpl_res = self._get_valid_result(result, id_only)              if tpl_res is None:                  _warn(                      f"Adapter for {var_name} did not return a valid result. Please check the documentation on List of Values Adapters."                  )              else:                  if not id_only and len(tpl_res) > 2 and isinstance(tpl_res[2], list) and len(tpl_res[2]) > 0:                      tpl_res = (tpl_res[0], tpl_res[1], self.__on_tree(adapter, tpl_res[2]))                  return (                      (tpl_res + result[len(tpl_res) :])                      if isinstance(result, tuple) and isinstance(tpl_res, tuple)                      else tpl_res                  )          except Exception as e:              _warn(f"Cannot run adapter for {var_name}", e)          return None        def __on_tree(self, adapter: t.Optional[t.Callable], tree: t.List[t.Any]):          ret_list = []          for elt in tree:              ret = self._run(adapter, elt, adapter.__name__ if adapter else "adapter")              if ret is not None:                  ret_list.append(ret)          return ret_list        def _get_valid_result(self, value: t.Any, id_only=False) -> t.Union[t.Tuple[str, ...], str, None]:          id = self.__get_id(value)          if id_only:              return id          label = self.__get_label(value)          if label is None:              return None          children = self.__get_children(value)          return (id, label) if children is None else (id, label, children)  # type: ignore        def __get_id(self, value: t.Any, dig=True) -> str:          if isinstance(value, str):              return value          elif dig:              if isinstance(value, (list, tuple)) and len(value):                  return self.__get_id(value[0], False)              elif hasattr(value, "id"):                  return self.__get_id(value.id, False)              elif hasattr(value, "__getitem__") and "id" in value:                  return self.__get_id(value.get("id"), False)          if value is not None and type(value).__name__ not in self.__warning_by_type:              _warn(f"LoV id must be a string, using a string representation of {type(value)}.")              self.__warning_by_type.add(type(value).__name__)          return "" if value is None else str(value)        def __get_label(self, value: t.Any, dig=True) -> t.Union[str, t.Dict, None]:          if isinstance(value, (str, Icon)):              return Icon.get_dict_or(value)          elif dig:              if isinstance(value, (list, tuple)) and len(value) > 1:                  return self.__get_label(value[1], False)              elif hasattr(value, "label"):                  return self.__get_label(value.label, False)              elif hasattr(value, "__getitem__") and "label" in value:                  return self.__get_label(value["label"], False)          return None        def __get_children(self, value: t.Any) -> t.Optional[t.List[t.Any]]:          if isinstance(value, (tuple, list)) and len(value) > 2:              return value[2] if isinstance(value[2], list) else [value[2]]          elif hasattr(value, "children"):              return value.children if isinstance(value.children, list) else [value.children]          elif hasattr(value, "__getitem__") and "children" in value:              return value["children"] if isinstance(value["children"], list) else [value["children"]]          return None


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:              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]


from __future__ import annotations    import ast  import builtins  import re  import typing as t    from .._warnings import _warn    if t.TYPE_CHECKING:      from ..gui import Gui    from . import (      _get_client_var_name,      _get_expr_var_name,      _getscopeattr,      _getscopeattr_drill,      _hasscopeattr,      _MapDict,      _setscopeattr,      _setscopeattr_drill,      _TaipyBase,      _variable_decode,      _variable_encode,  )      class _Evaluator:      # Regex to separate content from inside curly braces when evaluating f string expressions      __EXPR_RE = re.compile(r"\{(([^\}]*)([^\{]*))\}")      __EXPR_IS_EXPR = re.compile(r"[^\\][{}]")      __EXPR_IS_EDGE_CASE = re.compile(r"^\s*{([^}]*)}\s*$")      __EXPR_VALID_VAR_EDGE_CASE = re.compile(r"^([a-zA-Z\.\_0-9\[\]]*)$")      __EXPR_EDGE_CASE_F_STRING = re.compile(r"[\{]*[a-zA-Z_][a-zA-Z0-9_]*:.+")      __IS_TAIPYEXPR_RE = re.compile(r"TpExPr_(.*)")        def __init__(self, default_bindings: t.Dict[str, t.Any], shared_variable: t.List[str]) -> None:          # key = expression, value = hashed value of the expression          self.__expr_to_hash: t.Dict[str, str] = {}          # key = hashed value of the expression, value = expression          self.__hash_to_expr: t.Dict[str, str] = {}          # key = variable name of the expression, key = list of related expressions          # ex: {x + y}          # "x_TPMDL_0": ["{x + y}"],          # "y_TPMDL_0": ["{x + y}"],          self.__var_to_expr_list: t.Dict[str, t.List[str]] = {}          # key = expression, value = list of related variables          # "{x + y}": {"x": "x_TPMDL_", "y": "y_TPMDL_0"}          self.__expr_to_var_map: t.Dict[str, t.Dict[str, str]] = {}          # instead of binding everywhere the types          self.__global_ctx = default_bindings          # expr to holders          self.__expr_to_holders: t.Dict[str, t.Set[t.Type[_TaipyBase]]] = {}          # shared variables between multiple clients          self.__shared_variable = shared_variable        @staticmethod      def _expr_decode(s: str):          return str(result[1]) if (result := _Evaluator.__IS_TAIPYEXPR_RE.match(s)) else s        def get_hash_from_expr(self, expr: str) -> str:          return self.__expr_to_hash.get(expr, expr)        def get_expr_from_hash(self, hash_val: str) -> str:          return self.__hash_to_expr.get(hash_val, hash_val)        def get_shared_variables(self) -> t.List[str]:          return self.__shared_variable        def _is_expression(self, expr: str) -> bool:          return len(_Evaluator.__EXPR_IS_EXPR.findall(expr)) != 0        def _fetch_expression_list(self, expr: str) -> t.List:          return [v[0] for v in _Evaluator.__EXPR_RE.findall(expr)]        def _analyze_expression(self, gui: Gui, expr: str) -> t.Tuple[t.Dict[str, t.Any], t.Dict[str, str]]:          var_val: t.Dict[str, t.Any] = {}          var_map: t.Dict[str, str] = {}          non_vars = list(self.__global_ctx.keys())          non_vars.extend(dir(builtins))          # Get a list of expressions (value that has been wrapped in curly braces {}) and find variables to bind          for e in self._fetch_expression_list(expr):              var_name = e.split(sep=".")[0]              st = ast.parse('f"{' + e + '}"' if _Evaluator.__EXPR_EDGE_CASE_F_STRING.match(e) else e)              args = [arg.arg for node in ast.walk(st) if isinstance(node, ast.arguments) for arg in node.args]              targets = [                  compr.target.id for node in ast.walk(st) if isinstance(node, ast.ListComp) for compr in node.generators  # type: ignore              ]              for node in ast.walk(st):                  if isinstance(node, ast.Name):                      var_name = node.id.split(sep=".")[0]                      if var_name not in args and var_name not in targets and var_name not in non_vars:                          try:                              encoded_var_name = gui._bind_var(var_name)                              var_val[var_name] = _getscopeattr_drill(gui, encoded_var_name)                              var_map[var_name] = encoded_var_name                          except AttributeError as e:                              _warn(f"Variable '{var_name}' is not defined (in expression '{expr}')", e)          return var_val, var_map        def __save_expression(          self,          gui: Gui,          expr: str,          expr_hash: t.Optional[str],          expr_evaluated: t.Optional[t.Any],          var_map: t.Dict[str, str],      ):          if expr in self.__expr_to_hash:              expr_hash = self.__expr_to_hash[expr]              gui._bind_var_val(expr_hash, expr_evaluated)              return expr_hash          if expr_hash is None:              expr_hash = _get_expr_var_name(expr)          else:              # edge case, only a single variable              expr_hash = f"tpec_{_get_client_var_name(expr)}"          self.__expr_to_hash[expr] = expr_hash          gui._bind_var_val(expr_hash, expr_evaluated)          self.__hash_to_expr[expr_hash] = expr          for var in var_map.values():              if var not in self.__global_ctx.keys():                  lst = self.__var_to_expr_list.get(var)                  if lst is None:                      self.__var_to_expr_list[var] = [expr]                  else:                      lst.append(expr)          if expr not in self.__expr_to_var_map:              self.__expr_to_var_map[expr] = var_map          # save expr_hash to shared variable if valid          for encoded_var_name in var_map.values():              var_name, module_name = _variable_decode(encoded_var_name)              # only variables in the main module with be taken into account              if module_name is not None and module_name != gui._get_default_module_name():                  continue              if var_name in self.__shared_variable:                  self.__shared_variable.append(expr_hash)          return expr_hash        def evaluate_bind_holder(self, gui: Gui, holder: t.Type[_TaipyBase], expr: str) -> str:          expr_hash = self.__expr_to_hash.get(expr, "unknownExpr")          hash_name = self.__get_holder_hash(holder, expr_hash)          expr_lit = expr.replace("'", "\\'")          holder_expr = f"{holder.__name__}({expr},'{expr_lit}')"          self.__evaluate_holder(gui, holder, expr)          if a_set := self.__expr_to_holders.get(expr):              a_set.add(holder)          else:              self.__expr_to_holders[expr] = {holder}          self.__expr_to_hash[holder_expr] = hash_name          # expression is only the first part ...          expr = expr.split(".")[0]          self.__expr_to_var_map[holder_expr] = {expr: expr}          if a_list := self.__var_to_expr_list.get(expr):              if holder_expr not in a_list:                  a_list.append(holder_expr)          else:              self.__var_to_expr_list[expr] = [holder_expr]          return hash_name        def evaluate_holders(self, gui: Gui, expr: str) -> t.List[str]:          lst = []          for hld in self.__expr_to_holders.get(expr, []):              hash_val = self.__get_holder_hash(hld, self.__expr_to_hash.get(expr, ""))              self.__evaluate_holder(gui, hld, expr)              lst.append(hash_val)          return lst        @staticmethod      def __get_holder_hash(holder: t.Type[_TaipyBase], expr_hash: str) -> str:          return f"{holder.get_hash()}_{_get_client_var_name(expr_hash)}"        def __evaluate_holder(self, gui: Gui, holder: t.Type[_TaipyBase], expr: str) -> t.Optional[_TaipyBase]:          try:              expr_hash = self.__expr_to_hash.get(expr, "unknownExpr")              holder_hash = self.__get_holder_hash(holder, expr_hash)              expr_value = _getscopeattr_drill(gui, expr_hash)              holder_value = _getscopeattr(gui, holder_hash, None)              if not isinstance(holder_value, _TaipyBase):                  holder_value = holder(expr_value, expr_hash)                  _setscopeattr(gui, holder_hash, holder_value)              else:                  holder_value.set(expr_value)              return holder_value          except Exception as e:              _warn(f"Cannot evaluate expression {holder.__name__}({expr_hash},'{expr_hash}') for {expr}", e)          return None        def evaluate_expr(self, gui: Gui, expr: str) -> t.Any:          if not self._is_expression(expr):              return expr          var_val, var_map = self._analyze_expression(gui, expr)          expr_hash = None          is_edge_case = False            # The expr_string is placed here in case expr get replaced by edge case          expr_string = 'f"' + expr.replace('"', '\\"') + '"'          # simplify expression if it only contains var_name          m = _Evaluator.__EXPR_IS_EDGE_CASE.match(expr)          if m and not _Evaluator.__EXPR_EDGE_CASE_F_STRING.match(expr):              expr = m.group(1)              expr_hash = expr if _Evaluator.__EXPR_VALID_VAR_EDGE_CASE.match(expr) else None              is_edge_case = True          # validate whether expression has already been evaluated          module_name = gui._get_locals_context()          not_encoded_expr = expr          expr = f"TpExPr_{_variable_encode(expr, module_name)}"          if expr in self.__expr_to_hash and _hasscopeattr(gui, self.__expr_to_hash[expr]):              return self.__expr_to_hash[expr]          try:              # evaluate expressions              ctx: t.Dict[str, t.Any] = {}              ctx.update(self.__global_ctx)              # entries in var_val are not always seen (NameError) when passed as locals              ctx.update(var_val)              expr_evaluated = eval(not_encoded_expr if is_edge_case else expr_string, ctx)          except Exception as e:              _warn(f"Cannot evaluate expression '{not_encoded_expr if is_edge_case else expr_string}'", e)              expr_evaluated = None          # save the expression if it needs to be re-evaluated          return self.__save_expression(gui, expr, expr_hash, expr_evaluated, var_map)        def refresh_expr(self, gui: Gui, var_name: str, holder: t.Optional[_TaipyBase]):          """          This function will execute when the __request_var_update function receive a refresh order          """          expr = self.__hash_to_expr.get(var_name)          if expr:              expr_decoded, _ = _variable_decode(expr)              var_map = self.__expr_to_var_map.get(expr, {})              eval_dict = {k: _getscopeattr_drill(gui, gui._bind_var(v)) for k, v in var_map.items()}              if self._is_expression(expr_decoded):                  expr_string = 'f"' + _variable_decode(expr)[0].replace('"', '\\"') + '"'              else:                  expr_string = expr_decoded              try:                  ctx: t.Dict[str, t.Any] = {}                  ctx.update(self.__global_ctx)                  ctx.update(eval_dict)                  expr_evaluated = eval(expr_string, ctx)                  _setscopeattr(gui, var_name, expr_evaluated)                  if holder is not None:                      holder.set(expr_evaluated)              except Exception as e:                  _warn(f"Exception raised evaluating {expr_string}", e)        def re_evaluate_expr(self, gui: Gui, var_name: str) -> t.Set[str]:          """          This function will execute when the _update_var function is handling          an expression with only a single variable          """          modified_vars: t.Set[str] = set()          # Verify that the current hash is an edge case one (only a single variable inside the original expression)          if var_name.startswith("tp_"):              return modified_vars          expr_original = None          # if var_name starts with tpec_ --> it is an edge case with modified var          if var_name.startswith("tpec_"):              # backup for later reference              var_name_original = var_name              expr_original = self.__hash_to_expr[var_name]              temp_expr_var_map = self.__expr_to_var_map[expr_original]              if len(temp_expr_var_map) <= 1:                  # since this is an edge case --> only 1 item in the dict and that item is the original var                  for v in temp_expr_var_map.values():                      var_name = v                  # construct correct var_path to reassign values                  var_name_full, _ = _variable_decode(expr_original)                  var_name_full = var_name_full.split(".")                  var_name_full[0] = var_name                  var_name_full = ".".join(var_name_full)                  _setscopeattr_drill(gui, var_name_full, _getscopeattr(gui, var_name_original))              else:                  # multiple key-value pair in expr_var_map --> expr is special case a["b"]                  key = ""                  for v in temp_expr_var_map.values():                      if isinstance(_getscopeattr(gui, v), _MapDict):                          var_name = v                      else:                          key = v                  if key == "":                      return modified_vars                  _setscopeattr_drill(gui, f"{var_name}.{_getscopeattr(gui, key)}", _getscopeattr(gui, var_name_original))          # A middle check to see if var_name is from _MapDict          if "." in var_name:              var_name = var_name[: var_name.index(".")]          # otherwise, thar var_name is correct and doesn't require any resolution          if var_name not in self.__var_to_expr_list:              # _warn("{var_name} not found.")              return modified_vars          # refresh expressions and holders          for expr in self.__var_to_expr_list[var_name]:              expr_decoded, _ = _variable_decode(expr)              hash_expr = self.__expr_to_hash.get(expr, "UnknownExpr")              if expr != var_name and not expr.startswith(_TaipyBase._HOLDER_PREFIX):                  expr_var_map = self.__expr_to_var_map.get(expr)  # ["x", "y"]                  if expr_var_map is None:                      _warn(f"Something is amiss with expression list for {expr}.")                  else:                      eval_dict = {k: _getscopeattr_drill(gui, gui._bind_var(v)) for k, v in expr_var_map.items()}                      if self._is_expression(expr_decoded):                          expr_string = 'f"' + _variable_decode(expr)[0].replace('"', '\\"') + '"'                      else:                          expr_string = expr_decoded                      try:                          ctx: t.Dict[str, t.Any] = {}                          ctx.update(self.__global_ctx)                          ctx.update(eval_dict)                          expr_evaluated = eval(expr_string, ctx)                          _setscopeattr(gui, hash_expr, expr_evaluated)                      except Exception as e:                          _warn(f"Exception raised evaluating {expr_string}", e)              # refresh holders if any              for h in self.__expr_to_holders.get(expr, []):                  holder_hash = self.__get_holder_hash(h, self.get_hash_from_expr(expr))                  if holder_hash not in modified_vars:                      _setscopeattr(gui, holder_hash, self.__evaluate_holder(gui, h, expr))                      modified_vars.add(holder_hash)              modified_vars.add(hash_expr)          return modified_vars        def _get_instance_in_context(self, name: str):          return self.__global_ctx.get(name)


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 {}