from taipy.gui import Markdown, invoke_long_callback  import taipy as tp   import pandas as pd    import datetime as dt    from config.config import scenario_cfg    scenario_selector = [(s.id, s.name) for s in tp.get_scenarios()]  selected_scenario = None  selected_date = dt.datetime(2020,10,1)    scenario_country = "No selected scenario"  scenario_date = "No selected scenario"  scenario_name = ""    result = pd.DataFrame({"Date":[dt.datetime(2020,1,1)],                         "Deaths_x":[0],"Deaths_y":[0],                         "Predictions_x":[0],"Predictions_y":[0]})    def create_new_scenario(state):      if state.scenario_name is not None or state.scenario_name == "":          scenario = tp.create_scenario(scenario_cfg, name=state.scenario_name)          state.scenario_selector += [(scenario.id, scenario.name)]          state.selected_scenario = scenario.id          actualize_graph(state)            def submit_heavy(scenario):      tp.submit(scenario)    def submit_status(state, status):      actualize_graph(state)    def submit_scenario(state):      # 1) get the selected scenario      # 2) write in country Data Node, the selected country      # 3) submit the scenario      # 4) actualize le graph avec actualize_graph      if state.selected_scenario is not None:          scenario = tp.get(state.selected_scenario)          scenario.country.write(state.selected_country)          scenario.date.write(state.selected_date.replace(tzinfo=None))          invoke_long_callback(state, submit_heavy, [scenario], submit_status)    def actualize_graph(state):      # 1) update the result dataframe      # 2) change selected_country with the predicted country of the scenario      if state.selected_scenario is not None:          scenario = tp.get(state.selected_scenario)          result_arima = scenario.pipelines['ARIMA'].result.read()          result_rd = scenario.pipelines['LinearRegression'].result.read()          if result_arima is not None and result_rd is not None:              state.result = result_rd.merge(result_arima, on="Date", how="outer").sort_values(by='Date')          else:              state.result = result          state.scenario_country = scenario.country.read()          state.scenario_date = scenario.date.read().strftime("%d %B %Y")    predictions_md = Markdown("""  # **Prediction**{: .color-primary} page      ## Scenario Creation      <|layout|columns=5 5 5 5|gap=30px|  **Scenario Name**
  <|{scenario_name}|input|label=Name|>
 <|Create|button|on_action=create_new_scenario|>    **Prediction Date**
  <|{selected_date}|date|label=Prediction date|>  <|Submit|button|on_action=submit_scenario|>    **Country**
  <|{selected_country}|selector|lov={selector_country}|dropdown|on_change=on_change_country|label=Country|>  |>    ---------------------------------------    ## Result    <|layout|columns=2 3 3|gap=30px|  <|{selected_scenario}|selector|lov={scenario_selector}|on_change=actualize_graph|dropdown|value_by_id|label=Scenario|>     <|card m1|  #### Country of prediction :  <|{scenario_country}|>  |>    <|card m1|  #### Date of prediction : <|{scenario_date}|>  |>  |>
    <|{result}|chart|x=Date|y[1]=Deaths_x|type[1]=bar|y[2]=Predictions_x|y[3]=Predictions_y|>  """)


import numpy as np  from taipy.gui import Markdown    from data.data import data    marker_map = {"color":"Deaths", "size": "Size", "showscale":True, "colorscale":"Viridis"}  layout_map = {              "dragmode": "zoom",              "mapbox": { "style": "open-street-map", "center": { "lat": 38, "lon": -90 }, "zoom": 3}              }  options = {"unselected":{"marker":{"opacity":0.5}}}    def initialize_map(data):      data['Province/State'] = data['Province/State'].fillna(data["Country/Region"])      data_province = data.groupby(["Country/Region",                                    'Province/State',                                    'Longitude',                                    'Latitude'])\                           .max()                                   data_province_displayed = data_province[data_province['Deaths']>10].reset_index()        data_province_displayed['Size'] = np.sqrt(data_province_displayed.loc[:,'Deaths']/data_province_displayed.loc[:,'Deaths'].max())*80 + 3      data_province_displayed['Text'] = data_province_displayed.loc[:,'Deaths'].astype(str) + ' deaths </br> ' + data_province_displayed.loc[:,'Province/State']      return data_province_displayed      data_province_displayed = initialize_map(data)    map_md = Markdown("""  # **Map**{: .color-primary} Statistics    <|{data_province_displayed}|chart|type=scattermapbox|lat=Latitude|lon=Longitude|marker={marker_map}|layout={layout_map}|text=Text|mode=markers|height=800px|options={options}|>  """)


import numpy as np  import pandas as pd    from taipy.gui import Markdown    from data.data import data    selected_country = 'France'  data_country_date = None    representation_selector = ['Cumulative', 'Density']  selected_representation = representation_selector[0]    layout = {'barmode':'stack', "hovermode":"x"}  options = {"unselected":{"marker":{"opacity":0.5}}}  country_md = "<|{data_country_date}|chart|type=bar|x=Date|y[1]=Deaths|y[2]=Recovered|y[3]=Confirmed|layout={layout}|options={options}|>"      def initialize_case_evolution(data, selected_country='France'):      # Aggregation of the dataframe to erase the regions that will not be used here      data_country_date = data.groupby(["Country/Region",'Date'])\                              .sum()\                              .reset_index()            # a country is selected, here France by default      data_country_date = data_country_date.loc[data_country_date['Country/Region']==selected_country]      return data_country_date    data_country_date = initialize_case_evolution(data)  pie_chart = pd.DataFrame({"labels": ["Deaths", "Recovered", "Confirmed"],"values": [data_country_date.iloc[-1, 6], data_country_date.iloc[-1, 5], data_country_date.iloc[-1, 4]]})        def convert_density(state):      if state.selected_representation == 'Density':          df_temp = state.data_country_date.copy()          df_temp['Deaths'] = df_temp['Deaths'].diff().fillna(0)          df_temp['Recovered'] = df_temp['Recovered'].diff().fillna(0)          df_temp['Confirmed'] = df_temp['Confirmed'].diff().fillna(0)          state.data_country_date = df_temp      else:          state.data_country_date = initialize_case_evolution(data, state.selected_country)    def on_change_country(state):      # state contains all the Gui variables and this is through this state variable that we can update the Gui      # state.selected_country, state.data_country_date, ...      # update data_country_date with the right country (use initialize_case_evolution)      print("Chosen country: ", state.selected_country)      state.data_country_date = initialize_case_evolution(data, state.selected_country)      state.pie_chart = pd.DataFrame({"labels": ["Deaths", "Recovered", "Confirmed"],                                      "values": [state.data_country_date.iloc[-1, 6], state.data_country_date.iloc[-1, 5], state.data_country_date.iloc[-1, 4]]})      if state.selected_representation == 'Density':          convert_density(state)      country_md = Markdown("pages/country.md")


from taipy.gui import Gui, notify    text = ""  revealed = False    page = """  <|{text if text else 'Write something in the input'}|>    <|{text}|input|on_change={lambda state: notify(state, 'i', s.text)}|>    <|part|render={len(text)>0}|  Part hidden and discovered after input  |>    -----    <|Push|button|on_action={lambda state: state.assign("revealed", True)}|>    <|part|render={revealed}|  Part hidden and discovered after button  |>  """    Gui(page).run()


# Write an app that calls a function every 5 seconds


from taipy.gui import Gui, Markdown, invoke_long_callback, notify  import numpy as np    status = 0  num_iterations = 10_000_000  pi_list = []    def pi_approx(num_iterations):      k, s = 3.0, 1.0      pi_list = []      for i in range(num_iterations):          s = s-((1/k) * (-1)**i)          k += 2          if (i+1)%(int(num_iterations/1_000)+1) == 0:              pi_list += [np.abs(4*s-np.pi)]        return pi_list          def heavy_status(state, status, pi_list):      notify(state, 'i', f"Status parameter: {status}")      if isinstance(status, bool):          if status:              notify(state, 'success', "Finished")              state.pi_list = pi_list          else:              notify(state, 'error', f"An error was raised")      else:          state.status += 1        def on_action(state):      invoke_long_callback(state,                           pi_approx, [int(state.num_iterations)],                           heavy_status, [],                           2000)              page = Markdown("""  How many times was the status function called? <|{status}|>    ## Number of approximation    <|{num_iterations}|number|label=# of approximation|>    <|Approximate pie|button|on_action=on_action|>    ## Evolution of approximation  <|{pi_list}|chart|layout={layout}|>  """)    layout = {      "yaxis": {      "type": 'log',      "autorange": True      }    }    Gui(page).run()


from taipy.gui import Gui, notify     text = ""    page_1 = """  # Page 1  <|{text}|>  """    page_2 = """  # Page 2  <|Raise error|button|on_action=raise_error|>  """    hidden_page_3 = """  # Hidden Page  """    def raise_error(state):      raise(ValueError("This is an error"))      def on_init(state):      print("When a new client connects, this function is called")      state.text = "Hello, world!"    def on_change(state, var_name, var_value):      notify(state, 'i', f'{var_name} changed')    def on_navigate(state, page_name: str):       if page_name == "hidden_page_3":          return "page_1"      notify(state, 'i', f'{page_name} navigated')      return page_name    def on_exception(state, function_name: str, ex: Exception):      err = f"A problem occured in {function_name}"      print(err)      notify(state, 'e', err)      pages = {           "/":"<|navbar|>",           "page_1": page_1,           "page_2": page_2,            "hidden_page_3": hidden_page_3}    Gui(pages=pages).run(port=5003)


from taipy.gui import Gui    selected = []    a = [1, 2]  b = [2, 3]    selector_lov = [a, b]    page = """  <|{selected}|selector|lov={selector_lov}|adapter={lambda s: s.name}|>  """    gui = Gui(page)  gui.run()


from taipy.gui import Gui  from math import cos, exp    value = 10    page = """  Markdown  # Taipy *Demo*    Value: <|{value}|text|>    <|{value}|slider|on_change=on_slider|>    <|{data}|chart|>  """    def on_slider(state):      state.data = compute_data(state.value)    def compute_data(decay:int)->list:      return [cos(i/6) * exp(-i*decay/600) for i in range(100)]    data = compute_data(value)    Gui(page).run(use_reloader=True, port=5002)


from taipy.gui import Gui  from math import cos, exp    value = 10    page = """  Markdown  # Taipy *Demo*  """    Gui(page).run(use_reloader=True, port=5002)


# Write an app that create simple charts by poviding inputs and diplay them


from taipy.gui import Gui     title = 1    md = """  <|{title}|number|on_change=change_partial|>    <|part|partial={p}|>  """    def change_partial(state):      title_int = int(state.title)      new_html = f'<h{title_int}>test{title_int}</h{title_int}>'      print(new_html)      state.p.update_content(state, new_html)    gui = Gui(md)  p = gui.add_partial("
test
")  gui.run(port=5001)


import yfinance as yf  from taipy.gui import Gui  from taipy.gui.data.decimator import MinMaxDecimator, RDP, LTTB      df_AAPL = yf.Ticker("AAPL").history(interval="1d", period = "100Y")  df_AAPL["DATE"] = df_AAPL.index.astype(int).astype(float)    n_out = 500  decimator_instance = MinMaxDecimator(n_out=n_out)    decimate_data_count = len(df_AAPL)    page = """  # Decimator    From a data length of <|{len(df_AAPL)}|> to <|{n_out}|>    ## Without decimator    <|{df_AAPL}|chart|x=DATE|y=Open|>    ## With decimator    <|{df_AAPL}|chart|x=DATE|y=Open|decimator=decimator_instance|>  """    gui = Gui(page)  gui.run(port=5025)


from taipy import Config  import taipy as tp    def read_text(path: str) -> str:      with open(path, 'r') as text_reader:          data = text_reader.read()      return data      def write_text(data: str, path: str) -> None:      with open(path, 'w') as text_writer:          text_writer.write(data)      historical_data_cfg = Config.configure_generic_data_node(      id="historical_data",      read_fct=read_text,      write_fct=write_text,      read_fct_args=["../data.txt"],      write_fct_args=["../data.txt"])      scenario_cfg = Config.configure_scenario(id="my_scenario", additional_data_node_configs=[historical_data_cfg])    scenario = tp.create_scenario(scenario_cfg)


import taipy as tp  from config.config_toml import scenario_cfg    if __name__=="__main__":      tp.Core().run()      scenario_1 = tp.create_scenario(scenario_cfg)      scenario_2 = tp.create_scenario(scenario_cfg)      scenario_1.submit()      scenario_2.submit()        scenario_1 = tp.create_scenario(scenario_cfg)      scenario_1.submit(wait=True)      scenario_1.submit(wait=True, timeout=5)


import taipy as tp    from config.config import scenario_cfg    if __name__=="__main__":      tp.Core().run()      scenario_1 = tp.create_scenario(scenario_cfg)      scenario_2 = tp.create_scenario(scenario_cfg)      scenario_1.submit()      scenario_2.submit()        scenario_1 = tp.create_scenario(scenario_cfg)      scenario_1.submit(wait=True)      scenario_1.submit(wait=True, timeout=5)


from taipy import Config  from algos.algos import *    Config.configure_job_executions(mode="standalone", max_nb_of_workers=2)    # Configuration of Data Nodes  input_cfg = Config.configure_data_node("input", default_data=21)  intermediate_cfg = Config.configure_data_node("intermediate", default_data=21)  output_cfg = Config.configure_data_node("output")    # Configuration of tasks  first_task_cfg = Config.configure_task("double",                                         double,                                         input_cfg,                                         intermediate_cfg)    second_task_cfg = Config.configure_task("add",                                          add,                                          intermediate_cfg,                                          output_cfg)    # Configuration of the pipeline and scenario  scenario_cfg = Config.configure_scenario(id="my_scenario",                                                      task_configs=[first_task_cfg,                                                                    second_task_cfg])    Config.export("config_07.toml")


from taipy import Config   from algos.algos import *    Config.load('config/config_07.toml')  Config.configure_job_executions(mode="standalone", max_nb_of_workers=2)  scenario_cfg = Config.scenarios['my_scenario']


import time      # Normal function used by Taipy  def double(nb):      return nb * 2    def add(nb):      print("Wait 5 seconds in add function")      time.sleep(5)      return nb + 10


import taipy as tp    from taipy.gui import Markdown    from config.config import *    scenario = None  df_metrics = None  data_node = None      pages = {'/':'<|navbar|> <|toggle|theme|> <br/>',           'Scenario': Markdown('pages/scenario.md'),           'Data-Node': Markdown('pages/data_node.md')}      if __name__ == "__main__":      tp.Core().run()      tp.Gui(pages=pages).run(port=4999)


import taipy as tp    import datetime as dt    from config.config import *      def create_and_run_scenario(date: dt.datetime):      scenario = tp.create_scenario(config=scenario_cfg,                                    name=f"scenario_{date.date()}",                                    creation_date=date)      scenario.day.write(date)      tp.submit(scenario)      return scenario    if __name__ == "__main__":      tp.Core().run()                my_first_scenario = create_and_run_scenario(dt.datetime(2021, 1, 25))            predictions = my_first_scenario.predictions.read()      print("Predictions\n", predictions)        [s for s in tp.get_scenarios()]      [d for d in tp.get_data_nodes()]


from taipy import Config, Scope, Frequency    from taipy.core import Scenario    import datetime as dt    from algos.algos import clean_data, predict, evaluate      ## Input Data Nodes  initial_dataset_cfg = Config.configure_data_node(id="initial_dataset",                                                   storage_type="csv",                                                   path="data/dataset.csv",                                                   scope=Scope.GLOBAL)    # We assume the current day is the 26th of July 2021.  # This day can be changed to simulate multiple executions of scenarios on different days  day_cfg = Config.configure_data_node(id="day", default_data=dt.datetime(2021, 7, 26))    ## Remaining Data Node  cleaned_dataset_cfg = Config.configure_data_node(id="cleaned_dataset",                                                   storage_type="parquet",                                                   scope=Scope.GLOBAL)  predictions_cfg = Config.configure_data_node(id="predictions")    # Task config objects  clean_data_task_cfg = Config.configure_task(id="clean_data",                                              function=clean_data,                                              input=initial_dataset_cfg,                                              output=cleaned_dataset_cfg,                                              skippable=True)    predict_task_cfg = Config.configure_task(id="predict",                                                   function=predict,                                                   input=[cleaned_dataset_cfg, day_cfg],                                                   output=predictions_cfg)    evaluation_cfg = Config.configure_data_node(id="evaluation")  evaluate_task_cfg = Config.configure_task(id="evaluate",                                              function=evaluate,                                              input=[predictions_cfg, cleaned_dataset_cfg, day_cfg],                                              output=evaluation_cfg)    #   # Configure our scenario config.  scenario_cfg = Config.configure_scenario(id="scenario", task_configs=[clean_data_task_cfg, predict_task_cfg,evaluate_task_cfg], frequency=Frequency.MONTHLY)    Config.export('config/config.toml')


import datetime as dt  import pandas as pd      def clean_data(initial_dataset: pd.DataFrame):      print("     Cleaning data")      initial_dataset['Date'] = pd.to_datetime(initial_dataset['Date'])      cleaned_dataset = initial_dataset[['Date', 'Value']]      return cleaned_dataset      def predict(cleaned_dataset: pd.DataFrame, day: dt.datetime):      print("     Predicting")      train_dataset = cleaned_dataset[cleaned_dataset['Date'] < pd.Timestamp(day.date())]      predictions = train_dataset['Value'][-30:].reset_index(drop=True)      return pd.DataFrame({"Prediction":predictions})      def evaluate(predictions, cleaned_dataset, day):      print("     Evaluating")      expected = cleaned_dataset.loc[cleaned_dataset['Date'] >= pd.Timestamp(day.date()), 'Value'][:30].reset_index(drop=True)      mae = ((predictions['Prediction'] - expected) ** 2).mean()      return int(mae)


from taipy.gui import Gui, notify  import datetime as dt  import yfinance as yf    def get_stock_data(ticker):      now = dt.date.today()      past = now - dt.timedelta(days=365*2)      return yf.download(ticker, past, now).reset_index()    def update_ticker(state):      # state.data =       ...    ticker = 'AAPL'  data = get_stock_data(ticker)    historical = """  """    Gui(historical).run()


from taipy.gui import Gui, notify  import datetime as dt  import yfinance as yf    def get_stock_data(ticker):      now = dt.date.today()      past = now - dt.timedelta(days=365*2)      return yf.download(ticker, past, now).reset_index()    def update_ticker(state):      state.data = get_stock_data(state.ticker)      notify(state, "success", "Ticker updated!")    ticker = 'AAPL'  data = get_stock_data(ticker)    historical = """  #### Stock Price **Analysis**{: .color-primary}  <|{ticker}|toggle|lov=MSFT;GOOG;AAPL|on_change=update_ticker|>    Mean Volume: <|{int(data['Volume'].mean())}|>    <|{data}|chart|x=Date|y=Volume|>  """    Gui(historical).run()


from taipy.gui import Gui  import taipy as tp    from pages.data_viz import historical  from pages.predictions_sol import predictions, scenario    ticker = 'AAPL'    pages = {"/":"<|navbar|>",           "Historical":historical,           "Prediction":predictions}    tp.Core().run()  Gui(pages=pages).run(port=5001)


from datetime import timedelta  import yfinance as yf  from prophet import Prophet    def get_data(ticker, date):      past = date - timedelta(days=365*7)      return yf.download(ticker, past, date).reset_index()    def predict(preprocessed_dataset):      df_train = preprocessed_dataset[['Date', 'Close']]      df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})  # This is the format that Prophet accepts        m = Prophet()      m.fit(df_train)      future = m.make_future_dataframe(periods=365)      predictions = m.predict(future)[['ds', 'yhat']].rename(columns={'ds': 'Date', 'yhat': 'Predictions'})[-365:]      return predictions.reset_index()


import taipy as tp   from taipy.gui import notify, Markdown  import datetime as dt    tp.Config.load("config/config.toml")    ticker = 'AAPL'  scenario = None  data_node = None  jobs = []  default_data = {"Date":[0], "Predictions":[0]}    def on_submission_status_change(state, submittable, details):      submission_status = details.get('submission_status')        if submission_status == 'COMPLETED':          print(f"{submittable.name} has completed.")          notify(state, 'success', 'Completed!')          state.refresh('scenario')        elif submission_status == 'FAILED':          print(f"{submittable.name} has failed.")          notify(state, 'error', 'Completed!')    predictions = Markdown("""  Put a scenario selector                            ### **Daily**{: .color-primary} Predictions <|{scenario.ticker.read() if scenario else ticker}|toggle|lov=MSFT;GOOG;AAPL|active={scenario}|on_change=save|>    Put a scenario viewer                           <|{show_preditions(scenario)}|chart|x=Date|y=Predictions|>    <|1 5|layout|  Put a Data Node selector                           Put a Data Node  |>                           Put a job selector  """)    def show_preditions(scenario):      if scenario and scenario.predictions.read() is not None:          print(scenario)          return scenario.predictions.read()      else:          return default_data    def save(state, var_name, var_value):      state.scenario.ticker.write(var_value)      state.scenario.date.write(dt.date.today())      notify(state, "success", 'Parameters saved: ready for submission!')      state.scenario.predictions.write(None)      state.scenario = state.scenario


import taipy as tp   from taipy.gui import notify, Markdown  import datetime as dt    tp.Config.load("config/config.toml")    ticker = 'AAPL'  scenario = None  data_node = None  jobs = []  default_data = {"Date":[0], "Predictions":[0]}    def on_submission_status_change(state, submittable, details):      submission_status = details.get('submission_status')        if submission_status == 'COMPLETED':          print(f"{submittable.name} has completed.")          notify(state, 'success', 'Completed!')          state.refresh('scenario')        elif submission_status == 'FAILED':          print(f"{submittable.name} has failed.")          notify(state, 'error', 'Completed!')    predictions = Markdown("""  <|{scenario}|scenario_selector|>     ### **Daily**{: .color-primary} Predictions <|{scenario.ticker.read() if scenario else ticker}|toggle|lov=MSFT;GOOG;AAPL|active={scenario}|on_change=save|>    <|{scenario}|scenario|on_submission_change=on_submission_status_change|>     <|{show_preditions(scenario)}|chart|x=Date|y=Predictions|>    <|1 5|layout|  <|{data_node}|data_node_selector|>    <|{data_node}|data_node|>  |>                           <|{jobs}|job_selector|>  """)    def show_preditions(scenario):      if scenario and scenario.predictions.read() is not None:          print(scenario)          return scenario.predictions.read()      else:          return default_data    def save(state, var_name, var_value):      state.scenario.ticker.write(var_value)      state.scenario.date.write(dt.date.today())      notify(state, "success", 'Parameters saved: ready for submission!')      state.scenario.predictions.write(None)      state.scenario = state.scenario


from taipy.gui import notify, Markdown  import datetime as dt  import yfinance as yf    def get_stock_data(ticker):      now = dt.date.today()      past = now - dt.timedelta(days=365*2)      return yf.download(ticker, past, now).reset_index()    def update_ticker(state):      state.data = get_stock_data(state.ticker)      notify(state, "success", "Ticker updated!")    ticker = 'AAPL'  data = get_stock_data(ticker)    historical = Markdown("""  ## Stock Price **Analysis**{: .color-primary} <|{ticker}|toggle|lov=MSFT;GOOG;AAPL|on_change=update_ticker|>    <|{data}|chart|x=Date|y=Volume|>  """)


from taipy import Gui    import pandas as pd  import requests    API_URL = "https://api-inference.huggingface.co/models/bigcode/starcoder"  headers = {"Authorization": "Bearer [ENTER-YOUR-API-KEY-HERE]"}    DATA_PATH = "data.csv"    df = pd.read_csv(DATA_PATH, sep=";")  data = pd.DataFrame(      {          "Date": pd.to_datetime(              [                  "2020-01-01",                  "2020-01-02",                  "2020-01-03",                  "2020-01-04",                  "2020-01-05",                  "2020-01-06",                  "2020-01-07",              ]          ),          "Sales": [100, 250, 500, 400, 450, 600, 650],          "Revenue": [150, 200, 600, 800, 850, 900, 950],          "Energy": ["Oil", "Coal", "Gas", "Nuclear", "Hydro", "Solar", "Wind"],          "Usage": [0.33, 0.27, 0.21, 0.06, 0.05, 0.05, 0.03],      }  )  context = ""  for instruction, code in zip(df["instruction"], df["code"]):      context += f"{instruction}\n{code}\n"      def query(payload: dict) -> dict:      """      Queries StarCoder API        Args:          payload: Payload for StarCoder API        Returns:          dict: StarCoder API response      """      response = requests.post(API_URL, headers=headers, json=payload, timeout=20)      return response.json()      def prompt(input_instruction: str) -> str:      """      Prompts StarCoder to generate Taipy GUI code        Args:          instuction (str): Instruction for StarCoder        Returns:          str: Taipy GUI code      """      current_prompt = f"{context}\n{input_instruction}\n"      output = ""      final_result = ""        # Re-query until the output contains the closing tag      timeout = 0      while ">" not in output and timeout < 10:          output = query(              {                  "inputs": current_prompt + output,                  "parameters": {                      "return_full_text": False,                  },              }          )[0]["generated_text"]          timeout += 1          final_result += output        output_code = f"""<{final_result.split("<")[1].split(">")[0]}>"""      return output_code      def on_enter_press(state) -> None:      """      Prompt StarCoder to generate Taipy GUI code when user presses enter        Args:          state (State): Taipy GUI state      """      state.result = prompt(state.instruction)      state.p.update_content(state, state.result)      print(state.result)      instruction = ""  result = ""      page = """  # Taipy**Copilot**{: .color-primary}    Enter your instruction here:  <|{instruction}|input|on_action=on_enter_press|class_name=fullwidth|>    <|Data|expandable|  <|{data[:5]}|table|width=100%|show_all=True|>  |>    <|part|partial={p}|>  """    gui = Gui(page)  p = gui.add_partial("""<|{data}|chart|mode=lines|x=Date|y=Sales|>""")  gui.run()


import json      def add_line(source, line, step):        line = line.replace('Getting Started with Taipy Core', 'Getting Started with Taipy Core on Notebooks')      line = line.replace('(../src/', '(https://docs.taipy.io/en/latest/getting_started/src/')      line = line.replace('(time_series.csv)', '(https://docs.taipy.io/en/latest/getting_started/src/time_series.csv)') #!!!!!      line = line.replace('(time_series_2.csv)', '(https://docs.taipy.io/en/latest/getting_started/src/time_series_2.csv)')      line = line.replace('!!! example "Configuration"','')      line = line.replace('=== "Python configuration"','')              if line.startswith('!['):          if step != 'index':              line = line.replace('(', '(https://raw.githubusercontent.com/Avaiga/taipy-getting-started-core/develop/' + step + '/')          else:              line = line.replace('(', '(https://raw.githubusercontent.com/Avaiga/taipy-getting-started-core/develop/')            # conversion of Markdown image to HTML          img_src = line.split('](')[1].split(')')[0]          width = line.split('](')[1].split(')')[1].split(' ')[1]            source.append('
\n')          source.append(f' \n')          source.append('
\n')            elif step == 'step_00' and line.startswith('from taipy'):          source.append("from taipy.gui import Gui, Markdown\n")      elif 'Notebook' in line and 'step' in step:          pass      else:          source.append(line + '\n')        return source      def detect_new_cell(notebook, source, cell, line, execution_count, force_creation=False):      if line.startswith('```python') or line.startswith('```') and cell == 'code' or force_creation:          source = source[:-1]            if cell == 'code':              notebook['cells'].append({                  "cell_type": "code",                  "metadata": {},                  "outputs": [],                  "execution_count": execution_count,                  "source": source              })              cell = 'markdown'              execution_count += 1          else:              notebook['cells'].append({                  "cell_type": "markdown",                  "metadata": {},                  "source": source              })              cell = 'code'            source = []        return cell, source, notebook, execution_count      def create_introduction(notebook, execution_count):      with open('index.md', 'r') as f:          text = f.read()        split_text = text.split('\n')      source = []        for line in split_text:          if not line.startswith('``` console'):              add_line(source, line, 'index')          else:              break        notebook['cells'].append({          "cell_type": "markdown",          "metadata": {},            "source": source      })        notebook['cells'].append({          "cell_type": "code",          "metadata": {},          "outputs": [],          "execution_count": execution_count,          "source": ['# !pip install taipy\n']      })        notebook['cells'].append({          "cell_type": "markdown",          "metadata": {},          "source": ['## Using Notebooks\n','Using Notebooks, you **may want to restart the kernel** after a run of Taipy Core\n']      })        execution_count += 1      return notebook, execution_count      def create_steps(notebook, execution_count):      steps = ['step_0' + str(i) for i in range(1, 9)]      source = []        for step in steps:          if source != []:              cell, source, notebook, execution_count = detect_new_cell(notebook,                                                                        source,                                                                        cell,                                                                        line,                                                                        execution_count,                                                                        force_creation=True)            with open(step + '/ReadMe.md', 'r') as f:              text = f.read()            split_text = text.split('\n')          cell = "markdown"            for_studio = 0            for line in split_text:              if cell == "markdown":                  line=line.replace("    ","")              elif cell == "code" and (line[:8] == "        " or len(line)<=1) and for_studio == 2:                  line=line[8:]                 elif cell == "code" and (line[:4] == "    " or len(line)<=1) and for_studio == 2:                  line=line[4:]              else:                  for_studio = 0                            if '=== "Taipy Studio' in line:                  for_studio = 1              if '=== "Python configuration"' in line:                  for_studio = 2                                if for_studio != 1:                  add_line(source, line, step)                  cell, source, notebook, execution_count = detect_new_cell(notebook, source, cell, line, execution_count)        return notebook, execution_count      if __name__ == '__main__':      notebook = {          "cells": [],          "metadata": {              "language_info": {                  "codemirror_mode": {                      "name": "ipython",                      "version": 3                  },                  "file_extension": ".py",                  "mimetype": "text/x-python",                  "name": "python",                  "nbconvert_exporter": "python",                  "pygments_lexer": "ipython3"              },              "orig_nbformat": 4          },          "nbformat": 4,          "nbformat_minor": 2      }        execution_count = 0        notebook, execution_count = create_introduction(notebook, execution_count)      notebook, execution_count = create_steps(notebook, execution_count)        with open('getting_started.ipynb', 'w', encoding='utf-8') as f:          json.dump(notebook, f, indent=2)


from taipy.core.config import Config, Frequency, Status  import taipy as tp  import datetime as dt  import time      # Normal function used by Taipy  def double(nb):      return nb * 2    def add(nb):      print("Wait 10 seconds in add function")      time.sleep(10)      return nb + 10      # Configuration of Data Nodes  input_cfg = Config.configure_data_node("input", default_data=21)  intermediate_cfg = Config.configure_data_node("intermediate")  output_cfg = Config.configure_data_node("output")      # Configuration of tasks  first_task_cfg = Config.configure_task("double",                                      double,                                      input_cfg,                                      intermediate_cfg)    second_task_cfg = Config.configure_task("add",                                      add,                                      intermediate_cfg,                                      output_cfg)      def callback_scenario_state(scenario, job):      """All the scenarios are subscribed to the callback_scenario_state function. It means whenever a job is done, it is called.      Depending on the job and the status, it will update the message stored in a json that is then displayed on the GUI.        Args:          scenario (Scenario): the scenario of the job changed          job (_type_): the job that has its status changed      """      print(scenario.name)      if job.status == tp.core.Status.COMPLETED:          for data_node in job.task.output.values():              print(data_node.read())    # Configuration of scenario  scenario_cfg = Config.configure_scenario_from_tasks(id="my_scenario",                                                      task_configs=[first_task_cfg,                                                                    second_task_cfg],                                                      name="my_scenario")      Config.export("config_09.toml")    if __name__=="__main__":      tp.Core().run()      scenario_1 = tp.create_scenario(scenario_cfg)      scenario_1.subscribe(callback_scenario_state)        scenario_1.submit(wait=True)            tp.Rest().run()


from taipy.core.config import Config, Scope, Frequency  import taipy as tp  import datetime as dt  import pandas as pd      def filter_by_month(df, month):      df['Date'] = pd.to_datetime(df['Date'])       df = df[df['Date'].dt.month == month]      return df    def count_values(df):      return len(df)      Config.load('config_06.toml')    # my_scenario is the id of the scenario configured  scenario_cfg = Config.scenarios['my_scenario']    if __name__ == '__main__':      tp.Core().run()        scenario_1 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2022,10,7),                                      name="Scenario 2022/10/7")      scenario_2 = tp.create_scenario(scenario_cfg,                                  creation_date=dt.datetime(2022,10,5),                                  name="Scenario 2022/10/5")      scenario_3 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2021,9,1),                                      name="Scenario 2022/9/1")          # scenario 1 and 2 belongs to the same cycle      scenario_1.month.write(10)        scenario_1.submit()        # first task has already been executed by scenario 1      # because scenario 2 shares the same data node for this task      scenario_2.submit()        # every task has already been executed so everything will be skipped      scenario_2.submit()        # scenario 3 has no connection to the other scenarios so everything will be executed      scenario_3.month.write(9)      scenario_3.submit()        # changing an input data node will make the task be reexecuted      print("Scenario 3: change in historical data")      scenario_3.historical_data.write(pd.read_csv('time_series_2.csv'))      scenario_3.submit()


from taipy.core.config import Config, Frequency  import taipy as tp      # Normal function used by Taipy  def double(nb):      return nb * 2    def add(nb):      return nb + 10      # Configuration of Data Nodes  input_cfg = Config.configure_data_node("input", default_data=21)  intermediate_cfg = Config.configure_data_node("intermediate")  output_cfg = Config.configure_data_node("output")    # Configuration of tasks  first_task_cfg = Config.configure_task("double",                                      double,                                      input_cfg,                                      intermediate_cfg)    second_task_cfg = Config.configure_task("add",                                      add,                                      intermediate_cfg,                                      output_cfg)        def compare_function(*data_node_results):      # example of function      compare_result = {}      current_res_i = 0      for current_res in data_node_results:          compare_result[current_res_i] = {}          next_res_i = 0          for next_res in data_node_results:              print(f"comparing result {current_res_i} with result {next_res_i}")              compare_result[current_res_i][next_res_i] = next_res - current_res              next_res_i += 1          current_res_i += 1      return compare_result      scenario_cfg = Config.configure_scenario_from_tasks(id="multiply_scenario",                                                      name="my_scenario",                                                      task_configs=[first_task_cfg, second_task_cfg],                                                      comparators={output_cfg.id: compare_function})    Config.export("config_08.toml")    if __name__=="__main__":      tp.Core().run()        scenario_1 = tp.create_scenario(scenario_cfg)      scenario_2 = tp.create_scenario(scenario_cfg)        scenario_1.input.write(10)      scenario_2.input.write(8)        scenario_1.submit()      scenario_2.submit()            print(tp.compare_scenarios(scenario_1, scenario_2))        tp.Rest().run()


from taipy.core.config import Config  import taipy as tp  import datetime as dt  import pandas as pd  import time    # Normal function used by Taipy  def double(nb):      return nb * 2    def add(nb):      print("Wait 10 seconds in add function")      time.sleep(10)      return nb + 10      Config.load('config_07.toml')  Config.configure_job_executions(mode="standalone", max_nb_of_workers=2)      if __name__=="__main__":      scenario_cfg = Config.scenarios['my_scenario']      tp.Core().run()      scenario_1 = tp.create_scenario(scenario_cfg)      scenario_2 = tp.create_scenario(scenario_cfg)      scenario_1.submit()      scenario_2.submit()        scenario_1 = tp.create_scenario(scenario_cfg)      scenario_1.submit(wait=True)      scenario_1.submit(wait=True, timeout=5)


from taipy.core.config import Config  import taipy as tp  import datetime as dt  import pandas as pd      def filter_current(df):      current_month = dt.datetime.now().month      df['Date'] = pd.to_datetime(df['Date'])       df = df[df['Date'].dt.month == current_month]      return df    def count_values(df):      return len(df)      historical_data_cfg = Config.configure_csv_data_node(id="historical_data",                                                       default_path="src/time_series.csv")  month_values_cfg =  Config.configure_data_node(id="month_data")  nb_of_values_cfg = Config.configure_data_node(id="nb_of_values")      task_filter_cfg = Config.configure_task(id="filter_current",                                                   function=filter_current,                                                   input=historical_data_cfg,                                                   output=month_values_cfg)    task_count_values_cfg = Config.configure_task(id="count_values",                                                   function=count_values,                                                   input=month_values_cfg,                                                   output=nb_of_values_cfg)      scenario_cfg = Config.configure_scenario_from_tasks(id="my_scenario",                                                      task_configs=[task_filter_cfg,                                                                    task_count_values_cfg])    Config.export('config_03.toml')    if __name__ == '__main__':      tp.Core().run()        scenario = tp.create_scenario(scenario_cfg, creation_date=dt.datetime(2022,10,7), name="Scenario 2022/10/7")      scenario.submit()        print("Nb of values of scenario:", scenario.nb_of_values.read())        data_node = None        tp.Gui("""<|{scenario}|scenario_selector|>                <|{scenario}|scenario|>                <|{scenario}|scenario_dag|>                <|{data_node}|data_node_selector|>""").run()


from taipy.core.config import Config  import taipy as tp  import datetime as dt  import pandas as pd  import time    # Normal function used by Taipy  def double(nb):      return nb * 2    def add(nb):      print("Wait 10 seconds in add function")      time.sleep(10)      return nb + 10    Config.configure_job_executions(mode="standalone", max_nb_of_workers=2)    # Configuration of Data Nodes  input_cfg = Config.configure_data_node("input", default_data=21)  intermediate_cfg = Config.configure_data_node("intermediate", default_data=21)  output_cfg = Config.configure_data_node("output")    # Configuration of tasks  first_task_cfg = Config.configure_task("double",                                         double,                                         input_cfg,                                         intermediate_cfg)    second_task_cfg = Config.configure_task("add",                                          add,                                          intermediate_cfg,                                          output_cfg)    # Configuration of the pipeline and scenario  scenario_cfg = Config.configure_scenario_from_tasks(id="my_scenario",                                                      task_configs=[first_task_cfg,                                                                    second_task_cfg])    Config.export("config_07.toml")    if __name__=="__main__":      tp.Core().run()      scenario_1 = tp.create_scenario(scenario_cfg)      scenario_2 = tp.create_scenario(scenario_cfg)      scenario_1.submit()      scenario_2.submit()        scenario_1 = tp.create_scenario(scenario_cfg)      scenario_1.submit(wait=True)      scenario_1.submit(wait=True, timeout=5)


from taipy.core.config import Config, Frequency, Scope  import taipy as tp  import datetime as dt  import pandas as pd      def filter_by_month(df, month):      df['Date'] = pd.to_datetime(df['Date'])       df = df[df['Date'].dt.month == month]      return df    def count_values(df):      return len(df)    Config.load('config_05.toml')    if __name__ == '__main__':      # my_scenario is the id of the scenario configured      scenario_cfg = Config.scenarios['my_scenario']        tp.Core().run()        scenario_1 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2022,10,7),                                      name="Scenario 2022/10/7")      scenario_2 = tp.create_scenario(scenario_cfg,                                  creation_date=dt.datetime(2022,10,5),                                  name="Scenario 2022/10/5")      scenario_3 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2021,9,1),                                      name="Scenario 2021/9/1")          scenario_1.month.write(10)      print("Scenario 1: month", scenario_1.month.read())      print("Scenario 2: month", scenario_2.month.read())        print("\nScenario 1: submit")      scenario_1.submit()      print("Value", scenario_1.nb_of_values.read())          print("\nScenario 2: first submit")      scenario_2.submit()      print("Value", scenario_2.nb_of_values.read())      print("Scenario 2: second submit")      scenario_2.submit()      print("Value", scenario_2.nb_of_values.read())          print("\nScenario 3: submit")      scenario_3.month.write(9)      scenario_3.submit()      print("Value", scenario_3.nb_of_values.read())


from taipy.core.config import Config, Scope, Frequency  import taipy as tp  import datetime as dt  import pandas as pd      def filter_by_month(df, month):      df['Date'] = pd.to_datetime(df['Date'])       df = df[df['Date'].dt.month == month]      return df    def count_values(df):      return len(df)      historical_data_cfg = Config.configure_csv_data_node(id="historical_data",                                                   default_path="time_series.csv",                                                   scope=Scope.GLOBAL)  month_cfg =  Config.configure_data_node(id="month", scope=Scope.CYCLE)  month_values_cfg =  Config.configure_data_node(id="month_data",                                                 scope=Scope.CYCLE)    nb_of_values_cfg = Config.configure_data_node(id="nb_of_values")      task_filter_cfg = Config.configure_task(id="filter_by_month",                                                   function=filter_by_month,                                                   input=[historical_data_cfg, month_cfg],                                                   output=month_values_cfg,                                                   skippable=True)    task_count_values_cfg = Config.configure_task(id="count_values",                                                   function=count_values,                                                   input=month_values_cfg,                                                   output=nb_of_values_cfg,                                                   skippable=True)    scenario_cfg = Config.configure_scenario_from_tasks(id="my_scenario",                                                      task_configs=[task_filter_cfg,                                                                    task_count_values_cfg],                                                      frequency=Frequency.MONTHLY)    Config.export('config_06.toml')    if __name__ == '__main__':      tp.Core().run()        scenario_1 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2022,10,7),                                      name="Scenario 2022/10/7")      scenario_2 = tp.create_scenario(scenario_cfg,                                  creation_date=dt.datetime(2022,10,5),                                  name="Scenario 2022/10/5")      scenario_3 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2021,9,1),                                      name="Scenario 2022/9/1")          # scenario 1 and 2 belongs to the same cycle      scenario_1.month.write(10)        scenario_1.submit()        # first task has already been executed by scenario 1      # because scenario 2 shares the same data node for this task      scenario_2.submit()        # every task has already been executed so everything will be skipped      scenario_2.submit()        # scenario 3 has no connection to the other scenarios so everything will be executed      scenario_3.month.write(9)      scenario_3.submit()        # changing an input data node will make the task be reexecuted      print("Scenario 3: change in historical data")      scenario_3.historical_data.write(pd.read_csv('time_series_2.csv'))      scenario_3.submit()


from taipy.core.config import Config, Frequency  import taipy as tp  import datetime as dt  import pandas as pd      def filter_by_month(df, month):      df['Date'] = pd.to_datetime(df['Date'])       df = df[df['Date'].dt.month == month]      return df    def count_values(df):      return len(df)      Config.load('config_04.toml')    if __name__ == '__main__':      # my_scenario is the id of the scenario configured      scenario_cfg = Config.scenarios['my_scenario']        tp.Core().run()        scenario_1 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2022,10,7),                                      name="Scenario 2022/10/7")      scenario_2 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2022,10,5),                                      name="Scenario 2022/10/5")        scenario_1.month.write(10)      scenario_2.month.write(10)        print("Month Data Node of Scenario 1", scenario_1.month.read())      print("Month Data Node of Scenario 2", scenario_2.month.read())        scenario_1.submit()      scenario_2.submit()          print("Scenario 1 before", scenario_1.is_primary)      print("Scenario 2 before", scenario_2.is_primary)        tp.set_primary(scenario_2)        print("Scenario 1 after", scenario_1.is_primary)      print("Scenario 2 after", scenario_2.is_primary)          scenario_3 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2021,9,1),                                      name="Scenario 2022/9/1")      scenario_3.month.write(9)      scenario_3.submit()        print("Is scenario 3 primary?", scenario_3.is_primary)        data_node = None      scenario = None          tp.Gui("""<|{scenario}|scenario_selector|>                <|{scenario}|scenario|>                <|{scenario}|scenario_dag|>                <|{data_node}|data_node_selector|>""").run()


from taipy import Config  import taipy as tp      def double(nb):      return nb * 2    input_data_node_cfg = Config.configure_data_node("input", default_data=21)  output_data_node_cfg = Config.configure_data_node("output")    task_cfg = Config.configure_task("double",                                   double,                                   input_data_node_cfg,                                   output_data_node_cfg)    scenario_cfg = Config.configure_scenario_from_tasks(id="my_scenario",                                                      task_configs=[task_cfg])    Config.export('config_02.toml')    if __name__ == '__main__':      tp.Core().run()        scenario = tp.create_scenario(scenario_cfg, name="Scenario")      tp.submit(scenario)      print("Output of First submit:", scenario.output.read())        print("Before write", scenario.input.read())      scenario.input.write(54)      print("After write",scenario.input.read())          tp.submit(scenario)      print("Second submit",scenario.output.read())        # Basic functions of Taipy Core       print([s.name for s in tp.get_scenarios()])      scenario = tp.get(scenario.id)      tp.delete(scenario.id)        scenario = None      data_node = None        tp.Gui("""<|{scenario}|scenario_selector|>                <|{scenario}|scenario|>                <|{scenario}|scenario_dag|>                <|{data_node}|data_node_selector|>""").run()


from taipy.core.config import Config, Frequency, Scope  import taipy as tp  import datetime as dt  import pandas as pd      def filter_by_month(df, month):      df['Date'] = pd.to_datetime(df['Date'])       df = df[df['Date'].dt.month == month]      return df    def count_values(df):      return len(df)      historical_data_cfg = Config.configure_csv_data_node(id="historical_data",                                                   default_path="time_series.csv",                                                   scope=Scope.GLOBAL)  month_cfg =  Config.configure_data_node(id="month", scope=Scope.CYCLE)    month_values_cfg = Config.configure_data_node(id="month_data",                                                 scope=Scope.CYCLE)  nb_of_values_cfg = Config.configure_data_node(id="nb_of_values")      task_filter_cfg = Config.configure_task(id="filter_by_month",                                                   function=filter_by_month,                                                   input=[historical_data_cfg,month_cfg],                                                   output=month_values_cfg)    task_count_values_cfg = Config.configure_task(id="count_values",                                                   function=count_values,                                                   input=month_values_cfg,                                                   output=nb_of_values_cfg)        scenario_cfg = Config.configure_scenario_from_tasks(id="my_scenario",                                                      task_configs=[task_filter_cfg,                                                                    task_count_values_cfg],                                                      frequency=Frequency.MONTHLY)    Config.export('config_05.toml')    if __name__ == '__main__':      tp.Core().run()        scenario_1 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2022,10,7),                                      name="Scenario 2022/10/7")      scenario_2 = tp.create_scenario(scenario_cfg,                                  creation_date=dt.datetime(2022,10,5),                                  name="Scenario 2022/10/5")      scenario_3 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2021,9,1),                                      name="Scenario 2021/9/1")        scenario_1.month.write(10)      print("Scenario 1: month", scenario_1.month.read())      print("Scenario 2: month", scenario_2.month.read())        print("\nScenario 1: submit")      scenario_1.submit()      print("Value", scenario_1.nb_of_values.read())        print("\nScenario 2: first submit")      scenario_2.submit()      print("Value", scenario_2.nb_of_values.read())            print("Scenario 2: second submit")      scenario_2.submit()      print("Value", scenario_2.nb_of_values.read())        print("\nScenario 3: submit")      scenario_3.month.write(9)      scenario_3.submit()      print("Value", scenario_3.nb_of_values.read())


from taipy import Config  import taipy as tp  import pandas as pd  import datetime as dt      data = pd.read_csv("https://raw.githubusercontent.com/Avaiga/taipy-getting-started-core/src/daily-min-temperatures.csv")      # Normal function used by Taipy  def predict(historical_temperature: pd.DataFrame, date_to_forecast: str) -> float:      print(f"Running baseline...")      historical_temperature['Date'] = pd.to_datetime(historical_temperature['Date'])      historical_same_day = historical_temperature.loc[          (historical_temperature['Date'].dt.day == date_to_forecast.day) &          (historical_temperature['Date'].dt.month == date_to_forecast.month)      ]      return historical_same_day['Temp'].mean()    # Configuration of Data Nodes  historical_temperature_cfg = Config.configure_data_node("historical_temperature")  date_to_forecast_cfg = Config.configure_data_node("date_to_forecast")  predictions_cfg = Config.configure_data_node("predictions")    # Configuration of tasks  predictions_cfg = Config.configure_task("predict",                                          predict,                                          [historical_temperature_cfg, date_to_forecast_cfg],                                          predictions_cfg)    # Configuration of scenario  scenario_cfg = Config.configure_scenario_from_tasks(id="my_scenario",                                                       task_configs=[predictions_cfg])    Config.export('config_01.toml')    if __name__ == '__main__':      # Run of the Core      tp.Core().run()        # Creation of the scenario and execution      scenario = tp.create_scenario(scenario_cfg)      scenario.historical_temperature.write(data)      scenario.date_to_forecast.write(dt.datetime.now())      tp.submit(scenario)        print("Value at the end of task", scenario.predictions.read())        def save(state):          state.scenario.historical_temperature.write(data)          state.scenario.date_to_forecast.write(state.date)          tp.gui.notify(state, "s", "Saved! Ready to submit")        date = None      scenario_md = """  <|{scenario}|scenario_selector|>  <|{date}|date|on_change=save|active={scenario}|>  <|{scenario}|scenario|>  <|{scenario}|scenario_dag|>    <|Refresh|button|on_action={lambda s: s.assign("scenario", scenario)}|>  <|{scenario.predictions.read() if scenario else ''}|>  """        tp.Gui(scenario_md).run()


from taipy import Config  import taipy as tp  import pandas as pd  import datetime as dt      data = pd.read_csv("https://raw.githubusercontent.com/Avaiga/taipy-getting-started-core/src/daily-min-temperatures.csv")      # Normal function used by Taipy  def predict(historical_temperature: pd.DataFrame, date_to_forecast: str) -> float:      print(f"Running baseline...")      historical_temperature['Date'] = pd.to_datetime(historical_temperature['Date'])      historical_same_day = historical_temperature.loc[          (historical_temperature['Date'].dt.day == date_to_forecast.day) &          (historical_temperature['Date'].dt.month == date_to_forecast.month)      ]      return historical_same_day['Temp'].mean()    Config.load('config_01.toml')    if __name__ == '__main__':      scenario_cfg = Config.scenarios['my_scenario']        # Run of the Core      tp.Core().run()        # Creation of the scenario and execution      scenario = tp.create_scenario(scenario_cfg)      scenario.historical_temperature.write(data)      scenario.date_to_forecast.write(dt.datetime.now())      tp.submit(scenario)        print("Value at the end of task", scenario.predictions.read())        def save(state):          state.scenario.historical_temperature.write(data)          state.scenario.date_to_forecast.write(state.date)          tp.gui.notify(state, "s", "Saved! Ready to submit")        date = None      scenario_md = """  <|{scenario}|scenario_selector|>  <|{date}|date|on_change=save|active={scenario}|>  <|{scenario}|scenario|>  <|{scenario}|scenario_dag|>    <|Refresh|button|on_action={lambda s: s.assign("scenario", scenario)}|>  <|{scenario.predictions.read() if scenario else ''}|>  """        tp.Gui(scenario_md).run()      Config.load('config_01.toml')    if __name__ == '__main__':          # my_scenario is the id of the scenario configured      scenario_cfg = Config.scenarios['my_scenario']          # Run of the Core      tp.Core().run()        # Creation of the scenario and execution      scenario = tp.create_scenario(scenario_cfg)      tp.submit(scenario)        print("Value at the end of task", scenario.output.read())


from taipy.core.config import Config, Frequency  import taipy as tp  import datetime as dt  import pandas as pd      def filter_by_month(df, month):      df['Date'] = pd.to_datetime(df['Date'])       df = df[df['Date'].dt.month == month]      return df    def count_values(df):      return len(df)      historical_data_cfg = Config.configure_csv_data_node(id="historical_data",                                                       default_path="time_series.csv")  month_cfg =  Config.configure_data_node(id="month")  month_values_cfg =  Config.configure_data_node(id="month_data")  nb_of_values_cfg = Config.configure_data_node(id="nb_of_values")      task_filter_cfg = Config.configure_task(id="filter_by_month",                                                   function=filter_by_month,                                                   input=[historical_data_cfg, month_cfg],                                                   output=month_values_cfg)    task_count_values_cfg = Config.configure_task(id="count_values",                                                   function=count_values,                                                   input=month_values_cfg,                                                   output=nb_of_values_cfg)    scenario_cfg = Config.configure_scenario_from_tasks(id="my_scenario",                                                      task_configs=[task_filter_cfg,                                                                    task_count_values_cfg],                                                      frequency=Frequency.MONTHLY)    Config.export('config_04.toml')    if __name__ == '__main__':      tp.Core().run()        scenario_1 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2022,10,7),                                      name="Scenario 2022/10/7")      scenario_2 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2022,10,5),                                      name="Scenario 2022/10/5")        scenario_1.month.write(10)      scenario_2.month.write(10)        print("Month Data Node of Scenario 1", scenario_1.month.read())      print("Month Data Node of Scenario 2", scenario_2.month.read())        scenario_1.submit()      scenario_2.submit()        print("Scenario 1 before", scenario_1.is_primary)      print("Scenario 2 before", scenario_2.is_primary)        tp.set_primary(scenario_2)        print("Scenario 1 after", scenario_1.is_primary)      print("Scenario 2 after", scenario_2.is_primary)        scenario_3 = tp.create_scenario(scenario_cfg,                                      creation_date=dt.datetime(2021,9,1),                                      name="Scenario 2022/9/1")      scenario_3.month.write(9)      scenario_3.submit()        print("Is scenario 3 primary?", scenario_3.is_primary)        scenario = None      data_node = None        tp.Gui("""<|{scenario}|scenario_selector|>                <|{scenario}|scenario|>                <|{scenario}|scenario_dag|>                <|{data_node}|data_node_selector|>""").run()


from taipy.core.config import Config, Scope, Frequency  import taipy as tp  import datetime as dt  import pandas as pd  import time      Config.load('config_09.toml')  Config.configure_job_executions(mode="standalone", max_nb_of_workers=2)      def filter_by_month(df, month):      df['Date'] = pd.to_datetime(df['Date'])       df = df[df['Date'].dt.month == month]      return df    def count_values(df):      print("Wait 10 seconds")      time.sleep(10)      return len(df)      def callback_scenario_state(scenario, job):      """All the scenarios are subscribed to the callback_scenario_state function. It means whenever a job is done, it is called.      Depending on the job and the status, it will update the message stored in a json that is then displayed on the GUI.        Args:          scenario (Scenario): the scenario of the job changed          job (_type_): the job that has its status changed      """      print(scenario.name)      if job.status.value == 7:          for data_node in job.task.output.values():              print(data_node.read())      if __name__=="__main__":      # my_scenario is the id of the scenario configured      scenario_cfg = Config.scenarios['my_scenario']        tp.Core().run()      scenario_1 = tp.create_scenario(scenario_cfg, creation_date=dt.datetime(2022,10,7), name="Scenario 2022/10/7")      scenario_1.subscribe(callback_scenario_state)        scenario_1.submit(wait=True)      scenario_1.submit(wait=True, timeout=5)


from taipy import Config  import taipy as tp      def double(nb):      return nb * 2    Config.load('config_02.toml')    if __name__ == '__main__':      # my_scenario is the id of the scenario configured      scenario_cfg = Config.scenarios['my_scenario']        scenario = tp.create_scenario(scenario_cfg, name="Scenario")      tp.submit(scenario)      print("Output of First submit:", scenario.output.read())        print("Before write", scenario.input.read())      scenario.input.write(54)      print("After write",scenario.input.read())          tp.submit(scenario)      print("Second submit",scenario.output.read())        # Basic functions of Taipy Core       print([s.name for s in tp.get_scenarios()])      scenario = tp.get(scenario.id)      tp.delete(scenario.id)        scenario = None      data_node = None        tp.Gui("""<|{scenario}|scenario_selector|>                <|{scenario}|scenario|>                <|{scenario}|scenario_dag|>                <|{data_node}|data_node_selector|>""").run()


from taipy.core.config import Config  import taipy as tp  import datetime as dt  import pandas as pd      def filter_current(df):      current_month = dt.datetime.now().month      df['Date'] = pd.to_datetime(df['Date'])       df = df[df['Date'].dt.month == current_month]      return df    def count_values(df):      return len(df)      Config.load('config_03.toml')    if __name__ == '__main__':      # my_scenario is the id of the scenario configured      scenario_cfg = Config.scenarios['my_scenario']        tp.Core().run()        scenario = tp.create_scenario(scenario_cfg, creation_date=dt.datetime(2022,10,7), name="Scenario 2022/10/7")      scenario.submit()        print("Nb of values of scenario:", scenario.nb_of_values.read())        data_node = None        tp.Gui("""<|{scenario}|scenario_selector|>                <|{scenario}|scenario|>                <|{scenario}|scenario_dag|>                <|{data_node}|data_node_selector|>""").run()


from importlib import util, import_module  from pathlib import Path  import sys  import inspect  import os  import json    if len(sys.argv) < 3:    print("Packages should be passed as arguments after the name of the searched file.", file=sys.stderr)    exit(1)  else:    errors = 0    file_name = sys.argv[1]    result = dict()    exit_code = 1    for package in sys.argv[2:]:      parts = package.split(".")      package_found = True      for idx in range(len(parts)):        if not util.find_spec(".".join(parts[0: idx+1])):          package_found = False          break      if not package_found:        print(f"Package {package} not found.", file=sys.stderr)        errors += 1      else:        module = import_module(package)        found = False        try:          module_file = inspect.getfile(module)          for root, dirs, files in os.walk(Path(module_file).parent.resolve()):            root_path = Path(root)            if file_name in files:              result[package] = str((root_path / file_name).resolve())              found = True        except Exception as e:          print(f"Error accessing {package}: {e}.", file=sys.stderr)          exit_code += 1        if not found:          print(f"File {file_name} not found in Package {package}.", file=sys.stderr)          errors += 1    if len(result):      json.dump(result, sys.stdout)    elif errors:      exit(exit_code)


from taipy import Gui  import cv2    face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")    number_of_faces_detected = 0  selected_file = None  image = None      def process_image(state):      img = cv2.imread(state.selected_file, cv2.IMREAD_UNCHANGED)      gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)      faces = face_cascade.detectMultiScale(gray)      state.number_of_faces_detected = len(faces)      # Draw a rectangle around faces      for (x, y, w, h) in faces:          cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)        state.image = cv2.imencode(".jpg", img)[1].tobytes()      content = """  <|{selected_file}|file_selector|label=Upload File|on_action=process_image|extensions=.jpg,.gif,.png|drop_message=Drop Message|>    <|{image}|image|width=300px|height=300px|>    <|{number_of_faces_detected} face(s) detected|>  """      if __name__ == "__main__":      Gui(page=content).run(dark_mode=False, port=8080)


from setuptools import find_packages, setup    setup(      author="You Name",      author_email="your@email.domain",      python_requires=">=3.8",      classifiers=[          "Intended Audience :: Developers",          # "License :: OSI Approved :: Apache Software License",          "Natural Language :: English",          "Programming Language :: Python :: 3",          "Programming Language :: Python :: 3.8",          "Programming Language :: Python :: 3.9",          "Programming Language :: Python :: 3.10",      ],      # license="Apache License 2.0",      install_requires=["taipy-gui>=2.0"],      include_package_data=True,      name="guiext-library",      description="My taipy-gui extension demo",      long_description="This package contains a demonstration of using the Taipy GUI Extension API.",      keywords="taipy",      packages=find_packages(include=["demo_lib", "demo_lib.*"]),      version="1.0.0",      zip_safe=False  )


from taipy.gui import Gui  from library import Library    page = """  # Extension library    <|library.element|>  """  gui = Gui(page=page)  gui.add_library(Library())    if __name__ == "__main__":      # Run main app      gui.run()


from pathlib import Path  from taipy.gui.extension import ElementLibrary, Element, ElementProperty, PropertyType      class Library(ElementLibrary):      elts = {          # Declare the elements of the library here, as key/value pairs of          # a dictionary.          # - The key is used as the element name.          # - The value must be an instance of taipy.gui.extension.Element          #          # Ex:          # "element_name": Element(          #    "default_property_name"          #    {          #      "property_name": ElementProperty(...)          #    },          #    react_component="ElementComponent"          # ),      }        def get_name(self) -> str:          return "library"        def get_elements(self) -> dict:          return Library.elts        def get_scripts(self) -> list[str]:          # Only one JavaScript bundle for this library.          return ["library/frontend/dist/library.js"]        def get_resource(self, name: str) -> Path:          return super().get_resource(name)


# Export the library class for easier access by developers using it  from .library import Library


#Import modules  import taipy as tp  from taipy import Config, Scope, Gui  import pandas as pd  import numpy as np    #Back-End Code  #Filter function for best/worst colleges within 1 stat  def filtering_college(initial_dataset: pd.DataFrame, selected_stat, ):      completed_graph_dataset = initial_dataset[selected_stat]      completed_graph_data = completed_graph_dataset.nlargest(10, selected_stat, keep = "all")      return completed_graph_data    #Data Node Creation  initial_dataset_cfg = Config.configure_data_node(id="initial_dataset",storage_type="csv",path="College_Data.csv",scope=Scope.GLOBAL)    selected_stat_cfg = Config.configure_data_node(id = "selected_stat", default_data = "Name", slope = Scope.GLOBAL)    completed_graph_data_cfg = Config.configure_data_node(id="completed_graph_data", scope=Scope.GLOBAL)    #Task Creation  filtered_college_cfg = Config.configure_task(id = "filtered_college", function=filtering_college, input = [initial_dataset_cfg, selected_stat_cfg], output = [completed_graph_data_cfg])    #Pipeline Creation  pipeline_cfg = Config.configure_scenario(id="pipeline",task_configs=[filtered_college_cfg])    #Scenario Creation  scenario_cfg = Config.configure_scenario(id = "scenario", pipeline_configs = [pipeline_cfg])  #scenario = tp.create_scenario(scenario_cfg)  #Core creation  if __name__ == "__main__":      tp.Core().run()  #Start of Front-End Code  #Callback Function  def modify_df(state):      scenario.selected_node.write(state.selected_stat)      tp.submit(scenario)      state.df = scenario.completed_graph_data_cfg.read()    list_stats = ["Name","Private","Apps","Accept","Enroll","Top10perc","Top25perc","F.Undergrad","P.Undergrad","Outstate","Room.Board","Books","Personal","PhD","Terminal","S.F.Ratio","perc.alumni","Expend","Grad.Rate"]  selected_stat = "Top10perc"  df = pd.DataFrame(columns = ["Name", selected_stat], copy = True)  #Variable Instantiation    #App Creation  college_stat_app = """<|{selected_stat}|selector|lov={list_stats}|on_change=modify_df|dropdown|>  <|{df}|chart|x=Name|y=selected_stat|type=bar|title=College Stats|>"""        #Runs the app (finally)  print(selected_stat)  Gui(page = college_stat_app).run()


import json      def add_line(source, line, step):        line = line.replace('Getting Started with Taipy GUI', 'Getting Started with Taipy GUI on Notebooks')      line = line.replace('(../src/', '(https://docs.taipy.io/en/latest/getting_started/src/')        if line.startswith('!['):          if step != 'index':              line = line.replace('(', '(https://github.com/Avaiga/taipy-getting-started-gui/blob/latest/' + step + '/')          else:              line = line.replace('(', '(https://github.com/Avaiga/taipy-getting-started-gui/blob/latest/')            # conversion of Markdown image to HTML          img_src = line.split('](')[1].split(')')[0]          width = line.split('](')[1].split(')')[1].split(' ')[1]            source.append('
\n')          source.append(f' \n')          source.append('
\n')            elif step == 'step_00' and line.startswith('from taipy'):          source.append("from taipy.gui import Gui, Markdown\n")      elif 'Notebook' in line and 'step' in step:          pass      else:          source.append(line + '\n')        return source      def detect_new_cell(notebook, source, cell, line, execution_count, force_creation=False):      if line.startswith('```python') or line.startswith('```') and cell == 'code' or force_creation:          source = source[:-1]            if cell == 'code':              notebook['cells'].append({                  "cell_type": "code",                  "metadata": {},                  "outputs": [],                  "execution_count": execution_count,                  "source": source              })              cell = 'markdown'              execution_count += 1          else:              notebook['cells'].append({                  "cell_type": "markdown",                  "metadata": {},                  "source": source              })              cell = 'code'            source = []        return cell, source, notebook, execution_count      def create_introduction(notebook, execution_count):      with open('index.md', 'r') as f:          text = f.read()        split_text = text.split('\n')      source = []        for line in split_text:          if not line.startswith('``` console'):              add_line(source, line, 'index')          else:              break        notebook['cells'].append({          "cell_type": "markdown",          "metadata": {},          "source": source      })        notebook['cells'].append({          "cell_type": "code",          "metadata": {},          "outputs": [],          "execution_count": execution_count,          "source": ['# !pip install taipy\n']      })        notebook['cells'].append({          "cell_type": "markdown",          "metadata": {},          "source": ['## Using Notebooks\n',]      })        execution_count += 1      return notebook, execution_count      def create_steps(notebook, execution_count):      steps = ['step_0' + str(i) for i in range(1, 8)]      source = []        for step in steps:          if source != []:              cell, source, notebook, execution_count = detect_new_cell(notebook,                                                                        source,                                                                        cell,                                                                        line,                                                                        execution_count,                                                                        force_creation=True)            with open(step + '/ReadMe.md', 'r') as f:              text = f.read()            split_text = text.split('\n')          cell = "markdown"            for_studio = 0            for line in split_text:              if cell == "markdown":                  line=line.replace("    ","")              elif cell == "code" and (line[:4] == "    " or len(line)<=1) and for_studio == 2:                  line=line[4:]              else:                  for_studio = 0                            if '=== "Taipy Studio' in line:                  for_studio = 1              if '=== "Python configuration"' in line:                  for_studio = 2                                if for_studio != 1:                  add_line(source, line, step)                  cell, source, notebook, execution_count = detect_new_cell(notebook, source, cell, line, execution_count)        return notebook, execution_count      if __name__ == '__main__':      notebook = {          "cells": [],          "metadata": {              "language_info": {                  "codemirror_mode": {                      "name": "ipython",                      "version": 3                  },                  "file_extension": ".py",                  "mimetype": "text/x-python",                  "name": "python",                  "nbconvert_exporter": "python",                  "pygments_lexer": "ipython3"              },              "orig_nbformat": 4          },          "nbformat": 4,          "nbformat_minor": 2      }        execution_count = 0        notebook, execution_count = create_introduction(notebook, execution_count)      notebook, execution_count = create_steps(notebook, execution_count)        with open('getting_started.ipynb', 'w', encoding='utf-8') as f:          json.dump(notebook, f, indent=2)


from taipy.gui import Gui, notify    text = "Original text"    # Definition of the page  page = """  # Getting started with Taipy GUI    My text: <|{text}|>    <|{text}|input|>    <|Run local|button|on_action=on_button_action|>  """    def on_button_action(state):      notify(state, 'info', f'The text is: {state.text}')      state.text = "Button Pressed"    def on_change(state, var_name, var_value):      if var_name == "text" and var_value == "Reset":          state.text = ""          return      Gui(page).run()


from transformers import AutoTokenizer  from transformers import AutoModelForSequenceClassification  from scipy.special import softmax    import numpy as np  import pandas as pd   from taipy.gui import Gui, notify    text = "Original text"    page = """  # Getting started with Taipy GUI    <|layout|columns=1 1|  <|  My text: <|{text}|>    Enter a word:  <|{text}|input|>  <|Analyze|button|on_action=local_callback|>  |>      <|Table|expandable|  <|{dataframe}|table|width=100%|number_format=%.2f|>  |>  |>    <|layout|columns=1 1 1|  ## Positive <|{np.mean(dataframe['Score Pos'])}|text|format=%.2f|raw|>    ## Neutral <|{np.mean(dataframe['Score Neu'])}|text|format=%.2f|raw|>    ## Negative <|{np.mean(dataframe['Score Neg'])}|text|format=%.2f|raw|>  |>    <|{dataframe}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|>  """    MODEL = f"cardiffnlp/twitter-roberta-base-sentiment"  tokenizer = AutoTokenizer.from_pretrained(MODEL)  model = AutoModelForSequenceClassification.from_pretrained(MODEL)    dataframe = pd.DataFrame({"Text":[''],                            "Score Pos":[0.33],                            "Score Neu":[0.33],                            "Score Neg":[0.33],                            "Overall":[0]})    dataframe2 = dataframe.copy()    def analyze_text(text):      # Run for Roberta Model      encoded_text = tokenizer(text, return_tensors='pt')      output = model(**encoded_text)      scores = output[0][0].detach().numpy()      scores = softmax(scores)            return {"Text":text[:50],              "Score Pos":scores[2],              "Score Neu":scores[1],              "Score Neg":scores[0],              "Overall":scores[2]-scores[0]}      def local_callback(state):      notify(state, 'Info', f'The text is: {state.text}', True)      temp = state.dataframe.copy()      scores = analyze_text(state.text)      temp.loc[len(temp)] = scores      state.dataframe = temp      state.text = ""      path = ""  treatment = 0    page_file = """  <|{path}|file_selector|extensions=.txt|label=Upload .txt file|on_action=analyze_file|> <|{f'Downloading {treatment}%...'}|>
    <|Table|expandable|  <|{dataframe2}|table|width=100%|number_format=%.2f|>  |>
    <|{dataframe2}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|height=600px|>    """    def analyze_file(state):      state.dataframe2 = dataframe2      state.treatment = 0      with open(state.path,"r", encoding='utf-8') as f:          data = f.read()                    # split lines and eliminates duplicates          file_list = list(dict.fromkeys(data.replace('\n', ' ').split(".")[:-1]))                  for i in range(len(file_list)):          text = file_list[i]          state.treatment = int((i+1)*100/len(file_list))          temp = state.dataframe2.copy()          scores = analyze_text(text)          temp.loc[len(temp)] = scores          state.dataframe2 = temp                state.path = None          pages = {"/":"<|toggle|theme|>\n\n<|navbar|>\n",           "line":page,           "text":page_file}      Gui(pages=pages).run()


from transformers import AutoTokenizer  from transformers import AutoModelForSequenceClassification  from scipy.special import softmax    import numpy as np  import pandas as pd   from taipy.gui import Gui, notify    text = "Original text"    page = """  # Getting started with Taipy GUI    <|layout|columns=1 1|  <|  My text: <|{text}|>    Enter a word:  <|{text}|input|>  <|Analyze|button|on_action=local_callback|>  |>      <|Table|expandable|  <|{dataframe}|table|width=100%|number_format=%.2f|>  |>  |>    <|layout|columns=1 1 1|  ## Positive <|{float(np.mean(dataframe['Score Pos']))}|text|format=%.2f|raw|>%    ## Neutral <|{float(np.mean(dataframe['Score Neu']))}|text|format=%.2f|raw|>%    ## Negative <|{float(np.mean(dataframe['Score Neg']))}|text|format=%.2f|raw|>%  |>    <br/>    <|{dataframe}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|>  """    MODEL = f"cardiffnlp/twitter-roberta-base-sentiment"  tokenizer = AutoTokenizer.from_pretrained(MODEL)  model = AutoModelForSequenceClassification.from_pretrained(MODEL)    dataframe = pd.DataFrame({"Text":[''],                            "Score Pos":[0.33],                            "Score Neu":[0.33],                            "Score Neg":[0.33],                            "Overall":[0]})      def analyze_text(text):      # Run for Roberta Model      encoded_text = tokenizer(text, return_tensors='pt')      output = model(**encoded_text)      scores = output[0][0].detach().numpy()      scores = softmax(scores)            return {"Text":text,              "Score Pos":scores[2],              "Score Neu":scores[1],              "Score Neg":scores[0],              "Overall":scores[2]-scores[0]}      def local_callback(state):      notify(state, 'Info', f'The text is: {state.text}', True)      temp = state.dataframe.copy()      scores = analyze_text(state.text)      temp.loc[len(temp)] = scores      state.dataframe = temp      state.text = ""    Gui(page).run()


from taipy.gui import Gui    text = "Original text"    page = """  # Getting started with Taipy GUI    My text: <|{text}|>    <|{text}|input|>  """    Gui(page).run()


from transformers import AutoTokenizer  from transformers import AutoModelForSequenceClassification  from scipy.special import softmax    import numpy as np  import pandas as pd   from taipy.gui import Gui, notify    text = "Original text"    MODEL = f"cardiffnlp/twitter-roberta-base-sentiment"  tokenizer = AutoTokenizer.from_pretrained(MODEL)  model = AutoModelForSequenceClassification.from_pretrained(MODEL)    dataframe = pd.DataFrame({"Text":[''],                            "Score Pos":[0.33],                            "Score Neu":[0.33],                            "Score Neg":[0.33],                            "Overall":[0]})    # Torch is, for now, only available for the Python version between 3.8 and 3.10.   # If you cannot install these packages, just return a dictionary of random numbers for the `analyze_text(text).`  def analyze_text(text):      # Run for Roberta Model      encoded_text = tokenizer(text, return_tensors='pt')      output = model(**encoded_text)      scores = output[0][0].detach().numpy()      scores = softmax(scores)            return {"Text":text,              "Score Pos":scores[2],              "Score Neu":scores[1],              "Score Neg":scores[0],              "Overall":scores[2]-scores[0]}      def local_callback(state):      notify(state, 'Info', f'The text is: {state.text}', True)      temp = state.dataframe.copy()      scores = analyze_text(state.text)      temp.loc[len(temp)] = scores      state.dataframe = temp      state.text = ""        page = """  <|toggle|theme|>    # Getting started with Taipy GUI    My text: <|{text}|>    Enter a word:    <|{text}|input|>    <|Analyze|button|on_action=local_callback|>    ## Positive  <|{float(np.mean(dataframe['Score Pos']))}|text|format=%.2f|>%    ## Neutral  <|{float(np.mean(dataframe['Score Neu']))}|text|format=%.2f|>%    ## Negative  <|{float(np.mean(dataframe['Score Neg']))}|text|format=%.2f|>%    <|{dataframe}|table|number_format=%.2f|>    <|{dataframe}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|>  """    Gui(page).run()


from taipy import Gui    Gui(page="# Getting started with *Taipy*").run()


import pandas as pd   from taipy.gui import Gui, notify      text = "Original text"    page = """  <|toggle|theme|>    # Getting started with Taipy GUI    My text: <|{text}|>    <|{text}|input|>    <|Analyze|button|on_action=local_callback|>    <|{dataframe}|table|number_format=%.2f|>    <|{dataframe}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|>  """    dataframe = pd.DataFrame({"Text":['Test', 'Other', 'Love'],                            "Score Pos":[1, 1, 4],                            "Score Neu":[2, 3, 1],                            "Score Neg":[1, 2, 0],                            "Overall":[0, -1, 4]})      def local_callback(state):      notify(state, 'info', f'The text is: {state.text}')            temp = state.dataframe.copy()      temp.loc[len(temp)] = {"Text":state.text,                              "Score Pos":0,                              "Score Neu":0,                              "Score Neg":0,                              "Overall":0}      state.dataframe = temp      state.text = ""    Gui(page).run()


from taipy.gui import Gui, Markdown    input_pid = None  navigation = [("/add_product", "Add Prodcut"), "/", "Home"]  page = """  # Admin Panel  ## Add Product    def submit_button(state):      state.    <|{input_pid}|input|>  <|submit|button|on_action = submit_button>  """      page1 = """   ii   """    Gui(page=page+page1).run(title="Go To Mall | Admin Panel", port=4000)


from taipy import Config  from taipy import Core, Gui  from taipy.gui import Markdown  import taipy as tp  from pages.home import home_md  from pages.temp import temp_page      def build_message(name: str):      return f"Hello! {name}"      input_name_data_node_cfg = Config.configure_data_node(id="input_name")  message_data_node_cfg = Config.configure_data_node(id="message")  build_msg_task_cfg = Config.configure_task(      "buil_msg", build_message, input_name_data_node_cfg, message_data_node_cfg)  scenario_cfg = Config.configure_scenario(      "scenariod", task_configs=[build_msg_task_cfg])    # making GUI    input_name = "M ahi"  message = None      def submit_scenario(state):      state.scenario.input_name.write(state.input_name)      state.scenario.submit()      state.message = scenario.message.read()      love = "sazia"  page = """  Name: <|{input_name}|input|>  <|submit|button|on_action=submit_scenario|>  Message: <|{message}|text|>  Kima : <|All world are need to safe|text|>  """      pages = {      "/": home_md,      "temp": temp_page,  }      if __name__ == "__main__":      Core().run()    #     mange scenarios and data      scenario = tp.create_scenario(scenario_cfg)    #     instance of run gui      Gui(pages=pages).run(title="Mahi Template", port=5000,                           favicon="https://www.youtube.com/s/gaming/emoji/7ff574f2/emoji_u1f602.png", )


from taipy.gui import Gui, Markdown  name = "maho"  ...  page = """   ...   <|{dialog_is_visible}|dialog|   Enter a name:     <|{name}|input|>   |>   ...   """  ...  pages = {    "/" : page,    'page1': Markdown("# My first page"),    'page2': Markdown("# My second page")  }        Gui(pages=pages).run(title="Mahi App",port=5001 )


from taipy.gui import Markdown, Gui      text = "Welcome to home page"  mahi_text = "So how are you"    home_md = Markdown("""  # **Home**   <|{text}|> <br/>                     <|{mahi_text}|>    """)


from taipy.gui import Gui, Markdown      def fahren_to_celcius(fahr):      return (fahr-32)*5/9      fahr = 100  celcious = fahren_to_celcius(fahr)    temp_page = Markdown("""    # **Home**  Fahrenheit : <|{fahr}|>                    Converted Celcius : <|{celcious}|>    """)


from taipy.gui import Gui, Markdown, notify    value = 0    single_page = Markdown("""  # Taipy Application    Check the documentation [here](https://docs.taipy.io/en/latest/manuals/about/).    <|{value}|slider|on_change=on_slider|> <|Push|button|on_action=on_push|>    """)    def on_push(state):      ...    def on_slider(state):      if state.value == 100:          notify(state, "success", "Taipy is running!")    def on_change(state, var_name:str, var_value):      ...      if __name__ == "__main__":      gui = Gui(single_page)      gui.run()


from taipy.gui import Gui  from taipy.config import Config     from pages.root.root import *  from pages.page_1.page_1 import page_1_md  from pages.page_2.page_2 import page_2_md    Config.load("config/config.toml")    def on_change(state, var_name:str, var_value):      ...    pages = {"/":root_md,           "page_1":page_1_md,           "page_2":page_2_md}      if __name__ == "__main__":      gui = Gui(pages=pages)      gui.run()


from taipy.config import Config


import pandas as pd  import numpy as np    from sklearn.linear_model import LinearRegression    def clean_data(data):      ...      return data.dropna().drop_duplicates()    def predict(data):      model = LinearRegression()      model.fit(data[["x"]], data[["y"]])      data["y_pred"] = model.predict(data[["x"]])      return data    def evaluate(data):      ...      return np.random.rand()


from taipy.gui import Markdown  import pandas as pd    scenario = None  results = None    def show_results(state):      state.results = state.scenario.predictions.read()    page_1_md = Markdown("pages/page_1/page_1.md")


from taipy.gui import Markdown    root_md = Markdown("pages/root/root.md")


from taipy.gui import Markdown    import pandas as pd    path = None  data = None    def drop_csv(state):      state.data = pd.read_csv(state.path)    page_2_md = Markdown("pages/page_2/page_2.md")


from taipy.gui import Gui, Markdown, notify    from pages.root.root import *  from pages.page_1.page_1 import page_1_md  from pages.page_2.page_2 import page_2_md      def on_change(state, var_name:str, var_value):      ...      pages = {"/":root_md,           "page_1":page_1_md,           "page_2":page_2_md}      if __name__ == "__main__":      gui = Gui(pages=pages)      gui.run()


from taipy.gui import Markdown    page_1_md = Markdown("pages/page_1/page_1.md")


from taipy.gui import Markdown    page_2_md = Markdown("pages/page_2/page_2.md")


from taipy.gui import Gui  from pages import home  import os      gui = Gui(page=home.page).run(      title="Demo Logistic Regression",      port=os.environ.get("PORT", "8000"),  )


from config.nodes import (      node_initial_dataset,      node_prediction,      node_prediction_model,      node_X,      node_Y,  )  from models.data import make_X, make_Y  from models.predict import train, predict  from taipy import Config      task_make_X = Config.configure_task(      id="make_X",      input=[node_initial_dataset],      output=node_X,      function=make_X,  )    task_make_Y = Config.configure_task(      id="make_Y",      input=[node_initial_dataset],      output=node_Y,      function=make_Y,  )    task_train = Config.configure_task(      id="train", input=[node_X, node_Y], output=node_prediction_model, function=train  )    task_predict = Config.configure_task(      id="predict", input=[node_X, node_Y], output=node_prediction, function=predict  )


from taipy import Config      node_initial_dataset = Config.configure_data_node(id="initial_dataset")    node_X = Config.configure_data_node(id="X")    node_Y = Config.configure_data_node(id="Y")    node_prediction_model = Config.configure_data_node(id="prediction_model")    node_prediction = Config.configure_data_node(id="prediction")


from taipy import Config  from config.tasks import task_make_X, task_make_Y, task_train, task_predict    pipeline_train = Config.configure_pipeline(      id="train", task_configs=[task_make_X, task_make_Y, task_train]  )    pipeline_predict = Config.configure_pipeline(id="predict", task_configs=[task_predict])


from sklearn.linear_model import LogisticRegression      def train(X, Y):      X_train, Y_train = X[:50], Y[:50]      X_test, Y_test = X[50:], Y[50:]      # Using scikit-learn default      regression = LogisticRegression(random_state=0).fit(X_train, Y_train)      print(f"intercept: {regression.intercept_} coefficients: {regression.coef_}")      print(f"train accuracy: {regression.score(X_train, Y_train)}")      print(f"test accuracy: {regression.score(X_test, Y_test)}")      return regression      def predict(x, regression: LogisticRegression):      return regression.predict(x)


import numpy as np    # Set seed for random number generator  rg = np.random.default_rng(seed=0)    # Create an array with 500 rows and 3 columns.  # This will serve as initial data node  initial_dataset = rg.normal(size=(500, 3))      def make_X(dataset):      # Remove the first column which can be considered as noise      X1 = np.delete(dataset, 0, axis=1)        # Now create two more columns correlated with X1      X2 = X1 + 0.1 * np.random.normal(size=(500, 2))      X = np.concatenate((X1, X2), axis=1)        return X      def make_Y(dataset):      P = 1 / (1 + np.e ** (-np.matmul(dataset, [1, 1, 1])))      Y = P > 0.5      return Y


from taipy.gui import Markdown  import taipy as tp  from taipy.core.job.job import Job  from config.pipelines import pipeline_train  from models.data import initial_dataset      def job_status_changed(pipeline, job: Job):      print(job.status)      def training_button_clicked(state, id, action):      pipeline = tp.create_pipeline(pipeline_train)      # Set initial dataset:      pipeline.initial_dataset.write(initial_dataset)      tp.subscribe_pipeline(          pipeline=pipeline,          callback=job_status_changed,      )      tp.submit(pipeline)      page = Markdown("src/pages/home.md")


from taipy import Gui    page = """  # Hello World 🌍 with *Taipy*This is my first Taipy test app.  And it is running fine!  """    Gui(page).run(use_reloader=True)  # use_reloader=True if you are in development


from taipy import Gui  from page.dashboard_fossil_fuels_consumption import *    if __name__ == "__main__":      Gui(page).run(          use_reloader=True,          title="Test",          dark_mode=False,      )  # use_reloader=True if you are in development


import pandas as pd  import taipy as tp    from data.data import dataset_fossil_fuels_gdp    country = "Spain"  region = "Europe"  lov_region = list(dataset_fossil_fuels_gdp.Entity.unique())      def load_dataset(_country):      """Load dataset for a specific country.        Args:          _country (str): The name of the country.        Returns:          pandas.DataFrame: A DataFrame containing the fossil fuels GDP data for the specified country.      """      dataset_fossil_fuels_gdp_cp = dataset_fossil_fuels_gdp.reset_index()        dataset_fossil_fuels_gdp_cp = dataset_fossil_fuels_gdp_cp[          dataset_fossil_fuels_gdp["Entity"] == _country      ]      return dataset_fossil_fuels_gdp_cp      dataset_fossil_fuels_gdp_cp = load_dataset(country)      def on_change_country(state):      """Update the dataset based on the selected country.        Args:          state (object): The "state" of the variables ran by the program (value changes through selectors)        Returns:          None      """      print("country is:", state.country)      _country = state.country      dataset_fossil_fuels_gdp_cp = load_dataset(_country)      state.dataset_fossil_fuels_gdp_cp = dataset_fossil_fuels_gdp_cp      layout = {"yaxis": {"range": [0, 100000]}, "xaxis": {"range": [1965, 2021]}}    page = """  # Fossil Fuel consumption by per capita by country*    Data comes from Our World in Data    <|{country}|selector|lov={lov_region}|on_change=on_change_country|dropdown|label=Country/Region|>        <|{dataset_fossil_fuels_gdp_cp}|chart|type=plot|x=Year|y=Fossil fuels per capita (kWh)|height=200%|layout={layout}|>    ## Fossil fuel per capita for <|{country}|>:  <|{dataset_fossil_fuels_gdp_cp}|table|height=400px|width=95%|>      """


import pandas as pd      dataset_fossil_fuels_gdp = pd.read_csv("data/per-capita-fossil-energy-vs-gdp.csv")  country_codes = pd.read_csv("./data/country_codes.csv")    dataset_fossil_fuels_gdp = dataset_fossil_fuels_gdp.merge(      country_codes[["alpha-3", "region"]], how="left", left_on="Code", right_on="alpha-3"  )    dataset_fossil_fuels_gdp = dataset_fossil_fuels_gdp[      ~dataset_fossil_fuels_gdp["Fossil fuels per capita (kWh)"].isnull()  ].reset_index()    dataset_fossil_fuels_gdp["Fossil fuels per capita (kWh)"] = (      dataset_fossil_fuels_gdp["Fossil fuels per capita (kWh)"] * 1000  )